openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
266 lines (265 loc) • 11.1 kB
JavaScript
import { a as asOptionalRecord } from "./record-coerce-CVPuDqcc.mjs";
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { t as createLazyRuntimeMethod } from "./lazy-runtime-zGjszCtt.mjs";
import { n as authorizeOperatorScopesForMethod } from "./method-scopes-Dpyb0Ck-.mjs";
import { r as GatewayErrorDetailCodes, t as ErrorCodes } from "./gateway-error-details-B69XiHdh.mjs";
import { p as errorShape } from "./error-codes-BzF7aRQ0.mjs";
import { r as resolveRequestedSessionAgentId } from "./session-request-agent-tfwWH53J.mjs";
import { i as logWarn } from "./logger-CIwfuhOU.mjs";
import { a as readGatewayRequestMutationAuthority } from "./session-mutation-guards-Bjnk_O0z.mjs";
import { c as subscribeMcpAppModelContext, l as updateMcpAppModelContext, o as removeMcpAppModelContextItem, r as getMcpAppModelContext } from "./mcp-app-model-context-Nt0AWggG.mjs";
import { l as buildMcpAppSandboxPath } from "./mcp-ui-resource-3UHFH-eE.mjs";
import { d as withMcpAppActiveView, l as resolveMcpAppRequesterId, o as requireMcpAppInteraction, r as executeMcpAppOperation, s as resolveMcpAppActiveView, t as McpAppViewExpiredError, u as supportsMcpAppInteraction } from "./mcp-app-operations-Qv9yxlnB.mjs";
import { t as createMcpAppStandaloneTicket } from "./mcp-app-standalone-CtVsHHh4.mjs";
import { t as retainSessionScopedRead } from "./session-scoped-read-D2_BUoMM.mjs";
//#region src/gateway/server-methods/mcp-app.ts
const fileRuntime = () => import("./mcp-app-host-files-Bv0Hm3Qr.mjs");
const readMcpAppHostFile = createLazyRuntimeMethod(fileRuntime, (e) => e.readMcpAppHostFile);
const writeMcpAppHostFile = createLazyRuntimeMethod(fileRuntime, (e) => e.writeMcpAppHostFile);
const subscribeMcpAppHostFile = createLazyRuntimeMethod(fileRuntime, (e) => e.subscribeMcpAppHostFile);
const canOpenMcpAppFiles = createLazyRuntimeMethod(fileRuntime, (e) => e.canOpenMcpAppFiles);
const openMcpAppFile = createLazyRuntimeMethod(fileRuntime, (e) => e.openMcpAppFile);
function requireString(e, t) {
const n = e[t];
if (typeof n !== "string" || !n.trim()) throw new Error(`${t} is required`);
return n.trim();
}
function optionalRecord(e, t) {
const n = e[t];
if (n === void 0) return;
const r = asOptionalRecord(n);
if (!r) throw new Error(`${t} must be an object`);
return r;
}
function optionalCursor(e) {
const t = e.cursor;
return typeof t === "string" ? { cursor: t } : void 0;
}
var McpAppRequestError = class extends Error {
constructor(e) {
super(e.message);
this.shape = e;
}
};
function resolveMcpAppSessionOwner(e, t) {
const n = requireString(e, "sessionKey");
const r = typeof e.agentId === "string" && e.agentId.trim() ? e.agentId.trim() : void 0;
const i = resolveRequestedSessionAgentId(t, n, r);
if (!i.ok) throw new McpAppRequestError(i.error);
return i.agentId;
}
function resolveRequestedMcpAppView({ params: e, context: t, client: n }, r) {
return resolveMcpAppActiveView({
sessionKey: requireString(e, "sessionKey"),
agentId: resolveMcpAppSessionOwner(e, r?.cfg ?? t.getRuntimeConfig()),
viewId: requireString(e, "viewId"),
requesterId: r ? r.requesterId : resolveMcpAppRequesterId(n),
cfg: t.getRuntimeConfig(),
restore: false
});
}
function operationHandler(e) {
return mcpAppHandler(async (t) => {
const { params: n, context: r, client: i } = t;
const a = readGatewayRequestMutationAuthority(t);
const o = e(n);
const s = r.getRuntimeConfig();
const c = resolveMcpAppRequesterId(i);
const l = await resolveRequestedMcpAppView(t, {
cfg: s,
requesterId: c
});
const u = await retainSessionScopedRead(t, requireString(n, "sessionKey"), l.view.agentId);
try {
const e = o.method === "resources/read" && o.params.uri.startsWith("openclaw-file://") ? await readMcpAppHostFile(t, l.view, o.params) : await executeMcpAppOperation(l, o, {
options: t,
assertCurrent: () => {
a.assertCurrent();
u?.assertCurrent();
t.sessionMutationAuthorization?.assertCurrent();
if (resolveMcpAppRequesterId(i) !== c || l.view.requesterId !== void 0 && l.view.requesterId !== c) throw new McpAppViewExpiredError();
}
});
u?.assertCurrent();
return e;
} finally {
u?.release();
}
});
}
function mcpAppHandler(e) {
return async (t) => {
try {
t.respond(true, await e(t));
} catch (e) {
t.respond(false, void 0, e instanceof McpAppRequestError ? e.shape : errorShape(ErrorCodes.UNAVAILABLE, formatErrorMessage(e), e instanceof McpAppViewExpiredError ? { details: { code: GatewayErrorDetailCodes.MCP_APP_VIEW_EXPIRED } } : void 0));
}
};
}
const modelContextSubscriptions = /* @__PURE__ */ new WeakMap();
function hostFileHandler(e) {
return mcpAppHandler(async (t) => {
const n = await resolveRequestedMcpAppView(t);
return withMcpAppActiveView(n, "read", () => e(t, n.view));
});
}
const mcpAppHandlers = {
"mcp.app.formResource": mcpAppHandler(async (e) => {
const { executeMcpAppFormResource: t } = await import("./mcp-app-form-resources-TCtv8YPz.mjs");
return t(e);
}),
"mcp.app.view": mcpAppHandler(async (e) => {
const { params: t, context: n, client: r } = e;
const i = requireString(t, "sessionKey");
const a = resolveMcpAppSessionOwner(t, n.getRuntimeConfig());
const o = resolveMcpAppRequesterId(r);
const s = await retainSessionScopedRead(e, i, a);
const assertRequestCurrent = () => {
s?.assertCurrent();
if (o !== resolveMcpAppRequesterId(r)) throw new McpAppViewExpiredError();
};
try {
const e = await resolveMcpAppActiveView({
sessionKey: requireString(t, "sessionKey"),
agentId: resolveMcpAppSessionOwner(t, n.getRuntimeConfig()),
viewId: requireString(t, "viewId"),
requesterId: resolveMcpAppRequesterId(r),
cfg: n.getRuntimeConfig()
});
s?.assertCurrent();
const i = await withMcpAppActiveView(e, "read", async () => {
const { view: i } = e;
if (r?.connId) {
const t = modelContextSubscriptions.get(i) ?? /* @__PURE__ */ new Map();
const a = t.get(r.connId);
a?.();
if (a) i.disposeCallbacks?.delete(a);
if (t.size >= 32 && !t.has(r.connId)) throw new Error("MCP App connection limit reached");
const o = r.connId;
let s = getMcpAppModelContext(e.runtime, i)?.updateId;
const c = subscribeMcpAppModelContext(i, (e) => {
const t = s;
s = e?.updateId;
n.broadcastToConnIds("mcp.app.hostContextChanged", {
viewId: i.viewId,
...e === null ? {
modelContext: null,
updateId: t
} : {}
}, /* @__PURE__ */ new Set([o]));
});
const stop = () => {
c();
r.connectionSignal?.removeEventListener("abort", stop);
if (t.get(o) === stop) t.delete(o);
i.disposeCallbacks?.delete(stop);
};
r.connectionSignal?.addEventListener("abort", stop, { once: true });
t.set(o, stop);
modelContextSubscriptions.set(i, t);
i.disposeCallbacks ??= /* @__PURE__ */ new Set();
i.disposeCallbacks.add(stop);
if (r.connectionSignal?.aborted) stop();
}
const a = await supportsMcpAppInteraction(i);
const o = a && Boolean(e.runtime.sessionKey) && await canOpenMcpAppFiles(i);
const s = a && Boolean(e.runtime.sessionKey) && e.runtime.mcpAppModelContextRevoked !== true;
const c = n.getMcpAppSandboxPort?.() ?? await n.ensureSandboxHostPort?.();
if (c === void 0) throw new Error("MCP App sandbox listener is unavailable; restart the Gateway");
const l = r?.remoteControlUiIngress;
const u = l?.sandboxOrigin ?? n.getRuntimeConfig().mcp?.apps?.sandboxOrigin;
let d = void 0;
try {
d = createMcpAppStandaloneTicket({
sessionKey: requireString(t, "sessionKey"),
view: i,
toolOperationsAuthorized: authorizeOperatorScopesForMethod("mcp.app.callTool", r?.connect?.scopes ?? []).allowed
});
} catch (e) {
logWarn(`mcp-app: standalone ticket unavailable: ${formatErrorMessage(e)}`);
}
assertRequestCurrent();
return {
sandboxUrl: l ? new URL(buildMcpAppSandboxPath(i.csp), l.sandboxOrigin).href : buildMcpAppSandboxPath(i.csp),
sandboxPort: c,
...u ? { sandboxOrigin: new URL(u).origin } : {},
html: i.html,
...i.csp ? { csp: i.csp } : {},
toolInput: i.toolInput,
toolResult: i.toolResult,
hostContext: {
"openai/modelContext": getMcpAppModelContext(e.runtime, i),
...i.deepLink ? { "openai/deepLink": i.deepLink } : {}
},
...i.displayModes ? { displayModes: i.displayModes } : {},
...i.displayMode ? { displayMode: i.displayMode } : {},
richModelContextSupported: s && i.richModelContextSupported !== false,
fileResourcesSupported: a && Boolean(i.hostFile),
openFilesSupported: o,
...d ? {
standaloneUrl: d.url,
standaloneExpiresAtMs: d.expiresAtMs
} : {},
messageSupported: a,
updateModelContextSupported: s
};
});
assertRequestCurrent();
return i;
} finally {
s?.release();
}
}),
"mcp.app.updateModelContext": mcpAppHandler(async (e) => {
const { params: t } = e;
const n = await resolveRequestedMcpAppView(e);
return await withMcpAppActiveView(n, "read", async () => {
await requireMcpAppInteraction(n.view);
return updateMcpAppModelContext(n.runtime, n.view, t);
});
}),
"mcp.app.modelContext": mcpAppHandler(async (e) => {
const t = await resolveRequestedMcpAppView(e);
await requireMcpAppInteraction(t.view);
return { state: getMcpAppModelContext(t.runtime, t.view) };
}),
"mcp.app.removeModelContext": mcpAppHandler(async (e) => {
const { params: t } = e;
const n = await resolveRequestedMcpAppView(e);
await requireMcpAppInteraction(n.view);
if (t.index !== void 0 && typeof t.index !== "number") throw new Error("index must be a number");
return { state: removeMcpAppModelContextItem(n.runtime, n.view, requireString(t, "updateId"), t.index) };
}),
"mcp.app.writeResource": hostFileHandler((e, t) => writeMcpAppHostFile(e, t, e.params)),
"mcp.app.subscribeResource": hostFileHandler((e, t) => subscribeMcpAppHostFile(e, t, requireString(e.params, "uri"), true)),
"mcp.app.unsubscribeResource": hostFileHandler((e, t) => subscribeMcpAppHostFile(e, t, requireString(e.params, "uri"), false)),
"mcp.app.openFile": hostFileHandler((e, t) => openMcpAppFile(e, t, requireString(e.params, "path"))),
"mcp.app.callTool": operationHandler((e) => ({
method: "tools/call",
params: {
name: requireString(e, "toolName"),
arguments: optionalRecord(e, "arguments") ?? {}
}
})),
"mcp.app.listTools": operationHandler((e) => ({
method: "tools/list",
params: optionalCursor(e) ?? {}
})),
"mcp.app.listResources": operationHandler((e) => ({
method: "resources/list",
params: optionalCursor(e) ?? {}
})),
"mcp.app.listResourceTemplates": operationHandler((e) => ({
method: "resources/templates/list",
params: optionalCursor(e) ?? {}
})),
"mcp.app.readResource": operationHandler((e) => ({
method: "resources/read",
params: {
uri: requireString(e, "uri"),
_meta: optionalRecord(e, "_meta")
}
}))
};
//#endregion
export { mcpAppHandlers };