UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

306 lines (305 loc) • 9.24 kB
import { Jn as string, Un as record, sr as unknown } from "./schemas-Cy6abvsu.mjs"; import { i as logWarn } from "./logger-CIwfuhOU.mjs"; import { i as withGuardedFetchRequestAuthority, t as captureGuardedFetchRequestAuthority } from "./fetch-request-authority-nK0cxa_-.mjs"; import { AsyncLocalStorage } from "node:async_hooks"; import { CallToolResultSchema, GetPromptResultSchema, ReadResourceResultSchema } from "@modelcontextprotocol/core"; import { ProtocolError, ProtocolErrorCode, isInputRequiredResult, withInputRequired } from "@modelcontextprotocol/client"; //#region src/agents/native-mcp-runtime-client.ts /** Typed adaptation only. The containing session owns connection, admission and cleanup. */ function createNativeMcpClientBridge(e) { const { client: t } = e; const n = e.transport.send.bind(e.transport); e.transport.send = async (e, t) => { if ("method" in e && "id" in e) captureGuardedFetchRequestAuthority()?.(); await n(e, t); }; const r = /* @__PURE__ */ new Set(); const i = /* @__PURE__ */ new Set(); const a = /* @__PURE__ */ new Map(); let o = false; const assertOpen = () => { if (o) throw new Error("MCP connection closed; reacquire the server view"); }; const callbackOwner = () => { if (i.size !== 1) throw new ProtocolError(ProtocolErrorCode.InvalidRequest, "MCP callback has no unambiguous active requester"); const e = i.values().next().value; e.assertCurrent(); return e; }; const callback = async (e, t, n = false) => { const r = callbackOwner(); const i = AbortSignal.any([r.signal, e.mcpReq.signal]); i.throwIfAborted(); const a = n ? r.holdForHumanInput() : void 0; try { const e = await r.view.restore(t, r.view, i); r.assertCurrent(); i.throwIfAborted(); return e; } finally { a?.(); } }; if (e.context.capabilities.roots) { const n = e.context.roots; t.setRequestHandler("roots/list", (t, r) => { e.signal.throwIfAborted(); assertOpen(); r.mcpReq.signal.throwIfAborted(); return n; }); } if (e.context.capabilities.elicitation) t.setRequestHandler("elicitation/create", (e, t) => callback(t, async (t, n) => { const r = await t.context.elicit(e.params, { signal: n }); t.assertCurrent(); n.throwIfAborted(); if (e.params.mode === "url" && r.action === "accept") a.set(e.params.elicitationId, t); return r; }, true)); if (e.context.capabilities.sampling) t.setRequestHandler("sampling/createMessage", (e, t) => callback(t, (t, n) => t.context.createMessage(e.params, { signal: n }))); if (e.context.capabilities.extensions?.["openai/elicitation"]) t.setRequestHandler("openai/elicitation/create", { params: record(string(), unknown()) }, (e, t) => callback(t, (t, n) => t.context.elicitCustom(e, { signal: n }), true)); const emit = (e, t = r) => { if (e.kind === "closed") { if (o) return; o = true; a.clear(); } for (const n of t) { try { if (e.kind !== "closed") n.assertCurrent(); } catch { continue; } for (const t of n.listeners) try { n.restore(t, e); } catch { logWarn("bundle-mcp: projection listener failed"); } } }; const notification = (t) => { if (o) return; if (t.method === "notifications/elicitation/complete") { const e = a.get(t.params.elicitationId); a.delete(t.params.elicitationId); if (e) emit({ kind: "notification", notification: t }, /* @__PURE__ */ new Set([e])); } else if (t.method.endsWith("/list_changed")) { e.invalidateCatalog(); emit({ kind: "notification", notification: t }); } else if (i.size === 1) emit({ kind: "notification", notification: t }, /* @__PURE__ */ new Set([callbackOwner().view])); }; t.setNotificationHandler("notifications/tools/list_changed", notification); t.setNotificationHandler("notifications/resources/list_changed", notification); t.setNotificationHandler("notifications/prompts/list_changed", notification); t.setNotificationHandler("notifications/resources/updated", notification); t.setNotificationHandler("notifications/message", notification); t.setNotificationHandler("notifications/elicitation/complete", notification); function bind(n) { const o = new AbortController(); const s = /* @__PURE__ */ new Set(); const c = AbortSignal.any([e.signal, o.signal]); const l = { context: n, signal: c, assertCurrent() { c.throwIfAborted(); assertOpen(); n.assertCurrent(); }, restore: AsyncLocalStorage.snapshot(), listeners: /* @__PURE__ */ new Set() }; r.add(l); const run = async (n, r) => { const a = AbortSignal.any([l.signal, n.signal]); const assertCurrent = () => { l.assertCurrent(); a.throwIfAborted(); n.assertCurrent(); }; assertCurrent(); const o = e.acquireLease(); const c = Promise.withResolvers(); s.add(c.promise); try { const o = await e.runRequest(a, async (a, o) => { const assertActive = () => { assertCurrent(); a.signal.throwIfAborted(); }; assertActive(); const s = { view: l, signal: a.signal, assertCurrent: assertActive, holdForHumanInput: o }; i.add(s); let c; const onAbort = () => { if (t.getProtocolEra() === "legacy") { c ??= e.retire(); c.catch(() => void 0); } }; a.signal.addEventListener("abort", onAbort, { once: true }); try { return await l.restore(() => withGuardedFetchRequestAuthority(assertActive, () => r({ ...a, onprogress: n.onprogress ? (e) => { assertActive(); l.restore(n.onprogress, e); } : void 0 }))); } catch (e) { a.signal.throwIfAborted(); throw e; } finally { a.signal.removeEventListener("abort", onAbort); try { if (c) await c; } finally { i.delete(s); } } }); assertCurrent(); return o; } finally { o(); s.delete(c.promise); c.resolve(); } }; const flow = async (n, r, i, a, o) => { const s = await run(a, (a) => e.transportType === "stdio" ? t.request({ method: n, params: r }, withInputRequired(i), { ...a, allowInputRequired: true }) : t.request({ method: n, params: r }, i, a)); if (!isInputRequiredResult(s)) { o?.(s); return { kind: "complete", result: s }; } let c = false; return { kind: "input-required", result: s, resume(e, t) { l.assertCurrent(); a.signal.throwIfAborted(); a.assertCurrent(); t.signal.throwIfAborted(); t.assertCurrent(); if (c) throw new Error("MCP continuation was already resumed"); c = true; return flow(n, { ...r, requestState: s.requestState, inputResponses: e }, i, { ...t, signal: AbortSignal.any([a.signal, t.signal]), assertCurrent() { a.assertCurrent(); t.assertCurrent(); } }, o); } }; }; return { protocol: { getServerInfo: () => t.getServerVersion(), getCapabilities: () => t.getServerCapabilities(), getInstructions: () => t.getInstructions(), getProtocolEra: () => t.getProtocolEra(), getProtocolVersion: () => t.getNegotiatedProtocolVersion(), listTools: (e, n) => run(n, (n) => t.request({ method: "tools/list", params: e }, n)), listResources: (e, n) => run(n, (n) => t.request({ method: "resources/list", params: e }, n)), listResourceTemplates: (e, n) => run(n, (n) => t.request({ method: "resources/templates/list", params: e }, n)), listPrompts: (e, n) => run(n, (n) => t.request({ method: "prompts/list", params: e }, n)), complete: (e, n) => run(n, (n) => t.request({ method: "completion/complete", params: e }, n)), callTool: async (n, r) => { if (e.transportType === "stdio") { const t = e.validatorForCall(n.name); return flow("tools/call", n, CallToolResultSchema, r, t); } return { kind: "complete", result: await run(r, (e) => t.callTool(n, e)) }; }, readResource: (e, t) => flow("resources/read", e, ReadResourceResultSchema, t), getPrompt: (e, t) => flow("prompts/get", e, GetPromptResultSchema, t), rootsChanged: (e) => run(e, () => t.sendRootsListChanged()), subscribe(e) { l.assertCurrent(); l.listeners.add(e); return () => l.listeners.delete(e); } }, initialize: (e) => run({ signal: c, assertCurrent: l.assertCurrent }, e), async detach() { o.abort(/* @__PURE__ */ new Error("MCP projection view released")); await Promise.all(s); r.delete(l); l.listeners.clear(); for (const [e, t] of a) if (t === l) a.delete(e); } }; } return { bind, emit, async listenForCatalogChanges(n) { const r = t.getServerCapabilities(); const i = { ...r?.tools?.listChanged ? { toolsListChanged: true } : {}, ...r?.resources?.listChanged ? { resourcesListChanged: true } : {}, ...r?.prompts?.listChanged ? { promptsListChanged: true } : {} }; if (Object.keys(i).length > 0) return t.listen(i, { signal: e.signal, timeout: n }); } }; } //#endregion export { createNativeMcpClientBridge };