> ## 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协议核心架构与概念详解

> 深入解析MCP协议核心架构与设计原理，详细说明Host、Client、Server三方角色职责划分与协议完整生命周期管理。涵盖initialize能力协商机制、Tools/Resources/Prompts等Primitive类型定义，帮助开发者全面理解MCP协议架构与AI应用集成模式

# MCP 核心概念

## 1.1 MCP解决什么问题

每个AI应用都需要连接外部系统。没有MCP之前，每个AI应用都要为每个外部系统写一套定制集成代码。N个AI应用 x M个外部系统 = N x M个集成。

MCP把这变成了N+M：每个AI应用实现一个MCP Client，每个外部系统实现一个MCP Server。通过标准协议通信，任意组合。

这一设计直接借鉴了微软的Language Server Protocol (LSP)。LSP解决了"每个编辑器 x 每种语言"的集成爆炸问题，MCP用同样的思路解决"每个AI应用 x 每个外部系统"的问题。

**协议版本**: `2025-11-25`
**规范地址**: [modelcontextprotocol.io](https://modelcontextprotocol.io)
**规范仓库**: [github.com/modelcontextprotocol/specification](https://github.com/modelcontextprotocol/specification)

## 1.2 三个参与方

### MCP Host（宿主）

AI应用本身。负责管理一个或多个MCP Client。

**例子**: Claude Desktop、VS Code (Copilot)、ChatGPT、Cursor

Host的职责：

* 启动和管理MCP Client连接
* 将MCP Server暴露的能力（工具、资源）提供给AI模型
* 处理用户交互
* 执行安全策略（如工具调用需用户确认）

### MCP Client（客户端）

Host内部为每个Server连接创建的组件。每个Client与一个MCP Server保持**1:1的专用连接**。

**你通常不需要直接开发Client** — Host会自动创建和管理。

Client还可以向Server暴露自己的能力（Sampling、Roots、Elicitation），让Server能够反向请求LLM推理或用户输入。

### MCP Server（服务器）

提供工具、数据和提示词的程序。**这是大多数开发者需要构建的部分。**

**例子**:

* 文件系统Server: 让AI读写本地文件
* 数据库Server: 让AI查询数据库
* Sentry Server: 让AI查看错误日志
* 你的商务Server: 让AI搜索商品、查询订单

### 架构图

```
┌─────────────────────────────────────────┐
│           MCP Host (AI应用)              │
│                                         │
│  ┌──────────┐  ┌──────────┐            │
│  │ Client 1 │  │ Client 2 │  ...       │
│  └─────┬────┘  └─────┬────┘            │
└────────┼─────────────┼──────────────────┘
         │ 1:1         │ 1:1
    ┌────┴────┐   ┌────┴────┐
    │Server A │   │Server B │
    │(本地)   │   │(远程)   │
    │stdio    │   │HTTP     │
    └─────────┘   └─────────┘
```

一个Host可以连接多个Server。每个Client-Server对维持独立的有状态连接。本地Server通过stdio通信，远程Server通过Streamable HTTP通信。

## 1.3 协议生命周期

MCP是**有状态协议**，连接有三个阶段：初始化、操作、关闭。

### 阶段一：初始化（Initialization）

Client发送 `initialize` 请求，双方协商协议版本和支持的能力。

```json theme={null}
// Client → Server: initialize请求
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "initialize",
  "params": {
    "protocolVersion": "2025-11-25",
    "capabilities": {
      "sampling": {},
      "elicitation": {},
      "roots": { "listChanged": true }
    },
    "clientInfo": { "name": "my-app", "version": "1.0.0" }
  }
}

// Server → Client: initialize响应
{
  "jsonrpc": "2.0",
  "id": 1,
  "result": {
    "protocolVersion": "2025-11-25",
    "capabilities": {
      "tools": { "listChanged": true },
      "resources": { "subscribe": true, "listChanged": true },
      "prompts": { "listChanged": true }
    },
    "serverInfo": { "name": "my-server", "version": "1.0.0" }
  }
}

// Client → Server: initialized通知（确认初始化完成）
{
  "jsonrpc": "2.0",
  "method": "notifications/initialized"
}
```

**能力协商的关键**:

* Client声明自己支持什么（如 `sampling` LLM推理、`elicitation` 用户交互、`roots` 文件系统边界）
* Server声明自己提供什么（如 `tools` 工具、`resources` 资源、`prompts` 提示词）
* 双方只使用对方声明支持的能力
* 协议版本必须双方一致，否则初始化失败

**超时机制**: 初始化阶段有超时限制。如果Server未在规定时间内响应，Client应断开连接。

### 阶段二：操作（Operation）

初始化完成后，进入正常操作阶段。Client可以发现和调用Server的能力：

```json theme={null}
// Client → Server: 发现工具
{ "jsonrpc": "2.0", "id": 2, "method": "tools/list" }

// Server → Client: 工具列表
{
  "jsonrpc": "2.0",
  "id": 2,
  "result": {
    "tools": [
      {
        "name": "search_products",
        "title": "商品搜索",
        "description": "搜索商品目录",
        "inputSchema": {
          "type": "object",
          "properties": {
            "query": { "type": "string", "description": "搜索关键词" }
          },
          "required": ["query"]
        }
      }
    ]
  }
}
```

**工具执行**:

AI模型决定使用某个工具时，通过Client调用：

```json theme={null}
// Client → Server: 调用工具
{
  "jsonrpc": "2.0",
  "id": 3,
  "method": "tools/call",
  "params": {
    "name": "search_products",
    "arguments": { "query": "跑步鞋" }
  }
}

// Server → Client: 工具结果
{
  "jsonrpc": "2.0",
  "id": 3,
  "result": {
    "content": [
      { "type": "text", "text": "[{\"name\": \"Nike Air Max\", \"price\": 899}]" }
    ]
  }
}
```

**通知机制**:

Server可以主动通知Client工具列表变化（需在初始化时声明 `listChanged: true`）：

```json theme={null}
// Server → Client (通知，无id，不期望响应)
{ "jsonrpc": "2.0", "method": "notifications/tools/list_changed" }
```

Client收到后会重新请求 `tools/list` 获取最新列表。

### 阶段三：关闭（Shutdown）

连接可以由任意一方发起关闭。关闭后所有未完成的请求应被取消，资源应被清理。

## 1.4 全部Primitive总览

MCP的Primitive分为Server端和Client端两类：

### Server端 Primitive（Server向Client提供）

| Primitive     | 控制方  | 发现方法             | 执行方法             | 用途                |
| ------------- | ---- | ---------------- | ---------------- | ----------------- |
| **Tools**     | 模型控制 | `tools/list`     | `tools/call`     | 可执行函数（查数据库、调API等） |
| **Resources** | 应用控制 | `resources/list` | `resources/read` | 数据源（文件、记录、API响应）  |
| **Prompts**   | 用户控制 | `prompts/list`   | `prompts/get`    | 可复用的交互模板          |

**控制方的含义**:

* 模型控制（Tools）: AI模型自主决定何时调用哪个工具
* 应用控制（Resources）: Host应用决定何时读取哪些资源提供给模型
* 用户控制（Prompts）: 用户主动选择使用哪个提示词模板

### Client端 Primitive（Client向Server提供）

| Primitive       | 方法                       | 用途                                                                                                   |
| --------------- | ------------------------ | ---------------------------------------------------------------------------------------------------- |
| **Sampling**    | `sampling/createMessage` | Server请求Host的LLM完成推理。支持模型偏好设置：hints（模型提示）、costPriority / speedPriority / intelligencePriority（优先级权衡） |
| **Roots**       | `roots/list`             | Server查询Client的文件系统边界。返回 `file://` URI列表，告知Server可以访问哪些目录                                            |
| **Elicitation** | `elicitation/request`    | Server请求Client向用户询问信息。适用于需要用户确认或补充输入的场景                                                              |

### 内容类型

工具返回结果、资源数据等均使用统一的内容类型系统：

| 类型                  | 说明    | 示例             |
| ------------------- | ----- | -------------- |
| `text`              | 纯文本   | JSON数据、说明文字    |
| `image`             | 图片    | Base64编码或URI引用 |
| `audio`             | 音频    | 语音数据（Base64编码） |
| `resource_link`     | 资源链接  | 引用一个MCP资源URI   |
| `embedded_resource` | 嵌入式资源 | 内联的资源数据        |

所有内容类型均支持 `annotations` 元数据字段，用于标注受众、优先级等信息。

## 1.5 实验性特性

### Tasks（任务）

Tasks是实验性功能，为持久执行的操作提供包装。当工具调用的结果无法立即返回（如异步处理、长时间运算）时，可通过Task机制实现延迟交付。

## 1.6 MCP不做什么

MCP专注于**上下文交换**，不涉及：

* AI模型如何处理上下文（那是AI应用的事）
* AI模型的选择和配置
* 用户界面设计
* 业务逻辑和工作流编排

MCP只负责：AI应用与外部系统之间的标准化通信。

***

**下一章**: [数据层协议](/zh/book-5/ch2-data-layer) — JSON-RPC 2.0消息格式和能力协商详解
