MCP SDK 深度解读
Model Context Protocol(MCP)是 Anthropic 开源的 Agent 工具调用标准协议,定义了 LLM 应用与外部工具/数据源之间的通信规范。2025 年发布后迅速成为行业标准,Claude Code、Cursor、Windsurf 等主流 Agent 工具均已原生支持。
GitHub: https://github.com/modelcontextprotocol/python-sdk
前置知识
- Agent 架构概述 — 理解 Agent 的工具调用循环
- Function Calling 原理 — LLM 工具调用的基础
项目定位
MCP 解决的核心问题:不同 Agent 工具如何统一接入各种外部工具?为什么需要一个"USB-C for AI"标准?
核心概念
| 概念 | 说明 |
|---|---|
| Tools | Server 暴露给 LLM 的可调用函数(如 read_file、search_web) |
| Resources | Server 暴露给 LLM 的可读数据(如文件内容、数据库记录) |
| Prompts | Server 预定义的提示词模板 |
| Client | LLM 应用端,负责发现 Server 能力并发起调用 |
| Server | 工具提供端,声明能力并执行调用 |
完整项目文件树
python-sdk/
├── src/mcp/
│ ├── __init__.py
│ ├── types.py # 核心数据类型(Tool/Resource/Prompt)
│ ├── server/
│ │ ├── __init__.py
│ │ ├── fastmcp.py # 高层 API:装饰器定义工具
│ │ ├── lowlevel.py # 低层 API:手动管理协议
│ │ └── memory.py # 资源订阅与通知
│ ├── client/
│ │ ├── __init__.py
│ │ ├── client.py # Client 基类
│ │ ├── session.py # 会话管理
│ │ └── auth.py # OAuth 认证
│ ├── shared/
│ │ ├── protocol.py # JSON-RPC 消息定义
│ │ ├── session.py # 会话状态机
│ │ └── exceptions.py # 错误类型
│ ├── server/
│ │ └── stdio.py # stdio 传输
│ └── client/
│ ├── stdio.py # stdio 客户端
│ └── streamable_http.py # HTTP 传输
└── examples/
├── everything/ # 全功能示例 Server
└── quickstart/ # 快速入门
关键模块解析
1. FastMCP — 装饰器式工具定义
from mcp.server.fastmcp import FastMCP
mcp = FastMCP("my-server")
@mcp.tool()
def read_file(path: str) -> str:
"""读取指定路径的文件内容"""
with open(path) as f:
return f.read()
@mcp.resource("config://app")
def get_config() -> str:
"""返回应用配置"""
return "debug=true"
if __name__ == "__main__":
mcp.run() # 默认 stdio 传输
FastMCP 通过 Python 类型注解自动生成 JSON Schema,这是 MCP 最优雅的设计——开发者只需写普通函数,协议细节由框架处理。
2. 协议层 — JSON-RPC 2.0
MCP 基于 JSON-RPC 2.0,核心方法:
| 方法 | 方向 | 说明 |
|---|---|---|
initialize | Client → Server | 握手,交换协议版本和能力 |
tools/list | Client → Server | 获取 Server 提供的工具列表 |
tools/call | Client → Server | 调用指定工具 |
resources/list | Client → Server | 获取可读资源列表 |
resources/read | Client → Server | 读取资源内容 |
notifications/tools/list_changed | Server → Client | 工具列表更新通知 |
3. 传输层
MCP 支持两种传输方式:
- stdio:父子进程通信,Client 启动 Server 子进程,通过 stdin/stdout 交换消息。适合本地工具。
- Streamable HTTP:Server 运行在远程,Client 通过 HTTP POST 发送请求,SSE 接收通知。适合云端工具。
4. 能力协商(Capabilities)
握手时双方声明自己支持的能力:
# Client 声明
{
"capabilities": {
"roots": {"listChanged": True}, // 支持工作区根目录
"sampling": {} // 支持 Server 反向调用 LLM
}
}
# Server 声明
{
"capabilities": {
"tools": {"listChanged": True}, // 工具列表可动态变化
"resources": {"subscribe": True}, // 支持资源订阅
"prompts": {"listChanged": True} // 提示词列表可动态变化
}
}
FDE 实战要点
- 写 MCP Server 是 FDE 高频工作:公司内部工具(数据库查询、API调用、部署操作)都需要封装成 MCP Server 供 Agent 调用
- stdio 模式最常用:Claude Code 等工具通过子进程方式启动 MCP Server,无需网络配置
- 错误处理很重要:工具调用失败时返回结构化错误信息,让 Agent 能理解并恢复
- 安全边界:MCP Server 有系统权限,需要严格控制暴露的工具和参数验证