openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
225 lines (224 loc) • 7.83 kB
JavaScript
import { a as resolveGlobalSingleton } from "./global-singleton-D7yf05nR.mjs";
import { o as racePromiseWithAbortSignal } from "./src-BPmQBLJp.mjs";
import "./abort-signal-D4Q6SEw7.mjs";
import { t as runTasksWithConcurrency } from "./run-with-concurrency-B34GDKXE.mjs";
import { r as compareMcpCatalogTools } from "./agent-bundle-mcp-names-856aMFJA.mjs";
import { t as getSessionMcpRequestSignal } from "./agent-bundle-mcp-request-context-B-LzHCC-.mjs";
import { n as recordAgentCleanupFailure } from "./run-cleanup-timeout-Bk3vN1Oh.mjs";
//#region src/agents/native-mcp-runtime.ts
const nativeMcpRuntimeBindings = resolveGlobalSingleton(Symbol.for("openclaw.nativeMcpRuntimeBindings"), () => /* @__PURE__ */ new WeakMap());
async function acquireNativeMcpServer(e, t, n) {
n.assertCurrent();
const r = nativeMcpRuntimeBindings.get(e);
if (!r) throw new Error("MCP runtime has no projection binding");
const i = await r.acquire(t, n);
try {
n.assertCurrent();
return i;
} catch (e) {
await i.release();
throw e;
}
}
//#endregion
//#region src/agents/agent-bundle-mcp-combined.ts
async function loadCurrentCatalog(e) {
if (e.retiredCatalog) return e.retiredCatalog;
try {
const t = await e.getCatalog();
return e.retiredCatalog ?? t;
} catch (t) {
if (e.retiredCatalog) return e.retiredCatalog;
throw t;
}
}
/** Safe names are precomputed from the full declared set, so no re-suffix is needed. */
function mergeMcpToolCatalogs(e) {
const t = {};
const n = [];
const r = [];
const i = [];
const a = [];
for (const o of e) {
for (const [e, n] of Object.entries(o.servers).toSorted(([e], [t]) => e.localeCompare(t))) t[e] = n;
n.push(...o.tools);
r.push(...o.policyTools ?? [...o.tools, ...o.sessionDeniedTools ?? []]);
if (o.sessionDeniedTools) i.push(...o.sessionDeniedTools);
if (o.diagnostics) a.push(...o.diagnostics);
}
n.sort(compareMcpCatalogTools);
r.sort(compareMcpCatalogTools);
i.sort(compareMcpCatalogTools);
return {
version: 1,
generatedAt: Math.max(0, ...e.map((e) => e.generatedAt)),
servers: t,
tools: n,
...r.length > 0 ? { policyTools: r } : {},
...i.length > 0 ? { sessionDeniedTools: i } : {},
...a.length > 0 ? { diagnostics: a } : {}
};
}
function createCombinedSessionMcpRuntime(e) {
if (e.parts.length === 1 && !e.serverOwners) return e.parts[0];
const t = e.parts;
let n = 0;
let r;
let i;
let a = Math.max(Date.now(), ...t.map((e) => e.lastUsedAt));
let o = null;
let s = null;
let c;
const l = e.serverOwners ?? /* @__PURE__ */ new Map();
const u = t.find((e) => e.requesterConnect)?.requesterConnect;
const rememberServerOwners = (e, t) => {
for (const n of Object.keys(e.servers)) l.set(n, t);
};
const cachedCatalogIsCurrent = () => o !== null && s !== null && t.every((e, t) => (e.retiredCatalog ?? e.peekCatalog()) === s?.[t]);
const loadCatalog = async () => {
if (o && !o.diagnostics?.length && cachedCatalogIsCurrent()) return o;
if (c) return c;
const n = (async () => {
const { results: n, firstError: r, hasError: i } = await runTasksWithConcurrency({
tasks: t.map((e) => () => loadCurrentCatalog(e)),
limit: 6,
errorMode: "continue"
});
if (i) throw r;
const a = t.map((e, t) => e.retiredCatalog ?? e.peekCatalog() ?? n[t]);
if (o && s?.every((e, t) => e === a[t])) return o;
if (!e.serverOwners) {
l.clear();
for (let e = 0; e < t.length; e += 1) rememberServerOwners(a[e], t[e]);
}
s = a;
o = mergeMcpToolCatalogs(a);
return o;
})();
c = n;
try {
return await n;
} finally {
c = void 0;
}
};
const ownerForServer = async (e) => {
const t = getSessionMcpRequestSignal();
t?.throwIfAborted();
if (l.size === 0) await racePromiseWithAbortSignal(loadCatalog(), t);
const n = l.get(e);
if (n) return n;
throw new Error(`bundle-mcp server "${e}" is not connected`);
};
const d = {
sessionId: e.sessionId,
sessionKey: e.sessionKey,
workspaceDir: e.workspaceDir,
agentDir: e.agentDir,
configFingerprint: t.map((e) => e.configFingerprint).join(":"),
...u ? { requesterConnect: u } : {},
isRequesterScopedServer(e) {
return l.get(e)?.requesterScope !== void 0;
},
canReadLocalFiles: (e) => l.get(e)?.canReadLocalFiles?.(e) === true,
mcpAppsEnabled: t.some((e) => e.mcpAppsEnabled === true),
createdAt: Math.min(Date.now(), ...t.map((e) => e.createdAt)),
get lastUsedAt() {
return Math.max(a, ...t.map((e) => e.lastUsedAt));
},
get activeLeases() {
return Math.max(n, t.reduce((e, t) => e + (t.activeLeases ?? 0), 0));
},
acquireLease() {
n += 1;
const e = t.map((e) => e.acquireLease?.());
let r = false;
return () => {
if (r) return;
r = true;
n -= 1;
for (const t of e) t?.();
};
},
getCatalog: loadCatalog,
peekCatalog() {
if (o && cachedCatalogIsCurrent()) return o;
const e = t.map((e) => e.retiredCatalog ?? e.peekCatalog());
if (e.some((e) => e === null)) return null;
return mergeMcpToolCatalogs(e);
},
getServerRequestTimeoutMs(e) {
return l.get(e)?.getServerRequestTimeoutMs?.(e);
},
markUsed() {
a = Date.now();
for (const e of t) e.markUsed();
},
async callTool(e, t, n, r) {
return await (await ownerForServer(e)).callTool(e, t, n, r);
},
async listTools(e, t) {
const n = await ownerForServer(e);
if (!n.listTools) throw new Error(`bundle-mcp server "${e}" does not support listTools`);
return await n.listTools(e, t);
},
async listResources(e, t) {
const n = await ownerForServer(e);
if (!n.listResources) throw new Error(`bundle-mcp server "${e}" does not support listResources`);
return await n.listResources(e, t);
},
async readResource(e, t, n) {
const r = await ownerForServer(e);
if (!r.readResource) throw new Error(`bundle-mcp server "${e}" does not support readResource`);
return await r.readResource(e, t, n);
},
async listResourceTemplates(e, t) {
const n = await ownerForServer(e);
if (!n.listResourceTemplates) throw new Error(`bundle-mcp server "${e}" does not support listResourceTemplates`);
return await n.listResourceTemplates(e, t);
},
async listPrompts(e) {
const t = await ownerForServer(e);
if (!t.listPrompts) throw new Error(`bundle-mcp server "${e}" does not support listPrompts`);
return await t.listPrompts(e);
},
async getPrompt(e, t, n) {
const r = await ownerForServer(e);
if (!r.getPrompt) throw new Error(`bundle-mcp server "${e}" does not support getPrompt`);
return await r.getPrompt(e, t, n);
},
async joinCleanup() {
await r;
const e = await Promise.allSettled(t.map(async (e) => {
if (!e.joinCleanup) throw new Error("MCP runtime does not expose cleanup ownership");
await e.joinCleanup();
}));
i ??= e.find((e) => e.status === "rejected");
if (i) {
recordAgentCleanupFailure();
throw i.reason;
}
},
async dispose() {
r ??= Promise.allSettled(t.map(async (e) => await e.dispose())).then((e) => {
i ??= e.find((e) => e.status === "rejected");
});
await r;
if (i) recordAgentCleanupFailure();
}
};
nativeMcpRuntimeBindings.set(d, {
hasServer: (e) => t.some((t) => nativeMcpRuntimeBindings.get(t)?.hasServer(e)),
async acquire(e, n) {
const r = l.get(e) ?? t.find((t) => nativeMcpRuntimeBindings.get(t)?.hasServer(e));
if (!r) throw new Error(`MCP server "${e}" has no projection owner`);
return acquireNativeMcpServer(r, e, n);
}
});
return d;
}
//#endregion
//#region src/agents/agent-bundle-mcp-runtime-owner.ts
const sessionMcpRuntimeOwners = resolveGlobalSingleton(Symbol.for("openclaw.sessionMcpRuntimeOwners"), () => /* @__PURE__ */ new WeakMap());
//#endregion
export { nativeMcpRuntimeBindings as i, createCombinedSessionMcpRuntime as n, acquireNativeMcpServer as r, sessionMcpRuntimeOwners as t };