1. 什么是资源? #
资源(Resources)是服务器向客户端暴露的可读数据,供语言模型作为上下文使用。每个资源由 URI 唯一标识。
协议版本:2025-11-25
| 通俗理解 | 说明 |
|---|---|
| 数据源 | 文件、数据库查询结果、API 响应等,供 AI 参考 |
| 应用驱动 | 由客户端/应用决定何时将哪些资源纳入上下文 |
| 可订阅 | 客户端可订阅资源变更,收到更新通知 |
2. 本章你将学到 #
- 资源的能力声明与协议消息
- 如何列出、读取资源
- 资源模板与订阅
- 数据结构、URI 方案、错误处理
3. 典型场景 #
用户打开 VS Code 中的 main.rs,连接文件系统 MCP 服务器。客户端通过 resources/list 获取文件列表,用户选择 main.rs 后,客户端调用 resources/read 获取内容,将其作为上下文发给 LLM,LLM 据此回答问题或生成代码。
4. 能力 #
服务器必须声明 resources 能力:
{
"capabilities": {
"resources": {
"subscribe": true,
"listChanged": true
}
}
}| 特性 | 说明 |
|---|---|
subscribe |
客户端可订阅单个资源,在其变化时接收通知 |
listChanged |
资源列表变化时,服务器发送通知 |
两者均为可选,可都不支持、支持其一或两者都支持。
5. 协议消息 #
5.1 列出资源(resources/list) #
请求:
{
"jsonrpc": "2.0",
"id": 1,
"method": "resources/list",
"params": { "cursor": "optional-cursor-value" }
}支持分页。
响应:
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"resources": [
{
"uri": "file:///project/src/main.rs",
"name": "main.rs",
"title": "Rust Main File",
"description": "Primary entry point",
"mimeType": "text/x-rust"
}
],
"nextCursor": "next-page-cursor"
}
}5.2 读取资源(resources/read) #
请求:
{
"jsonrpc": "2.0",
"id": 2,
"method": "resources/read",
"params": { "uri": "file:///project/src/main.rs" }
}响应:
{
"jsonrpc": "2.0",
"id": 2,
"result": {
"contents": [
{
"uri": "file:///project/src/main.rs",
"mimeType": "text/x-rust",
"text": "fn main() {\n println!(\"Hello world!\");\n}"
}
]
}
}5.3 资源模板(resources/templates/list) #
资源模板使用 URI 模板 暴露参数化资源,如 file:///{path}。参数可通过补全 API 自动补全。
5.4 列表变更通知 #
{
"jsonrpc": "2.0",
"method": "notifications/resources/list_changed"
}5.5 订阅 #
订阅:
{
"jsonrpc": "2.0",
"id": 4,
"method": "resources/subscribe",
"params": { "uri": "file:///project/src/main.rs" }
}更新通知:
{
"jsonrpc": "2.0",
"method": "notifications/resources/updated",
"params": { "uri": "file:///project/src/main.rs" }
}6. 流程示意 #
sequenceDiagram
participant C as 客户端
participant S as 服务器
C->>S: resources/list
S-->>C: 资源列表
C->>S: resources/read (uri)
S-->>C: 资源内容
C->>S: resources/subscribe (uri)
S-->>C: 订阅确认
S-->>C: notifications/resources/updated
C->>S: resources/read
S-->>C: 更新后的内容
7. 数据结构 #
7.1 资源定义 #
| 字段 | 说明 |
|---|---|
uri |
唯一标识符 |
name |
资源名称 |
title |
可选,显示名称 |
description |
可选,描述 |
mimeType |
可选,MIME 类型 |
size |
可选,大小(字节) |
icons |
可选,图标数组 |
7.2 资源内容 #
| 类型 | 字段 | 说明 |
|---|---|---|
| 文本 | text |
纯文本内容 |
| 二进制 | blob |
base64 编码数据 |
7.3 注解 #
| 注解 | 说明 |
|---|---|
audience |
目标受众:["user"]、["assistant"] 或 ["user", "assistant"] |
priority |
0.0–1.0,重要性(1 最重要) |
lastModified |
ISO 8601 时间戳,最后修改时间 |
8. 常用 URI 方案 #
| 方案 | 说明 |
|---|---|
file:// |
文件系统资源(可不必映射到物理文件) |
https:// |
Web 资源(客户端能自行获取时使用) |
git:// |
Git 版本控制 |
| 自定义 | 须符合 RFC3986 |
9. 错误处理 #
| 情况 | 错误码 |
|---|---|
| 资源未找到 | -32002 |
| 内部错误 | -32603 |
10. 安全要点 #
| 要点 | 说明 |
|---|---|
| URI 验证 | 服务器必须验证所有资源 URI |
| 访问控制 | 应当对敏感资源实施访问控制 |
| 二进制编码 | 二进制数据必须正确 base64 编码 |