Chapter 08
MCP 协议集成
Model Context Protocol (MCP) 让 Claude Code 可以连接外部工具服务器 — 将任意工具、资源和 prompt 模板无缝集成到对话中。
MCP 概览
MCP 是 Anthropic 提出的标准协议,用于连接 AI 模型和外部工具/数据源。Claude Code 作为 MCP Client,可以连接多个 MCP Server。
MCP Client
Claude Code
↔
GitHub MCP Server
PR, Issues, Reviews
Database MCP Server
Query, Schema
Custom MCP Server
自定义工具
集成架构
MCP 集成涉及以下关键组件:
- MCP Client 管理 — AppState 中维护
mcpClients列表,每个连接对应一个 MCP Server - 工具注入 — MCP Server 提供的工具以
mcp__{server}__{tool}前缀注入到工具池 - 资源访问 — 通过
ListMcpResourcesTool和ReadMcpResourceTool读取 MCP 资源 - MCPTool 代理 — 通用工具代理,透传执行任意 MCP 工具
MCP 工具代理
MCP Server 提供的工具通过 MCPTool 代理执行:
// MCP 工具命名约定 mcp__github__create_pr // server: github, tool: create_pr mcp__database__query // server: database, tool: query mcp__slack__send_message // server: slack, tool: send_message // MCPTool 执行流程 class MCPTool { // 开放式输入 schema — 透传 MCP 工具的参数 inputSchema: 'passthrough' async call(input, context) { // 1. 工具名和参数在运行时覆盖 const result = await mcpClient.callTool(toolName, input); // 2. 返回执行结果 return result; } }
权限处理
MCP 工具的权限通过通配符匹配:
// 权限规则示例 { toolName: 'mcp__github__*' } // 允许 github server 的所有工具 { toolName: 'mcp__database__query' } // 仅允许 database 的 query 工具
资源系统
ListMcpResourcesTool
列出 MCP Server 可用资源。支持按 server 名称过滤。返回 URI、名称、MIME 类型、描述。使用 LRU 缓存。
ReadMcpResourceTool
通过 URI 读取特定资源内容。支持文本和二进制内容。二进制数据持久化到 blob 文件。
MCP Server 生命周期
1
配置注册
MCP Server 在 settings.json 或 Agent 定义的 mcpServers 中配置。包含启动命令、环境变量等。
2
连接建立
Claude Code 启动时或 Agent 初始化时,连接配置的 MCP Server。initializeAgentMcpServers() 处理 Agent 专属的 Server。
3
工具发现
连接后自动发现 Server 提供的工具,以 mcp__ 前缀加入工具池。工具 schema 从 Server 动态获取。
4
使用 & 清理
对话中正常使用 MCP 工具。Agent 退出时清理内联定义的 Server(命名引用的 Server 被 memoize 保留)。