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

# 资源

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

<Info>**协议修订版本**: 2025-06-18</Info>

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

## 用户交互模型

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

例如，应用程序可以：

* 通过树状或列表视图中的 UI 元素显式选择资源
* 允许用户搜索和筛选可用资源
* 根据启发式规则或 AI 模型的选择自动包含上下文

<img src="https://mintcdn.com/transdocs/yT-0qMgTVh0QCSbv/specification/2025-06-18/server/resource-picker.png?fit=max&auto=format&n=yT-0qMgTVh0QCSbv&q=85&s=65ea60a3dd9568df2cd338bda5d62d0c" alt="资源上下文选择器示例" width="174" height="181" data-path="specification/2025-06-18/server/resource-picker.png" />

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

## 功能能力

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

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

该能力支持两个可选功能：

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

`subscribe` 和 `listChanged` 都是可选的——服务器可以支持两者之一、都不支持或都支持：

```json theme={null}
{
  "capabilities": {
    "resources": {} // 不支持任何功能
  }
}
```

```json theme={null}
{
  "capabilities": {
    "resources": {
      "subscribe": true // 仅支持订阅
    }
  }
}
```

```json theme={null}
{
  "capabilities": {
    "resources": {
      "listChanged": true // 仅支持资源列表变更通知
    }
  }
}
```

## 协议消息

### 列出资源

要发现可用资源，客户端发送 `resources/list` 请求。此操作支持 [分页](/specification/2025-06-18/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 软件应用主文件",
        "description": "主程序入口",
        "mimeType": "text/x-rust"
      }
    ],
    "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",
        "name": "main.rs",
        "title": "Rust 软件应用主文件",
        "mimeType": "text/x-rust",
        "text": "fn main() {\n    println!(\"Hello world!\");\n}"
      }
    ]
  }
}
```

### 资源模板

资源模板允许服务器使用 [URI 模板](https://datatracker.ietf.org/doc/html/rfc6570) 暴露参数化资源。参数可以通过 [补全 API](/specification/2025-06-18/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": "项目文件",
        "title": "📁 项目文件",
        "description": "访问项目目录中的文件",
        "mimeType": "application/octet-stream"
      }
    ]
  }
}
```

### 资源列表变更通知

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

```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",
    "title": "Rust 软件应用主文件"
  }
}
```

## 消息流程

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

    Note over Client,Server: 资源发现
    Client->>Server: resources/list
    Server-->>Client: 资源列表

    Note over Client,Server: 资源访问
    Client->>Server: resources/read
    Server-->>Client: 资源内容

    Note over Client,Server: 订阅
    Client->>Server: resources/subscribe
    Server-->>Client: 订阅确认

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

## 数据类型

### 资源

资源定义包括：

* `uri`：资源的唯一标识符
* `name`：资源的名称
* `title`：用于显示的可读名称（可选）
* `description`：描述（可选）
* `mimeType`：MIME 类型（可选）
* `size`：大小（字节数，可选）

### 资源内容

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

#### 文本内容

```json theme={null}
{
  "uri": "file:///example.txt",
  "name": "example.txt",
  "title": "示例文本文件",
  "mimeType": "text/plain",
  "text": "资源内容"
}
```

#### 二进制内容

```json theme={null}
{
  "uri": "file:///example.png",
  "name": "example.png",
  "title": "示例图片",
  "mimeType": "image/png",
  "blob": "base64-encoded-data"
}
```

### 注解

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

* **`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 类型](https://specifications.freedesktop.org/shared-mime-info-spec/0.14/ar01s02.html#id-1.3.14)（如 `inode/directory`）来标识没有标准 MIME 类型的非普通文件（如目录）。

### git://

Git 版本控制集成。

### 自定义 URI 方案

自定义 URI 方案 **必须** 遵循 [RFC3986](https://datatracker.ietf.org/doc/html/rfc3986)，并考虑上述指导原则。

## 错误处理

服务器 **应该** 为常见的失败情况返回标准 JSON-RPC 错误码：

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

示例错误：

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

## 安全注意事项

1. 服务器 **必须** 验证所有资源 URI
2. 对于敏感资源，**应该** 实施访问控制
3. 二进制数据 **必须** 正确编码
4. 在执行操作前 **应该** 检查资源权限
