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

# 资源

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

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

<Note>
  为简洁起见，本页中的请求示例省略了必需的 `_meta`
  请求元数据（`io.modelcontextprotocol/protocolVersion`、
  `io.modelcontextprotocol/clientInfo` 和
  `io.modelcontextprotocol/clientCapabilities`）。每个请求 **必须** 包含
  这些字段；请参见 [`_meta`](/specification/draft/basic/index#meta)。
</Note>

## User Interaction Model

MCP 中的资源设计为 **应用驱动** 的，由宿主应用程序根据其需求决定如何整合上下文。

例如，应用程序可以：

* 通过 UI 元素（如树形视图或列表视图）暴露资源以供显式选择
* 允许用户搜索和过滤可用资源
* 基于启发式方法或 AI 模型的选择实现自动上下文包含

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

然而，实现可以通过任何适合其需求的界面模式暴露资源—协议本身并不强制任何特定的用户交互模型。

## 能力

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

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

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

* `listChanged`：当可用资源列表发生变化时，服务器是否会发送通知。
* `subscribe`：服务器是否支持对通过订阅/监听请求的资源使用 `resourceSubscriptions` 过滤器时的资源特定更新通知。

服务器可以独立地声明其中任一特性，也可以同时声明，或者都不声明。

不支持 `listChanged` 或 `subscribe` 的服务器可以省略它：

```json theme={null}
{
  "capabilities": {
    "resources": {}
  }
}
```

声明了 `resources` 能力的服务器 **必须** 对 `resources/list` 请求返回当前对请求客户端可用的资源集合。该集合 **可以** 为空，并且 **可以** 随时间变化（参见 [列表变更通知](#list-changed-notification)），但 **不得** 因连接而异，也不得因为连接上的其他请求而副作用式地变化。该集合 **可以** 根据请求中提供的授权而变化——例如，仅返回调用方已获授权范围所允许的资源——因为凭据是每个请求的输入，而不是连接状态。

## 协议消息

### 列出资源

要发现可用资源，客户端发送 `resources/list` 请求。此操作支持 [分页](/specification/draft/server/utilities/pagination) 和 [缓存](/specification/draft/server/utilities/caching)。

**请求：**

```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": {
    "resultType": "complete",
    "resources": [
      {
        "uri": "file:///project/src/main.rs",
        "name": "main.rs",
        "title": "Rust 软件应用程序主文件",
        "description": "主要应用程序入口点",
        "mimeType": "text/x-rust",
        "icons": [
          {
            "src": "https://example.com/rust-file-icon.png",
            "mimeType": "image/png",
            "sizes": ["48x48"]
          }
        ]
      }
    ],
    "nextCursor": "next-page-cursor",
    "ttlMs": 300000,
    "cacheScope": "public"
  }
}
```

### 读取资源

要检索资源内容，客户端发送 `resources/read` 请求。此操作支持 [缓存](/specification/draft/server/utilities/caching)。

**请求：**

```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": {
    "resultType": "complete",
    "contents": [
      {
        "uri": "file:///project/src/main.rs",
        "mimeType": "text/x-rust",
        "text": "fn main() {\n    println!(\"Hello world!\");\n}"
      }
    ],
    "ttlMs": 60000,
    "cacheScope": "private"
  }
}
```

服务器 **可以** 在单个 `resources/read` 请求的响应中返回多个资源内容。例如，当读取目录资源时，服务器可以返回多个文件的内容。

Servers **MAY** also respond to `resources/read` with an [`InputRequiredResult`](/specification/draft/basic/patterns/mrtr#inputrequiredresult) to indicate that additional input is needed before the resource can be read. This follows the [multi round-trip requests](/specification/draft/basic/patterns/mrtr#multi-round-trip-requests) mechanism. When retrying the request, clients include `inputResponses` and, if provided by the server, `requestState` in the request parameters.

或者，如果 `uri` 的 scheme 是 `https://`，客户端可以直接从 Web 获取该资源。有关更多信息，请参见 [常见 URI 方案部分](#https%3A%2F%2F)。

### 资源模板

资源模板允许服务器使用 [URI 模板](https://datatracker.ietf.org/doc/html/rfc6570) 暴露参数化资源。参数可以通过 [补全 API](/specification/draft/server/utilities/completion) 自动补全。此操作支持 [分页](/specification/draft/server/utilities/pagination) 和 [缓存](/specification/draft/server/utilities/caching)。

**请求：**

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

**响应：**

```json theme={null}
{
  "jsonrpc": "2.0",
  "id": 3,
  "result": {
    "resultType": "complete",
    "resourceTemplates": [
      {
        "uriTemplate": "file:///{path}",
        "name": "Project Files",
        "title": "📁 项目文件",
        "description": "访问项目目录中的文件",
        "mimeType": "application/octet-stream",
        "icons": [
          {
            "src": "https://example.com/folder-icon.png",
            "mimeType": "image/png",
            "sizes": ["48x48"]
          }
        ]
      }
    ],
    "nextCursor": "next-page-cursor",
    "ttlMs": 300000,
    "cacheScope": "public"
  }
}
```

### 列表变更通知

当可用资源列表变更时，声明了 `listChanged` 能力的服务器 **应该** 发送通知：

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

### 订阅

客户端可以通过发送一个 [`subscriptions/listen`][subscriptions-listen] 请求，并在 `notifications.resourceSubscriptions` 中列出资源 URI，来订阅特定资源的变更通知。服务器会在所生成的流上，在受监视资源发生变化时发送 `notifications/resources/updated`。

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

完整协议机制（确认、`subscriptionId` 关联以及取消）请参见 [Subscriptions][subscriptions]。

[subscriptions-listen]: /specification/draft/schema#subscriptionslistenrequest

[subscriptions]: /specification/draft/basic/patterns/subscriptions

## 消息流

```mermaid theme={null}
sequenceDiagram
    participant 客户端
    participant 服务器

    Note over 客户端，服务器：资源发现
    客户端->>服务器：resources/list
    服务器-->>客户端：资源列表

    Note over 客户端，服务器：资源模板发现
    客户端->>服务器：resources/templates/list
    服务器-->>客户端：资源模板列表

    Note over 客户端，服务器：资源访问
    客户端->>服务器：resources/read
    服务器-->>客户端：资源内容

    Note over Client,Server: 订阅变更
    Client->>Server: subscriptions/listen (resourceSubscriptions)
    Server--)Client: notifications/subscriptions/acknowledged

    Note over Client,Server: 资源已更新
    Server--)Client: notifications/resources/updated
    Client->>Server: resources/read
    Server-->>Client: 更新后的内容
```

## 数据类型

### 资源

资源定义包括：

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

### 资源内容

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

#### 文本内容

```json theme={null}
{
  "uri": "file:///example.txt",
  "mimeType": "text/plain",
  "text": "资源内容"
}
```

#### 二进制内容

```json theme={null}
{
  "uri": "file:///example.png",
  "mimeType": "image/png",
  "blob": "base64 编码的数据"
}
```

### 注解

资源、资源模板和内容块支持可选的注解，这些注解向客户端提供关于如何使用或显示资源的提示：

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

带注解的资源示例：

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

客户端可以使用这些注解来：

* 根据目标受众过滤资源
* 优先确定哪些资源包含在上下文中
* 显示修改时间或按最近程度排序

## 常见 URI 方案

协议定义了几种标准 URI 方案。此列表并非详尽无遗—实现始终可以自由使用额外的自定义 URI 方案。

### https\://

用于表示网络上可用的资源。

服务器 **应该** 仅在客户端能够自行从网络获取和加载资源时使用此方案—即，它不需要通过 MCP 服务器读取资源。

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

### file://

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

MCP 服务器 **可以** 使用 [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 方案 **必须** 符合 [RFC3986](https://datatracker.ietf.org/doc/html/rfc3986)，同时考虑上述指导。

## 错误处理

如果请求的资源不存在，服务器 **必须** 返回 JSON-RPC 错误，代码为 `-32602`（无效参数）。对于内部错误，服务器 **应该** 返回 `-32603`。

为向后兼容，客户端 **也应** 接受 `-32002` 作为资源未找到错误，因为较早的协议版本使用了此代码。

服务器 **不得** 为不存在的资源返回空的 `contents` 数组。空数组具有歧义——它可能表示资源存在但没有内容，也可能表示资源根本不存在。

错误示例：

```json theme={null}
{
  "jsonrpc": "2.0",
  "id": 5,
  "error": {
    "code": -32602,
    "message": "资源未找到",
    "data": {
      "uri": "file:///nonexistent.txt"
    }
  }
}
```

## 安全考虑

1. 服务器 **必须** 验证所有资源 URI
2. 对于敏感资源 **应** 实施访问控制
3. 二进制数据 **必须** 被正确编码
4. 操作前 **应** 检查资源权限
5. 服务器 **必须** 清理文件路径以防止目录遍历攻击
   当提供 `file://` 资源时
