Skip to content

Commit 14b9e20

Browse files
miga-heygenclaude
andauthored
fix(studio): tolerate WebMCP execute calls without an options object (#3860)
* fix(studio): tolerate WebMCP execute calls without an options object Every Studio write tool (studio_set_text, studio_set_style, studio_transform, studio_add_animation, studio_update_animation, studio_add_keyframe, studio_delete_animation) registered its handler as `execute: (input, { signal }) => ...`. The W3C shape passes an options object, but the bundled `@mcp-b/global` polyfill 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`. The destructure therefore threw `TypeError: Cannot destructure property 'signal' of 'undefined'` before the handler ran, while the read tools, which ignore the second parameter, kept working. Route the seven signal-taking tools through one `writeTool` helper in `buildStudioTools` that reads `options?.signal`, so a missing options object yields an undefined signal at a single boundary. The handlers already default an undefined signal to a never-aborted one, so nothing downstream changes. `ModelContextTool.execute` now declares `options` optional to match what callers actually do. Upstream check: `@mcp-b/global` 5.0.1 (pinned), 5.0.3 and 5.1.0 ship a byte-identical `@mcp-b/webmcp-polyfill` chunk and the same one-argument call in `@mcp-b/webmcp-ts-sdk`, so a dependency bump would not fix this. Tests: drive `studio_set_text` through the real `@mcp-b/global` package under jsdom (registry entry `execute` and Chromium-style `executeTool`) and assert a saved result; call every write tool with one argument against a fake model context and assert none reports an `internal` failure. The existing spec-shaped tests, including the early abort path, still pass, which proves a provided signal still reaches the handler. Shared inert deps builders move to `webmcpTestUtils.ts`. Closes #3858 Co-Authored-By: Claude Fable 5.1 <[email protected]> * test(studio): cover the native-mirror WebMCP execute path Install a native-looking `document.modelContext` before importing `@mcp-b/global` so the bridge wraps it and mirrors every Studio registration into it. One setup then exercises both one-argument call paths the package ships: the in-page BrowserMcpServer wrapper (registry entry and Chromium-style `executeTool`) and the descriptor mirrored into the native context. Both fail with "Cannot destructure property 'signal' of 'undefined'" without the fix and save with it. Co-Authored-By: Claude Fable 5.1 <[email protected]> --------- Co-authored-by: Claude Fable 5.1 <[email protected]>
1 parent 8820a01 commit 14b9e20

5 files changed

Lines changed: 410 additions & 96 deletions

File tree

‎packages/studio/src/webmcp/types.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,8 +57,12 @@ export interface ModelContextTool {
5757
* A rejection is NOT a usable error channel: the spec discards the reason and
5858
* rejects the caller with a bare UnknownError. Resolve with a tagged failure
5959
* instead. See `toolResult.ts`.
60+
*
61+
* `options` is optional here although the spec always passes it: the
62+
* `@mcp-b/global` polyfill (through 5.1.0) calls `execute(input)` with no
63+
* second argument, so a Studio handler must not depend on receiving one.
6064
*/
61-
execute: (input: object, options: ToolExecuteCallbackOptions) => Promise<unknown>;
65+
execute: (input: object, options?: ToolExecuteCallbackOptions) => Promise<unknown>;
6266
annotations?: ModelContextToolAnnotations;
6367
}
6468

Lines changed: 219 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,219 @@
1+
// @vitest-environment jsdom
2+
/**
3+
* Drives the write tools through the REAL `@mcp-b/global` package rather than
4+
* a fake `document.modelContext`.
5+
*
6+
* The package invokes a registered `execute` with the input alone, on both of
7+
* its paths: the in-page `BrowserMcpServer` wrapper that agents reach through
8+
* the registry and `executeTool`, and the descriptor it mirrors into a native
9+
* `document.modelContext` when the browser ships one. A Studio handler that
10+
* destructured `{ signal }` from the missing second argument threw before it
11+
* ran, so every write tool failed with "Cannot destructure property 'signal'
12+
* of 'undefined'" while the read tools kept working. This file proves the fix
13+
* against the code that ships in the polyfill chunk. The spec-shaped call and
14+
* the abort path live in `useStudioAgentTools.test.tsx`; the polyfill cannot
15+
* exercise them because it drops the caller's signal before the handler.
16+
*
17+
* A native-looking `modelContext` is installed BEFORE the import so the bridge
18+
* wraps it and mirrors every registration into it, which is how both paths get
19+
* covered from one setup. Its own file because the import is a one-shot side
20+
* effect that the sibling suite's fake would otherwise have to fight.
21+
*/
22+
import { act } from "react";
23+
import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";
24+
import { mountReactHarness } from "../hooks/domSelectionTestHarness";
25+
import { mintElementHandle } from "./handles";
26+
import { useStudioAgentTools, type StudioAgentToolsDeps } from "./useStudioAgentTools";
27+
import { previewDoc, selectionFor, studioAgentToolsDeps } from "./webmcpTestUtils";
28+
29+
vi.mock("../telemetry/client", () => ({ trackEvent: vi.fn() }));
30+
31+
Reflect.set(globalThis, "IS_REACT_ACT_ENVIRONMENT", true);
32+
33+
/** What a browser's own `registerTool` receives from the bridge. */
34+
interface MirroredTool {
35+
name: string;
36+
description: string;
37+
execute: (input: object, options?: { signal?: AbortSignal }) => Promise<unknown>;
38+
}
39+
40+
/** What `getTools()` returns and `executeTool()` accepts. */
41+
interface RegisteredTool {
42+
name: string;
43+
description: string;
44+
window: Window;
45+
origin: string;
46+
}
47+
48+
/** The bridge's registry entry, as the reporter of the bug drove it. */
49+
interface BridgeToolEntry {
50+
item: { name: string };
51+
execute: (input: object, signal?: AbortSignal) => Promise<unknown>;
52+
}
53+
54+
interface BridgeModelContext {
55+
tools: Map<string, BridgeToolEntry>;
56+
getTools(): Promise<RegisteredTool[]>;
57+
executeTool(
58+
tool: RegisteredTool,
59+
inputArguments: string,
60+
options?: { signal?: AbortSignal },
61+
): Promise<string | null>;
62+
}
63+
64+
const mirrored: MirroredTool[] = [];
65+
/** Enough of a browser's `modelContext` for the bridge to wrap and mirror into. */
66+
const fakeNative = {
67+
registerTool: async (tool: MirroredTool): Promise<void> => {
68+
mirrored.push(tool);
69+
},
70+
// The bridge delegates `getTools()` to the native context when there is one,
71+
// and its own `executeTool` then insists on a full `RegisteredTool`.
72+
getTools: async (): Promise<RegisteredTool[]> =>
73+
mirrored.map((tool) => ({
74+
name: tool.name,
75+
description: tool.description,
76+
window,
77+
origin: window.location.origin,
78+
})),
79+
};
80+
81+
let cleanup: (() => void) | null = null;
82+
83+
beforeAll(async () => {
84+
// Configurable, so the bridge is allowed to replace it with itself.
85+
Object.defineProperty(document, "modelContext", {
86+
value: fakeNative,
87+
configurable: true,
88+
writable: true,
89+
});
90+
await import("@mcp-b/global");
91+
expect(Reflect.get(document, "modelContext")).not.toBe(fakeNative);
92+
});
93+
94+
afterEach(async () => {
95+
cleanup?.();
96+
cleanup = null;
97+
mirrored.length = 0;
98+
// The polyfill watches the document with a MutationObserver that reads jsdom
99+
// globals. Empty the document and let the observer settle now, while those
100+
// globals still exist, instead of when vitest closes the window.
101+
document.body.replaceChildren();
102+
await new Promise((resolve) => setTimeout(resolve, 0));
103+
window.localStorage.clear();
104+
});
105+
106+
function bridge(): BridgeModelContext {
107+
// Through `unknown`: importing the package brings its own `Document.modelContext`
108+
// typing into scope, and this file reads the bridge's non-standard surface.
109+
return Reflect.get(document, "modelContext") as unknown as BridgeModelContext;
110+
}
111+
112+
/** Registration is async, so wait for the whole tool set to land. */
113+
async function waitForTools(count: number): Promise<void> {
114+
const deadline = Date.now() + 5_000;
115+
while (bridge().tools.size !== count || mirrored.length !== count) {
116+
if (Date.now() > deadline) {
117+
throw new Error(
118+
`expected ${count} tools, saw ${bridge().tools.size} in the bridge and ${mirrored.length} mirrored`,
119+
);
120+
}
121+
await new Promise((resolve) => setTimeout(resolve, 10));
122+
}
123+
}
124+
125+
function bridgeEntry(name: string): BridgeToolEntry {
126+
const entry = [...bridge().tools.values()].find((candidate) => candidate.item.name === name);
127+
if (!entry) throw new Error(`expected ${name} in the bridge registry`);
128+
return entry;
129+
}
130+
131+
function mirroredTool(name: string): MirroredTool {
132+
const tool = mirrored.find((candidate) => candidate.name === name);
133+
if (!tool) throw new Error(`expected ${name} to be mirrored into the native context`);
134+
return tool;
135+
}
136+
137+
/** Mount Studio's tools against a preview whose `#agent` element can be edited. */
138+
async function mountEditableAgent() {
139+
const doc = previewDoc('<h1 id="agent">Agent</h1>');
140+
const agent = doc.getElementById("agent") as HTMLElement;
141+
const handle = mintElementHandle({
142+
projectId: "demo",
143+
domId: "agent",
144+
sourceFile: "index.html",
145+
activeCompositionPath: "index.html",
146+
});
147+
if (!handle) throw new Error("expected agent handle");
148+
const setText = vi.fn(
149+
async () =>
150+
({
151+
ok: true,
152+
persistence: { sourceFile: "index.html", version: '"sha256:after"', changed: true },
153+
}) as const,
154+
);
155+
const deps: StudioAgentToolsDeps = studioAgentToolsDeps({
156+
getPreviewDocument: () => doc,
157+
buildSelection: async (element) => selectionFor(element),
158+
setText,
159+
});
160+
161+
function Probe() {
162+
useStudioAgentTools(deps);
163+
return null;
164+
}
165+
await act(async () => {
166+
const root = mountReactHarness(<Probe />);
167+
cleanup = () => act(() => root.unmount());
168+
});
169+
await waitForTools(12);
170+
return { agent, handle, setText };
171+
}
172+
173+
describe("useStudioAgentTools through @mcp-b/global", () => {
174+
it("saves through studio_set_text when the in-page server calls execute with the input alone", async () => {
175+
const { agent, handle, setText } = await mountEditableAgent();
176+
177+
// Registry entry, as `[...document.modelContext.tools.values()]` exposes it.
178+
const viaEntry = await bridgeEntry("studio_set_text").execute(
179+
{ handle, text: "Through the registry" },
180+
new AbortController().signal,
181+
);
182+
expect(viaEntry).toMatchObject({ ok: true, stage: "saved", changed: true });
183+
184+
// Chromium's `executeTool` extension, which the bridge also implements.
185+
const descriptor = (await bridge().getTools()).find((tool) => tool.name === "studio_set_text");
186+
if (!descriptor) throw new Error("expected studio_set_text in getTools()");
187+
const viaExecuteTool = await bridge().executeTool(
188+
descriptor,
189+
JSON.stringify({ handle, text: "Through executeTool" }),
190+
{ signal: new AbortController().signal },
191+
);
192+
expect(JSON.parse(viaExecuteTool ?? "null")).toMatchObject({ ok: true, stage: "saved" });
193+
194+
expect(setText).toHaveBeenCalledTimes(2);
195+
expect(setText).toHaveBeenCalledWith(
196+
expect.objectContaining({ element: agent }),
197+
"Through the registry",
198+
"self",
199+
);
200+
});
201+
202+
it("saves through the descriptor the bridge mirrors into a native modelContext", async () => {
203+
const { agent, handle, setText } = await mountEditableAgent();
204+
205+
// The browser would call this with `(input, { signal })`; the mirror drops
206+
// the options before Studio's handler sees them.
207+
const result = await mirroredTool("studio_set_text").execute(
208+
{ handle, text: "Through the native mirror" },
209+
{ signal: new AbortController().signal },
210+
);
211+
212+
expect(result).toMatchObject({ ok: true, stage: "saved", changed: true });
213+
expect(setText).toHaveBeenCalledWith(
214+
expect.objectContaining({ element: agent }),
215+
"Through the native mirror",
216+
"self",
217+
);
218+
});
219+
});

0 commit comments

Comments
 (0)