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): accept ConnectOptions object for remoteEndpoint (#40964)
Aditya Singh899c7a5e4cd1
diff --git a/packages/playwright-core/src/tools/mcp/browserFactory.ts b/packages/playwright-core/src/tools/mcp/browserFactory.tsindex ab171f1ebe..4ea7e58372 100644--- a/packages/playwright-core/src/tools/mcp/browserFactory.ts+++ b/packages/playwright-core/src/tools/mcp/browserFactory.ts@@ -115,7 +115,16 @@ async function createCDPBrowser(config: FullConfig, clientInfo: ClientInfo): Proasync function createRemoteBrowser(config: FullConfig): Promise<BrowserWithInfo> {testDebug('create browser (remote)');- const descriptor = await serverRegistry.find(config.browser.remoteEndpoint!);+ // `remoteEndpoint` may be a plain URL string or a ConnectOptions object that+ // carries additional fields such as `exposeNetwork`, `headers`, `slowMo`, and+ // `timeout`. Normalize once so the rest of the function deals with a single+ // shape.+ const remote = config.browser.remoteEndpoint!;+ const remoteOptions = typeof remote === 'string'+ ? { endpoint: remote }+ : remote;++ const descriptor = await serverRegistry.find(remoteOptions.endpoint);if (descriptor) {const browser = await connectToBrowserAcrossVersions(descriptor);return {@@ -131,13 +140,9 @@ async function createRemoteBrowser(config: FullConfig): Promise<BrowserWithInfo>};}- const endpoint = config.browser.remoteEndpoint!;const playwrightObject = playwright as Playwright;// Use connectToBrowser instead of playwright[browserName].connect because we don't have browserName.- const browser = await connectToBrowser(playwrightObject, {- endpoint,- headers: config.browser.remoteHeaders,- });+ const browser = await connectToBrowser(playwrightObject, remoteOptions);browser._connectToBrowserType(playwrightObject[browser._browserName], {}, undefined);return { browser, browserInfo: browserInfo(browser, config), canBind: false, ownership: 'attached' };}diff --git a/packages/playwright-core/src/tools/mcp/config.d.ts b/packages/playwright-core/src/tools/mcp/config.d.tsindex 18bc3bc76f..bd9835c2e2 100644--- a/packages/playwright-core/src/tools/mcp/config.d.ts+++ b/packages/playwright-core/src/tools/mcp/config.d.ts@@ -82,14 +82,13 @@ export type Config = {cdpTimeout?: number;/**- * Remote endpoint to connect to an existing Playwright server.+ * Remote endpoint to connect to an existing Playwright server. May be a+ * WebSocket URL string, or a [ConnectOptions] object that mirrors the+ * `connectOptions` shape used by the test runner. When passed as an object,+ * `exposeNetwork`, `headers`, `slowMo`, and `timeout` are forwarded to the+ * underlying connect call.*/- remoteEndpoint?: string;-- /**- * Headers to send with the remote endpoint connect request.- */- remoteHeaders?: Record<string, string>;+ remoteEndpoint?: string | playwright.ConnectOptions & { endpoint: string };/*** Paths to TypeScript files to add as initialization scripts for Playwright page.diff --git a/packages/playwright-core/src/tools/mcp/config.ts b/packages/playwright-core/src/tools/mcp/config.tsindex 3f08edac21..2583e2684d 100644--- a/packages/playwright-core/src/tools/mcp/config.ts+++ b/packages/playwright-core/src/tools/mcp/config.ts@@ -64,7 +64,6 @@ export type CLIOptions = {port?: number;proxyBypass?: string;proxyServer?: string;- remoteHeader?: Record<string, string>;saveSession?: boolean;secrets?: Record<string, string>;sharedBrowserContext?: boolean;@@ -334,7 +333,6 @@ function configFromCLIOptions(cliOptions: CLIOptions): Config & { configFile?: sinitPage: cliOptions.initPage,initScript: cliOptions.initScript,remoteEndpoint: cliOptions.endpoint,- remoteHeaders: cliOptions.remoteHeader,},extension: cliOptions.extension,server: {@@ -407,7 +405,6 @@ export function configFromEnv(env?: NodeJS.ProcessEnv): Config & { configFile?:options.port = numberParser(e.PLAYWRIGHT_MCP_PORT);options.proxyBypass = envToString(e.PLAYWRIGHT_MCP_PROXY_BYPASS);options.proxyServer = envToString(e.PLAYWRIGHT_MCP_PROXY_SERVER);- options.remoteHeader = headerParser(envToString(e.PLAYWRIGHT_MCP_REMOTE_HEADERS));options.secrets = dotenvFileLoader(e.PLAYWRIGHT_MCP_SECRETS_FILE);options.storageState = envToString(e.PLAYWRIGHT_MCP_STORAGE_STATE);options.testIdAttribute = envToString(e.PLAYWRIGHT_MCP_TEST_ID_ATTRIBUTE);diff --git a/packages/playwright-core/src/tools/mcp/program.ts b/packages/playwright-core/src/tools/mcp/program.tsindex dd3aa7fa74..f42c1b0dcc 100644--- a/packages/playwright-core/src/tools/mcp/program.ts+++ b/packages/playwright-core/src/tools/mcp/program.ts@@ -64,7 +64,6 @@ export function decorateMCPCommand(command: Command) {.option('--port <port>', 'port to listen on for SSE transport.').option('--proxy-bypass <bypass>', 'comma-separated domains to bypass proxy, for example ".com,chromium.org,.domain.com"').option('--proxy-server <proxy>', 'specify proxy server, for example "http://myproxy:3128" or "socks5://myproxy:8080"')- .option('--remote-header <headers...>', 'headers to send with the remote endpoint connect request, multiple can be specified.', headerParser).option('--sandbox', 'enable the sandbox for all process types that are normally not sandboxed.').option('--save-session', 'Whether to save the Playwright MCP session into the output directory.').option('--secrets <path>', 'path to a file containing secrets in the dotenv format', dotenvFileLoader)diff --git a/tests/mcp/cli-remote.spec.ts b/tests/mcp/cli-remote.spec.tsdeleted file mode 100644index 40fb22b236..0000000000--- a/tests/mcp/cli-remote.spec.ts+++ /dev/null@@ -1,38 +0,0 @@-/**- * 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.- */--import fs from 'fs';-import { test, expect } from './cli-fixtures';--test.skip(({ mcpBrowser }) => mcpBrowser !== 'chromium', 'Run only on the chromium project; the remote server connection is browser-agnostic.');--test('attach to run-server endpoint with remoteHeaders from config', async ({ cli, runServerEndpoint, server }, testInfo) => {- const configPath = testInfo.outputPath('config.json');- await fs.promises.writeFile(configPath, JSON.stringify({- browser: {- remoteEndpoint: runServerEndpoint,- remoteHeaders: { 'x-playwright-browser': 'chromium' },- isolated: true,- },- }, null, 2));-- const { exitCode } = await cli('attach', runServerEndpoint, '-s=remote', `--config=${configPath}`);- expect(exitCode).toBe(0);-- await cli('-s=remote', 'goto', server.HELLO_WORLD);- const { inlineSnapshot } = await cli('-s=remote', 'snapshot');- expect(inlineSnapshot).toContain('Hello, world!');-});diff --git a/tests/mcp/remote-endpoint.spec.ts b/tests/mcp/remote-endpoint.spec.tsindex 6aba3e9df2..2a19e73754 100644--- a/tests/mcp/remote-endpoint.spec.ts+++ b/tests/mcp/remote-endpoint.spec.ts@@ -18,12 +18,11 @@ import { test, expect } from './fixtures';test.skip(({ mcpBrowser }) => mcpBrowser !== 'chromium', 'Run only on the chromium project; the remote server connection is browser-agnostic.');-test('remoteHeaders selects the browser on run-server endpoint', async ({ startClient, server, runServerEndpoint }) => {+test('connect without headers fails on run-server endpoint', async ({ startClient, server, runServerEndpoint }) => {const { client } = await startClient({config: {browser: {remoteEndpoint: runServerEndpoint,- remoteHeaders: { 'x-playwright-browser': 'chromium' },isolated: true,},},@@ -31,18 +30,22 @@ test('remoteHeaders selects the browser on run-server endpoint', async ({ startCconst response = await client.callTool({name: 'browser_navigate',- arguments: { url: server.HELLO_WORLD },+ arguments: { url: server.EMPTY_PAGE },});expect(response).toHaveResponse({- page: expect.stringContaining('Page Title: Title'),+ isError: true,+ error: expect.stringContaining(`reading 'launch'`),});});-test('connect without remoteHeaders fails on run-server endpoint', async ({ startClient, server, runServerEndpoint }) => {+test('remoteEndpoint accepts ConnectOptions object with headers', async ({ startClient, server, runServerEndpoint }) => {const { client } = await startClient({config: {browser: {- remoteEndpoint: runServerEndpoint,+ remoteEndpoint: {+ endpoint: runServerEndpoint,+ headers: { 'x-playwright-browser': 'chromium' },+ },isolated: true,},},@@ -50,10 +53,9 @@ test('connect without remoteHeaders fails on run-server endpoint', async ({ starconst response = await client.callTool({name: 'browser_navigate',- arguments: { url: server.EMPTY_PAGE },+ arguments: { url: server.HELLO_WORLD },});expect(response).toHaveResponse({- isError: true,- error: expect.stringContaining(`reading 'launch'`),+ page: expect.stringContaining('Page Title: Title'),});});