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): detect and install browser (#39157)
Yury Semikhatsky467c0c0c69fc
diff --git a/packages/playwright-core/src/server/browserType.ts b/packages/playwright-core/src/server/browserType.tsindex 98a2adec30..ec377c1498 100644--- a/packages/playwright-core/src/server/browserType.ts+++ b/packages/playwright-core/src/server/browserType.ts@@ -56,7 +56,7 @@ export abstract class BrowserType extends SdkObject {}executablePath(): string {- return registry.findExecutable(this._name).executablePath(this.attribution.playwright.options.sdkLanguage) || '';+ return registry.findExecutable(this._name).executablePath() || '';}name(): string {diff --git a/packages/playwright-core/src/server/registry/index.ts b/packages/playwright-core/src/server/registry/index.tsindex 51a05463be..ab205b45d2 100644--- a/packages/playwright-core/src/server/registry/index.ts+++ b/packages/playwright-core/src/server/registry/index.ts@@ -561,7 +561,7 @@ export interface Executable {revision?: string,browserVersion?: string,executablePathOrDie(sdkLanguage: string): string;- executablePath(sdkLanguage: string): string | undefined;+ executablePath(): string | undefined;_validateHostRequirements(sdkLanguage: string): Promise<void>;wslExecutablePath?: string}@@ -962,7 +962,7 @@ export class Registry {name,browserName: 'chromium',directory: undefined,- executablePath: (sdkLanguage: string) => executablePath(sdkLanguage, false),+ executablePath: () => executablePath('', false),executablePathOrDie: (sdkLanguage: string) => executablePath(sdkLanguage, true)!,installType: install ? 'install-script' : 'none',_validateHostRequirements: () => Promise.resolve(),@@ -1001,7 +1001,7 @@ export class Registry {name,browserName: 'firefox',directory: undefined,- executablePath: (sdkLanguage: string) => executablePath(sdkLanguage, false),+ executablePath: () => executablePath('', false),executablePathOrDie: (sdkLanguage: string) => executablePath(sdkLanguage, true)!,installType: 'none',_validateHostRequirements: () => Promise.resolve(),@@ -1083,8 +1083,8 @@ export class Registry {if (!executable._install)throw new Error(`ERROR: Playwright does not support installing ${executable.name}`);- const { embedderName } = getEmbedderName();- if (!getAsBooleanFromENV('CI') && !executable._isHermeticInstallation && !options?.force && executable.executablePath(embedderName)) {+ if (!getAsBooleanFromENV('CI') && !executable._isHermeticInstallation && !options?.force && executable.executablePath()) {+ const { embedderName } = getEmbedderName();const command = buildPlaywrightCLICommand(embedderName, 'install --force ' + executable.name);// eslint-disable-next-line no-restricted-propertiesprocess.stderr.write('\n' + wrapInASCIIBox([diff --git a/packages/playwright/src/mcp/extension/cdpRelay.ts b/packages/playwright/src/mcp/extension/cdpRelay.tsindex 2d683eaedb..927fa96536 100644--- a/packages/playwright/src/mcp/extension/cdpRelay.ts+++ b/packages/playwright/src/mcp/extension/cdpRelay.ts@@ -138,7 +138,7 @@ export class CDPRelayServer {const executableInfo = registry.findExecutable(this._browserChannel);if (!executableInfo)throw new Error(`Unsupported channel: "${this._browserChannel}"`);- executablePath = executableInfo.executablePath('javascript');+ executablePath = executableInfo.executablePath();if (!executablePath)throw new Error(`"${this._browserChannel}" executable not found. Make sure it is installed at a standard location.`);}diff --git a/packages/playwright/src/mcp/program.ts b/packages/playwright/src/mcp/program.tsindex 37270e0160..ce34ad93b7 100644--- a/packages/playwright/src/mcp/program.ts+++ b/packages/playwright/src/mcp/program.ts@@ -149,7 +149,7 @@ export function decorateCommand(command: Command, version: string) {function checkFfmpeg(): boolean {try {const executable = registry.findExecutable('ffmpeg')!;- return fs.existsSync(executable.executablePath('javascript')!);+ return fs.existsSync(executable.executablePath()!);} catch (error) {return false;}diff --git a/packages/playwright/src/mcp/terminal/program.ts b/packages/playwright/src/mcp/terminal/program.tsindex 988d79f3a1..1c6799cf84 100644--- a/packages/playwright/src/mcp/terminal/program.ts+++ b/packages/playwright/src/mcp/terminal/program.ts@@ -27,6 +27,8 @@ import path from 'path';import { SocketConnection } from './socketConnection';import type { FullConfig } from '../browser/config';+import type { Config } from '../config';+type MinimistArgs = {_: string[];[key: string]: any;@@ -572,6 +574,42 @@ async function install(args: MinimistArgs) {await fs.promises.cp(skillSourceDir, skillDestDir, { recursive: true });console.log(`Skills installed to ${path.relative(cwd, skillDestDir)}`);}++ if (!args.config && !fs.existsSync(defaultConfigFile())) {+ const channel = await checkAndInstallBrowser();+ if (channel !== 'chrome')+ await createDefaultConfig(channel);+ }+}++async function createDefaultConfig(channel: string) {+ const config: Config = {+ browser: {+ browserName: 'chromium',+ launchOptions: {+ channel,+ },+ },+ };+ await fs.promises.writeFile(defaultConfigFile(), JSON.stringify(config, null, 2));+ console.log(`Created default config for ${channel} at ${path.relative(process.cwd(), defaultConfigFile())}.`);+}++async function checkAndInstallBrowser() {+ const { registry } = await import('playwright-core/lib/server/registry/index');+ const channels = ['chrome', 'msedge'];+ for (const channel of channels) {+ const executable = registry.findExecutable(channel);+ if (!executable?.executablePath())+ continue;+ console.log(`Found ${channel} browser.`);+ return channel;+ }+ const chromiumExecutable = registry.findExecutable('chromium');+ // Unlike channels, chromium executable path is always valid, even if the browser is not installed.+ if (!fs.existsSync(chromiumExecutable?.executablePath()!))+ await registry.install([chromiumExecutable]);+ return 'chromium';}function daemonSocketPath(clientInfo: ClientInfo, sessionName: string): string {@@ -582,11 +620,15 @@ function daemonSocketPath(clientInfo: ClientInfo, sessionName: string): string {return path.join(socketsDir, clientInfo.workspaceDirHash, socketName);}+function defaultConfigFile(): string {+ return path.resolve('.playwright', 'cli.config.json');+}+function sessionConfigFromArgs(clientInfo: ClientInfo, sessionName: string, args: MinimistArgs): SessionConfig {let config = args.config ? path.resolve(args.config) : undefined;try {- if (!config && fs.existsSync(path.join('.playwright', 'cli.config.json')))- config = path.resolve('.playwright', 'cli.config.json');+ if (!config && fs.existsSync(defaultConfigFile()))+ config = defaultConfigFile();} catch {}diff --git a/tests/mcp/cli-misc.spec.ts b/tests/mcp/cli-misc.spec.tsindex b780a4dbde..6bb430ef8b 100644--- a/tests/mcp/cli-misc.spec.ts+++ b/tests/mcp/cli-misc.spec.ts@@ -52,3 +52,11 @@ test('install workspace w/skills', async ({ cli }, testInfo) => {const references = await fs.promises.readdir(referencesDir);expect(references.length).toBeGreaterThan(0);});++test('install handles browser detection', async ({ cli }) => {+ const { output } = await cli('install');+ // Verify that one of the browser detection outcomes occurred+ const foundMatch = output.match(/Found ((?:chrome|msedge)[\w-]*) browser\./m);+ if (foundMatch?.[1] !== 'chrome')+ expect(output).toContain(`Created default config for ${foundMatch?.[1] ?? 'chromium'}.`);+});