Skip to content

Write HTML. Render video. Built for agents.

fix(studio): tolerate WebMCP execute calls without an options object (#3860)

miga-heygen14b9e2039b69
diff --git a/packages/studio/src/webmcp/types.ts b/packages/studio/src/webmcp/types.ts
index 626ad61d17..dcf976f88d 100644
--- a/packages/studio/src/webmcp/types.ts
+++ b/packages/studio/src/webmcp/types.ts
@@ -57,8 +57,12 @@ export interface ModelContextTool {
* A rejection is NOT a usable error channel: the spec discards the reason and
* rejects the caller with a bare UnknownError. Resolve with a tagged failure
* instead. See `toolResult.ts`.
+ *
+ * `options` is optional here although the spec always passes it: the
+ * `@mcp-b/global` polyfill (through 5.1.0) calls `execute(input)` with no
+ * second argument, so a Studio handler must not depend on receiving one.
*/
- execute: (input: object, options: ToolExecuteCallbackOptions) => Promise<unknown>;
+ execute: (input: object, options?: ToolExecuteCallbackOptions) => Promise<unknown>;
annotations?: ModelContextToolAnnotations;
}
diff --git a/packages/studio/src/webmcp/useStudioAgentTools.polyfill.test.tsx b/packages/studio/src/webmcp/useStudioAgentTools.polyfill.test.tsx
new file mode 100644
index 0000000000..b9fa2b207f
--- /dev/null
+++ b/packages/studio/src/webmcp/useStudioAgentTools.polyfill.test.tsx
@@ -0,0 +1,219 @@
+// @vitest-environment jsdom
+/**
+ * Drives the write tools through the REAL `@mcp-b/global` package rather than
+ * a fake `document.modelContext`.
+ *
+ * The package invokes a registered `execute` with the input alone, on both of
+ * its paths: the in-page `BrowserMcpServer` wrapper that agents reach through
+ * the registry and `executeTool`, and the descriptor it mirrors into a native
+ * `document.modelContext` when the browser ships one. A Studio handler that
+ * destructured `{ signal }` from the missing second argument threw before it
+ * ran, so every write tool failed with "Cannot destructure property 'signal'
+ * of 'undefined'" while the read tools kept working. This file proves the fix
+ * against the code that ships in the polyfill chunk. The spec-shaped call and
+ * the abort path live in `useStudioAgentTools.test.tsx`; the polyfill cannot
+ * exercise them because it drops the caller's signal before the handler.
+ *
+ * A native-looking `modelContext` is installed BEFORE the import so the bridge
+ * wraps it and mirrors every registration into it, which is how both paths get
+ * covered from one setup. Its own file because the import is a one-shot side
+ * effect that the sibling suite's fake would otherwise have to fight.
+ */
+import { act } from "react";
+import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";
+import { mountReactHarness } from "../hooks/domSelectionTestHarness";
+import { mintElementHandle } from "./handles";
+import { useStudioAgentTools, type StudioAgentToolsDeps } from "./useStudioAgentTools";
+import { previewDoc, selectionFor, studioAgentToolsDeps } from "./webmcpTestUtils";
+
+vi.mock("../telemetry/client", () => ({ trackEvent: vi.fn() }));
+
+Reflect.set(globalThis, "IS_REACT_ACT_ENVIRONMENT", true);
+
+/** What a browser's own `registerTool` receives from the bridge. */
+interface MirroredTool {
+ name: string;
+ description: string;
+ execute: (input: object, options?: { signal?: AbortSignal }) => Promise<unknown>;
+}
+
+/** What `getTools()` returns and `executeTool()` accepts. */
+interface RegisteredTool {
+ name: string;
+ description: string;
+ window: Window;
+ origin: string;
+}
+
+/** The bridge's registry entry, as the reporter of the bug drove it. */
+interface BridgeToolEntry {
+ item: { name: string };
+ execute: (input: object, signal?: AbortSignal) => Promise<unknown>;
+}
+
+interface BridgeModelContext {
+ tools: Map<string, BridgeToolEntry>;
+ getTools(): Promise<RegisteredTool[]>;
+ executeTool(
+ tool: RegisteredTool,
+ inputArguments: string,
+ options?: { signal?: AbortSignal },
+ ): Promise<string | null>;
+}
+
+const mirrored: MirroredTool[] = [];
+/** Enough of a browser's `modelContext` for the bridge to wrap and mirror into. */
+const fakeNative = {
+ registerTool: async (tool: MirroredTool): Promise<void> => {
+ mirrored.push(tool);
+ },
+ // The bridge delegates `getTools()` to the native context when there is one,
+ // and its own `executeTool` then insists on a full `RegisteredTool`.
+ getTools: async (): Promise<RegisteredTool[]> =>
+ mirrored.map((tool) => ({
+ name: tool.name,
+ description: tool.description,
+ window,
+ origin: window.location.origin,
+ })),
+};
+
+let cleanup: (() => void) | null = null;
+
+beforeAll(async () => {
+ // Configurable, so the bridge is allowed to replace it with itself.
+ Object.defineProperty(document, "modelContext", {
+ value: fakeNative,
+ configurable: true,
+ writable: true,
+ });
+ await import("@mcp-b/global");
+ expect(Reflect.get(document, "modelContext")).not.toBe(fakeNative);
+});
+
+afterEach(async () => {
+ cleanup?.();
+ cleanup = null;
+ mirrored.length = 0;
+ // The polyfill watches the document with a MutationObserver that reads jsdom
+ // globals. Empty the document and let the observer settle now, while those
+ // globals still exist, instead of when vitest closes the window.
+ document.body.replaceChildren();
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ window.localStorage.clear();
+});
+
+function bridge(): BridgeModelContext {
+ // Through `unknown`: importing the package brings its own `Document.modelContext`
+ // typing into scope, and this file reads the bridge's non-standard surface.
+ return Reflect.get(document, "modelContext") as unknown as BridgeModelContext;
+}
+
+/** Registration is async, so wait for the whole tool set to land. */
+async function waitForTools(count: number): Promise<void> {
+ const deadline = Date.now() + 5_000;
+ while (bridge().tools.size !== count || mirrored.length !== count) {
+ if (Date.now() > deadline) {
+ throw new Error(
+ `expected ${count} tools, saw ${bridge().tools.size} in the bridge and ${mirrored.length} mirrored`,
+ );
+ }
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ }
+}
+
+function bridgeEntry(name: string): BridgeToolEntry {
+ const entry = [...bridge().tools.values()].find((candidate) => candidate.item.name === name);
+ if (!entry) throw new Error(`expected ${name} in the bridge registry`);
+ return entry;
+}
+
+function mirroredTool(name: string): MirroredTool {
+ const tool = mirrored.find((candidate) => candidate.name === name);
+ if (!tool) throw new Error(`expected ${name} to be mirrored into the native context`);
+ return tool;
+}
+
+/** Mount Studio's tools against a preview whose `#agent` element can be edited. */
+async function mountEditableAgent() {
+ const doc = previewDoc('<h1 id="agent">Agent</h1>');
+ const agent = doc.getElementById("agent") as HTMLElement;
+ const handle = mintElementHandle({
+ projectId: "demo",
+ domId: "agent",
+ sourceFile: "index.html",
+ activeCompositionPath: "index.html",
+ });
+ if (!handle) throw new Error("expected agent handle");
+ const setText = vi.fn(
+ async () =>
+ ({
+ ok: true,
+ persistence: { sourceFile: "index.html", version: '"sha256:after"', changed: true },
+ }) as const,
+ );
+ const deps: StudioAgentToolsDeps = studioAgentToolsDeps({
+ getPreviewDocument: () => doc,
+ buildSelection: async (element) => selectionFor(element),
+ setText,
+ });
+
+ function Probe() {
+ useStudioAgentTools(deps);
+ return null;
+ }
+ await act(async () => {
+ const root = mountReactHarness(<Probe />);
+ cleanup = () => act(() => root.unmount());
+ });
+ await waitForTools(12);
+ return { agent, handle, setText };
+}
+
+describe("useStudioAgentTools through @mcp-b/global", () => {
+ it("saves through studio_set_text when the in-page server calls execute with the input alone", async () => {
+ const { agent, handle, setText } = await mountEditableAgent();
+
+ // Registry entry, as `[...document.modelContext.tools.values()]` exposes it.
+ const viaEntry = await bridgeEntry("studio_set_text").execute(
+ { handle, text: "Through the registry" },
+ new AbortController().signal,
+ );
+ expect(viaEntry).toMatchObject({ ok: true, stage: "saved", changed: true });
+
+ // Chromium's `executeTool` extension, which the bridge also implements.
+ const descriptor = (await bridge().getTools()).find((tool) => tool.name === "studio_set_text");
+ if (!descriptor) throw new Error("expected studio_set_text in getTools()");
+ const viaExecuteTool = await bridge().executeTool(
+ descriptor,
+ JSON.stringify({ handle, text: "Through executeTool" }),
+ { signal: new AbortController().signal },
+ );
+ expect(JSON.parse(viaExecuteTool ?? "null")).toMatchObject({ ok: true, stage: "saved" });
+
+ expect(setText).toHaveBeenCalledTimes(2);
+ expect(setText).toHaveBeenCalledWith(
+ expect.objectContaining({ element: agent }),
+ "Through the registry",
+ "self",
+ );
+ });
+
+ it("saves through the descriptor the bridge mirrors into a native modelContext", async () => {
+ const { agent, handle, setText } = await mountEditableAgent();
+
+ // The browser would call this with `(input, { signal })`; the mirror drops
+ // the options before Studio's handler sees them.
+ const result = await mirroredTool("studio_set_text").execute(
+ { handle, text: "Through the native mirror" },
+ { signal: new AbortController().signal },
+ );
+
+ expect(result).toMatchObject({ ok: true, stage: "saved", changed: true });
+ expect(setText).toHaveBeenCalledWith(
+ expect.objectContaining({ element: agent }),
+ "Through the native mirror",
+ "self",
+ );
+ });
+});
diff --git a/packages/studio/src/webmcp/useStudioAgentTools.test.tsx b/packages/studio/src/webmcp/useStudioAgentTools.test.tsx
index 19b252ee32..55fb8bedac 100644
--- a/packages/studio/src/webmcp/useStudioAgentTools.test.tsx
+++ b/packages/studio/src/webmcp/useStudioAgentTools.test.tsx
@@ -6,8 +6,7 @@ import { writeStudioUiPreferences } from "../utils/studioUiPreferences";
import { mintElementHandle } from "./handles";
import { useStudioAgentTools, type StudioAgentToolsDeps } from "./useStudioAgentTools";
import type { ModelContext, ModelContextRegisterToolOptions, ModelContextTool } from "./types";
-import type { StudioLookSnapshot } from "./tools/lookTools";
-import { previewDoc, selectionFor } from "./webmcpTestUtils";
+import { lookSnapshot, previewDoc, selectionFor, studioAgentToolsDeps } from "./webmcpTestUtils";
const trackEvent = vi.hoisted(() => vi.fn());
vi.mock("../telemetry/client", () => ({ trackEvent }));
@@ -16,57 +15,6 @@ Reflect.set(globalThis, "IS_REACT_ACT_ENVIRONMENT", true);
let cleanup: (() => void) | null = null;
-function snapshot(overrides: Partial<StudioLookSnapshot> = {}): StudioLookSnapshot {
- return {
- projectId: "demo",
- compositionPath: "index.html",
- currentTime: 0,
- duration: 10,
- isPlaying: false,
- elements: [],
- scene: { status: "ready", items: [], drillInItem: null },
- selection: null,
- selectionAnimationCount: 0,
- history: { canUndo: false, canRedo: false, undoLabel: null, redoLabel: null },
- ...overrides,
- };
-}
-
-/** Full deps with inert defaults; override only what the test is about. */
-function deps(overrides: Partial<StudioAgentToolsDeps> = {}): StudioAgentToolsDeps {
- return {
- getSnapshot: () => snapshot(),
- getPreviewDocument: () => null,
- buildSelection: async () => null,
- applySelection: () => undefined,
- requestSeek: () => undefined,
- readPlayhead: () => ({ currentTime: 0, duration: 10, isPlaying: false }),
- getProjectId: () => "demo",
- getCompositionPath: () => "index.html",
- probeFrame: async () => ({ ok: true, status: 200 }),
- wait: async () => undefined,
- getCurrentSelection: () => null,
- getWriteBlockedReason: () => null,
- setText: async () => ({ ok: true }),
- setStyle: async () => ({ ok: true }),
- readBox: () => ({ x: 0, y: 0, width: 100, height: 50 }),
- moveTo: async () => undefined,
- resizeTo: async () => undefined,
- rotateTo: async () => undefined,
- addAnimation: async () => true,
- updateAnimation: async () => true,
- addKeyframe: async () => undefined,
- deleteAnimation: async () => true,
- getAnimationsForSelection: async () => [],
- getGsapDiagnostics: () => ({
- animations: [],
- multipleTimelines: false,
- unsupportedTimelinePattern: false,
- }),
- ...overrides,
- };
-}
-
async function executeRegistered<T>(
registered: ModelContextTool[],
name: string,
@@ -78,6 +26,17 @@ async function executeRegistered<T>(
return (await tool.execute(input, { signal })) as T;
}
+/** The call shape `@mcp-b/global` uses: the input and nothing else. */
+async function executeRegisteredWithoutOptions<T>(
+ registered: ModelContextTool[],
+ name: string,
+ input: object,
+): Promise<T> {
+ const tool = registered.find((candidate) => candidate.name === name);
+ if (!tool) throw new Error(`expected ${name} to be registered`);
+ return (await tool.execute(input)) as T;
+}
+
function mountedTargetDeps(overrides: Partial<StudioAgentToolsDeps> = {}) {
const doc = previewDoc('<h1 id="human">Human</h1><h1 id="agent">Agent</h1>');
const human = doc.getElementById("human") as HTMLElement;
@@ -93,7 +52,7 @@ function mountedTargetDeps(overrides: Partial<StudioAgentToolsDeps> = {}) {
agent,
agentHandle,
currentSelection: selectionFor(human),
- deps: deps({
+ deps: studioAgentToolsDeps({
getPreviewDocument: () => doc,
buildSelection: async (element) => selectionFor(element),
...overrides,
@@ -160,7 +119,7 @@ describe("useStudioAgentTools", () => {
const { registered } = installModelContext();
await act(async () => {
- mountTools(deps({ getSnapshot: () => snapshot() }));
+ mountTools(studioAgentToolsDeps({ getSnapshot: () => lookSnapshot() }));
});
expect(registered.map((tool) => tool.name)).toEqual([
@@ -188,13 +147,17 @@ describe("useStudioAgentTools", () => {
let harness: ReturnType<typeof mountTools> | null = null;
await act(async () => {
- harness = mountTools(deps({ getSnapshot: () => snapshot() }));
+ harness = mountTools(studioAgentToolsDeps({ getSnapshot: () => lookSnapshot() }));
});
expect(registerTool).toHaveBeenCalledTimes(12);
await act(async () => {
- harness?.rerenderWith(deps({ getSnapshot: () => snapshot({ currentTime: 5 }) }));
- harness?.rerenderWith(deps({ getSnapshot: () => snapshot({ currentTime: 6 }) }));
+ harness?.rerenderWith(
+ studioAgentToolsDeps({ getSnapshot: () => lookSnapshot({ currentTime: 5 }) }),
+ );
+ harness?.rerenderWith(
+ studioAgentToolsDeps({ getSnapshot: () => lookSnapshot({ currentTime: 6 }) }),
+ );
});
expect(registerTool).toHaveBeenCalledTimes(12);
@@ -207,11 +170,15 @@ describe("useStudioAgentTools", () => {
let harness: ReturnType<typeof mountTools> | null = null;
await act(async () => {
- harness = mountTools(deps({ getSnapshot: () => snapshot({ currentTime: 1 }) }));
+ harness = mountTools(
+ studioAgentToolsDeps({ getSnapshot: () => lookSnapshot({ currentTime: 1 }) }),
+ );
});
await act(async () => {
- harness?.rerenderWith(deps({ getSnapshot: () => snapshot({ currentTime: 42 }) }));
+ harness?.rerenderWith(
+ studioAgentToolsDeps({ getSnapshot: () => lookSnapshot({ currentTime: 42 }) }),
+ );
});
const result = await executeFirstRegistered<{
@@ -227,7 +194,7 @@ describe("useStudioAgentTools", () => {
const { registerTool } = installModelContext();
await act(async () => {
- mountTools(deps({ getSnapshot: () => snapshot() }));
+ mountTools(studioAgentToolsDeps({ getSnapshot: () => lookSnapshot() }));
});
const signal = registerTool.mock.calls[0]?.[1]?.signal;
expect(signal?.aborted).toBe(false);
@@ -242,7 +209,7 @@ describe("useStudioAgentTools", () => {
removeModelContext();
await act(async () => {
- mountTools(deps({ getSnapshot: () => snapshot() }));
+ mountTools(studioAgentToolsDeps({ getSnapshot: () => lookSnapshot() }));
});
// The assertion is that mounting did not throw; a browser without the
@@ -255,7 +222,7 @@ describe("useStudioAgentTools", () => {
const { registerTool } = installModelContext();
await act(async () => {
- mountTools(deps({ getSnapshot: () => snapshot() }));
+ mountTools(studioAgentToolsDeps({ getSnapshot: () => lookSnapshot() }));
});
expect(registerTool).not.toHaveBeenCalled();
@@ -265,7 +232,7 @@ describe("useStudioAgentTools", () => {
const { registerTool } = installModelContext();
await act(async () => {
- mountTools(deps({ getSnapshot: () => snapshot() }));
+ mountTools(studioAgentToolsDeps({ getSnapshot: () => lookSnapshot() }));
});
expect(registerTool).toHaveBeenCalledTimes(12);
@@ -276,7 +243,7 @@ describe("useStudioAgentTools", () => {
registerTool.mockRejectedValue(new DOMException("blocked", "NotAllowedError"));
await act(async () => {
- mountTools(deps({ getSnapshot: () => snapshot() }));
+ mountTools(studioAgentToolsDeps({ getSnapshot: () => lookSnapshot() }));
});
expect(trackEvent).toHaveBeenCalledWith("webmcp_registration_failed", {
@@ -290,7 +257,7 @@ describe("useStudioAgentTools", () => {
await act(async () => {
mountTools(
- deps({
+ studioAgentToolsDeps({
getSnapshot: () => {
throw new TypeError("handler signature moved");
},
@@ -310,7 +277,7 @@ describe("useStudioAgentTools", () => {
it("requires a source-safe handle on every source-writing tool", async () => {
const { registered } = installModelContext();
- await act(async () => mountTools(deps()));
+ await act(async () => mountTools(studioAgentToolsDeps()));
for (const name of [
"studio_set_text",
@@ -394,6 +361,53 @@ describe("useStudioAgentTools", () => {
expect(setText).not.toHaveBeenCalled();
});
+ it("runs every write tool when execute is called with the input alone", async () => {
+ // `@mcp-b/global` invokes `execute(input)` with no options object, both from
+ // its in-page server and from the descriptor it mirrors into a native
+ // `document.modelContext`. Handlers that destructured `{ signal }` threw a
+ // TypeError before running, which `runToolBody` reports as `internal`.
+ const { registered } = installModelContext();
+ const consoleError = vi.spyOn(console, "error").mockImplementation(() => undefined);
+ const targeted = mountedTargetDeps();
+ const setText = vi.fn(
+ async () =>
+ ({
+ ok: true,
+ persistence: { sourceFile: "index.html", version: '"sha256:after"', changed: true },
+ }) as const,
+ );
+ await act(async () => mountTools({ ...targeted.deps, setText }));
+
+ const writeTools = registered.filter((tool) => tool.annotations?.readOnlyHint === false);
+ expect(writeTools.map((tool) => tool.name)).toEqual([
+ "studio_select",
+ "studio_seek",
+ "studio_set_text",
+ "studio_set_style",
+ "studio_transform",
+ "studio_add_animation",
+ "studio_update_animation",
+ "studio_add_keyframe",
+ "studio_delete_animation",
+ ]);
+ for (const tool of writeTools) {
+ // One argument, exactly as the polyfill calls it. An empty input is a bad
+ // request, never a crash: the failure kind must not be `internal`.
+ const result = (await tool.execute({})) as { ok: boolean; kind?: string };
+ expect(result.ok, tool.name).toBe(false);
+ expect(result.kind, tool.name).not.toBe("internal");
+ }
+ expect(consoleError).not.toHaveBeenCalled();
+
+ const saved = await executeRegisteredWithoutOptions<{ ok: boolean; stage: string }>(
+ registered,
+ "studio_set_text",
+ { handle: targeted.agentHandle, text: "Edited without options" },
+ );
+ expect(saved).toMatchObject({ ok: true, stage: "saved" });
+ expect(setText).toHaveBeenCalledTimes(1);
+ });
+
it("reports dispatched, saved, and verified only from their corresponding evidence", async () => {
const { registered } = installModelContext();
const targeted = mountedTargetDeps();
diff --git a/packages/studio/src/webmcp/useStudioAgentTools.ts b/packages/studio/src/webmcp/useStudioAgentTools.ts
index 717f9dcd38..913ceb21b4 100644
--- a/packages/studio/src/webmcp/useStudioAgentTools.ts
+++ b/packages/studio/src/webmcp/useStudioAgentTools.ts
@@ -112,6 +112,32 @@ export interface StudioAgentToolsDeps
* state. That is the whole point of the ref: see the registration note below.
*/
function buildStudioTools(depsRef: { readonly current: StudioAgentToolsDeps }): ModelContextTool[] {
+ /**
+ * `execute` for a tool whose handler takes the caller's abort signal.
+ *
+ * The spec shape is `execute(input, { signal })`, but `@mcp-b/global` (5.0.1
+ * through 5.1.0; the polyfill chunk is byte-identical across them) invokes a
+ * registered `execute` with the input ALONE, both from its in-page
+ * `BrowserMcpServer` wrapper and from the descriptor it mirrors into a native
+ * `document.modelContext`. A handler that destructures its second argument
+ * throws before it runs, so every write tool failed with "Cannot destructure
+ * property 'signal' of 'undefined'" while the read tools, which ignore the
+ * argument, kept working. This is the one boundary that tolerates the missing
+ * options object. Each handler already defaults an undefined signal to a
+ * never-aborted one, so nothing downstream has to.
+ */
+ const writeTool =
+ <T>(
+ name: string,
+ run: (
+ deps: StudioAgentToolsDeps,
+ input: object,
+ signal: AbortSignal | undefined,
+ ) => Promise<ToolResult<T>>,
+ ): ModelContextTool["execute"] =>
+ (input, options) =>
+ runToolBody<T>(name, () => run(depsRef.current, input, options?.signal));
+
return [
{
name: "studio_look",
@@ -177,10 +203,9 @@ function buildStudioTools(depsRef: { readonly current: StudioAgentToolsDeps }):
description: STUDIO_SET_TEXT_DESCRIPTION,
inputSchema: STUDIO_SET_TEXT_INPUT_SCHEMA,
annotations: { readOnlyHint: false, untrustedContentHint: true },
- execute: (input, { signal }): Promise<ToolResult<StudioSetTextResult>> =>
- runToolBody<StudioSetTextResult>("studio_set_text", () =>
- studioSetText(depsRef.current, input, signal),
- ),
+ execute: writeTool<StudioSetTextResult>("studio_set_text", (deps, input, signal) =>
+ studioSetText(deps, input, signal),
+ ),
},
{
name: "studio_set_style",
@@ -188,10 +213,9 @@ function buildStudioTools(depsRef: { readonly current: StudioAgentToolsDeps }):
description: STUDIO_SET_STYLE_DESCRIPTION,
inputSchema: STUDIO_SET_STYLE_INPUT_SCHEMA,
annotations: { readOnlyHint: false },
- execute: (input, { signal }): Promise<ToolResult<StudioSetStyleResult>> =>
- runToolBody<StudioSetStyleResult>("studio_set_style", () =>
- studioSetStyle(depsRef.current, input, signal),
- ),
+ execute: writeTool<StudioSetStyleResult>("studio_set_style", (deps, input, signal) =>
+ studioSetStyle(deps, input, signal),
+ ),
},
{
name: "studio_transform",
@@ -199,10 +223,9 @@ function buildStudioTools(depsRef: { readonly current: StudioAgentToolsDeps }):
description: STUDIO_TRANSFORM_DESCRIPTION,
inputSchema: STUDIO_TRANSFORM_INPUT_SCHEMA,
annotations: { readOnlyHint: false },
- execute: (input, { signal }): Promise<ToolResult<StudioTransformResult>> =>
- runToolBody<StudioTransformResult>("studio_transform", () =>
- studioTransform(depsRef.current, input as StudioTransformInput, signal),
- ),
+ execute: writeTool<StudioTransformResult>("studio_transform", (deps, input, signal) =>
+ studioTransform(deps, input as StudioTransformInput, signal),
+ ),
},
{
name: "studio_add_animation",
@@ -210,10 +233,9 @@ function buildStudioTools(depsRef: { readonly current: StudioAgentToolsDeps }):
description: STUDIO_ADD_ANIMATION_DESCRIPTION,
inputSchema: STUDIO_ADD_ANIMATION_INPUT_SCHEMA,
annotations: { readOnlyHint: false },
- execute: (input, { signal }): Promise<ToolResult<StudioAddAnimationResult>> =>
- runToolBody<StudioAddAnimationResult>("studio_add_animation", () =>
- studioAddAnimation(depsRef.current, input, signal),
- ),
+ execute: writeTool<StudioAddAnimationResult>("studio_add_animation", (deps, input, signal) =>
+ studioAddAnimation(deps, input, signal),
+ ),
},
{
name: "studio_update_animation",
@@ -221,10 +243,10 @@ function buildStudioTools(depsRef: { readonly current: StudioAgentToolsDeps }):
description: STUDIO_UPDATE_ANIMATION_DESCRIPTION,
inputSchema: STUDIO_UPDATE_ANIMATION_INPUT_SCHEMA,
annotations: { readOnlyHint: false },
- execute: (input, { signal }): Promise<ToolResult<StudioUpdateAnimationResult>> =>
- runToolBody<StudioUpdateAnimationResult>("studio_update_animation", () =>
- studioUpdateAnimation(depsRef.current, input, signal),
- ),
+ execute: writeTool<StudioUpdateAnimationResult>(
+ "studio_update_animation",
+ (deps, input, signal) => studioUpdateAnimation(deps, input, signal),
+ ),
},
{
name: "studio_add_keyframe",
@@ -232,10 +254,9 @@ function buildStudioTools(depsRef: { readonly current: StudioAgentToolsDeps }):
description: STUDIO_ADD_KEYFRAME_DESCRIPTION,
inputSchema: STUDIO_ADD_KEYFRAME_INPUT_SCHEMA,
annotations: { readOnlyHint: false },
- execute: (input, { signal }): Promise<ToolResult<StudioAddKeyframeResult>> =>
- runToolBody<StudioAddKeyframeResult>("studio_add_keyframe", () =>
- studioAddKeyframe(depsRef.current, input, signal),
- ),
+ execute: writeTool<StudioAddKeyframeResult>("studio_add_keyframe", (deps, input, signal) =>
+ studioAddKeyframe(deps, input, signal),
+ ),
},
{
name: "studio_delete_animation",
@@ -243,10 +264,10 @@ function buildStudioTools(depsRef: { readonly current: StudioAgentToolsDeps }):
description: STUDIO_DELETE_ANIMATION_DESCRIPTION,
inputSchema: STUDIO_DELETE_ANIMATION_INPUT_SCHEMA,
annotations: { readOnlyHint: false },
- execute: (input, { signal }): Promise<ToolResult<StudioDeleteAnimationResult>> =>
- runToolBody<StudioDeleteAnimationResult>("studio_delete_animation", () =>
- studioDeleteAnimation(depsRef.current, input, signal),
- ),
+ execute: writeTool<StudioDeleteAnimationResult>(
+ "studio_delete_animation",
+ (deps, input, signal) => studioDeleteAnimation(deps, input, signal),
+ ),
},
];
}
diff --git a/packages/studio/src/webmcp/webmcpTestUtils.ts b/packages/studio/src/webmcp/webmcpTestUtils.ts
index f7f0c8c553..8d68fee394 100644
--- a/packages/studio/src/webmcp/webmcpTestUtils.ts
+++ b/packages/studio/src/webmcp/webmcpTestUtils.ts
@@ -8,7 +8,9 @@
import { expect } from "vitest";
import type { DomEditSelection } from "../components/editor/domEditingTypes";
import type { ToolFailure, ToolResult } from "./toolResult";
+import type { StudioLookSnapshot } from "./tools/lookTools";
import type { SelectionToolDeps } from "./tools/selectionTools";
+import type { StudioAgentToolsDeps } from "./useStudioAgentTools";
import { mintElementHandle } from "./handles";
import type { TargetedWriteDeps } from "./writeCoordinator";
@@ -126,3 +128,57 @@ export function expectFailure(result: ToolResult<unknown>): ToolFailure {
if (result.ok) throw new Error("unreachable");
return result;
}
+
+/** A Studio snapshot with nothing in it; override only what the test is about. */
+export function lookSnapshot(overrides: Partial<StudioLookSnapshot> = {}): StudioLookSnapshot {
+ return {
+ projectId: "demo",
+ compositionPath: "index.html",
+ currentTime: 0,
+ duration: 10,
+ isPlaying: false,
+ elements: [],
+ scene: { status: "ready", items: [], drillInItem: null },
+ selection: null,
+ selectionAnimationCount: 0,
+ history: { canUndo: false, canRedo: false, undoLabel: null, redoLabel: null },
+ ...overrides,
+ };
+}
+
+/** Full `useStudioAgentTools` deps with inert defaults; override only what the test is about. */
+export function studioAgentToolsDeps(
+ overrides: Partial<StudioAgentToolsDeps> = {},
+): StudioAgentToolsDeps {
+ return {
+ getSnapshot: () => lookSnapshot(),
+ getPreviewDocument: () => null,
+ buildSelection: async () => null,
+ applySelection: () => undefined,
+ requestSeek: () => undefined,
+ readPlayhead: () => ({ currentTime: 0, duration: 10, isPlaying: false }),
+ getProjectId: () => "demo",
+ getCompositionPath: () => "index.html",
+ probeFrame: async () => ({ ok: true, status: 200 }),
+ wait: async () => undefined,
+ getCurrentSelection: () => null,
+ getWriteBlockedReason: () => null,
+ setText: async () => ({ ok: true }),
+ setStyle: async () => ({ ok: true }),
+ readBox: () => ({ x: 0, y: 0, width: 100, height: 50 }),
+ moveTo: async () => undefined,
+ resizeTo: async () => undefined,
+ rotateTo: async () => undefined,
+ addAnimation: async () => true,
+ updateAnimation: async () => true,
+ addKeyframe: async () => undefined,
+ deleteAnimation: async () => true,
+ getAnimationsForSelection: async () => [],
+ getGsapDiagnostics: () => ({
+ animations: [],
+ multipleTimelines: false,
+ unsupportedTimelinePattern: false,
+ }),
+ ...overrides,
+ };
+}