MCP:AI 应用的 USB-C 接口
2026/3/23
MCPAIAgent协议
MCP 就像 USB-C 端口一样,为 AI 应用提供了一种标准化的方式来连接外部系统。
一、什么是 MCP?
MCP(Model Context Protocol) 是 Anthropic 在 2024 年发布的开放标准,用于连接 AI 应用与外部系统。
核心价值
| 角色 | 价值 |
|---|---|
| 开发者 | 减少集成开发时间和复杂度 |
| AI 应用 | 获得丰富的数据源和工具生态 |
| 最终用户 | 更强大的 AI 能力,可以访问数据和执行操作 |
支持的平台
- AI 助手:Claude、ChatGPT
- 开发工具:VS Code、Cursor、Windsurf
- 其他:Zed、Continue、MCPJam
二、架构概览
客户端-服务器模型
graph TB
subgraph "MCP Host(AI 应用)"
C1[MCP Client 1]
C2[MCP Client 2]
C3[MCP Client 3]
end
S1[MCP Server A<br/>本地文件系统]
S2[MCP Server B<br/>数据库]
S3[MCP Server C<br/>远程服务]
C1 -->|STDIO| S1
C2 -->|STDIO| S2
C3 -->|HTTP| S3
关键角色
| 角色 | 说明 | 示例 |
|---|---|---|
| MCP Host | AI 应用,管理多个 MCP Client | Claude Desktop、VS Code |
| MCP Client | 维护与 MCP Server 的连接 | VS Code 中的连接实例 |
| MCP Server | 提供上下文给 MCP Client | 文件系统服务器、Sentry 服务器 |
两层架构
flowchart TB
subgraph 传输层
A[STDIO Transport<br/>本地进程通信]
B[HTTP Transport<br/>远程服务通信]
end
subgraph 数据层
C[生命周期管理]
D[Primitives<br/>Tools/Resources/Prompts]
E[Notifications]
end
A --> C
B --> C
C --> D
D --> E
三、核心概念
1. Primitives(原语)
MCP 定义了三类服务器原语:
Tools(工具)
可执行的函数,AI 可以调用以执行操作:
{
"name": "weather_current",
"description": "获取指定地点的天气信息",
"inputSchema": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "城市名称或坐标"
},
"units": {
"type": "string",
"enum": ["metric", "imperial"],
"default": "metric"
}
},
"required": ["location"]
}
}
Resources(资源)
数据源,提供上下文信息:
{
"uri": "file:///path/to/document.pdf",
"name": "项目文档",
"mimeType": "application/pdf"
}
Prompts(提示词)
可复用的交互模板:
{
"name": "code_review",
"description": "代码审查提示词模板",
"arguments": [
{
"name": "language",
"description": "编程语言",
"required": true
}
]
}
2. Client Primitives
服务器也可以请求客户端的能力:
| 原语 | 方法 | 用途 |
|---|---|---|
| Sampling | sampling/complete | 请求 LLM 补全 |
| Elicitation | elicitation/request | 请求用户输入 |
| Logging | logging/* | 发送日志消息 |
3. Notifications
实时通知,保持客户端和服务器同步:
{
"jsonrpc": "2.0",
"method": "notifications/tools/list_changed"
}
四、通信流程
初始化握手
sequenceDiagram
participant Client
participant Server
Client->>Server: initialize request
Note over Client,Server: 协议版本、能力协商
Server->>Client: initialize response
Client->>Server: initialized notification
Note over Client,Server: 连接就绪
初始化请求:
{
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": {
"protocolVersion": "2025-06-18",
"capabilities": {
"elicitation": {}
},
"clientInfo": {
"name": "my-client",
"version": "1.0.0"
}
}
}
初始化响应:
{
"jsonrpc": "2.0",
"id": 1,
"result": {
"protocolVersion": "2025-06-18",
"capabilities": {
"tools": { "listChanged": true },
"resources": {}
},
"serverInfo": {
"name": "my-server",
"version": "1.0.0"
}
}
}
工具调用流程
sequenceDiagram
participant Client
participant Server
Client->>Server: tools/list
Server->>Client: 工具列表
Client->>Server: tools/call
Note over Client,Server: 执行工具
Server->>Client: 执行结果
五、与 Function Calling 对比
| 维度 | Function Calling | MCP |
|---|---|---|
| 标准化 | 各厂商不同 | 统一标准 |
| 生态 | 封闭 | 开放 |
| 传输 | API 调用 | STDIO / HTTP |
| 发现 | 手动配置 | 自动发现 |
| 状态 | 无状态 | 有状态 |
| 通知 | 不支持 | 支持 |
Function Calling 的问题
tools = [{"type": "function", "function": {...}}]
tools = [{"name": "...", "input_schema": {...}}]
tools = [Tool(function_declarations=[...])]
每个平台都有自己的格式,MCP 统一了这些差异。
MCP 的优势
- 一次开发,处处运行:写一个 MCP Server,可以在 Claude、ChatGPT、VS Code 中使用
- 标准化协议:基于 JSON-RPC 2.0
- 丰富生态:大量现成的 MCP Server
- 实时同步:通知机制保持状态一致
六、开发 MCP Server
使用 Python SDK
from mcp.server import Server
from mcp.server.stdio import stdio_server
from mcp.types import Tool, TextContent
server = Server("my-server")
@server.list_tools()
async def list_tools():
return [
Tool(
name="calculator",
description="执行数学计算",
inputSchema={
"type": "object",
"properties": {
"expression": {
"type": "string",
"description": "数学表达式"
}
},
"required": ["expression"]
}
)
]
@server.call_tool()
async def call_tool(name: str, arguments: dict):
if name == "calculator":
result = eval(arguments["expression"])
return [TextContent(type="text", text=str(result))]
raise ValueError(f"Unknown tool: {name}")
async def main():
async with stdio_server() as (read, write):
await server.run(read, write)
if __name__ == "__main__":
import asyncio
asyncio.run(main())
使用 TypeScript SDK
import { Server } from "@modelcontextprotocol/sdk/server";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio";
const server = new Server({
name: "my-server",
version: "1.0.0"
}, {
capabilities: {
tools: {}
}
});
server.setRequestHandler("tools/list", async () => ({
tools: [{
name: "calculator",
description: "执行数学计算",
inputSchema: {
type: "object",
properties: {
expression: {
type: "string",
description: "数学表达式"
}
},
required: ["expression"]
}
}]
}));
server.setRequestHandler("tools/call", async (request) => {
if (request.params.name === "calculator") {
const result = eval(request.params.arguments.expression);
return {
content: [{ type: "text", text: String(result) }]
};
}
throw new Error(`Unknown tool: ${request.params.name}`);
});
const transport = new StdioServerTransport();
await server.connect(transport);
七、配置 MCP Server
Claude Desktop 配置
{
"mcpServers": {
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/dir"]
},
"postgres": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-postgres"],
"env": {
"DATABASE_URL": "postgresql://user:pass@localhost/db"
}
}
}
}
VS Code 配置
{
"mcp.servers": {
"github": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"],
"env": {
"GITHUB_TOKEN": "${input:github_token}"
}
}
}
}
八、官方 MCP Servers
| 服务器 | 功能 |
|---|---|
| filesystem | 文件系统访问 |
| postgres | PostgreSQL 数据库 |
| sqlite | SQLite 数据库 |
| github | GitHub API |
| gitlab | GitLab API |
| google-maps | Google Maps API |
| slack | Slack API |
| puppeteer | 浏览器自动化 |
九、最佳实践
1. 工具命名
// ✅ 好的命名
"name": "weather_current"
"name": "database_query"
// ❌ 不好的命名
"name": "getWeather"
"name": "query"
2. 描述要详细
{
"description": "获取指定地点的当前天气信息,包括温度、湿度、风速等。支持城市名称、地址或坐标格式。"
}
3. 错误处理
@server.call_tool()
async def call_tool(name: str, arguments: dict):
try:
# 执行操作
result = do_something(arguments)
return [TextContent(type="text", text=str(result))]
except Exception as e:
return [TextContent(type="text", text=f"错误: {str(e)}", isError=True)]
4. 使用通知
await server.send_notification("notifications/tools/list_changed")
十、总结
MCP 的核心价值
| 价值 | 说明 |
|---|---|
| 标准化 | 统一的协议,一次开发处处运行 |
| 生态 | 丰富的现成服务器 |
| 实时 | 通知机制保持同步 |
| 灵活 | 本地/远程,STDIO/HTTP |
适用场景
- AI 助手:连接数据源和工具
- IDE 集成:增强开发体验
- 企业应用:连接内部系统
- 自动化:工作流集成