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

# 资源

> 将服务器中的数据和内容暴露给 LLM

资源（Resources）是模型上下文协议（Model Context Protocol，MCP）中的一个核心原语，它允许服务器暴露可被客户端读取并用作 LLM 交互上下文的数据和内容。

<Note>
  资源被设计为**应用程序控制**（application-controlled）的，这意味着客户端应用程序可以决定如何以及何时使用它们。
  不同的 MCP 客户端可能会以不同方式处理资源。例如：

  * Claude Desktop 目前要求用户在使用资源之前明确选择它们
  * 其他客户端可能会基于启发式规则自动选择资源
  * 某些实现甚至可能允许 AI 模型自行决定使用哪些资源

  服务器作者在实现资源支持时应该准备好处理这些任何交互模式。如果要自动向模型暴露数据，服务器作者应该使用**模型控制**（model-controlled）的原语，如[工具](./tools)。
</Note>

## 概述

资源代表 MCP 服务器想要提供给客户端的任何类型的数据。这可以包括：

* 文件内容
* 数据库记录
* API 响应
* 实时系统数据
* 屏幕截图和图像
* 日志文件
* 以及更多

每个资源都由唯一的 URI 标识，可以包含文本或二进制数据。

## 资源 URI

资源使用以下格式的 URI 进行标识：

```
[protocol]://[host]/[path]
```

For example:

* `file:///home/user/documents/report.pdf`
* `postgres://database/customers/schema`
* `screen://localhost/display1`

协议和路径结构由 MCP 服务器实现定义。服务器可以定义自己的自定义 URI 方案。

## 资源类型

资源可以包含两种类型的内容：

### 文本资源

文本资源包含 UTF-8 编码的文本数据。这些适用于：

* 源代码
* 配置文件
* 日志文件
* JSON/XML 数据
* 纯文本

### 二进制资源

二进制资源包含以 base64 编码的原始二进制数据。这些适用于：

* 图像
* PDF 文件
* 音频文件
* 视频文件
* 其他非文本格式

## 资源发现

客户端可以通过两种主要方法发现可用资源：

### 直接资源

服务器通过 `resources/list` 端点暴露具体资源列表。每个资源包括：

```typescript
{
  uri: string;           // Unique identifier for the resource
  name: string;          // Human-readable name
  description?: string;  // Optional description
  mimeType?: string;     // Optional MIME type
}
```

### 资源模板

对于动态资源，服务器可以暴露 [URI 模板](https://datatracker.ietf.org/doc/html/rfc6570)，客户端可以使用这些模板构造有效的资源 URI：

```typescript
{
  uriTemplate: string;   // URI template following RFC 6570
  name: string;          // Human-readable name for this type
  description?: string;  // Optional description
  mimeType?: string;     // Optional MIME type for all matching resources
}
```

## 读取资源

要读取资源，客户端需要使用资源 URI 发送 `resources/read` 请求。

服务器响应资源内容列表：

```typescript
{
  contents: [
    {
      uri: string;        // The URI of the resource
      mimeType?: string;  // Optional MIME type

      // One of:
      text?: string;      // For text resources
      blob?: string;      // For binary resources (base64 encoded)
    }
  ]
}
```

<Tip>
  服务器可能会对一个 `resources/read` 请求返回多个资源。例如，当读取目录时，可以用这种方式返回目录中的文件列表。
</Tip>

## 资源更新

MCP 通过两种机制支持资源的实时更新：

### 列表变更

当可用资源列表发生变化时，服务器可以通过 `notifications/resources/list_changed` 通知来通知客户端。

### 内容变更

客户端可以订阅特定资源的更新：

1. 客户端使用资源 URI 发送 `resources/subscribe`
2. 当资源发生变化时，服务器发送 `notifications/resources/updated`
3. 客户端可以使用 `resources/read` 获取最新内容
4. 客户端可以使用 `resources/unsubscribe` 取消订阅

## 示例实现

这是在 MCP 服务器中实现资源支持的一个简单示例：

<Tabs>
  <Tab title="TypeScript">
    ```typescript
    const server = new Server({
      name: "example-server",
      version: "1.0.0"
    }, {
      capabilities: {
        resources: {}
      }
    });

    // List available resources
    server.setRequestHandler(ListResourcesRequestSchema, async () => {
      return {
        resources: [
          {
            uri: "file:///logs/app.log",
            name: "Application Logs",
            mimeType: "text/plain"
          }
        ]
      };
    });

    // Read resource contents
    server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
      const uri = request.params.uri;

      if (uri === "file:///logs/app.log") {
        const logContents = await readLogFile();
        return {
          contents: [
            {
              uri,
              mimeType: "text/plain",
              text: logContents
            }
          ]
        };
      }

      throw new Error("Resource not found");
    });
    ```
  </Tab>

  <Tab title="Python">
    ```python
    app = Server("example-server")

    @app.list_resources()
    async def list_resources() -> list[types.Resource]:
        return [
            types.Resource(
                uri="file:///logs/app.log",
                name="Application Logs",
                mimeType="text/plain"
            )
        ]

    @app.read_resource()
    async def read_resource(uri: AnyUrl) -> str:
        if str(uri) == "file:///logs/app.log":
            log_contents = await read_log_file()
            return log_contents

        raise ValueError("Resource not found")

    # Start server
    async with stdio_server() as streams:
        await app.run(
            streams[0],
            streams[1],
            app.create_initialization_options()
        )
    ```
  </Tab>
</Tabs>

## 最佳实践

在实现资源支持时：

1. 使用清晰、描述性的资源名称和 URI
2. 包含有助于 LLM 理解的描述信息
3. 在已知时设置适当的 MIME 类型
4. 为动态内容实现资源模板
5. 对频繁变化的资源使用订阅机制
6. 优雅地处理错误，提供清晰的错误消息
7. 考虑大型资源列表的分页
8. 在适当时缓存资源内容
9. 在处理前验证 URI
10. 记录你的自定义 URI 方案

## 安全考虑

在暴露资源时：

* 验证所有资源 URI
* 实现适当的访问控制
* 净化文件路径以防止目录遍历
* 谨慎处理二进制数据
* 考虑资源读取的速率限制
* 审计资源访问
* 传输中的敏感数据加密
* 验证 MIME 类型
* 为长时间运行的读取实现超时
* 适当处理资源清理
