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

"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:
- Whether the MCP server started correctly by reading the Claude Code logs
- Whether Tool Search is enabled, which it is by default in Claude Code
- 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.tomlin 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 automaticallyapproval_mode = "prompt": ask for user confirmation before each tool callapproval_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:
- Open Cursor Settings with
Cmd+,or from the Settings menu - Go to the MCP settings page, Settings -> MCP
- Click “Add new MCP Server”
- Fill in the configuration:
- Server name:
playwright - Command type:
npx - Command:
@playwright/mcp@latest
- Server name:
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.
| Parameter | Purpose | Default | Safety note |
|---|---|---|---|
--headless | Run without showing a browser window | false (headed) | Use headed mode during development so you can observe browser actions |
--browser | Choose the browser type | chrome | Options include chrome, firefox, webkit, and msedge |
--allowed-origins | List of allowed origins | Unlimited | Not a security boundary; it does not affect redirects and cannot protect sensitive sites by itself |
--blocked-origins | List of blocked origins | None | Not a security boundary, same caveat as above |
--isolated | Isolated mode; each session uses a separate profile | false | Recommended for concurrent clients or multiple projects |
--storage-state | Specify a login-state file path | None | Saves cookies and localStorage; be careful with real accounts |
--output-dir | Output directory for screenshots, logs, and related files | None | Set a path so results are easy to find |
--save-session | Save session state | false | Use with a persistent profile |
--snapshot-mode | Accessibility snapshot mode | default | Controls snapshot detail |
--allow-unrestricted-file-access | Allow unrestricted file access | false | High risk; enable only when you understand the impact |
--secrets | Secret configuration through environment variables or files | None | Used 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.
| Mode | Login-state persistence | Profile path | Concurrency | Good fit | Safety advice |
|---|---|---|---|---|---|
| persistent | Saves cookies, localStorage, and related state | macOS: ~/Library/Caches/ms-playwright/mcp-{channel}-{workspace-hash} | One profile can be used by only one browser instance at a time | Long tasks where the AI needs to remember login state | Do not use a real account by default; start with a test account |
| isolated | Does not persist state; each session is independent | Temporary directory, cleaned up per session | Supports concurrent clients or multiple projects | Tests, exploration, and tasks that do not need login state | Recommended as the production default |
| browser extension | Persists depending on the browser | Browser extension directory | Depends on the browser | Connecting to an existing browser session | Advanced 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
--isolatedmode - Or configure a different
--user-data-dirfor 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
--isolatedin 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_unsafeallows 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’sapproval_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:
-
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"] -
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_unsafecall, 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
Not Recommended for Beginners
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
-
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. -
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.
-
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.
-
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.
-
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.
-
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:
-
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.
-
Control access: restrict reachable origins, file paths, and browser capabilities. For example, block access to internal IP ranges or sensitive paths.
-
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.
-
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:
-
Make sure Playwright MCP has been added to your client, whether Claude Code, Codex, or Cursor
-
Start your local development server, such as Astro or Next.js, and make sure
http://localhost:4321is reachable -
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. -
Watch whether the AI calls browser tools, whether the browser starts, and whether the page opens
Acceptance Checklist
| Check | Expected result | How to confirm |
|---|---|---|
| Browser starts | A browser window opens in headed mode, or the browser process starts in headless mode | Watch the UI or process manager |
| MCP server is connected | The client logs show “Connected to MCP server” | Check the client logs |
| Accessibility snapshot returns | The AI can find and click the navigation menu | The AI output includes a description of the click action |
| Tool calls require approval | Depends on your configuration; Codex may show an approval dialog | Watch whether the client asks for approval |
| Output directory and logs are traceable | Screenshots, console logs, and related output appear under --output-dir | Check 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-modeparameter 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
| Scenario | Prefer Playwright MCP | Prefer 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 addcommand or a project-level.mcp.json; Tool Search is enabled by default - Codex: use the
codex mcp addcommand orconfig.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
Step 1: Check Node.js
Run node --version in your terminal and confirm that Node.js is version 18 or newer. - 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
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
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
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
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?
Should I learn Playwright MCP or Browser Use first?
Why do I not see browser tools after adding MCP?
Why does the browser open but the AI cannot find a button?
Should I use headed or headless mode?
What is the difference between persistent profile, isolated, and storage state?
Why is browser_run_code_unsafe dangerous?
Can Playwright MCP use login state, cookies, or captchas?
Can Playwright MCP replace Playwright test scripts?
Can --allowed-origins restrict which sites the AI visits?
16 min read · Published on: Sep 4, 2026 · Modified on: Sep 4, 2026
Browser Automation Agent Practice Guide: Playwright, Browser Use, and Computer Use
If you landed here from search, the fastest way to build context is to jump to the previous or next post in this same series.
Previous
Browser Use Beginner Guide: Open Pages, Click Buttons, and Extract Data with an AI Agent
A practical Browser Use tutorial for running your first AI browser agent with Python: install browser-use, configure an API key, write tasks for opening pages, clicking buttons, and extracting data, then debug with history, allowed_domains, screenshots, and errors.
Part 2 of 3
Next
This is the latest post in the series so far.



Comments
Sign in with GitHub to leave a comment