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 HostAI 应用,管理多个 MCP ClientClaude 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

服务器也可以请求客户端的能力:

原语方法用途
Samplingsampling/complete请求 LLM 补全
Elicitationelicitation/request请求用户输入
Logginglogging/*发送日志消息

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 CallingMCP
标准化各厂商不同统一标准
生态封闭开放
传输API 调用STDIO / HTTP
发现手动配置自动发现
状态无状态有状态
通知不支持支持

Function Calling 的问题

tools = [{"type": "function", "function": {...}}]

tools = [{"name": "...", "input_schema": {...}}]

tools = [Tool(function_declarations=[...])]

每个平台都有自己的格式,MCP 统一了这些差异。

MCP 的优势

  1. 一次开发,处处运行:写一个 MCP Server,可以在 Claude、ChatGPT、VS Code 中使用
  2. 标准化协议:基于 JSON-RPC 2.0
  3. 丰富生态:大量现成的 MCP Server
  4. 实时同步:通知机制保持状态一致

六、开发 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文件系统访问
postgresPostgreSQL 数据库
sqliteSQLite 数据库
githubGitHub API
gitlabGitLab API
google-mapsGoogle Maps API
slackSlack 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 集成:增强开发体验
  • 企业应用:连接内部系统
  • 自动化:工作流集成

参考资料

📝 文章反馈