MCP からリソースとプロンプトを取得する
作成した通貨サーバーは、リソース(file://currencies.txt)とプロンプト(convert_currency_prompt)を公開しています。このプロンプトは、ユーザーのリクエストにタスク固有の文脈とルールを組み合わせたものです。LLM にデータを渡すには、クライアントが両方を一度に取得する必要があります。get_context_from_mcp() というヘルパー関数を実装して、リソースのテキストとプロンプトのテキスト(ユーザーの入力が埋め込まれた状態)を返すようにしましょう。呼び出し元はこの戻り値を使ってメッセージを組み立てられます。
currency_server.py ファイルには、ツール、リソース、プロンプトが用意されています。同じセッションを使って、リソースの読み取りとユーザー入力を含むプロンプトの取得を行いましょう。
この演習はコースの一部です
Model Context Protocol(MCP)入門
演習の手順
- セッション内で、
"file://currencies.txt"のリソースを読み取るメソッドを呼び出します。 - プロンプト名
"convert_currency_prompt"を指定し、キー"currency_request"、値user_queryを持つargumentsディクショナリを使って、ユーザーの入力付きでプロンプトを取得するメソッドを呼び出します。
実践的なインタラクティブ演習
このサンプルコードを完成させて、この演習に挑戦してみましょう。
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
async def get_context_from_mcp(user_query: str) -> tuple[str, str]:
"""Fetch resource content and prompt text from the MCP server."""
params = StdioServerParameters(command=sys.executable, args=["currency_server.py"])
async with stdio_client(params) as (reader, writer):
async with ClientSession(reader, writer) as session:
await session.initialize()
# Read the resource (supported currencies)
resource_result = await session.____("file://currencies.txt")
resource_text = resource_result.contents[0].text
# Get the prompt with the user's query
prompt_result = await session.____("convert_currency_prompt",
arguments={"currency_request": user_query})
prompt_text = prompt_result.messages[0].content.text
return resource_text, prompt_text
print(asyncio.run(get_context_from_mcp("How much is 50 GBP in euros?")))