MCP 是大模型与外部系统之间的标准化接口协议,让 AI 应用可以像 USB 设备一样即插即用。

核心概念 Link to heading

你在 Claude Code 中使用 skill、调用外部工具时,底层就是 MCP 在通信。

MCP 定义了三类角色:

  • Host — 运行大模型的宿主程序,如 Claude Desktop、IDE 插件、自定义 AI 应用
  • Client — 嵌入 Host 的 MCP 客户端,负责与 Server 建立连接、发送请求、管理生命周期。Host 可以包含多个 Client,每个 Client 连接一个 Server
  • Server — 暴露能力给大模型的服务端,提供三种核心资源:
    • Tools — 可执行操作(API 调用、数据库查询、文件读写)
    • Resources — 只读数据源(文件、日志、配置)
    • Prompts — 预置模板(快速构造结构化输入)

传输层支持两种协议:

  • stdio — 本地进程通信,通过标准输入/输出传递 JSON-RPC 消息
  • SSE(Server-Sent Events) — 远程 HTTP 通信,适合跨网络场景

协议层统一使用 JSON-RPC 2.0 格式,确保不同语言、不同平台的实现可以互操作。

架构与数据流 Link to heading

Host、Client、Server 之间的调用链路如下:

sequenceDiagram participant H as Host (Claude Desktop) participant C as Client (MCP Client) participant S as Server (MCP Server) H->>C: 用户请求"查天气" C->>S: tools/list (初始化时获取可用工具) S-->>C: 返回工具列表 [get_weather] C->>H: 可用工具清单 H->>C: tools/call (name="get_weather", args={city: "Beijing"}) C->>S: JSON-RPC tools/call 请求 S-->>C: 执行结果 {temperature: 25, unit: "C"} C-->>H: 返回结构化结果 H->>H: 将结果注入上下文,生成回复

关键要点:

  1. 初始化阶段 — Client 连接 Server 后,首先调用 tools/list / resources/list / prompts/list 获取可用能力
  2. 运行时调用 — Host 决定调用哪个工具,Client 将其转换为 JSON-RPC 请求发送给 Server
  3. 结果回传 — Server 执行逻辑,返回结构化数据,Host 将其注入模型上下文

一条典型的 JSON-RPC 请求:

{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "tools/call",
  "params": {
    "name": "get_weather",
    "arguments": { "city": "Beijing" }
  }
}

实际使用 Link to heading

场景一:解析 MCP Server 配置 Link to heading

在 Claude Code 的 settings.json 中配置 MCP Server:

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

这里的 commandargs 定义了启动方式,Claude Code 通过 stdio 与 Server 通信。

场景二:最简 MCP Server(Python) Link to heading

from mcp.server.fastmcp import FastMCP

mcp = FastMCP("demo")

@mcp.tool()
def hello(name: str) -> str:
    return f"Hello, {name}!"

if __name__ == "__main__":
    mcp.run()

不到 10 行代码就实现了一个 MCP Server。启动后,任何支持 MCP 的 Host(Claude Desktop、Claude Code)都能发现 hello 这个工具并调用它。

// 请求
{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"hello","arguments":{"name":"World"}}}
// 响应
{"jsonrpc":"2.0","id":1,"result":{"content":[{"type":"text","text":"Hello, World!"}]}}

这就是 MCP 协议的核心:定义能力、建立连接、交换消息。无论多复杂的 Server,都遵循这个模式。

官方链接 Link to heading

[1] https://modelcontextprotocol.io/introduction

[2] https://modelcontextprotocol.io/docs

[3] https://github.com/modelcontextprotocol/python-sdk

[4] https://github.com/modelcontextprotocol/typescript-sdk

Signature Link to heading

本文由 AI 生成,不保证正确,仅作参考