第 10 讲:MCP 外部工具协议——连接无限扩展能力

OpenCode 源码解析 · 第 10 讲

OpenCode 源码解析 第 10 讲:MCP 外部工具协议——连接无限扩展能力 基于 dev 分支源码 · 2026-07-17 一、MCP:OpenCode 的外部扩展引擎 前九讲覆盖了 OpenCode 从 CLI 到 LSP 的内部能力。这一讲进入 MCP(Model Context Protocol) ——Anthropic 提出的标准化协议,让 OpenCode 能连接任意外部工具和服务。MCP 模块横跨 5 个文件、约 1,798 行代码 ,覆盖了配置解析、连接管理、OAuth 认证和工具桥接。 📦 本讲核心文件 packages/opencode/src/mcp/index.ts (1012 行)— MCP 服务与连接管理 packages/opencode/src/mcp/auth.ts (163 行)— OAuth 令牌存储 packages/opencode/src/mcp/catalog.ts (170 行)— 工具目录与转换 packages/opencode/src/mcp/oauth-provider.ts (259 行)— OAuth 认证提供者 packages/opencode/src/mcp/oauth-callback.ts (194 行)— OAuth 回调处理 二、MCP Service 架构 mcp/index.ts 实现了完整的 MCP 服务,支持三种传输方式:Stdio、SSE、Streamable HTTP。核心是 Interface 接口和 State 状态管理。 1. MCP 服务接口 📄 mcp/index.ts (第 157-180 行) export interface Interface { readonly status: () => Effect.Effect<Record<string, Status>> readonly clients: () => Effect.Effect<Record<string, MCPClient>> readonly instructions: () => Effect.Effect<ServerInstructions[]> readonly tools: () => Effect.Effect<Record<string, Tool>> readonly prompts: () => Effect.Effect<Record<string, PromptInfo>> readonly resources: (clientName?: string) => Effect.Effect<Record<string, ResourceInfo>> readonly resourceTemplates: (clientName?: string) => Effect.Effect<Record<string, ResourceTemplateInfo>> readonly add: (name: string, mcp: ConfigMCPV1.Info) => Effect.Effect<{ status: Status }> readonly connect: (name: string) => Effect.Effect<void> readonly disconnect: (name: string) => Effect.Effect<void> readonly getPrompt: (clientName: string, name: string, args?: Record<string, string>) => Effect.Effect<PromptResult> readonly readResource: (clientName: string, resourceUri: string) => Effect.Effect<ResourceResult> readonly startAuth: (name: string) => Effect.Effect<AuthResult> } 设计亮点: 13 个公开方法覆盖了 MCP 协议的核心能力——状态查询、客户端管理、工具注册、资源访问、Prompt 调用和 OA…

阅读全文:OpenCode 源码解析 第 10 讲