Playwright · MCP · AI Agents

Playwright Concepts

Learn modern Playwright architecture from beginner to advanced — including MCP, AI Agents, Playwright Agents and Agentic Testing — with easy-to-understand visual diagrams.

Section 1

Model Context Protocol (MCP)

Forget the buzzword for a second. The fastest way to understand MCP is to watch one run happen — so that is exactly what this section starts with.

❌ What it is not

Not an AI model. Not an agent. Not a framework or a library.

🔗 What it is

An open protocol — one shared language between an AI app and your tools.

⚡ What it changes

The model stops describing the work and starts doing it.

Watch a real MCP run

Pick a task, press Play, and follow the request travelling down the stack and the result coming back up. Every line on the right is the kind of message that really crosses the wire.

Task

You:

Press Play to start the run…

0 / 0
request going down result coming back

now the same task — without MCP

Identical prompt, identical model. The only thing removed is access. Press Play and watch how far it gets.

You:

Press Play to start the run…

0 / 0
request that cannot leave the model unreachable

Same question, same intelligence, opposite outcome. The top run ends with a verified answer and a real locator. This one ends with a plausible guess and a homework list — because the model never got to look at anything.

So what actually happened?

The model never guessed

It read the real page, the real console and the real test id. Without MCP it would have invented a selector like .btn-checkout and hoped.

Every action was a tool call

Lines like browser_click { ref: "add-to-cart-1" } are the protocol. The model chooses which tool and what arguments; the server does the work and returns a structured result.

The loop ran several times before you saw an answer

Call → read result → decide the next call. That repeated loop is what makes it feel agentic — and it is the bridge to Section 2.

The model did not get smarter. It got access. Same weights, same reasoning — the only new ingredient was a set of tools it was allowed to call.

Set it up in about 60 seconds

MCP stops being abstract the moment you run it yourself. The official Playwright MCP server is one command.

Install Playwright & its browsers

npm init playwright@latest
npx playwright install

Add the MCP server to Claude Code

claude mcp add playwright npx @playwright/mcp@latest

One line. That is the whole integration.

Or configure it by hand

For any other MCP client (Claude Desktop, VS Code, Cursor…), drop this into its MCP config file:

{
  "mcpServers": {
    "playwright": {
      "command": "npx",
      "args": ["@playwright/mcp@latest"]
    }
  }
}

Restart the client and ask it something that needs a browser — “open example.com and tell me the H1”. If it opens a real Chromium window, MCP is working. Point it at a practice app rather than production.

What Playwright MCP actually gives the model

Not magic — a named list of callable tools. These are the ones you will see most:

ToolWhat it doesWhy QA cares
browser_navigateOpens a URL in a real browserStarts every journey
browser_snapshotReturns the accessibility tree — roles, names, test idsThe big one. Real locators instead of guesses
browser_clickClicks an element from that snapshotDrives the flow
browser_typeFills inputsForms, search, login
browser_console_messagesReads console outputCatches the JS error behind a failure
browser_network_requestsLists requests and status codesSpots the 500 the UI hid
browser_take_screenshotCaptures the viewportEvidence and visual checks

Notice what is missing: there is no “look at the pixels” tool. Playwright MCP hands the model a structured accessibility snapshot, which is why generated locators come out as getByRole and getByTestId instead of brittle CSS chains.

MCP is not just browsers — explore the other servers

Same protocol, different server. Click a tab to see what each one unlocks.

Playwright — drive a real browser

browser_navigatebrowser_snapshotbrowser_clickbrowser_typebrowser_console_messages

“Walk through guest checkout on staging and tell me every field that has no label.”

What you get back: a real walkthrough, plus a list of unlabelled inputs with the exact locator for each — an accessibility bug report nobody had to write by hand.

GitHub — branch, commit, review

list_issuescreate_branchcreate_or_update_filecreate_pull_requestget_workflow_run_logs

“The nightly run failed. Read the CI log, fix the broken locator and open a PR.”

What you get back: a branch, a one-line diff in the page object, and a PR whose description quotes the exact CI error it fixes.

Files — read and write the project

read_filewrite_filelist_directorysearch_files

“Which of our 240 specs still use page.waitForTimeout?”

What you get back: the real file list with line numbers — and, if you ask, a refactor to web-first assertions across all of them.

Database — verify what the UI claims

querylist_tablesdescribe_table

“I placed order #1042 in the UI. Did it actually persist?”

What you get back: the real row — status, total, timestamp. A green toast is not proof; a row in the table is. Keep this connection read-only.

Jira — close the loop with the ticket

search_issuesget_issueadd_commenttransition_issue

“Read QA-318, turn its acceptance criteria into scenarios, then comment the result.”

What you get back: scenarios traceable to the criteria that produced them, and a comment on the ticket with pass/fail evidence.

API — set up state fast, assert the contract

http_requestdescribe_endpoint

“Seed a user with 3 items in the cart, then start the UI test from there.”

What you get back: state created in one API call instead of six UI clicks — faster and far less flaky than driving setup through the interface.

Why Anthropic created MCP

Before MCP, every AI app needed a bespoke connector for every tool: M apps × N tools = M×N integrations, each with its own auth and format. Anthropic open-sourced MCP in late 2024 to collapse that into M+N — one server per tool, one client per app, everything interoperable. That is why Microsoft, OpenAI, Google, JetBrains and GitHub all ship MCP servers today.

4 AI apps 4 tools — 16 custom connectors
❌ Without MCP — M×N
MCP 4 AI apps 4 tools — 8 reusable connections
✅ With MCP — M+N

Section 1.1

Why Do We Need MCP?

The fastest way to understand MCP is to look at what an AI model can and cannot do without it.

Without MCP
  • AI cannot access the browser
  • Cannot execute Playwright
  • Cannot read your project files
  • Cannot interact with GitHub
  • Cannot inspect databases
  • Cannot call external tools
  • Only describes what you should do
With MCP
  • Execute Playwright tests
  • Read the whole project
  • Run tests and read the output
  • Drive a real browser
  • Fix and re-run failing tests
  • Read logs, traces and reports
  • Generate production-ready code
  • Access GitHub — branch, commit, PR
  • Execute SQL for data validation
  • Use REST / GraphQL APIs

Section 1.2

MCP Architecture

Hover (or tap) any block to see what it does. The dotted lines show live protocol traffic.

User — the person writing the prompt 👤 User writes the prompt 1 8 AI model — Claude / ChatGPT 🧠 Claude / ChatGPT decides which tool to use 2 7 MCP Client — inside the AI application 📡 MCP Client speaks the MCP protocol 3 6 MCP Server — exposes tools to the model 🤝 MCP Server exposes tools · executes them · returns structured results 4 invoke 5 result Playwright MCP server 🎭 Playwright GitHub MCP server 🐙 GitHub Filesystem MCP server 📁 Files Database MCP server 🗃️ Database Browser MCP server 🌐 Browser API MCP server 📡 API Jira MCP server 📋 Jira one client · many servers · every server speaks the same protocol 1–4 request & tool call 5–8 result travels back two-way
Figure 1 — MCP architecture as a full round trip: your request travels down (steps 1–4) and the result travels back up the same path (steps 5–8). The client/server split is what turns the M×N integration problem into M+N.

Section 1.3

MCP Workflow

What actually happens, step by step, when you type a prompt like “open the shop, add a product to the cart and tell me the badge count”.

Request → Response round trip

💬User Request“Add a product to the cart”
🧠AI Modelplans which tools to call
📡MCP Clientserialises the tool call
🎭Playwright MCP Serverexecutes browser_click, browser_type…
🌐Browserreal Chromium session
📱Applicationyour app under test
📊Result Back to AIaccessibility snapshot + console + network
Useranswer, generated test, or next action

The loop can repeat many times before you see an answer. The model calls a tool, reads the result, decides the next tool, and only replies to you once the goal is met. That loop is what makes it feel agentic.

Section 1.4

QA Perspective Flow

The same loop, told from a QA engineer’s chair — from prompt to a committed, passing test.

Prompt → Green build → repeat

🤵QA Engineerknows what to verify
✍️Prompt“Write an E2E test for guest checkout”
🧠Claudereasons about the scenario
🎭Playwright MCPtool calls over the protocol
🌐Browserreal session, real timing
🛒Applicationshop.qaautomationlabs.com
📸Capture ResultDOM snapshot, roles, test-ids
📝Generate Testspec + page object + fixtures
▶️Execute Testnpx playwright test
📈Generate ReportHTML report, trace, video
🔧Fix Failurebetter locator, better wait
🐙Commit to GitHubbranch → PR → CI

Section 1.5

Without MCP vs With MCP

Same goal, two very different loops. On the left you do every step. On the right you supervise.

Without MCP — manual loop
🤵 QA Engineer
✍️ Write Code
▶️ Run Test
❌ Check Failure
🐛 Debug
🔄 Repeat…

Every iteration costs human time. Flaky locators mean the loop runs again tomorrow, and the day after.

With MCP — assisted loop
🤵 QA Engineer
💬 Prompt AI
🔗 MCP
📝 Generate Test
▶️ Execute
🔍 Analyze Failure
🩹 Heal
📈 Generate Report

You stay the reviewer and the decision-maker. The repetitive middle of the loop is automated.

Section 1.6

Real QA Use Cases

Ten things teams are genuinely doing today with Playwright plus MCP.

Generate Playwright Test

Describe a scenario; get a runnable spec with page objects and real locators taken from the live DOM.

Execute Tests

Run the suite, a project, a single spec or a single --grep tag, and read the output.

Visual Testing

Capture and compare screenshots, then explain what changed instead of just failing a diff.

API Testing

Probe endpoints, learn the schema, and generate request/response assertions that match reality.

Accessibility Testing

Run axe checks through the browser tool and get prioritised, human-readable remediation steps.

GitHub Integration

Create a branch, commit the new specs, open a PR and summarise the change for reviewers.

Jira Integration

Turn acceptance criteria into scenarios, and post pass/fail evidence back onto the ticket.

Database Validation

Assert the UI action produced the right row, status and audit entry — not just the right toast message.

Self-Healing Tests

When a selector breaks, find an equivalent element in the current DOM and propose a stronger locator.

AI-assisted Debugging

Read the trace, the console errors and the network log together, then explain the root cause in one paragraph.

Section 2

AI Agents

MCP gave the model hands. Agents give it a plan. This section explains what an agent really is — without any jargon.

What is an AI Agent?

An AI agent is a model that is given a goal, a set of tools, and permission to keep working until the goal is met.
Think of the difference between asking a colleague “how do I book a flight?” (they explain) and saying “book me a flight to Bangalore next Tuesday” (they open the site, compare options, pick one, and come back with a confirmation). The second one is an agent.

The formal definition

An agent is a loop: observe → think → act → observe again. The model looks at the current state, decides on an action, calls a tool (very often through MCP), reads the result, and repeats. It stops when the goal is achieved, when it hits a guardrail, or when it needs a human decision.

AI Assistant vs AI Agent

Comparison of AI assistants and AI agents
AspectAI AssistantAI Agent
What you give itA questionA goal
What it returnsAn answer or a code snippetA completed outcome
ToolsNone — text onlyBrowser, files, GitHub, DB, APIs
Number of stepsOne turnMany turns, self-directed
Memory of progressJust the chat historyTracks a task list and its own state
Failure handlingYou debug itIt re-plans and retries
QA analogy“Show me a login test example”“Cover the whole login module and open a PR”

Why agents are becoming popular

Tools became standard

MCP made “plug a model into a real system” a five-minute config change instead of a project.

Models got better at planning

Modern models can decompose a fuzzy goal into ordered, verifiable steps — the hard part of automation.

Feedback loops are cheap

Running a test and reading the output is fast, so the agent can self-correct instead of guessing.

The boring middle disappears

Scaffolding, locator hunting, fixture wiring and report chasing are exactly what agents are good at.

Real-world examples

💻 Coding agents that open PRs 📧 Inbox triage agents 📋 Research agents that cite sources 🚚 Travel booking agents 🛡️ SRE agents that read dashboards 💳 Reconciliation agents in finance

QA examples

Exploration agent

Crawls an unfamiliar app, maps the pages and forms, and proposes a coverage matrix before a line of code exists.

Maintenance agent

Runs nightly, finds the three specs that broke after a UI refactor, and opens a PR with fixed locators.

Triage agent

Groups 40 CI failures into 3 root causes and tells you which one is a real product bug.

Coverage agent

Compares the test suite against the requirements doc and lists the scenarios nobody wrote.

Section 2.1

Why Do We Need Agents?

Traditional automation is one long human loop. Agentic testing splits that loop into specialists.

Traditional Automation
🤵 Human
✍️ Write Test
▶️ Execute
🐛 Debug
  • One person is the bottleneck for every step
  • Maintenance grows faster than coverage
  • Knowledge lives in one head
Agentic Testing
🤵 Human
💬 Prompt
📝 Planner
⚙️ Generator
▶️ Executor
🩹 Healer
📈 Report
  • Each agent has one clear responsibility
  • Steps run in parallel where possible
  • The human reviews instead of typing

Section 2.2

Agent Architecture

A single “super agent” is hard to control. Real systems use a planner, a task manager, and a team of narrow specialists. Hover any agent to see its job.

User — supplies the goal 👤 User Planner — converts the goal into a plan 📝 Planner goal → ordered plan Task Manager — dispatches work to specialists 🏠 Task Manager routes · parallelises · tracks state SPECIALIZED AGENTS Browser Agent 🌐 Browser Agent API Agent 📡 API Agent Database Agent 🗃️ Database Agent GitHub Agent 🐙 GitHub Agent Report Agent 📈 Report Agent Healing Agent 🩹 Healing Agent results collected retry / re-plan review & approve Result — merged outcome ✅ Result tests · report · PR narrow agents · one responsibility each · a human approves the outcome dispatch results retry loop back to the human
Figure 2 — Multi-agent architecture, end to end. Work is dispatched down, results are collected back up, failures loop back to be re-planned, and the finished outcome returns to the human for review. Narrow agents are easier to test, trust and debug than one giant agent.

Section 3

Playwright Agents

A Playwright Agent is not one big robot. It is a multi-agent architecture in which different agents own different responsibilities in the test lifecycle — planning, generating and healing.

The three roles map cleanly onto how a good QA team already works: someone decides what to test (Planner), someone writes the code (Generator), and someone keeps the suite green when the UI moves (Healer). The agents just do it faster, and never get bored.

Planner Agent

Explores the app and turns a requirement into a structured test plan. It never writes or runs code.

Generator Agent

Turns the plan into real Playwright code — page objects, specs, fixtures, assertions.

Healer Agent

Wakes up only when a test fails, finds why, repairs the locator or wait, and re-runs to prove it.

Section 3.1

Planner Agent

The Planner is the analyst of the team. Give it a requirement and a URL; it gives you back a test plan a human can review before a single line of code is written.

Responsibilities

  • Understand the requirement — read the story, ticket or acceptance criteria
  • Analyze the prompt — separate what is in scope from what is not
  • Break the task down — modules, pages, user journeys, edge cases
  • Create an execution strategy — order, dependencies, test data, parallelism
  • Generate the plan — a reviewable document, not code

Planner flow

💬Prompt“Cover the checkout module”
🧠Understand Requirementscope, actors, success criteria
🔎Analyze Websitecrawl via Playwright MCP
📄Identify Pagescart, address, payment, confirmation
🎯Identify Scenarioshappy path, empty cart, invalid card…
📋Generate Test Planordered, prioritised, reviewable
Example What a Planner actually produces

Prompt: “Create a test plan for the checkout flow on shop.qaautomationlabs.com.”

# Test Plan — Checkout Module
Under test: shop.qaautomationlabs.com
Pages found: /cart.php, /checkout.php, /order-confirm.php

TC-01  Guest checkout — happy path            [P1]
        add product → cart → checkout → pay → confirmation id shown
TC-02  Checkout with empty cart is blocked    [P1]
TC-03  Required address fields validated      [P2]
TC-04  Cart total = sum(line items)           [P1]
TC-05  Quantity update recalculates total     [P2]
TC-06  Cart survives a page reload            [P2]

Test data:  demo@demo.com / demo  ·  product ids 1–20
Order:      TC-01 first (seeds state), rest independent
Not in scope: real payment gateway, email delivery

Notice there is no code here at all. That is deliberate — a plan is cheap to review and cheap to change. Fixing scope at this stage costs seconds; fixing it after 600 lines of specs costs an afternoon.

Section 3.2

Generator Agent

The Generator is the developer of the team. It takes the approved plan and writes real, runnable Playwright code — using locators read from the live DOM, not invented from memory.

Responsibilities

  • Create Playwright code — idiomatic, typed, lint-clean
  • Create Page Objects — one class per page, actions not selectors leaking into specs
  • Generate locators — prefer getByRole / getByTestId over CSS chains
  • Assertions — web-first, auto-retrying expect()
  • Fixtures — login state, seeded data, cleanup
  • Test data — deterministic, isolated per worker
  • Reports — wire up HTML reporter, traces, videos on failure

Generator flow

📋Test Planapproved by a human
🧩Generate Page ObjectsCartPage, CheckoutPage…
📝Generate Testsone spec per scenario
Generate Assertionsweb-first, auto-retrying
🔧Generate Fixturesauth state, test data, cleanup
📈Generate Reportsreporter config, trace on retry
Example From plan line TC-01 to runnable code
// pages/CartPage.ts — generated page object
import { Page, Locator, expect } from '@playwright/test';

export class CartPage {
  readonly badge: Locator;
  readonly checkoutBtn: Locator;

  constructor(private readonly page: Page) {
    // locators read from the live DOM via Playwright MCP
    this.badge       = page.getByTestId('cart-count');
    this.checkoutBtn = page.getByRole('button', { name: 'Proceed to Checkout' });
  }

  async expectItemCount(n: number) {
    await expect(this.badge).toHaveText(String(n));
  }
}

// tests/checkout.spec.ts — generated spec
test('TC-01 guest checkout happy path', async ({ page }) => {
  const cart = new CartPage(page);
  await page.goto('/womens-wear.php');
  await page.getByTestId('add-to-cart-1').click();
  await cart.expectItemCount(1);
  await cart.checkoutBtn.click();
  await expect(page.getByTestId('order-id')).toBeVisible();
});

Why this is better than a hand-guessed test: the agent read data-testid="cart-count" from the real page. It did not guess .cart > span.badge:nth-child(2) and hope.

Section 3.3

Healer Agent

The Healer is the maintainer — and for most teams it is the agent that saves the most time. Suites rarely fail because the test logic is wrong; they fail because the UI moved.

When a test fails, the Healer does what an experienced engineer does: read the error, look at the page as it is now, compare it with what the test expected, find the element that clearly corresponds, and switch to a locator that will not break again. Then it re-runs the test — because a fix you have not verified is just a guess.

Responsibilities

  • Detect failures — distinguish a broken locator from a genuine product bug
  • Analyze logs — error message, stack, console, network, trace
  • Find better locators — role + accessible name, or a stable test id
  • Retry safely — only where a retry is legitimate, never to mask a real bug
  • Repair selectors — edit the page object, not fifty specs
  • Suggest fixes — propose a diff for human review rather than silently rewriting

Self-healing must never hide a real defect. If the “Checkout” button is missing because the feature is broken, the correct behaviour is to fail loudly — not to find something else to click. A good Healer proves the element still exists and still means the same thing before it repairs anything.

Healer flow

Test FailedTimeoutError: locator not found
🔍Analyze Failureerror + trace + console
📈Compare DOMexpected vs current snapshot
🎯Find Better LocatorgetByRole / getByTestId
✍️Update Testpatch the page object
🔄Retryre-run the failing spec
Successgreen — and a diff to review
Example A real heal, start to finish
✗ TC-01 guest checkout happy path
  TimeoutError: locator.click: Timeout 30000ms exceeded.
  waiting for locator('.btn-checkout')

— Healer: reading the current accessibility snapshot …
  button "Proceed to Checkout"  [data-testid="checkout-btn"]
  → same text, same position, class renamed by the UI refactor

— Healer: proposed patch
- checkoutBtn = page.locator('.btn-checkout');
+ checkoutBtn = page.getByRole('button', { name: 'Proceed to Checkout' });

— Healer: re-running TC-01 …
✓ TC-01 guest checkout happy path (4.1s)

The fix also made the test better: a CSS class is an implementation detail, while the button’s role and accessible name are what the user actually perceives.

Section 3.4

Complete Playwright Agent Workflow

All three agents together, including the failure branch that loops back through the Healer. Hover any node for detail.

QA Engineer 🤵 QA Engineer Prompt 💬 Prompt Planner Agent 📝 Planner Agent Generator Agent ⚙️ Generator Agent Playwright 🎭 Playwright Execute Test ▶️ Execute Test Failure? Failure? YES Healer 🩹 Healer Fix Test 🔧 Fix Test Run Again 🔄 Run Again re-execute until green NO Generate Report 📈 Generate Report GitHub Commit 🐙 GitHub Commit review, merge & next requirement plan → generate → execute → heal → report → commit — with a human approving the outcome main path failure → heal pass → report back to the engineer
Figure 3 — The full agent loop, closed end to end. Green is the happy path, red is the healing cycle (fix → re-execute until green), and the violet path returns the finished work to the engineer to review, merge and start the next requirement.

Section 3.5

Traditional Playwright vs Playwright Agent

Same framework, same browsers, same assertions — a very different day-to-day.

ActivityTraditional PlaywrightPlaywright Agent
Writing tests Manual you type every line AI-assisted generated from a reviewed plan
Debugging Manual open the trace, bisect by hand Automatic failure analysed and explained
Execution Manual you decide what to run, when Autonomous scoped runs triggered by the agent
Reporting Manual read the HTML report yourself AI-generated summarised, grouped, prioritised
Maintenance Manual fix every broken selector by hand Self-healing repaired and re-verified, diff for review
Coverage discovery Manual depends on who remembers what Explored the app is crawled and mapped
Who reviews A human writes and a human reviews A human reviews — and that stays non-negotiable

Section 3.6

Real World Workflow

How the pieces sit inside a normal delivery pipeline, from a requirement landing in the backlog to a dashboard the whole team watches.

1 · RequirementA story or Jira ticket arrives with acceptance criteria.
2 · PlannerExplores the app, maps the pages, drafts a prioritised test plan for review.
3 · GeneratorWrites page objects, specs, fixtures and assertions from the approved plan.
4 · ExecutionPlaywright runs the suite in parallel across projects and browsers.
5 · HealerRepairs locator-level failures, re-runs them, and flags anything that looks like a real bug.
6 · ReportingHTML report plus traces, videos and a plain-English summary of the run.
7 · GitHubBranch, commit and pull request — a human reviews the diff before it merges.
8 · CI/CDThe pipeline re-runs everything on every push; the merge gate stays honest.
9 · DashboardTrends, flake rate and coverage over time — the signal the team actually manages by.

Track 3

Playwright CLI Skills

There is a second way to hand a coding agent a browser — not through MCP tool schemas, but through a shell command it already knows how to run. That is @playwright/cli.

🧮 Token-efficient

Short command output instead of large tool schemas sitting in the model’s context.

🎯 Ref-based

Every command returns an accessibility snapshot with element refs like e21.

⚡ Daemon-backed

A persistent browser process, so there is no start-up cost on every command.

The agent runs playwright-cli click e21 the same way it runs git commit. No protocol, no JSON-RPC — just a command and its output. That is the whole idea: agents are already excellent at using a terminal.

Watch the CLI loop

The real TodoMVC walkthrough from the Playwright docs. Press Play and watch each command return a fresh snapshot that the next command depends on.

Goal: Add two todos to TodoMVC and tick the first one off.

Press Play to start the session…

0 / 0
command the agent runs snapshot returned to the agent

Notice check e21. The agent never invented that reference — it read it from the snapshot the previous command returned. Refs are what make the interaction deterministic instead of a guess at a CSS selector.

Track 3.1

Playwright CLI vs MCP

Two doors into the same browser. They are not rivals — they suit different jobs.

Playwright CLIPlaywright MCP
Best for Coding agents (Claude Code, Copilot) working inside a large codebase Specialised agentic loops and exploratory automation
How it works The agent runs shell commands The model calls MCP tools with structured parameters
Token cost Lower concise output, skills loaded on demand Higher tool schemas plus snapshots in context
Default modeHeadlessHeaded
Setup npm install -g @playwright/cli JSON config in the MCP client

Rule of thumb. If the agent is already living in your repo and context is precious, reach for the CLI. If you are building a dedicated automation loop where a model should reason over rich structured tool results, reach for MCP. Plenty of teams use both.

Track 3.2

Install & Skills

Node.js 20+ and a coding agent (Claude Code, Copilot, Cursor…) are the only prerequisites.

Install the CLI

npm install -g @playwright/cli@latest
playwright-cli --help

Prefer not to install globally? npx playwright-cli --help works too.

Install a browser

One is downloaded automatically on first use, but you can be explicit:

playwright-cli install-browser                # chromium (default)
playwright-cli install-browser firefox        # a specific browser
playwright-cli install-browser --with-deps    # + Linux system deps

Install the skills — the important bit

playwright-cli install --skills

This drops skill files locally so your agent gets structured reference docs for the CLI instead of guessing from --help.

Optional: pin a session

PLAYWRIGHT_CLI_SESSION=todo-app claude .

Keeps one agent’s browser state isolated from another’s.

install-browser flags

FlagWhat it does
--with-depsAlso install Linux system dependencies
--dry-runPreview what would be installed
--listList available browsers across installations
--forceReinstall even if already present
--only-shellOnly the Chromium headless shell
--no-shellSkip the Chromium headless shell

The CLI drives a real browser with real cookies and real storage. Point it at a test environment or a practice app such as the QA Automation Labs demo shop — never at production with live credentials.

Track 3.3

The snapshot → ref → command loop

Every CLI interaction follows the same four beats. Once this clicks, the whole command set makes sense.

The core workflow

📂Openplaywright-cli open <url>
📄Snapshotaccessibility tree written to .playwright-cli/*.yml
🎯Pick a refe.g. e21 — a stable handle on one element
👆Interactclick / fill / type / check using that ref
🔄Fresh snapshotnew state, new refs — then repeat

What the CLI prints after every command

### Page
- Page URL: https://demo.playwright.dev/todomvc/#/
- Page Title: React - TodoMVC

### Snapshot
[Snapshot](.playwright-cli/page-2026-02-14T19-22-42-679Z.yml)

Short by design. The heavy accessibility tree lives in the .yml file; only the pointer goes into the agent’s context. That is the token trick.

Track 3.4

Command reference

The full surface, grouped the way the docs group it. Click a category.

Core — open a page and act on it

open [url]goto <url>closeclick <ref>dblclick <ref>fill <ref> <text>type <text>select <ref> <val>check <ref>uncheck <ref>hover <ref>drag <start> <end>upload <file>snapshotscreenshot [ref]pdfeval <func> [ref]resize <w> <h>dialog-acceptdialog-dismiss

QA angle: snapshot is your best friend when writing tests — it is the same accessibility view Playwright’s getByRole uses, so whatever you see there is what you should assert on.

Navigation — move through history

go-backgo-forwardreload

QA angle: perfect for the checks people forget — does the cart survive a reload? Does go-back from checkout keep the basket intact?

Keyboard & Mouse — low-level input

press <key>keydown <key>keyup <key>mousemove <x> <y>mousedown [btn]mouseup [btn]mousewheel <dx> <dy>

QA angle: keyboard-only journeys are an accessibility requirement. press Tab repeatedly and read each snapshot to verify a sane focus order.

Tabs — multi-tab flows

tab-listtab-new [url]tab-select <idx>tab-close [idx]

QA angle: anything that opens a new window — OAuth pop-ups, payment redirects, “open in new tab” links, PDF previews.

Storage & authentication

state-save [file]state-load <file>cookie-listcookie-get <name>cookie-set <name> <val>cookie-delete <name>cookie-clearlocalstorage-listlocalstorage-get <key>localstorage-set <k> <v>localstorage-clearsessionstorage-*

QA angle: state-save once after logging in, then state-load before every run — the CLI equivalent of Playwright’s storageState. It is the single biggest speed-up for authenticated suites.

Network & mocking

networkroute <pattern> [opts]route-listunroute [pattern]

QA angle: the fastest way to test the unhappy paths. Route the cart API to a 500 and check the UI degrades honestly instead of showing an empty basket.

DevTools — console, tracing, video

console [min-level]run-code <code>tracing-starttracing-stopvideo-start [file]video-chapter <title>video-stopshow

QA angle: wrap a flaky journey in tracing-start / tracing-stop and hand the trace to a human. console error often explains a failure in one line.

Sessions — isolated browsers

-s=<name> <cmd>listclose-all

QA angle: two sessions, two logged-in users, one shared document — the simplest way to exercise real multi-user behaviour. Also how you stop parallel agents fighting over one browser.

Global options

--headed watch it happen --browser=firefox switch engine --persistent keep the profile --profile named profile -s=<name> pick a session

Track 3.5

What the skills teach your agent

Running playwright-cli install --skills gives the agent structured reference guides it can pull in on demand — instead of you pasting instructions into every prompt.

Running & debugging tests

How to run, debug and manage a Playwright test suite from the command line.

Request mocking

Intercepting and mocking network requests to force the paths you cannot trigger by hand.

Running Playwright code

Executing arbitrary Playwright snippets when a single command is not enough.

Session management

Juggling several isolated browser sessions at once.

Storage state

Persisting and restoring cookies and localStorage so tests start logged in.

Test generation

Turning a recorded interaction into an actual Playwright test.

Tracing

Recording and inspecting execution traces for post-mortem debugging.

Video recording

Capturing a session as video — useful evidence on a bug ticket.

Inspecting attributes

Reading element attributes that the accessibility snapshot does not expose.

No skills? Still fine.

You can point an agent at the CLI and let it discover the commands itself:

Test the "add todo" flow on https://demo.playwright.dev/todomvc
using playwright-cli. Check playwright-cli --help for available commands.

Skills work with Claude Code, GitHub Copilot, Cursor and any agent that supports locally installed skills.

Track 3.6

Which one should you reach for?

Use the CLI when…
  • Your agent is already working inside the repo
  • Context window is the constraint you keep hitting
  • You want browser work mixed in with code edits and git
  • You like being able to run the exact same command yourself
  • Headless CI runs are the default you want
Use MCP when…
  • You are building a dedicated agentic testing loop
  • You want structured tool results to reason over
  • You are combining browser, GitHub, DB and Jira servers
  • Exploratory automation, where watching it matters
  • Your client is a chat app rather than a terminal agent

Honest answer: learn both. They share the same mental model — snapshot the page, target an element by its accessible identity, act, re-snapshot. Master that loop and switching between CLI and MCP is a matter of syntax, not concepts. See Track 1 for the MCP side.

Section 4

Interactive Learning

Everything above, compressed into answers you can quiz yourself with. Open one, cover the text, and try to explain it out loud first.

Q1 What is MCP?

MCP (Model Context Protocol) is an open standard that lets an AI model talk to external tools and data sources through one common language. The AI app runs an MCP client; each tool runs an MCP server.

It is not a model and not an agent — it is the wiring. Without MCP a model can only describe what you should do; with MCP it can open the browser, read your repo, query the database and run your tests. Anthropic open-sourced it in late 2024 to replace M×N custom integrations with M+N.

Q2 What is an AI Agent?

An AI agent is a model that is given a goal, a set of tools, and permission to keep working until the goal is met. It runs a loop: observe → think → act → observe.

An assistant answers a question in one turn. An agent completes an outcome over many turns, tracks its own progress, and re-plans when something fails.

Q3 What is a Playwright Agent?

A Playwright Agent is a multi-agent architecture for the test lifecycle. Instead of one model doing everything, specialised agents each own one responsibility — most commonly Planner (what to test), Generator (write the code) and Healer (keep it green).

Underneath it is still ordinary Playwright: the same runner, the same browsers, the same expect() assertions. The agents write and maintain the code; Playwright executes it.

Q4 What does the Planner Agent do?

It converts a requirement into a reviewable test plan: understand the requirement, explore the application, identify pages, identify scenarios, set priorities and test data, and state what is out of scope.

The Planner does not execute tests and does not write code. That separation is the whole point — a plan is cheap to review and cheap to correct, and catching a scope mistake here saves rewriting hundreds of lines later.

Q5 What does the Generator Agent do?

It turns the approved plan into runnable Playwright code: page objects, spec files, locators, web-first assertions, fixtures, test data and reporter configuration.

Its key advantage over a hand-written first draft is that it reads locators from the live DOM through the browser tool, so it can prefer getByRole and getByTestId instead of guessing a fragile CSS chain.

Q6 What does the Healer Agent do?

It reacts to failures: analyse the error and trace, compare the expected DOM with the current one, find a better locator, patch the page object, and re-run to prove the fix.

The critical rule: a Healer must never mask a real product bug. If an element is genuinely missing because the feature is broken, the test has to fail loudly. Healing applies to how we find an element, never to whether the behaviour is correct.

Q7 Common interview questions
  • Is MCP an AI model? No — it is a communication protocol. The intelligence stays in the model.
  • MCP client vs MCP server? The client lives in the AI application and speaks the protocol; the server wraps a tool and exposes its capabilities.
  • Why does MCP exist? To collapse M×N bespoke integrations into M+N reusable ones.
  • Assistant vs agent? An assistant answers; an agent pursues a goal across many tool-using steps.
  • Does the Planner run tests? No. It only produces the plan.
  • How does Playwright MCP see the page? Through the accessibility tree — structured roles and names, not pixels.
  • Is self-healing safe? Only with human review and only for locator-level changes; never to hide a functional defect.
  • Do agents replace QA engineers? No. They remove the repetitive middle. Deciding what “correct” means is still a human job.
  • How do you keep an agent from breaking things? Read-only credentials, a dedicated test environment, scoped filesystem access, and a PR gate.
Q8 Best practices
  • Review the plan before the code. Correcting scope takes seconds; rewriting specs takes hours.
  • Keep humans on the merge gate. Agents propose; people approve.
  • Give every element a stable data-testid. Good locators make agents dramatically more reliable.
  • Point agents at a test environment with read-only database credentials — never production.
  • Scope your MCP servers. Expose only the folders, repos and tables the task genuinely needs.
  • Prefer web-first assertions (expect(locator).toBeVisible()) over manual sleeps — for humans and agents alike.
  • Track healed tests. A test healed three times is telling you the UI is unstable, not that healing works well.
  • Commit the plan alongside the specs. It is the best documentation your suite will ever have.
Q9 How do I start today, with zero experience?

A realistic first week:

  1. Install Playwright: npm init playwright@latest
  2. Write one ordinary test by hand, so you know what “good” looks like.
  3. Add the Playwright MCP server to your AI client’s MCP config.
  4. Ask it to explore one page and list the locators it can see.
  5. Ask it to generate one test — then read every line and correct it.
  6. Break a selector on purpose and ask it to heal the test.

Practise against a site built for it — try the QA Automation Labs demo shop, where every element already carries a data-testid.

Section 5

Beginner Tips

The seven sentences that clear up almost every beginner misconception.

MCP is not an AI model.

MCP is a communication protocol.

Agents are task executors.

Playwright Agent combines AI with Playwright automation.

The Planner does not execute tests.

The Generator creates automation code.

The Healer repairs failing tests — it never hides real bugs.

One last thing. None of this removes the need to understand testing. An agent can write a hundred assertions; deciding which hundred are worth writing is still the QA engineer’s job — and it is the part of the role that is getting more valuable, not less.

Want more? Explore the courses, practise on the demo shop and the UI testing playground, or read the blog.

Scroll to Top