From 3e8d55a402d53ab50795ed5c03a4648860f7cd09 Mon Sep 17 00:00:00 2001 From: Yoav Weiss Date: Thu, 15 Oct 2026 09:36:21 +0300 Subject: [PATCH 1/8] Match WebMCP shape where executeTools takes an object --- examples/AGENTS.md | 2 +- src/content-scripts/page-bridge.js | 7 +- src/content-scripts/webmcp-polyfill.js | 38 ++++++++++- src/lib/webmcp/lifecycle.ts | 3 +- tests/browser/webmcp-wpt.mjs | 2 +- tests/webmcp-page-bridge.test.ts | 21 ++++-- tests/webmcp-polyfill.test.ts | 95 ++++++++++++++++++++++---- tests/webmcp-script-injector.test.ts | 4 +- 8 files changed, 139 insertions(+), 33 deletions(-) diff --git a/examples/AGENTS.md b/examples/AGENTS.md index 287ea68..06e7603 100644 --- a/examples/AGENTS.md +++ b/examples/AGENTS.md @@ -484,7 +484,7 @@ if (document.modelContext) { - `registerTool(tool, options)` - Register one uniquely named tool; use `options.signal` to remove it - `getTools(options)` - Discover visible tool descriptors -- `executeTool(tool, jsonArguments, options)` - Execute a discovered descriptor +- `executeTool(tool, inputObject, options)` - Execute a discovered descriptor with an input object (omitted means `{}`) - `addEventListener('toolchange', handler)` - Observe registration changes ## Testing Your Tool diff --git a/src/content-scripts/page-bridge.js b/src/content-scripts/page-bridge.js index d3b1ed7..882ea14 100644 --- a/src/content-scripts/page-bridge.js +++ b/src/content-scripts/page-bridge.js @@ -241,11 +241,8 @@ const methods = getApiMethods(); if (!methods) throw new PublicBridgeError('Tool catalog is unavailable'); - return Reflect.apply(methods.executeTool, api, [ - registeredTool, - JSON.stringify(args ?? {}), - { signal } - ]); + // executeTool() takes the input object itself and serializes it (Chromium M155+). + return Reflect.apply(methods.executeTool, api, [registeredTool, args ?? {}, { signal }]); } async function onMessage(event) { diff --git a/src/content-scripts/webmcp-polyfill.js b/src/content-scripts/webmcp-polyfill.js index 609b93b..c80fdb9 100644 --- a/src/content-scripts/webmcp-polyfill.js +++ b/src/content-scripts/webmcp-polyfill.js @@ -83,6 +83,20 @@ return new DOMException('WebMCP tool execution failed', 'UnknownError'); } + /** Web IDL `object` conversion accepts functions and rejects null and every other primitive. */ + function isWebIdlObject(value) { + return (typeof value === 'object' && value !== null) || typeof value === 'function'; + } + + /** Infra's "serialize a JavaScript value to a JSON string". */ + function serializeJsonString(value) { + const serialized = JSON.stringify(value); + if (serialized === undefined) { + throw new TypeError('Value cannot be serialized to a JSON string'); + } + return serialized; + } + function serializeExecutionResult(value) { const serialized = value !== null && typeof value === 'object' ? JSON.stringify(value) : String(value); @@ -218,7 +232,10 @@ window, origin: window.location.origin }; - if (entry.inputSchema !== undefined) descriptor.inputSchema = entry.inputSchema; + // Like Chromium, expose a fresh object parsed from the schema serialized at registration. + if (entry.inputSchema !== undefined) { + descriptor.inputSchema = JSON.parse(entry.inputSchema); + } if (entry.annotations !== undefined) descriptor.annotations = { ...entry.annotations }; return descriptor; }); @@ -226,7 +243,7 @@ return Promise.resolve(tools); } - executeTool(tool, inputArguments, rawOptions = {}) { + executeTool(tool, inputObject, rawOptions = {}) { if (this === null || !(this instanceof LocalModelContext)) { throw new TypeError('Illegal invocation'); } @@ -250,11 +267,25 @@ } const origin = String(descriptor.origin).toWellFormed(); + // `optional object inputObject`: undefined means omitted; any other non-object is a TypeError. + if (inputObject !== undefined && !isWebIdlObject(inputObject)) { + return Promise.reject(new TypeError("The 'inputObject' argument must be an object")); + } + const options = rawOptions ?? {}; const signal = options.signal; if (signal !== undefined && !(signal instanceof AbortSignal)) { throw new TypeError("The 'signal' member must be an AbortSignal"); } + + // The tool receives only the JSON serialization of the caller's object, never the object + // itself. Serialization failures reject before the abort check, matching the spec's order. + let inputArguments; + try { + inputArguments = serializeJsonString(inputObject === undefined ? {} : inputObject); + } catch (error) { + return Promise.reject(error); + } if (signal?.aborted) return Promise.reject(signal.reason); const entry = @@ -263,9 +294,10 @@ : null; if (!entry) return Promise.reject(unknownError()); + // A toJSON() method can serialize an object to a primitive; tools only ever receive objects. let input; try { - input = JSON.parse(String(inputArguments)); + input = JSON.parse(inputArguments); } catch { return Promise.reject(unknownError()); } diff --git a/src/lib/webmcp/lifecycle.ts b/src/lib/webmcp/lifecycle.ts index dcc740c..f10049a 100644 --- a/src/lib/webmcp/lifecycle.ts +++ b/src/lib/webmcp/lifecycle.ts @@ -397,7 +397,8 @@ export class TabManager { return; } - // Parse inputSchema if it's a JSON string (Chrome's native API returns it as string) + // Current Chromium and the local polyfill expose inputSchema as an object; Chromium before M155 + // exposed a JSON string, which is still parsed here. const normalizedTools = (params.tools || []).map((tool) => { let inputSchema = tool.inputSchema; if (typeof inputSchema === 'string') { diff --git a/tests/browser/webmcp-wpt.mjs b/tests/browser/webmcp-wpt.mjs index 14b0fe8..b57a0e6 100644 --- a/tests/browser/webmcp-wpt.mjs +++ b/tests/browser/webmcp-wpt.mjs @@ -6,7 +6,7 @@ import { fileURLToPath } from 'node:url'; import { chromeSandboxArgs, findChrome } from './chrome-harness.mjs'; const repositoryRoot = fileURLToPath(new URL('../../', import.meta.url)); -const defaultWptRevision = 'c7c7a1b2641777d1f5f3934705ddde645eb82116'; +const defaultWptRevision = '0c7a6c61ffc3e1d4eab65b7a8a6b1281aaa7c703'; const wptRevision = process.env.AGENTBOARD_WPT_REVISION || defaultWptRevision; const wptRoot = path.resolve( process.env.AGENTBOARD_WPT_ROOT || path.join(repositoryRoot, 'local/wpt') diff --git a/tests/webmcp-page-bridge.test.ts b/tests/webmcp-page-bridge.test.ts index 3eedc9e..d75da68 100644 --- a/tests/webmcp-page-bridge.test.ts +++ b/tests/webmcp-page-bridge.test.ts @@ -75,7 +75,7 @@ function nativeTool(window: Window, name: string, overrides: Partial name, title: '', description: `${name} description`, - inputSchema: JSON.stringify({ type: 'object', properties: {} }), + inputSchema: { type: 'object', properties: {} }, window, origin: window.location.origin, ...overrides, @@ -149,10 +149,10 @@ describe('WebMCP page bridge catalog and execution', () => { { name: 'local_tool', description: 'Local tool', - inputSchema: JSON.stringify({ + inputSchema: { type: 'object', properties: { value: { type: 'number' } }, - }), + }, }, ], }, @@ -173,7 +173,7 @@ describe('WebMCP page bridge catalog and execution', () => { expect(response(harness, 'local-call').result).toBe(JSON.stringify({ echoed: { value: 7 } })); }); - it('keeps native Window descriptors in-page and invokes the exact descriptor with JSON', async () => { + it('keeps native Window descriptors in-page and invokes the exact descriptor with an object', async () => { const harness = createHarness({ loadPolyfill: false }); const descriptor = nativeTool(harness.window, 'native_tool', { annotations: { readOnlyHint: true }, @@ -201,11 +201,22 @@ describe('WebMCP page bridge catalog and execution', () => { await flush(harness.window); expect(native.api.executeTool.mock.calls[0][0]).toBe(descriptor); - expect(native.api.executeTool.mock.calls[0][1]).toBe(JSON.stringify({ answer: 42 })); + // Chromium M155+ takes the input object itself; a JSON string is rejected as a non-object. + expect(native.api.executeTool.mock.calls[0][1]).toEqual({ answer: 42 }); expect(native.api.executeTool.mock.calls[0][2].signal).toBeInstanceOf( harness.window.AbortSignal ); expect(response(harness, 'native-call').result).toBe('native-result'); + + harness.send({ + id: 'native-call-without-arguments', + method: 'tools/call', + params: { name: 'native_tool' }, + }); + await flush(harness.window); + + expect(native.api.executeTool.mock.calls[1][1]).toEqual({}); + expect(response(harness, 'native-call-without-arguments').result).toBe('native-result'); }); it('forwards cancellation to an in-flight ModelContext execution', async () => { diff --git a/tests/webmcp-polyfill.test.ts b/tests/webmcp-polyfill.test.ts index 8cf329c..f0e3e7e 100644 --- a/tests/webmcp-polyfill.test.ts +++ b/tests/webmcp-polyfill.test.ts @@ -260,7 +260,7 @@ describe('WebMCP local backend contract', () => { const dom = createDom(); loadPolyfill(dom); const modelContext = (dom.window.document as any).modelContext; - await registerTool(modelContext, { + const { tool: zTool } = await registerTool(modelContext, { name: 'z_tool', title: 'Zed', annotations: { readOnlyHint: true, untrustedContentHint: true }, @@ -269,6 +269,8 @@ describe('WebMCP local backend contract', () => { name: 'a_tool', inputSchema: undefined, }); + // Registration serializes the schema; later mutation of the page's object is not observed. + (zTool.inputSchema as Record).type = 'mutated after registration'; const first = await modelContext.getTools(); const second = await modelContext.getTools(); @@ -284,10 +286,17 @@ describe('WebMCP local backend contract', () => { expect(first[0]).not.toHaveProperty('inputSchema'); expect(first[1]).toMatchObject({ title: 'Zed', - inputSchema: JSON.stringify({ type: 'object', properties: {} }), + inputSchema: { type: 'object', properties: {} }, annotations: { readOnlyHint: true, untrustedContentHint: true }, }); expect(first[0]).not.toBe(second[0]); + // Each descriptor carries its own object parsed from the serialized registration schema. + expect(first[1].inputSchema).not.toBe(second[1].inputSchema); + first[1].inputSchema.type = 'mutated by caller'; + expect((await modelContext.getTools())[1].inputSchema).toEqual({ + type: 'object', + properties: {}, + }); }); it('converts tool titles as USVString values', async () => { @@ -414,13 +423,16 @@ describe('WebMCP local backend contract', () => { execute, }); const [descriptor] = await modelContext.getTools(); + const input = { value: 7 }; - const result = await modelContext.executeTool(descriptor, JSON.stringify({ value: 7 })); + const result = await modelContext.executeTool(descriptor, input); expect(execute).toHaveBeenCalledWith( { value: 7 }, { signal: expect.any(dom.window.AbortSignal) } ); + // The tool receives a JSON round trip of the caller's object, never the object itself. + expect(execute.mock.calls[0][0]).not.toBe(input); expect(execute.mock.calls[0][1].signal.aborted).toBe(false); expect(receiver).toBeUndefined(); expect(result).toBe(JSON.stringify({ echoed: { value: 7 } })); @@ -441,7 +453,7 @@ describe('WebMCP local backend contract', () => { }); const [descriptor] = await modelContext.getTools(); - await expect(modelContext.executeTool(descriptor, '{}')).rejects.toMatchObject({ + await expect(modelContext.executeTool(descriptor, {})).rejects.toMatchObject({ name: 'UnknownError', message: 'WebMCP tool execution failed', }); @@ -463,7 +475,7 @@ describe('WebMCP local backend contract', () => { }); const [descriptor] = await modelContext.getTools(); - await expect(modelContext.executeTool(descriptor, '{}')).rejects.toMatchObject({ + await expect(modelContext.executeTool(descriptor, {})).rejects.toMatchObject({ name: 'UnknownError', message: 'WebMCP tool execution failed', }); @@ -480,25 +492,78 @@ describe('WebMCP local backend contract', () => { for (const member of ['name', 'description', 'window', 'origin']) { const missingDescriptor = { ...descriptor }; delete missingDescriptor[member]; - await expect(modelContext.executeTool(missingDescriptor, '{}')).rejects.toBeInstanceOf( + await expect(modelContext.executeTool(missingDescriptor, {})).rejects.toBeInstanceOf( dom.window.TypeError ); await expect( - modelContext.executeTool({ ...descriptor, [member]: undefined }, '{}') + modelContext.executeTool({ ...descriptor, [member]: undefined }, {}) ).rejects.toBeInstanceOf(dom.window.TypeError); } await expect( - modelContext.executeTool({ ...descriptor, window: {} }, '{}') + modelContext.executeTool({ ...descriptor, window: {} }, {}) ).rejects.toBeInstanceOf(dom.window.TypeError); - for (const input of ['not-json', '"primitive"', '123', 'true', 'null']) { - await expect(modelContext.executeTool(descriptor, input)).rejects.toMatchObject({ - name: 'UnknownError', - }); + await expect( + modelContext.executeTool({ ...descriptor, name: 'missing_tool' }, {}) + ).rejects.toMatchObject({ name: 'UnknownError' }); + }); + + it('takes an input object and rejects what object conversion or JSON serialization rejects', async () => { + const dom = createDom(); + loadPolyfill(dom); + const modelContext = (dom.window.document as any).modelContext; + const { execute } = await registerTool(modelContext); + const [descriptor] = await modelContext.getTools(); + + // Arrays are objects; an omitted or undefined input is an empty object. + await modelContext.executeTool(descriptor, [1, 2, 3]); + await modelContext.executeTool(descriptor); + await modelContext.executeTool(descriptor, undefined); + await modelContext.executeTool(descriptor, undefined, {}); + expect(execute.mock.calls.map(([input]) => input)).toEqual([[1, 2, 3], {}, {}, {}]); + execute.mockClear(); + + const circular: Record = {}; + circular.self = circular; + for (const input of [ + '{}', + 'hello', + 123, + true, + null, + 10n, + Symbol('input'), + () => ({}), + { toJSON: () => undefined }, + { count: 10n }, + circular, + ]) { + await expect(modelContext.executeTool(descriptor, input)).rejects.toBeInstanceOf( + dom.window.TypeError + ); } + + const serializationError = new Error('toJSON failure'); await expect( - modelContext.executeTool({ ...descriptor, name: 'missing_tool' }, '{}') + modelContext.executeTool(descriptor, { + toJSON() { + throw serializationError; + }, + }) + ).rejects.toBe(serializationError); + + // Serialization precedes the abort check, so invalid input wins over an aborted signal. + const aborted = new dom.window.AbortController(); + aborted.abort(); + await expect( + modelContext.executeTool(descriptor, circular, { signal: aborted.signal }) + ).rejects.toBeInstanceOf(dom.window.TypeError); + + // toJSON() can serialize an object to a primitive, which never reaches the tool. + await expect( + modelContext.executeTool(descriptor, { toJSON: () => 'primitive' }) ).rejects.toMatchObject({ name: 'UnknownError' }); + expect(execute).not.toHaveBeenCalled(); }); it('propagates per-execution cancellation with Chromium event ordering', async () => { @@ -527,7 +592,7 @@ describe('WebMCP local backend contract', () => { const preAbortedReason = { reason: 'already cancelled' }; preAborted.abort(preAbortedReason); await expect( - modelContext.executeTool(descriptor, '{}', { signal: preAborted.signal }) + modelContext.executeTool(descriptor, {}, { signal: preAborted.signal }) ).rejects.toBe(preAbortedReason); expect(execute).not.toHaveBeenCalled(); @@ -553,7 +618,7 @@ describe('WebMCP local backend contract', () => { const controller = new dom.window.AbortController(); const reason = { reason: 'cancelled' }; - const execution = modelContext.executeTool(descriptor, '{}', { signal: controller.signal }); + const execution = modelContext.executeTool(descriptor, {}, { signal: controller.signal }); expect(execute).toHaveBeenCalledOnce(); expect(events).toEqual(['tool started', 'toolactivated']); diff --git a/tests/webmcp-script-injector.test.ts b/tests/webmcp-script-injector.test.ts index 0cbecb2..3cef116 100644 --- a/tests/webmcp-script-injector.test.ts +++ b/tests/webmcp-script-injector.test.ts @@ -379,7 +379,7 @@ describe('WebMCP Script Injector', () => { expect(initialSignal.aborted).toBe(false); let tools = await modelContext.getTools(); const initialTool = tools.find((tool: any) => tool.name === 'test_test_tool'); - expect(await modelContext.executeTool(initialTool, '{}')).toBe('test result'); + expect(await modelContext.executeTool(initialTool, {})).toBe('test result'); mockExecuteScript.mockClear(); vi.mocked(chrome.tabs.get).mockResolvedValue({ @@ -410,7 +410,7 @@ describe('WebMCP Script Injector', () => { tools = await modelContext.getTools(); const updatedTool = tools.find((tool: any) => tool.name === 'test_test_tool'); expect(tools).toHaveLength(1); - expect(await modelContext.executeTool(updatedTool, '{}')).toBe('updated result'); + expect(await modelContext.executeTool(updatedTool, {})).toBe('updated result'); dom.window.close(); }); From 1dd0a29816ff2ee2fcc50f2c0f60c1e41f41ca1a Mon Sep 17 00:00:00 2001 From: Ilya Grigorik Date: Fri, 16 Oct 2026 22:16:51 -0700 Subject: [PATCH 2/8] expose consequentialHint and debugging in polyfill ToolAnnotations Chromium (M155 and M156 respectively) added two members to the ToolAnnotations dictionary. Dictionary conversion means every member reads back as false once annotations are present, so getTools() descriptors from the polyfill were missing keys that WPT getTools-imperative-annotations now asserts at the revision this branch pins. --- src/content-scripts/webmcp-polyfill.js | 5 ++++- tests/webmcp-polyfill.test.ts | 27 ++++++++++++++++++++++++-- 2 files changed, 29 insertions(+), 3 deletions(-) diff --git a/src/content-scripts/webmcp-polyfill.js b/src/content-scripts/webmcp-polyfill.js index c80fdb9..ce92aa3 100644 --- a/src/content-scripts/webmcp-polyfill.js +++ b/src/content-scripts/webmcp-polyfill.js @@ -175,10 +175,13 @@ } if (signal?.aborted) return Promise.reject(signal.reason); + // ToolAnnotations dictionary conversion: every member defaults to false once annotations exist. const annotations = rawTool.annotations ? { readOnlyHint: Boolean(rawTool.annotations.readOnlyHint), - untrustedContentHint: Boolean(rawTool.annotations.untrustedContentHint) + untrustedContentHint: Boolean(rawTool.annotations.untrustedContentHint), + consequentialHint: Boolean(rawTool.annotations.consequentialHint), + debugging: Boolean(rawTool.annotations.debugging) } : undefined; const entry = { diff --git a/tests/webmcp-polyfill.test.ts b/tests/webmcp-polyfill.test.ts index f0e3e7e..9ba8008 100644 --- a/tests/webmcp-polyfill.test.ts +++ b/tests/webmcp-polyfill.test.ts @@ -263,7 +263,7 @@ describe('WebMCP local backend contract', () => { const { tool: zTool } = await registerTool(modelContext, { name: 'z_tool', title: 'Zed', - annotations: { readOnlyHint: true, untrustedContentHint: true }, + annotations: { readOnlyHint: true, untrustedContentHint: true, debugging: true }, }); await registerTool(modelContext, { name: 'a_tool', @@ -287,7 +287,13 @@ describe('WebMCP local backend contract', () => { expect(first[1]).toMatchObject({ title: 'Zed', inputSchema: { type: 'object', properties: {} }, - annotations: { readOnlyHint: true, untrustedContentHint: true }, + }); + // ToolAnnotations is a dictionary: omitted members read back as false, never as missing. + expect(first[1].annotations).toEqual({ + readOnlyHint: true, + untrustedContentHint: true, + consequentialHint: false, + debugging: true, }); expect(first[0]).not.toBe(second[0]); // Each descriptor carries its own object parsed from the serialized registration schema. @@ -299,6 +305,23 @@ describe('WebMCP local backend contract', () => { }); }); + it('exposes every ToolAnnotations member once annotations are provided', async () => { + const dom = createDom(); + loadPolyfill(dom); + const modelContext = (dom.window.document as any).modelContext; + await registerTool(modelContext, { name: 'bare_tool' }); + await registerTool(modelContext, { name: 'empty_tool', annotations: {} }); + + const [bare, empty] = await modelContext.getTools(); + expect(bare).not.toHaveProperty('annotations'); + expect(empty.annotations).toEqual({ + readOnlyHint: false, + untrustedContentHint: false, + consequentialHint: false, + debugging: false, + }); + }); + it('converts tool titles as USVString values', async () => { const dom = createDom(); loadPolyfill(dom); From cc1b37a5aec4a23c2eba005b5270c46ff322ccfb Mon Sep 17 00:00:00 2001 From: Ilya Grigorik Date: Fri, 16 Oct 2026 22:20:33 -0700 Subject: [PATCH 3/8] dispatch ToolActivatedEvent and ToolCancelEvent at the polyfill ModelContext Chromium moved toolactivated and toolcancel from window to document.modelContext as ToolActivatedEvent/ToolCancelEvent instances (M156) and removed the window dispatch; WPT executeTool-abort at the pinned revision asserts the new target, the interface brand and event.target identity, and timed out against the polyfill's window-targeted plain Events. The local backend now fires the two interfaces at itself and the facade re-dispatches fresh instances so page code observes document.modelContext as the target, the same way toolchange was already forwarded. ontoolactivated and ontoolcancel join ontoolchange; the three handler attributes share one Web IDL style definition instead of a hand-written accessor pair per class. --- examples/AGENTS.md | 1 + src/content-scripts/webmcp-polyfill.js | 130 ++++++++++++++++--------- tests/webmcp-polyfill.test.ts | 120 +++++++++++++++++++++-- 3 files changed, 194 insertions(+), 57 deletions(-) diff --git a/examples/AGENTS.md b/examples/AGENTS.md index 06e7603..993ff5c 100644 --- a/examples/AGENTS.md +++ b/examples/AGENTS.md @@ -486,6 +486,7 @@ if (document.modelContext) { - `getTools(options)` - Discover visible tool descriptors - `executeTool(tool, inputObject, options)` - Execute a discovered descriptor with an input object (omitted means `{}`) - `addEventListener('toolchange', handler)` - Observe registration changes +- `addEventListener('toolactivated' | 'toolcancel', handler)` - Observe execution start and cancellation; `event.toolName` names the tool ## Testing Your Tool diff --git a/src/content-scripts/webmcp-polyfill.js b/src/content-scripts/webmcp-polyfill.js index ce92aa3..b80fded 100644 --- a/src/content-scripts/webmcp-polyfill.js +++ b/src/content-scripts/webmcp-polyfill.js @@ -103,19 +103,77 @@ return serialized || 'Operation succeeded'; } - function dispatchToolEvent(type, toolName) { - const event = new Event(type); - Object.defineProperty(event, 'toolName', { - value: toolName, - configurable: true, - enumerable: true - }); - window.dispatchEvent(event); + /** + * `interface ToolActivatedEvent : Event { constructor(DOMString type, optional init = {}); + * readonly attribute DOMString toolName; }` and the identically shaped ToolCancelEvent. Both + * are dispatched at the ModelContext, matching Chromium since M156; nothing fires at window. + */ + function defineToolEventInterface(interfaceName) { + const ToolEvent = class extends Event { + #toolName; + + constructor(type, eventInitDict = {}) { + super(type, eventInitDict); + const toolName = eventInitDict?.toolName; + this.#toolName = toolName === undefined ? '' : String(toolName); + } + + get toolName() { + return this.#toolName; + } + }; + Object.defineProperty(ToolEvent, 'name', { value: interfaceName }); + Object.defineProperty(ToolEvent.prototype, Symbol.toStringTag, { value: interfaceName }); + return ToolEvent; + } + + const ToolActivatedEvent = defineToolEventInterface('ToolActivatedEvent'); + const ToolCancelEvent = defineToolEventInterface('ToolCancelEvent'); + const TOOL_EVENT_INTERFACES = { toolactivated: ToolActivatedEvent, toolcancel: ToolCancelEvent }; + const MODEL_CONTEXT_EVENT_TYPES = ['toolchange', 'toolactivated', 'toolcancel']; + + /** Re-create an event so a forwarding target dispatches its own instance, never a used one. */ + function cloneModelContextEvent(event) { + const ToolEvent = TOOL_EVENT_INTERFACES[event.type]; + if (!ToolEvent) return new Event(event.type); + return new ToolEvent(event.type, { toolName: event.toolName }); + } + + /** + * Web IDL event handler attributes (`ontoolchange` etc.) layered over EventTarget. One shared + * definition serves both the local backend and the public facade; the handler map lives outside + * the classes because private fields cannot be installed on a prototype from a helper. + */ + const eventHandlerAttributes = new WeakMap(); + function defineEventHandlerAttributes(prototype, types) { + for (const type of types) { + Object.defineProperty(prototype, `on${type}`, { + configurable: true, + enumerable: true, + get() { + return eventHandlerAttributes.get(this)?.get(type) ?? null; + }, + set(callback) { + if (callback !== null && typeof callback !== 'function') { + throw new TypeError(`on${type} must be a function or null`); + } + let handlers = eventHandlerAttributes.get(this); + if (!handlers) eventHandlerAttributes.set(this, (handlers = new Map())); + const previous = handlers.get(type); + if (previous) this.removeEventListener(type, previous); + if (callback) { + handlers.set(type, callback); + this.addEventListener(type, callback); + } else { + handlers.delete(type); + } + } + }); + } } class LocalModelContext extends EventTarget { #tools = new Map(); - #ontoolchange = null; registerTool(rawTool, rawOptions = {}) { if (this === null || !(this instanceof LocalModelContext)) { @@ -175,7 +233,7 @@ } if (signal?.aborted) return Promise.reject(signal.reason); - // ToolAnnotations dictionary conversion: every member defaults to false once annotations exist. + // ToolAnnotations is a dictionary: once present, every omitted member reads back as false. const annotations = rawTool.annotations ? { readOnlyHint: Boolean(rawTool.annotations.readOnlyHint), @@ -323,7 +381,7 @@ // Caller rejection runs first; target cancellation crosses a browser boundary in Chromium. setTimeout(() => { callbackController.abort(abortError()); - dispatchToolEvent('toolcancel', name); + this.dispatchEvent(new ToolCancelEvent('toolcancel', { toolName: name })); }, 0); }; signal?.addEventListener('abort', onAbort, { once: true }); @@ -338,7 +396,7 @@ } catch { callbackFailed = true; } - dispatchToolEvent('toolactivated', name); + this.dispatchEvent(new ToolActivatedEvent('toolactivated', { toolName: name })); if (callbackFailed) { if (!settled) { @@ -367,19 +425,6 @@ }); } - set ontoolchange(callback) { - if (callback !== null && typeof callback !== 'function') { - throw new TypeError('ontoolchange must be a function or null'); - } - if (this.#ontoolchange) this.removeEventListener('toolchange', this.#ontoolchange); - this.#ontoolchange = callback; - if (callback) this.addEventListener('toolchange', callback); - } - - get ontoolchange() { - return this.#ontoolchange; - } - #queueToolChange(afterDispatch) { setTimeout(() => { this.dispatchEvent(new Event('toolchange')); @@ -391,6 +436,7 @@ Object.defineProperty(LocalModelContext.prototype, Symbol.toStringTag, { value: 'ModelContext' }); + defineEventHandlerAttributes(LocalModelContext.prototype, MODEL_CONTEXT_EVENT_TYPES); ensureTrustedTypesPolicy(); @@ -419,8 +465,10 @@ const native = readNativeModelContext(); const api = native || new LocalModelContext(); - const forwardToolChange = () => facade.dispatchEvent(new Event('toolchange')); - api.addEventListener('toolchange', forwardToolChange); + // Page code only ever holds the facade, so events the backend fires at itself must be + // re-dispatched there with the facade as target. + const forwardEvent = (event) => facade.dispatchEvent(cloneModelContextEvent(event)); + for (const type of MODEL_CONTEXT_EVENT_TYPES) api.addEventListener(type, forwardEvent); selectedBackend = { api, @@ -433,8 +481,6 @@ } class ModelContext extends EventTarget { - #ontoolchange = null; - constructor(...constructionArgs) { if (constructionArgs[0] !== modelContextConstructionKey) { throw new TypeError('Illegal constructor'); @@ -459,29 +505,19 @@ const backend = selectBackend(); return Reflect.apply(backend.executeTool, backend.api, args); } - - set ontoolchange(callback) { - if (callback !== null && typeof callback !== 'function') { - throw new TypeError('ontoolchange must be a function or null'); - } - if (this.#ontoolchange) this.removeEventListener('toolchange', this.#ontoolchange); - this.#ontoolchange = callback; - if (callback) this.addEventListener('toolchange', callback); - } - - get ontoolchange() { - return this.#ontoolchange; - } } Object.defineProperty(ModelContext.prototype, Symbol.toStringTag, { value: 'ModelContext' }); - Object.defineProperty(window, 'ModelContext', { - value: ModelContext, - writable: true, - configurable: true - }); + defineEventHandlerAttributes(ModelContext.prototype, MODEL_CONTEXT_EVENT_TYPES); + for (const [interfaceName, value] of Object.entries({ + ModelContext, + ToolActivatedEvent, + ToolCancelEvent + })) { + Object.defineProperty(window, interfaceName, { value, writable: true, configurable: true }); + } facade = new ModelContext(modelContextConstructionKey); Object.defineProperty(document, 'modelContext', { diff --git a/tests/webmcp-polyfill.test.ts b/tests/webmcp-polyfill.test.ts index 9ba8008..9834c02 100644 --- a/tests/webmcp-polyfill.test.ts +++ b/tests/webmcp-polyfill.test.ts @@ -111,20 +111,111 @@ describe('WebMCP bootstrap backend selection', () => { expect(native.registerTool).toHaveBeenCalledWith(tool); }); - it('forwards native toolchange events through the stable facade', async () => { + it('forwards native ModelContext events through the stable facade', async () => { const dom = createDom(); loadPolyfill(dom); const facade = (dom.window.document as any).modelContext; const native = createNativeModelContext(dom); exposeNativeOnPrototype(dom, native); const listener = vi.fn(); - facade.addEventListener('toolchange', listener); + for (const type of ['toolchange', 'toolactivated', 'toolcancel']) { + facade.addEventListener(type, listener); + } await facade.getTools(); native.dispatchEvent(new dom.window.Event('toolchange')); + const nativeActivated = new dom.window.Event('toolactivated'); + Object.defineProperty(nativeActivated, 'toolName', { value: 'native_tool' }); + native.dispatchEvent(nativeActivated); + const nativeCancelled = new dom.window.Event('toolcancel'); + Object.defineProperty(nativeCancelled, 'toolName', { value: 'native_tool' }); + native.dispatchEvent(nativeCancelled); + + const forwarded = listener.mock.calls.map(([event]) => event); + expect(forwarded.map((event) => event.type)).toEqual([ + 'toolchange', + 'toolactivated', + 'toolcancel', + ]); + expect(forwarded.every((event) => event.target === facade)).toBe(true); + // Forwarded tool events are re-created as the page-visible interfaces, carrying the tool name. + expect(forwarded[1]).toBeInstanceOf((dom.window as any).ToolActivatedEvent); + expect(forwarded[2]).toBeInstanceOf((dom.window as any).ToolCancelEvent); + expect(forwarded.slice(1).map((event) => event.toolName)).toEqual([ + 'native_tool', + 'native_tool', + ]); + }); - expect(listener).toHaveBeenCalledOnce(); - expect(listener.mock.calls[0][0].target).toBe(facade); + it('exposes the ToolActivatedEvent and ToolCancelEvent interfaces', () => { + const dom = createDom(); + loadPolyfill(dom); + const { ToolActivatedEvent, ToolCancelEvent } = dom.window as any; + + for (const [ToolEvent, name] of [ + [ToolActivatedEvent, 'ToolActivatedEvent'], + [ToolCancelEvent, 'ToolCancelEvent'], + ]) { + expect(Object.getOwnPropertyDescriptor(dom.window, name)).toMatchObject({ + value: ToolEvent, + writable: true, + enumerable: false, + configurable: true, + }); + expect(ToolEvent.name).toBe(name); + expect(Object.getPrototypeOf(ToolEvent.prototype)).toBe(dom.window.Event.prototype); + + const event = new ToolEvent('custom', { toolName: 'named', bubbles: true }); + expect(Object.prototype.toString.call(event)).toBe(`[object ${name}]`); + expect(event.type).toBe('custom'); + expect(event.bubbles).toBe(true); + expect(event.toolName).toBe('named'); + // `DOMString toolName = ""`: omitted defaults to the empty string, anything else stringifies. + expect(new ToolEvent('custom').toolName).toBe(''); + expect(new ToolEvent('custom', {}).toolName).toBe(''); + expect(new ToolEvent('custom', { toolName: 7 }).toolName).toBe('7'); + } + }); + + it('implements ontoolchange, ontoolactivated and ontoolcancel handler attributes', async () => { + const dom = createDom(); + loadPolyfill(dom); + const modelContext = (dom.window.document as any).modelContext; + const seen: string[] = []; + + for (const type of ['toolchange', 'toolactivated', 'toolcancel']) { + const attribute = `on${type}`; + expect(modelContext[attribute]).toBeNull(); + expect(() => (modelContext[attribute] = 'nope')).toThrow(dom.window.TypeError); + + const replaced = vi.fn(); + modelContext[attribute] = replaced; + const handler = (event: any) => seen.push(`${type}:${event.toolName ?? ''}`); + modelContext[attribute] = handler; + expect(modelContext[attribute]).toBe(handler); + modelContext.dispatchEvent(new dom.window.Event(type)); + // Assigning a new handler detaches the previous one instead of stacking listeners. + expect(replaced).not.toHaveBeenCalled(); + } + expect(seen).toEqual(['toolchange:', 'toolactivated:', 'toolcancel:']); + seen.length = 0; + + const execute = vi.fn( + () => new Promise(() => {}) // never settles so cancellation is observable + ); + await registerTool(modelContext, { name: 'handled_tool', execute }); + const [descriptor] = await modelContext.getTools(); + const controller = new dom.window.AbortController(); + const execution = modelContext.executeTool(descriptor, {}, { signal: controller.signal }); + controller.abort(); + await expect(execution).rejects.toMatchObject({ name: 'AbortError' }); + await new Promise((resolve) => setTimeout(resolve, 0)); + expect(seen).toEqual(['toolchange:', 'toolactivated:handled_tool', 'toolcancel:handled_tool']); + + modelContext.ontoolcancel = null; + expect(modelContext.ontoolcancel).toBeNull(); + modelContext.dispatchEvent(new dom.window.Event('toolcancel')); + expect(seen).toHaveLength(3); }); it('latches the local backend when first use occurs before native exposure', async () => { @@ -619,19 +710,27 @@ describe('WebMCP local backend contract', () => { ).rejects.toBe(preAbortedReason); expect(execute).not.toHaveBeenCalled(); - dom.window.addEventListener( + // Chromium dispatches ToolActivatedEvent/ToolCancelEvent at the ModelContext, never at window. + const windowListener = vi.fn(); + dom.window.addEventListener('toolactivated', windowListener); + dom.window.addEventListener('toolcancel', windowListener); + modelContext.addEventListener( 'toolactivated', - (event) => { - expect((event as Event & { toolName: string }).toolName).toBe('slow_tool'); + (event: any) => { + expect(event).toBeInstanceOf((dom.window as any).ToolActivatedEvent); + expect(event.target).toBe(modelContext); + expect(event.toolName).toBe('slow_tool'); events.push('toolactivated'); }, { once: true } ); const cancelled = new Promise((resolve) => { - dom.window.addEventListener( + modelContext.addEventListener( 'toolcancel', - (event) => { - expect((event as Event & { toolName: string }).toolName).toBe('slow_tool'); + (event: any) => { + expect(event).toBeInstanceOf((dom.window as any).ToolCancelEvent); + expect(event.target).toBe(modelContext); + expect(event.toolName).toBe('slow_tool'); events.push('toolcancel'); resolve(); }, @@ -661,6 +760,7 @@ describe('WebMCP local backend contract', () => { 'signal aborted', 'toolcancel', ]); + expect(windowListener).not.toHaveBeenCalled(); let serializationAttempted = false; finishExecution({ From dda71eb8dbd57b9956a95c538f372a35215d6c7b Mon Sep 17 00:00:00 2001 From: Ilya Grigorik Date: Fri, 16 Oct 2026 22:21:35 -0700 Subject: [PATCH 4/8] require Chromium M155+ for native WebMCP end to end The bridge now sends executeTool() an object, which Chromium before M155 (DOMString inputArguments) cannot parse, so keeping the lifecycle's parse of string inputSchema values only let a catalog load whose every call would fail. Native and polyfill both expose inputSchema as an object; pass it through. M154 left stable on 2026-10-06 and the WebMCP origin trial runs on 155+, so no supported configuration still speaks the string shape. --- src/content-scripts/page-bridge.js | 1 - src/lib/webmcp/lifecycle.ts | 17 +---------------- 2 files changed, 1 insertion(+), 17 deletions(-) diff --git a/src/content-scripts/page-bridge.js b/src/content-scripts/page-bridge.js index 882ea14..56a0c02 100644 --- a/src/content-scripts/page-bridge.js +++ b/src/content-scripts/page-bridge.js @@ -47,7 +47,6 @@ } function cloneJsonValue(value) { - if (typeof value === 'string') return value; return JSON.parse(JSON.stringify(value)); } diff --git a/src/lib/webmcp/lifecycle.ts b/src/lib/webmcp/lifecycle.ts index f10049a..1ce8cda 100644 --- a/src/lib/webmcp/lifecycle.ts +++ b/src/lib/webmcp/lifecycle.ts @@ -397,23 +397,8 @@ export class TabManager { return; } - // Current Chromium and the local polyfill expose inputSchema as an object; Chromium before M155 - // exposed a JSON string, which is still parsed here. - const normalizedTools = (params.tools || []).map((tool) => { - let inputSchema = tool.inputSchema; - if (typeof inputSchema === 'string') { - try { - inputSchema = JSON.parse(inputSchema); - log.debug(`[WebMCP Lifecycle] Parsed inputSchema for tool "${tool.name}"`); - } catch (e) { - log.warn(`[WebMCP Lifecycle] Failed to parse inputSchema for tool "${tool.name}":`, e); - } - } - return { ...tool, inputSchema }; - }); - const registry: ToolRegistry = { - tools: normalizedTools, + tools: params.tools || [], origin: params.origin || '', timestamp: params.timestamp ?? Date.now(), }; From 00f51d0676a678340eccb81b2088897a6f2334ee Mon Sep 17 00:00:00 2001 From: Ilya Grigorik Date: Fri, 16 Oct 2026 22:24:18 -0700 Subject: [PATCH 5/8] run the WebMCP WPT conformance harness in CI tests/browser/webmcp-wpt.mjs already pins a WPT revision and runs the built polyfill against it with native WebMCP disabled, but only by hand. This branch bumped that pin and would have merged with two files red had the harness not been run manually, so it now runs on the 24.x leg next to the other browser tests. Chrome's wpt product needs no hosts-file changes, so no sudo is required. --- .github/workflows/ci.yml | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8066f3e..7c4a3c7 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -73,6 +73,15 @@ jobs: CHROME_FOR_TESTING_BIN: ${{ steps.setup-chrome.outputs.chrome-path }} AGENTBOARD_CHROME_NO_SANDBOX: '1' + # Runs the built polyfill against the WPT revision pinned in tests/browser/webmcp-wpt.mjs + # with native WebMCP disabled, so a pin bump cannot land while the polyfill lags Chromium. + - name: Run WebMCP polyfill conformance tests (WPT) + if: matrix.node-version == '24.x' + run: pnpm run test:browser:webmcp-wpt:built + env: + CHROME_BIN: ${{ steps.setup-chrome.outputs.chrome-path }} + AGENTBOARD_CHROME_NO_SANDBOX: '1' + # Optional: Upload build artifacts for debugging - name: Upload build artifacts if: always() From 07f08b332710bb11c8137f33cbaa0ce5d09be7d7 Mon Sep 17 00:00:00 2001 From: Ilya Grigorik Date: Fri, 16 Oct 2026 22:40:19 -0700 Subject: [PATCH 6/8] only run the WPT dirty-checkout guard on a pre-existing checkout A fresh `git clone --no-checkout --sparse` reports every tracked file in WPT as deleted, so `git status --porcelain` produced 12 MB of output and spawnSync failed with ENOBUFS at its 1 MB buffer. That path never ran on a machine that already had local/wpt, and CI is the first fresh clone. The guard exists to protect modifications in an existing checkout, so it now runs only there. --- tests/browser/webmcp-wpt.mjs | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/tests/browser/webmcp-wpt.mjs b/tests/browser/webmcp-wpt.mjs index b57a0e6..b5396e0 100644 --- a/tests/browser/webmcp-wpt.mjs +++ b/tests/browser/webmcp-wpt.mjs @@ -81,11 +81,13 @@ function ensureWptCheckout() { wptRoot, ]); git(['sparse-checkout', 'set', ...sparseCheckoutPaths]); - } - - const dirtyFiles = git(['status', '--porcelain', '--untracked-files=no'], { capture: true }); - if (dirtyFiles) { - throw new Error(`Refusing to change the modified WPT checkout at ${wptRoot}:\n${dirtyFiles}`); + } else { + // Only a pre-existing checkout can hold work worth protecting. A fresh --no-checkout clone + // reports every tracked file in WPT as deleted, which overflows spawnSync's output buffer. + const dirtyFiles = git(['status', '--porcelain', '--untracked-files=no'], { capture: true }); + if (dirtyFiles) { + throw new Error(`Refusing to change the modified WPT checkout at ${wptRoot}:\n${dirtyFiles}`); + } } const hasRevision = spawnSync( From 2713e7f943284dac86ed10c81ffd3d581ac4b543 Mon Sep 17 00:00:00 2001 From: Ilya Grigorik Date: Fri, 16 Oct 2026 22:49:43 -0700 Subject: [PATCH 7/8] pass wpt run options before the product so the test list parses on Python < 3.12.7 argparse before 3.12.7 matches a trailing nargs='*' positional as empty when options separate it from the preceding positional, so `wpt run chrome --yes ... test.html` reported every test path as an unrecognized argument. Stock python3 on Ubuntu 24.04 (the CI runner) is 3.12.3; local runs on newer interpreters never hit it. Options now come first and `chrome` is followed directly by the tests, which parses on every version. Reproduced and verified with a fresh clone and a 3.12.3 venv: the old order fails, the new order runs 19/19 files. --- tests/browser/webmcp-wpt.mjs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/tests/browser/webmcp-wpt.mjs b/tests/browser/webmcp-wpt.mjs index b5396e0..5f7e4e2 100644 --- a/tests/browser/webmcp-wpt.mjs +++ b/tests/browser/webmcp-wpt.mjs @@ -200,9 +200,11 @@ function main() { const binaryArgs = ['--disable-blink-features=WebMCP', ...chromeSandboxArgs()].map( (argument) => `--binary-arg=${argument}` ); + // Options precede the positionals so `product` and the test list stay contiguous: argparse before + // Python 3.12.7 consumes a trailing nargs='*' positional as empty when options separate it from + // the one before, leaving every test path "unrecognized" (stock python3 on Ubuntu 24.04 is 3.12.3). const args = [ 'run', - 'chrome', '--yes', `--channel=${inferChromeChannel(chrome)}`, `--binary=${chrome}`, @@ -215,6 +217,7 @@ function main() { `--inject-script=${injectedPolyfillPath}`, `--log-wptreport=${reportPath}`, ...binaryArgs, + 'chrome', ...selectedTests, ]; From 6bfddc1d8688700dfc9d107bc8a4d1de5aafb992 Mon Sep 17 00:00:00 2001 From: Ilya Grigorik Date: Fri, 16 Oct 2026 22:58:22 -0700 Subject: [PATCH 8/8] restrict wpt run to testharness and crashtest so no accessibility deps are built wpt run defaults to every test type, and the presence of aamtest makes it install requirements_platform_accessibility.txt: on Linux that is PyGObject, which builds pycairo from source and fails on CI without cairo headers. On macOS the same file resolves to pyobjc wheels, so local runs never noticed. The canonical WebMCP files are testharness tests plus one crashtest; naming those two types skips the file entirely instead of adding system packages. Verified with a fresh clone and a Python 3.12.3 venv: no accessibility packages installed, 19/19 files and 39/39 subtests pass. --- tests/browser/webmcp-wpt.mjs | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/tests/browser/webmcp-wpt.mjs b/tests/browser/webmcp-wpt.mjs index 5f7e4e2..d15f4f5 100644 --- a/tests/browser/webmcp-wpt.mjs +++ b/tests/browser/webmcp-wpt.mjs @@ -205,6 +205,13 @@ function main() { // the one before, leaving every test path "unrecognized" (stock python3 on Ubuntu 24.04 is 3.12.3). const args = [ 'run', + // The canonical files are testharness tests plus one crashtest. Naming the types keeps wpt from + // installing the aamtest (platform accessibility) requirements, which on Linux build PyGObject + // and pycairo from source against system headers CI does not have. nargs='*' option: it ends + // at the next --flag, so it must not be the last option before the positionals. + '--test-types', + 'testharness', + 'crashtest', '--yes', `--channel=${inferChromeChannel(chrome)}`, `--binary=${chrome}`,