แสดงรายการ Resource จาก Client
เซิร์ฟเวอร์ถูกเขียนลงในไฟล์ currency_server.py และพร้อมเชื่อมต่อแล้ว ขั้นแรก ให้สร้าง client ที่สามารถแสดงรายการ resource ที่มีอยู่บนเซิร์ฟเวอร์นี้
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Model Context Protocol (MCP) เบื้องต้น
คำแนะนำการฝึกหัด
- ภายใน context ของ server session ให้ดึงข้อมูล resource ที่มีอยู่
- วนลูปผ่าน
response.resourcesแล้วแสดงผล URI, ชื่อ และคำอธิบายของแต่ละ resource โดยใช้ attribute ที่เกี่ยวข้อง
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
async def list_resources():
"""List all available resources 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()
# Get the list of resources
response = ____ ____()
print("Available resources:")
# Print each resource's URI, name, and description
for resource in response.____:
print(f" - {resource.____}")
print(f" Name: {resource.____}")
print(f" Description: {resource.____}")
return response.resources
asyncio.run(list_resources())