從用戶端讀取資源
來完成最後一步:為用戶端加入功能,讓它可以從你的 MCP 伺服器讀取資源資料!這份貨幣及其符號的清單,能讓 LLM 當成核對表,檢查使用者是否請求了 convert_currency() 工具支援的貨幣,同時也驗證該工具函式的引數是否為有效的貨幣符號。
currency_server.py 檔案已經啟動,隨時可以使用。
本練習屬於課程
Model Context Protocol(MCP)入門
練習說明
- 定義一個名為
read_resource()的非同步函式,接受型別為str的resource_uri參數。 - 在函式內,使用
session.read_resource()搭配await讀取指定 URI 的資源,並將結果指定給resource_content。 - 逐一走訪每個資源的內容,並印出其
.mimeType與.text屬性。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
# Define an async function for reading MCP resources
____ ____ ____(____: ____):
"""Read a specific resource by URI."""
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()
print(f"Reading resource: {resource_uri}")
# Read the resource from the session context
resource_content = ____ ____
# Print the contents of each resource
for content in ____:
print(f"\nContent ({content.mimeType}):")
print(content.____)
return resource_content
asyncio.run(read_resource("file://currencies.txt"))