深度长文|MCP 协议 2026:从 0 到事实标准,开发者完全指南
MCP(Model Context Protocol)是 Anthropic 在 2024 年底提出、2025 年被 OpenAI / Google / 开源社区接受的 AI 工具调用协议。2026 年 6 月,它已经事实上成为标准。
本文 5000 字:协议原理、生态现状、Server 开发、最佳实践。
一、协议原理
MCP 是一个JSON-RPC 风格的协议,定义了 Agent 与工具之间的通信方式。
三类角色:
通信方式:
二、生态现状(2026 年 6 月)
三、写一个 MCP Server
from mcp.server import Server
from mcp.types import Tool, TextContent
app = Server("my-mcp-server")
@app.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"]
}
)
]
@app.call_tool()
async def call_tool(name: str, arguments: dict):
if name == "get_weather":
city = arguments["city"]
# 调用天气 API
result = await fetch_weather(city)
return [TextContent(type="text", text=result)]
if __name__ == "__main__":
app.run("stdio")
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
const server = new Server({ name: "my-mcp-server", version: "1.0.0" }, { capabilities: { tools: {} } });
server.setRequestHandler(ListToolsRequestSchema, async () => ({
tools: [{
name: "get_weather",
description: "Get current weather",
inputSchema: { type: "object", properties: { city: { type: "string" } }, required: ["city"] }
}]
}));
server.setRequestHandler(CallToolRequestSchema, async (request) => {
if (request.params.name === "get_weather") {
const result = await fetchWeather(request.params.arguments.city);
return { content: [{ type: "text", text: result }] };
}
throw new Error("Unknown tool");
});
const transport = new StdioServerTransport();
await server.connect(transport);
{
"mcpServers": {
"weather": {
"command": "python",
"args": ["/path/to/weather_server.py"],
"env": {"WEATHER_API_KEY": "xxx"}
},
"github": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"],
"env": {"GITHUB_TOKEN": "ghp_xxx"}
}
}
}