Skip to content

Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.

chore(mcp): extract serving config (#39523)

Pavel Feldman23d98999a974
diff --git a/packages/playwright-core/src/cli/daemon/commands.ts b/packages/playwright-core/src/cli/daemon/commands.ts
index 9a289fa35d..2065cc1d93 100644
--- a/packages/playwright-core/src/cli/daemon/commands.ts
+++ b/packages/playwright-core/src/cli/daemon/commands.ts
@@ -875,7 +875,7 @@ const installBrowser = declareCommand({
['only-shell']: z.boolean().optional().describe('Only install headless shell when installing Chromium'),
['no-shell']: z.boolean().optional().describe('Do not install Chromium headless shell'),
}),
- toolName: 'browser_install',
+ toolName: '',
toolParams: () => ({}),
});
diff --git a/packages/playwright-core/src/cli/daemon/daemon.ts b/packages/playwright-core/src/cli/daemon/daemon.ts
index 89a25504a6..d77a1d5940 100644
--- a/packages/playwright-core/src/cli/daemon/daemon.ts
+++ b/packages/playwright-core/src/cli/daemon/daemon.ts
@@ -30,9 +30,8 @@ import { SocketConnection } from '../client/socketConnection';
import { commands } from './commands';
import { parseCommand } from './command';
+import type * as playwright from '../../..';
import type * as mcp from '../../mcp/exports';
-import type { FullConfig } from '../../mcp/browser/config';
-import type { BrowserContextFactory } from '../../mcp/browser/browserContextFactory';
import type { SessionConfig } from '../client/registry';
const daemonDebug = debug('pw:daemon');
@@ -48,9 +47,9 @@ async function socketExists(socketPath: string): Promise<boolean> {
}
export async function startMcpDaemonServer(
- mcpConfig: FullConfig,
+ config: mcp.ContextConfig,
sessionConfig: SessionConfig,
- contextFactory: BrowserContextFactory,
+ browserContext: playwright.BrowserContext,
noShutdown?: boolean,
): Promise<() => Promise<void>> {
const { socketPath } = sessionConfig;
@@ -65,18 +64,6 @@ export async function startMcpDaemonServer(
}
}
- const cwd = url.pathToFileURL(process.cwd()).href;
- const clientInfo = {
- name: 'playwright-cli',
- version: sessionConfig.version,
- roots: [{
- uri: cwd,
- name: 'cwd'
- }],
- timestamp: Date.now(),
- };
-
- const browserContext = mcpConfig.browser.isolated ? await contextFactory.createContext(clientInfo) : (await contextFactory.contexts(clientInfo))[0];
if (!noShutdown) {
browserContext.on('close', () => {
daemonDebug('browser closed, shutting down daemon');
@@ -84,8 +71,16 @@ export async function startMcpDaemonServer(
});
}
- const backend = new BrowserServerBackend(mcpConfig, browserContext, browserTools);
- await backend.initialize(clientInfo);
+ const backend = new BrowserServerBackend(config, browserContext, browserTools);
+ await backend.initialize({
+ name: 'playwright-cli',
+ version: sessionConfig.version,
+ roots: [{
+ uri: url.pathToFileURL(process.cwd()).href,
+ name: 'cwd',
+ }],
+ timestamp: Date.now(),
+ });
await fs.mkdir(path.dirname(socketPath), { recursive: true });
diff --git a/packages/playwright-core/src/cli/daemon/program.ts b/packages/playwright-core/src/cli/daemon/program.ts
index 0b261b1cdb..e79269b1d9 100644
--- a/packages/playwright-core/src/cli/daemon/program.ts
+++ b/packages/playwright-core/src/cli/daemon/program.ts
@@ -17,6 +17,7 @@
/* eslint-disable no-console */
import fs from 'fs';
+import url from 'url';
import { startMcpDaemonServer } from './daemon';
import { setupExitWatchdog } from '../../mcp/browser/watchdog';
@@ -38,13 +39,26 @@ export function decorateCLICommand(command: Command, version: string) {
setupExitWatchdog();
const sessionConfig = await fs.promises.readFile(options.daemonSession, 'utf-8').then(data => JSON.parse(data) as SessionConfig);
+
+ const cwd = url.pathToFileURL(process.cwd()).href;
+ const clientInfo = {
+ name: 'playwright-cli',
+ version: sessionConfig.version,
+ roots: [{
+ uri: cwd,
+ name: 'cwd'
+ }],
+ timestamp: Date.now(),
+ };
+
const mcpConfig = await resolveCLIConfig(sessionConfig);
- const browserContextFactory = contextFactory(mcpConfig);
const extensionContextFactory = new ExtensionContextFactory(mcpConfig.browser.launchOptions.channel || 'chrome', mcpConfig.browser.userDataDir, mcpConfig.browser.launchOptions.executablePath);
-
+ const browserContextFactory = contextFactory(mcpConfig);
const cf = mcpConfig.extension ? extensionContextFactory : browserContextFactory;
+
try {
- await startMcpDaemonServer(mcpConfig, sessionConfig, cf);
+ const browserContext = mcpConfig.browser.isolated ? await cf.createContext(clientInfo) : (await cf.contexts(clientInfo))[0];
+ await startMcpDaemonServer(mcpConfig, sessionConfig, browserContext);
console.log(`### Config`);
console.log('```json');
console.log(JSON.stringify(mcpConfig, null, 2));
diff --git a/packages/playwright-core/src/mcp/browser/browserContextFactory.ts b/packages/playwright-core/src/mcp/browser/browserContextFactory.ts
index c3c9bc6ea8..4f4c620562 100644
--- a/packages/playwright-core/src/mcp/browser/browserContextFactory.ts
+++ b/packages/playwright-core/src/mcp/browser/browserContextFactory.ts
@@ -23,7 +23,7 @@ import * as playwright from '../../..';
import { registryDirectory } from '../../server/registry/index';
import { startTraceViewerServer } from '../../server';
import { testDebug } from '../log';
-import { outputDir, outputFile } from './config';
+import { outputDir, outputFile } from './context';
import { firstRootPath } from '../sdk/server';
import type { FullConfig } from './config';
@@ -255,13 +255,15 @@ function createHash(data: string): string {
}
async function computeTracesDir(config: FullConfig, clientInfo: ClientInfo): Promise<string | undefined> {
- return path.resolve(outputDir(config, clientInfo), 'traces');
+ const cwd = firstRootPath(clientInfo);
+ return path.resolve(outputDir({ config, cwd }), 'traces');
}
async function browserContextOptionsFromConfig(config: FullConfig, clientInfo: ClientInfo): Promise<playwright.BrowserContextOptions> {
const result = { ...config.browser.contextOptions };
if (config.saveVideo) {
- const dir = await outputFile(config, clientInfo, `videos`, { origin: 'code' });
+ const cwd = firstRootPath(clientInfo);
+ const dir = await outputFile({ config, cwd }, `videos`, { origin: 'code' });
result.recordVideo = {
dir,
size: config.saveVideo,
@@ -310,5 +312,5 @@ function throwBrowserIsNotInstalledError(config: FullConfig): never {
if (config.skillMode)
throw new Error(`Browser "${channel}" is not installed. Run \`playwright-cli install-browser ${channel}\` to install`);
else
- throw new Error(`Browser "${channel}" is not installed. Either install it (likely) or change the config.`);
+ throw new Error(`Browser "${channel}" is not installed. Run \`npx @playwright/mcp install-browser ${channel}\` to install`);
}
diff --git a/packages/playwright-core/src/mcp/browser/browserServerBackend.ts b/packages/playwright-core/src/mcp/browser/browserServerBackend.ts
index a8b158eab4..5b005d5a0c 100644
--- a/packages/playwright-core/src/mcp/browser/browserServerBackend.ts
+++ b/packages/playwright-core/src/mcp/browser/browserServerBackend.ts
@@ -14,37 +14,39 @@
* limitations under the License.
*/
-import { FullConfig } from './config';
import { Context } from './context';
import { Response } from './response';
import { SessionLog } from './sessionLog';
import { toMcpTool } from '../sdk/tool';
import { logUnhandledError } from '../log';
+import { firstRootPath } from '../sdk/server';
+import type { ContextConfig } from './context';
import type * as playwright from '../../..';
import type { Tool } from './tools/tool';
import type * as mcpServer from '../sdk/server';
-import type { ServerBackend } from '../sdk/server';
+import type { ClientInfo, ServerBackend } from '../sdk/server';
export class BrowserServerBackend implements ServerBackend {
private _tools: Tool[];
private _context: Context | undefined;
private _sessionLog: SessionLog | undefined;
- private _config: FullConfig;
+ private _config: ContextConfig;
readonly browserContext: playwright.BrowserContext;
- constructor(config: FullConfig, browserContext: playwright.BrowserContext, tools: Tool[]) {
+ constructor(config: ContextConfig, browserContext: playwright.BrowserContext, tools: Tool[]) {
this._config = config;
this._tools = tools;
this.browserContext = browserContext;
}
- async initialize(clientInfo: mcpServer.ClientInfo): Promise<void> {
- this._sessionLog = this._config.saveSession ? await SessionLog.create(this._config, clientInfo) : undefined;
+ async initialize(clientInfo: ClientInfo): Promise<void> {
+ const cwd = firstRootPath(clientInfo);
+ this._sessionLog = this._config.saveSession ? await SessionLog.create(this._config, cwd) : undefined;
this._context = new Context(this.browserContext, {
config: this._config,
sessionLog: this._sessionLog,
- clientInfo,
+ cwd,
});
}
diff --git a/packages/playwright-core/src/mcp/browser/config.ts b/packages/playwright-core/src/mcp/browser/config.ts
index 6c3792e0c4..639a5f8b2a 100644
--- a/packages/playwright-core/src/mcp/browser/config.ts
+++ b/packages/playwright-core/src/mcp/browser/config.ts
@@ -16,18 +16,15 @@
import fs from 'fs';
import os from 'os';
-import path from 'path';
import { registry } from '../../server';
import { devices } from '../../..';
-import { dotenv, debug } from '../../utilsBundle';
+import { dotenv } from '../../utilsBundle';
import { configFromIniFile } from './configIni';
-import { firstRootPath } from '../sdk/server';
import type * as playwright from '../../..';
import type { Config, ToolCapability } from '../config';
-import type { ClientInfo } from '../sdk/server';
async function fileExistsAsync(resolved: string) {
try { return (await fs.promises.stat(resolved)).isFile(); } catch { return false; }
@@ -93,19 +90,7 @@ export const defaultConfig: FullConfig = {
},
isolated: false,
},
- console: {
- level: 'info',
- },
- network: {
- allowedOrigins: undefined,
- blockedOrigins: undefined,
- },
server: {},
- saveTrace: false,
- snapshot: {
- mode: 'incremental',
- output: 'stdout',
- },
timeouts: {
action: 5000,
navigation: 60000,
@@ -122,21 +107,7 @@ export type FullConfig = Config & {
contextOptions: NonNullable<BrowserUserConfig['contextOptions']>;
isolated: boolean;
},
- console: {
- level: 'error' | 'warning' | 'info' | 'debug';
- },
- network: NonNullable<Config['network']>,
- saveTrace: boolean;
server: NonNullable<Config['server']>,
- snapshot: {
- mode: 'incremental' | 'full' | 'none';
- output: 'stdout' | 'file';
- },
- timeouts: {
- action: number;
- navigation: number;
- expect: number;
- },
skillMode?: boolean;
configFile?: string;
};
@@ -378,45 +349,6 @@ export async function loadConfig(configFile: string | undefined): Promise<Config
}
}
-// These methods should return resolved absolute file names.
-
-export function workspaceDir(clientInfo: ClientInfo): string {
- return path.resolve(firstRootPath(clientInfo));
-}
-
-export async function workspaceFile(config: FullConfig, clientInfo: ClientInfo, fileName: string, perCallWorkspaceDir?: string): Promise<string> {
- const workspace = perCallWorkspaceDir ?? workspaceDir(clientInfo);
- const resolvedName = path.resolve(workspace, fileName);
- await checkFile(config, clientInfo, resolvedName, { origin: 'code' });
- return resolvedName;
-}
-
-export function outputDir(config: FullConfig, clientInfo: ClientInfo): string {
- if (config.outputDir)
- return path.resolve(config.outputDir);
- return path.resolve(firstRootPath(clientInfo), config.skillMode ? '.playwright-cli' : '.playwright-mcp');
-}
-
-export async function outputFile(config: FullConfig, clientInfo: ClientInfo, fileName: string, options: { origin: 'code' | 'llm' }): Promise<string> {
- const resolvedFile = path.resolve(outputDir(config, clientInfo), fileName);
- await checkFile(config, clientInfo, resolvedFile, options);
- await fs.promises.mkdir(path.dirname(resolvedFile), { recursive: true });
- debug('pw:mcp:file')(resolvedFile);
- return resolvedFile;
-}
-
-async function checkFile(config: FullConfig, clientInfo: ClientInfo, resolvedFilename: string, options: { origin: 'code' | 'llm' }) {
- // Trust code.
- if (options.origin === 'code')
- return;
-
- // Trust llm to use valid characters in file names.
- const output = outputDir(config, clientInfo);
- const workspace = workspaceDir(clientInfo);
- if (!resolvedFilename.startsWith(output) && !resolvedFilename.startsWith(workspace))
- throw new Error(`Resolved file path ${resolvedFilename} is outside of the output directory ${output} and workspace directory ${workspace}. Use relative file names to stay within the output directory.`);
-}
-
function pickDefined<T extends object>(obj: T | undefined): Partial<T> {
return Object.fromEntries(
Object.entries(obj ?? {}).filter(([_, v]) => v !== undefined)
diff --git a/packages/playwright-core/src/mcp/browser/context.ts b/packages/playwright-core/src/mcp/browser/context.ts
index 8a768c9a5d..8f0a40755c 100644
--- a/packages/playwright-core/src/mcp/browser/context.ts
+++ b/packages/playwright-core/src/mcp/browser/context.ts
@@ -14,6 +14,7 @@
* limitations under the License.
*/
+import fs from 'fs';
import path from 'path';
import { disposeAll } from '../../client/disposable';
@@ -23,23 +24,42 @@ import { escapeWithQuotes } from '../../utils/isomorphic/stringUtils';
import { selectors } from '../../..';
import { Tab } from './tab';
-import { outputFile, workspaceFile } from './config';
-import { allRootPaths, firstRootPath } from '../sdk/server';
import type * as playwright from '../../..';
-import type { FullConfig } from './config';
import type { SessionLog } from './sessionLog';
import type { Tracing } from '../../client/tracing';
import type { Disposable } from '../../client/disposable';
import type { BrowserContext } from '../../client/browserContext';
-import type { ClientInfo } from '../sdk/server';
+import type { Config } from '../config.d.ts';
const testDebug = debug('pw:mcp:test');
+export type ContextConfig = Pick<Config,
+ 'allowUnrestrictedFileAccess' |
+ 'capabilities' |
+ 'codegen' |
+ 'console' |
+ 'imageResponses' |
+ 'network' |
+ 'outputDir' |
+ 'outputMode' |
+ 'saveSession' |
+ 'saveTrace' |
+ 'secrets' |
+ 'snapshot' |
+ 'testIdAttribute' |
+ 'timeouts'> & {
+ browser?: {
+ initScript?: string[];
+ initPage?: string[];
+ };
+ skillMode?: boolean;
+ };
+
type ContextOptions = {
- config: FullConfig;
- sessionLog: SessionLog | undefined;
- clientInfo: ClientInfo;
+ config: ContextConfig;
+ sessionLog?: SessionLog;
+ cwd: string;
};
export type RouteEntry = {
@@ -62,14 +82,13 @@ export type FilenameTemplate = {
type VideoParams = NonNullable<Parameters<playwright.Video['start']>[0]>;
export class Context {
- readonly config: FullConfig;
+ readonly config: ContextConfig;
readonly sessionLog: SessionLog | undefined;
readonly options: ContextOptions;
private _rawBrowserContext: playwright.BrowserContext;
private _browserContextPromise: Promise<playwright.BrowserContext> | undefined;
private _tabs: Tab[] = [];
private _currentTab: Tab | undefined;
- private _clientInfo: ClientInfo;
private _routes: RouteEntry[] = [];
private _video: {
allVideos: Set<playwright.Video>;
@@ -84,7 +103,6 @@ export class Context {
this.sessionLog = options.sessionLog;
this.options = options;
this._rawBrowserContext = browserContext;
- this._clientInfo = options.clientInfo;
testDebug('create context');
}
@@ -144,12 +162,12 @@ export class Context {
}
async workspaceFile(fileName: string, perCallWorkspaceDir: string | undefined): Promise<string> {
- return await workspaceFile(this.config, this._clientInfo, fileName, perCallWorkspaceDir);
+ return await workspaceFile(this.options, fileName, perCallWorkspaceDir);
}
async outputFile(template: FilenameTemplate, options: { origin: 'code' | 'llm' }): Promise<string> {
const baseName = template.suggestedFilename || `${template.prefix}-${(template.date ?? new Date()).toISOString().replace(/[:.]/g, '-')}${template.ext ? '.' + template.ext : ''}`;
- return await outputFile(this.config, this._clientInfo, baseName, options);
+ return await outputFile(this.options, baseName, options);
}
async startVideoRecording(params: VideoParams) {
@@ -261,7 +279,7 @@ export class Context {
const browserContext = this._rawBrowserContext;
if (!this.config.allowUnrestrictedFileAccess) {
(browserContext as any)._setAllowedProtocols(['http:', 'https:', 'about:', 'data:']);
- (browserContext as any)._setAllowedDirectories(allRootPaths(this._clientInfo));
+ (browserContext as any)._setAllowedDirectories([this.options.cwd]);
}
await this._setupRequestInterception(browserContext);
@@ -278,9 +296,8 @@ export class Context {
},
});
}
- const rootPath = firstRootPath(this._clientInfo);
- for (const initScript of this.config.browser.initScript || [])
- this._disposables.push(await browserContext.addInitScript({ path: path.resolve(rootPath, initScript) }));
+ for (const initScript of this.config.browser?.initScript || [])
+ this._disposables.push(await browserContext.addInitScript({ path: path.resolve(this.options.cwd, initScript) }));
for (const page of browserContext.pages())
this._onPageCreated(page);
@@ -315,3 +332,36 @@ function originOrHostGlob(originOrHost: string) {
// Support for legacy host-only mode.
return `*://${originOrHost}/**`;
}
+
+export async function workspaceFile(options: ContextOptions, fileName: string, perCallWorkspaceDir?: string): Promise<string> {
+ const workspace = perCallWorkspaceDir ?? options.cwd;
+ const resolvedName = path.resolve(workspace, fileName);
+ await checkFile(options, resolvedName, { origin: 'code' });
+ return resolvedName;
+}
+
+export function outputDir(options: ContextOptions): string {
+ if (options.config.outputDir)
+ return path.resolve(options.config.outputDir);
+ return path.resolve(options.cwd, options.config.skillMode ? '.playwright-cli' : '.playwright-mcp');
+}
+
+export async function outputFile(options: ContextOptions, fileName: string, flags: { origin: 'code' | 'llm' }): Promise<string> {
+ const resolvedFile = path.resolve(outputDir(options), fileName);
+ await checkFile(options, resolvedFile, flags);
+ await fs.promises.mkdir(path.dirname(resolvedFile), { recursive: true });
+ debug('pw:mcp:file')(resolvedFile);
+ return resolvedFile;
+}
+
+async function checkFile(options: ContextOptions, resolvedFilename: string, flags: { origin: 'code' | 'llm' }) {
+ // Trust code.
+ if (flags.origin === 'code')
+ return;
+
+ // Trust llm to use valid characters in file names.
+ const output = outputDir(options);
+ const workspace = options.cwd;
+ if (!resolvedFilename.startsWith(output) && !resolvedFilename.startsWith(workspace))
+ throw new Error(`Resolved file path ${resolvedFilename} is outside of the output directory ${output} and workspace directory ${workspace}. Use relative file names to stay within the output directory.`);
+}
diff --git a/packages/playwright-core/src/mcp/browser/response.ts b/packages/playwright-core/src/mcp/browser/response.ts
index aef1215924..e15f6ba8f2 100644
--- a/packages/playwright-core/src/mcp/browser/response.ts
+++ b/packages/playwright-core/src/mcp/browser/response.ts
@@ -20,7 +20,6 @@ import path from 'path';
import { debug } from '../../utilsBundle';
import { renderModalStates, shouldIncludeMessage } from './tab';
import { scaleImageToFitMessage } from './tools/screenshot';
-import { firstRootPath } from '../sdk/server';
import type { TabHeader } from './tab';
import type { CallToolResult, ImageContent, TextContent } from '@modelcontextprotocol/sdk/types.js';
@@ -59,7 +58,7 @@ export class Response {
this._context = context;
this.toolName = toolName;
this.toolArgs = toolArgs;
- this._clientWorkspace = relativeTo ?? firstRootPath(context.options.clientInfo);
+ this._clientWorkspace = relativeTo ?? context.options.cwd;
}
private _computRelativeTo(fileName: string): string {
@@ -120,7 +119,7 @@ export class Response {
}
setIncludeSnapshot() {
- this._includeSnapshot = this._context.config.snapshot.mode;
+ this._includeSnapshot = this._context.config.snapshot?.mode || 'incremental';
}
setIncludeFullSnapshot(includeSnapshotFileName?: string) {
@@ -222,8 +221,8 @@ export class Response {
text.push(`- New console entries: ${tabSnapshot.consoleLink}`);
if (tabSnapshot?.events.filter(event => event.type !== 'request').length) {
for (const event of tabSnapshot.events) {
- if (event.type === 'console' && this._context.config.outputMode !== 'file' && this._context.config.snapshot.mode !== 'none') {
- if (shouldIncludeMessage(this._context.config.console.level, event.message.type))
+ if (event.type === 'console' && this._context.config.outputMode !== 'file' && this._context.config.snapshot?.mode !== 'none') {
+ if (shouldIncludeMessage(this._context.config.console?.level, event.message.type))
text.push(`- ${trimMiddle(event.message.toString(), 100)}`);
} else if (event.type === 'download-start') {
text.push(`- Downloading file ${event.download.download.suggestedFilename()} ...`);
diff --git a/packages/playwright-core/src/mcp/browser/sessionLog.ts b/packages/playwright-core/src/mcp/browser/sessionLog.ts
index 8edae8fd02..8e213031d2 100644
--- a/packages/playwright-core/src/mcp/browser/sessionLog.ts
+++ b/packages/playwright-core/src/mcp/browser/sessionLog.ts
@@ -17,11 +17,10 @@
import fs from 'fs';
import path from 'path';
-import { outputFile } from './config';
+import { outputFile } from './context';
import { parseResponse } from './response';
-import type { FullConfig } from './config';
-import type * as mcpServer from '../sdk/server';
+import type { ContextConfig } from './context';
export class SessionLog {
private _folder: string;
@@ -33,8 +32,8 @@ export class SessionLog {
this._file = path.join(this._folder, 'session.md');
}
- static async create(config: FullConfig, clientInfo: mcpServer.ClientInfo): Promise<SessionLog> {
- const sessionFolder = await outputFile(config, clientInfo, `session-${Date.now()}`, { origin: 'code' });
+ static async create(config: ContextConfig, cwd: string): Promise<SessionLog> {
+ const sessionFolder = await outputFile({ config, cwd }, `session-${Date.now()}`, { origin: 'code' });
await fs.promises.mkdir(sessionFolder, { recursive: true });
// eslint-disable-next-line no-console
console.error(`Session: ${sessionFolder}`);
diff --git a/packages/playwright-core/src/mcp/browser/tab.ts b/packages/playwright-core/src/mcp/browser/tab.ts
index 427e159d6c..4a8cc2b72d 100644
--- a/packages/playwright-core/src/mcp/browser/tab.ts
+++ b/packages/playwright-core/src/mcp/browser/tab.ts
@@ -30,11 +30,10 @@ import { handleDialog } from './tools/dialogs';
import { uploadFile } from './tools/files';
import { disposeAll } from '../../client/disposable';
-import type { Context } from './context';
+import type { Disposable } from '../../client/disposable';
+import type { Context, ContextConfig } from './context';
import type { Page } from '../../client/page';
import type { Locator } from '../../client/locator';
-import type { FullConfig } from './config';
-import type { Disposable } from '../../client/disposable';
const TabEvents = {
modalState: 'modalState'
@@ -105,9 +104,9 @@ export class Tab extends EventEmitter<TabEventsInterface> {
private _recentEventEntries: EventEntry[] = [];
private _consoleLog: LogFile;
private _disposables: Disposable[];
- readonly actionTimeoutOptions: { timeout: number; };
- readonly navigationTimeoutOptions: { timeout: number; };
- readonly expectTimeoutOptions: { timeout: number; };
+ readonly actionTimeoutOptions: { timeout?: number; };
+ readonly navigationTimeoutOptions: { timeout?: number; };
+ readonly expectTimeoutOptions: { timeout?: number; };
constructor(context: Context, page: playwright.Page, onPageClose: (tab: Tab) => void) {
super();
@@ -139,9 +138,9 @@ export class Tab extends EventEmitter<TabEventsInterface> {
const wallTime = Date.now();
this._consoleLog = new LogFile(this.context, wallTime, 'console', 'Console');
this._initializedPromise = this._initialize();
- this.actionTimeoutOptions = { timeout: context.config.timeouts.action };
- this.navigationTimeoutOptions = { timeout: context.config.timeouts.navigation };
- this.expectTimeoutOptions = { timeout: context.config.timeouts.expect };
+ this.actionTimeoutOptions = { timeout: context.config.timeouts?.action };
+ this.navigationTimeoutOptions = { timeout: context.config.timeouts?.navigation };
+ this.expectTimeoutOptions = { timeout: context.config.timeouts?.expect };
}
async dispose() {
@@ -170,7 +169,7 @@ export class Tab extends EventEmitter<TabEventsInterface> {
const requests = await this.page.requests().catch(() => []);
for (const request of requests.filter(r => r.existingResponse() || r.failure()))
this._requests.push(request);
- for (const initPage of this.context.config.browser.initPage || []) {
+ for (const initPage of this.context.config.browser?.initPage || []) {
try {
const { default: func } = await import(url.pathToFileURL(initPage).href);
await func({ page: this.page });
@@ -496,7 +495,7 @@ function pageErrorToConsoleMessage(errorOrValue: Error | any): ConsoleMessage {
};
}
-export function renderModalStates(config: FullConfig, modalStates: ModalState[]): string[] {
+export function renderModalStates(config: ContextConfig, modalStates: ModalState[]): string[] {
const result: string[] = [];
if (modalStates.length === 0)
result.push('- There is no modal state present');
@@ -509,9 +508,9 @@ type ConsoleMessageType = ReturnType<playwright.ConsoleMessage['type']>;
type ConsoleMessageLevel = 'error' | 'warning' | 'info' | 'debug';
const consoleMessageLevels: ConsoleMessageLevel[] = ['error', 'warning', 'info', 'debug'];
-export function shouldIncludeMessage(thresholdLevel: ConsoleMessageLevel, type: ConsoleMessageType): boolean {
+export function shouldIncludeMessage(thresholdLevel: ConsoleMessageLevel | undefined, type: ConsoleMessageType): boolean {
const messageLevel = consoleLevelForMessageType(type);
- return consoleMessageLevels.indexOf(messageLevel) <= consoleMessageLevels.indexOf(thresholdLevel);
+ return consoleMessageLevels.indexOf(messageLevel) <= consoleMessageLevels.indexOf(thresholdLevel || 'info');
}
function consoleLevelForMessageType(type: ConsoleMessageType): ConsoleMessageLevel {
diff --git a/packages/playwright-core/src/mcp/browser/tools.ts b/packages/playwright-core/src/mcp/browser/tools.ts
index cae0bf3267..eea07dc6b5 100644
--- a/packages/playwright-core/src/mcp/browser/tools.ts
+++ b/packages/playwright-core/src/mcp/browser/tools.ts
@@ -23,7 +23,6 @@ import dialogs from './tools/dialogs';
import evaluate from './tools/evaluate';
import files from './tools/files';
import form from './tools/form';
-import install from './tools/install';
import keyboard from './tools/keyboard';
import mouse from './tools/mouse';
import navigate from './tools/navigate';
@@ -42,7 +41,7 @@ import wait from './tools/wait';
import webstorage from './tools/webstorage';
import type { Tool } from './tools/tool';
-import type { FullConfig } from './config';
+import type { ContextConfig } from './context';
export const browserTools: Tool<any>[] = [
...common,
@@ -54,7 +53,6 @@ export const browserTools: Tool<any>[] = [
...evaluate,
...files,
...form,
- ...install,
...keyboard,
...mouse,
...navigate,
@@ -73,6 +71,6 @@ export const browserTools: Tool<any>[] = [
...webstorage,
];
-export function filteredTools(config: FullConfig) {
+export function filteredTools(config: Pick<ContextConfig, 'capabilities'>) {
return browserTools.filter(tool => tool.capability.startsWith('core') || config.capabilities?.includes(tool.capability)).filter(tool => !tool.skillOnly);
}
diff --git a/packages/playwright-core/src/mcp/browser/tools/install.ts b/packages/playwright-core/src/mcp/browser/tools/install.ts
deleted file mode 100644
index 00a66635ef..0000000000
--- a/packages/playwright-core/src/mcp/browser/tools/install.ts
+++ /dev/null
@@ -1,60 +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 { fork } from 'child_process';
-import path from 'path';
-
-import { z } from '../../../mcpBundle';
-import { defineTool } from './tool';
-import { renderTabsMarkdown } from '../response';
-
-const install = defineTool({
- capability: 'core-install',
- schema: {
- name: 'browser_install',
- title: 'Install the browser specified in the config',
- description: 'Install the browser specified in the config. Call this if you get an error about the browser not being installed.',
- inputSchema: z.object({}),
- type: 'action',
- },
-
- handle: async (context, params, response) => {
- const channel = context.config.browser?.launchOptions?.channel ?? context.config.browser?.browserName ?? 'chrome';
- const cliPath = path.join(require.resolve('playwright-core/package.json'), '../cli.js');
- const child = fork(cliPath, ['install', channel], {
- stdio: 'pipe',
- });
- const output: string[] = [];
- child.stdout?.on('data', data => output.push(data.toString()));
- child.stderr?.on('data', data => output.push(data.toString()));
- await new Promise<void>((resolve, reject) => {
- child.on('close', code => {
- if (code === 0)
- resolve();
- else
- reject(new Error(`Failed to install browser: ${output.join('')}`));
- });
- });
- response.addTextResult(`Browser ${channel} installed.`);
- const tabHeaders = await Promise.all(context.tabs().map(tab => tab.headerSnapshot()));
- const result = renderTabsMarkdown(tabHeaders);
- response.addTextResult(result.join('\n'));
- },
-});
-
-export default [
- install,
-];
diff --git a/packages/playwright-core/src/mcp/exports.ts b/packages/playwright-core/src/mcp/exports.ts
index 1e9b6bb529..16b84f6c6e 100644
--- a/packages/playwright-core/src/mcp/exports.ts
+++ b/packages/playwright-core/src/mcp/exports.ts
@@ -17,19 +17,14 @@
// SDK
export * from './sdk/server';
export * from './sdk/tool';
-export * from './sdk/http';
export { browserTools } from './browser/tools';
export { BrowserServerBackend } from './browser/browserServerBackend';
-export { contextFactory, identityBrowserContextFactory } from './browser/browserContextFactory';
-export { defaultConfig, resolveConfig } from './browser/config';
export { parseResponse } from './browser/response';
export { Tab } from './browser/tab';
export { setupExitWatchdog } from './browser/watchdog';
-export type { BrowserContextFactory } from './browser/browserContextFactory';
-export type { FullConfig } from './browser/config';
export type { Tool as BrowserTool } from './browser/tools/tool';
export { logUnhandledError } from './log';
-export type { Config, ToolCapability } from './config';
+export type { ContextConfig } from './browser/context';
export { startMcpDaemonServer } from '../cli/daemon/daemon';
export { sessionConfigFromArgs } from '../cli/client/program';
export { createClientInfo } from '../cli/client/registry';
diff --git a/packages/playwright-core/src/mcp/program.ts b/packages/playwright-core/src/mcp/program.ts
index d043d50d00..1ec90c6653 100644
--- a/packages/playwright-core/src/mcp/program.ts
+++ b/packages/playwright-core/src/mcp/program.ts
@@ -140,3 +140,19 @@ export function decorateMCPCommand(command: Command, version: string) {
await mcpServer.start(factory, config.server);
});
}
+
+export function decorateMCPInstallBrowserCommand(command: Command, version: string) {
+ command
+ .description('ensure browsers necessary for this version of Playwright are installed')
+ .option('--with-deps', 'install system dependencies for browsers')
+ .option('--dry-run', 'do not execute installation, only print information')
+ .option('--list', 'prints list of browsers from all playwright installations')
+ .option('--force', 'force reinstall of already installed browsers')
+ .option('--only-shell', 'only install headless shell when installing chromium')
+ .option('--no-shell', 'do not install chromium headless shell')
+ .action(async options => {
+ const { program } = require('../program');
+ const argv = process.argv.map(arg => arg === 'install-browser' ? 'install' : arg);
+ program.parse(argv);
+ });
+}
diff --git a/packages/playwright/src/mcp/test/browserBackend.ts b/packages/playwright/src/mcp/test/browserBackend.ts
index 7368f493e4..12b698f274 100644
--- a/packages/playwright/src/mcp/test/browserBackend.ts
+++ b/packages/playwright/src/mcp/test/browserBackend.ts
@@ -18,7 +18,7 @@ import path from 'path';
import fs from 'fs';
import { createGuid } from 'playwright-core/lib/utils';
import * as mcp from 'playwright-core/lib/mcp/exports';
-import { defaultConfig, BrowserServerBackend, Tab, identityBrowserContextFactory, startMcpDaemonServer, sessionConfigFromArgs, createClientInfo } from 'playwright-core/lib/mcp/exports';
+import { BrowserServerBackend } from 'playwright-core/lib/mcp/exports';
import { stripAnsiEscapes } from '../../util';
@@ -46,7 +46,7 @@ export function createCustomMessageHandler(testInfo: TestInfoImpl, context: play
if (data.initialize) {
if (backend)
throw new Error('MCP backend is already initialized');
- const config: mcp.FullConfig = { ...defaultConfig, capabilities: ['testing'] };
+ const config: mcp.ContextConfig = { capabilities: ['testing'] };
const tools = mcp.filteredTools(config);
backend = new BrowserServerBackend(config, context, tools);
await backend.initialize(data.initialize.clientInfo);
@@ -97,7 +97,7 @@ async function generatePausedMessage(testInfo: TestInfoImpl, context: playwright
`- Page Title: ${await page.title()}`.trim()
);
// Only print console errors when pausing on error, not when everything works as expected.
- let console = testInfo.errors.length ? await Tab.collectConsoleMessages(page) : [];
+ let console = testInfo.errors.length ? await mcp.Tab.collectConsoleMessages(page) : [];
console = console.filter(msg => msg.type === 'error');
if (console.length) {
lines.push('- Console Messages:');
@@ -125,17 +125,17 @@ export async function runDaemonForContext(testInfo: TestInfoImpl, context: playw
const outputDir = path.join(testInfo.artifactsDir(), '.playwright-mcp');
const sessionName = `test-worker-${createGuid().slice(0, 6)}`;
- const clientInfo = createClientInfo();
- const sessionConfig = sessionConfigFromArgs(clientInfo, sessionName, { _: [] });
+ const clientInfo = mcp.createClientInfo();
+ const sessionConfig = mcp.sessionConfigFromArgs(clientInfo, sessionName, { _: [] });
const sessionConfigFile = path.resolve(clientInfo.daemonProfilesDir, `${sessionName}.session`);
await fs.promises.mkdir(path.dirname(sessionConfigFile), { recursive: true });
await fs.promises.writeFile(sessionConfigFile, JSON.stringify(sessionConfig, null, 2));
- await startMcpDaemonServer({
- ...defaultConfig,
+
+ await mcp.startMcpDaemonServer({
outputMode: 'file',
- snapshot: { mode: 'full', output: 'file' },
+ snapshot: { mode: 'full' },
outputDir,
- }, sessionConfig, identityBrowserContextFactory(context), true /* noShutdown */);
+ }, sessionConfig, context, true /* noShutdown */);
const lines = [''];
if (testInfo.errors.length) {
diff --git a/tests/mcp/capabilities.spec.ts b/tests/mcp/capabilities.spec.ts
index b5272a0ea3..2ab5c44af6 100644
--- a/tests/mcp/capabilities.spec.ts
+++ b/tests/mcp/capabilities.spec.ts
@@ -30,7 +30,6 @@ test('test snapshot tool list', async ({ client }) => {
'browser_select_option',
'browser_type',
'browser_close',
- 'browser_install',
'browser_navigate_back',
'browser_navigate',
'browser_network_requests',
diff --git a/tests/mcp/generator.spec.ts b/tests/mcp/generator.spec.ts
index 9e593fd0ff..81bac70222 100644
--- a/tests/mcp/generator.spec.ts
+++ b/tests/mcp/generator.spec.ts
@@ -38,7 +38,6 @@ test('generator tools intent', async ({ startClient }) => {
expect(toolsWithIntent).toContain('browser_fill_form');
expect(toolsWithIntent).toContain('browser_handle_dialog');
expect(toolsWithIntent).toContain('browser_hover');
- expect(toolsWithIntent).toContain('browser_install');
expect(toolsWithIntent).toContain('browser_mouse_click_xy');
expect(toolsWithIntent).toContain('browser_mouse_drag_xy');
expect(toolsWithIntent).toContain('browser_mouse_move_xy');
diff --git a/tests/mcp/install.spec.ts b/tests/mcp/install.spec.ts
deleted file mode 100644
index feb8081225..0000000000
--- a/tests/mcp/install.spec.ts
+++ /dev/null
@@ -1,26 +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 { test, expect } from './fixtures';
-
-test('browser_install', async ({ client, mcpBrowser }) => {
- test.skip(mcpBrowser !== 'chromium', 'Test only chromium');
- expect(await client.callTool({
- name: 'browser_install',
- })).toHaveResponse({
- result: expect.stringContaining(`No open tabs`),
- });
-});