MCP Resource
MCP Resource 是 Model Context Protocol(MCP)中的核心概念之一,指服务器向客户端暴露的可访问数据资源单元,允许 AI Agent 在运行时动态获取外部数据和内容。
定义
MCP Resource 是 MCP 协议定义的资源抽象机制。在 MCP 架构中,Server 可以向 Client 暴露两类核心能力:Tools(工具)和Resources(资源)。Resources 代表服务器上的数据或内容,客户端可以列出可用资源并读取其内容。这使得 AI Agent 能够在对话上下文中动态访问数据库、文件系统、API 响应等外部数据源,而无需将这些数据硬编码到提示词中。
应用场景
- 数据库查询:服务器暴露数据库表或查询结果作为资源,Agent 可在推理过程中读取最新数据
- 配置文件读取:让 Agent 访问项目配置文件、API 密钥、环境变量等
- 实时数据获取:股票价格、天气信息、新闻摘要等动态数据的按需获取
- 文档检索:将知识库、文档库作为资源暴露,支持 RAG 场景
- 状态同步:多 Agent 系统间共享状态和上下文
示例
以下是 MCP Server 暴露资源的典型 JSON-RPC 交互流程:
1. 客户端列出可用资源:
// Client → Server
{
"jsonrpc": "2.0",
"id": 1,
"method": "resources/list",
"params": {}
}
2. 服务器返回资源列表:
// Server → Client
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"resources": [
{
"uri": "config://app/settings",
"name": "Application Settings",
"mimeType": "application/json",
"description": "当前应用的配置信息"
},
{
"uri": "db://users/recent",
"name": "Recent Users",
"mimeType": "application/json",
"description": "最近活跃的用户列表"
}
]
}
}
3. 客户端读取特定资源:
// Client → Server
{
"jsonrpc": "2.0",
"id": 2,
"method": "resources/read",
"params": {
"uri": "db://users/recent"
}
}
4. 服务器返回资源内容:
// Server → Client
{
"jsonrpc": "2.0",
"id": 2,
"result": {
"contents": [{
"uri": "db://users/recent",
"mimeType": "application/json",
"text": "[{\"id\": 1, \"name\": \"张三\"}, {\"id\": 2, \"name\": \"李四\"}]"
}]
}
}
与 Tool 的区别
| 特性 | MCP Resource | MCP Tool |
|---|---|---|
| 调用方向 | Server → Client(数据推拉) | Client → Server(主动调用) |
| 用途 | 暴露数据供 Agent 读取 | 暴露操作供 Agent 执行 |
| 交互模式 | List → Read 两步流程 | 直接 Call 调用 |
| 典型场景 | 数据库、文件、配置 | API 调用、计算、修改 |