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

# MCP数据层JSON-RPC协议详解

> MCP数据层协议详解，全面讲解JSON-RPC 2.0请求响应与通知消息格式规范以及initialize能力协商完整流程。包括Server端与Client端全部Primitive定义、标准错误码处理机制以及文本图片音频等多媒体内容类型规范，构建可靠的MCP协议通信基础

# 数据层协议

## 2.1 JSON-RPC 2.0基础

MCP的数据层基于 [JSON-RPC 2.0](https://www.jsonrpc.org/) 规范。所有消息都是JSON格式，分三类：

### 请求 (Request)

```json theme={null}
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/list",
  "params": {}
}
```

* `jsonrpc`: 固定为 `"2.0"`
* `id`: 请求唯一标识（字符串或数字），用于匹配响应
* `method`: 调用的方法名
* `params`: 方法参数（可选，Object类型）

### 响应 (Response)

成功响应：

```json theme={null}
{
  "jsonrpc": "2.0",
  "id": 1,
  "result": { "tools": [] }
}
```

错误响应：

```json theme={null}
{
  "jsonrpc": "2.0",
  "id": 1,
  "error": { "code": -32601, "message": "Method not found", "data": {} }
}
```

`result` 和 `error` 互斥，一个响应只会包含其中之一。

### 通知 (Notification)

没有 `id` 字段，不期望响应：

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

通知是单向的，发送方不需要等待任何回复。

## 2.2 Server端 Primitive

MCP Server可以暴露三种核心能力：

### Tools（工具）— 模型控制

可执行的函数。AI模型自主决定何时调用。

| 方法                                 | 方向              | 用途             |
| ---------------------------------- | --------------- | -------------- |
| `tools/list`                       | Client → Server | 列出所有可用工具（支持分页） |
| `tools/call`                       | Client → Server | 执行指定工具         |
| `notifications/tools/list_changed` | Server → Client | 工具列表变更通知       |

**工具定义**（协议版本 `2025-11-25`）:

```json theme={null}
{
  "name": "check_inventory",
  "title": "库存查询",
  "description": "查询指定SKU的实时库存数量",
  "inputSchema": {
    "type": "object",
    "properties": {
      "sku": { "type": "string", "description": "商品SKU编号" },
      "warehouse": { "type": "string", "description": "仓库代码（可选）" }
    },
    "required": ["sku"]
  },
  "outputSchema": {
    "type": "object",
    "properties": {
      "sku": { "type": "string" },
      "quantity": { "type": "number" },
      "warehouses": {
        "type": "array",
        "items": {
          "type": "object",
          "properties": {
            "code": { "type": "string" },
            "quantity": { "type": "number" }
          }
        }
      }
    }
  }
}
```

**关键字段说明**:

* `name`: 工具的唯一标识符
* `title`: 人类可读的显示名称
* `description`: 描述工具用途，直接影响AI模型的选择决策
* `inputSchema`: JSON Schema格式的输入参数定义（必需）
* `outputSchema`: JSON Schema格式的输出结构定义（可选，`2025-11-25` 新增）

**工具执行结果**:

```json theme={null}
{
  "content": [
    { "type": "text", "text": "SKU SHOE-001 库存: 北京仓 45件, 上海仓 23件" }
  ],
  "structuredContent": {
    "sku": "SHOE-001",
    "quantity": 68,
    "warehouses": [
      { "code": "BJ", "quantity": 45 },
      { "code": "SH", "quantity": 23 }
    ]
  },
  "isError": false
}
```

* `content`: 内容数组，支持多种类型（text、image、audio、resource\_link、embedded\_resource）
* `structuredContent`: 与 `outputSchema` 对应的结构化数据（可选，与 `content` 同时返回，优先用于程序化处理）
* `isError`: 标识是否为工具级错误（`true` 表示工具执行失败但协议层正常）

**两种错误类型**:

1. **协议层错误**: JSON-RPC error响应，表示请求本身有问题（方法不存在、参数无效等）
2. **工具层错误**: `isError: true`，表示工具执行了但遇到业务错误（商品不存在、权限不足等）

### Resources（资源）— 应用控制

数据源，提供上下文信息。和Tools的区别：Tools是"做事"，Resources是"提供信息"。

| 方法                                     | 方向              | 用途             |
| -------------------------------------- | --------------- | -------------- |
| `resources/list`                       | Client → Server | 列出所有可用资源（支持分页） |
| `resources/read`                       | Client → Server | 读取指定资源         |
| `resources/subscribe`                  | Client → Server | 订阅资源变化         |
| `resources/unsubscribe`                | Client → Server | 取消订阅           |
| `notifications/resources/list_changed` | Server → Client | 资源列表变更通知       |
| `notifications/resources/updated`      | Server → Client | 已订阅资源内容变更通知    |

**资源定义**:

```json theme={null}
{
  "uri": "commerce://catalog/categories",
  "name": "商品分类",
  "description": "当前所有商品分类及其层级结构",
  "mimeType": "application/json",
  "annotations": {
    "audience": ["user", "assistant"],
    "priority": 0.8,
    "lastModified": "2026-04-10T08:00:00Z"
  }
}
```

**Annotations字段说明**:

* `audience`: 目标受众，可选值包括 `"user"` 和 `"assistant"`
* `priority`: 优先级，0到1之间的浮点数（1为最高优先级）
* `lastModified`: 最后修改时间（ISO 8601格式）

**URI模板**: 资源URI支持RFC 6570 URI模板语法，用于定义动态资源：

```
commerce://products/{sku}
commerce://orders/{orderId}/items
```

### Prompts（提示词模板）— 用户控制

可复用的交互模板。Server可以提供预定义的提示词，用户在Host应用中主动选择使用。

| 方法                                   | 方向              | 用途                      |
| ------------------------------------ | --------------- | ----------------------- |
| `prompts/list`                       | Client → Server | 列出所有可用提示词（支持分页）         |
| `prompts/get`                        | Client → Server | 获取指定提示词（支持arguments参数化） |
| `notifications/prompts/list_changed` | Server → Client | 提示词列表变更通知               |

**提示词定义**:

```json theme={null}
{
  "name": "product_recommendation",
  "description": "根据用户需求推荐商品",
  "arguments": [
    { "name": "category", "description": "商品类别", "required": true },
    { "name": "budget", "description": "预算范围", "required": false }
  ]
}
```

**获取提示词**:

```json theme={null}
// Client → Server
{
  "method": "prompts/get",
  "params": {
    "name": "product_recommendation",
    "arguments": { "category": "运动鞋", "budget": "500-1000" }
  }
}

// Server → Client
{
  "result": {
    "messages": [
      {
        "role": "user",
        "content": {
          "type": "text",
          "text": "请推荐500-1000元价位的运动鞋，考虑性价比、舒适度和品牌口碑。"
        }
      }
    ]
  }
}
```

## 2.3 Client端 Primitive

MCP Client也可以暴露能力给Server（需在初始化时声明）：

### Sampling — Server请求LLM推理

Server无需内置AI SDK，可以请求Host的LLM完成推理。

```json theme={null}
// Server → Client
{
  "method": "sampling/createMessage",
  "params": {
    "messages": [
      { "role": "user", "content": { "type": "text", "text": "将以下文本翻译为英文：你好世界" } }
    ],
    "maxTokens": 100,
    "modelPreferences": {
      "hints": [{ "name": "claude-sonnet" }],
      "costPriority": 0.3,
      "speedPriority": 0.8,
      "intelligencePriority": 0.5
    }
  }
}
```

**modelPreferences字段**:

* `hints`: 模型提示列表，Server建议使用的模型（Host可以忽略）
* `costPriority`: 成本优先级（0-1，越高越倾向低成本模型）
* `speedPriority`: 速度优先级（0-1，越高越倾向快速模型）
* `intelligencePriority`: 智能优先级（0-1，越高越倾向高能力模型）

### Elicitation — Server请求用户输入

Server需要用户确认或补充信息时使用。

```json theme={null}
// Server → Client
{
  "method": "elicitation/request",
  "params": {
    "message": "退货需要确认以下信息",
    "requestedSchema": {
      "type": "object",
      "properties": {
        "reason": { "type": "string", "description": "退货原因" },
        "confirm": { "type": "boolean", "description": "确认退货" }
      },
      "required": ["reason", "confirm"]
    }
  }
}
```

### Roots — 文件系统边界

Server查询可访问的文件系统范围。

```json theme={null}
// Server → Client
{ "method": "roots/list" }

// Client → Server
{
  "result": {
    "roots": [
      { "uri": "file:///home/user/project", "name": "项目目录" }
    ]
  }
}
```

### Logging — 日志消息

Server向Client发送日志消息，用于调试和监控。

```json theme={null}
// Server → Client (通知)
{
  "method": "notifications/message",
  "params": {
    "level": "warning",
    "logger": "inventory-service",
    "data": "SKU SHOE-001 库存低于阈值"
  }
}
```

日志级别: `debug`、`info`、`notice`、`warning`、`error`、`critical`、`alert`、`emergency`。

## 2.4 能力协商

初始化时，双方声明支持的能力。只有声明的能力才能使用。

**Server能力**:

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

* `listChanged`: Server会在列表变化时发送通知
* `subscribe`: 支持资源订阅（内容变化时通知Client）

**Client能力**:

```json theme={null}
{
  "capabilities": {
    "sampling": {},
    "elicitation": {},
    "roots": { "listChanged": true }
  }
}
```

* `sampling`: Client支持Server请求LLM推理
* `elicitation`: Client支持Server请求用户输入
* `roots.listChanged`: Client会在文件系统边界变化时通知Server

## 2.5 错误处理

MCP使用JSON-RPC 2.0标准错误码加上MCP自定义扩展：

### 标准JSON-RPC错误码

| 错误码    | 含义                      |
| ------ | ----------------------- |
| -32700 | JSON解析错误（Parse error）   |
| -32600 | 无效的请求（Invalid Request）  |
| -32601 | 方法不存在（Method not found） |
| -32602 | 无效的参数（Invalid params）   |
| -32603 | 内部错误（Internal error）    |

### MCP自定义错误码

| 错误码    | 含义    | 说明           |
| ------ | ----- | ------------ |
| -32001 | 请求超时  | Server处理时间过长 |
| -32002 | 资源不存在 | 请求的资源URI无效   |

### 工具层错误

工具执行中的业务错误不使用JSON-RPC error，而是通过正常响应中的 `isError` 标志传递：

```json theme={null}
{
  "jsonrpc": "2.0",
  "id": 5,
  "result": {
    "content": [
      { "type": "text", "text": "订单 ORD-001 不存在或已取消" }
    ],
    "isError": true
  }
}
```

这种设计让AI模型能看到错误信息并据此调整行为（比如换一个订单号重试）。

***

**下一章**: [传输层](/zh/book-5/ch3-transport) — stdio和Streamable HTTP两种传输方式详解
