|
| 1 | +import { MultiServerMCPClient } from "@langchain/mcp-adapters"; |
| 2 | +import { StructuredToolInterface } from "@langchain/core/tools"; |
| 3 | +import type { ILogger } from "../Logger"; |
| 4 | + |
| 5 | +// 远端 MCP 服务(HTTP / SSE / streamable_http)重启 / 进程重建 / 网络抖动后, |
| 6 | +// 缓存的 client 上的请求会失败。codex 的设计是在 transport 层精准识别 HTTP 404 |
| 7 | +// + active session_id,但 langchain mcp-adapters 把 transport 包了一层,HTTP |
| 8 | +// 状态码上不来,所以这里覆盖更宽: |
| 9 | +// - JSON-RPC -32602(InvalidParams,常见于 session_id 不识别)/ -32000(ConnectionClosed) |
| 10 | +// - Node 网络层:ECONNRESET / ECONNREFUSED / EPIPE / ENOTFOUND / ETIMEDOUT |
| 11 | +// - undici/fetch:fetch failed / socket hang up / stream closed / 404 |
| 12 | +export function isStaleMcpConnectionError(err: any): boolean { |
| 13 | + if (!err) return false; |
| 14 | + const code = err.code; |
| 15 | + if (typeof code === 'number' && (code === -32602 || code === -32000)) return true; |
| 16 | + if (typeof code === 'string' && /^(ECONNRESET|ECONNREFUSED|EPIPE|ENOTFOUND|ETIMEDOUT|UND_ERR_SOCKET)$/.test(code)) return true; |
| 17 | + const msg = String(err?.message ?? ''); |
| 18 | + return /MCP error -3260[02]|fetch failed|socket hang up|stream (closed|aborted)|terminated|HTTP 404|status:?\s*404/i.test(msg); |
| 19 | +} |
| 20 | + |
| 21 | +type ConnectResult = { |
| 22 | + client: MultiServerMCPClient; |
| 23 | + tools: StructuredToolInterface[]; |
| 24 | +}; |
| 25 | + |
| 26 | +type State = |
| 27 | + | { kind: 'idle' } |
| 28 | + | { kind: 'connecting'; promise: Promise<ConnectResult> } |
| 29 | + | { kind: 'ready'; client: MultiServerMCPClient; tools: StructuredToolInterface[]; version: number } |
| 30 | + | { kind: 'closed' }; |
| 31 | + |
| 32 | +/** |
| 33 | + * 单个 MCP server 的连接包装,参考 codex 的 RmcpClient |
| 34 | + * (codex-rs/rmcp-client/src/rmcp_client.rs)。 |
| 35 | + * |
| 36 | + * 设计要点: |
| 37 | + * - 显式状态机:idle → connecting → ready → (recovery →) ready → ... → closed |
| 38 | + * - 原子 swap:recovery 完成后一次性替换 state |
| 39 | + * - 并发恢复合并:用 promise 链串行化,靠版本号判断"已恢复",惊群只触发一次重连 |
| 40 | + * - 操作级 retry:getTools / listPrompts / readResource / call_tool 等都走 |
| 41 | + * runOperation;命中 stale 错误自动重连并重试一次(仅一次,与 codex 一致) |
| 42 | + * - tool 级 retry:getTools 返回的每个 tool 自动通过 wrapTool 路由到 invokeTool, |
| 43 | + * 使工具调用透明地享受 recovery |
| 44 | + */ |
| 45 | +export class RecoverableMcpClient { |
| 46 | + private state: State = { kind: 'idle' }; |
| 47 | + private recoveryQueue: Promise<void> = Promise.resolve(); |
| 48 | + private versionCounter = 0; |
| 49 | + |
| 50 | + /** 连接超时(建立连接 + 拉首次 tool list 的总时长上限)。 |
| 51 | + * MCP server "TCP 通了但不响应" 的场景下没这个会让整个 client 死锁。 |
| 52 | + * codex 那边靠 initialize_context.timeout 兜底;我们这里硬编码 30s。 */ |
| 53 | + private static readonly CONNECT_TIMEOUT_MS = 30_000; |
| 54 | + |
| 55 | + constructor( |
| 56 | + private readonly name: string, |
| 57 | + private readonly config: any, |
| 58 | + private readonly logger?: ILogger, |
| 59 | + ) {} |
| 60 | + |
| 61 | + /** 暴露给上层操作的统一入口:保证 state=ready 后取出 client + 当前版本 */ |
| 62 | + private async ensureReady(): Promise<{ client: MultiServerMCPClient; version: number }> { |
| 63 | + if (this.state.kind === 'closed') { |
| 64 | + throw new Error(`MCP client "${this.name}" is closed`); |
| 65 | + } |
| 66 | + if (this.state.kind === 'ready') { |
| 67 | + return { client: this.state.client, version: this.state.version }; |
| 68 | + } |
| 69 | + if (this.state.kind === 'connecting') { |
| 70 | + await this.state.promise.catch(() => {}); |
| 71 | + return this.ensureReady(); |
| 72 | + } |
| 73 | + // idle: 启动初次连接 |
| 74 | + const promise = this.connect(); |
| 75 | + this.state = { kind: 'connecting', promise }; |
| 76 | + try { |
| 77 | + const { client, tools } = await promise; |
| 78 | + const cur = this.state as State; |
| 79 | + if (cur.kind === 'closed') { |
| 80 | + client.close().catch(() => {}); |
| 81 | + throw new Error(`MCP client "${this.name}" closed during connect`); |
| 82 | + } |
| 83 | + this.state = { kind: 'ready', client, tools, version: ++this.versionCounter }; |
| 84 | + } catch (err) { |
| 85 | + if (this.state.kind === 'connecting' && this.state.promise === promise) { |
| 86 | + this.state = { kind: 'idle' }; |
| 87 | + } |
| 88 | + throw err; |
| 89 | + } |
| 90 | + return this.ensureReady(); |
| 91 | + } |
| 92 | + |
| 93 | + private async connect(): Promise<ConnectResult> { |
| 94 | + const client = new MultiServerMCPClient({ mcpServers: { [this.name]: this.config } }); |
| 95 | + let timer: ReturnType<typeof setTimeout> | undefined; |
| 96 | + const timeout = new Promise<never>((_, rej) => { |
| 97 | + timer = setTimeout( |
| 98 | + () => rej(new Error(`MCP "${this.name}" connect timed out after ${RecoverableMcpClient.CONNECT_TIMEOUT_MS}ms`)), |
| 99 | + RecoverableMcpClient.CONNECT_TIMEOUT_MS, |
| 100 | + ); |
| 101 | + }); |
| 102 | + try { |
| 103 | + const tools = await Promise.race([client.getTools(), timeout]); |
| 104 | + return { client, tools: [...tools] }; |
| 105 | + } catch (err) { |
| 106 | + // 超时 / 连接失败:尽力关掉新建的 client,避免泄漏 socket / FD |
| 107 | + client.close().catch(() => {}); |
| 108 | + throw err; |
| 109 | + } finally { |
| 110 | + if (timer) clearTimeout(timer); |
| 111 | + } |
| 112 | + } |
| 113 | + |
| 114 | + /** 工具列表(每个 tool.invoke 自带 stale-recovery) */ |
| 115 | + async getTools(): Promise<StructuredToolInterface[]> { |
| 116 | + const { client: _c } = await this.ensureReady(); |
| 117 | + // ensureReady 之后 state 一定是 ready |
| 118 | + const tools = (this.state as Extract<State, { kind: 'ready' }>).tools; |
| 119 | + return tools.map(t => this.wrapTool(t)); |
| 120 | + } |
| 121 | + |
| 122 | + /** 用包过 stale-recovery 的方式跑一个操作;命中 stale 错误自动重连并重试一次 */ |
| 123 | + async runOperation<T>(op: (client: MultiServerMCPClient) => Promise<T>): Promise<T> { |
| 124 | + const { client, version } = await this.ensureReady(); |
| 125 | + try { |
| 126 | + return await op(client); |
| 127 | + } catch (err) { |
| 128 | + if (!isStaleMcpConnectionError(err)) throw err; |
| 129 | + this.logger?.warn(`MCP "${this.name}" stale connection (${(err as any)?.message ?? err}); reinitializing`); |
| 130 | + await this.recover(version); |
| 131 | + const after = await this.ensureReady(); |
| 132 | + return await op(after.client); |
| 133 | + } |
| 134 | + } |
| 135 | + |
| 136 | + /** |
| 137 | + * 重连:失效旧 client 并建一个新的。 |
| 138 | + * |
| 139 | + * 并发安全: |
| 140 | + * - 用 recoveryQueue 串行化所有 recover 调用 |
| 141 | + * - 持有 staleVersion;如果当前 ready 的 version 已经变了,说明别的并发 |
| 142 | + * caller 已经完成 recovery,直接返回("惊群"只实际跑一次) |
| 143 | + */ |
| 144 | + private async recover(staleVersion: number): Promise<void> { |
| 145 | + const previous = this.recoveryQueue; |
| 146 | + let release: () => void = () => {}; |
| 147 | + this.recoveryQueue = new Promise<void>(r => { release = r; }); |
| 148 | + try { |
| 149 | + await previous; |
| 150 | + } catch {} |
| 151 | + |
| 152 | + try { |
| 153 | + if (this.state.kind === 'closed') { |
| 154 | + throw new Error(`MCP client "${this.name}" is closed`); |
| 155 | + } |
| 156 | + if (this.state.kind === 'ready' && this.state.version !== staleVersion) { |
| 157 | + // 别的 caller 已经恢复完了,本次无需再做 |
| 158 | + return; |
| 159 | + } |
| 160 | + if (this.state.kind !== 'ready') { |
| 161 | + // idle / connecting:让 ensureReady 自己处理初次连接 |
| 162 | + return; |
| 163 | + } |
| 164 | + |
| 165 | + const oldClient = this.state.client; |
| 166 | + const { client, tools } = await this.connect(); |
| 167 | + // 异步 connect 期间外部可能调过 close();如果 state 已经是 closed, |
| 168 | + // 不要把它覆盖回 ready,并把新 client 关掉避免泄漏。 |
| 169 | + if ((this.state as State).kind === 'closed') { |
| 170 | + client.close().catch(() => {}); |
| 171 | + return; |
| 172 | + } |
| 173 | + // 原子 swap:JS 单线程下赋值即原子 |
| 174 | + this.state = { kind: 'ready', client, tools, version: ++this.versionCounter }; |
| 175 | + // 异步关掉旧 client(不阻塞、不抛错) |
| 176 | + oldClient.close().catch(() => {}); |
| 177 | + } finally { |
| 178 | + release(); |
| 179 | + } |
| 180 | + } |
| 181 | + |
| 182 | + private wrapTool(rawTool: StructuredToolInterface): StructuredToolInterface { |
| 183 | + return new Proxy(rawTool, { |
| 184 | + get: (target, prop, receiver) => { |
| 185 | + if (prop !== 'invoke') return Reflect.get(target, prop, receiver); |
| 186 | + return (input: any, config?: any) => this.invokeTool(target.name, input, config); |
| 187 | + }, |
| 188 | + }); |
| 189 | + } |
| 190 | + |
| 191 | + private async invokeTool(toolName: string, input: any, config: any): Promise<any> { |
| 192 | + return this.runOperation(async () => { |
| 193 | + // 此时 state 必然是 ready(runOperation 已经 ensureReady) |
| 194 | + const ready = this.state as Extract<State, { kind: 'ready' }>; |
| 195 | + const tool = ready.tools.find(t => t.name === toolName); |
| 196 | + if (!tool) throw new Error(`MCP tool "${toolName}" not found in "${this.name}"`); |
| 197 | + return await tool.invoke(input, config); |
| 198 | + }); |
| 199 | + } |
| 200 | + |
| 201 | + async close(): Promise<void> { |
| 202 | + const old = this.state; |
| 203 | + this.state = { kind: 'closed' }; |
| 204 | + if (old.kind === 'ready') { |
| 205 | + await old.client.close().catch(() => {}); |
| 206 | + } else if (old.kind === 'connecting') { |
| 207 | + try { |
| 208 | + const { client } = await old.promise; |
| 209 | + await client.close().catch(() => {}); |
| 210 | + } catch {} |
| 211 | + } |
| 212 | + } |
| 213 | +} |
0 commit comments