UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

971 lines (970 loc) • 30.1 kB
import { l as isRecord } from "../record-coerce-CVPuDqcc.mjs"; import { t as stableStringify } from "../stable-stringify-vqde_3tT.mjs"; import { o as racePromiseWithAbortSignal } from "../src-BPmQBLJp.mjs"; import "../abort-signal-D4Q6SEw7.mjs"; import { t as createLazyImportLoader } from "../lazy-promise-DiCvjz9w.mjs"; import { n as recordModelFallbackStop } from "../model-fallback-stop-BN_k3Te_.mjs"; import { n as monotonicNow, t as monotonicDeadlineAfter } from "../monotonic-time-Cc4T2fkU.mjs"; import { i as logWarn } from "../logger-CIwfuhOU.mjs"; import { i as withGuardedFetchRequestAuthority } from "../fetch-request-authority-nK0cxa_-.mjs"; import { i as withSessionMcpCallerAuthority, n as runWithSessionMcpRequestSignal, t as getSessionMcpRequestSignal } from "../agent-bundle-mcp-request-context-B-LzHCC-.mjs"; import { i as nativeMcpRuntimeBindings, n as createCombinedSessionMcpRuntime, r as acquireNativeMcpServer, t as sessionMcpRuntimeOwners } from "../agent-bundle-mcp-runtime-owner-COu6tF9k.mjs"; import { n as recordAgentCleanupFailure } from "../run-cleanup-timeout-Bk3vN1Oh.mjs"; import { l as hashMcpResolvedConnections, s as applyMcpConnectionOverride, u as partitionMcpServersByConnectionScope } from "../bundle-mcp-config-Ca9TXxki.mjs"; import { t as loadSessionMcpConfig } from "../agent-bundle-mcp-runtime-config-CBo1pSHY.mjs"; import { a as mcpListToolsResultSchema, c as toLegacyMcpListResourceTemplatesResult, d as listAllMcpTools, f as listMcpServerItems, i as mcpListResourceTemplatesResultSchema, l as toLegacyMcpListToolsResult, n as mcpCallToolResultSchema, o as toLegacyMcpCallToolResult, r as mcpGetPromptResultSchema, s as toLegacyMcpGetPromptResult, u as getCatalogListTimeoutMs } from "../mcp-sdk-compatibility-CPGbDXfB.mjs"; import { t as MCP_ELICITATION_TIMEOUT_MS } from "../mcp-client-elicitation-Cw8LWMma.mjs"; import { i as summarizeServerCapabilities, t as buildMcpClientCapabilities } from "../mcp-metadata-WjIQKgvn.mjs"; import { n as createMcpStartupBackoff, t as McpStartupBackoffError } from "../mcp-startup-backoff-cb5C4N0P.mjs"; //#region src/agents/agent-bundle-mcp-runtime-modules.ts const loadBundleMcpRuntimeModules = createLazyImportLoader(async () => { const [e, t, n, r, i, a, o, s, c] = await Promise.all([ import("@modelcontextprotocol/client"), import("../agent-bundle-mcp-catalog-projection-B2IW_OKE.mjs"), import("../mcp-client-elicitation.runtime-D8ItWa3F.mjs"), import("../mcp-client-lifecycle-CUf1EX4b.mjs"), import("../mcp-error-CDWGRpmN.mjs"), import("../mcp-json-schema-validator-Dhw5Wo8h.mjs"), import("../mcp-transport-pRhR91NQ.mjs"), import("../native-mcp-connect-CQyUAyrO.mjs"), import("../native-mcp-runtime-client-LPVRVI_4.mjs") ]); return { client: e, catalog: t, elicitation: n, lifecycle: r, errors: i, validator: a, transport: o, nativeConnect: s, nativeClient: c }; }).load; //#endregion //#region src/agents/agent-bundle-mcp-runtime-parts.ts /** Config publication selects parts; each supplied server owner retains its transports. */ function createSessionMcpRuntimeParts(e, t, n = /* @__PURE__ */ new Map()) { const r = loadSessionMcpConfig({ ...e, includeServerNames: void 0, excludeServerNames: void 0, logDiagnostics: true }); const i = loadSessionMcpConfig({ ...e, loaded: r.loaded, safeServerNamesByServer: r.safeServerNamesByServer, logDiagnostics: false }); const a = r.safeServerNamesByServer; const configForServer = (t, n = e, r = i.loaded) => { const o = n.connectionOverrides?.get(t); const s = loadSessionMcpConfig({ ...n, loaded: r, logDiagnostics: false, includeServerNames: /* @__PURE__ */ new Set([t]), excludeServerNames: void 0, safeServerNamesByServer: /* @__PURE__ */ new Map([[t, a.get(t)]]), toolOverrides: { ...n.toolOverrides, mcpToolsDeny: Object.fromEntries(Object.entries(n.toolOverrides?.mcpToolsDeny ?? {}).filter(([e]) => e === t)) } }); if (o) s.fingerprint += `:${hashMcpResolvedConnections(/* @__PURE__ */ new Map([[t, o]]))}`; return s; }; const o = /* @__PURE__ */ new Map(); for (const r of Object.keys(i.loaded.mcpServers)) { const i = configForServer(r); const s = i.fingerprint; const c = n.get(r); if (c?.configFingerprint === s && c.workspaceDir === e.workspaceDir && c.agentDir === e.agentDir) { o.set(r, c); n.delete(r); } else o.set(r, t({ ...e, serverName: r, serverConfig: i, safeServerNamesByServer: a, configFingerprint: s })); } const s = e.requesterConnect; const c = new Map(Object.keys(s?.catalog.servers ?? {}).map((t) => [t, configForServer(t, e, r.loaded).fingerprint])); let l = false; let u = Promise.resolve(); let d; const disposeParts = (e) => { u = Promise.allSettled([u, ...e.map(async (e) => { await e.dispose(); if (!e.joinCleanup) throw new Error("MCP runtime does not expose cleanup ownership"); await e.joinCleanup(); })]).then((e) => { d ??= e.find((e) => e.status === "rejected"); }); return u; }; const f = createCombinedSessionMcpRuntime({ ...e, parts: [...o.values()], serverOwners: new Map(o) }); f.configFingerprint = e.configFingerprint ?? i.fingerprint; f.requesterScope = e.requesterScope; f.requesterConnect = s && { ...s, get catalog() { const e = s.catalog; return { ...e, servers: Object.fromEntries(Object.entries(e.servers).filter(([e]) => c.has(e))), tools: e.tools.filter((e) => c.has(e.serverName)) }; }, createExecute(t) { const n = s.createExecute(t); return n && (async (...r) => { if (!c.has(t)) throw new Error(`bundle-mcp runtime disposed for session ${e.sessionId}`); return await n(...r); }); } }; f.mcpAppsEnabled = e.cfg?.mcp?.apps?.enabled === true; const p = f.joinCleanup; f.joinCleanup = async () => { await u; try { await p?.(); } catch (e) { d ??= { status: "rejected", reason: e }; } if (d) { recordAgentCleanupFailure(); throw d.reason; } }; f.dispose = async () => { c.clear(); l = true; const e = [...o.values()]; o.clear(); sessionMcpRuntimeOwners.delete(f); await disposeParts(e); if (d) recordAgentCleanupFailure(); }; sessionMcpRuntimeOwners.set(f, { hasServers: () => o.size > 0, isCurrent: () => !l, replace: (e) => createSessionMcpRuntimeParts(e, t, o), async retireUnusedServers(e) { if (l) return; const t = []; for (const [n, r] of o) if (!e.has(n) && (r.activeLeases ?? 0) === 0) { o.delete(n); t.push(r); } if (t.length === 0) return; l = true; await disposeParts(t); if (d) recordAgentCleanupFailure(); }, async reload({ cfg: t, manifestRegistry: n, reloadPlugins: r }) { const i = { ...e, cfg: t, manifestRegistry: n }; const s = loadSessionMcpConfig({ ...i, includeServerNames: void 0, excludeServerNames: void 0, safeServerNamesByServer: void 0, logDiagnostics: false }); const u = s.safeServerNamesByServer; const { requesterScopedServerNames: d } = partitionMcpServersByConnectionScope(s.loaded.mcpServers); for (const [n, o] of c) if (r && !Object.hasOwn(e.cfg?.mcp?.servers ?? {}, n) || t.gateway?.publicOrigin !== e.cfg?.gateway?.publicOrigin || configForServer(n, i, s.loaded).fingerprint !== o || u.get(n) !== a.get(n)) { l = true; c.delete(n); } const f = []; for (const [t, n] of o) { n.resetStartupBackoff(); if (r && n.pluginOwned || !Object.hasOwn(s.loaded.mcpServers, t) || d.includes(t) !== Boolean(e.requesterScope) || u.get(t) !== a.get(t) || configForServer(t, i, s.loaded).fingerprint !== n.configFingerprint) { l = true; o.delete(t); f.push(n); } } await disposeParts(f); } }); return f; } //#endregion //#region src/agents/mcp-request-lifecycle.ts let clientModule; function createMcpRequestLifecycle(e) { const t = /* @__PURE__ */ new WeakSet(); return { didTimeout: (e) => e !== null && typeof e === "object" && t.has(e), run: async ({ requestTimeoutMs: n }, r, i) => { const a = i ?? getSessionMcpRequestSignal(); let o = performance.now() + n; const { SdkError: s, SdkErrorCode: c } = await (clientModule ??= import("@modelcontextprotocol/client")); a?.throwIfAborted(); const l = new AbortController(); const u = a ? AbortSignal.any([a, l.signal]) : l.signal; const d = new s(c.RequestTimeout, "Request timed out", { timeout: n }); const onTimeout = () => { t.add(d); l.abort(d); }; let f = e; let p = 0; let m = 0; let h = false; let g = setTimeout(onTimeout, Math.max(0, o - performance.now())); g.unref?.(); const armTimeout = (e) => { clearTimeout(g); g = setTimeout(onTimeout, Math.max(0, e - performance.now())); g.unref?.(); }; const holdForHumanInput = () => { if (m++ === 0) { p = performance.now(); armTimeout(o + f); } return () => { if (--m === 0 && !h && !u.aborted) { const e = Math.min(performance.now() - p, f); f -= e; o += e; armTimeout(o); } }; }; try { if (performance.now() >= o) onTimeout(); u.throwIfAborted(); const e = await r(u, holdForHumanInput); a?.throwIfAborted(); return e; } catch (e) { a?.throwIfAborted(); throw e; } finally { h = true; clearTimeout(g); } } }; } //#endregion //#region src/agents/agent-bundle-mcp-runtime.ts const BUNDLE_MCP_FAILURE_THRESHOLD = 3; const BUNDLE_MCP_FAILURE_COOLDOWN_MS = 6e4; const BUNDLE_MCP_CATALOG_FAILURE_RETRY_MS = 5e3; function projectBundleMcpCatalogFailure(e, t) { return { ...e ?? { version: 1, servers: {}, tools: [] }, generatedAt: Date.now(), diagnostics: [t] }; } function createSessionMcpRuntime(e, t = /* @__PURE__ */ new Map()) { return createSessionMcpRuntimeParts(e, createServerMcpRuntime, t); } function createServerMcpRuntime(e, t) { const { loaded: n, fingerprint: r } = e.serverConfig; const i = e.serverName; const a = e.configFingerprint ?? r; let o; const s = e.cfg?.mcp?.apps?.enabled === true; const c = Date.now(); let l = c; let u = 0; let d; const f = new AbortController(); const p = createMcpStartupBackoff({ identity: [ e.workspaceDir, e.agentDir, e.requesterScope, i, a ], signal: f.signal, recoveryRetryMs: BUNDLE_MCP_CATALOG_FAILURE_RETRY_MS, runScoped: t !== void 0 }); let m = null; let h; let g; let _; const invalidateCatalog = () => { m = null; g = void 0; }; const scheduleCatalogServerRetry = (e) => { const t = h?.servers[i]; invalidateCatalog(); if (t) { m = projectBundleMcpCatalogFailure(h, { serverName: i, safeServerName: t.safeServerName ?? i, launchSummary: t.launchSummary, message: e }); g = monotonicNow(); } }; const catalogRetryIsDue = () => g !== void 0 && monotonicNow() >= g; let v; const y = t ? stableStringify({ capabilities: t.capabilities, roots: t.roots }) : void 0; let b = 0; const x = /* @__PURE__ */ new Set(); let S = false; let C; let w = false; const T = /* @__PURE__ */ new Set(); const disposeSession = (e) => { if (e.disposePromise) return e.disposePromise; const t = loadBundleMcpRuntimeModules().then(({ lifecycle: t }) => t.disposeMcpClient(e)).then((e) => { if (e === "uncertain") { w = true; recordAgentCleanupFailure(); } }).catch((e) => { w = true; recordAgentCleanupFailure(); throw e; }).finally(() => T.delete(t)); e.disposePromise = t; T.add(t); return t; }; let E; const recordServerToolFailure = (e, t) => { if (v !== e || e.retiring) return; const n = E; const r = (n?.session === e ? n.failures : 0) + 1; const i = { session: e, failures: r }; if (r >= BUNDLE_MCP_FAILURE_THRESHOLD) i.retryAfterMs = t + BUNDLE_MCP_FAILURE_COOLDOWN_MS; E = i; return r; }; const failIfDisposed = () => { if (d) throw new Error(`bundle-mcp runtime disposed for session ${e.sessionId}`); }; const requireConnectedSession = () => { const e = v; if (!e || !e.connected || !e.toolMetadata) throw new Error(e?.disconnectReason ? `bundle-mcp server "${i}" is disconnected: ${e.disconnectReason}` : `bundle-mcp server "${i}" is not connected`); return e; }; const retireSessionIfCurrent = async (e) => { if (v !== e) return false; e.retiring = true; v = void 0; e.nativeBridge?.emit({ kind: "closed" }); await disposeSession(e); return true; }; const D = createMcpRequestLifecycle(MCP_ELICITATION_TIMEOUT_MS); const runGuardedServerRequest = async (e, t, n) => { const r = getSessionMcpRequestSignal(); const a = n?.failureBackoff !== "ignore"; const o = monotonicNow(); const s = E; if (a && s?.session === e && s.retryAfterMs && o < s.retryAfterMs) throw new Error(`bundle-mcp server "${i}" is paused after repeated tool failures; retry after ${new Date(Date.now() - o + s.retryAfterMs).toISOString()}`); if (s && s.session !== e) E = void 0; try { const n = await t(); if (a && E?.session === e) E = void 0; return n; } catch (t) { const { lifecycle: { isMcpHttpSessionExpired: n }, errors: { redactMcpDiagnosticError: o } } = await loadBundleMcpRuntimeModules(); if (v !== e || e.retiring) throw t; const s = n(e, t); let c; if (s && !r?.aborted) c = "expired HTTP session"; else if (a && !r?.aborted) { const n = recordServerToolFailure(e, monotonicNow()); if (D.didTimeout(t) && n && n >= BUNDLE_MCP_FAILURE_THRESHOLD) c = "repeated request timeouts"; } if (c) { S ||= s; E = void 0; scheduleCatalogServerRetry(c); logWarn(`bundle-mcp: recycling server "${i}" after ${c}`); retireSessionIfCurrent(e).catch((e) => { logWarn(`bundle-mcp: failed to retire server "${i}" after ${c}: ${o(e)}`); }); } throw t; } }; const runGuardedMcpRequest = (e, t, n) => runGuardedServerRequest(e, () => D.run(e, withSessionMcpCallerAuthority(t)), n); const collectServerItems = (e, t) => listMcpServerItems(t, { client: e.client, timeoutMs: e.requestTimeoutMs, signal: f.signal, callerSignal: getSessionMcpRequestSignal(), runRequest: (t, n) => D.run(e, withSessionMcpCallerAuthority(t), n) }); const loadCatalog = async (r) => { failIfDisposed(); if (_) return _; const a = (async () => { const { client: { Client: a }, catalog: { projectBundleMcpServerCatalog: c }, elicitation: { bindMcpClientElicitation: l }, lifecycle: { ensureMcpSessionConnected: u, isMcpHttpSessionExpired: m }, errors: { isMcpMethodNotFoundError: g, redactMcpDiagnosticError: _ }, validator: { createMcpJsonSchemaValidator: y }, transport: { resolveMcpTransport: b }, nativeConnect: { observeNativeMcpProbe: x }, nativeClient: { createNativeMcpClientBridge: C } } = await loadBundleMcpRuntimeModules(); failIfDisposed(); const T = n.mcpServers[i]; const E = e.connectionOverrides?.get(i); const k = E ? applyMcpConnectionOverride(T, E) : T; const resolveTransport = () => b(i, k, { cfg: e.cfg, agentDir: e.agentDir, prepareDataDir: n.prepareDataDirsByServer?.[i]?.dataDir, requesterScope: e.requesterScope }); const A = resolveTransport(); if (!A) return { version: 1, generatedAt: Date.now(), servers: {}, tools: [] }; const j = e.safeServerNamesByServer?.get(i) ?? i; const M = E ? `${i}: requester-scoped connection` : A.description; failIfDisposed(); let N = v; if (N && !N.connected && !N.connectPromise) { await retireSessionIfCurrent(N); N = void 0; } const P = Boolean(N); const F = y(); const createSession = (e, n = false) => { const r = new a({ name: "openclaw-bundle-mcp", version: "0.0.0" }, { capabilities: t?.capabilities ?? buildMcpClientCapabilities(s), versionNegotiation: { mode: t && !n ? "auto" : "legacy" }, ...t ? { inputRequired: { autoFulfill: false } } : {}, jsonSchemaValidator: F, ...t ? {} : { listChanged: { tools: { autoRefresh: false, debounceMs: 0, onChanged: (e) => { if (e) logWarn(`bundle-mcp: failed to refresh changed tool list for server "${i}": ${_(e)}`); invalidateCatalog(); } } } } }); const o = { serverName: i, client: r, ...s && !t ? { withElicitation: l(r) } : {}, transport: e.transport, transportType: e.transportType, requestTimeoutMs: e.requestTimeoutMs, connected: false, retiring: false, detachStderr: e.detachStderr }; if (t) o.nativeBridge = C({ client: r, transport: e.transport, transportType: e.transportType, context: t, signal: f.signal, invalidateCatalog, validatorForCall: (e) => o.toolMetadata?.validatorForCall(e), retire: async () => { if (v === o) { invalidateCatalog(); await retireSessionIfCurrent(o); } }, acquireLease: () => { O.markUsed(); return O.acquireLease(); }, runRequest: (e, t) => runWithSessionMcpRequestSignal(e, () => runGuardedServerRequest(o, () => D.run(o, (e, n) => t({ signal: e, timeout: o.requestTimeoutMs + MCP_ELICITATION_TIMEOUT_MS }, n), e))) }); r.onclose = () => { const e = o.connected; o.connected = false; o.disconnectReason = "mcp transport closed"; if (e) o.nativeBridge?.emit({ kind: "closed" }); if (e && !d && !o.retiring && v === o) { S ||= o.transportType === "sse"; scheduleCatalogServerRetry("mcp transport closed"); logWarn(`bundle-mcp: server "${i}" closed; next request reconnects`); } }; return o; }; if (!N) { N = createSession(A); v = N; } try { failIfDisposed(); if (!N.connected) { const connect = async (e) => { if (!e.nativeBridge || !r) return u(e, A.connectionTimeoutMs); const t = e.nativeBridge.bind(r); try { await t.initialize(() => u(e, A.connectionTimeoutMs)); } finally { await t.detach(); } }; const e = t ? x(N.transport) : void 0; try { await p.connect(async () => { try { await connect(N); } catch (t) { if (!e?.canRestartLegacy(t)) throw t; e.detach(); await retireSessionIfCurrent(N); if (w) throw new Error("MCP probe cleanup could not confirm closure", { cause: t }); failIfDisposed(); r?.assertCurrent(); f.signal.throwIfAborted(); const n = resolveTransport(); if (!n) throw new Error("MCP projection transport is unavailable", { cause: t }); N = createSession(n, true); v = N; await connect(N); } }); } finally { e?.detach(); } } if (N.nativeBridge && N.client.getProtocolEra() === "modern" && !N.nativeSubscription) { const e = N; const t = await N.nativeBridge.listenForCatalogChanges(N.requestTimeoutMs); N.nativeSubscription = t; t?.closed.then(() => { e.nativeSubscription = void 0; if (!e.retiring && !d) { invalidateCatalog(); e.nativeBridge?.emit({ kind: "invalidated" }); } }); } o = void 0; failIfDisposed(); const a = summarizeServerCapabilities(N.client.getServerCapabilities()); let s; try { const list = () => listAllMcpTools(N.client, getCatalogListTimeoutMs(T, A.requestTimeoutMs), f.signal); if (N.nativeBridge && r) { const e = N.nativeBridge.bind(r); try { s = await e.initialize(list); } finally { await e.detach(); } } else s = await list(); } catch (e) { if (!a.tools && (a.resources || a.prompts) && g(e)) s = []; else throw e; } failIfDisposed(); const l = c({ serverName: i, safeServerName: j, launchDescription: M, rawServer: T, listedTools: s, schemaValidator: F, denialMap: e.toolOverrides?.mcpToolsDeny, capabilities: a, serverVersion: N.client.getServerVersion(), serverCapabilities: N.client.getServerCapabilities(), instructions: N.client.getInstructions()?.trim() || void 0, pluginId: n.pluginIdsByServer?.[i], connection: A }); N.toolMetadata = l.metadata; return l.catalog; } catch (e) { const t = _(e); if (e instanceof McpStartupBackoffError && e.authorizationRequired) h = void 0; o = e instanceof McpStartupBackoffError ? e.retryAfterMs : void 0; if (!d && (!(e instanceof McpStartupBackoffError) || e.reportFailure)) logWarn(`bundle-mcp: failed to ${P ? "refresh" : "start"} server "${i}" (${M}): ${t}`); if (!N.connected || m(N, e) || !P) await retireSessionIfCurrent(N); failIfDisposed(); return projectBundleMcpCatalogFailure(h, { serverName: i, safeServerName: j, launchSummary: M, message: t }); } })(); _ = a; try { const e = await a; failIfDisposed(); m = e; if (!e.diagnostics?.length) { h = e; S = false; } g = e.diagnostics?.length ? o ?? monotonicDeadlineAfter(BUNDLE_MCP_CATALOG_FAILURE_RETRY_MS) : void 0; return e; } finally { _ = void 0; } }; const getCatalog = async (t) => { failIfDisposed(); if (o === Infinity && !p.get()) { o = void 0; invalidateCatalog(); } if (!m && !v?.connected) { const t = p.get(); if (t) { if (t.authorizationRequired) h = void 0; m = projectBundleMcpCatalogFailure(h, { serverName: i, safeServerName: e.safeServerNamesByServer?.get(i) ?? i, launchSummary: i, message: t.message }); o = t.retryAfterMs; g = t.retryAfterMs; } } if (m && !catalogRetryIsDue()) return m; if (!m) { const e = v?.transportType === "stdio"; const n = await loadCatalog(t); return e && n.diagnostics?.length && h && !v ? loadCatalog(t) : n; } const n = m; g = void 0; loadCatalog(t).catch(() => { if (!d && m === n && g === void 0) g = monotonicDeadlineAfter(BUNDLE_MCP_CATALOG_FAILURE_RETRY_MS); }); return n; }; const getActiveSession = async (e) => { if (e !== i) throw new Error(`bundle-mcp server "${e}" is not connected`); const t = getSessionMcpRequestSignal(); t?.throwIfAborted(); await racePromiseWithAbortSignal(getCatalog(), t); if (S && _) await racePromiseWithAbortSignal(_, t); return requireConnectedSession(); }; const O = { get nativeContextKey() { return y; }, get nativeCapabilityContext() { return t?.capabilityContext; }, get nativeViewCount() { return b; }, resetStartupBackoff() { p.reset(); if (o !== void 0 || _ && !v?.connected) { o = void 0; invalidateCatalog(); } }, pluginOwned: !Object.hasOwn(e.cfg?.mcp?.servers ?? {}, i) || e.connectionOverrides?.has(i) === true, sessionId: e.sessionId, sessionKey: e.sessionKey, workspaceDir: e.workspaceDir, agentDir: e.agentDir, configFingerprint: a, ...e.requesterScope ? { requesterScope: e.requesterScope } : {}, ...e.requesterConnect ? { requesterConnect: e.requesterConnect } : {}, isRequesterScopedServer: () => e.requesterScope !== void 0, canReadLocalFiles: (e) => e === i && v?.connected === true && v.transportType === "stdio", mcpAppsEnabled: s, createdAt: c, get lastUsedAt() { return Math.max(l, ...[...x].map((e) => e.lastUsedAt)); }, get activeLeases() { return u + [...x].reduce((e, t) => e + (t.activeLeases ?? 0), 0); }, acquireLease() { u += 1; let e = false; return () => { if (e) return; e = true; u -= 1; }; }, getCatalog, get retiredCatalog() { return d; }, /** Synchronous catalog snapshot only; must not connect transports or issue tools/list. */ peekCatalog() { return m; }, /** Session-owned timeout that survives catalog invalidation. */ getServerRequestTimeoutMs(e) { return e === i ? v?.requestTimeoutMs : void 0; }, markUsed() { l = Date.now(); }, async callTool(e, t, n, r) { const i = await getActiveSession(e); const a = i.toolMetadata?.validatorForCall(t); const o = await runGuardedMcpRequest(i, (e, a) => { r?.assertCurrent?.(); const call = () => withGuardedFetchRequestAuthority(r?.assertCurrent, () => i.client.request({ method: "tools/call", params: { name: t, arguments: isRecord(n) ? n : {}, ...r?._meta ? { _meta: r._meta } : {} } }, mcpCallToolResultSchema, { timeout: i.requestTimeoutMs + (i.withElicitation ? MCP_ELICITATION_TIMEOUT_MS : 0), signal: e })); return i.withElicitation ? i.withElicitation(e, call, a) : call(); }); a?.(o); return toLegacyMcpCallToolResult(o); }, async listTools(e, t) { const n = await getActiveSession(e); return toLegacyMcpListToolsResult(await runGuardedMcpRequest(n, (e) => n.client.request({ method: "tools/list", params: t }, mcpListToolsResultSchema, { timeout: n.requestTimeoutMs, signal: e }))); }, async listResources(e, t) { const n = await getActiveSession(e); return await runGuardedServerRequest(n, async () => collectServerItems(n, "resources"), t); }, async readResource(e, t, n) { const r = await getActiveSession(e); return await runGuardedMcpRequest(r, (e) => r.client.request({ method: "resources/read", params: { uri: t, ...n?._meta ? { _meta: n._meta } : {} } }, { timeout: r.requestTimeoutMs, signal: e }), n); }, async listResourceTemplates(e, t) { const n = await getActiveSession(e); return toLegacyMcpListResourceTemplatesResult(await runGuardedMcpRequest(n, (e) => n.client.request({ method: "resources/templates/list", params: t }, mcpListResourceTemplatesResultSchema, { timeout: n.requestTimeoutMs, signal: e }))); }, async listPrompts(e) { const t = await getActiveSession(e); return runGuardedServerRequest(t, () => collectServerItems(t, "prompts")); }, async getPrompt(e, t, n) { const r = await getActiveSession(e); return toLegacyMcpGetPromptResult(await runGuardedMcpRequest(r, (e) => r.client.request({ method: "prompts/get", params: { name: t, ...n ? { arguments: n } : {} } }, mcpGetPromptResultSchema, { timeout: r.requestTimeoutMs, signal: e }))); }, async joinCleanup() { await C; await Promise.allSettled(T); if (w) { recordAgentCleanupFailure(); const e = /* @__PURE__ */ new Error("MCP runtime cleanup could not confirm closure"); recordModelFallbackStop(e); throw e; } }, dispose() { if (!C) { d = { version: 1, generatedAt: Date.now(), servers: {}, tools: [], diagnostics: [{ serverName: i, safeServerName: e.safeServerNamesByServer?.get(i) ?? i, launchSummary: i, message: "MCP server runtime retired; retry discovery on the next turn." }] }; v?.nativeBridge?.emit({ kind: "closed" }); p.dispose(); f.abort(/* @__PURE__ */ new Error(`bundle-mcp runtime disposed for session ${e.sessionId}`)); m = null; h = void 0; g = void 0; const t = _; _ = void 0; const n = v; v = void 0; const r = [...x]; x.clear(); C = (async () => { const e = Promise.allSettled(r.map(async (e) => { await e.dispose(); await e.joinCleanup?.(); })); if (n) await disposeSession(n).catch(() => void 0); await t?.catch(() => void 0); await Promise.allSettled(T); if ((await e).some((e) => e.status === "rejected")) w = true; })(); } C.then(() => { if (w) recordAgentCleanupFailure(); }); return C; } }; nativeMcpRuntimeBindings.set(O, { hasServer: (e) => e === i, async acquire(n, r) { failIfDisposed(); r.assertCurrent(); if (n !== i) throw new Error(`MCP server "${n}" has no projection owner`); if (r.capabilities.elicitation && !r.elicit) throw new Error("MCP elicitation capability requires a handler"); if (r.capabilities.sampling && !r.createMessage) throw new Error("MCP sampling capability requires a handler"); if (r.capabilities.extensions?.["openai/elicitation"] && !r.elicitCustom) throw new Error("MCP custom elicitation capability requires a handler"); const a = stableStringify({ capabilities: r.capabilities, roots: r.roots }); if (!t || y !== a || t.capabilityContext !== r.capabilityContext) { let t = [...x].find((e) => e.nativeContextKey === a && e.nativeCapabilityContext === r.capabilityContext); if (!t) { t = createServerMcpRuntime(e, r); x.add(t); } const i = t; const cleanupUnused = async () => { if (i.nativeViewCount === 0) { l = Math.max(l, i.lastUsedAt); try { await i.dispose(); await i.joinCleanup?.(); x.delete(i); } catch (e) { w = true; recordAgentCleanupFailure(); throw e; } } }; try { const e = await acquireNativeMcpServer(i, n, r); let t; return { ...e, release() { return t ??= (async () => { try { await e.release(); } finally { await cleanupUnused(); } })(); } }; } catch (e) { await cleanupUnused(); throw e; } } b += 1; const o = O.acquireLease(); let s; try { await getCatalog(r); if (_) await _; failIfDisposed(); r.assertCurrent(); const e = requireConnectedSession(); if (!e.nativeBridge) throw new Error("MCP session has no projection binding"); const t = e.nativeBridge.bind({ ...r, assertCurrent() { failIfDisposed(); r.assertCurrent(); if (e !== v || !e.connected) throw new Error("MCP projection connection retired"); } }); return { runtime: O, ...t.protocol, release() { return s ??= (async () => { try { await t.detach(); } finally { b -= 1; } })(); } }; } catch (e) { b -= 1; throw e; } finally { o(); } } }); return O; } //#endregion export { createSessionMcpRuntime };