什么是 MCP 协议?
MCP(Model Context Protocol,模型上下文协议)是由 Anthropic 于 2024 年底提出、2025 年被 OpenAI、Google 等主流厂商广泛采纳的开放标准协议。它定义了 AI 大模型如何与外部工具、数据源、服务进行标准化交互,是 AI Agent 时代的”USB 接口”。
在 MCP 出现之前,每个 AI 应用都需要为不同的工具(数据库、API、文件系统等)编写专用的集成代码,维护成本极高。MCP 通过标准化通信协议,让一个 AI 模型可以无缝连接任意实现了 MCP Server 的服务。
MCP 架构设计
MCP 采用 Client-Server 架构,包含三个核心角色:
- MCP Host(宿主):运行 AI 模型的应用,如 Claude Desktop、Cursor、自定义 Agent
- MCP Client:嵌入在 Host 中,负责与 MCP Server 建立 1:1 连接
- MCP Server:独立进程,暴露特定能力(工具、资源、提示词)给 AI 使用
┌─────────────────────────────────────┐
│ MCP Host Application │
│ ┌──────────────────────────────┐ │
│ │ AI Model (LLM) │ │
│ └──────────────┬───────────────┘ │
│ │ │
│ ┌──────────────▼───────────────┐ │
│ │ MCP Client │ │
│ └──────┬───────────┬───────────┘ │
└─────────┼───────────┼───────────────┘
│ │
stdio/SSE stdio/SSE
│ │
┌─────────▼──┐ ┌──────▼─────────┐
│ MCP Server │ │ MCP Server │
│ (数据库) │ │ (文件系统) │
└────────────┘ └────────────────┘
MCP 三大核心能力
1. Tools(工具调用)
允许 AI 执行具体操作,类似 OpenAI Function Calling,但更标准化:
# MCP Server 定义一个工具(Python SDK 示例)
from mcp.server import Server
from mcp.types import Tool, TextContent
server = Server("my-database-server")
@server.list_tools()
async def list_tools():
return [
Tool(
name="query_database",
description="Execute a SQL query and return results",
inputSchema={
"type": "object",
"properties": {
"sql": {"type": "string", "description": "SQL query to execute"},
"database": {"type": "string", "description": "Database name"}
},
"required": ["sql"]
}
)
]
@server.call_tool()
async def call_tool(name: str, arguments: dict):
if name == "query_database":
sql = arguments["sql"]
# 执行查询逻辑...
result = execute_sql(sql)
return [TextContent(type="text", text=str(result))]
2. Resources(资源读取)
允许 AI 读取外部数据(文件、数据库记录、API 响应),数据作为上下文注入模型:
@server.list_resources()
async def list_resources():
return [
Resource(
uri="file:///logs/app.log",
name="Application Logs",
mimeType="text/plain"
)
]
@server.read_resource()
async def read_resource(uri: str):
if uri == "file:///logs/app.log":
with open("/logs/app.log") as f:
return f.read()
3. Prompts(提示词模板)
服务端定义可复用的提示词模板,AI 可按需调用:
@server.list_prompts()
async def list_prompts():
return [
Prompt(
name="analyze_error",
description="Analyze an error log and suggest fixes",
arguments=[
PromptArgument(name="error_text", description="The error message", required=True)
]
)
]
MCP 传输协议
MCP 支持两种传输方式:
| 传输方式 | 适用场景 | 特点 |
|---|---|---|
| stdio | 本地 MCP Server | 通过标准输入/输出通信,低延迟,无需网络 |
| SSE(Server-Sent Events) | 远程 MCP Server | 基于 HTTP,支持跨机器,适合云端部署 |
快速搭建一个 MCP Server
# 安装 MCP Python SDK
pip install mcp
# 创建一个简单的天气查询 MCP Server
# weather_server.py
import asyncio
from mcp.server import Server
from mcp.server.stdio import stdio_server
from mcp.types import Tool, TextContent
import urllib.request, json
server = Server("weather-server")
@server.list_tools()
async def list_tools():
return [Tool(
name="get_weather",
description="Get current weather for a city",
inputSchema={
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"]
}
)]
@server.call_tool()
async def call_tool(name: str, arguments: dict):
if name == "get_weather":
city = arguments["city"]
url = f"https://wttr.in/{city}?format=j1"
data = json.loads(urllib.request.urlopen(url).read())
temp = data["current_condition"][0]["temp_C"]
desc = data["current_condition"][0]["weatherDesc"][0]["value"]
return [TextContent(type="text", text=f"{city}: {temp}°C, {desc}")]
async def main():
async with stdio_server() as streams:
await server.run(*streams, server.create_initialization_options())
asyncio.run(main())
# 在 Claude Desktop 的 mcp.json 中注册该 Server:
{
"mcpServers": {
"weather": {
"command": "python",
"args": ["/path/to/weather_server.py"]
}
}
}
2026 年 MCP 生态现状
截至 2026 年初,MCP 生态已相当成熟:
- 官方 Server:Anthropic 提供了 GitHub、Slack、PostgreSQL、Filesystem、Brave Search 等 30+ 官方 MCP Server
- 主流 IDE 支持:Cursor、VS Code(GitHub Copilot)、JetBrains AI Assistant 均已内置 MCP 支持
- 多语言 SDK:官方提供 Python、TypeScript SDK,社区提供 Go、Rust、Java 等语言的实现
- 安全机制:2025 年底规范新增了 OAuth 2.0 授权和细粒度权限控制
总结
MCP 的出现极大降低了 AI Agent 的工具集成成本,是 AI 应用从”聊天”走向”行动”的关键基础设施。无论你是在开发 AI 产品,还是为企业内部系统添加 AI 能力,掌握 MCP 协议都是 2026 年最值得投入的技术之一。