UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

170 lines (169 loc) • 5.53 kB
import { n as materializeErrorStack } from "./error-graph-internal-DdjdM90N.mjs"; import { a as finalizeCapturedOutput, i as createCapturedOutputBuffers, n as appendCapturedOutput } from "./exec-output-BYE24ROR.mjs"; import { n as monotonicNow } from "./monotonic-time-Cc4T2fkU.mjs"; import { n as McpStdioFrameDecoder, r as McpStdioFrameError, t as OpenClawStdioClientTransport } from "./mcp-stdio-transport-aswOgYcH.mjs"; import { ResultSchema } from "@modelcontextprotocol/core"; import { Protocol, ProtocolError } from "@modelcontextprotocol/client"; //#region src/agents/mcp-stdio-client.ts const MAX_STDERR_BYTES = 32768; /** * A strict client for a caller-owned stdio MCP proxy process fronting a stateful driver. * Any connection anomaly retires the whole connection; the caller supplies the error taxonomy. */ function createMcpStdioClient(e) { const { errors: t, startupTimeoutMs: n } = e; let r = false; let i = false; let a; let o; let s; let c = 0; const l = createCapturedOutputBuffers(); class StdioProtocol extends Protocol { buildContext(e) { return e; } async connect(o, s) { const c = s?.signal; const onAbort = () => fail(t.unavailable(`initialize timed out after ${n}ms`)); c?.addEventListener("abort", onAbort, { once: true }); try { await super.connect(o); if ((await request("initialize", { protocolVersion: e.protocolVersion, capabilities: {}, clientInfo: e.clientInfo }, { timeoutMs: n })).protocolVersion !== e.protocolVersion) throw t.protocol("proxy returned an incompatible protocol version"); await this.notification({ method: "notifications/initialized", params: {} }); r = !i && !a; } finally { c?.removeEventListener("abort", onAbort); } } assertCapabilityForMethod() {} assertNotificationCapability() {} assertRequestHandlerCapability(e) { if (e !== "ping") throw new Error(`MCP stdio request handler is not supported: ${e}`); } } class StdioTransport extends OpenClawStdioClientTransport { constructor(...e) { super(...e); this.onerror = (e) => fail(e instanceof McpStdioFrameError ? t.protocol(e.message, e.cause) : t.unavailable("proxy failed to start", e)); this.onexit = ({ code: e, signal: n }) => { if (!i && !a) { const r = finalizeCapturedOutput(l, "tail", true).toString("utf8").trim(); fail(t.unavailable(`proxy exited (${n ?? e ?? "unknown"})${r ? `: ${r}` : ""}`)); } }; } async send(e) { if ("method" in e && e.method === "notifications/cancelled") return; try { await super.send(e); } catch (e) { fail(t.unavailable("proxy write failed", e)); throw e; } } } const u = new StdioTransport({ command: e.command, args: e.args, env: e.env, exactEnv: true, decoder: new McpStdioFrameDecoder(e.maxFrameBytes) }); const d = new StdioProtocol({ supportedProtocolVersions: [e.protocolVersion] }); const onStderr = (e) => { appendCapturedOutput(l, e, MAX_STDERR_BYTES, "tail"); }; u.stderr.on("data", onStderr); const f = monotonicNow() + n; const p = import("./mcp-client-lifecycle-CUf1EX4b.mjs").then(({ connectMcpClient: e }) => { if (i || a) throw a ?? t.unavailable("proxy is stopping"); const r = f - monotonicNow(); if (r <= 0) throw t.unavailable(`initialize timed out after ${n}ms`); return e({ client: d, transport: u, timeoutMs: Math.max(1, Math.floor(r)) }); }).catch((e) => { fail(e instanceof Error ? e : t.unavailable("proxy failed to start", e)); throw a ?? e; }); p.catch(() => {}); function beginShutdown() { o ??= import("./mcp-client-lifecycle-CUf1EX4b.mjs").then(({ disposeMcpClient: e }) => e({ client: d, transport: u, transportType: "stdio", detachStderr: () => u.stderr.off("data", onStderr), onCleanupError: (e) => { materializeErrorStack(e); s = e; } })).then((e) => { if (e !== "closed") throw t.unavailable("proxy cleanup could not be confirmed", s); }); o.catch(materializeErrorStack); } function fail(e) { if (a || i) return; materializeErrorStack(e); a = e; u.terminate().catch(() => void 0); beginShutdown(); } async function request(n, r, { timeoutMs: o, signal: s }) { if (a) throw a; if (i) throw t.unavailable("proxy is stopping"); if (s?.aborted) throw t.unavailable("request was cancelled", s.reason); if (c >= e.maxPendingRequests) throw t.unavailable("proxy has too many pending requests"); c += 1; const onAbort = () => fail(t.unavailable("request was cancelled", s?.reason)); s?.addEventListener("abort", onAbort, { once: true }); try { return await d.request({ method: n, params: r }, ResultSchema, { timeout: o, maxTotalTimeout: o }); } catch (e) { const { isMcpRequestTimeoutError: r } = await import("./mcp-error-CDWGRpmN.mjs"); if (r(e)) fail(t.unavailable(`${n} timed out after ${o}ms`)); if (!a && e instanceof ProtocolError) throw t.protocol(`request failed: MCP error ${e.code}: ${e.message}`, e); throw a ?? e; } finally { c -= 1; s?.removeEventListener("abort", onAbort); } } return { isAvailable: () => r && !a && !i, get cleanupResult() { return u.cleanupResult; }, async request(e, t, n) { await p; return request(e, t, n); }, async stop() { i = true; a ??= t.unavailable("proxy is stopping"); materializeErrorStack(a); u.retire().catch(() => void 0); beginShutdown(); await p.catch(() => void 0); await o; } }; } //#endregion export { createMcpStdioClient };