Playwright MCP: Browser Automation for AI Agents

By Updated

What is 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 requests. Instead of an image, the agent gets a structured accessibility snapshot with references to page elements. As of November 29, 2026 the current version is 0.0.86, the license is Apache-2.0, and it needs Node.js 20 or newer.

TL;DR

  • -Playwright MCP gives an agent a browser. The agent reads the page's accessibility tree and addresses elements by ref; screenshots are for visual checks.
  • -Setup: claude mcp add playwright -- npx -y @playwright/[email protected] --isolated or codex mcp add playwright -- npx -y @playwright/[email protected] --isolated. Pin the version: the package is still 0.0.x.
  • -In the author's test, a full snapshot of one article took 17,572 tokens (o200k_base), 4,325 with depth 4, and a browser_find search took 1,515. Navigation returns only a link to a snapshot file: 126-138 tokens. Codex finished the same task in 26 seconds, Claude Code on Sonnet 5.5 in 23.
  • -The Playwright team recommends Playwright CLI with skills for coding agents. They keep MCP for long agentic loops where continuous browser context matters.
  • -Playwright MCP is not a security boundary, and neither is --allowed-origins: in the author's test the flag blocked direct navigation to a disallowed address but let through a 302 redirect from an allowed one. Snapshots also include text a person can't see: opacity:0, white 1px, an off-screen block, aria-hidden.

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:

# Claude Code
claude mcp add playwright -- npx -y @playwright/[email protected] --isolated
# Codex
codex mcp add playwright -- npx -y @playwright/[email protected] --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.

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:

- 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.

Installing in Claude Code and Codex

Claude Code

You need Node.js 20+ and the client (how to install Claude Code).

claude mcp add playwright -- npx -y @playwright/[email protected] --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:

[mcp_servers.playwright]
command = "npx"
args = ["-y", "@playwright/[email protected]", "--isolated"]
disabled_tools = ["browser_run_code_unsafe"]
startup_timeout_sec = 30

Per the Codex documentation, 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/[email protected] --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, 0.0.82 to 0.0.86, and the tool set changed.

Modes: persistent, isolated, extension, headless

ModeHow to enableWhat happensWhen to use it
Persistentdefaultprofile on disk, logins and cookies persist; each project has its own directoryrepeated work with one site
Isolated--isolatedprofile in memory, lost when the browser closes; initial state via --storage-statechecks, a clean environment, several clients at once
Extension--extensionconnects to your open Chrome or Edge through an extensiona site where you’re already logged in
CDP--cdp-endpointconnects to a running browser over Chrome DevTools Protocolyour 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.

GroupToolsWhat it adds
Default25navigation, clicks, forms, tabs, snapshots, screenshots, console, read-only network, theme emulation
network4mocking API responses, offline mode
storage17cookies, localStorage, sessionStorage, saving state
devtools13tracing, video, action recording, highlighting
vision6mouse by coordinates
testing5visibility and value assertions, locator generation
pdf1saving a page as PDF
config1reading 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.

CallPageResponse tokens
browser_navigateexample.com66
browser_navigatefuturecraft.pro, two pages126-138
browser_navigate with --snapshot-mode nonearticle111
browser_snapshothome page /ru/4,901
browser_snapshotprompt caching article17,572
browser_snapshot, depth: 4same article4,325
browser_find for “Цена” (price), 5 matchessame article1,515
browser_evaluate, list of h2same article194
browser_take_screenshot, PNGarticle108 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: 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.

CodexClaude Code 2.1.322
Modelgpt-6.2-solSonnet 5.5
Time26 s23 s
Stepsnavigate, find, click, snapshot (depth: 7)ToolSearch, navigate, snapshot, click, Bash (grep over the snapshot file), snapshot
Input197,275, of which 173,824 cached16 uncached, 30,865 cache write, 245,582 cache read
Output3041,049
Answerfirst in the “Most read” blocktop 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: 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.

npm install -g @playwright/[email protected]
playwright-cli install --skills
Playwright MCPPlaywright CLI
How the agent actscalls MCP tools with a schemaruns playwright-cli commands
What the client needsMCP supportshell access
Window by defaultyesno
Profile by defaulton diskin memory, --persistent writes to disk
Token use per the teamhigherlower
Loaded into context upfronttool definitionsskill 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.

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 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 isIn the snapshot
button aria-labelyes
image altyes
opacity: 0yes
white text, 1pxyes
off-screen block (left: -9999px)yes
element with aria-hidden="true"yes
display: noneno
HTML commentno

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 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, “will only be called for the first url if the response is a redirect”, and it doesn’t see 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 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 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:

{
  "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.

Common errors

SymptomCauseFix
Two clients conflict in one projectshared persistent profile--isolated or a separate --user-data-dir
Claude Code rejects -y or --isolatedno -- before npxadd the separator
Browser not foundthe channel isn’t installednpx @playwright/[email protected] install-browser chrome
Ref ... not foundpage changed after the snapshotnew snapshot or browser_find
net::ERR_BLOCKED_BY_CLIENTan origin list firedcheck --allowed-origins and --blocked-origins
Login disappeared--isolated and the browser closed--storage-state with a test account
Tab unavailable in extension modeanother extension’s frame or chrome://disable that extension on the site or use a clean profile
Codex doesn’t see tools on the first turnserver didn’t start in timewarm 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/[email protected] 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.

Frequently Asked Questions

How is Playwright MCP different from regular Playwright?
Playwright is a library and test runner: you write code, and it runs the same way every time. Playwright MCP exposes browser capabilities to an agent as tools, and the model decides what to call at each step. The first gives you a test in your repository, the second a finished task or a problem found.
How do I install Playwright MCP in Claude Code?
Run claude mcp add playwright -- npx -y @playwright/[email protected] --isolated. The double dash separates Claude Code flags from server flags; without it, Claude Code tries to read -y and --isolated itself. Check with claude mcp list in the terminal or /mcp in a session. You need Node.js 20+.
How do I install Playwright MCP in Codex?
Run codex mcp add playwright -- npx -y @playwright/[email protected] --isolated, or add an [mcp_servers.playwright] table to ~/.codex/config.toml. The server shows up in codex mcp list and in /mcp inside a session. If npx is downloading the package for the first time, the server may not start in time; raise startup_timeout_sec (10 seconds by default).
Does Playwright MCP run headed or headless?
Headed by default. The --headless flag runs it without a window, which you need on a server or in CI. As of November 29, 2026 the official Docker image supports headless Chromium only.
Playwright MCP or Playwright CLI: which should I choose?
For a coding agent with shell access, the Playwright team recommends the CLI with skills: commands are shorter and tool schemas stay out of the context. MCP suits clients without a shell, long exploratory sessions, and cases where you grant permissions per tool. The team doesn't publish token numbers.
How many tokens does Playwright MCP use?
In the author's test on version 0.0.86 (o200k_base tokenizer, one machine, one run each), the 25 tool definitions took 4,640 tokens, a full article snapshot 17,572, a home page snapshot 4,901, and a browser_find search 1,515. The pages were in Russian. Numbers for Claude will differ because it has its own tokenizer.
Is it safe to give an agent Playwright MCP?
The README says plainly that Playwright MCP is not a security boundary. Page text, including some that users can't see, lands in the snapshot and may contain instructions. In the author's test a redirect bypassed the --allowed-origins list, and the README calls browser_run_code_unsafe RCE-equivalent. The minimum: --isolated, a deny on the unsafe tool (in Claude Code this removes it from the list; 24 of 25 remained in the test), no logged-in profiles, and network restrictions outside the server.