शुरू करेंमुफ़्त में शुरू करें

क्लाइंट से Resources पढ़ना

अब आखिरी कदम उठाते हैं: क्लाइंट में ऐसी क्षमता जोड़ना ताकि वह आपके MCP सर्वर से किसी resource का डेटा पढ़ सके! मुद्राओं और उनके प्रतीकों की यह सूची एक LLM के लिए चेकलिस्ट की तरह काम कर सकती है, जिससे वह जाँच सके कि यूज़र ऐसी मुद्रा मांग रहा है जिसे convert_currency() टूल सपोर्ट करता है, और यह भी कि टूल फंक्शन के आर्ग्युमेंट मान्य मुद्रा-प्रतीक हैं.

currency_server.py फ़ाइल पहले से चल रही है और आपके उपयोग के लिए तैयार है.

यह अभ्यास पाठ्यक्रम का हिस्सा है

Model Context Protocol (MCP) परिचय

पाठ्यक्रम देखें

अभ्यास निर्देश

  • read_resource() नाम का एक async फंक्शन परिभाषित करें, जो str टाइप का resource_uri पैरामीटर लेता हो
  • फंक्शन के अंदर, दिए गए URI पर रिसोर्स पढ़ने के लिए await के साथ session.read_resource() का उपयोग करें, और परिणाम 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"))
कोड संपादित करें और चलाएँ