ListMcpResourcesTool:列出 MCP 资源
2026/8/2 16:54:01 · 来源
ListMcpResourcesTool 是 MCP 生态中的资源发现工具,让模型在连接 MCP Server 后能够动态列出所有可用资源 URI,避免盲猜。
它让模型先获得“资源发现能力”
ListMcpResourcesTool 的职责很像远程世界里的目录浏览。
如果模型已经接上了 MCP server,但不知道那边具体暴露了哪些资源,第一步就应该用它先列出来。
关键源码
tools/ListMcpResourcesTool/ListMcpResourcesTool.ts:
const inputSchema = z.object({
server: z.string().optional().describe('Optional server name to filter resources by'),
})
核心逻辑是:
const results = await Promise.all(
clientsToProcess.map(async client => {
const fresh = await ensureConnectedClient(client)
return await fetchResourcesForClient(fresh)
}),
)
这说明它不是静态读缓存,而是围绕 MCP client 连接状态工作的。
调用链
模型要读 MCP 资源 > ListMcpResourcesTool > 确认连接 client > fetchResourcesForClient > 返回资源目录 > 交给 ReadMcpResourceTool
小结
ListMcpResourcesTool 解决的是资源发现问题,没有它,模型只能盲猜 URI。
学习地图
🗺️ 学习地图:掌握 MCP 资源发现与读取
第一阶段:认知基础
- 了解 MCP(Model Context Protocol)核心概念——Resources、Tools、Prompts
- 理解 Resource URI 格式与分类(file://、database://、自定义协议等)
- 明确资源发现流程在 Agent 工作流中的位置
第二阶段:环境搭建
- 安装 MCP Python/TypeScript SDK
- 配置并启动一个 MCP Server(示例:filesystem server)
- 验证 Client ↔ Server 双向连接状态
第三阶段:使用 ListMcpResourcesTool
- 调用
list_resources()/resources/list方法获取资源列表 - 使用可选参数按服务器名称过滤资源
- 理解返回结果结构(URI、MIME 类型、描述等元数据)
第四阶段:深度实践
- 结合 ReadMcpResourceTool 完成「发现→读取」完整链路
- 处理分页与游标(cursor)获取全部资源
- 管理多 Server 场景下的客户端连接池
第五阶段:进阶探索
- 编写自定义 MCP Server 并暴露 ResourceTemplate
- 动态注册可变的虚拟资源(非静态文件)
- 在 Claude Code / Cursor 等 Agent IDE 中集成资源浏览 UI
动手实践——分步指南
- 安装 MCP SDK:
pip install mcp或npm install @modelcontextprotocol/sdk - 初始化一个 MCP Client 并连接到服务器:
from mcp import ClientSession session = await ClientSession() await session.connect( subprocess.Popen(["uvicorn", "my_server:app"], stdin=subprocess.PIPE, stdout=subprocess.PIPE) ) - 调用资源列表接口,不传参数获取全部:
resources = await session.list_resources() for r in resources: print(f"{r.uri} — {r.mimeType or 'text'}") - 按服务器名称过滤(如需要):在调用前过滤
resources结果,或在 Server 端通过 server filter 实现。 - (可选)处理分页:若响应包含
nextCursor,传入该游标再次调用list_resources(cursor=...)直到无下一页。 - 结合读取操作:从列表中选择一个 URI,传给 ReadMcpResourceTool:
content, mime_type = await session.read_resource("file:///path/to/file.txt") print(content) - 验证端到端链路:在 Claude Code / Cursor 中配置 MCP Server,观察 Agent 自动调用资源发现与读取的完整调用链。
- 探索自定义 Server:新建一个暴露 ResourceTemplate(动态 URI 前缀)的 Server,重启 Client 后重复步骤 3-6。
三大推荐资源
- 1MCP 官方规范 - Resources
MCP 协议 specification,详细描述 resources/list、资源 URI 格式及分页机制。
https://modelcontextprotocol.io/specification/2025-06-18/server/resources
- 2Anthropic MCP Python SDK 文档
MCP 官方 Python SDK,包含 list_resources()、read_resource() 等核心 API 的用法与示例。
https://github.com/modelcontextprotocol/python-sdk
- 3Phil Schmidt:MCP 入门指南
一篇清晰的 MCP 概览文章,解释了资源发现(Discovery)、上下文提供和 Agent 工作流中 MCP 的位置。
https://www.philschmid.de/mcp-introduction
链接由 AI 推荐——使用前建议快速核实。