Skip to content

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

fix(mcp): report invalid element targets and accept locators in any language (#43539)

Pavel Feldman27219bd2cc94
diff --git a/packages/playwright-core/src/tools/backend/tab.ts b/packages/playwright-core/src/tools/backend/tab.ts
index 27ba69e620..ac9826a9f3 100644
--- a/packages/playwright-core/src/tools/backend/tab.ts
+++ b/packages/playwright-core/src/tools/backend/tab.ts
@@ -584,10 +584,10 @@ export class Tab extends EventEmitter<TabEventsInterface> {
await this._initializedPromise;
return Promise.all(params.map(async param => {
if (!param.target.match(/^(f\d+)?e\d+$/)) {
- const selector = locatorOrSelectorAsSelector('javascript', param.target, this.context.config.testIdAttribute || 'data-testid');
- const handle = await this.page.$(selector);
+ const selector = targetAsSelector(param.target, this.context.config.testIdAttribute || 'data-testid');
+ const handle = selector ? await this.page.$(selector) : null;
if (!handle)
- throw new Error(`"${param.target}" does not match any elements.`);
+ throw new Error(targetErrorMessage(param.target, !!selector));
handle.dispose().catch(() => {});
return { locator: this.page.locator(selector), resolved: asLocator('javascript', selector), selector };
} else {
@@ -625,6 +625,26 @@ export function locatorSelector(locator: playwright.Locator): string {
return (locator as unknown as { _selector: string })._selector;
}
+// Accepts a selector or a locator in any language, e.g. `getByRole('button')` or `get_by_role("button")`.
+function targetAsSelector(target: string, testIdAttributeName: string): string {
+ for (const language of ['javascript', 'python', 'java', 'csharp'] as const) {
+ const selector = locatorOrSelectorAsSelector(language, target, testIdAttributeName);
+ if (selector)
+ return selector;
+ }
+ return '';
+}
+
+function targetErrorMessage(target: string, isSelector: boolean): string {
+ const message = isSelector ? `"${target}" does not match any elements.` : `"${target}" is not a valid target.`;
+ const ref = target.match(/\[ref=((?:f\d+)?e\d+)\]/)?.[1];
+ if (ref)
+ return `${message} To use the element with [ref=${ref}] from the page snapshot, pass "${ref}" as the target.`;
+ if (!isSelector)
+ return `${message} Use a ref from the page snapshot (e.g. "e5"), a CSS selector, or a locator (e.g. "getByRole('button', { name: 'Submit' })").`;
+ return message;
+}
+
function messageToConsoleMessage(message: playwright.ConsoleMessage): ConsoleMessage {
return {
type: message.type(),
diff --git a/tests/mcp/cli-core.spec.ts b/tests/mcp/cli-core.spec.ts
index 264458dccb..fca01b6717 100644
--- a/tests/mcp/cli-core.spec.ts
+++ b/tests/mcp/cli-core.spec.ts
@@ -285,6 +285,15 @@ test('click button with role locator', async ({ cli, server }) => {
\`\`\`js
await page.getByRole('button', { name: 'Submit' }).click();
\`\`\``);
+
+ for (const locator of [
+ 'get_by_role("button", name="Submit")',
+ 'getByRole(AriaRole.BUTTON, new Page.GetByRoleOptions().setName("Submit"))',
+ 'GetByRole(AriaRole.Button, new() { Name = "Submit" })',
+ ]) {
+ const { output } = await cli('click', locator);
+ expect(output).toContain(`await page.getByRole('button', { name: 'Submit' }).click();`);
+ }
});
test('click button with test id locator', async ({ cli, server }) => {
@@ -309,6 +318,12 @@ test('click button with wrong css selector', async ({ cli, server }) => {
const { output } = await cli('click', '#target');
expect(output).toContain(`"#target" does not match any elements.`);
+
+ const { output: invalidError } = await cli('click', 'button "Submit"');
+ expect(invalidError).toContain(`"button "Submit"" is not a valid target. Use a ref from the page snapshot (e.g. "e5"), a CSS selector, or a locator (e.g. "getByRole('button', { name: 'Submit' })").`);
+
+ const { output: refError } = await cli('click', 'button [ref=e2]');
+ expect(refError).toContain(`"button [ref=e2]" does not match any elements. To use the element with [ref=e2] from the page snapshot, pass "e2" as the target.`);
});
test('partial snapshot', async ({ cli, server }) => {