呼叫伺服器工具
現在要從你的用戶端觸發伺服器端的工具呼叫!同樣地,你會使用非同步作業,確保在等待其他作業完成時,程式不會出錯或凍結。
本練習屬於課程
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"})
)