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
feat(mcp): support both v1 and v2 extension protocol in cdpRelay (#40191)
Yury Semikhatsky091e3793246a
diff --git a/packages/playwright-core/src/tools/mcp/cdpRelay.ts b/packages/playwright-core/src/tools/mcp/cdpRelay.tsindex 79832104b6..623d1f5c4a 100644--- a/packages/playwright-core/src/tools/mcp/cdpRelay.ts+++ b/packages/playwright-core/src/tools/mcp/cdpRelay.ts@@ -15,11 +15,15 @@*//**- * WebSocket server that bridges Playwright MCP and Chrome Extension+ * WebSocket server that bridges Playwright MCP and Chrome Extension.** Endpoints:* - /cdp/guid - Full CDP interface for Playwright MCP- * - /extension/guid - Extension connection for chrome.debugger forwarding+ * - /extension/guid - Extension connection+ *+ * Protocol version is controlled by PLAYWRIGHT_EXTENSION_PROTOCOL env variable:+ * - v1: single-tab, extension manages debugger attachment+ * - v2 (default): multi-tab, relay manages debugger via chrome.* APIs*/import { spawn } from 'child_process';@@ -33,10 +37,13 @@ import { registry } from '../../server/registry/index';import { addressToString } from '../utils/mcp/http';import { logUnhandledError } from './log';+import { ExtensionProtocolV1 } from './cdpRelayV1';+import { ExtensionProtocolV2 } from './cdpRelayV2';import * as protocol from './protocol';import type websocket from 'ws';import type { ExtensionCommand, ExtensionEvents } from './protocol';+import type { CDPMessage, ExtensionProtocolHandler } from './cdpRelayHandler';import type { WebSocket, WebSocketServer } from 'ws';@@ -49,14 +56,7 @@ type CDPCommand = {params?: any;};-type CDPResponse = {- id?: number;- sessionId?: string;- method?: string;- params?: any;- result?: any;- error?: { code?: number; message: string };-};+type CDPResponse = CDPMessage;export class CDPRelayServer {private _wsHost: string;@@ -68,12 +68,8 @@ export class CDPRelayServer {private _wss: WebSocketServer;private _playwrightConnection: WebSocket | null = null;private _extensionConnection: ExtensionConnection | null = null;- private _connectedTabInfo: {- targetInfo: any;- // Page sessionId that should be used by this connection.- sessionId: string;- } | undefined;- private _nextSessionId: number = 1;+ private _protocolVersion: number;+ private _handler: ExtensionProtocolHandler;private _extensionConnectionPromise!: ManualPromise<void>;constructor(server: http.Server, browserChannel: string, userDataDir?: string, executablePath?: string) {@@ -81,6 +77,19 @@ export class CDPRelayServer {this._browserChannel = browserChannel;this._userDataDir = userDataDir;this._executablePath = executablePath;+ this._protocolVersion = parseInt(process.env.PLAYWRIGHT_EXTENSION_PROTOCOL ?? protocol.VERSION.toString(), 10);++ const sendCommand = (method: string, params: any): Promise<any> => {+ if (!this._extensionConnection)+ throw new Error('Extension not connected');+ return this._extensionConnection.send(method as keyof ExtensionCommand, params);+ };+ const sendToPlaywright = (message: CDPResponse) => this._sendToPlaywright(message);++ if (this._protocolVersion >= 2)+ this._handler = new ExtensionProtocolV2(sendCommand, sendToPlaywright);+ else+ this._handler = new ExtensionProtocolV1(sendCommand, sendToPlaywright);const uuid = crypto.randomUUID();this._cdpPath = `/cdp/${uuid}`;@@ -125,7 +134,7 @@ export class CDPRelayServer {version: undefined,};url.searchParams.set('client', JSON.stringify(client));- url.searchParams.set('protocolVersion', process.env.PWMCP_TEST_PROTOCOL_VERSION ?? protocol.VERSION.toString());+ url.searchParams.set('protocolVersion', this._protocolVersion.toString());const token = process.env.PLAYWRIGHT_MCP_EXTENSION_TOKEN;if (token)url.searchParams.set('token', token);@@ -214,7 +223,7 @@ export class CDPRelayServer {}private _resetExtensionConnection() {- this._connectedTabInfo = undefined;+ this._handler.reset();this._extensionConnection = null;this._extensionConnectionPromise = new ManualPromise();void this._extensionConnectionPromise.catch(logUnhandledError);@@ -239,23 +248,10 @@ export class CDPRelayServer {this._resetExtensionConnection();this._closePlaywrightConnection(`Extension disconnected: ${reason}`);};- this._extensionConnection.onmessage = this._handleExtensionMessage.bind(this);+ this._extensionConnection.onmessage = (method, params) => this._handler.handleExtensionEvent(method, params);this._extensionConnectionPromise.resolve();}- private _handleExtensionMessage<M extends keyof ExtensionEvents>(method: M, params: ExtensionEvents[M]['params']) {- switch (method) {- case 'forwardCDPEvent':- const sessionId = params.sessionId || this._connectedTabInfo?.sessionId;- this._sendToPlaywright({- sessionId,- method: params.method,- params: params.params- });- break;- }- }-private async _handlePlaywrightMessage(message: CDPCommand): Promise<void> {debugLogger('← Playwright:', `${message.method} (id=${message.id})`);const { id, sessionId, method, params } = message;@@ -284,44 +280,11 @@ export class CDPRelayServer {case 'Browser.setDownloadBehavior': {return { };}- case 'Target.setAutoAttach': {- // Forward child session handling.- if (sessionId)- break;- // Simulate auto-attach behavior with real target info- const { targetInfo } = await this._extensionConnection!.send('attachToTab', { });- this._connectedTabInfo = {- targetInfo,- sessionId: `pw-tab-${this._nextSessionId++}`,- };- debugLogger('Simulating auto-attach');- this._sendToPlaywright({- method: 'Target.attachedToTarget',- params: {- sessionId: this._connectedTabInfo.sessionId,- targetInfo: {- ...this._connectedTabInfo.targetInfo,- attached: true,- },- waitingForDebugger: false- }- });- return { };- }- case 'Target.getTargetInfo': {- return this._connectedTabInfo?.targetInfo;- }}- return await this._forwardToExtension(method, params, sessionId);- }-- private async _forwardToExtension(method: string, params: any, sessionId: string | undefined): Promise<any> {- if (!this._extensionConnection)- throw new Error('Extension not connected');- // Top level sessionId is only passed between the relay and the client.- if (this._connectedTabInfo?.sessionId === sessionId)- sessionId = undefined;- return await this._extensionConnection.send('forwardCDPCommand', { sessionId, method, params });+ const handled = await this._handler.handleCDPCommand(method, params, sessionId);+ if (handled)+ return handled.result;+ return await this._handler.forwardToExtension(method, params, sessionId);}private _sendToPlaywright(message: CDPResponse): void {diff --git a/packages/playwright-core/src/tools/mcp/cdpRelayHandler.ts b/packages/playwright-core/src/tools/mcp/cdpRelayHandler.tsnew file mode 100644index 0000000000..93ab891970--- /dev/null+++ b/packages/playwright-core/src/tools/mcp/cdpRelayHandler.ts@@ -0,0 +1,39 @@+/**+ * Copyright (c) Microsoft Corporation.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++export type CDPMessage = {+ id?: number;+ sessionId?: string;+ method?: string;+ params?: any;+ result?: any;+ error?: { code?: number; message: string };+};++export type SendCommand = (method: string, params: any) => Promise<any>;+export type SendToPlaywright = (message: CDPMessage) => void;++export interface ExtensionProtocolHandler {+ // Handle an event from the extension. Sends CDP events to Playwright as needed.+ handleExtensionEvent(method: string, params: any): void;+ // Handle a protocol-specific CDP command.+ // Returns { result } if handled, undefined to fall through to forwarding.+ handleCDPCommand(method: string, params: any, sessionId: string | undefined): Promise<{ result: any } | undefined>;+ // Forward a CDP command to the extension.+ forwardToExtension(method: string, params: any, sessionId: string | undefined): Promise<any>;+ // Reset protocol state on extension disconnect/reconnect.+ reset(): void;+}diff --git a/packages/playwright-core/src/tools/mcp/cdpRelayV1.ts b/packages/playwright-core/src/tools/mcp/cdpRelayV1.tsnew file mode 100644index 0000000000..aa9201ef0f--- /dev/null+++ b/packages/playwright-core/src/tools/mcp/cdpRelayV1.ts@@ -0,0 +1,91 @@+/**+ * Copyright (c) Microsoft Corporation.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++/**+ * Protocol v1: single-tab interface. The extension manages debugger+ * attachment and forwards CDP events/commands through a thin wrapper.+ */++import type { ExtensionProtocolHandler, SendCommand, SendToPlaywright } from './cdpRelayHandler';+import type { ExtensionEventsV1 } from './protocol';++export class ExtensionProtocolV1 implements ExtensionProtocolHandler {+ private _sendCommand: SendCommand;+ private _sendToPlaywright: SendToPlaywright;+ private _connectedTabInfo: { targetInfo: any; sessionId: string } | undefined;+ private _nextSessionId = 1;++ constructor(sendCommand: SendCommand, sendToPlaywright: SendToPlaywright) {+ this._sendCommand = sendCommand;+ this._sendToPlaywright = sendToPlaywright;+ }++ handleExtensionEvent(method: string, params: any): void {+ switch (method) {+ case 'forwardCDPEvent': {+ const p = params as ExtensionEventsV1['forwardCDPEvent']['params'];+ const sessionId = p.sessionId || this._connectedTabInfo?.sessionId;+ this._sendToPlaywright({+ sessionId,+ method: p.method,+ params: p.params,+ });+ break;+ }+ }+ }++ async handleCDPCommand(method: string, params: any, sessionId: string | undefined): Promise<{ result: any } | undefined> {+ switch (method) {+ case 'Target.setAutoAttach': {+ if (sessionId)+ return undefined;+ const { targetInfo } = await this._sendCommand('attachToTab', {});+ this._connectedTabInfo = {+ targetInfo,+ sessionId: `pw-tab-${this._nextSessionId++}`,+ };+ this._sendToPlaywright({+ method: 'Target.attachedToTarget',+ params: {+ sessionId: this._connectedTabInfo.sessionId,+ targetInfo: {+ ...this._connectedTabInfo.targetInfo,+ attached: true,+ },+ waitingForDebugger: false,+ },+ });+ return { result: {} };+ }+ case 'Target.getTargetInfo': {+ return { result: this._connectedTabInfo?.targetInfo };+ }+ }+ return undefined;+ }++ async forwardToExtension(method: string, params: any, sessionId: string | undefined): Promise<any> {+ // Top level sessionId is only passed between the relay and the client.+ if (this._connectedTabInfo?.sessionId === sessionId)+ sessionId = undefined;+ return await this._sendCommand('forwardCDPCommand', { sessionId, method, params });+ }++ reset(): void {+ this._connectedTabInfo = undefined;+ }+}diff --git a/packages/playwright-core/src/tools/mcp/cdpRelayV2.ts b/packages/playwright-core/src/tools/mcp/cdpRelayV2.tsnew file mode 100644index 0000000000..27872b77d1--- /dev/null+++ b/packages/playwright-core/src/tools/mcp/cdpRelayV2.ts@@ -0,0 +1,202 @@+/**+ * Copyright (c) Microsoft Corporation.+ *+ * Licensed under the Apache License, Version 2.0 (the "License");+ * you may not use this file except in compliance with the License.+ * You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing, software+ * distributed under the License is distributed on an "AS IS" BASIS,+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ * See the License for the specific language governing permissions and+ * limitations under the License.+ */++/**+ * Protocol v2: multi-tab interface. The relay owns CDP session management —+ * it asks the extension for the user's tab pick (extension.selectTab), then+ * attaches the debugger and dispatches Target.attachedToTarget events to+ * Playwright. Additional tabs are created either by Playwright+ * (Target.createTarget → chrome.tabs.create) or by the controlled tabs+ * themselves (chrome.tabs.onCreated event from the extension).+ */++import { logUnhandledError } from './log';++import type { ExtensionProtocolHandler, SendCommand, SendToPlaywright } from './cdpRelayHandler';+import type { ExtensionEventsV2 } from './protocol';++type TabSession = {+ tabId: number;+ sessionId: string;+ targetInfo: any;+ // Child CDP sessionIds (workers, oopifs, ...) belonging to this tab,+ // tracked via Target.attachedToTarget / Target.detachedFromTarget events.+ childSessions: Set<string>;+};++export class ExtensionProtocolV2 implements ExtensionProtocolHandler {+ private _sendCommand: SendCommand;+ private _sendToPlaywright: SendToPlaywright;+ private _tabSessions = new Map<number, TabSession>();+ private _nextSessionId = 1;++ constructor(sendCommand: SendCommand, sendToPlaywright: SendToPlaywright) {+ this._sendCommand = sendCommand;+ this._sendToPlaywright = sendToPlaywright;+ }++ handleExtensionEvent(method: string, params: any): void {+ switch (method) {+ case 'chrome.debugger.onEvent': {+ const [source, cdpMethod, cdpParams] = params as ExtensionEventsV2['chrome.debugger.onEvent']['params'];+ if (source.tabId === undefined)+ return;+ const tabSession = this._tabSessions.get(source.tabId);+ if (!tabSession)+ return;+ // Track child CDP sessions so we can route subsequent commands for+ // them to the correct tab. Target.attachedToTarget introduces a new+ // sessionId belonging to the same tab; Target.detachedFromTarget+ // releases it.+ const childSessionId = (cdpParams as { sessionId?: string } | undefined)?.sessionId;+ if (cdpMethod === 'Target.attachedToTarget' && childSessionId)+ tabSession.childSessions.add(childSessionId);+ else if (cdpMethod === 'Target.detachedFromTarget' && childSessionId)+ tabSession.childSessions.delete(childSessionId);+ // Top-level CDP events for the tab use the tab's relay sessionId.+ // Child CDP sessions (workers, oopifs) keep their own sessionId.+ const sessionId = source.sessionId || tabSession.sessionId;+ this._sendToPlaywright({+ sessionId,+ method: cdpMethod,+ params: cdpParams,+ });+ break;+ }+ case 'chrome.debugger.onDetach': {+ const [source] = params as ExtensionEventsV2['chrome.debugger.onDetach']['params'];+ if (source.tabId !== undefined)+ this._detachTab(source.tabId);+ break;+ }+ case 'chrome.tabs.onCreated': {+ const [tab] = params as ExtensionEventsV2['chrome.tabs.onCreated']['params'];+ // A controlled tab opened a popup. Attach to it.+ if (tab.id !== undefined)+ void this._attachTab(tab.id).catch(logUnhandledError);+ break;+ }+ case 'chrome.tabs.onRemoved': {+ const [tabId] = params as ExtensionEventsV2['chrome.tabs.onRemoved']['params'];+ this._detachTab(tabId);+ break;+ }+ }+ }++ async handleCDPCommand(method: string, params: any, sessionId: string | undefined): Promise<{ result: any } | undefined> {+ switch (method) {+ case 'Target.setAutoAttach': {+ if (sessionId)+ return undefined;+ // Ask the user to pick the initial tab via the connect UI, then attach.+ const { tabId } = await this._sendCommand('extension.selectTab', []);+ await this._attachTab(tabId);+ return { result: {} };+ }+ case 'Target.createTarget': {+ const tab = await this._sendCommand('chrome.tabs.create', [{ url: params?.url }]);+ if (tab?.id === undefined)+ throw new Error('Failed to create tab');+ const tabSession = await this._attachTab(tab.id);+ return { result: { targetId: tabSession.targetInfo?.targetId } };+ }+ case 'Target.getTargetInfo': {+ if (!sessionId)+ return { result: undefined };+ return { result: this._findTabSessionBySessionId(sessionId)?.targetInfo };+ }+ }+ return undefined;+ }++ async forwardToExtension(method: string, params: any, sessionId: string | undefined): Promise<any> {+ if (!sessionId)+ throw new Error(`Unsupported command without sessionId: ${method}`);+ // Resolve the sessionId to a tab session. Two cases:+ // 1. sessionId is a relay-level tab session (pw-tab-N) → strip and route by tabId.+ // 2. sessionId is a child CDP session (worker, oopif) → route to its owning tab,+ // keep the sessionId so the extension forwards it to chrome.debugger.+ let tabSession = this._findTabSessionBySessionId(sessionId);+ let cdpSessionId: string | undefined;+ if (!tabSession) {+ tabSession = this._findTabSessionByChildSessionId(sessionId);+ cdpSessionId = sessionId;+ }+ if (!tabSession)+ throw new Error(`No tab found for sessionId: ${sessionId}`);+ return await this._sendCommand('chrome.debugger.sendCommand', [+ { tabId: tabSession.tabId, sessionId: cdpSessionId },+ method,+ params,+ ]);+ }++ reset(): void {+ this._tabSessions.clear();+ }++ private async _attachTab(tabId: number): Promise<TabSession> {+ const existing = this._tabSessions.get(tabId);+ if (existing)+ return existing;+ await this._sendCommand('chrome.debugger.attach', [{ tabId }, '1.3']);+ const result = await this._sendCommand('chrome.debugger.sendCommand', [+ { tabId },+ 'Target.getTargetInfo',+ ]);+ const targetInfo = result?.targetInfo;+ const sessionId = `pw-tab-${this._nextSessionId++}`;+ const tabSession: TabSession = { tabId, sessionId, targetInfo, childSessions: new Set() };+ this._tabSessions.set(tabId, tabSession);+ this._sendToPlaywright({+ method: 'Target.attachedToTarget',+ params: {+ sessionId,+ targetInfo: { ...targetInfo, attached: true },+ waitingForDebugger: false,+ },+ });+ return tabSession;+ }++ private _detachTab(tabId: number): void {+ const tabSession = this._tabSessions.get(tabId);+ if (!tabSession)+ return;+ this._tabSessions.delete(tabId);+ this._sendToPlaywright({+ method: 'Target.detachedFromTarget',+ params: { sessionId: tabSession.sessionId },+ });+ }++ private _findTabSessionBySessionId(sessionId: string): TabSession | undefined {+ for (const session of this._tabSessions.values()) {+ if (session.sessionId === sessionId)+ return session;+ }+ return undefined;+ }++ private _findTabSessionByChildSessionId(childSessionId: string): TabSession | undefined {+ for (const session of this._tabSessions.values()) {+ if (session.childSessions.has(childSessionId))+ return session;+ }+ return undefined;+ }+}diff --git a/packages/playwright-core/src/tools/mcp/protocol.ts b/packages/playwright-core/src/tools/mcp/protocol.tsindex 7b0cb26166..c62f5a78c7 100644--- a/packages/playwright-core/src/tools/mcp/protocol.ts+++ b/packages/playwright-core/src/tools/mcp/protocol.ts@@ -16,11 +16,87 @@// Whenever the commands/events change, the version must be updated. The latest// extension version should be compatible with the old MCP clients.-export const VERSION = 1;+export const VERSION = 2;-export type ExtensionCommand = {+// Structural mirrors of @types/chrome shapes used over the wire. The extension+// imports the real chrome.* types and they are structurally compatible.+export type Debuggee = { tabId?: number; extensionId?: string; targetId?: string };+export type DebuggerSession = Debuggee & { sessionId?: string };+export type TabCreateProperties = {+ active?: boolean;+ index?: number;+ openerTabId?: number;+ pinned?: boolean;+ url?: string;+ windowId?: number;+};+export type Tab = {+ id?: number;+ index: number;+ windowId: number;+ openerTabId?: number;+ url?: string;+ title?: string;+ active: boolean;+ pinned: boolean;+};+export type TabRemoveInfo = { windowId: number; isWindowClosing: boolean };++// Protocol v2: command params/results mirror chrome.* positional arguments,+// so the extension can spread them straight into chrome.<api>.<method>(...).+export type ExtensionCommandV2 = {+ // chrome.debugger.attach(target, requiredVersion)+ 'chrome.debugger.attach': {+ params: [target: Debuggee, requiredVersion: string];+ result: void;+ };+ // chrome.debugger.detach(target)+ 'chrome.debugger.detach': {+ params: [target: Debuggee];+ result: void;+ };+ // chrome.debugger.sendCommand(target, method, commandParams?)+ 'chrome.debugger.sendCommand': {+ params: [target: DebuggerSession, method: string, commandParams?: object];+ result: any;+ };+ // chrome.tabs.create(createProperties)+ 'chrome.tabs.create': {+ params: [createProperties: TabCreateProperties];+ result: Tab;+ };+ // Playwright-specific: ask the user to pick a tab via the connect UI.+ 'extension.selectTab': {+ params: [];+ result: { tabId: number };+ };+};++// Protocol v2 events mirror chrome.<api>.<event>.addListener callback signatures.+export type ExtensionEventsV2 = {+ // chrome.debugger.onEvent: (source, method, params?) => void+ 'chrome.debugger.onEvent': {+ params: [source: DebuggerSession, method: string, eventParams?: object];+ };+ // chrome.debugger.onDetach: (source, reason) => void+ 'chrome.debugger.onDetach': {+ params: [source: Debuggee, reason: string];+ };+ // chrome.tabs.onCreated: (tab) => void+ 'chrome.tabs.onCreated': {+ params: [tab: Tab];+ };+ // chrome.tabs.onRemoved: (tabId, removeInfo) => void+ 'chrome.tabs.onRemoved': {+ params: [tabId: number, removeInfo: TabRemoveInfo];+ };+};++// Protocol v1: legacy single-tab interface.+export type ExtensionCommandV1 = {'attachToTab': {params: {};+ result: { targetInfo: any };};'forwardCDPCommand': {params: {@@ -28,10 +104,11 @@ export type ExtensionCommand = {sessionId?: stringparams?: any,};+ result: any;};};-export type ExtensionEvents = {+export type ExtensionEventsV1 = {'forwardCDPEvent': {params: {method: string,@@ -40,3 +117,7 @@ export type ExtensionEvents = {};};};++// Combined types for the relay which supports both protocol versions.+export type ExtensionCommand = ExtensionCommandV1 & ExtensionCommandV2;+export type ExtensionEvents = ExtensionEventsV1 & ExtensionEventsV2;