Skip to content
Merged
9 changes: 9 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down
3 changes: 2 additions & 1 deletion examples/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -484,8 +484,9 @@ 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
- `addEventListener('toolactivated' | 'toolcancel', handler)` - Observe execution start and cancellation; `event.toolName` names the tool

## Testing Your Tool

Expand Down
8 changes: 2 additions & 6 deletions src/content-scripts/page-bridge.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,6 @@
}

function cloneJsonValue(value) {
if (typeof value === 'string') return value;
return JSON.parse(JSON.stringify(value));
}

Expand Down Expand Up @@ -241,11 +240,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) {
Expand Down
171 changes: 121 additions & 50 deletions src/content-scripts/webmcp-polyfill.js
Original file line number Diff line number Diff line change
Expand Up @@ -83,25 +83,97 @@
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);
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)) {
Expand Down Expand Up @@ -161,10 +233,13 @@
}
if (signal?.aborted) return Promise.reject(signal.reason);

// ToolAnnotations is a dictionary: once present, every omitted member reads back as false.
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 = {
Expand Down Expand Up @@ -218,15 +293,18 @@
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;
});

return Promise.resolve(tools);
}

executeTool(tool, inputArguments, rawOptions = {}) {
executeTool(tool, inputObject, rawOptions = {}) {
if (this === null || !(this instanceof LocalModelContext)) {
throw new TypeError('Illegal invocation');
}
Expand All @@ -250,11 +328,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 =
Expand All @@ -263,9 +355,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());
}
Expand All @@ -288,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 });
Expand All @@ -303,7 +396,7 @@
} catch {
callbackFailed = true;
}
dispatchToolEvent('toolactivated', name);
this.dispatchEvent(new ToolActivatedEvent('toolactivated', { toolName: name }));

if (callbackFailed) {
if (!settled) {
Expand Down Expand Up @@ -332,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'));
Expand All @@ -356,6 +436,7 @@
Object.defineProperty(LocalModelContext.prototype, Symbol.toStringTag, {
value: 'ModelContext'
});
defineEventHandlerAttributes(LocalModelContext.prototype, MODEL_CONTEXT_EVENT_TYPES);

ensureTrustedTypesPolicy();

Expand Down Expand Up @@ -384,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,
Expand All @@ -398,8 +481,6 @@
}

class ModelContext extends EventTarget {
#ontoolchange = null;

constructor(...constructionArgs) {
if (constructionArgs[0] !== modelContextConstructionKey) {
throw new TypeError('Illegal constructor');
Expand All @@ -424,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', {
Expand Down
16 changes: 1 addition & 15 deletions src/lib/webmcp/lifecycle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -397,22 +397,8 @@ export class TabManager {
return;
}

// Parse inputSchema if it's a JSON string (Chrome's native API returns it as string)
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(),
};
Expand Down
Loading
Loading