การอ่าน Resource จาก Client
มาถึงขั้นตอนสุดท้ายแล้ว นั่นคือการเพิ่มความสามารถให้ client อ่านข้อมูล resource จาก MCP server ของคุณได้ รายการสกุลเงินและสัญลักษณ์เหล่านี้สามารถใช้เป็นรายการตรวจสอบสำหรับ LLM เพื่อยืนยันว่าผู้ใช้ระบุสกุลเงินที่ tool convert_currency() รองรับ และตรวจสอบว่า argument ของฟังก์ชัน tool เป็นสัญลักษณ์สกุลเงินที่ถูกต้อง
ไฟล์ currency_server.py ถูกเปิดใช้งานแล้วและพร้อมให้ใช้งาน
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Model Context Protocol (MCP) เบื้องต้น
คำแนะนำการฝึกหัด
- นิยามฟังก์ชัน async ชื่อ
read_resource()ที่รับพารามิเตอร์resource_uriชนิดstr - ภายในฟังก์ชัน ใช้
session.read_resource()พร้อมawaitเพื่ออ่าน resource ที่ URI ที่กำหนด แล้วกำหนดผลลัพธ์ให้กับตัวแปรresource_content - วนลูปผ่านเนื้อหาของแต่ละ resource และแสดง attribute
.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"))