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): allow configuring timeouts (#37311)
Pavel Feldmanb37caaaf5c9a
diff --git a/packages/playwright/src/mcp/browser/config.ts b/packages/playwright/src/mcp/browser/config.tsindex e06543f5ff..da22d0e380 100644--- a/packages/playwright/src/mcp/browser/config.ts+++ b/packages/playwright/src/mcp/browser/config.ts@@ -48,6 +48,8 @@ export type CLIOptions = {saveTrace?: boolean;secrets?: Record<string, string>;storageState?: string;+ timeoutAction?: number;+ timeoutNavigation?: number;userAgent?: string;userDataDir?: string;viewportSize?: string;@@ -71,6 +73,10 @@ const defaultConfig: FullConfig = {},server: {},saveTrace: false,+ timeouts: {+ action: 5000,+ navigation: 60000,+ },};type BrowserUserConfig = NonNullable<Config['browser']>;@@ -84,6 +90,10 @@ export type FullConfig = Config & {network: NonNullable<Config['network']>,saveTrace: boolean;server: NonNullable<Config['server']>,+ timeouts: {+ action: number;+ navigation: number;+ },};export async function resolveConfig(config: Config): Promise<FullConfig> {@@ -196,6 +206,10 @@ export function configFromCLIOptions(cliOptions: CLIOptions): Config {secrets: cliOptions.secrets,outputDir: cliOptions.outputDir,imageResponses: cliOptions.imageResponses,+ timeouts: {+ action: cliOptions.timeoutAction,+ navigation: cliOptions.timeoutNavigation,+ },};return result;@@ -221,12 +235,14 @@ function configFromEnv(): Config {options.imageResponses = 'omit';options.sandbox = envToBoolean(process.env.PLAYWRIGHT_MCP_SANDBOX);options.outputDir = envToString(process.env.PLAYWRIGHT_MCP_OUTPUT_DIR);- options.port = envToNumber(process.env.PLAYWRIGHT_MCP_PORT);+ options.port = numberParser(process.env.PLAYWRIGHT_MCP_PORT);options.proxyBypass = envToString(process.env.PLAYWRIGHT_MCP_PROXY_BYPASS);options.proxyServer = envToString(process.env.PLAYWRIGHT_MCP_PROXY_SERVER);options.saveTrace = envToBoolean(process.env.PLAYWRIGHT_MCP_SAVE_TRACE);options.secrets = dotenvFileLoader(process.env.PLAYWRIGHT_MCP_SECRETS_FILE);options.storageState = envToString(process.env.PLAYWRIGHT_MCP_STORAGE_STATE);+ options.timeoutAction = numberParser(process.env.PLAYWRIGHT_MCP_TIMEOUT_ACTION);+ options.timeoutNavigation = numberParser(process.env.PLAYWRIGHT_MCP_TIMEOUT_NAVIGATION);options.userAgent = envToString(process.env.PLAYWRIGHT_MCP_USER_AGENT);options.userDataDir = envToString(process.env.PLAYWRIGHT_MCP_USER_DATA_DIR);options.viewportSize = envToString(process.env.PLAYWRIGHT_MCP_VIEWPORT_SIZE);@@ -292,6 +308,10 @@ function mergeConfig(base: FullConfig, overrides: Config): FullConfig {...pickDefined(base.server),...pickDefined(overrides.server),},+ timeouts: {+ ...pickDefined(base.timeouts),+ ...pickDefined(overrides.timeouts),+ },} as FullConfig;}@@ -313,6 +333,12 @@ export function dotenvFileLoader(value: string | undefined): Record<string, strireturn dotenv.parse(fs.readFileSync(value, 'utf8'));}+export function numberParser(value: string | undefined): number | undefined {+ if (!value)+ return undefined;+ return +value;+}+export function headerParser(arg: string | undefined, previous?: Record<string, string>): Record<string, string> {if (!arg)return previous || {};@@ -322,12 +348,6 @@ export function headerParser(arg: string | undefined, previous?: Record<string,return result;}-function envToNumber(value: string | undefined): number | undefined {- if (!value)- return undefined;- return +value;-}-function envToBoolean(value: string | undefined): boolean | undefined {if (value === 'true' || value === '1')return true;diff --git a/packages/playwright/src/mcp/browser/tab.ts b/packages/playwright/src/mcp/browser/tab.tsindex 8904604e8f..a7b92bb01e 100644--- a/packages/playwright/src/mcp/browser/tab.ts+++ b/packages/playwright/src/mcp/browser/tab.ts@@ -77,8 +77,8 @@ export class Tab extends EventEmitter<TabEventsInterface> {page.on('download', download => {void this._downloadStarted(download);});- page.setDefaultNavigationTimeout(60000);- page.setDefaultTimeout(5000);+ page.setDefaultNavigationTimeout(this.context.config.timeouts.navigation);+ page.setDefaultTimeout(this.context.config.timeouts.action);(page as any)[tabSymbol] = this;}diff --git a/packages/playwright/src/mcp/config.d.ts b/packages/playwright/src/mcp/config.d.tsindex 49fe40226e..09a999d88c 100644--- a/packages/playwright/src/mcp/config.d.ts+++ b/packages/playwright/src/mcp/config.d.ts@@ -124,6 +124,18 @@ export type Config = {blockedOrigins?: string[];};+ timeouts?: {+ /*+ * Configures default action timeout: https://playwright.dev/docs/api/class-page#page-set-default-timeout. Defaults to 5000ms.+ */+ action?: number;++ /*+ * Configures default navigation timeout: https://playwright.dev/docs/api/class-page#page-set-default-navigation-timeout. Defaults to 60000ms.+ */+ navigation?: number;+ };+/*** Whether to send image responses to the client. Can be "allow", "omit", or "auto". Defaults to "auto", which sends images if the client can display them.*/diff --git a/packages/playwright/src/mcp/program.ts b/packages/playwright/src/mcp/program.tsindex aa9904e16b..25dcb12c40 100644--- a/packages/playwright/src/mcp/program.ts+++ b/packages/playwright/src/mcp/program.ts@@ -16,7 +16,7 @@import { ProgramOption } from 'playwright-core/lib/utilsBundle';import * as mcpServer from './sdk/server';-import { commaSeparatedList, dotenvFileLoader, headerParser, resolveCLIConfig, semicolonSeparatedList } from './browser/config';+import { commaSeparatedList, dotenvFileLoader, headerParser, numberParser, resolveCLIConfig, semicolonSeparatedList } from './browser/config';import { Context } from './browser/context';import { contextFactory } from './browser/browserContextFactory';import { ProxyBackend } from './sdk/proxyBackend';@@ -52,6 +52,8 @@ export function decorateCommand(command: Command, version: string) {.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('--timeout-action <timeout>', 'specify action timeout in milliseconds, defaults to 5000ms', numberParser)+ .option('--timeout-navigation <timeout>', 'specify navigation timeout in milliseconds, defaults to 60000ms', numberParser).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"')diff --git a/tests/mcp/timeouts.spec.ts b/tests/mcp/timeouts.spec.tsnew file mode 100644index 0000000000..57c4598121--- /dev/null+++ b/tests/mcp/timeouts.spec.ts@@ -0,0 +1,97 @@+/**+ * 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('action timeout (default)', async ({ client, server }) => {+ server.setContent('/', `+ <!DOCTYPE html>+ <html>+ <input readonly></input>+ </html>+ `, 'text/html');++ await client.callTool({+ name: 'browser_navigate',+ arguments: {+ url: server.PREFIX,+ },+ });++ expect(await client.callTool({+ name: 'browser_type',+ arguments: {+ element: 'textbox',+ ref: 'e2',+ text: 'Hi!',+ submit: true,+ },+ })).toHaveResponse({+ result: expect.stringContaining(`Timeout 5000ms exceeded.`),+ });+});++test('action timeout (custom)', async ({ startClient, server }) => {+ const { client } = await startClient({ args: [`--timeout-action=1234`] });+ server.setContent('/', `+ <!DOCTYPE html>+ <html>+ <input readonly></input>+ </html>+ `, 'text/html');++ await client.callTool({+ name: 'browser_navigate',+ arguments: {+ url: server.PREFIX,+ },+ });++ expect(await client.callTool({+ name: 'browser_type',+ arguments: {+ element: 'textbox',+ ref: 'e2',+ text: 'Hi!',+ submit: true,+ },+ })).toHaveResponse({+ result: expect.stringContaining(`Timeout 1234ms exceeded.`),+ });+});++test('navigation timeout', async ({ startClient, server }) => {+ const { client } = await startClient({ args: [`--timeout-navigation=1234`] });+ server.setRoute('/slow', async () => {+ await new Promise(f => setTimeout(f, 1500));+ return new Response('OK');+ });+ server.setContent('/', `+ <!DOCTYPE html>+ <html>+ <input readonly></input>+ </html>+ `, 'text/html');++ expect(await client.callTool({+ name: 'browser_navigate',+ arguments: {+ url: server.PREFIX + '/slow',+ },+ })).toHaveResponse({+ result: expect.stringContaining(`Timeout 1234ms exceeded.`),+ });+});