MCP (Model Context Protocol) 技术实现深度解析

前言

2024年底,Anthropic开源了 Model Context Protocol (MCP) —— 一个连接AI应用与外部系统的开放标准。MCP就像AI应用的”USB-C接口”,提供了标准化的方式让AI模型访问数据源、调用工具、执行工作流。

本文将深入剖析MCP的技术架构和核心实现原理。

什么是MCP?

MCP是一个开放协议,它定义了AI应用与外部系统之间的通信标准。通过MCP:

  • AI应用(如Claude、ChatGPT)可以连接数据源(文件、数据库)
  • 调用工具(搜索引擎、计算器)
  • 执行工作流(特定提示模板)
1
2
3
4
5
6
7
8
9
10
11
12
┌─────────────────────────────────────────────────────────────┐
│ AI Application │
│ (Claude Desktop, etc.) │
└─────────────────────────┬───────────────────────────────────┘
│ MCP Protocol
┌────────────────┼────────────────┐
▼ ▼ ▼
┌──────────┐ ┌──────────┐ ┌──────────┐
│ MCP │ │ MCP │ │ MCP │
│ Server │ │ Server │ │ Server │
│ (Files) │ │ (GitHub) │ │ (DB) │
└──────────┘ └──────────┘ └──────────┘

核心架构

三种参与者

MCP采用客户端-服务器架构,包含三种角色:

角色 说明 示例
Host AI应用,协调多个MCP客户端 Claude Desktop, VS Code
Client 维护与单个MCP Server的连接 Host内的连接组件
Server 提供上下文、工具和资源 文件系统服务、GitHub服务
1
2
3
4
5
6
7
8
9
10
11
12
┌─────────────────────────────────────────────────┐
│ MCP Host (AI Application) │
│ ┌─────────┐ ┌─────────┐ ┌─────────┐ │
│ │Client 1 │ │Client 2 │ │Client 3 │ │
│ └────┬────┘ └────┬────┘ └────┬────┘ │
└───────┼────────────┼────────────┼──────────────┘
│ │ │
▼ ▼ ▼
┌─────────┐ ┌─────────┐ ┌─────────┐
│ Server │ │ Server │ │ Server │
│(Local) │ │(Remote) │ │(Remote) │
└─────────┘ └─────────┘ └─────────┘

两层结构

MCP协议分为两层:

1. 数据层 (Data Layer)

基于 JSON-RPC 2.0 的协议层,定义:

  • 生命周期管理:连接初始化、能力协商、连接终止
  • 服务器特性:Tools、Resources、Prompts
  • 客户端特性:Sampling、Elicitation、Logging
  • 工具特性:通知、进度追踪

2. 传输层 (Transport Layer)

管理通信通道和认证:

  • Stdio Transport:本地进程通信
  • Streamable HTTP Transport:远程服务器通信

传输层详解

Stdio Transport(标准输入输出)

适用于本地MCP Server:

1
2
3
4
┌────────┐    stdin     ┌────────┐
│ Client │ ──────────▶ │ Server │
│ │ ◀────────── │ Process│
└────────┘ stdout └────────┘

特点:

  • Client启动Server作为子进程
  • 通过stdin/stdout交换JSON-RPC消息
  • 消息以换行符分隔
  • 无网络开销,性能最优
  • stderr可用于日志输出

Streamable HTTP Transport

适用于远程MCP Server:

1
2
3
4
┌────────┐   HTTP POST    ┌────────┐
│ Client │ ─────────────▶ │ Server │
│ │ ◀───────────── │ │
└────────┘ SSE Stream └────────┘

特点:

  • 使用HTTP POST发送消息
  • 支持Server-Sent Events (SSE)进行流式响应
  • 支持标准HTTP认证(Bearer Token、API Key)
  • 推荐使用OAuth获取认证令牌
  • 支持会话管理(Mcp-Session-Id

会话管理流程

1
2
3
4
5
6
7
8
9
10
11
12
Client                          Server
│ │
│── POST InitializeRequest ───▶│
│◀─ InitializeResponse │
│ (Mcp-Session-Id: xxx) │
│ │
│── POST Request ─────────────▶│
│ (Mcp-Session-Id: xxx) │
│◀─ Response or SSE Stream │
│ │
│── DELETE (terminate) ───────▶│
│ (Mcp-Session-Id: xxx) │

核心原语 (Primitives)

MCP定义了三种服务器端原语

1. Tools(工具)

可执行函数,AI模型可调用执行操作:

1
2
3
4
5
6
7
8
9
10
11
12
13
{
"name": "weather_current",
"title": "Weather Information",
"description": "Get current weather for any location",
"inputSchema": {
"type": "object",
"properties": {
"location": { "type": "string" },
"units": { "type": "string", "enum": ["metric", "imperial"] }
},
"required": ["location"]
}
}

2. Resources(资源)

提供上下文数据的数据源:

  • 文件内容
  • 数据库记录
  • API响应
1
2
3
4
5
{
"uri": "file:///path/to/document.md",
"name": "Project README",
"mimeType": "text/markdown"
}

3. Prompts(提示模板)

可复用的交互模板:

1
2
3
4
5
6
7
{
"name": "code_review",
"description": "Review code for best practices",
"arguments": [
{ "name": "code", "required": true }
]
}

客户端原语

MCP还定义了客户端可提供的原语,让服务器能构建更丰富的交互:

Sampling(采样)

允许服务器请求LLM补全,实现服务器端的AI能力:

1
2
3
4
5
6
7
{
"method": "sampling/complete",
"params": {
"messages": [...],
"maxTokens": 100
}
}

用途:服务器需要AI能力但不想内置模型SDK

Elicitation(询问)

允许服务器请求用户提供额外信息:

1
2
3
4
5
6
7
{
"method": "elicitation/request",
"params": {
"message": "Please confirm this action",
"requestedSchema": {...}
}
}

生命周期管理

MCP是有状态协议,需要完整的生命周期管理:

初始化握手

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Client                                    Server
│ │
│── initialize request ─────────────────▶│
│ { │
│ "protocolVersion": "2025-06-18", │
│ "capabilities": {...}, │
│ "clientInfo": {...} │
│ } │
│ │
│◀─ initialize response ─────────────────│
│ { │
│ "protocolVersion": "2025-06-18", │
│ "capabilities": { │
│ "tools": {"listChanged": true}, │
│ "resources": {} │
│ }, │
│ "serverInfo": {...} │
│ } │
│ │
│── notifications/initialized ──────────▶│
│ │

能力协商

capabilities对象声明支持的功能:

客户端能力

  • elicitation: 支持用户交互请求
  • sampling: 支持LLM采样

服务器能力

  • tools: 支持工具调用
  • resources: 支持资源访问
  • prompts: 支持提示模板
  • listChanged: 支持列表变更通知

工具发现与执行

发现工具

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// Request
{
"jsonrpc": "2.0",
"id": 2,
"method": "tools/list"
}

// Response
{
"jsonrpc": "2.0",
"id": 2,
"result": {
"tools": [
{
"name": "calculator",
"description": "Perform calculations",
"inputSchema": {...}
}
]
}
}

执行工具

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// Request
{
"jsonrpc": "2.0",
"id": 3,
"method": "tools/call",
"params": {
"name": "calculator",
"arguments": {
"expression": "2 + 3 * 4"
}
}
}

// Response
{
"jsonrpc": "2.0",
"id": 3,
"result": {
"content": [
{ "type": "text", "text": "14" }
]
}
}

通知机制

MCP支持实时通知,实现动态更新:

1
2
3
4
{
"jsonrpc": "2.0",
"method": "notifications/tools/list_changed"
}

当服务器的工具列表发生变化时,服务器可以主动通知客户端刷新。

安全考量

MCP赋予AI强大的能力,安全至关重要:

核心原则

  1. 用户同意与控制

    • 用户必须明确同意所有数据访问和操作
    • 用户保留对共享数据和执行操作的最终控制权
  2. 数据隐私

    • Host必须获得明确同意才能向服务器暴露用户数据
    • 未经同意不得传输资源数据
  3. 工具安全

    • 工具代表任意代码执行,必须谨慎对待
    • 调用任何工具前必须获得明确同意
  4. LLM采样控制

    • 用户必须明确批准任何LLM采样请求
    • 用户控制采样的提示和可见结果

Streamable HTTP安全警告

  • 服务器必须验证Origin头防止DNS重绑定攻击
  • 本地运行时应绑定到localhost
  • 服务器应该为所有连接实现认证

生态系统

MCP拥有丰富的生态系统:

官方SDK

  • TypeScript/Node.js
  • Python
  • Java
  • C# .NET

预构建服务器

  • Google Drive: 文件访问
  • Slack: 消息和频道
  • GitHub: 仓库操作
  • PostgreSQL: 数据库查询
  • Puppeteer: 浏览器自动化
  • Filesystem: 本地文件系统

支持的应用

  • Claude Desktop
  • Claude Code
  • VS Code (via extensions)
  • Zed Editor
  • Replit
  • Sourcegraph

与LSP的类比

MCP从 Language Server Protocol (LSP) 获得灵感:

LSP MCP
标准化编程语言支持 标准化AI上下文集成
Language Server MCP Server
IDE (Client) AI Application (Client)
代码补全、诊断 工具调用、资源访问

正如LSP统一了IDE与语言服务的接口,MCP统一了AI应用与外部系统的接口。

总结

MCP通过精巧的协议设计,实现了:

  1. 标准协议:基于JSON-RPC 2.0的统一通信协议
  2. 双层架构:数据层与传输层清晰分离
  3. 丰富原语:Tools、Resources、Prompts提供完整的上下文能力
  4. 双向通信:客户端原语让服务器也能主动交互
  5. 安全优先:从协议设计层面强调用户控制

MCP正在成为AI Agent生态的连接标准。无论你是想为AI应用提供数据源,还是构建能调用外部工具的AI Agent,MCP都提供了优雅的解决方案。


相关链接

感谢你的阅读,如果文章对你有帮助,可以请作者喝杯茶!