ComenzarEmpieza gratis

Reading Resources from the Client

Let's now take the final step: adding functionality to the client so it can read the resource's data from your MCP server! This list of currencies and their symbols could be used as a checklist by an LLM to check that the user is requesting a currency supported by the convert_currency() tool, and also that the tool function's arguments are valid currency symbols.

The currency_server.py file has been spun up and is ready for you to use.

Este ejercicio forma parte del curso

Introduction to Model Context Protocol (MCP)

Ver curso

Instrucciones del ejercicio

  • Define an async function called read_resource() that takes a resource_uri parameter of type str
  • Inside the function, use session.read_resource() with await to read the resource at the given URI, assigning the result to resource_content
  • Loop through the contents of each resource and print its .mimeType and .text attributes

Ejercicio interactivo práctico

Prueba este ejercicio y completa el código de muestra.

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"))
Editar y ejecutar código