サーバーツールの呼び出し
今度はクライアントからサーバーのツール呼び出しをトリガーしましょう。ここでも非同期処理を使用することで、他の処理の完了を待つ間にフリーズや予期しないエラーが起きないようにします。
この演習はコースの一部です
Model Context Protocol(MCP)入門
演習の手順
- ユーザーが指定した
tool_nameとargumentsパラメーターを使ってツールを呼び出しましょう。適切な Python のキーワードを使い、サーバーからの応答を待つように設定してください。 - サーバーレスポンスのテキスト内容を抽出して出力しましょう。
- 有効なパラメーターのセットを使って
"convert_currency"ツールを実行しましょう(値と通貨は自由に設定して構いません)。
実践的なインタラクティブ演習
このサンプルコードを完成させて、この演習に挑戦してみましょう。
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
async def call_mcp_tool(tool_name: str, arguments: dict) -> str:
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()
# Call the currency conversion tool
result = ____ ____(tool_name, arguments)
# Extract and print the text content of the server response
text_content = result.____[0].____
print(f"Conversion Result: {text_content}")
return text_content
# Run the "convert_currency" tool
asyncio.run(
call_mcp_tool("convert_currency",
{"amount": 250.0, "from_currency": "USD", "to_currency": "EUR"})
)