Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 24 additions & 1 deletion src/content-scripts/page-bridge.js
Original file line number Diff line number Diff line change
Expand Up @@ -241,13 +241,36 @@

const methods = getApiMethods();
if (!methods) throw new PublicBridgeError('Tool catalog is unavailable');

// Spec input is an object. Older Chromium wanted a string: retry only if the tool never ran.
const input = args ?? {};
let activated = false;
const onActivated = (event) => {
if (event.toolName === name) activated = true;
};
window.addEventListener('toolactivated', onActivated);
try {
return await Reflect.apply(methods.executeTool, api, [registeredTool, input, { signal }]);
} catch (error) {
if (activated || signal.aborted || !isLegacyStringInputRejection(error)) throw error;
} finally {
window.removeEventListener('toolactivated', onActivated);
}
return Reflect.apply(methods.executeTool, api, [
registeredTool,
JSON.stringify(args ?? {}),
JSON.stringify(input),
{ signal }
]);
}

function isLegacyStringInputRejection(error) {
try {
return error instanceof DOMException && error.name === 'UnknownError';
} catch {
return false;
}
}

async function onMessage(event) {
if (disposed || event.source !== window) return;
if (!event.data || event.data.source !== 'webmcp-bridge') return;
Expand Down
7 changes: 6 additions & 1 deletion src/content-scripts/webmcp-polyfill.js
Original file line number Diff line number Diff line change
Expand Up @@ -263,9 +263,14 @@
: null;
if (!entry) return Promise.reject(unknownError());

// Spec input is an object; a JSON string is still accepted from older callers.
let input;
try {
input = JSON.parse(String(inputArguments));
input = JSON.parse(
typeof inputArguments === 'string'
? inputArguments
: JSON.stringify(inputArguments === undefined ? {} : inputArguments)
);
} catch {
return Promise.reject(unknownError());
}
Expand Down
52 changes: 51 additions & 1 deletion tests/webmcp-page-bridge.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -201,7 +201,7 @@ 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 }));
expect(native.api.executeTool.mock.calls[0][1]).toEqual({ answer: 42 });
expect(native.api.executeTool.mock.calls[0][2].signal).toBeInstanceOf(
harness.window.AbortSignal
);
Expand Down Expand Up @@ -391,6 +391,56 @@ describe('WebMCP page bridge catalog and execution', () => {
expect(native.api.executeTool).not.toHaveBeenCalled();
});

it('retries with a JSON string only when legacy ModelContext rejected the object before running', async () => {
const harness = createHarness({ loadPolyfill: false });
const native = createNativeHarness(harness.window, [nativeTool(harness.window, 'legacy_tool')]);
native.api.executeTool.mockImplementationOnce(async () => {
throw new harness.window.DOMException('WebMCP tool execution failed', 'UnknownError');
});
installNative(harness, native);
harness.loadBridge();
await flush(harness.window);

harness.send({
id: 'legacy-call',
method: 'tools/call',
params: { name: 'legacy_tool', arguments: { answer: 42 } },
});
await flush(harness.window);

expect(native.api.executeTool).toHaveBeenCalledTimes(2);
expect(native.api.executeTool.mock.calls[0][1]).toEqual({ answer: 42 });
expect(native.api.executeTool.mock.calls[1][1]).toBe(JSON.stringify({ answer: 42 }));
expect(response(harness, 'legacy-call').result).toBe('native-result');
});

it('never retries a tool whose callback already ran', async () => {
const harness = createHarness({ loadPolyfill: false });
const native = createNativeHarness(harness.window, [nativeTool(harness.window, 'ran_tool')]);
native.api.executeTool.mockImplementationOnce(async () => {
const event = new harness.window.Event('toolactivated');
Object.defineProperty(event, 'toolName', { value: 'ran_tool' });
harness.window.dispatchEvent(event);
throw new harness.window.DOMException('WebMCP tool execution failed', 'UnknownError');
});
installNative(harness, native);
harness.loadBridge();
await flush(harness.window);

harness.send({
id: 'ran-call',
method: 'tools/call',
params: { name: 'ran_tool', arguments: {} },
});
await flush(harness.window);

expect(native.api.executeTool).toHaveBeenCalledTimes(1);
expect(response(harness, 'ran-call').error).toEqual({
code: -32000,
message: 'Tool execution failed',
});
});

it('does not relay arbitrary tool errors or stacks across the page boundary', async () => {
const harness = createHarness({ loadPolyfill: false });
const native = createNativeHarness(harness.window, [nativeTool(harness.window, 'unsafe_tool')]);
Expand Down
9 changes: 9 additions & 0 deletions tests/webmcp-polyfill.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -424,6 +424,15 @@ describe('WebMCP local backend contract', () => {
expect(execute.mock.calls[0][1].signal.aborted).toBe(false);
expect(receiver).toBeUndefined();
expect(result).toBe(JSON.stringify({ echoed: { value: 7 } }));

const input = { value: 8 };
const objectResult = await modelContext.executeTool(descriptor, input);
expect(execute.mock.calls[1][0]).toEqual({ value: 8 });
expect(execute.mock.calls[1][0]).not.toBe(input);
expect(objectResult).toBe(JSON.stringify({ echoed: { value: 8 } }));

await modelContext.executeTool(descriptor);
expect(execute.mock.calls[2][0]).toEqual({});
});

it('maps callback rejection to UnknownError without exposing its details', async () => {
Expand Down