Get startedGet started for free

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.

This exercise is part of the course

Introduction to Model Context Protocol (MCP)

View Course

Exercise instructions

  • 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

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

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"))
Edit and Run Code