MCP资源读取的客户端实现要点

该资料介绍MCP客户端读取服务器资源的做法,涵盖按URI读取文本与二进制内容、资源模板参数填充、多服务器URI改写、版本选择及原始协议对象访问,并说明二进制字段需先解码再写入文件。

如果您需要从服务器曝光的资源中读取数据, 如配置文件、 生成的内容或外部数据源, 则使用此功能 。 资源是MCP服务器所暴露的数据源,可以是具有固定内容的静态文件,也可以是动态模板,根据URI中的参数生成内容. ## 阅读资源 使用 URI 读取资源 : ```python async with client: content = await client.read_resource("file:///path/to/README.md") # content -> list[TextResourceContents | BlobResourceContents] # Access text content if hasattr(content[0], 'text'): print(content[0].text) # Access binary content if hasattr(content[0], 'blob'): print(f"Binary data: {len(content[0].blob)} bytes") ``` 资源模板基于 URI 参数生成内容。模板定义了类似模式 `weather://{city}/current`,您在读取时填写参数 : ```python async with client: # Read from a resource template weather_content = await client.read_resource("weather://london/current") print(weather_content[0].text) ``` ## 内容类型 资源根据所暴露的内容而返回不同的内容类型。 文本资源包括配置文件,JSON数据,以及其他人可读内容: ```python async with client: content = await client.read_resource("resource://config/settings.json") for item in content: if hasattr(item, 'text'): print(f"Text content: {item.text}") print(f"MIME type: {item.mime_type}") ``` 二进制资源包括图像、PDF和其他非文本数据。 `BlobResourceContents`,其名称: `blob` 字段为基数64 **字符串**,所以在将字节写入磁盘前解码: ```python import base64 from mcp_types import BlobResourceContents async with client: content = await client.read_resource("resource://images/logo.png") for item in content: if isinstance(item, BlobResourceContents): data = base64.b64decode(item.blob) print(f"Binary content: {len(data)} bytes") print(f"MIME type: {item.mime_type}") # Save to file with open("downloaded_logo.png", "wb") as f: f.write(data) ``` ## 多服务客户端 当使用多服务器客户端时,服务器名称会插入在 URI 方案之后, 所以 `weather://icons/sunny` 编辑 `weather` 服务器变为 `weather://weather/icons/sunny`: ```python async with client: # Multi-server client weather_icons = await client.read_resource("weather://weather/icons/sunny") templates = await client.read_resource("resource://assistant/templates/list") ``` ## 版本选择 当服务器曝光一个资源的多个版本时,您可以请求特定版本: ```python async with client: # Read the highest version (default) content = await client.read_resource("data://config") # Read a specific version content_v1 = await client.read_resource("data://config", version="1.0") ``` 见 [版本发现](<https://github.com/servers/versioning#version-discovery>) 如何发现可用的版本。 ## 原始协议访问 用于完整的控制, 使用 `read_resource_mcp()` 返回完整的 MCP 协议对象 : ```python async with client: result = await client.read_resource_mcp("resource://example") # result -> mcp_types.ReadResourceResult ```

查看原始来源