UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

322 lines (321 loc) • 9.99 kB
import { n as materializeErrorStack } from "./error-graph-internal-DdjdM90N.mjs"; import { SSEClientTransport, STDIO_DEFAULT_MAX_BUFFER_SIZE, SdkErrorCode, SdkHttpError, SseError, StreamableHTTPClientTransport } from "@modelcontextprotocol/client"; //#region src/agents/mcp-http-transport.ts const STREAM_RETRY_EXHAUSTED_RE = /^Maximum reconnection attempts \(\d+\) exceeded\.$/; const SESSION_TERMINATION_TIMEOUT_MS = 5e3; var McpSseSessionExpiredError = class extends Error {}; var McpHttpResponseTooLargeError = class extends Error { constructor(e) { super(`MCP ${e} exceeds ${STDIO_DEFAULT_MAX_BUFFER_SIZE} bytes`); this.code = "MCP_HTTP_RESPONSE_TOO_LARGE"; this.name = "McpHttpResponseTooLargeError"; } }; function isMcpSseEventTooLargeError(e) { return e.message.includes(`MCP SSE event exceeds ${STDIO_DEFAULT_MAX_BUFFER_SIZE} bytes`); } function isEventStreamResponse(e) { return e.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase() === "text/event-stream"; } function limitMcpResponseStream(e, t, n) { let r = 0; let i = 0; let a = 0; let o = false; let s = false; const checkEventLimit = () => { if (i + a > STDIO_DEFAULT_MAX_BUFFER_SIZE) throw new McpHttpResponseTooLargeError("SSE event"); }; const finishEventLine = () => { if (a === 0) i = 0; else if (!o) i += a + 1; a = 0; o = false; checkEventLimit(); }; const c = e.getReader(); return new ReadableStream({ async pull(e) { let i; try { i = await c.read(); } catch (t) { e.error(t); return; } const { done: l, value: u } = i; if (l) { e.close(); return; } try { if (!t) { r += u.byteLength; if (r > STDIO_DEFAULT_MAX_BUFFER_SIZE) throw new McpHttpResponseTooLargeError("HTTP response"); e.enqueue(u); return; } const i = Buffer.from(u.buffer, u.byteOffset, u.byteLength); let c = s && i[0] === 10 ? 1 : 0; if (i.length > 0) s = false; let l = i.indexOf(10, c); let d = i.indexOf(13, c); while (c < i.length) { const e = l < 0 ? d : d < 0 ? l : Math.min(l, d); const t = e < 0 ? i.length : e; if (t > c) { if (a === 0) o = i[c] === 58; a += t - c; s = false; checkEventLimit(); } n?.(i.subarray(c, t), e >= 0); if (e < 0) break; finishEventLine(); s = i[e] === 13; c = e + 1; if (s && i[c] === 10) { c += 1; s = false; } if (l >= 0 && l < c) l = i.indexOf(10, c); if (d >= 0 && d < c) d = i.indexOf(13, c); } e.enqueue(u); } catch (t) { c.cancel(t).catch(() => void 0); e.error(t); } }, async cancel(e) { await c.cancel(e).catch(() => void 0); } }); } function limitMcpHttpResponse(e) { if (!e.body) return e; return new Response(limitMcpResponseStream(e.body, isEventStreamResponse(e)), { status: e.status, statusText: e.statusText, headers: e.headers }); } function withMcpHttpResponseLimits(e) { return async (t, n) => limitMcpHttpResponse(await e(t, n)); } function toEventSourceByteStream(e) { if (e instanceof ReadableStream) return e; const t = e.getReader(); return new ReadableStream({ async pull(e) { const n = await t.read(); if (n.done) { e.close(); return; } if (!(n.value instanceof Uint8Array)) { await t.cancel(); throw new TypeError("MCP SSE response body must contain byte chunks"); } e.enqueue(new Uint8Array(n.value)); }, async cancel() { await t.cancel(); } }); } function limitMcpEventSourceResponse(e, t) { if (!e.body && e instanceof Response) return e; const n = e instanceof Response ? e.headers : new Headers(); if (!(e instanceof Response)) for (const t of ["content-type", "www-authenticate"]) { const r = e.headers.get(t); if (r) n.set(t, r); } const r = e.status === 200 && n.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase() === "text/event-stream" ? createSseEndpointObserver(t) : void 0; const i = e.body ? limitMcpResponseStream(toEventSourceByteStream(e.body), true, r) : null; const a = new Response(i, { status: e.status, ...e instanceof Response ? { statusText: e.statusText } : {}, headers: n }); Object.defineProperties(a, { url: { value: e.url }, redirected: { value: e.redirected } }); return a; } function createSseEndpointObserver(e) { const t = new TextDecoder(); const n = []; let r = ""; const i = []; return (a, o) => { const s = t.decode(a, { stream: true }); if (!o) { n.push(s); return; } const c = n.length > 0 ? n.join("") + s : s; n.length = 0; if (c === "") { if (r === "endpoint" && i.length > 0) e(i.join("\n")); r = ""; i.length = 0; return; } const l = c.indexOf(":"); const u = l < 0 ? c : c.slice(0, l); const d = l < 0 ? "" : c.slice(l + (c[l + 1] === " " ? 2 : 1)); if (u === "event") r = d; else if (u === "data") i.push(d); }; } var OpenClawMcpHttpTransport = class { constructor() { this.closed = false; this.closeEmitted = false; } emitClose() { if (this.closeEmitted) return; this.closeEmitted = true; this.onclose?.(); } emitError(e) { if (!this.closed) this.onerror?.(e); } async start() { this.transport.onmessage = (e) => this.onmessage?.(e); this.transport.onclose = () => this.emitClose(); this.transport.onerror = (e) => this.onTransportError(e); await this.transport.start(); } async close() { if (this.closed) return; this.closed = true; await this.transport.close(); this.emitClose(); } setProtocolVersion(e) { this.transport.setProtocolVersion(e); } }; /** Converts legacy SSE terminal HTTP failures into the lifecycle close the SDK omits. */ var OpenClawSSEClientTransport = class extends OpenClawMcpHttpTransport { constructor(e, t) { super(); const n = t?.fetch ?? fetch; const r = withMcpHttpResponseLimits(n); const i = t?.eventSourceInit; const a = i?.fetch; this.transport = new SSEClientTransport(e, { ...t, fetch: async (e, t) => { const n = await r(e, t); if (t?.method === "POST" && n.status === 404) { const e = await n.text().catch(() => null); throw new McpSseSessionExpiredError(`Error POSTing to endpoint (HTTP 404): ${e}`); } return n; }, eventSourceInit: { ...i, fetch: async (t, r) => { return limitMcpEventSourceResponse(a ? await a(t, r) : await n(t, r), (t) => this.handleAnnouncedEndpoint(t, e)); } } }); } handleAnnouncedEndpoint(e, t) { let n; try { n = new URL(e, t).href; } catch { return; } if (this.announcedEndpoint === void 0) { this.announcedEndpoint = n; return; } if (n === this.announcedEndpoint || this.sessionReplacedError) return; this.sessionReplacedError = new McpSseSessionExpiredError(`MCP SSE server reconnected onto a replacement session endpoint: ${n}`); materializeErrorStack(this.sessionReplacedError); this.emitError(this.sessionReplacedError); this.close(); setTimeout(() => void this.transport.close(), 0).unref(); } onTransportError(e) { this.emitError(e); if (isMcpSseEventTooLargeError(e) || e instanceof SseError && e.code !== void 0) { this.close(); setTimeout(() => void this.transport.close(), 0).unref(); } } async send(e) { if (this.sessionReplacedError) throw this.sessionReplacedError; if (this.closed) throw new Error("MCP SSE transport is closed"); await this.transport.send(e); } }; /** Owns Streamable HTTP notification recovery and stateful cleanup. */ var OpenClawStreamableHTTPClientTransport = class extends OpenClawMcpHttpTransport { constructor(e, t = {}) { super(); this.pendingExpiredNotificationGet = false; this.url = e; this.cleanupFetch = t.fetch ?? fetch; this.requestInit = t.requestInit; const runtimeFetch = async (e, t) => { if (this.closed) throw new Error("MCP Streamable HTTP transport is closed"); const n = limitMcpHttpResponse(await this.cleanupFetch(e, t)); if (t?.method === "GET" && !n.ok) n.body?.cancel().catch(() => void 0); if (t?.method === "POST" && !n.ok && this.transport.sessionId === void 0) this.failedStartupSessionId = n.headers.get("mcp-session-id") || this.failedStartupSessionId; if (t?.method === "GET" && n.status === 404 && this.sessionId !== void 0) this.pendingExpiredNotificationGet = true; return n; }; this.transport = new StreamableHTTPClientTransport(e, { ...t, fetch: runtimeFetch }); } get sessionId() { return this.transport.sessionId ?? this.failedStartupSessionId; } get protocolVersion() { return this.transport.protocolVersion; } onTransportError(e) { if (this.closed) { setTimeout(() => void this.transport.close(), 0).unref(); return; } this.emitError(e); const t = this.pendingExpiredNotificationGet && e instanceof SdkHttpError && e.status === 404; if (t) this.pendingExpiredNotificationGet = false; if (isMcpSseEventTooLargeError(e) || t || STREAM_RETRY_EXHAUSTED_RE.test(e.message)) this.close(); } async send(e, t) { await this.transport.send(e, t); } /** Uses a fresh request signal because failed initialization makes the SDK's signal unusable. */ async terminateSession() { const e = this.sessionId; if (!e || e === this.terminatedSessionId) return; const t = new Headers(this.requestInit?.headers); t.set("mcp-session-id", e); if (this.protocolVersion) t.set("mcp-protocol-version", this.protocolVersion); const n = await this.cleanupFetch(this.url, { ...this.requestInit, method: "DELETE", headers: t, signal: AbortSignal.timeout(SESSION_TERMINATION_TIMEOUT_MS) }); n.body?.cancel().catch(() => void 0); if (!n.ok && n.status !== 404 && n.status !== 405) throw new SdkHttpError(SdkErrorCode.ClientHttpFailedToTerminateSession, `Failed to terminate session: ${n.statusText}`, { status: n.status, statusText: n.statusText }); this.terminatedSessionId = e; } }; //#endregion export { OpenClawSSEClientTransport as n, OpenClawStreamableHTTPClientTransport as r, McpSseSessionExpiredError as t };