> ## Documentation Index
> Fetch the complete documentation index at: https://mcp.developerdoc.cn/llms.txt
> Use this file to discover all available pages before exploring further.

# 资源

<div id="enable-section-numbers" />

Model Context Protocol (MCP) 为服务器向客户端公开资源提供了标准化方式。
资源允许服务器共享为语言模型提供上下文的数据，例如文件、数据库 schema 或特定于应用的信息。
每个资源都由一个 [URI](https://datatracker.ietf.org/doc/html/rfc3986) 唯一标识。

## 用户交互模型

MCP 中的资源被设计为**应用驱动**，由宿主应用根据自身需求决定如何纳入上下文。

例如，应用可以：

* 通过树视图或列表视图中的 UI 元素公开资源，以便用户明确选择
* 允许用户搜索和筛选可用资源
* 基于启发式规则或 AI 模型的选择，自动纳入上下文

<img src="https://mintcdn.com/mcp-af858c62/jSqzMzM_desZfWyn/specification/2025-11-25/server/resource-picker.png?fit=max&auto=format&n=jSqzMzM_desZfWyn&q=85&s=2c7bd68554d28dc0963a49d701e4d161" alt="资源上下文选择器示例" width="174" height="181" data-path="specification/2025-11-25/server/resource-picker.png" />

不过，实现可以自由地通过任何适合自身需求的界面模式公开资源；
协议本身并不强制规定任何特定的用户交互模型。

## 能力

支持资源的服务器 **MUST** 声明 `resources` 能力：

```json theme={null}
{
  "capabilities": {
    "resources": {
      "subscribe": true,
      "listChanged": true
    }
  }
}
```

该能力支持两个可选特性：

* `subscribe`：客户端是否可以订阅单个资源的变化通知。
* `listChanged`：服务器是否会在可用资源列表变化时发出通知。

`subscribe` 和 `listChanged` 都是可选的；服务器可以二者都不支持、只支持其中之一，或同时支持二者：

```json theme={null}
{
  "capabilities": {
    "resources": {} // Neither feature supported
  }
}
```

```json theme={null}
{
  "capabilities": {
    "resources": {
      "subscribe": true // Only subscriptions supported
    }
  }
}
```

```json theme={null}
{
  "capabilities": {
    "resources": {
      "listChanged": true // Only list change notifications supported
    }
  }
}
```

## 协议消息

### 列出资源

为了发现可用资源，客户端会发送 `resources/list` 请求。此操作支持[分页](/specification/2025-11-25/server/utilities/pagination)。

**请求：**

```json theme={null}
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "resources/list",
  "params": {
    "cursor": "optional-cursor-value"
  }
}
```

**响应：**

```json theme={null}
{
  "jsonrpc": "2.0",
  "id": 1,
  "result": {
    "resources": [
      {
        "uri": "file:///project/src/main.rs",
        "name": "main.rs",
        "title": "Rust Software Application Main File",
        "description": "Primary application entry point",
        "mimeType": "text/x-rust",
        "icons": [
          {
            "src": "https://example.com/rust-file-icon.png",
            "mimeType": "image/png",
            "sizes": ["48x48"]
          }
        ]
      }
    ],
    "nextCursor": "next-page-cursor"
  }
}
```

### 读取资源

为了检索资源内容，客户端会发送 `resources/read` 请求：

**请求：**

```json theme={null}
{
  "jsonrpc": "2.0",
  "id": 2,
  "method": "resources/read",
  "params": {
    "uri": "file:///project/src/main.rs"
  }
}
```

**响应：**

```json theme={null}
{
  "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}"
      }
    ]
  }
}
```

### Resource Templates

资源模板允许服务器使用 [URI templates](https://datatracker.ietf.org/doc/html/rfc6570) 公开参数化资源。
参数可以通过[补全 API](/specification/2025-11-25/server/utilities/completion)自动补全。

**请求：**

```json theme={null}
{
  "jsonrpc": "2.0",
  "id": 3,
  "method": "resources/templates/list"
}
```

**响应：**

```json theme={null}
{
  "jsonrpc": "2.0",
  "id": 3,
  "result": {
    "resourceTemplates": [
      {
        "uriTemplate": "file:///{path}",
        "name": "Project Files",
        "title": "📁 Project Files",
        "description": "Access files in the project directory",
        "mimeType": "application/octet-stream",
        "icons": [
          {
            "src": "https://example.com/folder-icon.png",
            "mimeType": "image/png",
            "sizes": ["48x48"]
          }
        ]
      }
    ]
  }
}
```

### 列表变化通知

当可用资源列表变化时，已声明 `listChanged` 能力的服务器 **SHOULD** 发送通知：

```json theme={null}
{
  "jsonrpc": "2.0",
  "method": "notifications/resources/list_changed"
}
```

### 订阅

协议支持对资源变化进行可选订阅。客户端可以订阅特定资源，并在资源变化时接收通知：

**订阅请求：**

```json theme={null}
{
  "jsonrpc": "2.0",
  "id": 4,
  "method": "resources/subscribe",
  "params": {
    "uri": "file:///project/src/main.rs"
  }
}
```

**更新通知：**

```json theme={null}
{
  "jsonrpc": "2.0",
  "method": "notifications/resources/updated",
  "params": {
    "uri": "file:///project/src/main.rs"
  }
}
```

## 消息流

```mermaid theme={null}
sequenceDiagram
    participant Client
    participant Server

    Note over Client,Server: Resource Discovery
    Client->>Server: resources/list
    Server-->>Client: List of resources

    Note over Client,Server: Resource Template Discovery
    Client->>Server: resources/templates/list
    Server-->>Client: List of resource templates

    Note over Client,Server: Resource Access
    Client->>Server: resources/read
    Server-->>Client: Resource contents

    Note over Client,Server: Subscriptions
    Client->>Server: resources/subscribe
    Server-->>Client: Subscription confirmed

    Note over Client,Server: Updates
    Server--)Client: notifications/resources/updated
    Client->>Server: resources/read
    Server-->>Client: Updated contents
```

## 数据类型

### Resource

资源定义包括：

* `uri`：资源的唯一标识符
* `name`：资源名称。
* `title`：用于显示的可选人类可读资源名称。
* `description`：可选描述
* `icons`：用于在用户界面中显示的可选图标数组
* `mimeType`：可选 MIME 类型
* `size`：以字节为单位的可选大小

### 资源内容

资源可以包含文本或二进制数据：

#### 文本内容

```json theme={null}
{
  "uri": "file:///example.txt",
  "mimeType": "text/plain",
  "text": "Resource content"
}
```

#### 二进制内容

```json theme={null}
{
  "uri": "file:///example.png",
  "mimeType": "image/png",
  "blob": "base64-encoded-data"
}
```

### Annotations

资源、资源模板和内容块支持可选 annotations，用于向客户端提示如何使用或显示该资源：

* **`audience`**：表示该资源目标受众的数组。有效值为 `"user"` 和 `"assistant"`。例如，`["user", "assistant"]` 表示内容对二者都有用。
* **`priority`**：从 0.0 到 1.0 的数字，表示该资源的重要性。值为 1 表示“最重要”（实际上是必需的），0 表示“最不重要”（完全可选）。
* **`lastModified`**：ISO 8601 格式的时间戳，表示资源最后修改时间（例如 `"2025-01-12T15:00:58Z"`）。

带有 annotations 的资源示例：

```json theme={null}
{
  "uri": "file:///project/README.md",
  "name": "README.md",
  "title": "Project Documentation",
  "mimeType": "text/markdown",
  "annotations": {
    "audience": ["user"],
    "priority": 0.8,
    "lastModified": "2025-01-12T15:00:58Z"
  }
}
```

客户端可以使用这些 annotations 来：

* 根据目标受众筛选资源
* 对应纳入上下文的资源进行优先级排序
* 显示修改时间或按新近程度排序

## Common URI Schemes

协议定义了几种标准 URI 方案。此列表并不详尽；实现始终可以自由使用其他自定义 URI 方案。

### https\://

用于表示 Web 上可用的资源。

只有当客户端能够自行直接从 Web 获取并加载资源时，服务器才 **SHOULD** 使用此方案；
也就是说，客户端不需要通过 MCP 服务器读取该资源。

对于其他用例，即使服务器本身会通过互联网下载资源内容，服务器也 **SHOULD** 优先使用其他 URI 方案，或定义自定义方案。

### file://

用于标识行为类似文件系统的资源。不过，这些资源不需要映射到实际的物理文件系统。

MCP 服务器 **MAY** 使用 [XDG MIME type](https://specifications.freedesktop.org/shared-mime-info-spec/0.14/ar01s02.html#id-1.3.14)
来标识 file:// 资源，例如使用 `inode/directory` 表示目录等没有其他标准 MIME 类型的非常规文件。

### git://

Git 版本控制集成。

### 自定义 URI 方案

自定义 URI 方案 **MUST** 符合 [RFC3986](https://datatracker.ietf.org/doc/html/rfc3986)，并考虑上述指导。

## 错误处理

服务器 **SHOULD** 针对常见失败情况返回标准 JSON-RPC 错误：

* 资源未找到：`-32002`
* 内部错误：`-32603`

错误示例：

```json theme={null}
{
  "jsonrpc": "2.0",
  "id": 5,
  "error": {
    "code": -32002,
    "message": "Resource not found",
    "data": {
      "uri": "file:///nonexistent.txt"
    }
  }
}
```

## 安全注意事项

1. 服务器 **MUST** 验证所有资源 URI
2. 对敏感资源 **SHOULD** 实现访问控制
3. 二进制数据 **MUST** 正确编码
4. 操作前 **SHOULD** 检查资源权限
