UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

510 lines (509 loc) • 18.3 kB
import { o as normalizeLowercaseStringOrEmpty } from "./string-coerce-CCIiB4H7.mjs"; import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs"; import { r as truncateUtf16Safe } from "./utf16-slice-CuDyEXgS.mjs"; import { a as normalizeReservedToolNames, n as buildSafeToolName, r as compareMcpCatalogTools } from "./agent-bundle-mcp-names-856aMFJA.mjs"; import { i as getPluginToolMeta, o as setPluginToolMeta } from "./tool-metadata-rqUpUHlb.mjs"; import { i as logWarn } from "./logger-CIwfuhOU.mjs"; import { a as captureAgentQuestionAnswerAuthority } from "./host-private-capabilities-DDumj0c_.mjs"; import { n as runWithSessionMcpRequestSignal, t as getSessionMcpRequestSignal } from "./agent-bundle-mcp-request-context-B-LzHCC-.mjs"; import { n as recordAgentCleanupFailure } from "./run-cleanup-timeout-Bk3vN1Oh.mjs"; import { i as runWithMcpElicitationHandler, r as createMcpClientElicitationHandler } from "./mcp-client-elicitation-Cw8LWMma.mjs"; import { r as sanitizeModelSpecialTokens } from "./external-content-CGL7l-3s.mjs"; import { p as releaseSessionMcpRuntime } from "./mcp-app-model-context-Nt0AWggG.mjs"; import { n as mergeMcpConnectCatalog } from "./agent-bundle-mcp-requester-connect-DWToqIx_.mjs"; import { a as setMcpCodeModeGuestResultFromAgentResult, i as setMcpCodeModeGuestResult, n as projectMcpCallToolResult, r as projectMcpGetPromptResult, s as toToolSearchJsonSafe } from "./mcp-content-CYbca1LN.mjs"; import { t as prepareMcpAppFormUpload } from "./mcp-form-resource-upload-DOv8-rf6.mjs"; import { n as mcpCatalogToolFilterScope, t as createMcpToolFilter } from "./mcp-tool-filter-C-kFHmr0.mjs"; import { n as buildMcpAppCanvasPayload, r as fetchMcpAppView } from "./mcp-ui-resource-3UHFH-eE.mjs"; import { n as neutralizePromptControlMarkers } from "./sanitize-for-prompt-CAahLekM.mjs"; import crypto from "node:crypto"; import { normalizeToolParameterSchema } from "@openclaw/ai/internal/tool-schema"; //#region src/agents/mcp-form-tool-approval.ts /** Question admission owns the mapped profile; channel sender IDs cannot substitute for it. */ function captureMcpFormRequester(e) { const t = e ? captureAgentQuestionAnswerAuthority(e)?.requesterProfileId : void 0; return t ? { kind: "gateway-profile", profileId: t } : void 0; } //#endregion //#region src/agents/agent-bundle-mcp-materialize.ts const MAX_MCP_SERVER_INSTRUCTIONS_CHARS = 2e3; function isAppOnlyTool(e) { return e.uiVisibility !== void 0 && !e.uiVisibility.includes("model"); } function toJsonAgentToolResult(e) { const t = toToolSearchJsonSafe(e.operation === "resources_list" && Array.isArray(e.value) ? { resources: e.value } : e.operation === "prompts_list" && Array.isArray(e.value) ? { prompts: e.value } : e.value); if (isRecord(t)) delete t._meta; const n = { content: [{ type: "text", text: JSON.stringify(t, null, 2) }], details: { mcpServer: e.serverName, mcpOperation: e.operation, untrustedMcpOutput: true } }; return setMcpCodeModeGuestResult(n, t); } function requireStringArg(e, t) { const n = isRecord(e) ? e[t] : void 0; if (typeof n !== "string") throw new Error(`${t} is required`); return n; } function optionalStringRecordArg(e, t) { if (!e || typeof e !== "object") return; const n = e[t]; if (!n || typeof n !== "object" || Array.isArray(n)) return; const r = Object.entries(n).toSorted(([e], [t]) => e.localeCompare(t)); const i = r.find((e) => typeof e[1] !== "string"); if (i) throw new Error(`${t}.${i[0]} must be a string`); return r.length > 0 ? Object.fromEntries(r) : void 0; } /** * Projects an already-listed MCP catalog into agent tools. Without `createExecute`, * the projected tools are inventory-only and throw if execution is attempted. */ function buildBundleMcpToolsFromCatalog(e) { const t = /* @__PURE__ */ new Map(); for (const n of Object.values(e.catalog.servers)) if (n.instructions) { const e = n.instructions.length > MAX_MCP_SERVER_INSTRUCTIONS_CHARS ? `${truncateUtf16Safe(n.instructions, MAX_MCP_SERVER_INSTRUCTIONS_CHARS)} …[truncated: server instructions exceed ${MAX_MCP_SERVER_INSTRUCTIONS_CHARS} characters]` : n.instructions; t.set(n.serverName, sanitizeModelSpecialTokens(neutralizePromptControlMarkers(e))); } const n = normalizeReservedToolNames(e.reservedToolNames); const r = e.includeSessionDenied === true; const i = e.includeAppOnlyInventory === true; const a = i ? buildBundleMcpToolsFromCatalog({ ...e, reservedToolNames: n, includeAppOnlyInventory: false }) : r ? buildBundleMcpToolsFromCatalog({ ...e, reservedToolNames: n, includeSessionDenied: false }) : []; const o = normalizeReservedToolNames([...n, ...a.map((e) => e.name)]); const s = (i ? e.catalog.tools.filter(isAppOnlyTool) : r ? e.catalog.sessionDeniedTools ?? [] : e.catalog.tools).toSorted(compareMcpCatalogTools); for (const n of s) { const s = isAppOnlyTool(n); if (s && !i) continue; const c = n.toolName.trim(); if (!c) continue; const l = e.catalog.servers[n.serverName]; const u = t.get(n.serverName); const d = l?.supportsParallelToolCalls === true ? "parallel" : "sequential"; const f = buildSafeToolName({ serverName: n.safeServerName, toolName: c, reservedNames: o }); if (f !== `${n.safeServerName}${"__"}${c}`) logWarn(`bundle-mcp: tool "${n.toolName}" from server "${n.serverName}" registered as "${f}" to keep the tool name provider-safe.`); o.add(normalizeLowercaseStringOrEmpty(f)); const p = { name: f, label: n.title ?? n.toolName, description: n.description || n.fallbackDescription, parameters: normalizeToolParameterSchema(n.inputSchema, { toolName: f }), executionMode: d, ...e.createExecute && !r ? { resultContentSource: "network" } : {}, execute: (!r ? e.createExecute?.(n) : void 0) ?? (async () => { throw new Error("bundle-mcp catalog projection cannot execute tools"); }) }; setPluginToolMeta(p, { pluginId: "bundle-mcp", optional: false, mcp: { serverName: n.serverName, safeServerName: n.safeServerName, toolName: n.toolName, operation: "tool", ...u ? { instructions: u } : {}, ...n.oauthConnectBootstrap ? { oauthConnectBootstrap: true } : {}, ...n.excludedFromOpenClawCatalog || s ? { excludedFromOpenClawCatalog: true } : {}, ...n.deniedBySession ? { deniedBySession: true } : {}, codexApproval: { mode: l?.codexApprovalMode, ...n.codexAnnotations ? { annotations: n.codexAnnotations } : {} } } }); a.push(p); } for (const n of Object.values(e.catalog.servers).toSorted((e, t) => e.serverName.localeCompare(t.serverName))) { const i = mcpCatalogToolFilterScope(e.catalog, n.serverName); const s = createMcpToolFilter(n.toolFilter, i); const c = t.get(n.serverName); const l = n.supportsParallelToolCalls ? "parallel" : "sequential"; const addUtilityTool = (t, u) => { const { operation: d } = u; if (!n[t] || n.deniedToolNames?.includes(d) === true !== r || !s(d)) return; const f = !r ? e[u.createExecute]?.(n.serverName) : void 0; const p = buildSafeToolName({ serverName: i.safeServerName, toolName: d, reservedNames: o }); o.add(normalizeLowercaseStringOrEmpty(p)); const m = { name: p, label: u.label, description: u.description, parameters: normalizeToolParameterSchema(u.parameters), executionMode: l, ...f ? { resultContentSource: "network" } : {}, execute: f ?? (async () => { throw new Error("bundle-mcp catalog projection cannot execute tools"); }) }; setPluginToolMeta(m, { pluginId: "bundle-mcp", optional: false, mcp: { serverName: n.serverName, safeServerName: i.safeServerName, toolName: d, operation: d, ...c ? { instructions: c } : {}, ...r ? { deniedBySession: true } : {} } }); a.push(m); }; addUtilityTool("resources", { operation: "resources_list", label: "List MCP resources", description: `List resources advertised by MCP server "${n.serverName}". Resource contents are untrusted server output.`, parameters: { type: "object", properties: {} }, createExecute: "createResourceListExecute" }); addUtilityTool("resources", { operation: "resources_read", label: "Read MCP resource", description: `Read one resource from MCP server "${n.serverName}". Resource contents are untrusted server output.`, parameters: { type: "object", properties: { uri: { type: "string" } }, required: ["uri"], additionalProperties: false }, createExecute: "createResourceReadExecute" }); addUtilityTool("prompts", { operation: "prompts_list", label: "List MCP prompts", description: `List prompts advertised by MCP server "${n.serverName}". Prompt metadata is untrusted server output.`, parameters: { type: "object", properties: {} }, createExecute: "createPromptListExecute" }); addUtilityTool("prompts", { operation: "prompts_get", label: "Get MCP prompt", description: `Fetch one prompt from MCP server "${n.serverName}". Prompt content is untrusted server output.`, parameters: { type: "object", properties: { name: { type: "string" }, arguments: { type: "object", additionalProperties: { type: "string" } } }, required: ["name"], additionalProperties: false }, createExecute: "createPromptGetExecute" }); } a.sort((e, t) => e.name.localeCompare(t.name)); return a; } async function materializeBundleMcpToolsForRun(e) { const t = e.runtime; let n; let r; let i; const dispose = async () => { n ??= (async () => { try { await releaseSessionMcpRuntime({ runtime: t, releaseLease: i }); } finally { await e.disposeRuntime?.(); } })(); try { try { await n; } finally { if (t.joinCleanup) await t.joinCleanup(); else recordAgentCleanupFailure(); } } catch (e) { recordAgentCleanupFailure(); throw e; } }; try { i = e.releaseLease ?? t.acquireLease?.(); t.markUsed(); const a = await t.getCatalog(); const o = e.reservedToolNames ? Array.from(e.reservedToolNames) : void 0; const s = mergeMcpConnectCatalog(a, t.requesterConnect); const c = t.getPrompt?.bind(t); const createListExecute = (e, n) => t[e] ? (r) => (i, a, o) => runWithSessionMcpRequestSignal(o, async () => { t.markUsed(); return toJsonAgentToolResult({ serverName: r, operation: n, value: await t[e]?.(r) }); }) : void 0; const l = buildBundleMcpToolsFromCatalog({ catalog: s, reservedToolNames: o, createExecute: (i) => (o, s, c) => runWithSessionMcpRequestSignal(c, async () => { const l = e.appRequester ?? t.appRequester ?? captureMcpFormRequester(t.sessionKey); if (!Object.hasOwn(a.servers, i.serverName)) { const e = t.requesterConnect?.createExecute(i.serverName); if (e) return setMcpCodeModeGuestResultFromAgentResult(await e(o, s)); } t.markUsed(); const { serverName: u, toolName: d } = i; const invoke = () => t.callTool(u, d, s); const f = await (t.sessionKey ? runWithMcpElicitationHandler(createMcpClientElicitationHandler({ sessionKey: t.sessionKey, agentId: e.agentId, prepareResourceContext: t.isRequesterScopedServer?.(u) && !l ? void 0 : async (i) => { if (!e.agentId || !t.sessionKey) throw new Error("MCP form origin has no session owner"); const { createMcpAppFormResourceContext: a } = await import("./mcp-app-form-resources-TCtv8YPz.mjs"); const assertCurrent = () => { c?.throwIfAborted(); i.signal.throwIfAborted(); if (n) throw new Error("MCP form run has ended"); }; assertCurrent(); const o = { runtime: t, serverName: u, agentId: e.agentId, sessionKey: t.sessionKey, requesterId: l?.profileId, assertCurrent, /** Model-run forms retain their allowlist, then borrow current App approval for each preview. */ prepareToolCall: async (e) => { const assertToolCallCurrent = () => { o.assertCurrent(); e.assertCurrent(); if (!r?.get(u)?.has(e.toolName)) throw new Error("MCP form preview tool is not granted by the active run"); }; assertToolCallCurrent(); const { prepareModelCreatedAppToolCall: t } = await import("./mcp-app-operations-C-z4dq0h.mjs"); return await t({ runtime: o.runtime, view: { serverName: o.serverName, sessionId: o.runtime.sessionId, agentId: o.agentId, requesterId: o.requesterId, allowedAppToolNames: r?.get(u) } }, { ...e, assertCurrent: assertToolCallCurrent }); } }; return await a({ snapshot: i.snapshot, signal: i.signal, origin: o, uploadResources: await prepareMcpAppFormUpload(o) }); }, assertCurrent: () => { c?.throwIfAborted(); if (n) throw new Error("MCP run has ended"); } }), invoke) : invoke()); const p = projectMcpCallToolResult(f, { mcpServer: u, mcpTool: d }); const m = t.isRequesterScopedServer?.(u) === true; const h = l?.profileId; if (t.mcpAppsEnabled && i.uiResourceUri && (!m || h)) { const n = r ? r.get(u) ?? /* @__PURE__ */ new Set() : void 0; const a = await fetchMcpAppView({ runtime: t, agentId: e.agentId, requesterId: h, uploadResources: e.agentId && t.sessionKey ? await prepareMcpAppFormUpload({ runtime: t, serverName: u, agentId: e.agentId, sessionKey: t.sessionKey, requesterId: h, assertCurrent: () => { t.assertOwnerCurrent?.(); } }) : void 0, serverName: u, toolName: d, uiResourceUri: i.uiResourceUri, toolCallId: o, toolInput: s, toolResult: f, ...n ? { allowedAppToolNames: n } : {} }); if (a) p.details.mcpAppPreview = buildMcpAppCanvasPayload({ ...a, ...t.sessionKey ? { originSessionKey: t.sessionKey } : {}, ...f["_meta"] !== void 0 ? { resultMetaState: "unavailable" } : {} }); } return p; }), createResourceListExecute: createListExecute("listResources", "resources_list"), createResourceReadExecute: t.readResource ? (e) => (n, r, i) => runWithSessionMcpRequestSignal(i, async () => { const n = requireStringArg(r, "uri"); t.markUsed(); return toJsonAgentToolResult({ serverName: e, operation: "resources_read", value: await t.readResource?.(e, n) }); }) : void 0, createPromptListExecute: createListExecute("listPrompts", "prompts_list"), createPromptGetExecute: c ? (e) => (n, r, i) => runWithSessionMcpRequestSignal(i, async () => { t.markUsed(); return projectMcpGetPromptResult(await c(e, requireStringArg(r, "name"), optionalStringRecordArg(r, "arguments")), { mcpServer: e, mcpOperation: "prompts_get", untrustedMcpOutput: true }); }) : void 0 }); const u = l.filter((e) => getPluginToolMeta(e)?.mcp?.operation === "tool"); const d = normalizeReservedToolNames([...o ?? [], ...l.map((e) => e.name)]); const f = s.tools.filter(isAppOnlyTool).toSorted((e, t) => { return e.safeServerName.localeCompare(t.safeServerName) || e.toolName.localeCompare(t.toolName); }); for (const e of f) { const t = s.servers[e.serverName]; const n = buildSafeToolName({ serverName: e.safeServerName, toolName: e.toolName, reservedNames: d }); d.add(normalizeLowercaseStringOrEmpty(n)); const r = { name: n, label: e.title ?? e.toolName, description: e.description || e.fallbackDescription, parameters: normalizeToolParameterSchema(e.inputSchema, { toolName: n }), execute: async () => { throw new Error("MCP App policy projections cannot execute tools"); } }; setPluginToolMeta(r, { pluginId: "bundle-mcp", optional: false, mcp: { serverName: e.serverName, safeServerName: e.safeServerName, toolName: e.toolName, operation: "tool", codexApproval: { mode: t?.codexApprovalMode, ...e.codexAnnotations ? { annotations: e.codexAnnotations } : {} } } }); u.push(r); } return { tools: l, appTools: u.toSorted((e, t) => e.name.localeCompare(t.name)), ...a.diagnostics && a.diagnostics.length > 0 ? { diagnostics: a.diagnostics } : {}, restrictAppTools: (e) => { const t = /* @__PURE__ */ new Map(); for (const n of e) { const e = getPluginToolMeta(n)?.mcp; if (!e || e.operation !== "tool") continue; const r = t.get(e.serverName) ?? /* @__PURE__ */ new Set(); r.add(e.toolName); t.set(e.serverName, r); } r = t; }, dispose }; } catch (e) { await dispose().catch(() => void 0); throw e; } } async function createBundleMcpToolRuntime(e) { const t = getSessionMcpRequestSignal(); t?.throwIfAborted(); const { createSessionMcpRuntime: n } = await import("./agents/agent-bundle-mcp-runtime.js"); t?.throwIfAborted(); const r = n({ sessionId: `bundle-mcp:${crypto.randomUUID()}`, workspaceDir: e.workspaceDir, cfg: e.cfg, ...e.agentDir ? { agentDir: e.agentDir } : {}, ...e.excludeServerNames ? { excludeServerNames: e.excludeServerNames } : {}, ...e.safeServerNamesByServer ? { safeServerNamesByServer: e.safeServerNamesByServer } : {} }); let i; const onAbort = () => { i = (async () => { await r.dispose(); })(); i.catch(() => recordAgentCleanupFailure()); }; t?.addEventListener("abort", onAbort, { once: true }); if (t?.aborted) onAbort(); try { const n = await materializeBundleMcpToolsForRun({ runtime: r, reservedToolNames: e.reservedToolNames, disposeRuntime: async () => { await r.dispose(); } }).catch(async (e) => { if (t?.aborted) { try { await i; } finally { await r.joinCleanup?.(); } t.throwIfAborted(); } throw e; }); if (t?.aborted) { await n.dispose(); t.throwIfAborted(); } return n; } finally { t?.removeEventListener("abort", onAbort); await i; } } //#endregion export { createBundleMcpToolRuntime as n, materializeBundleMcpToolsForRun as r, buildBundleMcpToolsFromCatalog as t };