MCP 协议

image

模型上下文协议(MCP)基于一种灵活、可扩展的架构构建,该架构能够实现 LLM 应用程序与集成之间的无缝通信。

Protocol 协议

Transport layer 传输层

MCP 支持两种

  • Stdio transport: 适合本地进程互相调用,标准输入输出
  • HTTP with SSE transport: 适合远程调用,SSE 的HTTP 调用模式

所有传输都使用 JSON-RPC 2.0 来交换消息

Message Type 消息类型

  • Requests: 阻塞等待返回的调用模式,Results 是返回类型,Errors 是错误返回
  • Notifications:通知是不期望得到响应的单向消息

Connection lifecycle 链接生命周期

Initialize 初始化

sequenceDiagram
    participant Client
    participant Server

    Client->>Server: initialize request
    Server->>Client: initialize response
    Client->>Server: initialized notification

    Note over Client,Server: Connection ready for use
  1. 客户端发送带有协议版本和功能的 initialize 请求
  2. 服务器以其协议版本和功能进行响应
  3. 客户端发送 initialized 通知作为确认
  4. 普通消息交换开始

Message exchange 消息交换

  • Request-Response: 请求 - 响应:客户端或服务器发送请求,另一方进行响应
  • Notifications: 通知:任何一方发送单向消息

Termination 终止

  • Clean shutdown via close() 通过 close() 进行干净关闭
  • Transport disconnection 传输断开
  • Error conditions 错误条件

Error handling 错误处理

1
2
3
4
5
6
7
8
enum ErrorCode {
// Standard JSON-RPC error codes
ParseError = -32700,
InvalidRequest = -32600,
MethodNotFound = -32601,
InvalidParams = -32602,
InternalError = -32603
}

SDKs 和应用程序可以在 -32000 之上定义自己的错误代码。

Resources 资源

资源是模型上下文协议(MCP)中的核心原语,它允许服务器公开数据和内容,这些数据和内容可以被客户端读取,并用作 LLM 交互的上下文。

可以包括:

  • File contents 文件内容
  • Database records 数据库记录
  • API responses API 响应
  • Live system data 实时系统数据
  • Screenshots and images 屏幕截图和图像
  • Log files 日志文件
  • And more 并且更多

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

会有 Resource URIs 资源统一资源标识符

1
2
3
4
5
[protocol]://[host]/[path]

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

一般区分为

  • 文本类型: 源代码,配置文件等
  • 二进制资源:二进制资源包含以 base64 编码的原始二进制数据。

Prompts 提示

Prompt structure 提示结构

1
2
3
4
5
6
7
8
9
10
11
{
name: string; // Unique identifier for the prompt
description?: string; // Human-readable description
arguments?: [ // Optional list of arguments
{
name: string; // Argument identifier
description?: string; // Argument description
required?: boolean; // Whether argument is required
}
]
}

Discovering prompts 发现提示

客户端可以通过 prompts/list 端点发现可用的提示

Using prompts 使用提示

要使用提示,客户端发出一个 prompts/get 请求:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// Request
{
method: "prompts/get",
params: {
name: "analyze-code",
arguments: {
language: "python"
}
}
}

// Response
{
description: "Analyze Python code for potential improvements",
messages: [
{
role: "user",
content: {
type: "text",
text: "Please analyze the following Python code for potential improvements:\n\n```python\ndef calculate_sum(numbers):\n total = 0\n for num in numbers:\n total = total + num\n return total\n\nresult = calculate_sum([1, 2, 3, 4, 5])\nprint(result)\n```"
}
}
]
}

Tools 工具

MCP 中的工具允许服务器公开可执行函数,这些函数可由客户端调用,并被 LLMs 用于执行操作。工具的关键方面包括:

  • Discovery: 客户端可以通过 tools/list 端点列出可用工具
  • Invocation: 使用 tools/call 端点调用工具,其中服务器执行请求的操作并返回结果
  • Flexibility: 工具的范围可以从简单的计算到复杂的 API 交互

结果如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
{
name: string; // Unique identifier for the tool
description?: string; // Human-readable description
inputSchema: { // JSON Schema for the tool's parameters
type: "object",
properties: { ... } // Tool-specific parameters
},
annotations?: { // Optional hints about tool behavior
title?: string; // Human-readable title for the tool
readOnlyHint?: boolean; // If true, the tool does not modify its environment
destructiveHint?: boolean; // If true, the tool may perform destructive updates
idempotentHint?: boolean; // If true, repeated calls with same args have no additional effect
openWorldHint?: boolean; // If true, tool interacts with external entities
}
}

Sampling 采样

采样是一个强大的 MCP 功能,它允许服务器通过客户端请求 LLM 补全,在保持安全和隐私的同时实现复杂的代理行为。

  1. 服务器向客户端发送一个 sampling/createMessage 请求
  2. 客户端审查请求并可以对其进行修改
  3. 来自 LLM 的客户端样本
  4. 客户端审查完成情况
  5. 客户端将结果返回给服务器

这种人机循环设计确保用户能够控制 LLM 所看到和生成的内容。

Roots 根

根是 MCP 中的一个概念,它定义了服务器可以运行的边界。它们为客户端提供了一种向服务器告知相关资源及其位置的方式。

根具有几个重要的用途:

  • Guidance: 它们向服务器告知相关资源和位置
  • Clarity: 根使哪些资源是您工作区的一部分变得清晰
  • Organization: 多个根允许您同时处理不同的资源