openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
612 lines (611 loc) • 21.9 kB
JavaScript
import { a as asOptionalRecord } from "./record-coerce-CVPuDqcc.mjs";
import { a as resolveAgentDir, f as resolveAgentWorkspaceDir } from "./agent-scope-config-DmXgFGKP.mjs";
import { i as getGatewayPluginMetadataSnapshot } from "./current-plugin-metadata-state-BmYo9Q7A.mjs";
import { Dr as ZodError, Et as _enum, Fn as object, Jn as string, Lt as boolean, Nt as array, Pn as number, Un as record, or as union } from "./schemas-Cy6abvsu.mjs";
import "./agent-scope-BwB8YH6y.mjs";
import { t as ErrorCodes } from "./gateway-error-details-B69XiHdh.mjs";
import { p as errorShape } from "./error-codes-BzF7aRQ0.mjs";
import { i as getPluginToolMeta } from "./tool-metadata-rqUpUHlb.mjs";
import { n as getSessionRowProjection } from "./session-row-projection-access-CjLImwLs.mjs";
import { r as resolveSandboxRuntimeStatus } from "./runtime-status-C5ZOG7YR.mjs";
import { i as logWarn } from "./logger-CIwfuhOU.mjs";
import { n as getRegisteredAgentHarness } from "./registry-ubpieJjd.mjs";
import { o as resolveEffectiveAgentRuntime } from "./thinking-runtime-BKWl4CUs.mjs";
import { n as resolveSessionSelectedModelRefAsync } from "./session-utils-model-selection-BGYqZws_.mjs";
import { n as captureGatewayOperatorRunAuthority } from "./operator-run-authority-3Pm3MQDA.mjs";
import { t as iteratePluginRootContributions } from "./plugin-root-contributions-BNGZsh9w.mjs";
import { n as runWithSessionMcpRequestSignal } from "./agent-bundle-mcp-request-context-B-LzHCC-.mjs";
import { t as loadSessionMcpConfig } from "./agent-bundle-mcp-runtime-config-CBo1pSHY.mjs";
import { p as releaseSessionMcpRuntime } from "./mcp-app-model-context-Nt0AWggG.mjs";
import { n as acquireSessionMcpRuntime } from "./agent-bundle-mcp-manager-api-Um6GkoIv.mjs";
import { t as buildBundleMcpToolsFromCatalog } from "./agent-bundle-mcp-materialize-DM8C34_b.mjs";
import { n as mcpCatalogToolFilterScope, r as normalizeMcpToolFilter, t as createMcpToolFilter } from "./mcp-tool-filter-C-kFHmr0.mjs";
import { i as getMcpAppViewLease, n as buildMcpAppCanvasPayload, r as fetchMcpAppView } from "./mcp-ui-resource-3UHFH-eE.mjs";
import { i as resolveProjectedMcpCodexToolApprovalMode, r as requiresMcpCodexToolApproval } from "./mcp-codex-tool-approval-C6Ex4SQ6.mjs";
import { n as readMcpAppSettings } from "./mcp-app-extension-metadata-DyV6LL2L.mjs";
import { l as resolveMcpAppRequesterId, n as callMcpAppToolWithElicitation } from "./mcp-app-operations-Qv9yxlnB.mjs";
import { t as resolveSessionResourceToolPolicy } from "./session-resource-tool-policy-b29IoOJX.mjs";
import { r as prepareMcpAppHostFile } from "./mcp-app-host-files-B8Pimitv.mjs";
import { t as requestMcpAppToolApproval } from "./mcp-app-tool-approval-DxlS6Pj0.mjs";
import { randomUUID } from "node:crypto";
import { ResourceLinkSchema } from "@modelcontextprotocol/core";
//#region src/gateway/mcp-app-extension-runtime.ts
/** A request borrows the current owner; it never substitutes a different native transport. */
async function prepareMcpAppExtensionRuntime(e) {
const t = e.sessionAccessAuthority;
const n = getSessionRowProjection(e.context);
if (!t || !n) throw new Error("MCP App session authority is unavailable");
t.assertCurrent();
const { agentId: r, sessionKey: i, sessionId: a } = t.target;
const o = {
agentId: r,
key: i
};
const s = n.sharingTarget(o);
if (!s || s.entry.sessionId !== a) throw new Error("MCP App session changed");
const c = e.context.getRuntimeConfig();
if (c.mcp?.apps?.enabled !== true) throw new Error("MCP Apps are disabled");
const l = await resolveSessionSelectedModelRefAsync({
cfg: c,
agentId: r,
sessionKey: i,
source: {
entry: s.entry,
readSourceEntry: (e) => n.sharingTarget({
agentId: r,
key: e
})?.entry
},
manifestPlugins: getGatewayPluginMetadataSnapshot() ?? [],
assertCurrent: t.assertCurrent
});
const u = resolveEffectiveAgentRuntime({
cfg: c,
provider: l.provider,
modelId: l.model,
agentScope: {
kind: "prepared",
agentId: r
},
sessionKey: i,
sessionEntry: s.entry
});
const { authProfileOverride: d, authProfileOverrideSource: f, sandboxMode: p } = s.entry;
const current = (r = t.assertCurrent) => {
r();
if (e.context.getRuntimeConfig() !== c) throw new Error("MCP App configuration changed; reopen the App");
const i = n.sharingTarget(o);
if (!i || i.entry.sessionId !== a) throw new Error("MCP App session changed");
if (i.entry.authProfileOverride !== d || i.entry.authProfileOverrideSource !== f || i.entry.sandboxMode !== p) throw new Error("MCP App session runtime selection changed; reopen the App");
return i;
};
const m = current();
const h = m.entry.spawnedWorkspaceDir ?? resolveAgentWorkspaceDir(c, r);
const g = resolveMcpAppRequesterId(e.client);
const _ = u ? getRegisteredAgentHarness(u) : void 0;
if (u !== "openclaw" && !_) throw new Error("The selected session harness is unavailable");
const v = _?.harness;
const { loaded: y } = loadSessionMcpConfig({
workspaceDir: h,
cfg: c,
toolOverrides: m.entry.toolOverrides
});
let b;
if (u !== "openclaw") {
if (!v?.loadMcpToolCatalog || !v.acquireMcpAppRuntime) throw new Error("The session harness cannot open MCP Apps");
const n = {};
let o;
const prepareSession = () => {
o ??= (async () => {
const o = resolveSandboxRuntimeStatus({
cfg: c,
agentId: r,
sessionKey: i,
preparedSessionEntry: current().entry
});
if (t.sandboxRequired || o.sandboxed || o.sandboxRequired) throw new Error("Native App initialization cannot run outside required session isolation");
if (!_?.ownerPluginId) throw new Error("Native harness owner is unavailable");
const s = t.retain();
n.access = s;
const u = e.signal ? AbortSignal.any([s.signal, e.signal]) : s.signal;
const assertPreparationCurrent = () => {
current();
s.assertCurrent();
u.throwIfAborted();
};
assertPreparationCurrent();
const d = await captureGatewayOperatorRunAuthority({
client: e.client,
context: e.context,
hasCurrentClientAuthority: e.hasCurrentClientAuthority,
invocationAuthority: {
assertCurrent: assertPreparationCurrent,
signal: u
}
});
n.source = d;
assertPreparationCurrent();
const f = current();
const { prepareAgentHarnessSessionRuntime: p } = await import("./session-preparation-D6AyekH3.mjs");
const m = await p({
ownerPluginId: _.ownerPluginId,
nativeModelPolicySupport: v.nativeModelPolicySupport,
sourceAuthority: d?.authority,
assertCurrent: assertPreparationCurrent,
input: {
config: c,
agentId: r,
agentDir: resolveAgentDir(c, r),
sessionId: a,
sessionKey: i,
workspaceDir: h,
provider: l.provider,
modelId: l.model,
authProfileId: f.entry.authProfileOverride,
authProfileIdSource: f.entry.authProfileOverrideSource === "auto" ? "auto" : f.entry.authProfileOverride ? "user" : void 0,
senderId: g,
messageChannel: "webchat",
messageProvider: "webchat",
abortSignal: u,
permissionMode: f.entry.permissionMode,
sessionRoot: f.entry.sessionRoot,
toolOverrides: f.entry.toolOverrides,
spawnedBy: f.entry.spawnedBy,
groupId: f.entry.groupId,
groupChannel: f.entry.groupChannel,
groupSpace: f.entry.space,
sessionTarget: {
agentId: r,
sessionId: a,
sessionKey: i,
storePath: f.storePath,
expectedLifecycleRevision: f.entry.lifecycleRevision
}
}
});
n.setup = m;
assertPreparationCurrent();
return m.preparation;
})();
return o;
};
try {
b = await v.acquireMcpAppRuntime({
config: c,
agentId: r,
sessionId: a,
sessionKey: i,
workspaceDir: h,
mcpServerNames: Object.keys(y.mcpServers),
toolOverrides: m.entry.toolOverrides,
assertCurrent: t.assertCurrent,
appRequester: g ? {
kind: "gateway-profile",
profileId: g
} : void 0,
prepareSession
});
} finally {
try {
n.setup?.dispose();
} finally {
try {
n.source?.release();
} finally {
n.access?.release();
}
}
}
} else b = await acquireSessionMcpRuntime({
sessionId: a,
sessionKey: i,
agentId: r,
workspaceDir: h,
agentDir: resolveAgentDir(c, r),
cfg: c,
requesterSenderId: g,
messageChannel: "webchat",
toolOverrides: m.entry.toolOverrides
});
if (!b) throw new Error("Open a conversation with this plugin before launching its App");
const x = b;
const S = x.runtime;
const C = [];
try {
current();
const o = await S.getCatalog();
const s = {
...o,
servers: Object.fromEntries(Object.entries(o.servers).map(([e, t]) => [e, {
...t,
pluginId: t.pluginId ?? y.pluginIdsByServer?.[e]
}]))
};
current();
const c = buildBundleMcpToolsFromCatalog({
catalog: s,
includeAppOnlyInventory: true
});
const l = new Map(c.flatMap((e) => {
const t = getPluginToolMeta(e)?.mcp;
return t?.operation === "tool" ? [[JSON.stringify([t.serverName, t.toolName]), e.name]] : [];
}));
const assertTool = (r, i = false, a = t.assertCurrent) => {
const o = current(a);
if (e.context.getRuntimeConfig().mcp?.apps?.enabled !== true) throw new Error("MCP Apps are disabled");
const c = y.mcpServers[r.serverName];
if (!c && !(S.assertOwnerCurrent && s.servers[r.serverName]?.pluginId) || c && !createMcpToolFilter(normalizeMcpToolFilter(c.toolFilter), mcpCatalogToolFilterScope(s, r.serverName))(r.toolName)) throw new Error("MCP App tool is denied by server policy");
const u = l.get(JSON.stringify([r.serverName, r.toolName]));
if (!u || o.entry.toolOverrides?.mcpServers?.[r.serverName] === false || o.entry.toolOverrides?.mcpToolsDeny?.[r.serverName]?.includes(r.toolName)) throw new Error("MCP App tool is denied");
resolveSessionResourceToolPolicy({
config: e.context.getRuntimeConfig(),
client: e.client,
current: o,
readPreparedSessionEntry: (e) => n.sharingTarget(e)?.entry,
toolName: u,
assertNativeRuntimeCurrent: S.assertOwnerCurrent
});
return i && requiresMcpCodexToolApproval({
mode: (c ? resolveProjectedMcpCodexToolApprovalMode(r.serverName, c) : "prompt") ?? s.servers[r.serverName]?.codexApprovalMode,
fullPermission: o.entry.permissionMode === "full",
annotations: r.codexAnnotations
});
};
const prepareToolCall = async (e, n, a = t.assertCurrent) => {
const assertCurrent = () => {
n.assertCurrent();
assertTool(e, false, a);
};
n.assertCurrent();
const o = assertTool(e, true, a);
if (o) await requestMcpAppToolApproval({
options: n.options,
agentId: r,
sessionKey: i,
serverName: e.serverName,
toolName: e.toolName,
input: n.input,
view: n.view,
requesterId: resolveMcpAppRequesterId(n.options.client),
signal: n.signal,
assertCurrent
});
const assertExecutionCurrent = () => {
n.assertCurrent();
if (assertTool(e, true, a) && !o) throw new Error("MCP App approval policy changed before execution");
};
assertExecutionCurrent();
return assertExecutionCurrent;
};
const approveTool = async (n, r) => {
const i = assertTool(n, true) ? t.retain() : void 0;
if (i) C.push(i.release);
return prepareToolCall(n, {
options: e,
toolName: n.toolName,
input: r,
signal: i?.signal,
assertCurrent: i?.assertCurrent ?? t.assertCurrent
});
};
const u = s.tools.filter((e) => {
try {
assertTool(e);
return true;
} catch {
return false;
}
});
const retainViewAuthority = (e) => {
const n = t.retain();
const prepareViewToolCall = async (t) => {
const r = e.find((e) => e.toolName === t.toolName);
if (!r) throw new Error("MCP App tool is not granted to this view");
return prepareToolCall(r, {
...t,
signal: t.signal ? AbortSignal.any([n.signal, t.signal]) : n.signal
}, n.assertCurrent);
};
return {
...n,
prepareToolCall: prepareViewToolCall,
assertCurrent: () => {
if (current(n.assertCurrent).entry.permissionMode !== m.entry.permissionMode) throw new Error("MCP App permission mode changed; reopen the App");
for (const t of e) assertTool(t, false, n.assertCurrent);
}
};
};
return {
approveTool,
retainViewAuthority,
options: e,
runtime: S,
catalog: {
...s,
tools: u
},
agentId: r,
sessionKey: i,
sessionId: a,
workspaceDir: h,
requesterId: g,
access: t,
assertTool,
assertCurrent: () => {
current();
},
dispose: async () => {
for (const e of C.splice(0)) e();
await releaseSessionMcpRuntime(x);
await S.joinCleanup?.();
}
};
} catch (e) {
for (const e of C.splice(0)) e();
await releaseSessionMcpRuntime(b);
throw e;
}
}
//#endregion
//#region src/gateway/server-methods/mcp-app-extensions.ts
var UnsupportedMcpMentionResultError = class extends Error {};
const text = string().trim().min(1).max(2048);
const targetSchema = object({
sessionKey: text,
agentId: text.optional()
});
const launchSchema = targetSchema.extend({
serverName: text,
toolName: text,
entrypointType: _enum([
"global",
"thread",
"file",
"settings"
]),
quickAction: boolean().optional(),
filePath: text.optional(),
deepLink: text.optional()
});
const settingsSchema = targetSchema.extend({
serverName: text,
action: _enum([
"read",
"update",
"tool"
]),
toolName: text.optional(),
arguments: object({ set: record(string(), union([
string(),
number().finite(),
boolean()
])) }).optional()
});
const mentionSchema = targetSchema.extend({
serverName: text,
query: string().max(2048)
});
function toolFor(e, t, n) {
const r = e.catalog.tools.find((e) => e.serverName === t && e.toolName === n);
if (!r) throw new Error("MCP App tool is unavailable or denied");
e.assertTool(r);
return r;
}
function appToolsFor(e, t) {
return e.catalog.tools.filter((n) => {
if (n.serverName !== t || n.uiVisibility !== void 0 && !n.uiVisibility.includes("app")) return false;
try {
e.assertTool(n);
return true;
} catch {
return false;
}
});
}
async function uploadFor(e, t, n) {
const { prepareMcpAppFormUpload: r } = await import("./mcp-form-resource-upload-BRC1F9Tj.mjs");
return await r({
runtime: e.runtime,
serverName: t,
agentId: e.agentId,
sessionKey: e.sessionKey,
requesterId: e.requesterId,
assertCurrent: n
});
}
async function call(e, t, n) {
const r = await e.approveTool(t, n);
const i = e.retainViewAuthority(appToolsFor(e, t.serverName));
let a;
try {
a = await callMcpAppToolWithElicitation({
options: e.options,
uploadResources: await uploadFor(e, t.serverName, r),
origin: {
runtime: e.runtime,
serverName: t.serverName,
agentId: e.agentId,
sessionKey: e.sessionKey,
requesterId: e.requesterId,
assertCurrent: r,
prepareToolCall: i.prepareToolCall
},
toolName: t.toolName,
input: n,
assertCurrent: r
});
} finally {
i.release();
}
e.assertCurrent();
return a;
}
async function launch(e, t, n, r) {
if (!t.uiResourceUri?.startsWith("ui://")) throw new Error("MCP App resource is unavailable");
const i = await call(e, t, n);
if (i.isError) return { toolResult: i };
const a = appToolsFor(e, t.serverName);
const o = e.retainViewAuthority(a);
let s = false;
try {
const c = e.runtime;
const l = new Set(a.map((e) => e.toolName));
const u = await fetchMcpAppView({
runtime: c,
agentId: e.agentId,
serverName: t.serverName,
toolName: t.toolName,
uiResourceUri: t.uiResourceUri,
toolCallId: randomUUID(),
toolInput: n,
toolResult: i,
allowedAppToolNames: l,
requesterId: e.requesterId,
displayMode: t.appExtensions?.preferredModelDisplayMode,
prepareToolCall: o.prepareToolCall,
uploadResources: await uploadFor(e, t.serverName, o.assertCurrent),
...r,
authorizeAppInteraction: () => {
o.assertCurrent();
return true;
}
});
if (!u) throw new Error("MCP App resource could not be loaded");
const d = buildMcpAppCanvasPayload({
...u,
originSessionKey: e.sessionKey
});
e.assertCurrent();
const f = getMcpAppViewLease(u.viewId, c);
if (f) {
f.disposeCallbacks ??= /* @__PURE__ */ new Set();
f.disposeCallbacks.add(o.release);
s = true;
}
return {
viewId: u.viewId,
preview: d
};
} finally {
if (!s) o.release();
}
}
function handler(e, t, n) {
return async (r) => {
let i;
try {
const a = e.parse(r.params);
if (n && r.context.getRuntimeConfig().mcp?.apps?.enabled !== true) {
r.sessionAccessAuthority?.assertCurrent();
r.respond(true, n);
return;
}
await runWithSessionMcpRequestSignal(r.signal, async () => {
i = await prepareMcpAppExtensionRuntime(r);
const e = await t(i, a);
i.assertCurrent();
r.respond(true, e);
});
} catch (e) {
r.respond(false, void 0, errorShape(e instanceof ZodError ? ErrorCodes.INVALID_REQUEST : ErrorCodes.UNAVAILABLE, e instanceof Error ? e.message : String(e), e instanceof UnsupportedMcpMentionResultError ? { details: { code: "MCP_APP_UNSUPPORTED_MENTION_RESULT" } } : void 0));
} finally {
await i?.dispose().catch((e) => logWarn(`mcp-app: cleanup failed: ${String(e)}`));
}
};
}
const mcpAppExtensionHandlers = {
"mcp.app.discover": handler(targetSchema, (e) => ({
onboarding: (() => {
const t = getGatewayPluginMetadataSnapshot();
return t ? [...iteratePluginRootContributions({
metadataSnapshot: t,
config: e.options.context.getRuntimeConfig(),
contribution: "skills"
})].flatMap(({ record: e }) => e.onboardingSkill ? [{
pluginId: e.id,
title: e.name ?? e.id
}] : []) : [];
})(),
servers: Object.values(e.catalog.servers).flatMap((t) => {
const n = t.pluginId ? getGatewayPluginMetadataSnapshot()?.index.installRecords[t.pluginId] : void 0;
const r = n?.marketplacePlugin ?? t.pluginId;
const i = n?.marketplaceName ?? t.marketplace;
const a = e.catalog.tools.filter((e) => e.serverName === t.serverName);
const o = a.flatMap((e) => e.uiResourceUri?.startsWith("ui://") ? (e.appExtensions?.entrypoints ?? []).map((n) => ({
toolName: e.toolName,
title: e.title ?? e.toolName,
resourceUri: e.uiResourceUri,
icons: e.appExtensions?.icons ?? t.icons,
entrypoint: n
})) : []);
const s = t.settings && a.some((e) => e.toolName === t.settings?.readTool) && a.some((e) => e.toolName === t.settings?.updateTool) ? t.settings : void 0;
const c = a.find((e) => e.appExtensions?.mentionSearch)?.toolName;
return o.length || s || c ? [{
serverName: t.serverName,
...r ? { pluginId: r } : {},
...i ? { marketplace: i } : {},
label: t.title ?? t.serverName,
icons: t.icons,
entrypoints: o,
...s ? { settings: s } : {},
...c ? { mentionTool: c } : {}
}] : [];
})
}), {
servers: [],
onboarding: []
}),
"mcp.app.launch": handler(launchSchema, async (e, t) => {
const n = toolFor(e, t.serverName, t.toolName);
const r = n.appExtensions?.entrypoints?.find((e) => e.type === t.entrypointType);
if (!r) throw new Error("The requested MCP App entrypoint is not advertised");
if (t.quickAction) {
if (r.type !== "global" || !r.quickAction) throw new Error("MCP App quick action is unavailable");
const n = r.quickAction.target;
const i = toolFor(e, t.serverName, n.name);
return i.uiResourceUri ? launch(e, i, n.arguments ?? {}) : { toolResult: await call(e, i, n.arguments ?? {}) };
}
if (r.type === "file") {
if (!t.filePath) throw new Error("Choose a session file to open");
const i = await prepareMcpAppHostFile(e.options, {
sessionKey: e.sessionKey,
agentId: e.agentId,
path: t.filePath
});
e.assertCurrent();
if (!r.extensions.some((e) => i.name.toLowerCase().endsWith(e.toLowerCase()))) throw new Error("The file extension is not supported by this App");
return await launch(e, n, { file: {
name: i.name,
resourceUri: i.resourceUri
} }, { hostFile: i });
}
if (t.deepLink && (r.type !== "global" || !t.deepLink.startsWith("/") || t.deepLink.startsWith("//") || t.deepLink.includes("#"))) throw new Error("Invalid App-relative deep link");
return await launch(e, n, {}, t.deepLink ? { deepLink: { url: t.deepLink } } : void 0);
}),
"mcp.app.settings": handler(settingsSchema, async (e, t) => {
const n = e.catalog.servers[t.serverName]?.settings;
if (!n) throw new Error("Structured MCP settings are unavailable");
if (t.action === "update") {
if (!t.arguments) throw new Error("Changed settings are required");
return { toolResult: await call(e, toolFor(e, t.serverName, n.updateTool), t.arguments) };
}
const r = await call(e, toolFor(e, t.serverName, n.readTool), {});
if (r.isError) throw new Error("The MCP settings read tool failed");
const i = readMcpAppSettings(r.structuredContent);
if (t.action === "read") return i;
if (!i.layout?.some((e) => e.items.some((e) => e.kind === "tool" && e.tool === t.toolName))) throw new Error("Settings action is not advertised in the current layout");
const a = toolFor(e, t.serverName, t.toolName);
return a.uiResourceUri ? launch(e, a, {}) : { toolResult: await call(e, a, {}) };
}),
"mcp.app.mention": handler(mentionSchema, async (e, t) => {
const n = e.catalog.tools.find((e) => e.serverName === t.serverName && e.appExtensions?.mentionSearch);
if (!n) throw new Error("MCP mention search is unavailable");
const r = await call(e, n, { query: t.query });
if (r.isError) throw new Error("MCP mention search failed");
const i = array(ResourceLinkSchema).max(200).safeParse(asOptionalRecord(r.structuredContent)?.items);
if (!i.success) throw new UnsupportedMcpMentionResultError("This app returned an unsupported resource list");
return { resources: i.data };
})
};
//#endregion
export { mcpAppExtensionHandlers };