從用戶端列出資源
你的伺服器已寫入檔案 currency_server.py,現在可以連線了!先從建立一個用戶端開始,讓它可以列出此伺服器上可用的資源。
本練習屬於課程
Model Context Protocol(MCP)入門
練習說明
- 在伺服器工作階段(session)內容內,擷取可用的資源。
- 迴圈走訪
response.resources,並使用其屬性列印每個資源的 URI、名稱與描述。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
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())