> ## 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.

# 资源

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

## 用户交互模型

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

例如，应用程序可以：

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

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

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

## 能力

支持资源的服务器 **必须 (MUST)** 声明 `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-03-26/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",
        "description": "Primary application entry point",
        "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",
        "mimeType": "text/x-rust",
        "text": "fn main() {\n    println!(\"Hello world!\");\n}"
      }
    ]
  }
}
```

### 资源模板

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

**请求：**

```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": {
    "resourceTemplates": [
      {
        "uriTemplate": "file:///{path}",
        "name": "Project Files",
        "description": "Access files in the project directory",
        "mimeType": "application/octet-stream"
      }
    ],
    "nextCursor": "next-page-cursor"
  }
}
```

### 列表变更通知

当可用资源列表发生变化时，声明了 `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
```

## 数据类型

### 资源

资源定义包括：

* `uri`：资源的唯一标识符
* `name`：人类可读的名称
* `description`：可选描述
* `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"
}
```

## 常见 URI 方案

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

### https\://

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

仅当客户端能够自行直接从网络获取和加载资源时（即不需要通过 MCP 服务器读取资源），服务器 **应该 (SHOULD)** 使用此方案。

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

### file://

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

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

### git://

Git 版本控制集成。

## 错误处理

对于常见的失败情况，服务器 **应该 (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)** 检查资源权限
