playwright-generate-mcp
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@playwright-generate-mcp Generate a Playwright login spec with page objects, then run it and score quality."
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
playwright-generate-mcp
An enterprise-grade Model Context Protocol (MCP) server that empowers AI coding assistants (Cursor, Claude Desktop, Antigravity, Roo Code, etc.) to generate, score, run, and auto-heal robust, maintainable, and flake-resistant Playwright E2E tests.
It is built for QA teams: tests are generated from the QA test cases (Gherkin, CSV, Excel) and from what the live website really renders, never from frontend source code. It lives in its own automation repository, enforces a Domain-Driven Page Object Model (POM) architecture, provides cross-file quality scoring, extracts rich single-turn failure diagnostics, and adheres to strict web-first anti-flakiness rules.
๐งช QA-first workflow
Set up a separate automation repo โ ask the AI to run the
playwright_setup_qa_projectprompt, or callinit_qa_projectwith the target folder,BASE_URL,API_URLand (optionally)ID_SELECTOR. It createspackage.json,playwright.config.ts,.env/.env.example,.gitignore,docs/test-case/andassets/. To work in an existing automation repo instead, just open it (or callset_project_root);check_test_prerequisitesreports what is missing.Fill
.envโTEST_USER/TEST_PASSWORDare typed by you and never leave the file (it is git-ignored):BASE_URL=https://staging.your-app.com API_URL=https://api.staging.your-app.com ID_SELECTOR=qa # data-qa; becomes use.testIdAttribute = "data-qa" TEST_USER= TEST_PASSWORD=Install:
npm installandnpx playwright install chromiumin the automation repo (the MCP never installs anything).Put test cases in
docs/test-case/(.feature,.csv, optional.xlsx) and files used by upload steps inassets/. See the README created indocs/test-case/for the CSV columns.Generate โ run the
playwright_generate_from_testcaseprompt (optionally withids, e.g.TC-001, TC-002). The AI reads the test cases (read_test_cases), scrapes every page of the live site (inspect_page), scaffolds the domain (scaffold_test_domain), implements one test per test case ([TC-001] โฆtitle +@TC-001tag), then scores and runs it.
Selector priority when scraping and generating: data-testid > data-qa > data-{ID_SELECTOR} > semantic (getByRole > getByLabel / getByPlaceholder > getByText). ID_SELECTOR is wired into use.testIdAttribute, so page.getByTestId() reads your team's attribute; the other attributes use byTestId() / byQa() / byEnvId() from tests/e2e/support/selectors.ts.
Global auth โ for login/logout/register features (or via scaffold_auth_setup) the MCP creates tests/e2e/auth/: a setup project logs in once with TEST_USER / TEST_PASSWORD (through the login form, or the backend API) and saves the session to the git-ignored .auth/user.json; every other test and inspect_page (useAuth: true) reuses it. Login specs start logged out.
Related MCP server: Limetest MCP Server
โจ Key Features
๐ Live-site scraping instead of source code:
inspect_pageopens the application under test with the project's own Playwright and returns role, accessible name and the best locator per element, reaching modals and wizard steps throughsteps. Navigation is restricted toBASE_URL/API_URLorigins and credentials are redacted from the output.๐ Test-case driven:
read_test_casesparses Gherkin, CSV and Excel files into structured cases (id, steps, expected results, priority) so every generated test is traceable to its test case.๐๏ธ Domain-Driven POM Architecture: Enforces separation of concerns between Declarative Specs, Page Objects, Custom Fixtures, and Dynamic Data Factories. Every scaffolded file contains working reference examples, and the spec shows the four test styles (
@smoke,@ui,@regression,@integration) so generated tests stay consistent.๐ One source for every handler: specs must use the fixture's
*Api/*Mockhelpers;score_test_qualityflagsrequest.*/fetch/page.route()written inline in a spec (inlineApiCall,inlineRoute),@integrationtests without an*Apifixture, and unused helpers.๐ Cross-File POM Quality Scoring:
score_test_qualityandrun_playwright_testautomatically traverse import dependencies (.spec.ts$\rightarrow$.fixture.ts$\rightarrow$*.page.ts/*.component.ts), scoring locators and anti-patterns across all related files.โก Single-Turn Rich Diagnostics: When a test fails,
run_playwright_testimmediately returns the exact file & line location, error category, the last steps before failure, and โ from real browser events in the trace and/or the scaffolded diagnostics fixture โ console errors, page errors and failed requests (network errors and HTTP 4xx/5xx), plus screenshot/trace/video/error-context paths.๐ฆ Bounded, typed MCP output: every tool declares an
outputSchemaand returnsstructuredContent; the default run summary has a hard size cap (see Output contract).๐ก๏ธ Strict Anti-Flakiness Rules: Detects and discourages arbitrary sleeps (
waitForTimeout,setTimeout), un-awaited actions,networkidledependencies, and manual text extractions in favor of web-first auto-retrying assertions.๐ท๏ธ Multi-File & Tag-Only Test Execution:
run_playwright_testsupports running a single spec, an entire directory of specs, or tag-only runs (e.g.grep: "@smoke"orgrep: "@regression") across the test suite without requiring a specific spec file.๐ป Cross-Platform & Windows Ready: Safe process lifecycle management across Linux, macOS, and Windows (tree-kill via
taskkill /T /Fon Windows, POSIX process groups on Unix,.cmd/.batshell execution, andwindowsHideconsole suppression).๐งญ Stateless Root Auto-Discovery: Automatically traverses parent directories to discover
playwright.config.{ts,js,mjs,cjs,mts,cts}without requiring manual path configuration.๐ฌ Adaptive Interactive Confirmations: Supports interactive UI modals (
ask_question,vscode_askQuestions) or formatted numbered lists before applying test heals.
๐ Architecture Standard
This MCP guides AI agents to structure tests under a clean Domain-Driven hierarchy:
tests/e2e/
โโโ support/
โ โโโ diagnostics.fixture.ts # Shared auto fixture recording browser console/page/network events
โ โโโ selectors.ts # byTestId / byQa / byEnvId helpers for data-* attributes
โ โโโ assets.ts # assetPath(): files for upload steps, restricted to assets/
โโโ auth/ # Global auth handler (scaffold_auth_setup)
โ โโโ auth.setup.ts # Logs in once, saves .auth/user.json
โ โโโ auth.page.ts | auth.api.ts
โ โโโ auth.config.ts
โโโ domain/ # Grouped by business features
โ โโโ {feature}/
โ โโโ pages/ # Page Objects / Component Objects
โ โ โโโ {step}.page.ts
โ โโโ {feature}.mock.ts # page.route() handlers for @ui tests (success, empty, 422, 500, pending, request capture)
โ โโโ {feature}.api.ts # Real API helpers for @integration tests (CRUD, tracked cleanup)
โ โโโ {feature}.fixture.ts # Custom Fixture injecting Page Objects, mocks and APIs (API fixture auto-cleans)
โโโ factory/ # Dynamic test data builders
โ โโโ {entity}.factory.ts # Unique data per run and per worker
โโโ specs/ # Declarative, readable test specs
โโโ {feature}.spec.tsscaffold_test_domain generates an explicit skeleton: the spec's tests are test.fixme(...) (Playwright skips them) and the file carries an // @mcp-skeleton marker. score_test_quality reports scaffold.skeleton: true until the examples are adapted, test.fixme is changed to test and the marker is removed โ so an empty scaffold can never look like a passing test. Generated files compile under strict TypeScript and the reference examples are exercised in a real browser by the opt-in e2e suite. The shared support/ files are created once and are never overwritten, even with overwrite: true. The tool also returns a helperCatalog (fixtures with their locators and methods) so the AI does not need to re-read the files.
Core Design Rules
Strict Separation: No raw locators,
request.*orpage.route()inside*.spec.tsfiles. UI interactions live in Page Objects, mocks in*.mock.ts, real API calls in*.api.ts; a missing endpoint means a new method there.Custom Fixtures: Inject Page Objects and test data using
test.extend<Fixtures>()instead of manualnew Page()instantiations in specs.Dynamic Data Factories: Generate unique test data per run to prevent database unique-constraint collisions on test re-runs.
Stable Locators: Prioritize
data-testid>data-qa>data-{ID_SELECTOR}, thengetByRole>getByLabel/getByPlaceholder>getByText. Deep nested CSS (div > div > span) is strictly forbidden.Tagging Conventions:
@smoke: Critical happy paths.@regression: Comprehensive user flows.@ui: Pure UI/frontend tests usingpage.route()to stub API responses.@integration: Tests validating against real backend APIs.
Test prerequisite preflight
Use check_test_prerequisites before run_playwright_test when setting up a target project. The check is read-only: it inspects the target project's package.json, locally resolvable Playwright packages and CLI, supported config files, browser cache, optional Allure adapter/CLI, and existing report artifacts. It does not run npm install, download browsers, or generate reports. Follow the returned nextSteps manually, then run the preflight again.
Monorepos: Playwright hoisted to a workspace root (npm/yarn
workspaces,pnpm-workspace.yaml,lerna.json) is accepted and reported asresolvedFrom: "workspace". A package found in an unrelated parent directory is not.Browsers: installed builds are compared with the builds the installed Playwright expects (
playwright-core/browsers.json); a mismatch isoutdated. Incomplete downloads are ignored. Configs that use a brandedchannel(chrome,msedge) do not require the Playwright browser cache.
Reporters and browser diagnostics
run_playwright_test needs a JSON report, but --reporter=json would replace the project's own reporters. When the project has a playwright.config.*, the runner writes a temporary .pw-mcp-*.config.ts next to it that imports the project config unchanged and appends a JSON reporter, so HTML/Allure reporters keep working (runner.reporterStrategy: "config_wrapper", runner.preservedReporters, nativeReports). When Allure is configured and its local CLI is present, run_playwright_test automatically compiles the Allure report (allure-report/index.html) upon completion (reported in nativeReports.allureReportPath) without spawning blocking servers. The wrapper is deleted after every run, including timeouts and cancellations. Without a config file the runner falls back to --reporter=json (cli_override). check_test_prerequisites provides allure.autoGenerateReady and an actionable allure.setupGuide for first-time project onboarding. The HTML/Allure reporters are never opened with blocking commands automatically during MCP runs.
Browser diagnostics come only from real browser events:
Source | When available | What it provides |
|
| console errors/warnings, page errors, failed requests and HTTP โฅ 400 responses, recent steps |
| the test imports the scaffolded | the same events recorded with |
failures[].diagnosticsSources names the sources used; when it is absent, no browser diagnostics were available (they are never inferred from test-process stderr). Network errors quoted in the error message itself (e.g. net::ERR_CONNECTION_REFUSED) are kept with source: "error_message". Event counts and message lengths are bounded.
๐ ๏ธ MCP Tools
Tool | Description |
| Creates a standalone QA automation repo: |
| Reads |
| Opens a page of the live app ( |
| Creates the global auth handler under |
| Scaffolds the 6-file Domain-Driven POM structure for a feature ( |
| Runs Playwright tests (a single spec file, a directory, or tag-only with |
| Scores a spec file, page object, or test directory and its imported Page Objects with the TypeScript AST (comments and strings are ignored): |
| Full, bounded diagnostics for one failing test from a previous run report: location, recent steps, call log, browser console/page/network diagnostics, screenshot/trace/video/error-context paths. Pass |
|
|
| Statically analyzes |
| Read-only setup check for the local or workspace-hoisted Playwright package/CLI, config, browser builds, branded channels, optional Allure adapter/CLI and the QA layout ( |
| Runtime fallback to manually set the target project root if auto-detection is not applicable. |
๐ MCP Prompts
playwright_setup_qa_project: Onboarding for QA: collects path,BASE_URL,API_URL,ID_SELECTOR, creates the automation repo withinit_qa_projectand the global auth handler. It never asks for passwords in chat.playwright_generate_from_testcase(optional argumentids): The main QA workflow โread_test_casesโinspect_pageon the live site โscaffold_test_domainโ one test per test case ([TC-001]title +@TC-001tag) โscore_test_qualityโrun_playwright_test.playwright_write_test: Authoring rules and structure: scaffolding, stable locators, one source for every mock/api handler, global auth, secrets from.env, tagging. Contains no instruction to read frontend source.playwright_run_and_heal: Focused prompt guiding AI agents to run tests, inspect single-turn failure diagnostics and video recordings, re-inspect the live page withinspect_page, and perform safe, targeted healing in Page Objects.
๐ Output contract & token budget
Every tool declares an MCP
outputSchemaand returnsstructuredContent. The text content repeats it as a one-line summary followed by compact JSON, for clients that only forward text.Errors are returned with
isError: trueandstructuredContent: { error: { code, message, details? } }. Codes are stable:INVALID_PATH,INVALID_IDENTIFIER,INVALID_INPUT,NOT_FOUND,PROJECT_ROOT_NOT_FOUND,REPORT_ACCESS_DENIED,REPORT_NOT_FOUND,REPORT_TOO_LARGE,REPORT_MALFORMED,AMBIGUOUS_TEST,TEST_NOT_FOUND,TEST_NOT_FAILED,PLAYWRIGHT_NOT_INSTALLED,BROWSER_LAUNCH_FAILED,NAVIGATION_FAILED,INSPECT_TIMEOUT,INSPECT_FAILED,INTERNAL_ERROR.run_playwright_test(detail: "summary", the default) is capped at 6,000 characters of JSON (โ 1,500 tokens) for any suite size; a typical failing run is โ 3,500 characters (โ 900 tokens). It lists up to 5 failures and 20 non-passing tests, a 1,000-character stderr tail, and paths relative toprojectRoot. When the cap is reached, the least important detail is dropped first andoutputBudget.reducedistrue.detail: "full"is capped at 100,000 characters.get_failure_detailsreturns one failure with error messages up to 4,000 characters and absolute paths.JSON reports above 50 MB are rejected. The last 20 runner reports are kept for
get_failure_details; older ones are deleted, and all are removed when the server exits.
๐ Installation & Setup
1. Build from Source
git clone https://github.com/your-username/playwright-generate-mcp.git
cd playwright-generate-mcp
npm install
npm run build2. Configure MCP Client
Add the server to your MCP configuration file (e.g. claude_desktop_config.json, Cursor Settings, or Antigravity MCP settings):
{
"mcpServers": {
"playwright-generate": {
"command": "node",
"args": ["/absolute/path/to/playwright-generate-mcp/dist/index.js"]
}
}
}Or when published to NPM:
{
"mcpServers": {
"playwright-generate": {
"command": "npx",
"args": ["-y", "playwright-generate-mcp"]
}
}
}๐งโ๐ป Development
npm run dev # tsx watch mode
npm run build # Clean dist/ and compile TypeScript
npm start # Run compiled MCP server
npm test # Build, then run unit + integration tests (deterministic, no network)
npm run test:unit
npm run test:integration
npm run test:e2e # Opt-in: real Playwright, see below
npm run check:package # package.json / package-lock.json consistencyThe end-to-end suite runs only when PW_MCP_REAL_PLAYWRIGHT_WORKSPACE points to a directory whose package.json declares workspaces and that has @playwright/test, typescript, @types/node, dotenv, exceljs and a browser installed. It covers the real runner, the type-check of everything the scaffold tools generate, .xlsx reading, inspect_page against a local page, and the generated reference tests running end to end in Chromium (no internet needed):
mkdir ~/pw-lab && cd ~/pw-lab
echo '{"private":true,"workspaces":["*"]}' > package.json
npm i -D @playwright/test typescript @types/node dotenv exceljs && npx playwright install chromium
PW_MCP_REAL_PLAYWRIGHT_WORKSPACE=~/pw-lab npm run test:e2eSet PW_MCP_KEEP=1 to keep the temporary project of the end-to-end workflow test for debugging.
๐ License
MIT โ see LICENSE.
Available Tools
8 toolscheck_playwright_configCheck Playwright configA
Statically analyze playwright.config.* (TypeScript AST, not executed) for flakiness-relevant settings (retries, workers, trace, screenshot, video, forbidOnly, fullyParallel) and reporters (HTML/JSON/Allure). Reports whether each value is a literal or a runtime expression. Project-level, not per-spec.
Inputs: configPath, projectRoot. Returns: note, found, analysis, settings, +5 more
check_test_prerequisitesCheck test prerequisitesA
Read-only preflight check for a target project. Detects the local (or workspace-hoisted) Playwright package, CLI, config, browser builds matching the installed Playwright version, branded channels, optional Allure adapter/CLI, and report artifacts โ without installing packages or downloading browsers.
Inputs: projectRoot. Returns: allure, warnings, nextSteps, playwright, +3 more
generate_test_reportGenerate test reportA
Locate or generate a visual test report. 'quality' and 'html' locate existing reports (the quality dashboard at test-results/quality-report.html; the Playwright HTML report written by the project's html reporter). 'allure' generates allure-report/ from allure-results/ with the local Allure CLI (never downloaded). Returns status: located | generated | not_found | setup_required | generation_failed.
Inputs: reporter, projectRoot. Returns: mode, exists, status, message, +4 more
get_failure_detailsGet failure detailsA
Get the full diagnostic breakdown for one failing test from a previous run_playwright_test report: exact location, recent steps, call log, browser console errors, page errors, failed requests, and screenshot/trace/video/error-context paths. Pass testId when titles repeat (e.g. the same spec in several projects).
Inputs: testTitle (required), reportPath (required), testId, projectRoot. Returns: testId, location, errorType, fullTitle, +15 more
run_playwright_testRun Playwright testA
Run a Playwright spec file in the target project and return a bounded, structured result: explicit status, counts, runner/process metadata, up to 5 failures with location, error type, recent steps, browser console errors, page errors and failed requests (from trace.zip and/or the scaffolded diagnostics fixture), screenshot/trace/video/error-context paths, and a compact qualityScore. The project's own reporters (HTML, Allure) keep running. Use detail:'full' or get_failure_details for more. TOKEN ECONOMY INSTRUCTION: In your response, provide a clean, compact 2โ3 line summary (status, duration, video link, and failure cause) rather than dumping large markdown tables into chat. If tests fail, analyze the error and formulate a concrete fix proposal in '.page.ts'. To confirm with the user before applying fixes: 1) If an interactive question/selection tool is available in your environment (e.g. ask_question, vscode_askQuestions), MUST use it to present options: ['Apply Fix & Re-run', 'Review Diff First', 'Cancel']. 2) Otherwise, present the options as a clean numbered list in your response so the user can easily reply with just the number.
Inputs: specPath (required), grep, detail, headed, +3 more. Returns: tests, detail, runner, status, +17 more
scaffold_test_domainScaffold test domainA
Scaffold the Domain-Driven POM structure for a feature: pages, mock API handlers, real API helpers, custom fixture, dynamic data factory and a spec, plus a shared diagnostics fixture (tests/e2e/support) that records browser console/page/network events. The spec is an explicit skeleton: its tests are test.fixme (skipped) and marked @mcp-skeleton until the TODOs are implemented. Always use this before writing new tests to ensure a consistent structure.
Inputs: featureName (required), steps, overwrite, projectRoot. Returns: feature, skeleton, specFile, domainDir, +5 more
score_test_qualityScore test qualityA
Score a spec file and its imported Page Objects with the TypeScript AST (comments and strings are ignored): % semantic locators vs raw CSS/XPath, assertion density, anti-pattern warnings with line numbers, and scaffold skeleton status.
Inputs: specPath (required), projectRoot, generateHtmlReport. Returns: scaffold, warnings, antiPatterns, fileBreakdown, +3 more
set_project_rootSet project rootA
Explicitly set the target project root directory. Use this as a fallback if playwright.config.* cannot be automatically discovered by other tools.
Inputs: projectRoot (required). Returns: message, projectRoot
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelogโฆ
TDQS
Scored across 8 tools
Each tool targets a distinct phase: setup (set_project_root), preflight (check_test_prerequisites), config analysis (check_playwright_config), scaffolding, scoring, execution, failure drill-down, and reporting. The only mild overlap is between check_test_prerequisites, check_playwright_config, and set_project_root, all of which touch project setup/configuration, but their descriptions clearly delineate read-only checks versus an explicit override.
All eight tools follow a strict verb_noun snake_case pattern (set_project_root, check_test_prerequisites, run_playwright_test, get_failure_details, generate_test_report, etc.). No camelCase or mixed conventions; the scheme is fully predictable.
Eight tools is well-scoped for a Playwright test generation and quality workflow. Each tool occupies a distinct stage (setup, preflight, config, scaffold, score, run, diagnose, report) and none feel redundant or padding.
The surface covers a full lifecycle: project/config discovery, scaffolding, quality scoring, execution, failure diagnosis, and report generation. Minor gaps existโno tool to edit/apply suggested fixes or to clean up generated artifactsโbut an agent can work around these, and the run_playwright_test description even hints at fix proposals.
Maintenance
Related MCP Connectors
Approved test intent, reviewed Playwright automation and run evidence, inside your editor.
Write, run and check natural-language browser tests of your web app from your AI assistant.
Browser-based QA for AI-built software. Test pages with real browsers via agents.
Agentic AI quality engineering: run, debug and triage tests on real browsers and devices
Related MCP Servers
- AlicenseAqualityDmaintenanceGenerates intelligent Playwright locators with reliability rankings, creates Page Object Models, and runs test automation scripts directly from your IDE or AI assistant.510 npm1MIT
- AlicenseNot gradedqualityDmaintenanceEnables automated end-to-end testing powered by Playwright where test cases are defined in natural language and executed by AI. Uses lightweight snapshot analysis with vision mode fallback for sophisticated testing scenarios.3Apache 2.0
- AlicenseNot gradedqualityDmaintenanceEnables AI assistants to execute browser automation, perform QA tasks, and generate test code through natural language commands using Playwright.7MIT
- AlicenseNot gradedqualityDmaintenanceAutomates repository analysis, test planning, and generation of end-to-end tests with Playwright, acting as an intelligent quality assistant.18 npmMIT