เริ่มต้นใช้งานเริ่มต้นใช้งานได้ฟรี

การอ่าน 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"))
แก้ไขและรันโค้ด