diff --git a/bun.lock b/bun.lock index 6f906ddf16..a67f036888 100644 --- a/bun.lock +++ b/bun.lock @@ -384,7 +384,7 @@ "@hyperframes/shader-transitions": "workspace:*", "@hyperframes/studio-server": "workspace:*", "@lezer/highlight": "^1.2.3", - "@mcp-b/global": "^5.0.1", + "@mcp-b/global": "^6.1.0", "@phosphor-icons/react": "^2.1.10", "@tanstack/react-virtual": "^3.14.13", "acorn": "^8.17.0", @@ -891,19 +891,17 @@ "@marijn/find-cluster-break": ["@marijn/find-cluster-break@1.0.2", "", {}, "sha512-l0h88YhZFyKdXIFNfSWpyjStDjGHwZ/U7iobcK1cQQD8sejsONdQtTVU+1wVN1PBw40PiiHB1vA5S7VTfQiP9g=="], - "@mcp-b/global": ["@mcp-b/global@5.0.1", "", { "dependencies": { "@mcp-b/transports": "5.0.1", "@mcp-b/webmcp-polyfill": "5.0.1", "@mcp-b/webmcp-ts-sdk": "5.0.1", "@mcp-b/webmcp-types": "5.0.1", "@modelcontextprotocol/server": "2.0.0" } }, "sha512-Wca64tan5xaz1yyT8xeZj/3CLhN2vSjUUYmiZIBSw0XkgqDfezLc8EoLqAWIBgtbddDMpAHI3WDd+RhgJViQbg=="], + "@mcp-b/global": ["@mcp-b/global@6.1.0", "", { "dependencies": { "@mcp-b/transports": "6.1.0", "@mcp-b/webmcp-polyfill": "6.1.0", "@mcp-b/webmcp-ts-sdk": "6.1.0", "@modelcontextprotocol/server": "2.4.0" } }, "sha512-CAxzOTl+MJIx448mt8qGrvtPyKeAZ0y7fETY5peSXuHsEPeMu9ybc8vnfJCKa0AnojebYp6WVt6xklCvsePxxA=="], - "@mcp-b/transports": ["@mcp-b/transports@5.0.1", "", { "dependencies": { "@modelcontextprotocol/core": "2.0.0", "@modelcontextprotocol/server": "2.0.0", "@types/chrome": "^0.0.326" } }, "sha512-qgFns3DJ8I2LWDPx6CItQdGIHIammYTcVo6LqdcjC1pURhJyJRUCBc8Q2dNjNEK2gp3dALPmvk5S7OOe5iyA7w=="], + "@mcp-b/transports": ["@mcp-b/transports@6.1.0", "", { "dependencies": { "@modelcontextprotocol/core": "2.4.0", "@modelcontextprotocol/server": "2.4.0" } }, "sha512-5UNHBFCJK/wW8UPjg2SrwNif93p2yiVj1Adq0CqYeuawSvUw5RP28qHAqA3GxR0r7rENdisSzPchEds8ztFX0Q=="], - "@mcp-b/webmcp-polyfill": ["@mcp-b/webmcp-polyfill@5.0.1", "", { "dependencies": { "@mcp-b/webmcp-types": "5.0.1", "@standard-schema/spec": "^1.1.0" } }, "sha512-xw/7f0bu4dsqWaGCE4RbB5/nkkbczeIP6NNeatE61Yxfpfp3r2E7pdgHmtYKb3oZ2BxROiM/yWkgiM3Ol0nkjA=="], + "@mcp-b/webmcp-polyfill": ["@mcp-b/webmcp-polyfill@6.1.0", "", { "dependencies": { "@w3c/webmcp-polyfill": "0.1.0", "webmcp-types": "0.1.10" } }, "sha512-sKGIXmFP6F2hNM4vQLQThXb4vpnK3jKLcj1uUeyT9m0/Pf8xdoITKtiEqWaT5dd/SXj2ESfrnop+RWTZ0bNY1w=="], - "@mcp-b/webmcp-ts-sdk": ["@mcp-b/webmcp-ts-sdk@5.0.1", "", { "dependencies": { "@mcp-b/webmcp-polyfill": "5.0.1", "@mcp-b/webmcp-types": "5.0.1", "@modelcontextprotocol/server": "2.0.0" } }, "sha512-0o/mtUCjJSLw6l/81Yexnd6pXTYw1tZN2a7/e5zaMM5UWp/97vXhh5ktwfbodwu//L8/Rag7n69++rnhhE8zxw=="], + "@mcp-b/webmcp-ts-sdk": ["@mcp-b/webmcp-ts-sdk@6.1.0", "", { "dependencies": { "@mcp-b/webmcp-polyfill": "6.1.0", "@modelcontextprotocol/server": "2.4.0", "@standard-schema/spec": "^1.1.0", "webmcp-types": "0.1.10" } }, "sha512-Q0Zsg0gjKJQmrHyEuh7vlgYsJKM/KasJB2QyyPM/ztTkM7bvJ0NatpazhnSaVPdNMdGX1EXvEFAt2FQRzWgU5g=="], - "@mcp-b/webmcp-types": ["@mcp-b/webmcp-types@5.0.1", "", { "dependencies": { "@modelcontextprotocol/server": "2.0.0" } }, "sha512-UN7GsTrudXoMWxTL6n6451C19r5nsBzU4WLovRC6YVFnOJk3N5qYwmQySAISEi/0fcWkRDcT3OqAee7/jrl1iA=="], + "@modelcontextprotocol/core": ["@modelcontextprotocol/core@2.4.0", "", { "dependencies": { "zod": "^4.2.0" } }, "sha512-z8QBKqdfXLPzkLQuG4xp8hrVEMm1PZ1IgxMN2sMbJiFiAKOWXnAzogXn2W4aqIBlP1ea6U5yiqVquvUNM1Cj6Q=="], - "@modelcontextprotocol/core": ["@modelcontextprotocol/core@2.0.0", "", { "dependencies": { "zod": "^4.2.0" } }, "sha512-pJCEwGG7Lfr/+PQp9ZTwKXNeO5wzbfKL7H3MYpCorM4oFBoQrdjnBgEoqG+RjhsvS1FKrDbKux+M1HhlnGWqcA=="], - - "@modelcontextprotocol/server": ["@modelcontextprotocol/server@2.0.0", "", { "dependencies": { "@modelcontextprotocol/core": "2.0.0", "zod": "^4.2.0" } }, "sha512-YhHWdHfpFMQfd0prsEnxKeS3Qz3ytIGmsS0sth4KDjnacIT7hxk6hXHkJ9KysxlkvTM+WZAtQbbcUhdoP4Hvtw=="], + "@modelcontextprotocol/server": ["@modelcontextprotocol/server@2.4.0", "", { "dependencies": { "@modelcontextprotocol/core": "2.4.0", "zod": "^4.2.0" } }, "sha512-rgR9yxSaAJ+bcsi/XroT/S2AfPiIWloXAnrdfYSCms9ivVju0ishu/wW0J21Ho6+ZOR1r7RyeRbjiRuF87ix5Q=="], "@napi-rs/wasm-runtime": ["@napi-rs/wasm-runtime@1.1.4", "", { "dependencies": { "@tybys/wasm-util": "^0.10.1" }, "peerDependencies": { "@emnapi/core": "^1.7.1", "@emnapi/runtime": "^1.7.1" } }, "sha512-3NQNNgA1YSlJb/kMH1ildASP9HW7/7kYnRI2szWJaofaS1hWmbGI4H+d3+22aGzXXN9IJ+n+GiFVcGipJP18ow=="], @@ -1245,8 +1243,6 @@ "@types/chai": ["@types/chai@5.2.3", "", { "dependencies": { "@types/deep-eql": "*", "assertion-error": "^2.0.1" } }, "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA=="], - "@types/chrome": ["@types/chrome@0.0.326", "", { "dependencies": { "@types/filesystem": "*", "@types/har-format": "*" } }, "sha512-WS7jKf3ZRZFHOX7dATCZwqNJgdfiSF0qBRFxaO0LhIOvTNBrfkab26bsZwp6EBpYtqp8loMHJTnD6vDTLWPKYw=="], - "@types/css-tree": ["@types/css-tree@3.2.0", "", {}, "sha512-J5KXmk6BFIepOT7280FdFyNs4c5fh0Uee0otjKEvzchrRs38Ii9qminqc4ds0L19X8Zd/rT+brR9jkBthygjWw=="], "@types/deep-eql": ["@types/deep-eql@4.0.2", "", {}, "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw=="], @@ -1259,14 +1255,8 @@ "@types/estree": ["@types/estree@1.0.8", "", {}, "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w=="], - "@types/filesystem": ["@types/filesystem@0.0.36", "", { "dependencies": { "@types/filewriter": "*" } }, "sha512-vPDXOZuannb9FZdxgHnqSwAG/jvdGM8Wq+6N4D/d80z+D4HWH+bItqsZaVRQykAn6WEVeEkLm2oQigyHtgb0RA=="], - - "@types/filewriter": ["@types/filewriter@0.0.33", "", {}, "sha512-xFU8ZXTw4gd358lb2jw25nxY9QAgqn2+bKKjKOYfNCzN4DKCFetK7sPtrlpg66Ywe3vWY9FNxprZawAh9wfJ3g=="], - "@types/fontkit": ["@types/fontkit@2.0.9", "", { "dependencies": { "@types/node": "*" } }, "sha512-qNYerFky3muCmZPq+R+B3cUDRA5OONw/oh6aGGFxx2LOBz6yu8eamKusrhkHnC6rc2fm76+G9z9QoWSB2SaQaw=="], - "@types/har-format": ["@types/har-format@1.2.16", "", {}, "sha512-fluxdy7ryD3MV6h8pTfTYpy/xQzCFC7m89nOH9y94cNqJ1mDIDPut7MnRHI3F6qRmh/cT2fUjG1MLdCNb4hE9A=="], - "@types/jsdom": ["@types/jsdom@28.0.2", "", { "dependencies": { "@types/node": "*", "@types/tough-cookie": "*", "parse5": "^8.0.0", "undici-types": "^7.21.0" } }, "sha512-zZYItekplnGirFhVDrcB0+103TMakXfKfIp7uECxaFzFG3Ws5kYQSwVb1d4pQfJMMjQda6pfuZxueAv9CMiJbw=="], "@types/node": ["@types/node@25.7.0", "", { "dependencies": { "undici-types": "~7.21.0" } }, "sha512-z+pdZyxE+RTQE9AcboAZCb4otwcrvgHD+GlBpPgn0emDVt0ohrTMhAwlr2Wd9nZ+nihhYFxO2pThz3C5qSu2Eg=="], @@ -1345,6 +1335,8 @@ "@vitest/utils": ["@vitest/utils@4.1.12", "", { "dependencies": { "@vitest/pretty-format": "4.1.12", "convert-source-map": "^2.0.0", "tinyrainbow": "^3.1.0" } }, "sha512-Q3awXrwOfEV+qc3WmO5ONyE0yO7Q1gQ9/oyHxGLZ/pl7N3NO/ZztqQwKLuwMkV+CA1JYSIeO3gkHnRDIo4AVaA=="], + "@w3c/webmcp-polyfill": ["@w3c/webmcp-polyfill@0.1.0", "", { "dependencies": { "webmcp-types": "^0.1.9" } }, "sha512-FNzmob4B72T9cHDVODskyFjNi0JaZgcD1U0eFmuc2J4o3Lr5k1xabZ5rjw1AuvzgvdxRfvNr9FHUP9yG1s/StA=="], + "@webgpu/types": ["@webgpu/types@0.1.70", "", {}, "sha512-LFiNHHKMvmAEvwVew3JLJmTdShhbdwRFSImUshGhE2mGE8ybQzIo63l5uRp+YKnNx+8Qno8Kf6gN+DKMreIJCA=="], "abort-controller": ["abort-controller@3.0.0", "", { "dependencies": { "event-target-shim": "^5.0.0" } }, "sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg=="], @@ -2229,6 +2221,8 @@ "webidl-conversions": ["webidl-conversions@8.0.1", "", {}, "sha512-BMhLD/Sw+GbJC21C/UgyaZX41nPt8bUTg+jWyDeg7e7YN4xOM05YPSIXceACnXVtqyEw/LMClUQMtMZ+PGGpqQ=="], + "webmcp-types": ["webmcp-types@0.1.10", "", {}, "sha512-U4GQ1RpJ0tqCUt2ALMV9Pnhi+hsy8L31f/Q1v4mLVhW64r5sYhh+2+SjP/Lq4/9jP33vZgNkuRZARJl65A/ZIg=="], + "whatwg-mimetype": ["whatwg-mimetype@3.0.0", "", {}, "sha512-nt+N2dzIutVRxARx1nghPKGv1xHikU7HKdfafKkLNLindmPU/ch3U31NOCGGA/dmPcmb1VlofO0vnKAcsm0o/Q=="], "whatwg-url": ["whatwg-url@16.0.1", "", { "dependencies": { "@exodus/bytes": "^1.11.0", "tr46": "^6.0.0", "webidl-conversions": "^8.0.1" } }, "sha512-1to4zXBxmXHV3IiSSEInrreIlu02vUOvrhxJJH5vcxYTBDAx51cqZiKdyTxlecdKNSjj8EcxGBxNf6Vg+945gw=="], @@ -2325,6 +2319,10 @@ "@isaacs/fs-minipass/minipass": ["minipass@7.1.3", "", {}, "sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A=="], + "@modelcontextprotocol/core/zod": ["zod@4.6.7", "", {}, "sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg=="], + + "@modelcontextprotocol/server/zod": ["zod@4.6.7", "", {}, "sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg=="], + "@puppeteer/browsers/yargs": ["yargs@18.0.0", "", { "dependencies": { "cliui": "^9.0.1", "escalade": "^3.1.1", "get-caller-file": "^2.0.5", "string-width": "^7.2.0", "y18n": "^5.0.5", "yargs-parser": "^22.0.0" } }, "sha512-4UEqdc2RYGHZc7Doyqkrqiln3p9X2DZVxaGbwhn2pi7MrRagKaOcIKe8L3OxYcbhXLgLFUS3zAYuQjKBQgmuNg=="], "@tailwindcss/oxide-wasm32-wasi/@emnapi/core": ["@emnapi/core@1.11.3", "", { "dependencies": { "@emnapi/wasi-threads": "1.2.3", "tslib": "^2.4.0" }, "bundled": true }, "sha512-zLpS5asjEb7lq8jYLq37N6XKaE41DIexlY1rF/z4/tIl3wo13Sqm28fRyfIsKZD+NZ8mM5RoKkpW/rBcuoSZSg=="], diff --git a/packages/studio/package.json b/packages/studio/package.json index ed26bf4453..b051e3e5d5 100644 --- a/packages/studio/package.json +++ b/packages/studio/package.json @@ -116,7 +116,7 @@ "@hyperframes/shader-transitions": "workspace:*", "@hyperframes/studio-server": "workspace:*", "@lezer/highlight": "^1.2.3", - "@mcp-b/global": "^5.0.1", + "@mcp-b/global": "^6.1.0", "@phosphor-icons/react": "^2.1.10", "@tanstack/react-virtual": "^3.14.13", "acorn": "^8.17.0", diff --git a/packages/studio/src/webmcp/polyfill.transport.test.ts b/packages/studio/src/webmcp/polyfill.transport.test.ts index e4917e6061..991af3516d 100644 --- a/packages/studio/src/webmcp/polyfill.transport.test.ts +++ b/packages/studio/src/webmcp/polyfill.transport.test.ts @@ -1,24 +1,34 @@ // @vitest-environment jsdom /** * Loads the REAL `@mcp-b/global` through Studio's loader, inside a page that is - * framed by another site, and checks that neither of the package's message - * transports answers anyone but Studio's own page. + * framed by another site, and checks that neither of the package's MCP + * message transports answers anyone but Studio's own page. The W3C polyfill's + * frame protocol is not exercised here: the fake framer is not `window.top`. */ import { afterAll, expect, it, vi } from "vitest"; vi.mock("../telemetry/client", () => ({ trackEvent: vi.fn() })); -const framer = { postMessage: vi.fn() }; +// A top-level window: the polyfill walks `parent` until it reaches itself. +const framer = { + postMessage: vi.fn(), + get parent(): object { + return framer; + }, +}; const ownParent = Object.getOwnPropertyDescriptor(window, "parent"); afterAll(() => { if (ownParent) Object.defineProperty(window, "parent", ownParent); else Reflect.deleteProperty(window, "parent"); + Reflect.deleteProperty(window, "isSecureContext"); }); const settle = () => new Promise((resolve) => setTimeout(resolve, 20)); it("answers no MCP client but Studio's own page when another site frames Studio", async () => { Object.defineProperty(window, "parent", { value: framer, configurable: true }); + // jsdom leaves this undefined and the polyfill installs only in a secure context. + Object.defineProperty(window, "isSecureContext", { value: true, configurable: true }); const ownMessages = vi.spyOn(window, "postMessage"); const { loadModelContextPolyfill } = await import("./polyfill"); diff --git a/packages/studio/src/webmcp/types.ts b/packages/studio/src/webmcp/types.ts index dcf976f88d..0d020b4f4e 100644 --- a/packages/studio/src/webmcp/types.ts +++ b/packages/studio/src/webmcp/types.ts @@ -14,8 +14,8 @@ * Only the surface Studio registers against is declared. `getTools` and * `executeTool` are the consumer side; Studio registers, it does not call. * - * These stay hand-written rather than imported from `@mcp-b/webmcp-types`, - * which the polyfill pulls in. That package's `registerTool` is overloaded to + * These stay hand-written rather than imported from `webmcp-types`, which + * the polyfill pulls in. That package's `registerTool` is overloaded to * infer argument types from a literal `inputSchema`, which is useful when you * register one tool inline and actively hostile when you register a uniform * list of them, as `registerStudioTools` does. Narrower is the safe operation @@ -59,7 +59,7 @@ export interface ModelContextTool { * 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 + * `@mcp-b/global` polyfill before 6.0 called `execute(input)` with no * second argument, so a Studio handler must not depend on receiving one. */ execute: (input: object, options?: ToolExecuteCallbackOptions) => Promise; diff --git a/packages/studio/src/webmcp/useStudioAgentTools.polyfill.test.tsx b/packages/studio/src/webmcp/useStudioAgentTools.polyfill.test.tsx index b9fa2b207f..c16bc45cc7 100644 --- a/packages/studio/src/webmcp/useStudioAgentTools.polyfill.test.tsx +++ b/packages/studio/src/webmcp/useStudioAgentTools.polyfill.test.tsx @@ -3,24 +3,24 @@ * 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. + * The package installs the W3C polyfill and wraps it in an in-page MCP server + * that an out-of-browser agent reaches over the tab transport. This file + * proves a write tool saves when an MCP `tools/call` drives it through that + * chain, against the code that ships in the polyfill chunk. 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 { + afterAll, + afterEach, + beforeAll, + describe, + expect, + it, + vi, + type MockInstance, +} from "vitest"; import { mountReactHarness } from "../hooks/domSelectionTestHarness"; import { mintElementHandle } from "./handles"; import { useStudioAgentTools, type StudioAgentToolsDeps } from "./useStudioAgentTools"; @@ -30,71 +30,37 @@ 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; -} - -/** 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; -} - interface BridgeModelContext { - tools: Map; - getTools(): Promise; - executeTool( - tool: RegisteredTool, - inputArguments: string, - options?: { signal?: AbortSignal }, - ): Promise; + listTools(): { name: string }[]; + getTools(): Promise<{ name: string }[]>; } -const mirrored: MirroredTool[] = []; -/** Enough of a browser's `modelContext` for the bridge to wrap and mirror into. */ -const fakeNative = { - registerTool: async (tool: MirroredTool): Promise => { - 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 => - mirrored.map((tool) => ({ - name: tool.name, - description: tool.description, - window, - origin: window.location.origin, - })), -}; +interface JsonRpcResponse { + id: number; + result?: { structuredContent?: unknown; content?: { type: string; text?: string }[] }; + error?: unknown; +} 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, - }); + // jsdom leaves this undefined and the polyfill installs only in a secure context. + Object.defineProperty(window, "isSecureContext", { value: true, configurable: true }); await import("@mcp-b/global"); - expect(Reflect.get(document, "modelContext")).not.toBe(fakeNative); + expect(typeof bridge().listTools).toBe("function"); +}); + +afterAll(async () => { + // Close the server so its deferred tools-changed event doesn't fire after jsdom is torn down. + const { cleanupWebModelContext } = await import("@mcp-b/global"); + cleanupWebModelContext(); + await new Promise((resolve) => setTimeout(resolve, 0)); + Reflect.deleteProperty(window, "isSecureContext"); }); 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. @@ -112,28 +78,14 @@ function bridge(): BridgeModelContext { /** Registration is async, so wait for the whole tool set to land. */ async function waitForTools(count: number): Promise { const deadline = Date.now() + 5_000; - while (bridge().tools.size !== count || mirrored.length !== count) { + while (bridge().listTools().length !== count || (await bridge().getTools()).length !== count) { if (Date.now() > deadline) { - throw new Error( - `expected ${count} tools, saw ${bridge().tools.size} in the bridge and ${mirrored.length} mirrored`, - ); + throw new Error(`expected ${count} tools, saw ${bridge().listTools().length} in the bridge`); } 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('

Agent

'); @@ -170,49 +122,65 @@ async function mountEditableAgent() { return { agent, handle, setText }; } +/** Post one JSON-RPC message to the in-page server the way the tab client does. */ +function postToServer(payload: object): void { + window.dispatchEvent( + new MessageEvent("message", { + data: { channel: "mcp-default", type: "mcp", direction: "client-to-server", payload }, + origin: window.location.origin, + source: window, + }), + ); +} + +/** The server answers through `window.postMessage`; wait for the reply to `id`. */ +async function replyTo(sent: MockInstance, id: number): Promise { + const deadline = Date.now() + 5_000; + for (;;) { + for (const [message] of sent.mock.calls) { + const payload = (message as { payload?: unknown } | undefined)?.payload; + if (typeof payload === "object" && payload !== null && Reflect.get(payload, "id") === id) { + return payload as JsonRpcResponse; + } + } + if (Date.now() > deadline) throw new Error(`no MCP reply to request ${id}`); + await new Promise((resolve) => setTimeout(resolve, 10)); + } +} + describe("useStudioAgentTools through @mcp-b/global", () => { - it("saves through studio_set_text when the in-page server calls execute with the input alone", async () => { + it("saves through studio_set_text when an MCP client calls it", async () => { const { agent, handle, setText } = await mountEditableAgent(); + const sent = vi.spyOn(window, "postMessage"); - // 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 }); + postToServer({ + jsonrpc: "2.0", + id: 1, + method: "initialize", + params: { + protocolVersion: "2025-06-18", + capabilities: {}, + clientInfo: { name: "studio-test", version: "1.0.0" }, + }, + }); + expect((await replyTo(sent, 1)).error).toBeUndefined(); + postToServer({ jsonrpc: "2.0", method: "notifications/initialized" }); - // 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 }, - ); + postToServer({ + jsonrpc: "2.0", + id: 2, + method: "tools/call", + params: { name: "studio_set_text", arguments: { handle, text: "Through MCP" } }, + }); + const reply = await replyTo(sent, 2); + sent.mockRestore(); + const text = reply.result?.content?.[0]?.text; + const result = reply.result?.structuredContent ?? JSON.parse(text ?? "null"); expect(result).toMatchObject({ ok: true, stage: "saved", changed: true }); expect(setText).toHaveBeenCalledWith( expect.objectContaining({ element: agent }), - "Through the native mirror", + "Through MCP", "self", ); }); diff --git a/packages/studio/src/webmcp/useStudioAgentTools.test.tsx b/packages/studio/src/webmcp/useStudioAgentTools.test.tsx index 55fb8bedac..e972e967ea 100644 --- a/packages/studio/src/webmcp/useStudioAgentTools.test.tsx +++ b/packages/studio/src/webmcp/useStudioAgentTools.test.tsx @@ -26,7 +26,7 @@ async function executeRegistered( return (await tool.execute(input, { signal })) as T; } -/** The call shape `@mcp-b/global` uses: the input and nothing else. */ +/** The call shape `@mcp-b/global` used before 6.0: the input and nothing else. */ async function executeRegisteredWithoutOptions( registered: ModelContextTool[], name: string, @@ -362,7 +362,7 @@ describe("useStudioAgentTools", () => { }); 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 + // `@mcp-b/global` before 6.0 invoked `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`. diff --git a/packages/studio/src/webmcp/useStudioAgentTools.ts b/packages/studio/src/webmcp/useStudioAgentTools.ts index 3d34804317..6f555f036c 100644 --- a/packages/studio/src/webmcp/useStudioAgentTools.ts +++ b/packages/studio/src/webmcp/useStudioAgentTools.ts @@ -117,9 +117,8 @@ export function buildStudioTools(depsRef: { /** * `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 + * The spec shape is `execute(input, { signal })`, but `@mcp-b/global` before + * 6.0 invoked 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