การเรียกใช้ Tool ของเซิร์ฟเวอร์
ถึงเวลาเรียกใช้ tool บนเซิร์ฟเวอร์จากฝั่งไคลเอนต์แล้ว เช่นเดิม เราจะใช้การทำงานแบบ asynchronous เพื่อให้แน่ใจว่าโปรแกรมจะไม่ขัดข้องหรือค้างระหว่างรอการทำงานอื่น
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Model Context Protocol (MCP) เบื้องต้น
คำแนะนำการฝึกหัด
- เรียกใช้ tool ด้วยพารามิเตอร์
tool_nameและargumentsที่ผู้ใช้กำหนด โดยใช้คีย์เวิร์ด Python ที่เหมาะสมเพื่อให้การเรียกใช้หยุดรอการตอบสนองจากเซิร์ฟเวอร์ - ดึงข้อมูลและแสดงผล text content จากการตอบสนองของเซิร์ฟเวอร์
- รัน tool
"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"})
)