Toggle Theme

Playwright MCP Guide: Let Claude, Codex, and Cursor Control the Browser

Easton editorial illustration: central laptop with split code diff and rendered browser viewport, stacked screenshot evidence card with a visible check mark

"The official Playwright MCP documentation explains that the server exposes browser automation through structured accessibility snapshots and labels browser_run_code_unsafe as an RCE-equivalent high-risk tool."

You add [mcp_servers.playwright] to .codex/config.toml, run codex, and the browser really does open. Then the AI refuses to call the browser tools, or it opens the page but cannot find the button in the navigation bar. This guide gives you the complete setup paths for Claude Code, Codex, and Cursor, a first-run validation checklist, and the browser permissions you should not hand to AI casually.


What Playwright MCP Is

Playwright MCP is the Microsoft-maintained MCP server that exposes Playwright’s browser automation through Model Context Protocol to AI coding tools. Its core mechanism is not screenshot recognition. It works with the accessibility tree, giving the AI a structured view of the page so it can find buttons, links, input fields, and other interactive elements.

Core Capabilities and Tool List

Playwright MCP covers the main browser automation scenarios:

  • Navigation: open URLs, go back and forward, refresh
  • Clicking and input: click elements, fill forms, use the keyboard
  • Screenshots and snapshots: take page screenshots and read accessibility snapshots
  • Dialogs and tabs: handle alert/confirm/prompt dialogs and manage tabs
  • Network and console: inspect network requests and capture console logs
  • Storage state: save and restore cookies, localStorage, and sessionStorage

Those capabilities let it handle anything from a simple page click to a complex form submission flow.

How It Differs from Playwright CLI/SKILLS

The Microsoft README draws a clear trade-off between two routes:

  • The MCP route: better for persistent state, richer introspection, and a continuing browser context, such as exploratory automation, self-healing tests, or long-running tasks. The cost is that tool schemas and the accessibility tree enter the model context and consume tokens.
  • The CLI + SKILLS route: better for high-throughput code workflows with a smaller context footprint, but you need to call Playwright through commands or scripts.

If you already use an MCP-capable AI coding tool such as Claude Code, Codex, or Cursor, Playwright MCP is the most direct way to bring browser tools into that existing workflow.

How It Differs from Browser Use

Browser Use is a Python agent loop. You write Python code against its API, and the agent decides which browser actions to take from a prompt. Playwright MCP is different: it does not provide the agent loop. It provides the browser tool layer and lets your existing MCP client, such as Claude Code, Codex, or Cursor, decide when to call browser tools.

If you are a Python developer who wants a quick browser-agent starting point, read the Browser Use beginner tutorial on using AI to open pages, click buttons, and extract information. If you already work inside an MCP client and want browser capability in that tool, this guide helps you install, verify, and secure Playwright MCP.

Not a Replacement for a Test Framework

Playwright MCP is not a replacement for the Playwright test framework. It is useful for exploratory automation and frontend acceptance checks, but a stable E2E test suite still needs Playwright test scripts because tests need determinism, repeatability, and maintainability. AI-driven browser actions are not fully controllable. If you are interested in browser-mode testing, see Vitest Browser Mode.


Configure Playwright MCP in Claude Code

Prerequisites

Claude Code needs Node.js 18+ to run Playwright MCP. Check your Node version:

node --version

If it is below 18, upgrade Node.js first.

Add Command

Claude Code provides a dedicated MCP management command. Run this from your project root:

claude mcp add playwright npx @playwright/mcp@latest

This registers the Playwright MCP server in Claude Code. Use @playwright/mcp@latest; do not copy older community package names such as @executeautomation/playwright-mcp-server.

Project-Level .mcp.json

If you want to share the Playwright MCP configuration with teammates, create .mcp.json in the project root:

{
  "mcpServers": {
    "playwright": {
      "command": "npx",
      "args": ["@playwright/mcp@latest"],
      "env": {
        "BROWSER_PATH": "/usr/bin/chromium"
      }
    }
  }
}

When Claude Code discovers a project-level .mcp.json, it asks for approval. That protects you from a project silently adding an untrusted MCP server.

Environment Variable Expansion

.mcp.json supports environment variable expansion for machine-specific paths and sensitive values:

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

Tool Search and Output Token Management

Claude Code enables MCP Tool Search by default, which lazy-loads tools and reduces context usage. When MCP output is large, Claude Code also applies token management, with a default maximum output of 25,000 tokens. If the AI does not use browser tools, check:

  1. Whether the MCP server started correctly by reading the Claude Code logs
  2. Whether Tool Search is enabled, which it is by default in Claude Code
  3. Whether Node.js is version 18 or newer

Configure Playwright MCP in Codex

OpenAI Codex supports MCP servers in both the CLI and the IDE extension, but its configuration differs from Claude Code.

Add Command

The Codex CLI provides an MCP management command:

codex mcp add playwright -- npx @playwright/mcp@latest

Codex uses -- to separate the server name from the actual server command.

Configuration File Location

Codex MCP configuration is stored in config.toml. There are two common locations:

  • User level: ~/.codex/config.toml, applied globally
  • Project level: .codex/config.toml in the project root, applied only to that project

The CLI and IDE extension share this configuration.

config.toml Snippet

For manual configuration, add this to config.toml:

[mcp_servers.playwright]
command = "npx"
args = ["@playwright/mcp@latest"]

If you need environment variables or tool approval settings, add:

env_vars = ["HOME", "STORAGE_STATE_PATH"]
approval_mode = "prompt"

Tool Approval Modes

Codex provides three tool approval modes:

  • approval_mode = "allow": execute all tool calls automatically
  • approval_mode = "prompt": ask for user confirmation before each tool call
  • approval_mode = "deny": deny all tool calls

For high-risk Playwright MCP tools such as browser_run_code_unsafe, use:

[mcp_servers.playwright]
command = "npx"
args = ["@playwright/mcp@latest"]
disabled_tools = ["browser_run_code_unsafe"]
approval_mode = "prompt"

This prevents high-risk tools from running automatically and keeps sensitive actions behind human approval.

HTTP Server Support

Codex supports two MCP server types:

  • STDIO server: local process communication, useful for tools that need local system access, such as Playwright MCP
  • HTTP server: supports bearer tokens and OAuth authentication

Playwright MCP uses STDIO, so you do not need HTTP configuration for the default setup.


Configure Playwright MCP in Cursor

Cursor configures MCP through the Settings UI, unlike the command-line paths used by Claude Code and Codex.

UI Setup Steps

According to the Playwright official documentation, the Cursor setup is:

  1. Open Cursor Settings with Cmd+, or from the Settings menu
  2. Go to the MCP settings page, Settings -> MCP
  3. Click “Add new MCP Server”
  4. Fill in the configuration:
    • Server name: playwright
    • Command type: npx
    • Command: @playwright/mcp@latest

Standard Parameter Configuration

Cursor’s MCP server configuration can use Playwright MCP’s standard parameters:

  • --headless: run without a visible browser window; during development, headed mode is easier to debug
  • --browser: choose the browser, such as chrome/firefox/webkit/msedge
  • --output-dir: set the output directory path
  • --storage-state: set the login-state file path

The full parameter list appears in the standard configuration table below.

Configuration References

Cursor’s MCP documentation is available in the Cursor docs. Treat the Playwright official docs and Microsoft README as the source of truth for Playwright MCP details, and make sure you use the official package name @playwright/mcp@latest.


Standard Configuration Parameter Table

Playwright MCP provides several parameters for browser behavior, safety boundaries, and output management.

ParameterPurposeDefaultSafety note
--headlessRun without showing a browser windowfalse (headed)Use headed mode during development so you can observe browser actions
--browserChoose the browser typechromeOptions include chrome, firefox, webkit, and msedge
--allowed-originsList of allowed originsUnlimitedNot a security boundary; it does not affect redirects and cannot protect sensitive sites by itself
--blocked-originsList of blocked originsNoneNot a security boundary, same caveat as above
--isolatedIsolated mode; each session uses a separate profilefalseRecommended for concurrent clients or multiple projects
--storage-stateSpecify a login-state file pathNoneSaves cookies and localStorage; be careful with real accounts
--output-dirOutput directory for screenshots, logs, and related filesNoneSet a path so results are easy to find
--save-sessionSave session statefalseUse with a persistent profile
--snapshot-modeAccessibility snapshot modedefaultControls snapshot detail
--allow-unrestricted-file-accessAllow unrestricted file accessfalseHigh risk; enable only when you understand the impact
--secretsSecret configuration through environment variables or filesNoneUsed for sensitive information management

Key reminder: the official docs state that --allowed-origins and --blocked-origins are not security boundaries and do not affect redirects. If you need to restrict where the AI can browse, do not rely on those flags alone.


Three Profile Modes Compared

Playwright MCP supports three profile modes, which affect login-state persistence, concurrency, and security boundaries.

ModeLogin-state persistenceProfile pathConcurrencyGood fitSafety advice
persistentSaves cookies, localStorage, and related statemacOS: ~/Library/Caches/ms-playwright/mcp-{channel}-{workspace-hash}One profile can be used by only one browser instance at a timeLong tasks where the AI needs to remember login stateDo not use a real account by default; start with a test account
isolatedDoes not persist state; each session is independentTemporary directory, cleaned up per sessionSupports concurrent clients or multiple projectsTests, exploration, and tasks that do not need login stateRecommended as the production default
browser extensionPersists depending on the browserBrowser extension directoryDepends on the browserConnecting to an existing browser sessionAdvanced use; understand the browser extension security model first

Limits of a Persistent Profile

One persistent profile can be used by only one browser instance at a time. If you need concurrent clients or multiple projects using Playwright MCP at the same time, you need to:

  • Use --isolated mode
  • Or configure a different --user-data-dir for each client

Example persistent profile path on macOS:

~/Library/Caches/ms-playwright/mcp-chrome-a1b2c3d4

The {workspace-hash} part is generated from the project, so different projects use different profiles.

Login State and Security Boundaries

A persistent profile saves cookies, localStorage, and sessionStorage. The AI can access the login state stored in that browser. If you use a real account, it may be able to access personal data, payment information, and account settings.

Recommended practice:

  • Use --isolated in production so login state is not persisted
  • When the AI needs login state, use a test account instead of a real account
  • Do not let the AI automatically log into your real account or visit payment pages

Deeper login-state management belongs in a later article on AI browser login state. This guide only sets the boundary.


browser_run_code_unsafe Safety Warning

Security warning: browser_run_code_unsafe allows arbitrary Playwright scripts to run and is labeled RCE-equivalent by the official docs. Enable it only for fully trusted MCP clients. In production, disable it or require human approval through Codex’s approval_mode: prompt.

Playwright MCP includes a high-risk tool named browser_run_code_unsafe. It can execute arbitrary Playwright scripts in the browser context. The danger is straightforward:

  • If the MCP client is compromised or the AI behavior is not controlled, an attacker can use the tool to execute arbitrary code
  • The AI can read all browser data, including cookies, localStorage, sessionStorage, and personal data from signed-in accounts
  • If the browser is on a payment page or account settings page, the AI may read and leak sensitive information

Safety Configuration Recommendations

Production environment:

  1. Disable browser_run_code_unsafe:

    Add this to Codex’s ~/.codex/config.toml:

    [mcp_servers.playwright]
    command = "npx"
    args = ["@playwright/mcp@latest"]
    disabled_tools = ["browser_run_code_unsafe"]
  2. Or set approval mode:

    [mcp_servers.playwright]
    command = "npx"
    args = ["@playwright/mcp@latest"]
    approval_mode = "prompt"

    Then Codex will show a confirmation prompt before each browser_run_code_unsafe call, and you must approve it manually.

Development environment:

If you truly need browser_run_code_unsafe:

  • Enable it only in local development, not in production or against real accounts
  • Make sure you fully understand the script that will run
  • Do not let the AI generate and execute arbitrary scripts automatically; write the script yourself and let the AI run that known script

If you are new to Playwright MCP, do not start with browser_run_code_unsafe. Use safer Playwright MCP tools first, such as browser_click, browser_navigate, and browser_screenshot. Those tools have clearer boundaries and do not execute arbitrary code.


MCP Tools Safety Checklist

MCP lets AI call external tools, but connecting MCP does not mean letting the AI do anything automatically. You need safety controls on both the client side and the server side.

Client-Side Safety Recommendations

  1. Ask for user confirmation on sensitive actions: before calling browser_run_code_unsafe, visiting payment pages, changing account settings, or deleting data, ask the user to confirm. Do not let the AI run those high-risk operations automatically.

  2. Show tool inputs before execution: let the user see the exact parameters the AI is about to use. For example, if the AI will click a button, show the selector or coordinates and confirm that they are correct.

  3. Prevent malicious data leakage: inspect tool output so sensitive information such as passwords, tokens, or personal data is not read by the AI and sent elsewhere. If a tool returns sensitive data, do not let the AI write it to logs or external services.

  4. Set timeouts: browser operations can hang and consume resources or block other tasks. Set a reasonable timeout for each tool call, such as 30 seconds, and cancel automatically on timeout.

  5. Record tool usage: keep an operation log for audits and troubleshooting. Include the tool name, call time, input parameters, output result, and the user’s approval record.

  6. Verify tool results: check whether screenshots, console logs, and network requests match the expected result. If the AI says the click succeeded but the screenshot shows nothing changed, investigate.

Server-Side Safety Recommendations

If you build your own MCP server, rather than using the official Playwright MCP server, follow these recommendations:

  1. Validate inputs: validate URLs, selectors, and text input to prevent injection attacks. Do not let the AI pass a malicious URL or XSS payload unchecked.

  2. Control access: restrict reachable origins, file paths, and browser capabilities. For example, block access to internal IP ranges or sensitive paths.

  3. Rate limit: prevent the AI from calling tools so frequently that it exhausts resources or gets blocked by the target site. Set a reasonable limit, such as at most 10 calls per minute.

  4. Sanitize outputs: remove sensitive information before returning data to the AI. For example, do not return full cookie strings when only a small derived result is needed.


First Verification Task and Acceptance Checklist

After configuration, use a simple task to verify that Playwright MCP is wired correctly.

Example Task

Ask the AI to open your local preview page at http://localhost:4321, click the navigation menu, take a screenshot, and report console errors.

Step-by-step:

  1. Make sure Playwright MCP has been added to your client, whether Claude Code, Codex, or Cursor

  2. Start your local development server, such as Astro or Next.js, and make sure http://localhost:4321 is reachable

  3. Enter this prompt in Claude Code, Codex, or Cursor:

    Open http://localhost:4321, click "Articles" in the navigation menu, take a screenshot, and report whether the page has any console errors.
  4. Watch whether the AI calls browser tools, whether the browser starts, and whether the page opens

Acceptance Checklist

CheckExpected resultHow to confirm
Browser startsA browser window opens in headed mode, or the browser process starts in headless modeWatch the UI or process manager
MCP server is connectedThe client logs show “Connected to MCP server”Check the client logs
Accessibility snapshot returnsThe AI can find and click the navigation menuThe AI output includes a description of the click action
Tool calls require approvalDepends on your configuration; Codex may show an approval dialogWatch whether the client asks for approval
Output directory and logs are traceableScreenshots, console logs, and related output appear under --output-dirCheck the configured directory

Troubleshooting Failure Modes

The AI does not call browser tools:

  • Check whether the MCP server was added correctly by reading the client logs
  • Check whether the client supports MCP Tool Search; Claude Code enables it by default
  • Check whether Node.js is version 18 or newer

The browser opens but cannot find the button:

  • Playwright MCP works on the accessibility tree, not screenshots. If a page lacks semantic labels or ARIA attributes, the AI may not identify it
  • Inspect the page’s HTML and make sure the button has an accessible label or role
  • Or adjust the --snapshot-mode parameter to change snapshot detail

The browser starts and then closes immediately:

  • It may be running in headless mode, or the script may have finished
  • Check the client logs and confirm whether the browser started and closed normally
  • If you use headed mode, the browser window should stay open until the AI reports completion

Trade-Offs: Playwright MCP vs CLI/SKILLS

The Microsoft README states that coding agents may be better served by CLI + SKILLS in high-throughput code workflows, because MCP brings tool schemas and the accessibility tree into the context and consumes tokens. MCP is a better fit when you need persistent state, rich introspection, and a continuing browser context for exploratory automation, self-healing tests, or long-running tasks.

Scenario Comparison Table

ScenarioPrefer Playwright MCPPrefer Playwright CLI + SKILLS
Exploratory automation and self-healing tests✅ Good fit❌ Poor fit
Long tasks that need persistent browser context✅ Good fit❌ Poor fit
High-throughput code workflows❌ Poor fit because context usage is larger✅ Good fit
Need the smallest possible context footprint❌ Poor fit✅ Good fit
Already using an MCP client such as Claude Code, Codex, or Cursor✅ Good fit❌ Poor fit

This guide does not cover SKILLS usage in detail. A later article will cover practical Codex browser verification.


Summary and Next Steps

This guide covered Playwright MCP configuration for Claude Code, Codex, and Cursor, the first-run validation checklist, and the safety boundaries: the RCE risk of browser_run_code_unsafe, login-state persistence in profile modes, and the fact that --allowed-origins is not a security boundary.

Configuration Differences Summary

  • Claude Code: use the claude mcp add command or a project-level .mcp.json; Tool Search is enabled by default
  • Codex: use the codex mcp add command or config.toml; approval_mode can control high-risk tools
  • Cursor: configure it through the Settings UI, which differs from the other two clients

Suggested Next Steps

  • Need a tool comparison: read Browser Use vs Stagehand vs Playwright MCP, a 2026 AI browser-tool selection guide
  • Need login-state management: read AI browser login-state management
  • Need frontend testing: read Playwright frontend testing and verification
  • Need Codex browser verification: read Codex browser verification in practice
  • Need managed infrastructure: read managed browser infrastructure
  • Need security design: read AI browser security and approval design

If you have just configured Playwright MCP, run the localhost:4321 verification task first. Confirm that the browser starts, the AI calls tools, and screenshots are written to the configured directory. If it fails, work through the FAQ and check your Node.js version, client logs, and MCP server connection state.

First Playwright MCP connection checklist

Connect the official Playwright MCP server to an MCP client, then verify the browser, snapshot, action result, and logs on a low-risk page.

  1. 1

    Step 1: Check Node.js

    Run node --version in your terminal and confirm that Node.js is version 18 or newer.
  2. 2

    Step 2: Add the MCP server

    Use claude mcp add, codex mcp add, or the Cursor MCP settings page depending on your client, and use the official package name @playwright/mcp@latest.
  3. 3

    Step 3: Prepare a low-risk page

    Use a public demo or a local preview page first. Do not start with a primary account, an admin dashboard, or a payment page.
  4. 4

    Step 4: Ask the AI to act

    Ask the AI to open the page, click or type something observable, take a screenshot, and report console errors.
  5. 5

    Step 5: Check the result

    Confirm that the server is connected, the accessibility snapshot returns elements, the page result is visible, and screenshots and logs are traceable.
  6. 6

    Step 6: Tighten permissions

    Switch to an isolated profile, a test account, disabled_tools, or approval mode as needed so you do not hand real login state to the model.

FAQ

What is Playwright MCP, and how is it related to Playwright?
Playwright MCP wraps Playwright as an MCP server, so AI coding tools can call browser automation through the Model Context Protocol. Playwright itself is Microsoft's browser automation and testing framework; Playwright MCP is the AI-facing tool layer that exposes those capabilities to MCP clients.
Should I learn Playwright MCP or Browser Use first?
If you are a Python developer building a standalone browser agent, start with Browser Use. If you already use Claude Code, Codex, Cursor, or another MCP client and want browser tools inside that workflow, start with Playwright MCP.
Why do I not see browser tools after adding MCP?
Check whether the MCP server actually started, whether your client supports or enables MCP Tool Search, whether Node.js is at least version 18, and whether the client logs show a connection or npx error.
Why does the browser open but the AI cannot find a button?
Playwright MCP mainly works through the accessibility tree, not pure screenshot recognition. If the page lacks semantic HTML, accessible names, or ARIA attributes, the AI may not reliably identify buttons, links, and inputs.
Should I use headed or headless mode?
Use headed mode for development and first-run troubleshooting because you can watch the browser actions. Use headless mode for CI, remote servers, or background tasks, but verify behavior through screenshots, logs, and result checks.
What is the difference between persistent profile, isolated, and storage state?
A persistent profile saves cookies and login state, which is convenient for long tasks but riskier. Isolated mode keeps each session cleaner and is better for tests and concurrent clients. Storage state is useful when you want to load a controlled short-lived test-account session.
Why is browser_run_code_unsafe dangerous?
It can execute arbitrary Playwright scripts and is labeled RCE-equivalent by the official docs. If the MCP client or page context is not trustworthy, it can expose browser data and account permissions. In production, disable it or require approval.
Can Playwright MCP use login state, cookies, or captchas?
It can use login state through a persistent profile or storage state, but you should not use your primary real account. Do not bypass captchas or MFA; when those steps appear, the agent should stop and let a human take over.
Can Playwright MCP replace Playwright test scripts?
Not completely. Playwright MCP is good for exploratory page work, reproducing issues, and assisted acceptance checks. Stable regression, CI, and assertions should still be implemented as Playwright test scripts.
Can --allowed-origins restrict which sites the AI visits?
Do not treat it as a complete security boundary. The Microsoft README explicitly notes that allowed and blocked origins do not affect redirects and are not the only way to protect login state or sensitive data.

16 min read · Published on: Sep 4, 2026 · Modified on: Sep 4, 2026

Comments

Sign in with GitHub to leave a comment

Easton BlogEaston Blog