首页 / 技术博客 / MCP协议深度解析:AI工具调用的统一标准
技术动态 2026-06-07

MCP协议深度解析:AI工具调用的统一标准

全面解析Anthropic提出的Model Context Protocol,探讨MCP如何成为AI Agent工具调用的行业标准。

MCP三大原语 🔧 Tools 工具 模型可调用的函数/操作 📄 Resources 资源 模型可读取的数据/文件 💬 Prompts 提示 预定义的提示模板
MCP协议架构 MCP Host Claude / Cursor MCP Client JSON-RPC 2.0 Tools 工具 Resources 资源 传输层: stdio (本地进程) / SSE (远程服务) / Streamable HTTP (2026新标准)

MCP:AI工具调用的"USB标准"

在AI Agent爆发的2025-2026年,一个关键问题困扰着整个生态:每个AI应用都需要为每个外部工具编写定制集成代码。Anthropic在2024年底提出的Model Context Protocol(MCP)正在改变这一局面——它定义了一套开放的JSON-RPC 2.0协议,让AI模型能够以统一方式发现、调用外部工具和访问数据资源。截至目前,MCP已被Claude Desktop、Cursor、Cline、Windsurf等主流AI产品采纳,生态中已有超过10,000个MCP Server。

MCP核心架构

MCP采用经典的客户端-服务器架构,包含三个核心角色:

  • MCP Host:用户直接交互的AI应用(如Claude Desktop、Cursor IDE)
  • MCP Client:运行在Host内部,负责与MCP Server建立一对一连接
  • MCP Server:暴露工具、资源和提示词的服务端程序

三大原语(Primitives)

MCP定义了三种核心能力原语:

Tools(工具)— 模型可以调用的函数,由模型主动决定何时调用:

{
  "name": "query_database",
  "description": "执行SQL查询并返回结果",
  "inputSchema": {
    "type": "object",
    "properties": {
      "sql": { "type": "string", "description": "SQL查询语句" },
      "database": { "type": "string", "enum": ["production", "analytics"] }
    },
    "required": ["sql"]
  }
}

Resources(资源)— 客户端可以读取的数据源,类似REST的GET端点:

{
  "uri": "file:///project/README.md",
  "name": "项目README",
  "mimeType": "text/markdown"
}

Prompts(提示词模板)— 预定义的交互模板,可带参数:

{
  "name": "code_review",
  "description": "代码审查模板",
  "arguments": [
    { "name": "language", "type": "string" },
    { "name": "code", "type": "string" }
  ]
}

传输协议

MCP支持三种传输方式,适配不同部署场景:

stdio — 最简单的方式,适合本地进程:

{
  "mcpServers": {
    "filesystem": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-filesystem", "/home/user"]
    }
  }
}

SSE(Server-Sent Events) — 适合远程服务,已逐步被替代。

Streamable HTTP(2026新标准) — 统一的HTTP传输,支持流式响应和会话管理:

POST /mcp HTTP/1.1
Content-Type: application/json
Mcp-Session-Id: abc123

{"jsonrpc": "2.0", "method": "tools/call", "params": {"name": "query_database", "arguments": {"sql": "SELECT * FROM users LIMIT 5"}}, "id": 1}

构建MCP Server实战

Python SDK实现

from mcp.server import Server
from mcp.types import Tool, TextContent
import mcp.server.stdio
import asyncio

server = Server("my-tools-server")

@server.list_tools()
async def list_tools():
    return [
        Tool(
            name="calculate_bmi",
            description="根据身高体重计算BMI指数",
            inputSchema={
                "type": "object",
                "properties": {
                    "weight_kg": {"type": "number", "description": "体重(千克)"},
                    "height_m": {"type": "number", "description": "身高(米)"}
                },
                "required": ["weight_kg", "height_m"]
            }
        ),
        Tool(
            name="search_docs",
            description="搜索内部文档库",
            inputSchema={
                "type": "object",
                "properties": {
                    "query": {"type": "string", "description": "搜索关键词"},
                    "limit": {"type": "integer", "default": 5}
                },
                "required": ["query"]
            }
        )
    ]

@server.call_tool()
async def call_tool(name: str, arguments: dict):
    if name == "calculate_bmi":
        bmi = arguments["weight_kg"] / (arguments["height_m"] ** 2)
        category = "偏瘦" if bmi < 18.5 else "正常" if bmi < 24 else "偏胖"
        return [TextContent(type="text", text=f"BMI: {bmi:.1f}, 分类: {category}")]

    elif name == "search_docs":
        # 对接向量数据库实现语义搜索
        results = await vector_db.search(arguments["query"], limit=arguments.get("limit", 5))
        return [TextContent(type="text", text="\n".join(r.content for r in results))]

async def main():
    async with mcp.server.stdio.stdio_server() as (read, write):
        await server.run(read, write, server.create_initialization_options())

if __name__ == "__main__":
    asyncio.run(main())

TypeScript SDK实现

import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";

const server = new Server(
  { name: "git-tools", version: "1.0.0" },
  { capabilities: { tools: {} } }
);

server.setRequestHandler(ListToolsRequestSchema, async () => ({
  tools: [{
    name: "git_log",
    description: "获取Git提交历史",
    inputSchema: {
      type: "object",
      properties: {
        repo: { type: "string" },
        limit: { type: "number", default: 10 }
      },
      required: ["repo"]
    }
  }]
}));

server.setRequestHandler(CallToolRequestSchema, async (request) => {
  if (request.params.name === "git_log") {
    const { execSync } = await import("child_process");
    const log = execSync(
      `git -C ${request.params.arguments.repo} log --oneline -n ${request.params.arguments.limit}`,
      { encoding: "utf-8" }
    );
    return { content: [{ type: "text", text: log }] };
  }
});

const transport = new StdioServerTransport();
await server.connect(transport);

客户端集成配置

Claude Desktop配置

{
  "mcpServers": {
    "postgres": {
      "command": "uvx",
      "args": ["mcp-server-postgres", "postgresql://localhost/mydb"]
    },
    "github": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-github"],
      "env": { "GITHUB_TOKEN": "ghp_xxxx" }
    }
  }
}

Cursor IDE配置(.cursor/mcp.json)

{
  "mcpServers": {
    "filesystem": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-filesystem", "."]
    }
  }
}

生态与社区

MCP生态正在快速成长:

  • mcp.so — MCP Server发现平台,收录超过8000个Server
  • Smithery — MCP Server注册中心,支持一键安装
  • 官方SDK — Python(mcp)和TypeScript(@modelcontextprotocol/sdk
  • Glama — MCP Server托管和管理平台

主流MCP Server包括:@modelcontextprotocol/server-filesystem(文件系统)、@modelcontextprotocol/server-github(GitHub操作)、@modelcontextprotocol/server-postgres(数据库查询)、@modelcontextprotocol/server-puppeteer(网页自动化)等。

总结

MCP正在成为AI工具调用的事实标准。它的核心价值在于解耦——工具开发者只需实现一次MCP Server,即可被所有支持MCP的AI应用调用。随着Streamable HTTP传输的标准化和远程Server的普及,MCP将推动AI Agent生态从"烟囱式集成"走向"即插即用"的开放生态。对于开发者而言,现在正是构建MCP Server、加入这一生态的最佳时机。

订阅更新

获取最新的AI本地化技术文章和教程