Skip to content

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

feat(mcp): support test-id-attribute option (#37760)

Pavel Feldman47f3da37a272
diff --git a/packages/playwright/src/mcp/browser/config.ts b/packages/playwright/src/mcp/browser/config.ts
index 5ffe2f8d3c..d79cd236da 100644
--- a/packages/playwright/src/mcp/browser/config.ts
+++ b/packages/playwright/src/mcp/browser/config.ts
@@ -59,6 +59,7 @@ export type CLIOptions = {
secrets?: Record<string, string>;
sharedBrowserContext?: boolean;
storageState?: string;
+ testIdAttribute?: string;
timeoutAction?: number;
timeoutNavigation?: number;
userAgent?: string;
@@ -236,6 +237,7 @@ export function configFromCLIOptions(cliOptions: CLIOptions): Config {
sharedBrowserContext: cliOptions.sharedBrowserContext,
outputDir: cliOptions.outputDir,
imageResponses: cliOptions.imageResponses,
+ testIdAttribute: cliOptions.testIdAttribute,
timeouts: {
action: cliOptions.timeoutAction,
navigation: cliOptions.timeoutNavigation,
@@ -277,6 +279,7 @@ function configFromEnv(): Config {
options.saveVideo = resolutionParser('--save-video', process.env.PLAYWRIGHT_MCP_SAVE_VIDEO);
options.secrets = dotenvFileLoader(process.env.PLAYWRIGHT_MCP_SECRETS_FILE);
options.storageState = envToString(process.env.PLAYWRIGHT_MCP_STORAGE_STATE);
+ options.testIdAttribute = envToString(process.env.PLAYWRIGHT_MCP_TEST_ID_ATTRIBUTE);
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);
diff --git a/packages/playwright/src/mcp/browser/context.ts b/packages/playwright/src/mcp/browser/context.ts
index 015a0da514..657194f8e9 100644
--- a/packages/playwright/src/mcp/browser/context.ts
+++ b/packages/playwright/src/mcp/browser/context.ts
@@ -18,6 +18,7 @@ import fs from 'fs';
import path from 'path';
import { debug } from 'playwright-core/lib/utilsBundle';
+import { selectors } from 'playwright-core';
import { logUnhandledError } from '../log';
import { Tab } from './tab';
@@ -233,6 +234,9 @@ export class Context {
if (this._closeBrowserContextPromise)
throw new Error('Another browser context is being closed.');
// TODO: move to the browser context factory to make it based on isolation mode.
+
+ if (this.config.testIdAttribute)
+ selectors.setTestIdAttribute(this.config.testIdAttribute);
const result = await this._browserContextFactory.createContext(this._clientInfo, this._abortController.signal, this._runningToolName);
const { browserContext } = result;
await this._setupRequestInterception(browserContext);
diff --git a/packages/playwright/src/mcp/config.d.ts b/packages/playwright/src/mcp/config.d.ts
index dd373b9883..7a43731f3d 100644
--- a/packages/playwright/src/mcp/config.d.ts
+++ b/packages/playwright/src/mcp/config.d.ts
@@ -149,6 +149,11 @@ export type Config = {
blockedOrigins?: string[];
};
+ /**
+ * Specify the attribute to use for test ids, defaults to "data-testid".
+ */
+ testIdAttribute?: string;
+
timeouts?: {
/*
* Configures default action timeout: https://playwright.dev/docs/api/class-page#page-set-default-timeout. Defaults to 5000ms.
diff --git a/packages/playwright/src/mcp/program.ts b/packages/playwright/src/mcp/program.ts
index 7f7c2cf06a..8f979cc3d3 100644
--- a/packages/playwright/src/mcp/program.ts
+++ b/packages/playwright/src/mcp/program.ts
@@ -58,6 +58,7 @@ export function decorateCommand(command: Command, version: string) {
.option('--secrets <path>', 'path to a file containing secrets in the dotenv format', dotenvFileLoader)
.option('--shared-browser-context', 'reuse the same browser context between all connected HTTP clients.')
.option('--storage-state <path>', 'path to the storage state file for isolated sessions.')
+ .option('--test-id-attribute <attribute>', 'specify the attribute to use for test ids, defaults to "data-testid"')
.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')
diff --git a/tests/mcp/click.spec.ts b/tests/mcp/click.spec.ts
index 6f6a06dbd0..0335ccf8c9 100644
--- a/tests/mcp/click.spec.ts
+++ b/tests/mcp/click.spec.ts
@@ -153,3 +153,30 @@ test('browser_click (modifiers)', async ({ client, server, mcpBrowser }) => {
pageState: expect.stringContaining(`- generic [ref=e3]: ctrlKey:false metaKey:false shiftKey:true altKey:true`),
});
});
+
+test('browser_click (test id attribute)', async ({ startClient, server, mcpBrowser }) => {
+ server.setContent('/', `
+ <title>Title</title>
+ <button data-tid="submit">Submit</button>
+ `, 'text/html');
+
+ const { client } = await startClient({
+ args: [
+ '--test-id-attribute', 'data-tid',
+ ],
+ });
+ await client.callTool({
+ name: 'browser_navigate',
+ arguments: { url: server.PREFIX },
+ });
+
+ expect(await client.callTool({
+ name: 'browser_click',
+ arguments: {
+ element: 'Submit button',
+ ref: 'e2',
+ },
+ })).toHaveResponse({
+ code: `await page.getByTestId('submit').click();`,
+ });
+});
diff --git a/tests/mcp/generator.spec.ts b/tests/mcp/generator.spec.ts
index 8f7ffec24e..d0feace8e7 100644
--- a/tests/mcp/generator.spec.ts
+++ b/tests/mcp/generator.spec.ts
@@ -276,3 +276,44 @@ test('generator_write_test', async ({ startClient }, testInfo) => {
const code = fs.readFileSync(testInfo.outputPath('a.test.ts'), 'utf8');
expect(code).toBe(`// Test content`);
});
+
+test('should respect custom test id', async ({ startClient }) => {
+ await writeFiles({
+ 'playwright.config.ts': `
+ import { defineConfig } from '@playwright/test';
+ export default defineConfig({
+ use: {
+ testIdAttribute: 'data-tid'
+ }
+ });
+ `,
+ 'a.test.ts': `
+ import { test, expect } from '@playwright/test';
+ test.beforeEach(async ({ page }) => {
+ await page.setContent('<button data-tid="submit">Submit</button>');
+ });
+ test('template', async ({ page }) => {
+ });
+ `,
+ });
+
+ const { client } = await startClient();
+ await client.callTool({
+ name: 'generator_setup_page',
+ arguments: {
+ plan: 'Test plan',
+ seedFile: 'a.test.ts',
+ },
+ });
+
+ expect(await client.callTool({
+ name: 'browser_click',
+ arguments: {
+ element: 'Submit button',
+ ref: 'e2',
+ intent: 'Click submit button',
+ },
+ })).toHaveResponse({
+ code: `await page.getByTestId('submit').click();`,
+ });
+});