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): introduce init-page (#38167)

Pavel Feldmanefd7b6106c8b
diff --git a/packages/playwright/src/mcp/browser/DEPS.list b/packages/playwright/src/mcp/browser/DEPS.list
index 7c9ee17346..557a6fc5d5 100644
--- a/packages/playwright/src/mcp/browser/DEPS.list
+++ b/packages/playwright/src/mcp/browser/DEPS.list
@@ -3,4 +3,5 @@
../sdk/
../log.ts
../package.ts
+../../transform/transform.ts
../../util.ts
diff --git a/packages/playwright/src/mcp/browser/config.ts b/packages/playwright/src/mcp/browser/config.ts
index 0dec6a1166..551c2b7748 100644
--- a/packages/playwright/src/mcp/browser/config.ts
+++ b/packages/playwright/src/mcp/browser/config.ts
@@ -46,6 +46,7 @@ export type CLIOptions = {
host?: string;
ignoreHttpsErrors?: boolean;
initScript?: string[];
+ initPage?: string[];
isolated?: boolean;
imageResponses?: 'allow' | 'omit';
sandbox?: boolean;
@@ -218,6 +219,7 @@ export function configFromCLIOptions(cliOptions: CLIOptions): Config {
contextOptions,
cdpEndpoint: cliOptions.cdpEndpoint,
cdpHeaders: cliOptions.cdpHeader,
+ initPage: cliOptions.initPage,
initScript: cliOptions.initScript,
},
server: {
@@ -264,6 +266,9 @@ function configFromEnv(): Config {
options.headless = envToBoolean(process.env.PLAYWRIGHT_MCP_HEADLESS);
options.host = envToString(process.env.PLAYWRIGHT_MCP_HOST);
options.ignoreHttpsErrors = envToBoolean(process.env.PLAYWRIGHT_MCP_IGNORE_HTTPS_ERRORS);
+ const initPage = envToString(process.env.PLAYWRIGHT_MCP_INIT_PAGE);
+ if (initPage)
+ options.initPage = [initPage];
const initScript = envToString(process.env.PLAYWRIGHT_MCP_INIT_SCRIPT);
if (initScript)
options.initScript = [initScript];
diff --git a/packages/playwright/src/mcp/browser/context.ts b/packages/playwright/src/mcp/browser/context.ts
index 657194f8e9..f3d9208d03 100644
--- a/packages/playwright/src/mcp/browser/context.ts
+++ b/packages/playwright/src/mcp/browser/context.ts
@@ -90,6 +90,7 @@ export class Context {
const { browserContext } = await this._ensureBrowserContext();
const page = await browserContext.newPage();
this._currentTab = this._tabs.find(t => t.page === page)!;
+ await this._currentTab.initializedPromise;
return this._currentTab;
}
diff --git a/packages/playwright/src/mcp/browser/tab.ts b/packages/playwright/src/mcp/browser/tab.ts
index a27c9c9175..b99fd7d9ce 100644
--- a/packages/playwright/src/mcp/browser/tab.ts
+++ b/packages/playwright/src/mcp/browser/tab.ts
@@ -23,6 +23,7 @@ import { logUnhandledError } from '../log';
import { ModalState } from './tools/tool';
import { handleDialog } from './tools/dialogs';
import { uploadFile } from './tools/files';
+import { requireOrImport } from '../../transform/transform';
import type { Context } from './context';
import type { Page } from '../../../../playwright-core/src/client/page';
@@ -56,7 +57,7 @@ export class Tab extends EventEmitter<TabEventsInterface> {
private _onPageClose: (tab: Tab) => void;
private _modalStates: ModalState[] = [];
private _downloads: { download: playwright.Download, finished: boolean, outputFile: string }[] = [];
- private _initializedPromise: Promise<void>;
+ readonly initializedPromise: Promise<void>;
private _needsFullSnapshot = false;
constructor(context: Context, page: playwright.Page, onPageClose: (tab: Tab) => void) {
@@ -83,7 +84,7 @@ export class Tab extends EventEmitter<TabEventsInterface> {
page.setDefaultNavigationTimeout(this.context.config.timeouts.navigation);
page.setDefaultTimeout(this.context.config.timeouts.action);
(page as any)[tabSymbol] = this;
- this._initializedPromise = this._initialize();
+ this.initializedPromise = this._initialize();
}
static forPage(page: playwright.Page): Tab | undefined {
@@ -107,6 +108,14 @@ export class Tab extends EventEmitter<TabEventsInterface> {
const requests = await this.page.requests().catch(() => []);
for (const request of requests)
this._requests.add(request);
+ for (const initPage of this.context.config.browser.initPage || []) {
+ try {
+ const { default: func } = await requireOrImport(initPage);
+ await func({ page: this.page });
+ } catch (e) {
+ logUnhandledError(e);
+ }
+ }
}
modalStates(): ModalState[] {
@@ -210,12 +219,12 @@ export class Tab extends EventEmitter<TabEventsInterface> {
}
async consoleMessages(type?: 'error'): Promise<ConsoleMessage[]> {
- await this._initializedPromise;
+ await this.initializedPromise;
return this._consoleMessages.filter(message => type ? message.type === type : true);
}
async requests(): Promise<Set<playwright.Request>> {
- await this._initializedPromise;
+ await this.initializedPromise;
return this._requests;
}
diff --git a/packages/playwright/src/mcp/config.d.ts b/packages/playwright/src/mcp/config.d.ts
index 7a43731f3d..93d0bc03a6 100644
--- a/packages/playwright/src/mcp/config.d.ts
+++ b/packages/playwright/src/mcp/config.d.ts
@@ -69,6 +69,11 @@ export type Config = {
*/
remoteEndpoint?: string;
+ /**
+ * Paths to TypeScript files to add as initialization scripts for Playwright page.
+ */
+ initPage?: string[];
+
/**
* Paths to JavaScript files to add as initialization scripts.
* The scripts will be evaluated in every page before any of the page's scripts.
diff --git a/packages/playwright/src/mcp/program.ts b/packages/playwright/src/mcp/program.ts
index 99e7387720..4a8a7ecf19 100644
--- a/packages/playwright/src/mcp/program.ts
+++ b/packages/playwright/src/mcp/program.ts
@@ -50,6 +50,7 @@ export function decorateCommand(command: Command, version: string) {
.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('--init-page <path...>', 'path to TypeScript file to evaluate on Playwright page object')
.option('--init-script <path...>', 'path to JavaScript file to add as an initialization script. The script will be evaluated in every page before any of the page\'s scripts. Can be specified multiple times.')
.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".')
diff --git a/tests/mcp/init-page.spec.ts b/tests/mcp/init-page.spec.ts
new file mode 100644
index 0000000000..95013b364d
--- /dev/null
+++ b/tests/mcp/init-page.spec.ts
@@ -0,0 +1,37 @@
+/**
+ * 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 './fixtures';
+
+test('--init-page', async ({ startClient }) => {
+ const initPagePath = test.info().outputPath('aa.ts');
+ await fs.promises.writeFile(initPagePath, `
+ export default async ({ page }) => {
+ await page.setContent('<div>Hello world</div>');
+ };
+ `);
+ const { client } = await startClient({
+ args: [`--init-page=${initPagePath}`],
+ });
+ expect(await client.callTool({
+ name: 'browser_snapshot',
+ arguments: { url: 'about:blank' },
+ })).toHaveResponse({
+ pageState: expect.stringContaining('Hello world'),
+ });
+});