# Playwright MCP: Browser Automation for AI Agents

> Set up Playwright MCP in Claude Code and Codex: profile modes, 25 tools, snapshot sizes in tokens, what --allowed-origins misses, and when the CLI fits better.
> Author: Roman Belov · Published: 2026-11-17 · Source: https://futurecraft.pro/blog/playwright-mcp/

Playwright MCP is Microsoft's MCP server that lets an AI agent drive a real browser: open pages, click, fill in forms, read the console and network. Instead of an image, the model gets a structured snapshot of the accessibility tree, where elements carry `ref` handles for actions. One command connects it:

```bash
# Claude Code
claude mcp add playwright -- npx -y @playwright/mcp@0.0.86 --isolated
# Codex
codex mcp add playwright -- npx -y @playwright/mcp@0.0.86 --isolated
```

First check that it fits. For agents that code and run terminal commands, the Playwright team recommends Playwright CLI with skills. MCP remains for clients without a shell, long exploratory sessions, and per-tool permissions. For MCP itself, see [MCP servers explained](https://futurecraft.pro/blog/mcp-servers-explained/).

**How the numbers were obtained.** "Author's test" means a run on November 29, 2026: `@playwright/mcp` 0.0.86, `--headless --isolated --browser chrome`, one machine, one run each. Calls went through a client on the Python SDK `mcp` 2.3.0; the redirect and invisible-text experiments used two local pages. Codex and Claude Code did one task each; in Claude Code the server ran with the same flags. Response sizes use the o200k_base tokenizer, so numbers for Claude will differ.

## What Playwright MCP does

The server reads the accessibility tree that browsers build for screen readers. A snapshot keeps roles, labels and text, and interactive elements get refs. An example from the [documentation](https://playwright.dev/docs/getting-started-mcp):

```yaml
- heading "todos" [level=1]
- textbox "What needs to be done?" [ref=e5]
- listitem:
  - checkbox "Toggle Todo" [ref=e10]
```

The model calls `browser_type` with target `e5`, no coordinates to guess. A ref is valid only for the current snapshot: in the author's test, clicking a nonexistent `e99999` returned `Ref e99999 not found in the current page snapshot. Try capturing new snapshot.`

The blind spot: canvas and custom widgets without roles are missing from the tree or show up empty. For those, the `vision` group clicks by coordinates.

Playwright MCP doesn't replace a test framework. A test repeats the same steps, while here the model decides anew on every run. Mobile regression has its own tools, like [Maestro for Flutter](https://futurecraft.pro/blog/maestro-flutter-e2e-testing/).

## Installing in Claude Code and Codex

### Claude Code

You need Node.js 20+ and the client ([how to install Claude Code](https://futurecraft.pro/blog/install-claude-code/)).

```bash
claude mcp add playwright -- npx -y @playwright/mcp@0.0.86 --isolated
claude mcp list
```

Everything after `--` goes to the server untouched. The README command has neither separator nor flags; with `-y` or `--isolated` the separator is required. By default only you see the server, in the current project. `--scope project` writes it to `.mcp.json` for the team.

### Codex

Use `codex mcp add` as above or a table in `~/.codex/config.toml`:

```toml
[mcp_servers.playwright]
command = "npx"
args = ["-y", "@playwright/mcp@0.0.86", "--isolated"]
disabled_tools = ["browser_run_code_unsafe"]
startup_timeout_sec = 30
```

Per the [Codex documentation](https://learn.chatgpt.com/docs/extend/mcp), a server gets 10 seconds to start, and Codex waits 1,000 ms for optional servers when building the first tool list. Download the package ahead of time: `npx -y @playwright/mcp@0.0.86 --help`. The 30 is a margin; cold start wasn't measured. Non-interactive `codex exec` rejects tool calls by default, and `claude -p` needs permission too, for example `--allowedTools`.

### Why the version is pinned

The docs use `@latest` everywhere, but the package is still 0.0.x and depends on an alpha build of the core (`playwright` 1.66.0-alpha-2026-11-18, with 1.65.1 as stable). From September 18 to November 18, 2026 it had five [releases](https://github.com/microsoft/playwright-mcp/releases), 0.0.82 to 0.0.86, and the tool set changed.

## Modes: persistent, isolated, extension, headless

| Mode | How to enable | What happens | When to use it |
|---|---|---|---|
| Persistent | default | profile on disk, logins and cookies persist; each project has its own directory | repeated work with one site |
| Isolated | `--isolated` | profile in memory, lost when the browser closes; initial state via `--storage-state` | checks, a clean environment, several clients at once |
| Extension | `--extension` | connects to your open Chrome or Edge through an extension | a site where you're already logged in |
| CDP | `--cdp-endpoint` | connects to a running browser over Chrome DevTools Protocol | your own container or a remote browser |

The window is a separate setting: visible by default, hidden with `--headless`. One browser at a time can use a persistent profile, so a second agent in the project needs `--isolated` or its own `--user-data-dir`.

A headless browser launched by the server closes after an hour without calls (`--idle-timeout`), which in isolated mode wipes the login. Headed, CDP and extension browsers don't close on their own.

## Tools and what --caps adds

In the author's test the server exposed 25 tools by default; their definitions (name, description, schema) took 4,640 tokens. With `--caps=vision,pdf,devtools,storage,network,testing` that became 71 tools and 9,969 tokens. The `config` group wasn't in that run. The breakdown is from the README; its sum matches the test.

| Group | Tools | What it adds |
|---|---|---|
| Default | 25 | navigation, clicks, forms, tabs, snapshots, screenshots, console, read-only network, theme emulation |
| `network` | 4 | mocking API responses, offline mode |
| `storage` | 17 | cookies, localStorage, sessionStorage, saving state |
| `devtools` | 13 | tracing, video, action recording, highlighting |
| `vision` | 6 | mouse by coordinates |
| `testing` | 5 | visibility and value assertions, locator generation |
| `pdf` | 1 | saving a page as PDF |
| `config` | 1 | reading the resolved configuration |

The README options table and `--help` list only vision, pdf and devtools for `--caps`. The other groups loaded too.

`browser_evaluate` runs JavaScript inside the page. `browser_run_code_unsafe` runs it in the server process on your machine; the README calls it "RCE-equivalent". It's on by default.

A site can also register its own tools through experimental WebMCP; they appear as `webmcp_<tool>`. The documentation says to treat their names, descriptions and results as untrusted. `--no-webmcp` turns them off.

## Snapshot or screenshot: the cost in tokens

The project publishes no token numbers, only qualitative statements. The snapshot pages in the author's test are Russian, so English text will give different counts.

| Call | Page | Response tokens |
|---|---|---|
| `browser_navigate` | example.com | 66 |
| `browser_navigate` | futurecraft.pro, two pages | 126-138 |
| `browser_navigate` with `--snapshot-mode none` | article | 111 |
| `browser_snapshot` | home page `/ru/` | 4,901 |
| `browser_snapshot` | prompt caching article | 17,572 |
| `browser_snapshot`, `depth: 4` | same article | 4,325 |
| `browser_find` for "Цена" (price), 5 matches | same article | 1,515 |
| `browser_evaluate`, list of h2 | same article | 194 |
| `browser_take_screenshot`, PNG | article | 108 of text plus an image of 193,896 base64 characters |

Navigation is cheap because the snapshot isn't in the response: the server writes it to a `.yml` file and returns a link. Per the 0.0.86 code, a snapshot arrives as text only on an explicit `browser_snapshot` without `filename`. That's why `--snapshot-mode none` saved almost nothing. The documentation still says that when a tool runs, "it returns a structured snapshot".

The real spending starts when the agent asks for a full snapshot. On the long article, `browser_find` returned 11.6 times fewer tokens, a `depth: 4` snapshot 4 times fewer, and a targeted `browser_evaluate` query 90 times fewer. The answers aren't equivalent: a list of h2 headings doesn't replace element refs, and `depth` hides everything below the chosen level. Different markup will shift the ratios.

Image cost in tokens wasn't measured: models count images differently.

Claude Code has [its own thresholds](https://code.claude.com/docs/en/mcp): a warning when an MCP tool response exceeds 10,000 tokens, a default limit of 25,000, and text longer than 50,000 characters goes to a file. The article snapshot would probably exceed the first. Tool definitions load on demand by default, so a session starts with names only.

### One task in Codex and Claude Code

The task: open the futurecraft.pro home page, go to the blog, name the first article. One run each.

| | Codex | Claude Code 2.1.322 |
|---|---|---|
| Model | gpt-6.2-sol | Sonnet 5.5 |
| Time | 26 s | 23 s |
| Steps | navigate, find, click, snapshot (`depth: 7`) | ToolSearch, navigate, snapshot, click, Bash (grep over the snapshot file), snapshot |
| Input | 197,275, of which 173,824 cached | 16 uncached, 30,865 cache write, 245,582 cache read |
| Output | 304 | 1,049 |
| Answer | first in the "Most read" block | top of the main list |

The models and token counters differ, so don't compare prices. Input tokens add up over every model call and include the client's system portion, so browser responses are only part of them. The Claude Code run cost an estimated $0.1585 at API prices.

The page has both blocks, and "first article" fits either. Ask for something exact, like "newest by date".

## Playwright MCP vs Playwright CLI with skills

The Playwright MCP README opens by pointing to another product. Coding agents "might benefit" from [Playwright CLI](https://github.com/microsoft/playwright-cli): CLI calls are "more token-efficient" because tool schemas and long accessibility trees stay out of the context. MCP is kept for agentic loops with persistent state: exploratory automation, self-healing tests, long autonomous work.

```bash
npm install -g @playwright/cli@0.1.25
playwright-cli install --skills
```

| | Playwright MCP | Playwright CLI |
|---|---|---|
| How the agent acts | calls MCP tools with a schema | runs `playwright-cli` commands |
| What the client needs | MCP support | shell access |
| Window by default | yes | no |
| Profile by default | on disk | in memory, `--persistent` writes to disk |
| Token use per the team | higher | lower |
| Loaded into context upfront | tool definitions | skill description, commands as needed |

Claude Code defers MCP tool definitions, and server 0.0.86 already writes post-action snapshots to files. How far that closes the gap is unmeasured: the CLI wasn't in the test.

How to choose:

- **CLI** if the agent already works in a terminal and needs the browser to verify a change: the default for Claude Code and Codex.
- **MCP** if the client has no shell or shouldn't have one.
- **MCP** if you need per-tool permissions: denying `browser_run_code_unsafe` and asking before a file upload is easier than filtering command strings.
- **MCP** for long exploration of one application with reasoning over page structure.
- **Plain Playwright Test** for tests in CI. An agent can help write them, but they should run without a model.

The general protocol-or-direct-call choice is covered in [MCP vs API](https://futurecraft.pro/blog/mcp-vs-api/).

## Security: where the boundaries are

The README's Security section says one thing that matters: "Playwright MCP is **not** a security boundary". The guardrails below catch agent mistakes, not a targeted attack.

### Injection from the page

A snapshot enters the context as plain text, so instructions for the agent can sit right on the page. In March 2026 someone filed [issue 1479](https://github.com/microsoft/playwright-mcp/issues/1479) with an example: a command hidden in the `aria-label` of a block pushed off screen. Ten days later a project member closed it with a pointer to the Security section. Protection is up to whoever connects the server.

Which text reaches `browser_snapshot`, per the author's test on a marked local page (one run):

| Where the text is | In the snapshot |
|---|---|
| button `aria-label` | yes |
| image `alt` | yes |
| `opacity: 0` | yes |
| white text, 1px | yes |
| off-screen block (`left: -9999px`) | yes |
| element with `aria-hidden="true"` | yes |
| `display: none` | no |
| HTML comment | no |

Whether a model would follow such an instruction wasn't tested, so this isn't a successful injection. But a page clean to you may not be clean to an agent. The [MCP security guide](https://futurecraft.pro/blog/mcp-security-guide/) covers the general threat model.

### What --allowed-origins does and doesn't do

**Does.** In the author's test with `--allowed-origins https://example.com`, navigating to futurecraft.pro failed with `net::ERR_BLOCKED_BY_CLIENT`. `--blocked-origins https://futurecraft.pro` gave the same result.

**Doesn't.** The README says of both flags: "*does not* serve as a security boundary and *does not* affect redirects". The 0.0.86 code shows why: both use Playwright's own request interception. Its handler, per the [documentation](https://playwright.dev/docs/api/class-page#page-route), "will only be called for the first url if the response is a redirect", and it [doesn't see](https://playwright.dev/docs/api/class-browsercontext#browser-context-route) requests intercepted by a Service Worker.

The test agreed. Two pages ran on `127.0.0.1` on different ports, hence different origins, and only the first was allowed. Direct navigation to the second gave `net::ERR_BLOCKED_BY_CLIENT`. An address on the first that answers 302 to the second went through: `location.href` pointed to the forbidden page, and `browser_evaluate` read its text. One open redirect on an allowed site is enough. A Service Worker bypass wasn't tested.

Treat the flag as a fence and get isolation from a proxy, firewall or container network. Side effect: it blocks every request to unlisted origins, including CDNs and fonts, so layout may break.

`--allowed-hosts` is unrelated: it checks the host names the MCP server answers to over HTTP. The README's Docker service example listens on `0.0.0.0` with `--no-sandbox`. Before copying it, check who can see the port.

### Profiles, cookies and files

- A persistent profile keeps logins on disk. Don't open banking, email or admin panels through it.
- A `--storage-state` file contains sessions. The [Playwright documentation](https://playwright.dev/docs/auth) advises keeping such files in `.gitignore`.
- `--caps=storage` lets the model read and change cookies. Enable it per task.
- `--secrets` and `--redact-url-params` mask values in responses. The README calls them a convenience, "not a security feature".
- File access is limited to the workspace; navigating to `file:///etc/hosts` was rejected in the test: `Access to "file:" protocol is blocked`. A comment on the setting says this isn't "a secure boundary" either.
- In [extension mode](https://github.com/microsoft/playwright/tree/main/packages/extension) the client controls only its own tabs but can read cookies across the browser. Treat the token that skips the connection prompt like a password.

### Denying tools in Claude Code

In `.claude/settings.json`, per the [permissions documentation](https://code.claude.com/docs/en/permissions):

```json
{
  "permissions": {
    "deny": ["mcp__playwright__browser_run_code_unsafe"],
    "ask": [
      "mcp__playwright__browser_evaluate",
      "mcp__playwright__browser_file_upload"
    ]
  }
}
```

Rules are checked in order: deny, ask, allow. The `playwright` part matches the name you added the server under. Claude Code skips `mcp__` rules with parentheses in a settings file, so you can't restrict by URL this way. In the Claude Code test, the deny rule passed through `--disallowedTools` removed the tool: the model saw 24 instead of 25. Not tested: the settings file, `ask`, or `disabled_tools` in Codex.

## Where it's useful

**Checking a change.** "Open localhost:4321, show console errors and failed network requests, don't take a full snapshot". On futurecraft.pro, `browser_console_messages` found a broken analytics script in the test: `ERR_NAME_NOT_RESOLVED`, and the script's host had no public DNS record.

**A form.** "Fill in the signup form with test data, submit an empty email, quote the error text". This uses `browser_fill_form` and `browser_find`.

**Dark theme and phone.** `browser_emulate_media` switches the theme on the fly; `--device` and `--mobile` set the device at launch. Layout needs a screenshot: snapshots don't show color.

**API error.** With `--caps=network` the agent replaces a response with a 500 and looks at what the user would see.

It isn't meant for mass scraping: every step goes through the model. For other servers, see the [best MCP servers](https://futurecraft.pro/blog/best-mcp-servers-2026/).

## Common errors

| Symptom | Cause | Fix |
|---|---|---|
| Two clients conflict in one project | shared persistent profile | `--isolated` or a separate `--user-data-dir` |
| Claude Code rejects `-y` or `--isolated` | no `--` before npx | add the separator |
| Browser not found | the channel isn't installed | `npx @playwright/mcp@0.0.86 install-browser chrome` |
| `Ref ... not found` | page changed after the snapshot | new snapshot or `browser_find` |
| `net::ERR_BLOCKED_BY_CLIENT` | an origin list fired | check `--allowed-origins` and `--blocked-origins` |
| Login disappeared | `--isolated` and the browser closed | `--storage-state` with a test account |
| Tab unavailable in extension mode | another extension's frame or `chrome://` | disable that extension on the site or use a clean profile |
| Codex doesn't see tools on the first turn | server didn't start in time | warm up npx, set `required = true` |

`Ref` and `ERR_BLOCKED_BY_CLIENT` come from the test, the rest from documentation.

## Where to start

1. If the agent works in a terminal, try Playwright CLI with skills first.
2. Connect `@playwright/mcp@0.0.86` with `--isolated`, no `--caps`.
3. Deny `browser_run_code_unsafe` before the first run.
4. Have the agent open your local build and return console errors.
5. Add a project rule: `browser_find` first, full `browser_snapshot` when needed.
6. For untrusted sites, use a container with a restricted network.
