UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

332 lines (331 loc) • 11.1 kB
import { l as isRecord, r as asNullableRecord } from "./record-coerce-CVPuDqcc.mjs"; import "./src-H3RMXyFL.mjs"; import { t as expectDefined } from "./expect-DDakjvvQ.mjs"; import { t as stableStringify } from "./stable-stringify-vqde_3tT.mjs"; import "./utils-C8YECn2Q.mjs"; import { r as captureOpenClawStateWorkerContext } from "./openclaw-state-worker-context-DAKL_dnZ.mjs"; import { t as redactSensitiveArgv } from "./redact-argv-DPxYXiH3.mjs"; import { i as validateConfigObjectWithPlugins } from "./validation-DSwgLhC7.mjs"; import { t as REDACTED_SENTINEL } from "./redact-sentinel-Db2p5Put.mjs"; import { g as readSourceConfigSnapshotForWrite, h as readSourceConfigSnapshot } from "./io.runtime-DsJ2dLCQ.mjs"; import "./io-4QsrsWTJ.mjs"; import { n as withOpenClawStateLeaseAsync } from "./openclaw-state-lease-Cn13CM0c.mjs"; import { r as replaceConfigFile } from "./mutate-DhAOi0-2.mjs"; import { t as canonicalizeConfiguredMcpServer } from "./mcp-config-normalize-DxJwGDsa.mjs"; import { n as resolveMcpTransportConfig } from "./mcp-transport-config-r6XeT3o8.mjs"; import { r as restoreRedactedValues, t as redactConfigObject } from "./redact-snapshot-HHllfRSn.mjs"; import { n as buildConfigSchemaCore } from "./schema-B2vHhxPS.mjs"; //#region src/config/mcp-config.ts function normalizeToolSelectionList(e) { if (!e) return; const t = Array.from(new Set(e.map((e) => e.trim()).filter((e) => e.length > 0))).toSorted((e, t) => e.localeCompare(t)); return t.length > 0 ? t : void 0; } function restoreMcpServerArgvSentinels(e) { const t = e.incoming.args; if (!Array.isArray(t)) return { ok: true, server: e.incoming }; if (!t.some((e) => typeof e === "string" && e.includes("__OPENCLAW_REDACTED__"))) return { ok: true, server: e.incoming }; const n = e.original?.args; if (!Array.isArray(n) || !n.every((e) => typeof e === "string") || t.length !== n.length) return { ok: false, error: `Cannot restore MCP args containing "${REDACTED_SENTINEL}" without the same original argv shape.` }; const r = redactSensitiveArgv(n, REDACTED_SENTINEL); if (t.some((e, t) => e !== r[t])) return { ok: false, error: `Cannot restore MCP args containing "${REDACTED_SENTINEL}" after argv changed. Replace every redacted value explicitly before editing args.` }; return { ok: true, server: { ...e.incoming, args: n } }; } function resolveConfiguredMcpServers(e) { if (!e.valid) return { ok: false, path: e.path, error: "Config file is invalid; fix it before using MCP config commands." }; const t = e.sourceConfig; return { ok: true, path: e.path, config: structuredClone(t), mcpServers: t.mcp?.servers ?? {}, authoredConfig: e.authoredConfig, runtimeConfig: e.runtimeConfig, sourceConfigBeforeMigrations: e.sourceConfigBeforeMigrations, baseHash: e.hash }; } function redactMcpServerArgsForDisplay(e) { if (!isRecord(e)) return e; if (!Array.isArray(e.args) || !e.args.every((e) => typeof e === "string")) return e; return { ...e, args: redactSensitiveArgv(e.args, REDACTED_SENTINEL) }; } /** Redact MCP server secrets before CLI or chat display. */ function redactMcpServersForDisplay(e) { const t = Object.fromEntries(Object.entries(e).map(([e, t]) => [e, redactMcpServerArgsForDisplay(t)])); return redactConfigObject({ mcp: { servers: t } }, buildConfigSchemaCore().uiHints).mcp.servers; } async function listConfiguredMcpServers() { return resolveConfiguredMcpServers(await readSourceConfigSnapshot()); } async function mutateConfiguredMcpServer(e, t) { const n = e.name.trim(); if (!n) return { ok: false, path: "", error: "MCP server name is required." }; const { snapshot: r, writeOptions: i } = await readSourceConfigSnapshotForWrite(); const a = resolveConfiguredMcpServers(r); if (!a.ok) return a; const o = Object.hasOwn(a.mcpServers, n); const s = e.kind === "unset" ? "removed" : "updated"; if (e.kind !== "set" && !o) { const { baseHash: e, ...t } = a; return { ...t, [s]: false }; } if (e.kind === "set" && e.createOnly && o) return { ok: false, path: a.path, error: `MCP server ${JSON.stringify(n)} already exists.` }; const c = a.mcpServers[n]; if (e.kind !== "update" && e.expectedServer && (e.kind === "set" && (!o || !c) || c && stableStringify(canonicalizeConfiguredMcpServer(c)) !== stableStringify(canonicalizeConfiguredMcpServer(e.expectedServer)))) return { ok: false, path: a.path, error: `MCP server ${JSON.stringify(n)} changed and was not ${s}.` }; const l = a.config; const u = l.mcp?.servers ?? {}; if (e.kind === "set") { const t = restoreMcpServerArgvSentinels({ incoming: e.server, original: c }); if (!t.ok) return { ok: false, path: a.path, error: t.error }; const r = restoreRedactedValues({ mcp: { servers: { [n]: t.server } } }, { mcp: { servers: a.mcpServers } }, buildConfigSchemaCore().uiHints); if (!r.ok) return { ok: false, path: a.path, error: r.humanReadableMessage ?? "MCP server config contains an unrestorable redacted value." }; const i = r.result.mcp?.servers?.[n]; if (!isRecord(i)) return { ok: false, path: a.path, error: "MCP server config must be a JSON object." }; u[n] = canonicalizeConfiguredMcpServer(i); } else if (e.kind === "unset") delete u[n]; else u[n] = e.update({ ...u[n] }); const d = e.kind === "update" ? e.errorLabel : e.kind; const f = e.kind === "set" ? void 0 : { [s]: true }; const { assertCurrent: p, assertCurrentAsync: m } = e; if (Object.keys(u).length > 0) l.mcp = { ...l.mcp, servers: u }; else if (l.mcp) { delete l.mcp.servers; if (Object.keys(l.mcp).length === 0) delete l.mcp; } const h = validateConfigObjectWithPlugins(l); if (!h.ok) { const e = expectDefined(h.issues[0], "issues entry at 0"); return { ok: false, path: a.path, error: `Config invalid after MCP ${d} (${e.path}: ${e.message}).` }; } const g = await replaceConfigFile({ sourceConfig: l, baseHash: a.baseHash, writeOptions: { ...i, assertCurrent: () => { i.assertCurrent?.(); p?.(); }, beforeCommit: async () => { await i.beforeCommit?.(); await m?.(); } } }); if (t) { const e = a.mcpServers[n]; const r = u[n]; await t({ name: n, ...e ? { previous: e } : {}, ...r ? { next: r } : {} }); } return { ok: true, path: a.path, config: g.nextConfig, mcpServers: u, ...f }; } async function updateConfiguredMcpServerTools$1(e, t) { return mutateConfiguredMcpServer({ kind: "update", name: e.name, assertCurrent: e.assertCurrent, assertCurrentAsync: e.assertCurrentAsync, errorLabel: "tool selection update", update: (t) => { if (e.tools === null) delete t.toolFilter; else { const n = normalizeToolSelectionList(e.tools.include); const r = normalizeToolSelectionList(e.tools.exclude); if (n || r) t.toolFilter = { ...isRecord(t.toolFilter) ? t.toolFilter : {}, ...n ? { include: n } : {}, ...r ? { exclude: r } : {} }; else delete t.toolFilter; } return t; } }, t); } async function updateConfiguredMcpServer$1(e, t) { return mutateConfiguredMcpServer({ kind: "update", name: e.name, assertCurrent: e.assertCurrent, assertCurrentAsync: e.assertCurrentAsync, errorLabel: "configure", update: (t) => canonicalizeConfiguredMcpServer(e.update(t)) }, t); } async function setConfiguredMcpServer$1(e, t) { if (!e.name.trim()) return { ok: false, path: "", error: "MCP server name is required." }; if (!isRecord(e.server)) return { ok: false, path: "", error: "MCP server config must be a JSON object." }; return mutateConfiguredMcpServer({ ...e, kind: "set", server: e.server }, t); } async function unsetConfiguredMcpServer$1(e, t) { return mutateConfiguredMcpServer({ ...e, kind: "unset" }, t); } /** Low-level config writers; production mutations must use the agents-owned lifecycle facade. */ const mcpConfigInternal = { set: setConfiguredMcpServer$1, unset: unsetConfiguredMcpServer$1, update: updateConfiguredMcpServer$1, updateTools: updateConfiguredMcpServerTools$1 }; //#endregion //#region src/agents/mcp-lifecycle-lease.ts const MCP_LIFECYCLE_LEASE_SCOPE = "core:claw-mcp-lifecycle"; const MCP_LIFECYCLE_LEASE_MS = 3e5; const MCP_LIFECYCLE_WAIT_MS = 6e5; /** Serialize ownership decisions and global config mutations for one MCP server. */ async function withMcpLifecycleLease(e, t, n) { return await withOpenClawStateLeaseAsync({ scope: MCP_LIFECYCLE_LEASE_SCOPE, key: e.trim(), leaseMs: MCP_LIFECYCLE_LEASE_MS, waitMs: MCP_LIFECYCLE_WAIT_MS, leaseLabel: "Template MCP lifecycle lease", operationLabel: "templates.mcp.lifecycle.lease" }, captureOpenClawStateWorkerContext(t), n); } //#endregion //#region src/agents/mcp-config-mutation.ts /** Canonical configured-MCP mutations with OAuth credential lifecycle cleanup. */ function hasOAuthAuth(e) { return asNullableRecord(e)?.auth === "oauth"; } function hasRequesterIdentity(e) { return hasOAuthAuth(e) && asNullableRecord(asNullableRecord(e)?.oauth)?.identity === "per-requester"; } async function clearReplacedMcpOAuth(e) { if (!hasOAuthAuth(e.previous)) return; const t = resolveMcpTransportConfig(e.name, e.previous); if (t?.kind !== "http") return; const n = hasOAuthAuth(e.next) ? resolveMcpTransportConfig(e.name, e.next) : void 0; const r = n?.kind === "http" && n.url === t.url; const i = hasRequesterIdentity(e.previous); if (r && i === hasRequesterIdentity(e.next)) return; const [{ operatorMcpOAuthIdentity: a }, { clearMcpOAuthRequesters: o, clearMcpOAuthServer: s }] = await Promise.all([import("./mcp-oauth-identity-yyLNlCV7.mjs"), import("./mcp-oauth-Bzsr2nlm.mjs")]); const c = a(e.name, t.url); if (r && i) { await o(c); return; } await s(c); } async function withMcpLifecycleCoordination(e, t) { const n = e.name.trim(); if (!n || e.skipLifecycleLease) return t(e); return withMcpLifecycleLease(n, {}, (n) => { const assertCurrent = () => { e.assertCurrent?.(); n.assertCurrent(); }; return t({ ...e, assertCurrent, assertCurrentAsync: async () => { await e.assertCurrentAsync?.(); await n.assertOwned(); assertCurrent(); } }); }); } function setConfiguredMcpServer(e) { return withMcpLifecycleCoordination(e, (e) => mcpConfigInternal.set(e, clearReplacedMcpOAuth)); } function unsetConfiguredMcpServer(e) { return withMcpLifecycleCoordination(e, (e) => mcpConfigInternal.unset(e, clearReplacedMcpOAuth)); } function updateConfiguredMcpServer(e) { return withMcpLifecycleCoordination(e, (e) => mcpConfigInternal.update(e, clearReplacedMcpOAuth)); } function updateConfiguredMcpServerTools(e) { return withMcpLifecycleCoordination(e, (e) => mcpConfigInternal.updateTools(e, clearReplacedMcpOAuth)); } //#endregion export { withMcpLifecycleLease as a, updateConfiguredMcpServerTools as i, unsetConfiguredMcpServer as n, listConfiguredMcpServers as o, updateConfiguredMcpServer as r, redactMcpServersForDisplay as s, setConfiguredMcpServer as t };