openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
353 lines (352 loc) • 13.9 kB
JavaScript
import { a as resolveGlobalSingleton } from "./global-singleton-D7yf05nR.mjs";
import { Fn as object, Jn as string, Nt as array, Pn as number, Yt as discriminatedUnion, xn as literal } from "./schemas-Cy6abvsu.mjs";
import { a as captureAgentQuestionAnswerAuthority } from "./host-private-capabilities-DDumj0c_.mjs";
import { t as captureSessionEntryMetadataRead } from "./session-entry-source-authority-Bxiv7qVT.mjs";
import { a as readGatewayRequestMutationAuthority } from "./session-mutation-guards-Bjnk_O0z.mjs";
import { n as registerMcpFormResourceOwner, r as requireMcpFormQuestion } from "./mcp-form-resource-context-CZnlvKdp.mjs";
import { c as releaseMcpAppView, r as fetchMcpAppView } from "./mcp-ui-resource-3UHFH-eE.mjs";
import { t as createWorkspaceUploadBatch } from "./workspace-fs-e2DnPT_x.mjs";
import { n as compileStructuredInputForm, o as snapshotStructuredInput } from "./structured-input-DSYgb17h.mjs";
import { l as resolveMcpAppRequesterId, n as callMcpAppToolWithElicitation } from "./mcp-app-operations-Qv9yxlnB.mjs";
import { a as captureGatewayClientUploadCommitGuard } from "./upload-policy-Dp8z9OKP.mjs";
import { t as canSelectQuestion } from "./question-access-BorgbRXn.mjs";
import { r as readArtifactBase64Payload } from "./artifacts-base64-CVAZQm44.mjs";
import { a as withPreparedQuestionSessions, t as prepareQuestionAuthorization } from "./question-session-access-BfSx_moX.mjs";
import { t as retainSessionScopedRead } from "./session-scoped-read-D2_BUoMM.mjs";
import { r as withSessionFileRoot } from "./sessions-files-FYGHboLZ.mjs";
import { pathToFileURL } from "node:url";
import path from "node:path";
import { randomUUID } from "node:crypto";
import { ReadResourceResultSchema } from "@modelcontextprotocol/core";
//#region src/gateway/mcp-app-form-resources.ts
const forms = resolveGlobalSingleton(Symbol.for("openclaw.mcpFormResourceBindings"), () => /* @__PURE__ */ new WeakMap());
const MAX_UPLOAD_BYTES = 5242880;
const routingSchema = object({
sessionKey: string().min(1),
agentId: string().min(1).optional(),
viewId: string().min(1).max(128),
requestId: string().min(1).max(256),
questionId: string().min(1).max(256)
});
const actionSchema = discriminatedUnion("action", [object({
action: literal("preview"),
optionIndex: number().int().min(0).max(63)
}).strict(), object({
action: literal("upload"),
files: array(object({
name: string().min(1).max(255),
mimeType: string().max(256),
content: string().max(Math.ceil(MAX_UPLOAD_BYTES / 3) * 4 + 4),
relativePath: string().min(1).max(2048).optional()
}).strict()).min(1).max(64)
}).strict()]);
async function createMcpAppFormResourceContext(e) {
e.signal.throwIfAborted();
e.origin.assertCurrent();
const t = snapshotStructuredInput(e.snapshot, { richForm: true });
if (!t || typeof t !== "object" || Array.isArray(t)) throw new Error("Invalid rich form snapshot");
const n = captureAgentQuestionAnswerAuthority(e.origin.sessionKey);
if (e.origin.requesterId !== void 0 && n?.requesterProfileId !== void 0 && e.origin.requesterId !== n.requesterProfileId) throw new Error("MCP form requester does not match its question creator");
const r = {
...e.origin,
requesterId: e.origin.requesterId ?? n?.requesterProfileId
};
const i = "mcp-form-" + randomUUID();
let a = true;
let unregister = () => {};
const o = /* @__PURE__ */ new Map();
const s = /* @__PURE__ */ new Set();
const assertCurrent = () => {
e.signal.throwIfAborted();
if (!a) throw new Error("MCP form origin was retired");
r.assertCurrent();
n?.assertActive();
r.runtime.assertOwnerCurrent?.();
};
const dispose = () => {
if (!a) return;
a = false;
unregister();
e.signal.removeEventListener("abort", dispose);
for (const e of s) releaseMcpAppView(e, r.runtime);
s.clear();
o.clear();
d.pending.clear();
forms.delete(d);
};
const c = {
viewId: i,
uploads: e.uploadResources !== void 0,
previews: r.runtime.readResource !== void 0,
isUploadedResource: (e, t) => {
try {
assertCurrent();
return o.get(e)?.has(t) === true;
} catch {
return false;
}
}
};
const l = compileStructuredInputForm({
schema: t.requestedSchema,
message: typeof t.message === "string" ? t.message : void 0,
fallbackMessage: "MCP server needs input",
options: {
protocolName: "OpenAI",
allowRichForms: true,
resourceContext: c,
allowEmptyForm: true,
minimumChoiceCount: 1,
allowEnumNames: true
}
});
if (l.kind !== "ready" || l.plan.kind !== "form") throw new Error(l.kind === "unsupported" ? l.message : "Invalid resource form");
const u = new Map(l.plan.fields.map((e) => [e.question.id, e.question]));
if (!r.prepareToolCall && [...u.values()].some((e) => e.options?.some((e) => e.preview?.type === "mcp_app_tool"))) throw new Error("Form App previews require an originating tool authority hook");
const d = {
sessionKey: r.sessionKey,
agentId: r.agentId,
assertCurrent,
questions: u,
pending: /* @__PURE__ */ new Map(),
dispose
};
forms.set(d, {
origin: r,
uploaded: o,
uploadResources: e.uploadResources,
previewViews: s,
owner: d,
signal: e.signal,
operations: 0,
activeOperations: 0,
uploadedBytes: 0,
uploadedFiles: 0
});
unregister = registerMcpFormResourceOwner(i, d);
e.signal.addEventListener("abort", dispose, { once: true });
if (e.signal.aborted) {
dispose();
e.signal.throwIfAborted();
}
return {
context: c,
dispose
};
}
function acceptsFile(e, t) {
if (!t?.length) return true;
const n = e.name.toLowerCase();
const r = e.mimeType.toLowerCase().split(";", 1)[0];
return t.some((e) => {
const t = e.toLowerCase();
return t.startsWith(".") ? n.endsWith(t) : t.endsWith("/*") ? r.startsWith(t.slice(0, -1)) : r === t;
});
}
/** UI selectors choose only a live owner record; they never supply targets or restrictions. */
async function executeMcpAppFormResource(e) {
const { sessionKey: t, agentId: n, viewId: r, requestId: i, questionId: a, ...o } = e.params;
const s = routingSchema.parse({
sessionKey: t,
agentId: n,
viewId: r,
requestId: i,
questionId: a
});
const c = {
...s,
...actionSchema.parse(o)
};
const l = e.context.questionManager;
if (!l || !canSelectQuestion(l, c.requestId, e.client)) throw new Error("Question was not found");
const u = l.get(c.requestId);
const d = u ? l.observe(u.id, u) : null;
const f = u?.questions.find((e) => e.questionId === c.questionId);
if (!u || u.status !== "pending" || !d || !f || !u.agentId || u.sessionKey !== c.sessionKey || c.agentId && c.agentId !== u.agentId || f.resource?.viewId !== c.viewId) throw new Error("Question resource is not pending for this session");
const p = requireMcpFormQuestion({
...s,
agentId: u.agentId,
question: f,
record: u
});
const m = forms.get(p);
if (!m || resolveMcpAppRequesterId(e.client) !== m.origin.requesterId) throw new Error("Question resource is not owned by this requester");
if (m.operations >= 120 || m.activeOperations >= 4) throw new Error("MCP form resource request limit reached");
m.operations += 1;
m.activeOperations += 1;
let h;
try {
const t = readGatewayRequestMutationAuthority(e);
h = await retainSessionScopedRead(e, u.sessionKey, u.agentId);
const n = prepareQuestionAuthorization(e, d, u.id, c.action === "upload" ? "mutate" : "read");
const assertCurrent = () => {
t.assertCurrent();
e.sessionMutationAuthorization?.assertCurrent();
h?.assertCurrent();
p.assertCurrent();
if (e.context.getRuntimeConfig().mcp?.apps?.enabled !== true) throw new Error("MCP App runtime is unavailable");
if (l.get(u.id) !== u || !d.isCurrent() || u.status !== "pending" || resolveMcpAppRequesterId(e.client) !== m.origin.requesterId || p.pending.get(u.id)?.record !== u) throw new Error("Question resource authority expired");
};
await withPreparedQuestionSessions(e, [n.target], ([e]) => {
const t = n.authorize(e);
if (t) throw new Error(t.message);
}, { assertCurrent });
assertCurrent();
if (c.action === "preview") return await preview(m, e, f, c.optionIndex, assertCurrent);
const r = f.resource?.userOptions;
if (!r || !m.uploadResources) throw new Error("This question does not permit uploads");
const i = captureGatewayClientUploadCommitGuard({
method: "mcp.app.formResource",
requestParams: e.params,
client: e.client,
context: e.context
});
i?.();
let a = 0;
const o = c.files.map((e) => {
if (!acceptsFile(e, r.accept)) throw new Error("File does not match this question’s upload restrictions");
const t = readArtifactBase64Payload(e.content, { includeData: true });
if (!t?.data && e.content !== "") throw new Error("Invalid upload encoding");
a += t?.sizeBytes ?? 0;
if (a > MAX_UPLOAD_BYTES) throw new Error("Form upload exceeds the byte limit");
return {
name: e.name,
mimeType: e.mimeType,
data: Buffer.from(t?.data ?? "", "base64"),
relativePath: e.relativePath || void 0
};
});
if (m.uploadedBytes + a > MAX_UPLOAD_BYTES || m.uploadedFiles + o.length > 64) throw new Error("MCP form upload budget exceeded");
m.uploadedBytes += a;
m.uploadedFiles += o.length;
const s = await m.uploadResources({
options: e,
kind: r.kind,
files: o,
assertCurrent: () => {
assertCurrent();
i?.();
}
});
assertCurrent();
i?.();
if (!s.length || s.length > 64 || s.some((e) => !e.name || !URL.canParse(e.uri))) throw new Error("Upload provider returned invalid resources");
const g = m.uploaded.get(f.questionId) ?? /* @__PURE__ */ new Set();
for (const e of s) g.add(e.uri);
m.uploaded.set(f.questionId, g);
return { resources: s };
} finally {
m.activeOperations -= 1;
h?.release();
}
}
async function preview(e, t, n, r, i) {
const a = n.options[r]?.preview;
if (!a) throw new Error("This option has no preview");
const { origin: o } = e;
if (a.type === "resource_link") {
if (!o.runtime.readResource) throw new Error("Originating server cannot read resources");
const e = ReadResourceResultSchema.parse(await o.runtime.readResource(o.serverName, a.uri));
i();
if (JSON.stringify(e.contents).length > MAX_UPLOAD_BYTES * 2) throw new Error("Resource preview exceeds the byte limit");
return { preview: { contents: e.contents.map((e) => "text" in e ? {
mimeType: e.mimeType || void 0,
text: e.text
} : {
mimeType: e.mimeType || void 0,
blob: e.blob
}) } };
}
const s = await o.runtime.getCatalog();
i();
const c = s.tools.find((e) => e.serverName === o.serverName && e.toolName === a.name);
if (!c?.uiResourceUri || c.excludedFromOpenClawCatalog || c.deniedBySession || !o.prepareToolCall) throw new Error("Preview App tool is unavailable");
const l = a.arguments ?? {};
const u = await o.prepareToolCall({
options: t,
toolName: a.name,
input: l,
assertCurrent: i,
signal: e.signal
});
const assertExecutionCurrent = () => {
i();
if (u) u();
};
const d = await callMcpAppToolWithElicitation({
options: t,
origin: o,
toolName: a.name,
input: l,
assertCurrent: assertExecutionCurrent,
signal: e.signal,
uploadResources: e.uploadResources
});
assertExecutionCurrent();
if (d.isError) throw new Error("Preview App tool failed");
const f = await fetchMcpAppView({
runtime: o.runtime,
agentId: o.agentId,
serverName: o.serverName,
toolName: a.name,
uiResourceUri: c.uiResourceUri,
toolInput: l,
toolResult: d,
requesterId: o.requesterId,
allowedAppToolNames: new Set(s.tools.filter((e) => e.serverName === o.serverName && !e.excludedFromOpenClawCatalog && !e.deniedBySession && (e.uiVisibility === void 0 || e.uiVisibility.includes("app"))).map((e) => e.toolName)),
prepareToolCall: o.prepareToolCall,
uploadResources: e.uploadResources,
authorizeAppInteraction: () => {
e.owner.assertCurrent();
return true;
}
});
if (!f) throw new Error("Preview App resource is unavailable");
e.previewViews.add(f.viewId);
i();
return { preview: { viewId: f.viewId } };
}
/** Only a host adapter that proved this originating server can read the local workspace may opt in. */
function createMcpAppWorkspaceUploadProvider(e) {
const t = captureSessionEntryMetadataRead(e, e.assertCurrent);
const n = t?.readCurrent();
return async (r) => withSessionFileRoot(e, r.options.context.getRuntimeConfig(), async (i, a, o) => {
const assertCurrent = () => {
e.assertCurrent();
a();
t?.assertCurrent();
r.assertCurrent();
if (t) {
const e = t.readCurrent();
if (e?.sessionId !== n?.sessionId || e?.lifecycleRevision !== n?.lifecycleRevision) throw new Error("Form upload session generation changed");
}
const s = t ? t.readCurrent() : o();
if (!s || s.execNode || i.root !== e.workspaceDir) throw new Error("Form upload workspace authority changed");
i.fileWorkspace?.assertCurrent(r.options.context.getRuntimeConfig(), s);
};
const s = r.files.map((e) => {
if (e.name.includes("/") || e.name.includes("\\") || e.name === "." || e.name === "..") throw new Error("Invalid upload filename");
const t = r.kind === "directory" ? e.relativePath : e.name;
if (!t || r.kind === "directory" && t.split("/").length < 2 || r.kind === "file" && e.relativePath) throw new Error("Upload does not match the field’s file/directory mode");
return {
relativePath: t,
data: e.data
};
});
const c = await createWorkspaceUploadBatch({
rootDir: e.workspaceDir,
files: s,
assertCurrent
});
if (r.kind === "file") return c.paths.map((e, t) => ({
uri: pathToFileURL(e).href,
name: r.files[t].name
}));
return [...new Set(s.map((e) => e.relativePath.split("/")[0]))].map((e) => ({
uri: pathToFileURL(path.join(c.rootDir, e)).href,
name: e
}));
});
}
//#endregion
export { createMcpAppFormResourceContext, createMcpAppWorkspaceUploadProvider, executeMcpAppFormResource };