Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.
TypeScript automationchromechromiume2e-testingelectronend-to-end-testingfirefoxjavascriptplaywrighttesttest-automationtestingtesting-toolswebwebkit
chore(webmcp): remove enable/disable and toolsChanged event (#43080)
Pavel Feldman8885bdf2f3d1
diff --git a/docs/src/api/class-webmcp.md b/docs/src/api/class-webmcp.mdindex d927ce70be..4eb55da1b5 100644--- a/docs/src/api/class-webmcp.md+++ b/docs/src/api/class-webmcp.md@@ -2,12 +2,12 @@* since: v1.64* langs: js-[WebMCP] exposes the tools that a frame registers through the experimental [WebMCP](https://webmachinelearning.github.io/webmcp/) browser API, `navigator.modelContext`. It lists the tools, reports when the set of tools changes, and calls the tools.+[WebMCP] exposes the tools that a frame registers through the experimental [WebMCP](https://webmachinelearning.github.io/webmcp/) browser API, `navigator.modelContext`. It lists the tools and calls them.-Instances are accessed through [`property: Frame.webmcp`]. [`property: Page.webmcp`] is the instance of the main frame. Call [`method: WebMCP.enable`] before using the other methods.+Instances are accessed through [`property: Frame.webmcp`]. [`property: Page.webmcp`] is the instance of the main frame.:::note-WebMCP is an experimental browser feature. Chromium enables it with the `--enable-features=WebMCP` launch argument, Firefox with the `dom.modelcontext.enabled` preference. WebKit does not implement it.+WebMCP is an experimental browser feature. Chromium enables it with the `--enable-features=WebMCP` launch argument, Firefox with the `dom.modelcontext.enabled` and `dom.modelcontext.testing.enabled` preferences. WebKit does not implement it.:::Tool names, descriptions, input schemas and results are provided by the page, so treat them as untrusted input.@@ -15,7 +15,6 @@ Tool names, descriptions, input schemas and results are provided by the page, so```jsconst browser = await chromium.launch({ args: ['--enable-features=WebMCP'] });const page = await browser.newPage();-await page.webmcp.enable();await page.goto('https://example.com');for (const tool of await page.webmcp.tools())@@ -24,26 +23,6 @@ for (const tool of await page.webmcp.tools())const result = await page.webmcp.callTool('add', { a: 2, b: 40 });```-## event: WebMCP.toolsChanged-* since: v1.64-- argument: <[Array]<[Object]>>- * alias: WebMCPTool- - `name` <[string]> Tool name, unique within the frame.- - `description` <[string]> Tool description.- - `inputSchema` ?<[Serializable]> JSON Schema of the tool input, when the page provides one.- - `annotations` ?<[Object]> Hints the page provides about the tool.- - `readOnly` ?<[boolean]> The tool does not modify any state.- - `untrustedContent` ?<[boolean]> The tool output may contain third-party content.- - `consequential` ?<[boolean]> The tool takes a consequential action, such as placing an order.--Emitted while WebMCP is enabled, whenever the set of tools registered by the frame changes, for example when the page registers or unregisters a tool, or when the frame navigates away. The argument is the new list of tools, the same one [`method: WebMCP.tools`] returns.--```js-page.webmcp.on('toolschanged', tools => {- console.log('tools are now', tools.map(tool => tool.name));-});-```-## async method: WebMCP.callTool* since: v1.64- returns: <[Serializable]>@@ -70,27 +49,6 @@ Input for the tool, matching its `inputSchema`. Defaults to an empty object.### option: WebMCP.callTool.timeout = %%-input-timeout-js-%%* since: v1.64-## async method: WebMCP.disable-* since: v1.64--Stops tracking the tools that the frame registers and stops emitting [`event: WebMCP.toolsChanged`]. Disposing the [Disposable] returned by [`method: WebMCP.enable`] does the same.--## async method: WebMCP.enable-* since: v1.64-- returns: <[Disposable]>--Starts tracking the tools that the frame registers, so that [`method: WebMCP.tools`], [`method: WebMCP.callTool`] and [`event: WebMCP.toolsChanged`] work. Throws if the browser was launched without WebMCP support, see the note above for the launch options that enable it. Returns a [Disposable] that disables the tracking again.--Tracking is per frame. [`property: Page.webmcp`] covers the main frame only, child frames are tracked through their own [`property: Frame.webmcp`].--Chromium reports tool registrations natively. Firefox does not, so Playwright instruments `navigator.modelContext` in the page to observe registrations. Tools registered before the call are picked up as well.--```js-await page.webmcp.enable();-await page.goto('https://example.com');-console.log(await page.webmcp.tools());-```-## async method: WebMCP.tools* since: v1.64- returns: <[Array]<[Object]>>@@ -103,41 +61,9 @@ console.log(await page.webmcp.tools());- `untrustedContent` ?<[boolean]> The tool output may contain third-party content.- `consequential` ?<[boolean]> The tool takes a consequential action, such as placing an order.-Returns the tools currently registered by the frame.--### option: WebMCP.tools.timeout = %%-input-timeout-js-%%-* since: v1.64--## async method: WebMCP.waitForEvent-* since: v1.64-* langs: js-- returns: <[any]>--Waits for the event to fire and passes its value into the predicate function. Returns when the predicate returns a truthy value. Throws if the page is closed before the event is fired. Returns the event data value.+Returns the tools currently registered by the frame. Throws if the browser was launched without WebMCP support, see the note above for the launch options that enable it.-```js-const toolsPromise = page.webmcp.waitForEvent('toolschanged');-await page.getByRole('button', { name: 'Sign in' }).click();-const tools = await toolsPromise;-```+[`property: Page.webmcp`] covers the main frame only, child frames list their tools through their own [`property: Frame.webmcp`].-### param: WebMCP.waitForEvent.event = %%-wait-for-event-event-%%-* since: v1.64--### param: WebMCP.waitForEvent.optionsOrPredicate-* since: v1.64-* langs: js-- `optionsOrPredicate` ?<[function]|[Object]>- - `predicate` <[function]> Receives the event data and resolves to truthy value when the waiting should resolve.- - `timeout` ?<[float]> Maximum time to wait for in milliseconds. Defaults to `0` - no timeout. The default value can be changed via `actionTimeout` option in the config, or by using the [`method: BrowserContext.setDefaultTimeout`] or [`method: Page.setDefaultTimeout`] methods.--Either a predicate that receives an event or an options object. Optional.--### option: WebMCP.waitForEvent.predicate = %%-wait-for-event-predicate-%%-* since: v1.64--### option: WebMCP.waitForEvent.timeout = %%-wait-for-event-timeout-%%-* since: v1.64--### option: WebMCP.waitForEvent.signal = %%-wait-for-event-signal-%%+### option: WebMCP.tools.timeout = %%-input-timeout-js-%%* since: v1.64diff --git a/packages/injected/src/webMCP.ts b/packages/injected/src/webMCP.tsindex c763949119..5608a10d94 100644--- a/packages/injected/src/webMCP.ts+++ b/packages/injected/src/webMCP.ts@@ -25,18 +25,11 @@ export type WebMCPToolDescription = {};};-export type WebMCPScriptOptions = {- property: string;- bindingName: string;- bindingsControllerProperty: string;-};-type RegisteredTool = {name: string;description?: string;inputSchema?: unknown;annotations?: Record<string, boolean | undefined>;- execute?: (input: unknown) => unknown;window?: Window;};@@ -46,131 +39,80 @@ type ModelContext = {invokeTool?: (name: string, input: unknown) => Promise<unknown>;};-type BindingsController = {- callBinding(name: string, ...args: unknown[]): Promise<unknown>;-};-type GlobalThis = typeof globalThis;export class WebMCPScript {private _global: GlobalThis;- private _options: WebMCPScriptOptions;private _modelContext: ModelContext | undefined;- private _registry = new Map<string, RegisteredTool>();- static install(global: GlobalThis, options: WebMCPScriptOptions): Promise<WebMCPToolDescription[]> {- const existing = (global as any)[options.property] as WebMCPScript | undefined;- if (existing)- return Promise.resolve(existing._describe());- const script = new WebMCPScript(global, options);- Object.defineProperty(global, options.property, { value: script, configurable: true });- return script._collectRegisteredTools();- }-- constructor(global: GlobalThis, options: WebMCPScriptOptions) {+ constructor(global: GlobalThis) {this._global = global;- this._options = options;// Chromium exposes the entry point on `document`, Firefox on `navigator`.this._modelContext = (global.document as any)?.modelContext ?? (global.navigator as any)?.modelContext;- if (!this._modelContext)- return;- this._wrap('registerTool', (tool: RegisteredTool) => this._registry.set(tool.name, tool));- this._wrap('unregisterTool', (name: string) => this._registry.delete(name));- this._wrap('provideContext', (params?: { tools?: RegisteredTool[] }) => {- this._registry.clear();- for (const tool of params?.tools ?? [])- this._registry.set(tool.name, tool);- });- this._wrap('clearContext', () => this._registry.clear());}- async callTool(name: string, inputJson: string): Promise<string> {+ async tools(): Promise<WebMCPToolDescription[]> {+ return (await this._ownTools()).map(tool => this._describe(tool));+ }++ async callTool(name: string, input: object): Promise<unknown> {const modelContext = this._modelContext;if (!modelContext)throw new Error('WebMCP is not available on this page');- const input = JSON.parse(inputJson);if (modelContext.invokeTool)- return this._stringify(await modelContext.invokeTool(name, input));- if (modelContext.executeTool && modelContext.getTools) {- const tool = (await modelContext.getTools()).find(tool => this._isOwnTool(tool) && tool.name === name);- if (!tool)- throw new Error(`WebMCP tool "${name}" is not registered in this frame`);- const result = await this._executeTool(modelContext, tool, input, inputJson);- return typeof result === 'string' ? result : this._stringify(result);- }- const tool = this._registry.get(name);- if (!tool?.execute)+ return await modelContext.invokeTool(name, input);+ const tool = (await this._ownTools()).find(tool => tool.name === name);+ if (!tool || !modelContext.executeTool)throw new Error(`WebMCP tool "${name}" is not registered in this frame`);- return this._stringify(await tool.execute(input));+ return this._parseResult(await this._executeTool(modelContext, tool, input));}- private async _executeTool(modelContext: ModelContext, tool: RegisteredTool, input: object, inputJson: string): Promise<unknown> {+ private async _executeTool(modelContext: ModelContext, tool: RegisteredTool, input: object): Promise<unknown> {try {return await modelContext.executeTool!(tool, input);} catch (e) {// Chromium before 155 takes the input as a JSON string.if (!String((e as Error)?.message).includes('Failed to parse input arguments'))throw e;- return await modelContext.executeTool!(tool, inputJson);+ return await modelContext.executeTool!(tool, JSON.stringify(input));}}- private async _collectRegisteredTools(): Promise<WebMCPToolDescription[]> {- const tools = await this._modelContext?.getTools?.() ?? [];- for (const tool of tools) {- if (this._isOwnTool(tool))- this._registry.set(tool.name, tool);+ private _parseResult(result: unknown): unknown {+ // Chromium hands the result back as a string.+ if (typeof result !== 'string')+ return result;+ if (result === 'undefined')+ return undefined;+ try {+ return JSON.parse(result);+ } catch {+ return result;}- return this._describe();}- private _isOwnTool(tool: RegisteredTool): boolean {+ private async _ownTools(): Promise<RegisteredTool[]> {+ const tools = await this._modelContext?.getTools?.() ?? [];// Chromium's getTools() aggregates same-origin descendant frames, Firefox's does not.- return !('window' in tool) || tool.window === this._global.window;+ return tools.filter(tool => !('window' in tool) || tool.window === this._global.window);}- private _wrap(method: string, update: (...args: any[]) => void) {- const prototype = Object.getPrototypeOf(this._modelContext);- const original = prototype[method];- if (typeof original !== 'function')- return;- const script = this;- prototype[method] = function(this: unknown, ...args: unknown[]) {- const result = original.apply(this, args);- update(...args);- script._report();- return result;+ private _describe(tool: RegisteredTool): WebMCPToolDescription {+ const annotations = tool.annotations;+ return {+ name: tool.name,+ description: tool.description ?? '',+ inputSchema: this._parseInputSchema(tool.inputSchema),+ annotations: annotations ? {+ readOnly: annotations.readOnlyHint,+ untrustedContent: annotations.untrustedContentHint,+ consequential: annotations.consequentialHint,+ } : undefined,};}- private _report() {- const controller = (this._global as any)[this._options.bindingsControllerProperty] as BindingsController | undefined;- // Calling a disposed binding throws, the page must not notice.- try {- controller?.callBinding(this._options.bindingName, this._describe()).catch(() => {});- } catch {- }- }-- private _describe(): WebMCPToolDescription[] {- return [...this._registry.values()].map(tool => {- const annotations = tool.annotations;- return {- name: tool.name,- description: tool.description ?? '',- inputSchema: this._parseInputSchema(tool.inputSchema),- // The JS surface uses the `*Hint` names, the CDP WebMCP domain uses the short ones.- annotations: annotations ? {- readOnly: annotations.readOnlyHint ?? annotations.readOnly,- untrustedContent: annotations.untrustedContentHint ?? annotations.untrustedContent,- consequential: annotations.consequentialHint ?? annotations.consequential,- } : undefined,- };- });- }-private _parseInputSchema(inputSchema: unknown): unknown {- // Chromium hands the schema back as a JSON string, Firefox as an object.+ // Chromium before 155 hands the schema back as a JSON string.if (typeof inputSchema !== 'string')return inputSchema;try {@@ -179,8 +121,4 @@ export class WebMCPScript {return undefined;}}-- private _stringify(result: unknown): string {- return result === undefined ? 'null' : JSON.stringify(result);- }}diff --git a/packages/isomorphic/protocolMetainfo.ts b/packages/isomorphic/protocolMetainfo.tsindex 9bfc1b85aa..6869dcb458 100644--- a/packages/isomorphic/protocolMetainfo.ts+++ b/packages/isomorphic/protocolMetainfo.ts@@ -175,8 +175,6 @@ export const methodMetainfo = new Map<string, MethodMetainfo>([['Frame.waitForFunction', { title: 'Wait for function', subtitle: '{selector}', snapshot: true, pause: true, }],['Frame.waitForSelector', { title: 'Wait for selector', subtitle: '{selector}', renderParams: ['state'], snapshot: true, }],['Frame.expect', { title: 'Expect "{expression}"', subtitle: '{selector}', snapshot: true, pause: true, }],- ['Frame.webmcpEnable', { title: 'Enable WebMCP', group: 'configuration', }],- ['Frame.webmcpDisable', { title: 'Disable WebMCP', group: 'configuration', }],['Frame.webmcpTools', { title: 'List WebMCP tools', group: 'getter', }],['Frame.webmcpCallTool', { title: 'Call WebMCP tool', }],['JSHandle.dispose', { internal: true, }],diff --git a/packages/playwright-client/types/types.d.ts b/packages/playwright-client/types/types.d.tsindex 110d4ed5af..ed3dc49e12 100644--- a/packages/playwright-client/types/types.d.ts+++ b/packages/playwright-client/types/types.d.ts@@ -23835,21 +23835,20 @@ export interface WebError {/*** [WebMCP](https://playwright.dev/docs/api/class-webmcp) exposes the tools that a frame registers through the* experimental [WebMCP](https://playwright.dev/docs/api/class-webmcp) browser API, `navigator.modelContext`. It lists- * the tools, reports when the set of tools changes, and calls the tools.+ * the tools and calls them.** Instances are accessed through [frame.webmcp](https://playwright.dev/docs/api/class-frame#frame-webmcp).- * [page.webmcp](https://playwright.dev/docs/api/class-page#page-webmcp) is the instance of the main frame. Call- * [webMCP.enable()](https://playwright.dev/docs/api/class-webmcp#web-mcp-enable) before using the other methods.+ * [page.webmcp](https://playwright.dev/docs/api/class-page#page-webmcp) is the instance of the main frame.** **NOTE** WebMCP is an experimental browser feature. Chromium enables it with the `--enable-features=WebMCP` launch- * argument, Firefox with the `dom.modelcontext.enabled` preference. WebKit does not implement it.+ * argument, Firefox with the `dom.modelcontext.enabled` and `dom.modelcontext.testing.enabled` preferences. WebKit+ * does not implement it.** Tool names, descriptions, input schemas and results are provided by the page, so treat them as untrusted input.** ```js* const browser = await chromium.launch({ args: ['--enable-features=WebMCP'] });* const page = await browser.newPage();- * await page.webmcp.enable();* await page.goto('https://example.com');** for (const tool of await page.webmcp.tools())@@ -23860,273 +23859,6 @@ export interface WebError {**/export interface WebMCP {- /**- * Emitted while WebMCP is enabled, whenever the set of tools registered by the frame changes, for example when the- * page registers or unregisters a tool, or when the frame navigates away. The argument is the new list of tools, the- * same one [webMCP.tools([options])](https://playwright.dev/docs/api/class-webmcp#web-mcp-tools) returns.- *- * ```js- * page.webmcp.on('toolschanged', tools => {- * console.log('tools are now', tools.map(tool => tool.name));- * });- * ```- *- */- on(event: 'toolschanged', listener: (data: Array<{- /**- * Tool name, unique within the frame.- */- name: string;-- /**- * Tool description.- */- description: string;-- /**- * JSON Schema of the tool input, when the page provides one.- */- inputSchema?: Serializable;-- /**- * Hints the page provides about the tool.- */- annotations?: {- /**- * The tool does not modify any state.- */- readOnly?: boolean;-- /**- * The tool output may contain third-party content.- */- untrustedContent?: boolean;-- /**- * The tool takes a consequential action, such as placing an order.- */- consequential?: boolean;- };- }>) => any): this;-- /**- * Adds an event listener that will be automatically removed after it is triggered once. See `addListener` for more information about this event.- */- once(event: 'toolschanged', listener: (data: Array<{- /**- * Tool name, unique within the frame.- */- name: string;-- /**- * Tool description.- */- description: string;-- /**- * JSON Schema of the tool input, when the page provides one.- */- inputSchema?: Serializable;-- /**- * Hints the page provides about the tool.- */- annotations?: {- /**- * The tool does not modify any state.- */- readOnly?: boolean;-- /**- * The tool output may contain third-party content.- */- untrustedContent?: boolean;-- /**- * The tool takes a consequential action, such as placing an order.- */- consequential?: boolean;- };- }>) => any): this;-- /**- * Emitted while WebMCP is enabled, whenever the set of tools registered by the frame changes, for example when the- * page registers or unregisters a tool, or when the frame navigates away. The argument is the new list of tools, the- * same one [webMCP.tools([options])](https://playwright.dev/docs/api/class-webmcp#web-mcp-tools) returns.- *- * ```js- * page.webmcp.on('toolschanged', tools => {- * console.log('tools are now', tools.map(tool => tool.name));- * });- * ```- *- */- addListener(event: 'toolschanged', listener: (data: Array<{- /**- * Tool name, unique within the frame.- */- name: string;-- /**- * Tool description.- */- description: string;-- /**- * JSON Schema of the tool input, when the page provides one.- */- inputSchema?: Serializable;-- /**- * Hints the page provides about the tool.- */- annotations?: {- /**- * The tool does not modify any state.- */- readOnly?: boolean;-- /**- * The tool output may contain third-party content.- */- untrustedContent?: boolean;-- /**- * The tool takes a consequential action, such as placing an order.- */- consequential?: boolean;- };- }>) => any): this;-- /**- * Removes an event listener added by `on` or `addListener`.- */- removeListener(event: 'toolschanged', listener: (data: Array<{- /**- * Tool name, unique within the frame.- */- name: string;-- /**- * Tool description.- */- description: string;-- /**- * JSON Schema of the tool input, when the page provides one.- */- inputSchema?: Serializable;-- /**- * Hints the page provides about the tool.- */- annotations?: {- /**- * The tool does not modify any state.- */- readOnly?: boolean;-- /**- * The tool output may contain third-party content.- */- untrustedContent?: boolean;-- /**- * The tool takes a consequential action, such as placing an order.- */- consequential?: boolean;- };- }>) => any): this;-- /**- * Removes an event listener added by `on` or `addListener`.- */- off(event: 'toolschanged', listener: (data: Array<{- /**- * Tool name, unique within the frame.- */- name: string;-- /**- * Tool description.- */- description: string;-- /**- * JSON Schema of the tool input, when the page provides one.- */- inputSchema?: Serializable;-- /**- * Hints the page provides about the tool.- */- annotations?: {- /**- * The tool does not modify any state.- */- readOnly?: boolean;-- /**- * The tool output may contain third-party content.- */- untrustedContent?: boolean;-- /**- * The tool takes a consequential action, such as placing an order.- */- consequential?: boolean;- };- }>) => any): this;-- /**- * Emitted while WebMCP is enabled, whenever the set of tools registered by the frame changes, for example when the- * page registers or unregisters a tool, or when the frame navigates away. The argument is the new list of tools, the- * same one [webMCP.tools([options])](https://playwright.dev/docs/api/class-webmcp#web-mcp-tools) returns.- *- * ```js- * page.webmcp.on('toolschanged', tools => {- * console.log('tools are now', tools.map(tool => tool.name));- * });- * ```- *- */- prependListener(event: 'toolschanged', listener: (data: Array<{- /**- * Tool name, unique within the frame.- */- name: string;-- /**- * Tool description.- */- description: string;-- /**- * JSON Schema of the tool input, when the page provides one.- */- inputSchema?: Serializable;-- /**- * Hints the page provides about the tool.- */- annotations?: {- /**- * The tool does not modify any state.- */- readOnly?: boolean;-- /**- * The tool output may contain third-party content.- */- untrustedContent?: boolean;-- /**- * The tool takes a consequential action, such as placing an order.- */- consequential?: boolean;- };- }>) => any): this;-/*** Calls a tool registered by the frame and returns its result. The result is whatever the tool's `execute` function* resolved to, typically an object with a `content` array. A result with `isError: true` is returned as is. The@@ -24153,39 +23885,11 @@ export interface WebMCP {}): Promise<Serializable>;/**- * Stops tracking the tools that the frame registers and stops emitting- * [webMCP.on('toolschanged')](https://playwright.dev/docs/api/class-webmcp#web-mcp-event-tools-changed). Disposing- * the [Disposable](https://playwright.dev/docs/api/class-disposable) returned by- * [webMCP.enable()](https://playwright.dev/docs/api/class-webmcp#web-mcp-enable) does the same.- */- disable(): Promise<void>;-- /**- * Starts tracking the tools that the frame registers, so that- * [webMCP.tools([options])](https://playwright.dev/docs/api/class-webmcp#web-mcp-tools),- * [webMCP.callTool(name[, input, options])](https://playwright.dev/docs/api/class-webmcp#web-mcp-call-tool) and- * [webMCP.on('toolschanged')](https://playwright.dev/docs/api/class-webmcp#web-mcp-event-tools-changed) work. Throws- * if the browser was launched without WebMCP support, see the note above for the launch options that enable it.- * Returns a [Disposable](https://playwright.dev/docs/api/class-disposable) that disables the tracking again.+ * Returns the tools currently registered by the frame. Throws if the browser was launched without WebMCP support, see+ * the note above for the launch options that enable it.*- * Tracking is per frame. [page.webmcp](https://playwright.dev/docs/api/class-page#page-webmcp) covers the main frame- * only, child frames are tracked through their own- * [frame.webmcp](https://playwright.dev/docs/api/class-frame#frame-webmcp).- *- * Chromium reports tool registrations natively. Firefox does not, so Playwright instruments `navigator.modelContext`- * in the page to observe registrations. Tools registered before the call are picked up as well.- *- * ```js- * await page.webmcp.enable();- * await page.goto('https://example.com');- * console.log(await page.webmcp.tools());- * ```- *- */- enable(): Promise<Disposable>;-- /**- * Returns the tools currently registered by the frame.+ * [page.webmcp](https://playwright.dev/docs/api/class-page#page-webmcp) covers the main frame only, child frames list+ * their tools through their own [frame.webmcp](https://playwright.dev/docs/api/class-frame#frame-webmcp).* @param options*/tools(options?: {@@ -24232,126 +23936,6 @@ export interface WebMCP {consequential?: boolean;};}>>;-- /**- * Emitted while WebMCP is enabled, whenever the set of tools registered by the frame changes, for example when the- * page registers or unregisters a tool, or when the frame navigates away. The argument is the new list of tools, the- * same one [webMCP.tools([options])](https://playwright.dev/docs/api/class-webmcp#web-mcp-tools) returns.- *- * ```js- * page.webmcp.on('toolschanged', tools => {- * console.log('tools are now', tools.map(tool => tool.name));- * });- * ```- *- */- waitForEvent(event: 'toolschanged', optionsOrPredicate?: { predicate?: (data: Array<{- /**- * Tool name, unique within the frame.- */- name: string;-- /**- * Tool description.- */- description: string;-- /**- * JSON Schema of the tool input, when the page provides one.- */- inputSchema?: Serializable;-- /**- * Hints the page provides about the tool.- */- annotations?: {- /**- * The tool does not modify any state.- */- readOnly?: boolean;-- /**- * The tool output may contain third-party content.- */- untrustedContent?: boolean;-- /**- * The tool takes a consequential action, such as placing an order.- */- consequential?: boolean;- };- }>) => boolean | Promise<boolean>, timeout?: number, signal?: AbortSignal } | ((data: Array<{- /**- * Tool name, unique within the frame.- */- name: string;-- /**- * Tool description.- */- description: string;-- /**- * JSON Schema of the tool input, when the page provides one.- */- inputSchema?: Serializable;-- /**- * Hints the page provides about the tool.- */- annotations?: {- /**- * The tool does not modify any state.- */- readOnly?: boolean;-- /**- * The tool output may contain third-party content.- */- untrustedContent?: boolean;-- /**- * The tool takes a consequential action, such as placing an order.- */- consequential?: boolean;- };- }>) => boolean | Promise<boolean>)): Promise<Array<{- /**- * Tool name, unique within the frame.- */- name: string;-- /**- * Tool description.- */- description: string;-- /**- * JSON Schema of the tool input, when the page provides one.- */- inputSchema?: Serializable;-- /**- * Hints the page provides about the tool.- */- annotations?: {- /**- * The tool does not modify any state.- */- readOnly?: boolean;-- /**- * The tool output may contain third-party content.- */- untrustedContent?: boolean;-- /**- * The tool takes a consequential action, such as placing an order.- */- consequential?: boolean;- };- }>>;-}/**diff --git a/packages/playwright-core/src/client/channels.d.ts b/packages/playwright-core/src/client/channels.d.tsindex b16202f1dd..ff21926566 100644--- a/packages/playwright-core/src/client/channels.d.ts+++ b/packages/playwright-core/src/client/channels.d.ts@@ -2291,7 +2291,6 @@ export type FrameInitializer = {export interface FrameEventTarget {on(event: 'loadstate', callback: (params: FrameLoadstateEvent) => void): this;on(event: 'navigated', callback: (params: FrameNavigatedEvent) => void): this;- on(event: 'webmcpToolsChanged', callback: (params: FrameWebmcpToolsChangedEvent) => void): this;}export interface FrameChannel extends FrameEventTarget, Channel {_type_Frame: boolean;@@ -2345,8 +2344,6 @@ export interface FrameChannel extends FrameEventTarget, Channel {waitForFunction(params: FrameWaitForFunctionParams, options: TimeoutOptions): Promise<FrameWaitForFunctionResult>;waitForSelector(params: FrameWaitForSelectorParams, options: TimeoutOptions): Promise<FrameWaitForSelectorResult>;expect(params: FrameExpectParams, options: TimeoutOptions): Promise<FrameExpectResult>;- webmcpEnable(params: FrameWebmcpEnableParams, options: TimeoutOptions): Promise<FrameWebmcpEnableResult>;- webmcpDisable(params: FrameWebmcpDisableParams, options: TimeoutOptions): Promise<FrameWebmcpDisableResult>;webmcpTools(params: FrameWebmcpToolsParams, options: TimeoutOptions): Promise<FrameWebmcpToolsResult>;webmcpCallTool(params: FrameWebmcpCallToolParams, options: TimeoutOptions): Promise<FrameWebmcpCallToolResult>;}@@ -2362,18 +2359,6 @@ export type FrameNavigatedEvent = {},error?: string,};-export type FrameWebmcpToolsChangedEvent = {- tools: {- name: string,- description: string,- inputSchema?: any,- annotations?: {- readOnly?: boolean,- untrustedContent?: boolean,- consequential?: boolean,- },- }[],-};export type FrameEvalOnSelectorParams = {selector: string,strict?: boolean,@@ -3031,12 +3016,6 @@ export type FrameExpectErrorDetails = {timedOut?: boolean,customErrorMessage?: string,};-export type FrameWebmcpEnableParams = {};-export type FrameWebmcpEnableOptions = {};-export type FrameWebmcpEnableResult = void;-export type FrameWebmcpDisableParams = {};-export type FrameWebmcpDisableOptions = {};-export type FrameWebmcpDisableResult = void;export type FrameWebmcpToolsParams = {};export type FrameWebmcpToolsOptions = {};export type FrameWebmcpToolsResult = {@@ -3053,19 +3032,18 @@ export type FrameWebmcpToolsResult = {};export type FrameWebmcpCallToolParams = {name: string,- input?: any,+ input: SerializedArgument,};export type FrameWebmcpCallToolOptions = {- input?: any,+};export type FrameWebmcpCallToolResult = {- result?: any,+ result: SerializedValue,};export interface FrameEvents {'loadstate': FrameLoadstateEvent;'navigated': FrameNavigatedEvent;- 'webmcpToolsChanged': FrameWebmcpToolsChangedEvent;}// ----------- JSHandle -----------diff --git a/packages/playwright-core/src/client/events.ts b/packages/playwright-core/src/client/events.tsindex 2956cccacd..0233d000fe 100644--- a/packages/playwright-core/src/client/events.ts+++ b/packages/playwright-core/src/client/events.ts@@ -92,10 +92,6 @@ export const Events = {Worker: 'worker',},- WebMCP: {- ToolsChanged: 'toolschanged',- },-WebSocket: {Close: 'close',Error: 'socketerror',diff --git a/packages/playwright-core/src/client/webmcp.ts b/packages/playwright-core/src/client/webmcp.tsindex f4f89c6965..d5d9cc5441 100644--- a/packages/playwright-core/src/client/webmcp.ts+++ b/packages/playwright-core/src/client/webmcp.ts@@ -14,36 +14,19 @@* limitations under the License.*/-import { DisposableStub } from './disposable';-import { EventEmitter } from './eventEmitter';-import { Events } from './events';-import { kNoTimeout } from './timeoutSettings';-import { Waiter } from './waiter';+import { parseResult, serializeArgument } from './jsHandle';import type { Frame } from './frame';import type * as api from '../../types/types';import type * as channels from './channels';-import type { WaitForEventOptions } from './types';export type WebMCPTool = channels.FrameWebmcpToolsResult['tools'][number];-export class WebMCP extends EventEmitter implements api.WebMCP {+export class WebMCP implements api.WebMCP {private _frame: Frame;constructor(frame: Frame) {- super();- this.setMaxListeners(0);this._frame = frame;- this._frame._channel.on('webmcpToolsChanged', ({ tools }) => this.emit(Events.WebMCP.ToolsChanged, tools));- }-- async enable(): Promise<DisposableStub> {- await this._frame._channel.webmcpEnable({}, kNoTimeout);- return new DisposableStub(() => this.disable());- }-- async disable(): Promise<void> {- await this._frame._channel.webmcpDisable({}, kNoTimeout);}async tools(options: { timeout?: number } = {}): Promise<WebMCPTool[]> {@@ -52,22 +35,7 @@ export class WebMCP extends EventEmitter implements api.WebMCP {}async callTool(name: string, input?: any, options: { timeout?: number } = {}): Promise<any> {- const { result } = await this._frame._channel.webmcpCallTool({ name, input }, this._frame._timeout(options));- return result;- }-- async waitForEvent(event: string, optionsOrPredicate: WaitForEventOptions = {}): Promise<any> {- return await this._frame._wrapApiCall(async () => {- const timeoutOptions = this._frame._timeout(typeof optionsOrPredicate === 'function' ? {} : optionsOrPredicate);- const predicate = typeof optionsOrPredicate === 'function' ? optionsOrPredicate : optionsOrPredicate.predicate;- const waiter = Waiter.createForEvent(this._frame, event);- waiter.rejectOnTimeout(timeoutOptions, `Timeout ${timeoutOptions.timeout}ms exceeded while waiting for event "${event}"`);- const page = this._frame._page;- if (page)- waiter.rejectOnEvent(page, Events.Page.Close, () => page._closeErrorWithReason());- const result = await waiter.waitForEvent(this, event, predicate as any);- waiter.dispose();- return result;- });+ const { result } = await this._frame._channel.webmcpCallTool({ name, input: serializeArgument(input) }, this._frame._timeout(options));+ return parseResult(result);}}diff --git a/packages/playwright-core/src/server/channels.d.ts b/packages/playwright-core/src/server/channels.d.tsindex dd7b4f8902..7fd91ceebb 100644--- a/packages/playwright-core/src/server/channels.d.ts+++ b/packages/playwright-core/src/server/channels.d.ts@@ -2292,7 +2292,6 @@ export type FrameInitializer = {export interface FrameEventTarget {_dispatchEvent(event: 'loadstate', params?: FrameLoadstateEvent): void;_dispatchEvent(event: 'navigated', params?: FrameNavigatedEvent): void;- _dispatchEvent(event: 'webmcpToolsChanged', params?: FrameWebmcpToolsChangedEvent): void;}export interface FrameChannel extends FrameEventTarget, Channel {_type_Frame: boolean;@@ -2346,8 +2345,6 @@ export interface FrameChannel extends FrameEventTarget, Channel {waitForFunction(params: FrameWaitForFunctionParams, progress: Progress): Promise<FrameWaitForFunctionResult>;waitForSelector(params: FrameWaitForSelectorParams, progress: Progress): Promise<FrameWaitForSelectorResult>;expect(params: FrameExpectParams, progress: Progress): Promise<FrameExpectResult>;- webmcpEnable(params: FrameWebmcpEnableParams, progress: Progress): Promise<FrameWebmcpEnableResult>;- webmcpDisable(params: FrameWebmcpDisableParams, progress: Progress): Promise<FrameWebmcpDisableResult>;webmcpTools(params: FrameWebmcpToolsParams, progress: Progress): Promise<FrameWebmcpToolsResult>;webmcpCallTool(params: FrameWebmcpCallToolParams, progress: Progress): Promise<FrameWebmcpCallToolResult>;}@@ -2363,18 +2360,6 @@ export type FrameNavigatedEvent = {},error?: string,};-export type FrameWebmcpToolsChangedEvent = {- tools: {- name: string,- description: string,- inputSchema?: any,- annotations?: {- readOnly?: boolean,- untrustedContent?: boolean,- consequential?: boolean,- },- }[],-};export type FrameEvalOnSelectorParams = {selector: string,strict?: boolean,@@ -3032,12 +3017,6 @@ export type FrameExpectErrorDetails = {timedOut?: boolean,customErrorMessage?: string,};-export type FrameWebmcpEnableParams = {};-export type FrameWebmcpEnableOptions = {};-export type FrameWebmcpEnableResult = void;-export type FrameWebmcpDisableParams = {};-export type FrameWebmcpDisableOptions = {};-export type FrameWebmcpDisableResult = void;export type FrameWebmcpToolsParams = {};export type FrameWebmcpToolsOptions = {};export type FrameWebmcpToolsResult = {@@ -3054,19 +3033,18 @@ export type FrameWebmcpToolsResult = {};export type FrameWebmcpCallToolParams = {name: string,- input?: any,+ input: SerializedArgument,};export type FrameWebmcpCallToolOptions = {- input?: any,+};export type FrameWebmcpCallToolResult = {- result?: any,+ result: SerializedValue,};export interface FrameEvents {'loadstate': FrameLoadstateEvent;'navigated': FrameNavigatedEvent;- 'webmcpToolsChanged': FrameWebmcpToolsChangedEvent;}// ----------- JSHandle -----------diff --git a/packages/playwright-core/src/server/chromium/crPage.ts b/packages/playwright-core/src/server/chromium/crPage.tsindex 3ba35b2104..7c4824c23e 100644--- a/packages/playwright-core/src/server/chromium/crPage.ts+++ b/packages/playwright-core/src/server/chromium/crPage.ts@@ -18,7 +18,6 @@import { assert } from '@isomorphic/assert';import { rewriteErrorMessage } from '@utils/stackTrace';import { eventsHelper } from '@utils/eventsHelper';-import { ManualPromise } from '@isomorphic/manualPromise';import * as dialog from '../dialog';import * as dom from '../dom';import * as frames from '../frames';@@ -46,7 +45,6 @@ import type { InitScript, PageDelegate } from '../page';import type { Progress } from '../progress';import type * as types from '../types';import type * as channels from '../channels';-import type { RawWebMCPTool } from '../webmcp';export type WindowBounds = { top?: number, left?: number, width?: number, height?: number };@@ -88,9 +86,6 @@ export class CRPage implements PageDelegate {// of their Page.windowOpen events is not guaranteed to match the order// of new popup targets.readonly _nextWindowOpenPopupFeatures: string[][] = [];- // Resolves to whether the browser implements the WebMCP domain.- _webmcpSupported: Promise<boolean> = Promise.resolve(false);- private readonly _webmcpInvocations = new Map<string, ManualPromise<Protocol.WebMCP.toolRespondedPayload>>();static mainFrameSession(page: Page): FrameSession {const crPage = page.delegate as CRPage;@@ -166,34 +161,6 @@ export class CRPage implements PageDelegate {this._mainFrameSession._willBeginDownload();}- enableWebMCP(): Promise<boolean> {- return this._webmcpSupported;- }-- async callWebMCPTool(progress: Progress, frame: frames.Frame, name: string, input: unknown): Promise<unknown> {- const client = this._sessionForFrame(frame)._client;- const { invocationId } = await progress.race(client.send('WebMCP.invokeTool', { frameId: frame._id, toolName: name, input: input as Protocol.WebMCP.invokeToolParameters['input'] }));- // The invocation id arrives before any of the invocation events.- const responded = new ManualPromise<Protocol.WebMCP.toolRespondedPayload>();- this._webmcpInvocations.set(invocationId, responded);- try {- const response = await progress.race(responded);- if (response.exception?.objectId)- releaseObject(client, response.exception.objectId);- if (response.status === 'Completed')- return response.output;- throw new Error(response.errorText || response.exception?.description || `WebMCP tool "${name}" ${response.status === 'Canceled' ? 'was canceled' : 'failed'}`);- } finally {- this._webmcpInvocations.delete(invocationId);- if (!responded.isDone())- client._sendMayFail('WebMCP.cancelInvocation', { invocationId });- }- }-- _onWebMCPToolResponded(event: Protocol.WebMCP.toolRespondedPayload) {- this._webmcpInvocations.get(event.invocationId)?.resolve(event);- }-didClose() {for (const session of this._sessions.values())session.dispose();@@ -489,9 +456,6 @@ class FrameSession {eventsHelper.addEventListener(this._client, 'Runtime.executionContextCreated', event => this._onExecutionContextCreated(event.context)),eventsHelper.addEventListener(this._client, 'Runtime.executionContextDestroyed', event => this._onExecutionContextDestroyed(event.executionContextId)),eventsHelper.addEventListener(this._client, 'Runtime.executionContextsCleared', event => this._onExecutionContextsCleared()),- eventsHelper.addEventListener(this._client, 'WebMCP.toolsAdded', event => this._onWebMCPToolsAdded(event)),- eventsHelper.addEventListener(this._client, 'WebMCP.toolsRemoved', event => this._onWebMCPToolsRemoved(event)),- eventsHelper.addEventListener(this._client, 'WebMCP.toolResponded', event => this._crPage._onWebMCPToolResponded(event)),]);}@@ -539,12 +503,6 @@ class FrameSession {// so we have to buffer events instead.this._bufferedAttachedToTargetEvents = [];- // Enabling only reports the tools of the main frame, so listen from the start to catch the- // ones that child frames register. Older browsers do not have the domain.- const webmcpEnabled = this._client._sendMayFail('WebMCP.enable').then(result => !!result);- if (this._isMainFrame())- this._crPage._webmcpSupported = webmcpEnabled;-const promises: Promise<any>[] = [this._client.send('Page.enable'),this._client.send('Page.getFrameTree').then(({ frameTree }) => {@@ -586,7 +544,6 @@ class FrameSession {this._client.send('Log.enable', {}),lifecycleEventsEnabled = this._client.send('Page.setLifecycleEventsEnabled', { enabled: true }),this._client.send('Runtime.enable', {}),- webmcpEnabled,this._client.send('Page.addScriptToEvaluateOnNewDocument', {source: '',worldName: this._crPage.utilityWorldName,@@ -935,40 +892,6 @@ class FrameSession {}}- private _onWebMCPToolsAdded(event: Protocol.WebMCP.toolsAddedPayload) {- const toolsByFrame = new Map<frames.Frame, RawWebMCPTool[]>();- for (const tool of event.tools) {- const frame = this._page.frameManager.frame(tool.frameId);- if (!frame)- continue;- let tools = toolsByFrame.get(frame);- if (!tools) {- tools = [];- toolsByFrame.set(frame, tools);- }- tools.push({ name: tool.name, description: tool.description, inputSchema: tool.inputSchema, annotations: tool.annotations });- }- for (const [frame, tools] of toolsByFrame)- frame.webmcp.toolsAdded(tools);- }-- private _onWebMCPToolsRemoved(event: Protocol.WebMCP.toolsRemovedPayload) {- const namesByFrame = new Map<frames.Frame, string[]>();- for (const tool of event.tools) {- const frame = this._page.frameManager.frame(tool.frameId);- if (!frame)- continue;- let names = namesByFrame.get(frame);- if (!names) {- names = [];- namesByFrame.set(frame, names);- }- names.push(tool.name);- }- for (const [frame, names] of namesByFrame)- frame.webmcp.toolsRemoved(names);- }-_onDialog(event: Protocol.Page.javascriptDialogOpeningPayload) {if (!this._page.frameManager.frame(this._targetId))return; // Our frame/subtree may be gone already.diff --git a/packages/playwright-core/src/server/dispatchers/frameDispatcher.ts b/packages/playwright-core/src/server/dispatchers/frameDispatcher.tsindex eee4307277..5bc04e1d81 100644--- a/packages/playwright-core/src/server/dispatchers/frameDispatcher.ts+++ b/packages/playwright-core/src/server/dispatchers/frameDispatcher.ts@@ -25,7 +25,6 @@ import type { Progress } from '../progress';import type { BrowserContextDispatcher } from './browserContextDispatcher';import type { PageDispatcher } from './pageDispatcher';import type { NavigationEvent } from '../frames';-import type { WebMCPToolInfo } from '../webmcp';import type * as channels from '../channels';export class FrameDispatcher extends Dispatcher<Frame, channels.FrameChannel, BrowserContextDispatcher | PageDispatcher> implements channels.FrameChannel {@@ -58,7 +57,6 @@ export class FrameDispatcher extends Dispatcher<Frame, channels.FrameChannel, Br}, gcBucket);this._browserContextDispatcher = scope;this._frame = frame;- this.addObjectListener(Frame.Events.WebMCPToolsChanged, (tools: WebMCPToolInfo[]) => this._dispatchEvent('webmcpToolsChanged', { tools }));this.addObjectListener(Frame.Events.AddLifecycle, lifecycleEvent => {this._dispatchEvent('loadstate', { add: lifecycleEvent });});@@ -256,20 +254,12 @@ export class FrameDispatcher extends Dispatcher<Frame, channels.FrameChannel, Brreturn await this._frame.uncheck(progress, params, params);}- async webmcpEnable(params: channels.FrameWebmcpEnableParams, progress: Progress): Promise<void> {- await this._frame.webmcp.enable(progress);- }-- async webmcpDisable(params: channels.FrameWebmcpDisableParams, progress: Progress): Promise<void> {- await this._frame.webmcp.disable(progress);- }-async webmcpTools(params: channels.FrameWebmcpToolsParams, progress: Progress): Promise<channels.FrameWebmcpToolsResult> {return { tools: await this._frame.webmcp.tools(progress) };}async webmcpCallTool(params: channels.FrameWebmcpCallToolParams, progress: Progress): Promise<channels.FrameWebmcpCallToolResult> {- return { result: await this._frame.webmcp.callTool(progress, params.name, params.input) };+ return { result: serializeResult(await this._frame.webmcp.callTool(progress, params.name, parseArgument(params.input))) };}async waitForTimeout(params: channels.FrameWaitForTimeoutParams, progress: Progress): Promise<void> {diff --git a/packages/playwright-core/src/server/frames.ts b/packages/playwright-core/src/server/frames.tsindex 5d74ae0e39..d9080e4e2d 100644--- a/packages/playwright-core/src/server/frames.ts+++ b/packages/playwright-core/src/server/frames.ts@@ -48,7 +48,6 @@ import type { ScreenshotOptions } from './screenshotter';import type { RegisteredListener } from '@utils/eventsHelper';import type * as channels from './channels';import type { AriaSnapshotJSON } from '@isomorphic/ariaSnapshot';-import type { WebMCPToolInfo } from './webmcp';type ContextData = {contextPromise: ManualPromise<dom.FrameExecutionContext | { destroyedReason: string }>;@@ -504,14 +503,12 @@ const FrameEvent = {InternalNavigation: 'internalnavigation',AddLifecycle: 'addlifecycle',RemoveLifecycle: 'removelifecycle',- WebMCPToolsChanged: 'webmcptoolschanged',} as const;export type FrameEventMap = {[FrameEvent.InternalNavigation]: [event: NavigationEvent];[FrameEvent.AddLifecycle]: [event: types.LifecycleEvent];[FrameEvent.RemoveLifecycle]: [event: types.LifecycleEvent];- [FrameEvent.WebMCPToolsChanged]: [tools: WebMCPToolInfo[]];};export class Frame extends SdkObject<FrameEventMap> {diff --git a/packages/playwright-core/src/server/page.ts b/packages/playwright-core/src/server/page.tsindex 47e06bbc20..bc46024441 100644--- a/packages/playwright-core/src/server/page.ts+++ b/packages/playwright-core/src/server/page.ts@@ -41,7 +41,6 @@ import * as rawBindingsControllerSource from '../generated/bindingsControllerSouimport { Overlay } from './overlay';import { NonRecoverableDOMError } from './dom';import { Screencast } from './screencast';-import { WebMCPInstrumentation } from './webmcp';import { saveGlobalsSnapshotSource } from './javascript';import type { Artifact } from './artifact';@@ -96,8 +95,6 @@ export interface PageDelegate {pdf?: (options: channels.PagePdfParams) => Promise<Buffer>;coverage?: () => any;noUtilityWorld?: () => boolean;- enableWebMCP?(): Promise<boolean>;- callWebMCPTool?(progress: Progress, frame: frames.Frame, name: string, input: unknown): Promise<unknown>;// Work around WebKit's raf issues on Windows.rafCountForStablePosition(): number;@@ -204,7 +201,6 @@ export class Page extends SdkObject<PageEventMap> {readonly overlay: Overlay;readonly screencast: Screencast;- readonly webmcpInstrumentation: WebMCPInstrumentation;_closeReason: string | undefined;private _customCloseHandler?: (runBeforeUnload: boolean) => Promise<void>;@@ -221,7 +217,6 @@ export class Page extends SdkObject<PageEventMap> {this.frameManager = new frames.FrameManager(this);this.overlay = new Overlay(this);this.screencast = new Screencast(this);- this.webmcpInstrumentation = new WebMCPInstrumentation(this);if (delegate.pdf)this.pdf = delegate.pdf.bind(delegate);this.coverage = delegate.coverage ? delegate.coverage() : null;diff --git a/packages/playwright-core/src/server/webmcp.ts b/packages/playwright-core/src/server/webmcp.tsindex 1431304ad4..6634649920 100644--- a/packages/playwright-core/src/server/webmcp.ts+++ b/packages/playwright-core/src/server/webmcp.ts@@ -14,11 +14,11 @@* limitations under the License.*/-import { kBindingsControllerProperty } from '@isomorphic/utilityScriptSerializers';import * as rawWebMCPSource from '../generated/webMCPSource';-import { Frame } from './frames';-import type { InitScript, Page, PageBinding } from './page';+import type { Frame } from './frames';+import type { WebMCPToolDescription } from '@injected/webMCP';+import type { Page } from './page';import type { Progress } from './progress';export type WebMCPToolAnnotations = {@@ -34,210 +34,35 @@ export type WebMCPToolInfo = {annotations?: WebMCPToolAnnotations;};-export type RawWebMCPTool = {- name: string;- description: string;- inputSchema?: unknown;- annotations?: WebMCPToolAnnotations;-};--const kToolsChangedBinding = '__pw_webmcpToolsChanged';-const kScriptProperty = '__pw_webmcp';--const kScriptOptions = JSON.stringify({- property: kScriptProperty,- bindingName: kToolsChangedBinding,- bindingsControllerProperty: kBindingsControllerProperty,-});--const kInstallSource = `(() => {+const kScriptSource = `(() => {const module = {};${rawWebMCPSource.source}- return module.exports.WebMCPScript().install(globalThis, ${kScriptOptions});+ return new (module.exports.WebMCPScript())(globalThis);})()`;export class WebMCP {private _frame: Frame;- private _tools = new Map<string, WebMCPToolInfo>();- private _enabled: Promise<boolean> | undefined;- private _lastSignature: string | undefined;- private _changeScheduled = false;constructor(frame: Frame) {this._frame = frame;- frame.on(Frame.Events.InternalNavigation, event => {- if (event.newDocument && !event.error)- this.toolsReported([]);- });- }-- async enable(progress: Progress) {- if (!this._enabled) {- assertBrowserSupport(this._frame._page);- const enabled = this._enable(progress);- this._enabled = enabled;- enabled.catch(() => {- if (this._enabled === enabled)- this._enabled = undefined;- });- }- await progress.race(this._enabled);- }-- async disable(progress: Progress) {- const enabled = this._enabled;- if (!enabled)- return;- try {- await progress.race(enabled);- } catch {- }- if (this._enabled !== enabled)- return;- this._enabled = undefined;- this._lastSignature = undefined;- await this._frame._page.webmcpInstrumentation.release(progress, this._frame);}async tools(progress: Progress): Promise<WebMCPToolInfo[]> {- await progress.race(this._enabledPromise());- return this._snapshot();+ assertBrowserSupport(this._frame._page);+ const tools: WebMCPToolDescription[] = await this._frame.evaluateExpression(progress, `${kScriptSource}.tools()`, { world: 'utility' });+ return tools.map(normalizeTool);}async callTool(progress: Progress, name: string, input: unknown): Promise<unknown> {- const native = await progress.race(this._enabledPromise());- if (!this._tools.has(name)) {- const available = [...this._tools.keys()];+ const tools = await this.tools(progress);+ if (!tools.some(tool => tool.name === name)) {+ const available = tools.map(tool => tool.name);throw new Error(`No WebMCP tool named "${name}".` +(available.length ? ` Available tools: ${available.join(', ')}.` : ' The frame does not register any WebMCP tools.'));}- if (native)- return await this._frame._page.delegate.callWebMCPTool!(progress, this._frame, name, input ?? {});- return await this._callToolInPage(progress, name, input ?? {});- }-- toolsAdded(tools: RawWebMCPTool[]) {- for (const tool of tools)- this._tools.set(tool.name, normalizeTool(tool));- this._scheduleChanged();- }-- toolsRemoved(names: string[]) {- for (const name of names)- this._tools.delete(name);- this._scheduleChanged();- }-- toolsReported(tools: RawWebMCPTool[]) {- this._tools = new Map(tools.map(tool => [tool.name, normalizeTool(tool)]));- this._scheduleChanged();- }-- private _enabledPromise(): Promise<boolean> {- if (!this._enabled)- throw new Error('WebMCP is not enabled. Call webmcp.enable() first.');- return this._enabled;- }-- private async _enable(progress: Progress): Promise<boolean> {- const page = this._frame._page;- const native = await progress.race(page.delegate.enableWebMCP?.() ?? Promise.resolve(false));- if (!native)- this.toolsReported(await page.webmcpInstrumentation.acquire(progress, this._frame));- this._lastSignature = this._signature(this._snapshot());- return native;- }-- private _scheduleChanged() {- if (this._changeScheduled)- return;- this._changeScheduled = true;- queueMicrotask(() => {- this._changeScheduled = false;- this._emitIfChanged();- });- }-- private _emitIfChanged() {- if (this._lastSignature === undefined)- return;- const tools = this._snapshot();- const signature = this._signature(tools);- if (signature === this._lastSignature)- return;- this._lastSignature = signature;- this._frame.emit(Frame.Events.WebMCPToolsChanged, tools);- }-- private _signature(tools: WebMCPToolInfo[]): string {- return JSON.stringify(tools.map(tool => [tool.name, tool.description, tool.inputSchema ?? null, tool.annotations ?? null]));- }-- private _snapshot(): WebMCPToolInfo[] {- return [...this._tools.values()].map(tool => ({ ...tool }));- }-- private async _callToolInPage(progress: Progress, name: string, input: unknown): Promise<unknown> {- const resultJson: string = await this._frame.evaluateExpression(progress, `params => {- const script = globalThis[params.property];- if (!script)- throw new Error('WebMCP is not available in this frame');- return script.callTool(params.name, params.inputJson);- }`, { isFunction: true }, { property: kScriptProperty, name, inputJson: JSON.stringify(input) });- return JSON.parse(resultJson);- }-}--// Page-wide hooks for browsers that do not report tool registrations natively.-// Init scripts and bindings cover every frame, the frames pick out their own reports.-export class WebMCPInstrumentation {- private _page: Page;- private _frames = new Set<Frame>();- private _installed: Promise<{ binding: PageBinding, initScript: InitScript }> | undefined;-- constructor(page: Page) {- this._page = page;- }-- async acquire(progress: Progress, frame: Frame): Promise<RawWebMCPTool[]> {- if (!this._installed) {- const installed = this._install(progress);- this._installed = installed;- installed.catch(() => {- if (this._installed === installed)- this._installed = undefined;- });- }- await progress.race(this._installed);- this._frames.add(frame);- // The current document registered its tools before the hooks were in place, or while nobody listened.- return await progress.race(frame.nonStallingEvaluateInExistingContext(kInstallSource, 'main').catch(() => []));- }-- async release(progress: Progress, frame: Frame) {- this._frames.delete(frame);- if (this._frames.size || !this._installed)- return;- const installed = this._installed;- this._installed = undefined;- let hooks: { binding: PageBinding, initScript: InitScript };- try {- hooks = await progress.race(installed);- } catch {- return;- }- await progress.race(Promise.all([hooks.binding.dispose(), hooks.initScript.dispose()]));- }-- private async _install(progress: Progress) {- const binding = await this._page.exposeBinding(progress, kToolsChangedBinding, ({ frame }, tools: RawWebMCPTool[]) => frame.webmcp.toolsReported(tools), true);- try {- const initScript = await this._page.addInitScript(progress, kInstallSource);- return { binding, initScript };- } catch (error) {- binding.dispose().catch(() => {});- throw error;- }+ // Firefox denies the page access to objects created in the utility world, so the input is passed in the main world.+ const world = this._frame._page.browserContext._browser.options.browserType === 'firefox' ? 'main' : 'utility';+ return await this._frame.evaluateExpression(progress, `params => ${kScriptSource}.callTool(params.name, params.input)`, { isFunction: true, world }, { name, input: input ?? {} });}}@@ -254,12 +79,15 @@ function assertBrowserSupport(page: Page) {.flatMap(arg => arg.substring('--enable-features='.length).split(','));if (!features.includes('WebMCP'))throw new Error('WebMCP is not enabled. Launch the browser with the "--enable-features=WebMCP" argument.');- } else if (originalLaunchOptions.firefoxUserPrefs?.['dom.modelcontext.enabled'] !== true) {- throw new Error('WebMCP is not enabled. Launch the browser with the "dom.modelcontext.enabled" preference set to true.');+ } else {+ // The testing preference gates getTools() and invokeTool().+ const prefs = originalLaunchOptions.firefoxUserPrefs;+ if (prefs?.['dom.modelcontext.enabled'] !== true || prefs?.['dom.modelcontext.testing.enabled'] !== true)+ throw new Error('WebMCP is not enabled. Launch the browser with the "dom.modelcontext.enabled" and "dom.modelcontext.testing.enabled" preferences set to true.');}}-function normalizeTool(tool: RawWebMCPTool): WebMCPToolInfo {+function normalizeTool(tool: WebMCPToolDescription): WebMCPToolInfo {const annotations: WebMCPToolAnnotations = {};if (tool.annotations?.readOnly)annotations.readOnly = true;diff --git a/packages/playwright-core/src/tools/backend/tab.ts b/packages/playwright-core/src/tools/backend/tab.tsindex a996d11733..f23a36e438 100644--- a/packages/playwright-core/src/tools/backend/tab.ts+++ b/packages/playwright-core/src/tools/backend/tab.ts@@ -140,12 +140,6 @@ export class Tab extends EventEmitter<TabEventsInterface> {this._downloadStarted(download).catch(e => debug('pw:tools:error')(e));}),];- if (context.config.webmcp !== false) {- this._disposables.push(- eventsHelper.addEventListener(p, 'frameattached', frame => this._enableWebMCP(frame)),- eventsHelper.addEventListener(p, 'framedetached', () => this._refreshWebMCPTools()),- );- }// eslint-disable-next-line no-restricted-syntax(page as any)[tabSymbol] = this;const wallTime = Date.now();@@ -182,8 +176,6 @@ export class Tab extends EventEmitter<TabEventsInterface> {}private async _initialize() {- if (this.context.config.webmcp !== false)- await Promise.all(this.page.frames().map(frame => this._enableWebMCP(frame)));for (const message of await Tab.collectConsoleMessages(this.page))this._handleConsoleMessage(message);const requests = await this.page.requests().catch(() => []);@@ -498,21 +490,6 @@ export class Tab extends EventEmitter<TabEventsInterface> {return this._webmcpTools;}- private async _enableWebMCP(frame: playwright.Frame) {- try {- await frame.webmcp.enable();- } catch (e) {- debug('pw:tools:error')(e);- return;- }- // The browser reports registrations as they happen, so the MCP tool list follows the page.- frame.webmcp.on('toolschanged', () => this._refreshWebMCPTools());- }-- private _refreshWebMCPTools() {- this.updateWebMCPTools().catch(e => debug('pw:tools:error')(e));- }-async updateWebMCPTools(): Promise<void> {if (this.context.config.webmcp === false)return;diff --git a/packages/playwright-core/src/tools/backend/webmcp.ts b/packages/playwright-core/src/tools/backend/webmcp.tsindex 7cb6f17500..91a9814b0a 100644--- a/packages/playwright-core/src/tools/backend/webmcp.ts+++ b/packages/playwright-core/src/tools/backend/webmcp.ts@@ -63,7 +63,7 @@ export type WebMCPListing = {export async function listWebMCPTools(tab: Tab): Promise<WebMCPListing> {const frames = tab.page.frames();- // Frames that are not enabled or are stuck report no tools.+ // Frames that are stuck or belong to a browser without WebMCP report no tools.const toolsPerFrame = await Promise.all(frames.map(frame => frame.webmcp.tools({ timeout: kListTimeout }).catch(() => [])));// Several frames can share a URL, for example a widget embedded twice, and each one has its// own model context that can register the same tool name. Fall back to the frame's positiondiff --git a/packages/playwright-core/types/types.d.ts b/packages/playwright-core/types/types.d.tsindex 110d4ed5af..ed3dc49e12 100644--- a/packages/playwright-core/types/types.d.ts+++ b/packages/playwright-core/types/types.d.ts@@ -23835,21 +23835,20 @@ export interface WebError {/*** [WebMCP](https://playwright.dev/docs/api/class-webmcp) exposes the tools that a frame registers through the* experimental [WebMCP](https://playwright.dev/docs/api/class-webmcp) browser API, `navigator.modelContext`. It lists- * the tools, reports when the set of tools changes, and calls the tools.+ * the tools and calls them.** Instances are accessed through [frame.webmcp](https://playwright.dev/docs/api/class-frame#frame-webmcp).- * [page.webmcp](https://playwright.dev/docs/api/class-page#page-webmcp) is the instance of the main frame. Call- * [webMCP.enable()](https://playwright.dev/docs/api/class-webmcp#web-mcp-enable) before using the other methods.+ * [page.webmcp](https://playwright.dev/docs/api/class-page#page-webmcp) is the instance of the main frame.** **NOTE** WebMCP is an experimental browser feature. Chromium enables it with the `--enable-features=WebMCP` launch- * argument, Firefox with the `dom.modelcontext.enabled` preference. WebKit does not implement it.+ * argument, Firefox with the `dom.modelcontext.enabled` and `dom.modelcontext.testing.enabled` preferences. WebKit+ * does not implement it.** Tool names, descriptions, input schemas and results are provided by the page, so treat them as untrusted input.** ```js* const browser = await chromium.launch({ args: ['--enable-features=WebMCP'] });* const page = await browser.newPage();- * await page.webmcp.enable();* await page.goto('https://example.com');** for (const tool of await page.webmcp.tools())@@ -23860,273 +23859,6 @@ export interface WebError {**/export interface WebMCP {- /**- * Emitted while WebMCP is enabled, whenever the set of tools registered by the frame changes, for example when the- * page registers or unregisters a tool, or when the frame navigates away. The argument is the new list of tools, the- * same one [webMCP.tools([options])](https://playwright.dev/docs/api/class-webmcp#web-mcp-tools) returns.- *- * ```js- * page.webmcp.on('toolschanged', tools => {- * console.log('tools are now', tools.map(tool => tool.name));- * });- * ```- *- */- on(event: 'toolschanged', listener: (data: Array<{- /**- * Tool name, unique within the frame.- */- name: string;-- /**- * Tool description.- */- description: string;-- /**- * JSON Schema of the tool input, when the page provides one.- */- inputSchema?: Serializable;-- /**- * Hints the page provides about the tool.- */- annotations?: {- /**- * The tool does not modify any state.- */- readOnly?: boolean;-- /**- * The tool output may contain third-party content.- */- untrustedContent?: boolean;-- /**- * The tool takes a consequential action, such as placing an order.- */- consequential?: boolean;- };- }>) => any): this;-- /**- * Adds an event listener that will be automatically removed after it is triggered once. See `addListener` for more information about this event.- */- once(event: 'toolschanged', listener: (data: Array<{- /**- * Tool name, unique within the frame.- */- name: string;-- /**- * Tool description.- */- description: string;-- /**- * JSON Schema of the tool input, when the page provides one.- */- inputSchema?: Serializable;-- /**- * Hints the page provides about the tool.- */- annotations?: {- /**- * The tool does not modify any state.- */- readOnly?: boolean;-- /**- * The tool output may contain third-party content.- */- untrustedContent?: boolean;-- /**- * The tool takes a consequential action, such as placing an order.- */- consequential?: boolean;- };- }>) => any): this;-- /**- * Emitted while WebMCP is enabled, whenever the set of tools registered by the frame changes, for example when the- * page registers or unregisters a tool, or when the frame navigates away. The argument is the new list of tools, the- * same one [webMCP.tools([options])](https://playwright.dev/docs/api/class-webmcp#web-mcp-tools) returns.- *- * ```js- * page.webmcp.on('toolschanged', tools => {- * console.log('tools are now', tools.map(tool => tool.name));- * });- * ```- *- */- addListener(event: 'toolschanged', listener: (data: Array<{- /**- * Tool name, unique within the frame.- */- name: string;-- /**- * Tool description.- */- description: string;-- /**- * JSON Schema of the tool input, when the page provides one.- */- inputSchema?: Serializable;-- /**- * Hints the page provides about the tool.- */- annotations?: {- /**- * The tool does not modify any state.- */- readOnly?: boolean;-- /**- * The tool output may contain third-party content.- */- untrustedContent?: boolean;-- /**- * The tool takes a consequential action, such as placing an order.- */- consequential?: boolean;- };- }>) => any): this;-- /**- * Removes an event listener added by `on` or `addListener`.- */- removeListener(event: 'toolschanged', listener: (data: Array<{- /**- * Tool name, unique within the frame.- */- name: string;-- /**- * Tool description.- */- description: string;-- /**- * JSON Schema of the tool input, when the page provides one.- */- inputSchema?: Serializable;-- /**- * Hints the page provides about the tool.- */- annotations?: {- /**- * The tool does not modify any state.- */- readOnly?: boolean;-- /**- * The tool output may contain third-party content.- */- untrustedContent?: boolean;-- /**- * The tool takes a consequential action, such as placing an order.- */- consequential?: boolean;- };- }>) => any): this;-- /**- * Removes an event listener added by `on` or `addListener`.- */- off(event: 'toolschanged', listener: (data: Array<{- /**- * Tool name, unique within the frame.- */- name: string;-- /**- * Tool description.- */- description: string;-- /**- * JSON Schema of the tool input, when the page provides one.- */- inputSchema?: Serializable;-- /**- * Hints the page provides about the tool.- */- annotations?: {- /**- * The tool does not modify any state.- */- readOnly?: boolean;-- /**- * The tool output may contain third-party content.- */- untrustedContent?: boolean;-- /**- * The tool takes a consequential action, such as placing an order.- */- consequential?: boolean;- };- }>) => any): this;-- /**- * Emitted while WebMCP is enabled, whenever the set of tools registered by the frame changes, for example when the- * page registers or unregisters a tool, or when the frame navigates away. The argument is the new list of tools, the- * same one [webMCP.tools([options])](https://playwright.dev/docs/api/class-webmcp#web-mcp-tools) returns.- *- * ```js- * page.webmcp.on('toolschanged', tools => {- * console.log('tools are now', tools.map(tool => tool.name));- * });- * ```- *- */- prependListener(event: 'toolschanged', listener: (data: Array<{- /**- * Tool name, unique within the frame.- */- name: string;-- /**- * Tool description.- */- description: string;-- /**- * JSON Schema of the tool input, when the page provides one.- */- inputSchema?: Serializable;-- /**- * Hints the page provides about the tool.- */- annotations?: {- /**- * The tool does not modify any state.- */- readOnly?: boolean;-- /**- * The tool output may contain third-party content.- */- untrustedContent?: boolean;-- /**- * The tool takes a consequential action, such as placing an order.- */- consequential?: boolean;- };- }>) => any): this;-/*** Calls a tool registered by the frame and returns its result. The result is whatever the tool's `execute` function* resolved to, typically an object with a `content` array. A result with `isError: true` is returned as is. The@@ -24153,39 +23885,11 @@ export interface WebMCP {}): Promise<Serializable>;/**- * Stops tracking the tools that the frame registers and stops emitting- * [webMCP.on('toolschanged')](https://playwright.dev/docs/api/class-webmcp#web-mcp-event-tools-changed). Disposing- * the [Disposable](https://playwright.dev/docs/api/class-disposable) returned by- * [webMCP.enable()](https://playwright.dev/docs/api/class-webmcp#web-mcp-enable) does the same.- */- disable(): Promise<void>;-- /**- * Starts tracking the tools that the frame registers, so that- * [webMCP.tools([options])](https://playwright.dev/docs/api/class-webmcp#web-mcp-tools),- * [webMCP.callTool(name[, input, options])](https://playwright.dev/docs/api/class-webmcp#web-mcp-call-tool) and- * [webMCP.on('toolschanged')](https://playwright.dev/docs/api/class-webmcp#web-mcp-event-tools-changed) work. Throws- * if the browser was launched without WebMCP support, see the note above for the launch options that enable it.- * Returns a [Disposable](https://playwright.dev/docs/api/class-disposable) that disables the tracking again.+ * Returns the tools currently registered by the frame. Throws if the browser was launched without WebMCP support, see+ * the note above for the launch options that enable it.*- * Tracking is per frame. [page.webmcp](https://playwright.dev/docs/api/class-page#page-webmcp) covers the main frame- * only, child frames are tracked through their own- * [frame.webmcp](https://playwright.dev/docs/api/class-frame#frame-webmcp).- *- * Chromium reports tool registrations natively. Firefox does not, so Playwright instruments `navigator.modelContext`- * in the page to observe registrations. Tools registered before the call are picked up as well.- *- * ```js- * await page.webmcp.enable();- * await page.goto('https://example.com');- * console.log(await page.webmcp.tools());- * ```- *- */- enable(): Promise<Disposable>;-- /**- * Returns the tools currently registered by the frame.+ * [page.webmcp](https://playwright.dev/docs/api/class-page#page-webmcp) covers the main frame only, child frames list+ * their tools through their own [frame.webmcp](https://playwright.dev/docs/api/class-frame#frame-webmcp).* @param options*/tools(options?: {@@ -24232,126 +23936,6 @@ export interface WebMCP {consequential?: boolean;};}>>;-- /**- * Emitted while WebMCP is enabled, whenever the set of tools registered by the frame changes, for example when the- * page registers or unregisters a tool, or when the frame navigates away. The argument is the new list of tools, the- * same one [webMCP.tools([options])](https://playwright.dev/docs/api/class-webmcp#web-mcp-tools) returns.- *- * ```js- * page.webmcp.on('toolschanged', tools => {- * console.log('tools are now', tools.map(tool => tool.name));- * });- * ```- *- */- waitForEvent(event: 'toolschanged', optionsOrPredicate?: { predicate?: (data: Array<{- /**- * Tool name, unique within the frame.- */- name: string;-- /**- * Tool description.- */- description: string;-- /**- * JSON Schema of the tool input, when the page provides one.- */- inputSchema?: Serializable;-- /**- * Hints the page provides about the tool.- */- annotations?: {- /**- * The tool does not modify any state.- */- readOnly?: boolean;-- /**- * The tool output may contain third-party content.- */- untrustedContent?: boolean;-- /**- * The tool takes a consequential action, such as placing an order.- */- consequential?: boolean;- };- }>) => boolean | Promise<boolean>, timeout?: number, signal?: AbortSignal } | ((data: Array<{- /**- * Tool name, unique within the frame.- */- name: string;-- /**- * Tool description.- */- description: string;-- /**- * JSON Schema of the tool input, when the page provides one.- */- inputSchema?: Serializable;-- /**- * Hints the page provides about the tool.- */- annotations?: {- /**- * The tool does not modify any state.- */- readOnly?: boolean;-- /**- * The tool output may contain third-party content.- */- untrustedContent?: boolean;-- /**- * The tool takes a consequential action, such as placing an order.- */- consequential?: boolean;- };- }>) => boolean | Promise<boolean>)): Promise<Array<{- /**- * Tool name, unique within the frame.- */- name: string;-- /**- * Tool description.- */- description: string;-- /**- * JSON Schema of the tool input, when the page provides one.- */- inputSchema?: Serializable;-- /**- * Hints the page provides about the tool.- */- annotations?: {- /**- * The tool does not modify any state.- */- readOnly?: boolean;-- /**- * The tool output may contain third-party content.- */- untrustedContent?: boolean;-- /**- * The tool takes a consequential action, such as placing an order.- */- consequential?: boolean;- };- }>>;-}/**diff --git a/packages/protocol/spec/frame.yml b/packages/protocol/spec/frame.ymlindex d3934e4914..ab4a3fb973 100644--- a/packages/protocol/spec/frame.yml+++ b/packages/protocol/spec/frame.yml@@ -880,14 +880,6 @@ Frame:snapshot: truepause: true- webmcpEnable:- title: Enable WebMCP- group: configuration-- webmcpDisable:- title: Disable WebMCP- group: configuration-webmcpTools:title: List WebMCP toolsgroup: getter@@ -911,9 +903,9 @@ Frame:title: Call WebMCP toolparameters:name: string- input: json?+ input: SerializedArgumentreturns:- result: json?+ result: SerializedValueevents:@@ -931,20 +923,3 @@ Frame:properties:request: Request?error: string?-- webmcpToolsChanged:- parameters:- tools:- type: array- items:- type: object- properties:- name: string- description: string- inputSchema: json?- annotations:- type: object?- properties:- readOnly: boolean?- untrustedContent: boolean?- consequential: boolean?diff --git a/packages/protocol/src/validator.ts b/packages/protocol/src/validator.tsindex 0e0c3caff0..fd8b06b564 100644--- a/packages/protocol/src/validator.ts+++ b/packages/protocol/src/validator.ts@@ -1268,18 +1268,6 @@ scheme.FrameNavigatedEvent = tObject({})),error: tOptional(tString),});-scheme.FrameWebmcpToolsChangedEvent = tObject({- tools: tArray(tObject({- name: tString,- description: tString,- inputSchema: tOptional(tAny),- annotations: tOptional(tObject({- readOnly: tOptional(tBoolean),- untrustedContent: tOptional(tBoolean),- consequential: tOptional(tBoolean),- })),- })),-});scheme.FrameEvalOnSelectorParams = tObject({selector: tString,strict: tOptional(tBoolean),@@ -1694,10 +1682,6 @@ scheme.FrameExpectErrorDetails = tObject({timedOut: tOptional(tBoolean),customErrorMessage: tOptional(tString),});-scheme.FrameWebmcpEnableParams = tOptional(tObject({}));-scheme.FrameWebmcpEnableResult = tOptional(tObject({}));-scheme.FrameWebmcpDisableParams = tOptional(tObject({}));-scheme.FrameWebmcpDisableResult = tOptional(tObject({}));scheme.FrameWebmcpToolsParams = tOptional(tObject({}));scheme.FrameWebmcpToolsResult = tObject({tools: tArray(tObject({@@ -1713,10 +1697,10 @@ scheme.FrameWebmcpToolsResult = tObject({});scheme.FrameWebmcpCallToolParams = tObject({name: tString,- input: tOptional(tAny),+ input: tType('SerializedArgument'),});scheme.FrameWebmcpCallToolResult = tObject({- result: tOptional(tAny),+ result: tType('SerializedValue'),});scheme.JSHandleInitializer = tObject({preview: tString,diff --git a/tests/library/webmcp-disabled.spec.ts b/tests/library/webmcp-disabled.spec.tsindex 94b20aaa3a..a01b07501a 100644--- a/tests/library/webmcp-disabled.spec.ts+++ b/tests/library/webmcp-disabled.spec.ts@@ -20,7 +20,7 @@ test.skip(({ browserName }) => browserName === 'webkit', 'WebKit does not implemtest.skip(({ isBidi }) => isBidi, 'WebMCP is not implemented over BiDi');test('should throw when the browser was launched without WebMCP', async ({ page, browserName }) => {- const error = await page.webmcp.enable().catch(e => e);+ const error = await page.webmcp.tools().catch(e => e);expect(error.message).toContain('WebMCP is not enabled.');expect(error.message).toContain(browserName === 'firefox' ? 'dom.modelcontext.enabled' : '--enable-features=WebMCP');});diff --git a/tests/library/webmcp.spec.ts b/tests/library/webmcp.spec.tsindex cb88dd5c8a..78d93f35ca 100644--- a/tests/library/webmcp.spec.ts+++ b/tests/library/webmcp.spec.ts@@ -70,7 +70,6 @@ test('should list tools registered by the page', async ({ page, server }) => {async execute() {},});`));- await page.webmcp.enable();await page.goto(server.PREFIX + '/');// Browsers list tools in their own order.@@ -90,14 +89,12 @@ test('should list tools registered by the page', async ({ page, server }) => {});test('should report no tools when the page registers none', async ({ page, server }) => {- await page.webmcp.enable();await page.goto(server.EMPTY_PAGE);expect(await page.webmcp.tools()).toEqual([]);});test('should call a tool', async ({ page, server }) => {serve(server, '/', registerScript(kAdd));- await page.webmcp.enable();await page.goto(server.PREFIX + '/');expect(await page.webmcp.callTool('add', { a: 2, b: 40 })).toEqual({ content: [{ type: 'text', text: '42' }] });@@ -111,13 +108,12 @@ test('should return isError results as is', async ({ page, server }) => {async execute() { return { content: [{ type: 'text', text: 'nope' }], isError: true }; },});`));- await page.webmcp.enable();await page.goto(server.PREFIX + '/');expect(await page.webmcp.callTool('broken')).toEqual({ content: [{ type: 'text', text: 'nope' }], isError: true });});-test('should throw when the tool throws', async ({ page, server }) => {+test('should throw when the tool throws', async ({ page, server, browserName }) => {serve(server, '/', registerScript(`modelContext.registerTool({name: 'throwing',@@ -125,16 +121,15 @@ test('should throw when the tool throws', async ({ page, server }) => {async execute() { throw new Error('boom'); },});`));- await page.webmcp.enable();await page.goto(server.PREFIX + '/');const error = await page.webmcp.callTool('throwing').catch(e => e);- expect(error.message).toContain('boom');+ // Chromium does not report the error that the tool threw.+ expect(error.message).toContain(browserName === 'chromium' ? 'the invocation failed' : 'boom');});test('should throw for an unknown tool', async ({ page, server }) => {serve(server, '/', registerScript(kAdd));- await page.webmcp.enable();await page.goto(server.PREFIX + '/');const error = await page.webmcp.callTool('missing').catch(e => e);@@ -150,7 +145,6 @@ test('should time out when the tool does not settle', async ({ page, server }) =execute() { return new Promise(() => {}); },});`));- await page.webmcp.enable();await page.goto(server.PREFIX + '/');const error = await page.webmcp.callTool('stuck', {}, { timeout: 500 }).catch(e => e);@@ -159,7 +153,6 @@ test('should time out when the tool does not settle', async ({ page, server }) =test('should drop tools after navigation', async ({ page, server }) => {serve(server, '/', registerScript(kAdd));- await page.webmcp.enable();await page.goto(server.PREFIX + '/');expect(await page.webmcp.tools()).toHaveLength(1);@@ -169,84 +162,34 @@ test('should drop tools after navigation', async ({ page, server }) => {expect(error.message).toContain('The frame does not register any WebMCP tools');});-test('should emit toolschanged when navigating away from the tools', async ({ page, server }) => {+test('should list a tool registered after load', async ({ page, server }) => {serve(server, '/', registerScript(kAdd));- await page.webmcp.enable();await page.goto(server.PREFIX + '/');expect(await page.webmcp.tools()).toHaveLength(1);- const changed = page.webmcp.waitForEvent('toolschanged');- await page.goto(server.EMPTY_PAGE);- expect(await changed).toEqual([]);-});--test('should list tools registered before enable', async ({ page, server }) => {- serve(server, '/', registerScript(kAdd));- await page.goto(server.PREFIX + '/');-- await page.webmcp.enable();- expect(await page.webmcp.tools()).toEqual([expect.objectContaining({ name: 'add' })]);- expect(await page.webmcp.callTool('add', { a: 1, b: 2 })).toEqual({ content: [{ type: 'text', text: '3' }] });-});--test('should throw when used before enable', async ({ page }) => {- const error = await page.webmcp.tools().catch(e => e);- expect(error.message).toContain('WebMCP is not enabled. Call webmcp.enable() first.');-});--test('should stop after disable and resume after enable', async ({ page, server }) => {- serve(server, '/', registerScript(kAdd));- const disposable = await page.webmcp.enable();- await page.goto(server.PREFIX + '/');- expect(await page.webmcp.tools()).toHaveLength(1);-- const events: string[][] = [];- page.webmcp.on('toolschanged', tools => events.push(tools.map(tool => tool.name)));- await disposable.dispose();- const error = await page.webmcp.tools().catch(e => e);- expect(error.message).toContain('WebMCP is not enabled.');await page.evaluate(() => {const modelContext = (document as any).modelContext || (navigator as any).modelContext;modelContext.registerTool({ name: 'late', description: 'Registered later', async execute() {} });});- await page.goto(server.EMPTY_PAGE);- await page.goto(server.PREFIX + '/');- expect(events).toEqual([]);-- await page.webmcp.enable();- expect((await page.webmcp.tools()).map(tool => tool.name)).toEqual(['add']);- const changed = page.webmcp.waitForEvent('toolschanged');- await page.goto(server.EMPTY_PAGE);- expect(await changed).toEqual([]);-});--test('should emit toolschanged when the page unregisters a tool', async ({ page, server, browserName }) => {- test.skip(browserName !== 'firefox', 'Chromium does not implement unregisterTool');- serve(server, '/', registerScript(kAdd));- await page.webmcp.enable();- await page.goto(server.PREFIX + '/');- expect(await page.webmcp.tools()).toHaveLength(1);-- const changed = page.webmcp.waitForEvent('toolschanged');- await page.evaluate(() => (navigator as any).modelContext.unregisterTool('add'));- expect(await changed).toEqual([]);+ const tools = (await page.webmcp.tools()).sort((a, b) => a.name.localeCompare(b.name));+ expect(tools.map(tool => tool.name)).toEqual(['add', 'late']);});-test('should emit toolschanged when the page registers a tool', async ({ page, server }) => {- serve(server, '/', registerScript(kAdd));- await page.webmcp.enable();+test('should list tools while a tool is running', async ({ page, server }) => {+ serve(server, '/', registerScript(kAdd + `+ modelContext.registerTool({+ name: 'gated',+ description: 'Resolves when released',+ execute() { return new Promise(resolve => window.release = () => resolve({ content: [{ type: 'text', text: 'released' }] })); },+ });+ `));await page.goto(server.PREFIX + '/');- const events: string[][] = [];- page.webmcp.on('toolschanged', tools => events.push(tools.map(tool => tool.name)));- const changed = page.webmcp.waitForEvent('toolschanged');- await page.evaluate(() => {- const modelContext = (document as any).modelContext || (navigator as any).modelContext;- modelContext.registerTool({ name: 'late', description: 'Registered later', async execute() {} });- });- const tools = await changed;- expect(tools.map(tool => tool.name)).toEqual(['add', 'late']);- expect(events).toEqual([['add', 'late']]);+ const result = page.webmcp.callTool('gated');+ await page.waitForFunction(() => !!(window as any).release);+ expect(await page.webmcp.tools()).toHaveLength(2);+ await page.evaluate(() => (window as any).release());+ expect(await result).toEqual({ content: [{ type: 'text', text: 'released' }] });});test('should list declarative tools', async ({ page, server, browserName }) => {@@ -257,7 +200,6 @@ test('should list declarative tools', async ({ page, server, browserName }) => {<button>Subscribe</button></form>`);- await page.webmcp.enable();await page.goto(server.PREFIX + '/');expect(await page.webmcp.tools()).toEqual([expect.objectContaining({@@ -269,10 +211,6 @@ test('should list declarative tools', async ({ page, server, browserName }) => {// A declarative tool waits for the user to submit the form.const error = await page.webmcp.callTool('subscribe', { email: '[email protected]' }, { timeout: 500 }).catch(e => e);expect(error.message).toContain('Timeout 500ms exceeded');-- const changed = page.webmcp.waitForEvent('toolschanged');- await page.evaluate(() => document.querySelector('form')!.remove());- expect(await changed).toEqual([]);});test('should scope tools to their frame', async ({ page, server, browserName }) => {@@ -285,11 +223,9 @@ test('should scope tools to their frame', async ({ page, server, browserName })async execute() { return { content: [{ type: 'text', text: 'subscribed' }] }; },});`));- await page.webmcp.enable();await page.goto(server.PREFIX + '/');const childFrame = page.frames()[1];- await childFrame.webmcp.enable();expect(await page.webmcp.tools()).toEqual([expect.objectContaining({ name: 'add' })]);expect(await childFrame.webmcp.tools()).toEqual([expect.objectContaining({ name: 'subscribe' })]);expect(await childFrame.webmcp.callTool('subscribe')).toEqual({ content: [{ type: 'text', text: 'subscribed' }] });@@ -310,11 +246,31 @@ test('should call same-name tools in their own frame', async ({ page, server, br`);serve(server, '/', registerEcho('main') + `<iframe src="/frame.html"></iframe>`);serve(server, '/frame.html', registerEcho('frame'));- await page.webmcp.enable();await page.goto(server.PREFIX + '/');const childFrame = page.frames()[1];- await childFrame.webmcp.enable();expect(await page.webmcp.callTool('echo')).toEqual({ content: [{ type: 'text', text: 'main' }] });expect(await childFrame.webmcp.callTool('echo')).toEqual({ content: [{ type: 'text', text: 'frame' }] });});++test('should list and call tools in cross-origin and nested frames', async ({ page, server, browserName }) => {+ test.skip(browserName === 'firefox', 'Firefox does not support registering WebMCP tools in iframes yet, https://bugzilla.mozilla.org/show_bug.cgi?id=2019743');+ const registerEcho = (text: string) => registerScript(`+ modelContext.registerTool({+ name: 'echo-${text}',+ description: 'Echoes ${text}',+ async execute() { return { content: [{ type: 'text', text: '${text}' }] }; },+ });+ `);+ serve(server, '/', registerEcho('main') + `<iframe allow="tools" src="${server.CROSS_PROCESS_PREFIX}/frame.html"></iframe>`);+ serve(server, '/frame.html', registerEcho('frame') + `<iframe src="/nested.html"></iframe>`);+ serve(server, '/nested.html', registerEcho('nested'));+ await page.goto(server.PREFIX + '/');++ const [mainFrame, frame, nested] = page.frames();+ expect(await mainFrame.webmcp.tools()).toEqual([{ name: 'echo-main', description: 'Echoes main' }]);+ expect(await frame.webmcp.tools()).toEqual([{ name: 'echo-frame', description: 'Echoes frame' }]);+ expect(await nested.webmcp.tools()).toEqual([{ name: 'echo-nested', description: 'Echoes nested' }]);+ expect(await frame.webmcp.callTool('echo-frame')).toEqual({ content: [{ type: 'text', text: 'frame' }] });+ expect(await nested.webmcp.callTool('echo-nested')).toEqual({ content: [{ type: 'text', text: 'nested' }] });+});