Skip to content

Commit 097d901

Browse files
feat(studio): fall back to a WebMCP polyfill where the browser has none (#3514)
* feat(studio): fall back to a WebMCP polyfill where the browser has none WebMCP is an Origin Trial. Chrome 149 and Edge 150 have it behind a flag, ChatGPT Desktop ships it, and everything else does not. Without a fallback the tools registered in the previous change are invisible on stable Chrome, which is exactly where a bridge extension would connect from. Adds `@mcp-b/global` (MIT) as a DYNAMIC import, so a browser with native support never fetches it. Verified in the build output rather than asserted: the bundle keeps a bare `import("@mcp-b/global")` instead of inlining it. Chosen over the smaller `@mcp-b/webmcp-polyfill` because that one only defines `document.modelContext`. `@mcp-b/global` also stands up the in-page MCP server a bridge extension attaches to, and serving that case is the only reason the fallback exists at all. The load is guarded by a module-level promise so two mounts racing share one load, and an import failure is caught and logged rather than thrown: a missing agent surface must never stop Studio booting. The registration path re-checks the abort signal after the await, so unmounting mid-import registers nothing. Two things the type checker forced, both worth keeping: Installing the package brings its own global `Document.modelContext` declaration, which collided with the local one. Studio now reads the property through a type guard instead of augmenting `Document`, so there is only one declaration of that global and it is the package's. Studio keeps its own narrow tool types rather than importing the package's. Theirs overload `registerTool` to infer argument types from a literal `inputSchema`, which helps when registering one tool inline and fights a uniform registration loop. The comment in `types.ts` says so, and names the drift risk that choice accepts. The polyfill test asserts promise identity rather than counting imports. The ESM registry dedupes the import either way, so a call count would pass whether or not the guard existed. * fix(studio): observe and retry WebMCP fallback
1 parent 94da403 commit 097d901

7 files changed

Lines changed: 245 additions & 35 deletions

File tree

‎bun.lock‎

Lines changed: 38 additions & 13 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎packages/studio/package.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,7 @@
7171
"@hyperframes/player": "workspace:*",
7272
"@hyperframes/sdk": "workspace:*",
7373
"@hyperframes/studio-server": "workspace:*",
74+
"@mcp-b/global": "^5.0.1",
7475
"@phosphor-icons/react": "^2.1.10",
7576
"@tanstack/react-virtual": "^3.14.6",
7677
"bpm-detective": "^2.0.5",
Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
// @vitest-environment jsdom
2+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
3+
import type { ModelContext } from "./types";
4+
5+
// The real package defines `document.modelContext` as an import side effect.
6+
// A mock cannot do that, so tests stand the object up themselves to represent
7+
// the import having happened.
8+
const trackEvent = vi.hoisted(() => vi.fn());
9+
vi.mock("@mcp-b/global", () => ({}));
10+
vi.mock("../telemetry/client", () => ({ trackEvent }));
11+
12+
let loadModelContextPolyfill: typeof import("./polyfill").loadModelContextPolyfill;
13+
14+
function installModelContext(): ModelContext {
15+
const modelContext: ModelContext = { registerTool: vi.fn().mockResolvedValue(undefined) };
16+
Object.defineProperty(document, "modelContext", {
17+
value: modelContext,
18+
configurable: true,
19+
writable: true,
20+
});
21+
return modelContext;
22+
}
23+
24+
beforeEach(async () => {
25+
vi.resetModules();
26+
({ loadModelContextPolyfill } = await import("./polyfill"));
27+
trackEvent.mockReset();
28+
});
29+
30+
afterEach(() => {
31+
Reflect.deleteProperty(document, "modelContext");
32+
vi.restoreAllMocks();
33+
});
34+
35+
describe("loadModelContextPolyfill", () => {
36+
it("returns the model context the package defines", async () => {
37+
const modelContext = installModelContext();
38+
39+
await expect(loadModelContextPolyfill()).resolves.toBe(modelContext);
40+
expect(trackEvent).toHaveBeenCalledWith("webmcp.polyfill_loaded");
41+
});
42+
43+
it("shares one load between callers that race", async () => {
44+
installModelContext();
45+
46+
// Identity, not a call count: the guard being tested is the module-level
47+
// promise, and the ESM registry would dedupe the import either way.
48+
const first = loadModelContextPolyfill();
49+
const second = loadModelContextPolyfill();
50+
51+
expect(first).toBe(second);
52+
await expect(first).resolves.toBe(await second);
53+
});
54+
55+
it("reuses the settled load rather than starting another", async () => {
56+
installModelContext();
57+
58+
const first = loadModelContextPolyfill();
59+
await first;
60+
61+
expect(loadModelContextPolyfill()).toBe(first);
62+
});
63+
64+
it("returns null when the package loads but defines nothing", async () => {
65+
// Studio must still boot. A missing agent surface is not a broken editor.
66+
const first = loadModelContextPolyfill();
67+
await expect(first).resolves.toBeNull();
68+
69+
expect(trackEvent).toHaveBeenCalledWith("webmcp.polyfill_failed", {
70+
error_name: "ModelContextMissingError",
71+
});
72+
const retry = loadModelContextPolyfill();
73+
expect(retry).not.toBe(first);
74+
await expect(retry).resolves.toBeNull();
75+
});
76+
77+
it("reports a polyfill failure and lets a later mount retry", async () => {
78+
const failure = new TypeError("blocked by policy");
79+
Object.defineProperty(document, "modelContext", {
80+
configurable: true,
81+
get: () => {
82+
throw failure;
83+
},
84+
});
85+
86+
const first = loadModelContextPolyfill();
87+
await expect(first).resolves.toBeNull();
88+
expect(trackEvent).toHaveBeenCalledWith("webmcp.polyfill_failed", {
89+
error_name: "TypeError",
90+
});
91+
92+
Reflect.deleteProperty(document, "modelContext");
93+
const modelContext = installModelContext();
94+
const retry = loadModelContextPolyfill();
95+
expect(retry).not.toBe(first);
96+
await expect(retry).resolves.toBe(modelContext);
97+
});
98+
});
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
/**
2+
* The fallback for browsers that have not shipped WebMCP.
3+
*
4+
* `@mcp-b/global` does two things: it defines `document.modelContext`, and it
5+
* stands up an in-page MCP server for a bridge extension to attach to. The
6+
* second is the reason this is the chosen package over the bare
7+
* `@mcp-b/webmcp-polyfill`: without the server there is nothing for an
8+
* out-of-browser agent to connect to, which is the only case the fallback
9+
* exists to serve.
10+
*
11+
* It is a DYNAMIC import so a browser with native support never downloads it,
12+
* and so it lands in its own chunk rather than the entry bundle.
13+
*/
14+
15+
import { makeStudioDebugLogger } from "../utils/studioDebug";
16+
import { trackEvent } from "../telemetry/client";
17+
import { getModelContext, type ModelContext } from "./types";
18+
19+
const log = makeStudioDebugLogger("webmcp");
20+
21+
/**
22+
* Module-level, so two mounts racing (React StrictMode, or a remount during
23+
* the import) share one load instead of pulling the package twice.
24+
*/
25+
let pending: Promise<ModelContext | null> | null = null;
26+
27+
async function importPolyfill(): Promise<ModelContext | null> {
28+
try {
29+
await import("@mcp-b/global");
30+
const modelContext = getModelContext();
31+
if (!modelContext) {
32+
// The package loaded but did not define what it promises to define.
33+
log("polyfill", { loaded: true, modelContext: false });
34+
trackEvent("webmcp.polyfill_failed", { error_name: "ModelContextMissingError" });
35+
} else {
36+
trackEvent("webmcp.polyfill_loaded");
37+
}
38+
return modelContext;
39+
} catch (error) {
40+
// A missing agent surface must never break Studio's boot.
41+
log("polyfill", { failed: error instanceof Error ? error.message : String(error) });
42+
trackEvent("webmcp.polyfill_failed", {
43+
error_name: error instanceof Error ? error.name : "NonError",
44+
});
45+
return null;
46+
}
47+
}
48+
49+
export function loadModelContextPolyfill(): Promise<ModelContext | null> {
50+
if (pending) return pending;
51+
52+
const attempt = importPolyfill();
53+
pending = attempt;
54+
// A transient chunk/CSP failure must not disable WebMCP for the rest of the
55+
// tab. Concurrent callers still share this attempt; a later mount may retry.
56+
void attempt.then((modelContext) => {
57+
if (modelContext === null && pending === attempt) pending = null;
58+
});
59+
return pending;
60+
}

0 commit comments

Comments
 (0)