MCP协议详解:让AI Agent连接万物 MCP 协议实战给 AI 接上外部世界给 Claude 写工具给 GPT 写插件给 DeepSeek 写适配……换一个 AI 就得重写一遍。MCPModel Context Protocol要解决的就是这个问题——写一个 Server所有 AI 都能用。一、没有 MCP 的世界# 给 Claude 写工具claude_tooldefget_weather(city):...# 给 GPT 写工具语法不一样openai_tool{type:function,function:{name:get_weather,...}}# 给 DeepSeek 写工具又是另一种格式deepseek_tool{...}三个 AI三套工具代码。MCP 说别重复造轮子了。二、MCP 怎么工作┌──────────────────────────────────────────┐ │ MCP Host │ │ (Claude Desktop / Cursor / VS Code) │ │ │ │ ┌──────────────────────────────────┐ │ │ │ MCP Client │ │ │ │ (Host 内部管理连接) │ │ │ └──────────┬───────────────────────┘ │ └──────────────┼───────────────────────────┘ │ JSON-RPC 2.0 │ (stdio 或 HTTP) ┌──────────────▼───────────────────────────┐ │ MCP Server │ │ ┌─────────┐ ┌────────┐ ┌─────────┐ │ │ │Resources│ │ Tools │ │ Prompts │ │ │ └─────────┘ └────────┘ └─────────┘ │ │ │ │ ┌──────────────┐ │ │ │ Data Source │ │ │ │ (文件/数据库/API)│ │ │ └──────────────┘ │ └──────────────────────────────────────────┘四大能力能力说明示例Resources只读数据文件内容、数据库查询结果Tools可执行动作发邮件、创建文件、调 APIPrompts预设指令模板“审阅这段代码”SamplingServer 反向请求 LLM生成摘要三、写你的第一个 MCP Server# 安装pip install mcpfrommcp.server.fastmcpimportFastMCP mcpFastMCP(我的第一个 MCP Server)mcp.tool()defget_weather(city:str)-str:获取指定城市的天气信息weather_db{北京:晴25°C湿度 40%,上海:多云28°C湿度 65%,}returnweather_db.get(city,f未找到{city}的天气数据)mcp.tool()defcalculate(expression:str)-str:执行数学计算try:returnstr(eval(expression,{__builtins__:{}},{}))exceptExceptionase:returnf计算错误{e}mcp.resource(file://{path})defread_local_file(path:str)-str:读取本地文件内容try:withopen(path,r,encodingutf-8)asf:returnf.read()exceptExceptionase:returnf读取失败{e}if__name____main__:mcp.run()# 默认 stdio 模式保存为weather_server.py就这么简单。四、配置 Claude Desktop 使用它编辑 Claude Desktop 配置文件// macOS: ~/Library/Application Support/Claude/claude_desktop_config.json// Windows: %APPDATA%\Claude\claude_desktop_config.json{mcpServers:{weather-server:{command:python,args:[/path/to/weather_server.py]}}}重启 Claude Desktop在对话中输入北京今天什么天气Claude 会自动调用get_weather(北京)拿到结果后回复。五、生产级 MCP Server 写法5.1 工具设计原则# ❌ 一个工具干三件事mcp.tool()deffile_operation(op:str,path:str,content:str)-str:ifopread:...elifopwrite:...elifopdelete:...# ✅ 一个工具干一件事mcp.tool()defread_file(path:str)-str:读取文件内容mcp.tool()defwrite_file(path:str,content:str)-str:写入文件mcp.tool()defdelete_file(path:str)-str:删除文件原则单一职责、动词名词命名、参数类型明确、描述写清楚。5.2 HTTP 模式远程部署# pip install mcp[cli]# 启动 HTTP 模式的 MCP Server# mcp run weather_server.py --transport streamable-http --port 8080配置 Claude Desktop 远程连接{mcpServers:{weather-server:{url:http://your-server:8080/mcp,transport:streamable-http}}}5.3 安全防护importosmcp.tool()defread_file_safe(path:str)-str:安全读取文件限制目录、大小# 1. 路径遍历攻击防护safe_base/allowed/directoryfull_pathos.path.normpath(os.path.join(safe_base,path))ifnotfull_path.startswith(safe_base):return拒绝路径越界# 2. 文件大小限制ifos.path.getsize(full_path)10*1024*1024:# 10MBreturn拒绝文件超过 10MB# 3. 只读打开withopen(full_path,r)asf:returnf.read()六、MCP 常见 Server 推荐MCP Server用途anthropic/mcp-server-filesystem读写本地文件anthropic/mcp-server-github操作 GitHubIssue/PR/仓库anthropic/mcp-server-postgres查询 PostgreSQLPlaywright MCP浏览器自动化Brave Search MCP网络搜索MCP Hubhttps://mcp-cn.com 有 74 个中文 MCP Server。七、MCP vs Function Calling vs LangChain Tools维度Function CallingLangChain ToolMCP复用性❌ 绑定 LLM❌ 绑定 LangChain✅ 一次开发处处用标准化❌ 各厂商不同❌ LangChain 专属✅ 开放协议远程调用❌需要额外代码✅ 原生支持 HTTP适合场景单次开发LangChain 项目跨平台工具MCP 不是要替代 Function Calling而是提供工具接入的标准化方式。八、总结MCP AI 工具的 USB-C——写一个 Server所有 AI 都能用Python 写 MCP Server 只需 3 行装饰器——FastMCP 极简本地用 stdio远程用 HTTP——两种传输模式覆盖所有场景工具设计要单一职责——不要让 LLM 猜一个工具多种用途九、生产实战MCP Server 上线的检查清单9.1 权限隔离——MCP Server 的安全底线MCP Server 在本地运行时默认拥有当前用户的全部文件权限。一个 LLM 调了你的 MCP Server等于有了你的系统权限# 最安全的方式Docker 隔离运行# Dockerfile.mcpFROM python:3.12-slim RUN pipinstallmcp COPY my_server.py /app/ WORKDIR /app CMD[python,my_server.py]# 启动时限制文件系统访问# 只允许读写 /safe_data 目录dockerrun--rm\-v/safe_data:/safe_data:rw\--read-only\--networknone\my-mcp-server经验不要在生产环境用python my_server.py直接跑。MCP Server 跑在 Docker 里限制文件系统和网络访问就算 LLM 发疯也炸不了宿主机。9.2 高频调用的性能陷阱一个 Agent 可能在一轮对话中连续调用 10 次 MCP 工具。如果 MCP Server 每次都要冷启动延迟不可接受# ❌ 每个请求重连数据库defget_user(id:str)-str:dbconnect_to_db()# 慢resultdb.query(id)db.close()returnresult# ✅ 启动时建立连接池复用classDatabasePool:def__init__(self):self.poolcreate_connection_pool(min_size2,max_size10)defget_user(self,id:str)-str:withself.pool.get_connection()asconn:returnconn.query(id)db_poolDatabasePool()# 全局单例mcp.tool()defget_user(id:str)-str:returndb_pool.get_user(id)9.3 MCP Server 的版本兼容MCP 协议还在快速演进。2025 年 3 月从 HTTPSSE 升级到 Streamable HTTP。你的 Server 可能突然不兼容新版 Claude Desktop# 用 __version__ 标记协议版本方便排查# 如果 Claude Desktop 更新后连不上先检查协议版本mcpFastMCP(my-server,version1.0.0)# 锁定 mcp 依赖版本避免自动升级踩坑# requirements.txtmcp1.8.09.4 调试看不到 MCP Server 的报错MCP stdio 模式的报错不会出现在终端里——它藏在日志文件中# Claude Desktop 的 MCP 日志tail-f~/Library/Logs/Claude/mcp*.log# 或者用 MCP Inspector 调试npx modelcontextprotocol/inspector python my_server.py9.5 测试 MCP ServerimportpytestfrommcpimportClientpytest.mark.asyncioasyncdeftest_get_weather():asyncwithClient(python my_server.py)asclient:resultawaitclient.call_tool(get_weather,{city:北京})assert晴inresultor雨inresultor多云inresult下一篇《Multi-Agent 协作CrewAI 实战》——让 PM Agent、开发 Agent、测试 Agent 一起干活。系列文章00-总纲 → ①-LLM 原理 → ②-Prompt 工程 → ③-Function Calling → ④-RAG → ⑤-Agent 模式 → ⑥-LangGraph → ⑦-MCP → ⑧-Multi-Agent