QA and Test Automation · Lab 33 of 35

Playwright MCP: Drive a Browser With an AI Agent (ShopRung Lab)

Connect Playwright MCP to your AI tool, then drive ShopRung through it from a script exactly as an agent does: tools, snapshots, refs, a password kept out with --secrets, a stale ref, and the Playwright code each action returns, turned into a reviewed test that catches the free-shipping bug.

⏱ 60 minIntermediate💸 Free6 steps

Playwright 1.63Playwright MCPPython 3.12mcp SDK 2.3TypeScript

Overview video

1 / 6

0 of 6 steps done

What you will build

A folder shoprung-mcp-lab where you drive a real browser through Playwright MCP, the way an AI agent does, and keep the result as a normal test:

  • .mcp.json: Playwright MCP for your AI tool, with an isolated profile and the test password in .env.test, never in the conversation.
  • tools.py: lists the 24 tools an agent is offered, and what their descriptions cost (about 20,000 characters).
  • drive.py: logs in as Alice, adds the $75.00 keyboard and reads the cart through MCP tools, printing the Playwright code each action ran.
  • tests/free-shipping.spec.ts: that code, reviewed into a test with real assertions. It passes, and fails with ShopRung's free-shipping bug.

Before you start

Setup

S1Start ShopRung

Start ShopRung as in lab 1 with npm start and leave it running.

Run
curl http://localhost:8080/api/health
You should see
{"status":"UP","app":"ShopRung","version":"1.0.0"}

S2Make the project

You need Node.js 22 or newer and Python 3.12 or newer. Create package.json and requirements.txt with the contents below, then install Playwright with Chromium, and the MCP Python SDK in a virtual environment. Playwright MCP ships with Playwright since 1.62: there is nothing else to install.

Run
mkdir -p shoprung-mcp-lab/tests && cd shoprung-mcp-lab
npm install
npx playwright install chromium
python3 -m venv .venv && source .venv/bin/activate
pip install -r requirements.txt
npx playwright mcp --help | head -3
You should see
Usage: npx playwright mcp [options]

run the Playwright MCP server
1

Connect Playwright MCP to your AI tool

One config file, with the guard rails switched on.

Create .mcp.json in the project folder. Claude Code reads this file; other tools take the same server entry in their own MCP settings (VS Code in .vscode/mcp.json under servers, Cursor in .cursor/mcp.json). --isolated keeps the browser profile in memory, so nothing persists between sessions. --secrets .env.test lets the agent fill a password by its name: the value never enters the conversation.

Create .env.test with the practice password and .gitignore so it is never committed. Then, if you have an AI coding tool, open the folder and ask: "Use the playwright tools to log in to http://localhost:8080 as alice@shoprung.test with the password ALICE_PASSWORD, add the Quiet Mechanical Keyboard to the cart and tell me the cart total." Watch which tools it calls. No AI tool? Skip ahead: step 3 does the same from a script.

.mcp.json
{
  "mcpServers": {
    "playwright": {
      "command": "npx",
      "args": ["playwright", "mcp", "--isolated", "--secrets", ".env.test"]
    }
  }
}
  1. A fresh in-memory browser profile per session: no cookies or logins carried over.line 5
.env.test
ALICE_PASSWORD=Alice123!
  1. Practice accounts only. Never a real password.line 1
.gitignore
node_modules/
.venv/
test-results/
playwright-report/
.playwright-mcp/
# test account passwords: never commit
.env.test
  1. Secrets stay out of Git.line 7
Run
# in your AI tool, after it loads .mcp.json:
/mcp
You should seeyour text will differ: the model writes it
playwright · connected · 24 tools
2

See what the agent is offered

List the tools, and measure their cost.

Create tools.py. It starts the same server over standard input and output, as your AI tool does, and lists every tool with its first line of description. The size is the JSON of all tool definitions: an agent receives that with every request, before it does any work.

Run it: 24 tools in about 20,000 characters, roughly 5,000 tokens. Two of them, browser_evaluate and browser_run_code_unsafe, run arbitrary code: configure your AI tool to ask before it uses them.

tools.py
"""Start Playwright MCP and list its tools: what an AI agent is offered, and what that costs."""
import asyncio
import json
import os

from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client

SERVER = StdioServerParameters(command="npx", args=["playwright", "mcp", "--headless", "--isolated", *os.environ.get("MCP_EXTRA_ARGS", "").split()])


async def main() -> None:
    async with stdio_client(SERVER) as (read, write), ClientSession(read, write) as session:
        info = await session.initialize()
        tools = (await session.list_tools()).tools
        size = len(json.dumps([t.model_dump(mode="json", exclude_none=True) for t in tools]))
        print(f"{info.server_info.name} {info.server_info.version}: {len(tools)} tools, {size:,} characters")
        for t in tools:
            print(f"  {t.name:<28} {t.description.splitlines()[0][:60]}")


if __name__ == "__main__":
    asyncio.run(main())
  1. Extra server options, such as --no-sandbox in a container that runs as root.line 9
  2. What the tool list costs in every request.line 16
Run
python tools.py
You should see
Playwright 1.63.0: 24 tools, 20,013 characters
  browser_close                Close the page
  browser_resize               Resize the browser window
...
  browser_snapshot             Capture accessibility snapshot of the current page, this is 
  browser_click                Perform click on a web page
...
3

Drive ShopRung like an agent

Snapshots, refs and actions, from a script.

Create drive.py. It does what an agent does: navigate, take a snapshot (the page as an accessibility tree), find the ref of the element it wants, and act on that ref. ref() picks the ref from a snapshot line such as textbox "Email" [ref=e18]. The password field gets the secret's name, ALICE_PASSWORD; the server fills in the value from .env.test.

Run it. Every action prints the Playwright code it ran, with role-based locators, and the password appears as process.env['ALICE_PASSWORD'], not as text. browser_find reads only the matching part of the cart snapshot: the total is $75.00, so shipping was free.

drive.py
"""Drive ShopRung through Playwright MCP, step by step, like an AI agent would: navigate, read the snapshot,
pick refs, act. Prints what each tool returns and the Playwright code it ran.

    python drive.py
"""
import asyncio
import os
import re

from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client

BASE_URL = os.environ.get("BASE_URL", "http://localhost:8080")
SERVER = StdioServerParameters(command="npx", args=["playwright", "mcp", "--headless", "--isolated", "--secrets", ".env.test", *os.environ.get("MCP_EXTRA_ARGS", "").split()])


def text(result) -> str:
    return "\n".join(c.text for c in result.content if c.type == "text")


def ref(snapshot: str, pattern: str) -> str:
    """The ref of the first snapshot line that matches, for example 'textbox "Email"'."""
    m = re.search(pattern + r".*?\[ref=(\w+)\]", snapshot)
    if not m:
        raise LookupError(f"nothing like {pattern!r} in the snapshot")
    return m.group(1)


def code(result) -> str:
    m = re.search(r"```js\n(.*?)\n```", text(result), re.S)
    return m.group(1) if m else ""


async def main() -> None:
    async with stdio_client(SERVER) as (read, write), ClientSession(read, write) as s:
        await s.initialize()
        call = s.call_tool

        await call("browser_navigate", {"url": f"{BASE_URL}/#/login"})
        snap = login = text(await call("browser_snapshot", {}))
        print(f"login page snapshot: {len(snap)} characters")
        fields = [
            {"name": "Email", "type": "textbox", "target": ref(snap, r'textbox "Email"'), "value": "alice@shoprung.test"},
            {"name": "Password", "type": "textbox", "target": ref(snap, r'textbox "Password"'), "value": "ALICE_PASSWORD"},
        ]
        print(code(await call("browser_fill_form", {"fields": fields})))
        print(code(await call("browser_click", {"element": "Log in button", "target": ref(snap, r'button "Log in"')})))

        await call("browser_navigate", {"url": f"{BASE_URL}/#/product/8"})
        snap = text(await call("browser_snapshot", {}))
        print(code(await call("browser_click", {"element": "Add to cart", "target": ref(snap, r'button "Add to cart"')})))

        print(code(await call("browser_navigate", {"url": f"{BASE_URL}/#/cart"})))
        print(text(await call("browser_find", {"text": "Total"})).splitlines()[-4:])

        old = ref(login, r'button "Log in"')            # a ref from the login page, two pages ago
        print(f"click old ref {old}:", text(await call("browser_click", {"element": "Log in button", "target": old})).splitlines()[:3])


if __name__ == "__main__":
    asyncio.run(main())
  1. Secret names in, values filled by the server.line 14
  2. An agent reads the snapshot and picks a ref; this does the same with a pattern.line 21
  3. The name of the secret, not the password.line 44
  4. Cheaper than reading a whole snapshot when you need one value.line 54
Run
python drive.py
You should see
login page snapshot: 1785 characters
await page.getByRole('textbox', { name: 'Email' }).fill('alice@shoprung.test');
await page.getByRole('textbox', { name: 'Password' }).fill(process.env['ALICE_PASSWORD']);
await page.getByRole('button', { name: 'Log in' }).click();
await page.getByRole('button', { name: 'Add to cart' }).click();
await page.goto('http://localhost:8080/#/cart');
['        - generic [ref=e169]: Total', '        - generic [ref=e170]: $75.00', '      - button "Place order" [ref=e171] [cursor=pointer]', '  - alert [ref=e121]: Added to cart']
click old ref e21: ['### Error', 'Error: Ref e21 not found in the current page snapshot. Try capturing new snapshot.']
4

Refs belong to one snapshot

Understand the stale-ref error agents hit.

The last line of the output is on purpose: drive.py clicks the Log in button's ref from the login page, two pages later. The server answers "Ref e21 not found in the current page snapshot. Try capturing new snapshot." Refs are handed out per snapshot, and the page changed. An agent must take a new snapshot after every navigation or change, which is why each action returns the page state.

Try it in your AI tool too: ask it to click something "from before" after navigating. A good agent snapshots again; a confused one retries the old ref.

5

Turn the session into a test

Reviewed code with real assertions.

Create playwright.config.ts and tests/free-shipping.spec.ts. The steps are the code drive.py printed, with three review changes: relative URLs with baseURL, a data reset at the start, and assertions the session never made: Alice is logged in, the mug was added, and the cart shows subtotal $75.00, shipping Free and total $75.00 (PRICE-9: free shipping from $75.00).

The password comes from the same environment variable. Run the test.

playwright.config.ts
import { defineConfig } from '@playwright/test';

export default defineConfig({
  testDir: 'tests',
  use: { baseURL: process.env.BASE_URL ?? 'http://localhost:8080' },
});
tests/free-shipping.spec.ts
import { test, expect } from '@playwright/test';

// Recorded with Playwright MCP (drive.py), then reviewed: relative URLs, a data reset and real assertions.
test('a $75.00 cart ships free (PRICE-9)', async ({ page, request }) => {
  await request.post('/api/test/reset');
  await page.goto('/#/login');
  await page.getByRole('textbox', { name: 'Email' }).fill('alice@shoprung.test');
  await page.getByRole('textbox', { name: 'Password' }).fill(process.env['ALICE_PASSWORD']!);
  await page.getByRole('button', { name: 'Log in' }).click();
  await expect(page.getByText('Hi, Alice Shah')).toBeVisible();

  await page.goto('/#/product/8'); // Quiet Mechanical Keyboard, $75.00
  await page.getByRole('button', { name: 'Add to cart' }).click();
  await expect(page.getByRole('alert')).toHaveText('Added to cart');

  await page.goto('/#/cart');
  await expect(page.getByTestId('subtotal')).toHaveText('$75.00');
  await expect(page.getByTestId('shipping')).toHaveText('Free');
  await expect(page.getByTestId('total')).toHaveText('$75.00');
});
  1. An agent session starts from whatever state it finds. A test cannot.line 5
  2. The assertion is the reviewer's job: the rule, written down.line 18
Run
ALICE_PASSWORD='Alice123!' npx playwright test
You should seeyour text will differ: the model writes it
[1/1] tests/free-shipping.spec.ts:4:5 › a $75.00 cart ships free (PRICE-9)
  1 passed (1.2s)
6

Prove it catches the bug

See the new test fail once.

A test nobody has seen fail is not finished. Switch on ShopRung's free-shipping-boundary bug (free shipping only above $75.00) and run the test again: it fails on the shipping line with "Free" expected and "$4.99" received. Turn the bug off. Your agent session never had an opinion about shipping; the reviewed test does.

Run
curl -s -X POST http://localhost:8080/api/test/bugs -H "Content-Type: application/json" -d '{"enabled":["free-shipping-boundary"]}'
ALICE_PASSWORD='Alice123!' npx playwright test
curl -s -X POST http://localhost:8080/api/test/bugs -H "Content-Type: application/json" -d '{"enabled":[]}'
You should see
    Error: expect(locator).toHaveText(expected) failed

    Locator:  getByTestId('shipping')
    Expected: "Free"
    Received: "$4.99"
...
  1 failed

Check it works

python tools.py lists 24 tools; python drive.py prints the Playwright code with process.env['ALICE_PASSWORD'] (never the password) and a total of $75.00; the test passes on a normal ShopRung and fails with free-shipping-boundary on.

Search your terminal output for Alice123!: it should appear only in the command you typed, never in anything drive.py printed.

Test
python drive.py | grep -c "Alice123!"
You should see
0

Troubleshooting

"Running as root without --no-sandbox is not supported" in the tool output.

You are in a container running as root. Run with MCP_EXTRA_ARGS=--no-sandbox (only there; keep the sandbox on your own machine).

LookupError: nothing like 'textbox "Email"' in the snapshot.

The page did not load: ShopRung is not running, or BASE_URL points elsewhere. Set BASE_URL=http://localhost:PORT.

Invalid input: expected string, received undefined → at target.

Your Playwright version uses target for refs (1.63); older examples use ref. Pin @playwright/test to 1.63.0 as in package.json.

Your AI tool does not show the playwright server.

Check the file name and location your tool expects (.mcp.json, .vscode/mcp.json or .cursor/mcp.json) and restart it in the project folder.

The spec fails on "Hi, Alice Shah".

ALICE_PASSWORD is not set in that terminal. Set it as in step 5.

What changes in production

  • Teams use Playwright MCP to explore features and reproduce bugs with an agent, then keep reviewed Playwright tests in CI, which run without any model.
  • MCP servers are configured per project in version control, with secrets in ignored files or a secrets manager, never in prompts.
  • Unsafe tools (evaluate, run code) require approval; agents run against test environments and test accounts only.
  • Playwright is pinned, because tool names and arguments change between versions.

Interview angle

“How would you use an AI agent with Playwright MCP in a test team?”

For exploration and drafting. The agent reads accessibility snapshots, acts on refs, and every action returns the Playwright code it ran. I configure the server per project with an isolated profile and a secrets file, so passwords never enter the conversation, and require approval for the tools that run arbitrary code. Then I turn the session into a reviewed test: relative URLs, a data reset, and the assertions the agent never made. On our shop that test passed and failed as it should when the free-shipping bug was on.

Clean up

Practice

These run in your browser and check your answer.

Find a ref in a snapshot

Write find_ref(snapshot, role, name) that returns the ref of the first line with that role and quoted name, like button "Log in" [ref=e21] → "e21", or None if there is none.

Exercise
def find_ref(snapshot, role, name):
    for line in snapshot.splitlines():
        if name in line:
            return line.split("ref=")[1].rstrip("]")
    return None
Hint

Use a regular expression: re.escape(role) + ' "' + re.escape(name) + '".*?\[ref=(\w+)\]'.

The full project

Every file from this lab, as it is after the last step.

Download Playwright MCP project (.zip)