Skip to content

Open source CapCut alternative.

TypeScript

fix(app): give the Cut AI chat its editor tools reliably [rebuild]

David Le03f1a296767f
diff --git a/site/src/cut/engine/main.ts b/site/src/cut/engine/main.ts
index 04e153a4..d83a3995 100644
--- a/site/src/cut/engine/main.ts
+++ b/site/src/cut/engine/main.ts
@@ -5,8 +5,8 @@
* are computed at module load time), then dispatches:
*
* donkey-cut-engine serve the Cut API on 127.0.0.1
- * donkey-cut-engine mcp-proxy <base> <key> stdio MCP proxy (spawned by the
- * engine itself for AI chats)
+ * donkey-cut-engine mcp-proxy <base> <key> <user> stdio MCP proxy (spawned
+ * by the engine itself for AI chats)
*/
process.env.DONKEY_CUT_ENGINE ??= "1";
@@ -16,7 +16,7 @@ void (async () => {
if (cmd === "mcp-proxy") {
const { engineBaseUrl } = await import("./config");
const { runMcpProxy } = await import("../server/ai/mcp-proxy-core.mjs");
- runMcpProxy(rest[0] ?? engineBaseUrl(), rest[1] ?? "");
+ runMcpProxy(rest[0] ?? engineBaseUrl(), rest[1] ?? "", rest[2] ?? "");
return;
}
await import("./serve");
diff --git a/site/src/cut/server/ai/bridge.ts b/site/src/cut/server/ai/bridge.ts
index 1ebd4ca9..353487d2 100644
--- a/site/src/cut/server/ai/bridge.ts
+++ b/site/src/cut/server/ai/bridge.ts
@@ -53,6 +53,12 @@ export function callBrowserTool(
): Promise<{ output?: unknown; errorText?: string }> {
const session = sessions.get(sessionKey);
if (!session) {
+ // The proxy called with a key no open chat stream is registered under — a
+ // stale/mismatched session. Log which keys ARE live so a recurrence pins
+ // the drift instead of only surfacing to the model as "unreachable".
+ console.warn(
+ `[cut-ai] ${toolName}: no live editor session for ${sessionKey}; live: ${[...sessions.keys()].join(", ") || "none"}`
+ );
return Promise.resolve({ errorText: "No live editor session for this chat." });
}
const toolCallId = crypto.randomUUID().slice(0, 12);
@@ -61,6 +67,7 @@ export function callBrowserTool(
const timer = setTimeout(() => {
session.waiters.delete(toolCallId);
const errorText = `The editor did not answer the ${toolName} call in time.`;
+ console.warn(`[cut-ai] ${toolName}: editor tab did not answer within ${TOOL_TIMEOUT_MS}ms (session ${sessionKey})`);
session.writer.write({ type: "tool-output-error", toolCallId, errorText });
resolve({ errorText });
}, TOOL_TIMEOUT_MS);
diff --git a/site/src/cut/server/ai/catalog.ts b/site/src/cut/server/ai/catalog.ts
index 9c6e892b..5ddca51e 100644
--- a/site/src/cut/server/ai/catalog.ts
+++ b/site/src/cut/server/ai/catalog.ts
@@ -772,7 +772,7 @@ export function systemPrompt(): string {
Rules:
- First decide what the user wants handed back: an edit to the project, or words in chat. "Give me / write me a prompt, script, caption, ideas, a translation" asks for the text itself — write it in chat and leave the project untouched, even though a tool could act on it; they'll say "do it" or "add it" when they want it applied (and a follow-up like "in Korean" or "shorter" revises the text, keeping the same deliverable). A complaint or observation ("ugh, this is cluttered") is words too: sympathize, offer what you could do, and touch nothing until they say go. When they do ask for a change to the project, act directly with tools; don't describe steps they should click through unless they ask how.
-- Use ids exactly as given in the state, and act on what your tools return — each reports what it changed, so batch independent edits into one step and call get_state only when the snapshot is stale or a result surprised you.
+- Use ids exactly as given in the state, and act on what your tools return — each reports what it changed, so batch independent edits into one step and call get_state only when the snapshot is stale or a result surprised you. A tool that comes back "unreachable" or "no live editor session" is a dropped bridge, not a limit and not your request's fault — the editor never received the call, so quietly make the same call once more before doing anything else, and never tell the user to reconnect or restart the editor.
- When the user says "this" (this clip, this text), they mean the current selection.
- Keep replies short and concrete — one or two sentences about what you did, in that warm, lightly funny voice. You have no name and never name the app; a message that asks for nothing (a greeting, thanks) gets a short "How can I help?" / "What would you like to do?" back — words alone, no tool calls. No headings, no fluff, and never paste the editor_state snapshot or raw JSON back — say what it means in plain words (a failed render: name the error and offer to retry).
- Edits are undoable (unlimited undo), so prefer doing over asking; only ask when the request is genuinely ambiguous. The existing cut is the user's work: adding media adds — never delete, trim, or reorder clips already on the timeline unless that's what they asked for. Generation is different: undo removes the clip but the credits stay spent, so be certain the user asked for the media before calling a generation tool. Removing media is different too — delete_asset and library_organize deletes don't come back with undo, so they take an explicit ask naming the media.
diff --git a/site/src/cut/server/ai/mcp-proxy-core.mjs b/site/src/cut/server/ai/mcp-proxy-core.mjs
index 0a5991f9..a895944f 100644
--- a/site/src/cut/server/ai/mcp-proxy-core.mjs
+++ b/site/src/cut/server/ai/mcp-proxy-core.mjs
@@ -9,7 +9,12 @@
* Two launchers share this core: mcp-proxy.mjs (dev, spawned by file path
* with node) and the engine binary's `mcp-proxy` subcommand.
*/
-export function runMcpProxy(BASE = "http://localhost:3000", SESSION = "") {
+export function runMcpProxy(BASE = "http://localhost:3000", SESSION = "", USER = "") {
+ // Every Cut data route runs inside a user scope keyed by the `u` param; the
+ // proxy inherits the chatting account's id so its own tools/list and
+ // tools/call land in that same scope instead of 400ing as out-of-scope.
+ const scoped = (path) =>
+ USER ? `${path}${path.includes("?") ? "&" : "?"}u=${encodeURIComponent(USER)}` : path;
let buffer = "";
process.stdin.setEncoding("utf8");
process.stdin.on("data", (chunk) => {
@@ -27,6 +32,31 @@ export function runMcpProxy(BASE = "http://localhost:3000", SESSION = "") {
process.stdout.write(JSON.stringify(msg) + "\n");
}
+ const log = (line) => process.stderr.write(`[cut-mcp] ${line}\n`);
+
+ /**
+ * Fetch that rides out a transient blip reaching the engine (a dev-server
+ * recompile, an engine restart) instead of failing the whole call. Only for
+ * idempotent requests: a retried tools/call could double-run a paid render,
+ * so callers pass retry:true only for tools/list.
+ */
+ async function fetchEngine(url, init, label, retry) {
+ const attempts = retry ? 3 : 1;
+ let lastErr;
+ for (let i = 1; i <= attempts; i++) {
+ try {
+ const res = await fetch(url, init);
+ if (res.ok) return res;
+ lastErr = new Error(`HTTP ${res.status}`);
+ } catch (err) {
+ lastErr = err instanceof Error ? err : new Error(String(err));
+ }
+ log(`${label} attempt ${i}/${attempts} failed: ${lastErr.message}`);
+ if (i < attempts) await new Promise((r) => setTimeout(r, 150 * i));
+ }
+ throw lastErr;
+ }
+
async function handle(line) {
let req;
try {
@@ -51,19 +81,28 @@ export function runMcpProxy(BASE = "http://localhost:3000", SESSION = "") {
} else if (method === "ping") {
reply({});
} else if (method === "tools/list") {
- const res = await fetch(`${BASE}/api/cut/ai/proxy?type=catalog`);
+ // Idempotent: retry so a momentary hiccup can't leave the model with an
+ // empty tool set (which reads to it as "editing tools aren't reachable").
+ const res = await fetchEngine(`${BASE}${scoped("/api/cut/ai/proxy?type=catalog")}`, undefined, "tools/list", true);
const { tools } = await res.json();
reply({ tools });
} else if (method === "tools/call") {
- const res = await fetch(`${BASE}/api/cut/ai/proxy`, {
- method: "POST",
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify({
- sessionKey: SESSION,
- name: params?.name,
- args: params?.arguments ?? {},
- }),
- });
+ // No retry: the call may already have run on the editor by the time the
+ // response is lost, and re-running a generation tool would double-charge.
+ const res = await fetchEngine(
+ `${BASE}${scoped("/api/cut/ai/proxy")}`,
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ sessionKey: SESSION,
+ name: params?.name,
+ args: params?.arguments ?? {},
+ }),
+ },
+ `tools/call ${params?.name}`,
+ false
+ );
const body = await res.json();
reply(body); // { content: [...], isError? } — already MCP-shaped
} else if (id !== undefined) {
diff --git a/site/src/cut/server/ai/mcp-proxy.mjs b/site/src/cut/server/ai/mcp-proxy.mjs
index 5c489b87..f463e29b 100644
--- a/site/src/cut/server/ai/mcp-proxy.mjs
+++ b/site/src/cut/server/ai/mcp-proxy.mjs
@@ -4,9 +4,9 @@
* the Next dev server. The engine binary launches the same core via its
* `mcp-proxy` subcommand instead.
*
- * usage: node mcp-proxy.mjs <baseUrl> <sessionKey>
+ * usage: node mcp-proxy.mjs <baseUrl> <sessionKey> <userId>
*/
import { runMcpProxy } from "./mcp-proxy-core.mjs";
-const [, , BASE, SESSION] = process.argv;
-runMcpProxy(BASE, SESSION);
+const [, , BASE, SESSION, USER] = process.argv;
+runMcpProxy(BASE, SESSION, USER);
diff --git a/site/src/cut/server/http/ai.ts b/site/src/cut/server/http/ai.ts
index ee936557..e145dc9b 100644
--- a/site/src/cut/server/http/ai.ts
+++ b/site/src/cut/server/http/ai.ts
@@ -14,6 +14,7 @@ import {
import { rewriteCaptions, translateCaptions } from "../ai/captions";
import { writeVisualCues, type VisualFrame } from "../ai/visualSubtitles";
import { AI_SKILL_INDEX, AI_SKILLS, AI_TOOLS, attachedAssetsBlock, systemPrompt } from "../ai/catalog";
+import { currentCutUser } from "../userScope";
interface ChatBody {
messages: UIMessage[];
@@ -29,11 +30,14 @@ const proxyPath = () =>
path.join(process.cwd(), "src", "cut", "server", "ai", "mcp-proxy.mjs");
/** How to spawn the MCP proxy. The engine binary spawns itself with its
- * mcp-proxy subcommand; the dev server spawns node on the proxy source. */
-function mcpCommand(base: string, sessionKey: string): { command: string; args: string[] } {
+ * mcp-proxy subcommand; the dev server spawns node on the proxy source. The
+ * account id rides along so the proxy's own engine calls carry the `u` scope
+ * every data route requires — without it tools/list 400s and the model, left
+ * with no editor tools, narrates tool calls as raw XML instead. */
+function mcpCommand(base: string, sessionKey: string, user: string): { command: string; args: string[] } {
return process.env.DONKEY_CUT_ENGINE
- ? { command: process.execPath, args: ["mcp-proxy", base, sessionKey] }
- : { command: process.execPath, args: [proxyPath(), base, sessionKey] };
+ ? { command: process.execPath, args: ["mcp-proxy", base, sessionKey, user] }
+ : { command: process.execPath, args: [proxyPath(), base, sessionKey, user] };
}
function lastUserText(messages: UIMessage[]): string {
@@ -66,6 +70,7 @@ async function runClaude(
body: ChatBody,
base: string,
sessionKey: string,
+ user: string,
signal: AbortSignal
) {
const q = query({
@@ -83,13 +88,20 @@ async function runClaude(
mcpServers: {
cut: {
type: "stdio",
- ...mcpCommand(base, sessionKey),
+ ...mcpCommand(base, sessionKey, user),
alwaysLoad: true,
},
},
allowedTools: ["mcp__cut"],
permissionMode: "dontAsk",
settingSources: [], // don't drag the user's CLAUDE.md/settings into app chats
+ // The editor MCP is the whole tool surface. settingSources:[] only drops
+ // filesystem config — the SDK still auto-fetches the account's claude.ai
+ // cloud connectors (Gmail, Drive, …) and surfaces them to the model.
+ // These two flags make the isolation total: no connectors, and no MCP
+ // server except the one we pass here.
+ strictMcpConfig: true,
+ settings: { disableClaudeAiConnectors: true },
includePartialMessages: true,
maxTurns: 30,
cwd: os.tmpdir(),
@@ -104,6 +116,16 @@ async function runClaude(
for await (const msg of q) {
const m = msg as unknown as Record<string, unknown> & { type: string };
if (m.type === "system" && m.subtype === "init") {
+ // The editor MCP is the assistant's entire tool surface. If it didn't
+ // bind (an engine hiccup, an out-of-scope proxy call), the model would
+ // improvise by narrating tool calls as raw XML — surface a clear error
+ // instead of letting that reach the user.
+ const tools = Array.isArray(m.tools) ? (m.tools as unknown[]) : [];
+ if (!tools.some((t) => typeof t === "string" && t.startsWith("mcp__cut"))) {
+ emit({ type: "error", errorText: "The editor tools didn't load. Reload the tab and try again." });
+ await q.interrupt().catch(() => {});
+ break;
+ }
emit({ type: "data-session", data: { providerSession: m.session_id }, transient: true });
} else if (m.type === "stream_event") {
const ev = m.event as {
@@ -138,9 +160,10 @@ async function runCodex(
body: ChatBody,
base: string,
sessionKey: string,
+ user: string,
signal: AbortSignal
) {
- const mcp = mcpCommand(base, sessionKey);
+ const mcp = mcpCommand(base, sessionKey, user);
const args = ["exec"];
if (body.providerSession) args.push("resume", body.providerSession);
args.push(
@@ -336,6 +359,7 @@ export const aiApi = {
async chat(req: Request) {
const body = (await req.json()) as ChatBody;
const base = new URL(req.url).origin;
+ const user = currentCutUser();
const sessionKey = crypto.randomUUID();
const userText = lastUserText(body.messages);
const attachments = lastUserAttachments(body.messages);
@@ -351,11 +375,11 @@ export const aiApi = {
emit({ type: "data-session", data: { sessionKey }, transient: true });
try {
if (body.model.startsWith("claude")) {
- await runClaude(emit, prompt, body, base, sessionKey, req.signal);
+ await runClaude(emit, prompt, body, base, sessionKey, user, req.signal);
} else if (body.model === "cut-test") {
await runFake(emit, sessionKey, userText);
} else {
- await runCodex(emit, prompt, body, base, sessionKey, req.signal);
+ await runCodex(emit, prompt, body, base, sessionKey, user, req.signal);
}
} catch (err) {
emit({ type: "error", errorText: err instanceof Error ? err.message : String(err) });
diff --git a/site/src/cut/server/userScope.ts b/site/src/cut/server/userScope.ts
index 19ff32e2..d9e9aab7 100644
--- a/site/src/cut/server/userScope.ts
+++ b/site/src/cut/server/userScope.ts
@@ -28,9 +28,15 @@ export function runWithCutUser<T>(id: string, fn: () => T): T {
/** The current request's per-user data root. Path helpers build on this, so a
* path outside a user scope is impossible by construction. */
export function cutUserRoot(): string {
+ return path.join(cutDataRoot(), "users", currentCutUser());
+}
+
+/** The account id bound to the current request. The AI chat threads it into the
+ * spawned MCP proxy so the proxy's own engine calls stay in the same scope. */
+export function currentCutUser(): string {
const id = scope.getStore();
if (!id) throw new Error("No user scope bound to this request.");
- return path.join(cutDataRoot(), "users", id);
+ return id;
}
// Data written before user scoping lived directly under the data root. The