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: expose npx playwright run-mpc-server (#37316)
Pavel Feldmanf8f3e07efb4e
diff --git a/packages/playwright/src/mcp/program.ts b/packages/playwright/src/mcp/program.tsindex bc01c31806..aa9904e16b 100644--- a/packages/playwright/src/mcp/program.ts+++ b/packages/playwright/src/mcp/program.ts@@ -14,7 +14,7 @@* limitations under the License.*/-import { program, ProgramOption } from 'playwright-core/lib/utilsBundle';+import { ProgramOption } from 'playwright-core/lib/utilsBundle';import * as mcpServer from './sdk/server';import { commaSeparatedList, dotenvFileLoader, headerParser, resolveCLIConfig, semicolonSeparatedList } from './browser/config';import { Context } from './browser/context';@@ -23,98 +23,96 @@ import { ProxyBackend } from './sdk/proxyBackend';import { BrowserServerBackend } from './browser/browserServerBackend';import { ExtensionContextFactory } from './extension/extensionContextFactory';+import type { Command } from 'playwright-core/lib/utilsBundle';import type { MCPProvider } from './sdk/proxyBackend';-const packageJSON = require('../../package.json');+export function decorateCommand(command: Command, version: string) {+ command.option('--allowed-origins <origins>', 'semicolon-separated list of origins to allow the browser to request. Default is to allow all.', semicolonSeparatedList)+ .option('--blocked-origins <origins>', 'semicolon-separated list of origins to block the browser from requesting. Blocklist is evaluated before allowlist. If used without the allowlist, requests not matching the blocklist are still allowed.', semicolonSeparatedList)+ .option('--block-service-workers', 'block service workers')+ .option('--browser <browser>', 'browser or chrome channel to use, possible values: chrome, firefox, webkit, msedge.')+ .option('--caps <caps>', 'comma-separated list of additional capabilities to enable, possible values: vision, pdf.', commaSeparatedList)+ .option('--cdp-endpoint <endpoint>', 'CDP endpoint to connect to.')+ .option('--cdp-header <headers...>', 'CDP headers to send with the connect request, multiple can be specified.', headerParser)+ .option('--config <path>', 'path to the configuration file.')+ .option('--device <device>', 'device to emulate, for example: "iPhone 15"')+ .option('--executable-path <path>', 'path to the browser executable.')+ .option('--extension', 'Connect to a running browser instance (Edge/Chrome only). Requires the "Playwright MCP Bridge" browser extension to be installed.')+ .option('--headless', 'run browser in headless mode, headed by default')+ .option('--host <host>', 'host to bind server to. Default is localhost. Use 0.0.0.0 to bind to all interfaces.')+ .option('--ignore-https-errors', 'ignore https errors')+ .option('--isolated', 'keep the browser profile in memory, do not save it to disk.')+ .option('--image-responses <mode>', 'whether to send image responses to the client. Can be "allow" or "omit", Defaults to "allow".')+ .option('--no-sandbox', 'disable the sandbox for all process types that are normally sandboxed.')+ .option('--output-dir <path>', 'path to the directory for output files.')+ .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('--save-session', 'Whether to save the Playwright MCP session into the output directory.')+ .option('--save-trace', 'Whether to save the Playwright Trace of the session into the output directory.')+ .option('--secrets <path>', 'path to a file containing secrets in the dotenv format', dotenvFileLoader)+ .option('--storage-state <path>', 'path to the storage state file for isolated sessions.')+ .option('--user-agent <ua string>', 'specify user agent string')+ .option('--user-data-dir <path>', 'path to the user data directory. If not specified, a temporary directory will be created.')+ .option('--viewport-size <size>', 'specify browser viewport size in pixels, for example "1280, 720"')+ .addOption(new ProgramOption('--connect-tool', 'Allow to switch between different browser connection methods.').hideHelp())+ .addOption(new ProgramOption('--vision', 'Legacy option, use --caps=vision instead').hideHelp())+ .action(async options => {+ setupExitWatchdog();-program- .version('Version ' + packageJSON.version)- .name('Playwright MCP')- .option('--allowed-origins <origins>', 'semicolon-separated list of origins to allow the browser to request. Default is to allow all.', semicolonSeparatedList)- .option('--blocked-origins <origins>', 'semicolon-separated list of origins to block the browser from requesting. Blocklist is evaluated before allowlist. If used without the allowlist, requests not matching the blocklist are still allowed.', semicolonSeparatedList)- .option('--block-service-workers', 'block service workers')- .option('--browser <browser>', 'browser or chrome channel to use, possible values: chrome, firefox, webkit, msedge.')- .option('--caps <caps>', 'comma-separated list of additional capabilities to enable, possible values: vision, pdf.', commaSeparatedList)- .option('--cdp-endpoint <endpoint>', 'CDP endpoint to connect to.')- .option('--cdp-header <headers...>', 'CDP headers to send with the connect request, multiple can be specified.', headerParser)- .option('--config <path>', 'path to the configuration file.')- .option('--device <device>', 'device to emulate, for example: "iPhone 15"')- .option('--executable-path <path>', 'path to the browser executable.')- .option('--extension', 'Connect to a running browser instance (Edge/Chrome only). Requires the "Playwright MCP Bridge" browser extension to be installed.')- .option('--headless', 'run browser in headless mode, headed by default')- .option('--host <host>', 'host to bind server to. Default is localhost. Use 0.0.0.0 to bind to all interfaces.')- .option('--ignore-https-errors', 'ignore https errors')- .option('--isolated', 'keep the browser profile in memory, do not save it to disk.')- .option('--image-responses <mode>', 'whether to send image responses to the client. Can be "allow" or "omit", Defaults to "allow".')- .option('--no-sandbox', 'disable the sandbox for all process types that are normally sandboxed.')- .option('--output-dir <path>', 'path to the directory for output files.')- .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('--save-session', 'Whether to save the Playwright MCP session into the output directory.')- .option('--save-trace', 'Whether to save the Playwright Trace of the session into the output directory.')- .option('--secrets <path>', 'path to a file containing secrets in the dotenv format', dotenvFileLoader)- .option('--storage-state <path>', 'path to the storage state file for isolated sessions.')- .option('--user-agent <ua string>', 'specify user agent string')- .option('--user-data-dir <path>', 'path to the user data directory. If not specified, a temporary directory will be created.')- .option('--viewport-size <size>', 'specify browser viewport size in pixels, for example "1280, 720"')- .addOption(new ProgramOption('--connect-tool', 'Allow to switch between different browser connection methods.').hideHelp())- .addOption(new ProgramOption('--vision', 'Legacy option, use --caps=vision instead').hideHelp())- .action(async options => {- setupExitWatchdog();+ if (options.vision) {+ // eslint-disable-next-line no-console+ console.error('The --vision option is deprecated, use --caps=vision instead');+ options.caps = 'vision';+ }- if (options.vision) {- // eslint-disable-next-line no-console- console.error('The --vision option is deprecated, use --caps=vision instead');- options.caps = 'vision';- }+ const config = await resolveCLIConfig(options);+ const browserContextFactory = contextFactory(config);+ const extensionContextFactory = new ExtensionContextFactory(config.browser.launchOptions.channel || 'chrome', config.browser.userDataDir, config.browser.launchOptions.executablePath);- const config = await resolveCLIConfig(options);- const browserContextFactory = contextFactory(config);- const extensionContextFactory = new ExtensionContextFactory(config.browser.launchOptions.channel || 'chrome', config.browser.userDataDir, config.browser.launchOptions.executablePath);+ if (options.extension) {+ const serverBackendFactory: mcpServer.ServerBackendFactory = {+ name: 'Playwright w/ extension',+ nameInConfig: 'playwright-extension',+ version,+ create: () => new BrowserServerBackend(config, extensionContextFactory)+ };+ await mcpServer.start(serverBackendFactory, config.server);+ return;+ }- if (options.extension) {- const serverBackendFactory: mcpServer.ServerBackendFactory = {- name: 'Playwright w/ extension',- nameInConfig: 'playwright-extension',- version: packageJSON.version,- create: () => new BrowserServerBackend(config, extensionContextFactory)- };- await mcpServer.start(serverBackendFactory, config.server);- return;- }+ if (options.connectTool) {+ const providers: MCPProvider[] = [+ {+ name: 'default',+ description: 'Starts standalone browser',+ connect: () => mcpServer.wrapInProcess(new BrowserServerBackend(config, browserContextFactory)),+ },+ {+ name: 'extension',+ description: 'Connect to a browser using the Playwright MCP extension',+ connect: () => mcpServer.wrapInProcess(new BrowserServerBackend(config, extensionContextFactory)),+ },+ ];+ const factory: mcpServer.ServerBackendFactory = {+ name: 'Playwright w/ switch',+ nameInConfig: 'playwright-switch',+ version,+ create: () => new ProxyBackend(providers),+ };+ await mcpServer.start(factory, config.server);+ return;+ }- if (options.connectTool) {- const providers: MCPProvider[] = [- {- name: 'default',- description: 'Starts standalone browser',- connect: () => mcpServer.wrapInProcess(new BrowserServerBackend(config, browserContextFactory)),- },- {- name: 'extension',- description: 'Connect to a browser using the Playwright MCP extension',- connect: () => mcpServer.wrapInProcess(new BrowserServerBackend(config, extensionContextFactory)),- },- ];const factory: mcpServer.ServerBackendFactory = {- name: 'Playwright w/ switch',- nameInConfig: 'playwright-switch',- version: packageJSON.version,- create: () => new ProxyBackend(providers),+ name: 'Playwright',+ nameInConfig: 'playwright',+ version,+ create: () => new BrowserServerBackend(config, browserContextFactory)};await mcpServer.start(factory, config.server);- return;- }-- const factory: mcpServer.ServerBackendFactory = {- name: 'Playwright',- nameInConfig: 'playwright',- version: packageJSON.version,- create: () => new BrowserServerBackend(config, browserContextFactory)- };- await mcpServer.start(factory, config.server);- });+ });+}function setupExitWatchdog() {let isExiting = false;@@ -133,5 +131,3 @@ function setupExitWatchdog() {process.on('SIGINT', handleExit);process.on('SIGTERM', handleExit);}--void program.parseAsync(process.argv);diff --git a/packages/playwright/src/program.ts b/packages/playwright/src/program.tsindex 70731b8cb4..62d02f04d8 100644--- a/packages/playwright/src/program.ts+++ b/packages/playwright/src/program.ts@@ -35,12 +35,15 @@ import { runAllTestsWithConfig, TestRunner } from './runner/testRunner';import { createErrorCollectingReporter } from './runner/reporters';import { ServerBackendFactory, runMainBackend } from './mcp/sdk/exports';import { TestServerBackend } from './mcp/test/testBackend';+import { decorateCommand } from './mcp/program';import type { ConfigCLIOverrides } from './common/ipc';import type { TraceMode } from '../types/test';import type { ReporterDescription } from '../types/test';import type { Command } from 'playwright-core/lib/utilsBundle';+const packageJSON = require('../package.json');+function addTestCommand(program: Command) {const command = program.command('test [test-filter...]');command.description('run tests with Playwright Test');@@ -142,8 +145,14 @@ Examples:$ npx playwright merge-reports playwright-report`);}-function addMCPServerCommand(program: Command) {+function addBrowserMCPServerCommand(program: Command) {const command = program.command('run-mcp-server', { hidden: true });+ command.description('Interact with the browser over MCP');+ decorateCommand(command, packageJSON.version);+}++function addTestMCPServerCommand(program: Command) {+ const command = program.command('run-test-mcp-server', { hidden: true });command.description('Interact with the test runner over MCP');command.option('-c, --config <file>', `Configuration file, or a test directory with optional "playwright.config.{m,c}?{js,ts}"`);command.option('--host <host>', 'host to bind server to. Default is localhost. Use 0.0.0.0 to bind to all interfaces.');@@ -153,7 +162,7 @@ function addMCPServerCommand(program: Command) {const backendFactory: ServerBackendFactory = {name: 'Playwright Test Runner',nameInConfig: 'playwright-test-runner',- version: '0.0.0',+ version: packageJSON.version,create: () => new TestServerBackend(resolvedLocation, { muteConsole: options.port === undefined }),};const mdbUrl = await runMainBackend(backendFactory, { port: options.port === undefined ? undefined : +options.port });@@ -390,6 +399,7 @@ addTestCommand(program);addShowReportCommand(program);addMergeReportsCommand(program);addClearCacheCommand(program);-addMCPServerCommand(program);+addBrowserMCPServerCommand(program);+addTestMCPServerCommand(program);addDevServerCommand(program);addTestServerCommand(program);diff --git a/tests/mcp/cdp.spec.ts b/tests/mcp/cdp.spec.tsindex 5ff0930bba..fe209b7404 100644--- a/tests/mcp/cdp.spec.ts+++ b/tests/mcp/cdp.spec.ts@@ -84,7 +84,7 @@ test('should throw connection error and allow re-connecting', async ({ cdpServertest('does not support --device', async () => {const result = spawnSync('node', [- programPath, '--device=Pixel 5', '--cdp-endpoint=http://localhost:1234',+ ...programPath, '--device=Pixel 5', '--cdp-endpoint=http://localhost:1234',]);expect(result.error).toBeUndefined();expect(result.status).toBe(1);diff --git a/tests/mcp/click.spec.ts b/tests/mcp/click.spec.tsindex f7de50e3e7..6f6a06dbd0 100644--- a/tests/mcp/click.spec.ts+++ b/tests/mcp/click.spec.ts@@ -115,17 +115,19 @@ test('browser_click (modifiers)', async ({ client, server, mcpBrowser }) => {arguments: { url: server.PREFIX },});- expect(await client.callTool({- name: 'browser_click',- arguments: {- element: 'Submit button',- ref: 'e2',- modifiers: ['Control'],- },- })).toHaveResponse({- code: `await page.getByRole('button', { name: 'Submit' }).click({ modifiers: ['Control'] });`,- pageState: expect.stringContaining(`- generic [ref=e3]: ctrlKey:true metaKey:false shiftKey:false altKey:false`),- });+ if (process.platform !== 'darwin') {+ expect(await client.callTool({+ name: 'browser_click',+ arguments: {+ element: 'Submit button',+ ref: 'e2',+ modifiers: ['Control'],+ },+ })).toHaveResponse({+ code: `await page.getByRole('button', { name: 'Submit' }).click({ modifiers: ['Control'] });`,+ pageState: expect.stringContaining(`- generic [ref=e3]: ctrlKey:true metaKey:false shiftKey:false altKey:false`),+ });+ }expect(await client.callTool({name: 'browser_click',diff --git a/tests/mcp/fixtures.ts b/tests/mcp/fixtures.tsindex 7fb39c6807..47dc2e7e7c 100644--- a/tests/mcp/fixtures.ts+++ b/tests/mcp/fixtures.ts@@ -187,7 +187,7 @@ async function createTransport(args: string[], mcpMode: TestOptions['mcpMode'],const transport = new StdioClientTransport({command: 'node',- args: [programPath, ...args],+ args: [...programPath, ...args],cwd: path.dirname(test.info().config.configFile!),stderr: 'pipe',env: {@@ -277,4 +277,4 @@ function parseSections(text: string): Map<string, string> {return sections;}-export const programPath = path.join(__dirname, '../../packages/playwright/lib/mcp/program.js');+export const programPath = [path.join(__dirname, '../../packages/playwright/cli.js'), 'run-mcp-server'];diff --git a/tests/mcp/http.spec.ts b/tests/mcp/http.spec.tsindex 2289a2bb2d..69cc63d41c 100644--- a/tests/mcp/http.spec.ts+++ b/tests/mcp/http.spec.ts@@ -32,7 +32,7 @@ const test = baseTest.extend<{ serverEndpoint: (options?: { args?: string[], noPthrow new Error('Process already running');cp = spawn('node', [- programPath,+ ...programPath,...(options?.noPort ? [] : ['--port=0']),'--user-data-dir=' + userDataDir,...(mcpHeadless ? ['--headless'] : []),diff --git a/tests/mcp/sse.spec.ts b/tests/mcp/sse.spec.tsindex 42bdc4c228..5d8d706c0d 100644--- a/tests/mcp/sse.spec.ts+++ b/tests/mcp/sse.spec.ts@@ -32,7 +32,7 @@ const test = baseTest.extend<{ serverEndpoint: (options?: { args?: string[], noPthrow new Error('Process already running');cp = spawn('node', [- programPath,+ ...programPath,...(options?.noPort ? [] : ['--port=0']),'--user-data-dir=' + userDataDir,...(mcpHeadless ? ['--headless'] : []),