开始使用免费开始使用

从客户端读取资源

现在进入最后一步:为客户端添加功能,使其可以从您的 MCP 服务器读取资源数据!这份货币及其符号的清单可供 LLM 用作核对表,用来检查用户请求的货币是否被 convert_currency() 工具支持,并校验该工具函数的参数是否为有效的货币符号。

currency_server.py 文件已启动,随时可用。

本练习是课程的一部分

Model Context Protocol (MCP) 入门

查看课程

练习说明

  • 定义一个名为 read_resource() 的异步函数,接收类型为 str 的参数 resource_uri
  • 在函数内使用带有 awaitsession.read_resource() 读取给定 URI 的资源,并将结果赋值给 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"))
编辑并运行代码