Skip to content
Complete Guide & Cheatsheet

Playwright MCP

A Model Context Protocol server that gives AI agents full browser automation power: without screenshots, without vision models. Pure structured data, maximum reliability.

27k+ GitHub Stars@playwright/mcpNode.js 18+VS Code · Cursor · Claude

01What is Playwright MCP?

Understand the concept before diving into commands.

MCP stands for Model Context Protocol: an open standard that lets AI assistants (Copilot in VS Code, Claude, Cursor) control external tools.

Playwright MCP wraps the Playwright browser automation library into an MCP server. Instead of taking screenshots and asking a vision AI to guess what's on screen, it reads the page's accessibility tree: structured data describing every element. This is faster, cheaper, and more reliable.
AI Assistant (Copilot/Claude)→MCP Protocol→Playwright MCP Server→Real Browser (Chrome/Firefox)→Web Page
✓ What it's great for
  • • Automating web workflows with AI
  • • Form filling, data extraction
  • • End-to-end test generation
  • • Multi-step web navigation
  • • Long-running autonomous tasks
⚡ MCP vs CLI
  • • MCP = persistent browser state
  • • CLI = more token-efficient
  • • MCP = better for exploration
  • • CLI = better for bulk testing
  • • Use MCP for agentic loops
ℹ️
Using a coding agent (Claude Code, Codex, Copilot CLI)? The Playwright team now points coding agents at playwright-cli with Skills instead of MCP: CLI calls don't load large tool schemas and accessibility trees into the context window, which matters when the agent also has to hold your codebase and tests. MCP remains the better fit for exploratory automation, self-healing tests and long-running loops that need a persistent browser.

02Installation

You need Node.js 18 or newer. That's the only real prerequisite.

  1. 1
    Check Node.js version

    Open a terminal and verify you have Node.js 18+

    codets
    node --version# Expected: v18.x.x or higher
  2. 2
    No global install needed!

    Playwright MCP runs via npx: it downloads and runs automatically. You don't need to install it globally.

    codets
    npx @playwright/mcp@latest --version# This downloads and prints the version
  3. 3
    Optional: Install browsers explicitly

    If Chromium isn't installed, Playwright MCP will prompt you. You can pre-install it:

    codets
    npx playwright install chromium# Or install all browsers:npx playwright install
💡
Pro tip: You never need to run the MCP server manually. VS Code (or any MCP client) will start and stop it automatically based on the config you add.

03VS Code Setup

The fastest path: add Playwright MCP to VS Code in under 2 minutes.

Method A: One Command (Fastest)

Run this in your terminal while VS Code is installed:

TERMINALbash
code --add-mcp '{"name":"playwright","command":"npx","args":["@playwright/mcp@latest"]}'

That's it. Restart VS Code and the server is ready.

Method B: Manual Config File

  1. 1
    Open the MCP config file

    In VS Code: press Ctrl+Shift+P → search "MCP: Edit Server Configuration" Or create the file manually at .vscode/mcp.json in your project.

  2. 2
    Paste the minimal config
    .vscode/mcp.jsonjson
    {  "servers": {    "playwright": {      "command": "npx",      "args": ["@playwright/mcp@latest"]    }  }}
  3. 3
    Save and verify

    Press Ctrl+Shift+P → "MCP: List Servers". You should see playwright listed with a green status.

Method C: With Extra Options (Recommended for teams)

.vscode/mcp.jsonjson
{  "servers": {    "playwright": {      "command": "npx",      "args": [        "@playwright/mcp@latest",        "--browser", "chromium",        "--headless",        "--output-dir", "./playwright-output",        "--save-trace"      ]    }  }}
ℹ️
Note for GitHub Copilot users in VS Code: After adding the config, open Copilot Chat, switch to Agent mode (dropdown next to the input), and Playwright tools will appear automatically when you ask Copilot to browse something.

04Your First Run

Test that everything works end-to-end.

In VS Code Copilot Chat

Open Copilot Chat → switch to Agent mode → type:

PROMPT EXAMPLEts
Go to https://example.com, take a screenshot, and tell me the page title.

Copilot will automatically use browser_navigate, then browser_snapshot or browser_take_screenshot.

Manual Server Test (Terminal)

TERMINALbash
# Run the server directly to confirm it startsnpx @playwright/mcp@latest # Or with a visible browser window (headed mode)npx @playwright/mcp@latest --browser chromium # Or as a standalone HTTP server on port 8931npx @playwright/mcp@latest --port 8931

05CLI Arguments Reference

All arguments go in the args array of your config.

Browser Control

ArgumentValuesDefaultDescription
--browserchrome, firefox, webkit, msedgechromiumWhich browser engine to use
--headlessflagheadedRun without visible window (great for CI)
--device"iPhone 15", etc.-Emulate a mobile device
--viewport-size"1280x720"-Set browser window size
--user-agentstring-Override the user agent string
--executable-pathpath-Use a custom browser binary
--cdp-endpointURL-Connect to an existing browser via CDP

Session & Storage

ArgumentDescription
--isolatedFresh browser profile every session (no cookies saved)
--user-data-dir <path>Custom directory for browser profile (login state persists)
--storage-state <path>Load saved cookies/localStorage (from Playwright auth)

Output & Debugging

ArgumentDescription
--output-dir <path>Where to save screenshots, PDFs, traces
--save-traceSave Playwright Trace Viewer file for debugging
--save-video <size>Record a video of the session (e.g. 800x600)
--console-level <lvl>error/warning/info/debug, which console messages to capture

Network & Security

ArgumentDescription
--proxy-server <url>Route traffic through a proxy
--ignore-https-errorsAccept invalid/expired SSL certs
--blocked-origins <list>Block specific origins from loading
--no-sandboxDisable browser sandbox (Docker only)

Extra Capabilities

ArgumentDescription
--caps visionEnable coordinate-based mouse tools (xy clicks, drags)
--caps pdfEnable browser_pdf_save tool
--caps devtoolsEnable DevTools access
--caps testingEnable test assertion tools
--caps networkEnable request mocking and offline mode (browser_route, browser_unroute, browser_network_state_set)
--caps storageEnable cookie, localStorage, sessionStorage and storage-state tools
--caps configEnable browser_get_config: the final config after CLI options, env vars and config file are merged
--caps vision,pdfMultiple caps comma-separated
--no-webmcpDon't expose tools the page registers through the WebMCP API (exposed by default)

Timing & Performance

ArgumentDefaultDescription
--timeout-action <ms>5000msMax time to wait for a single action
--timeout-navigation <ms>60000msMax time to wait for page navigation
--snapshot-modeincrementalincremental / full / none

06Config File

For complex setups, use a JSON config file instead of long argument lists.

playwright-mcp.config.jsonjson
{  "browser": {    "browserName": "chromium",    "isolated": false,    "userDataDir": "./browser-data",    "launchOptions": {      "headless": false,      "channel": "chrome"    },    "contextOptions": {      "viewport": { "width": 1280, "height": 720 },      "locale": "en-US",      "timezoneId": "America/New_York"    }  },  "server": { "port": 8931, "host": "localhost" },  "capabilities": ["core", "pdf", "vision"],  "outputDir": "./playwright-output",  "saveTrace": true,  "timeouts": { "action": 5000, "navigation": 30000 },  "console": { "level": "info" },  "network": { "blockedOrigins": ["https://ads.example.com"] }}

Use it in your VS Code MCP config:

.vscode/mcp.jsonjson
{  "servers": {    "playwright": {      "command": "npx",      "args": ["@playwright/mcp@latest", "--config", "./playwright-mcp.config.json"]    }  }}

07Browser Profiles

Three modes for managing login state and sessions.

🔒 Persistent (Default)

Login state, cookies, localStorage all saved between sessions. Great for personal automation where you stay logged in.

codets
args: ["@playwright/mcp@latest"]# Profile stored at:# macOS: ~/Library/Caches/ms-playwright/...
🧪 Isolated

Fresh profile every session. Perfect for testing where you need a clean slate.

codets
args: [  "@playwright/mcp@latest",  "--isolated",  "--storage-state=./auth.json"]
🌐 Browser Extension Mode

Connect to your actual running Chrome/Edge with all your existing logins, extensions, and tabs.

codets
args: ["@playwright/mcp@latest", "--extension"]# Requires: "Playwright MCP Bridge" extension in Chrome/Edge

Saving & Reusing Auth State

save-auth.js (run once)ts
const { chromium } = require('playwright');const browser = await chromium.launch();const page = await browser.newPage();await page.goto('https://yoursite.com/login');// ... fill in credentials manually ...await page.context().storageState({ path: 'auth.json' });await browser.close();
MCP config with saved authts
args: ["@playwright/mcp@latest", "--isolated", "--storage-state=auth.json"]

08Capabilities (Tool Groups)

Tools are grouped into capabilities. Most are active by default; some require opt-in.

CapabilityFlagIncluded ToolsWhen to use
corealways onnavigate, click, type, screenshot, snapshot, fill, wait…Always available: standard automation
vision--caps visionmouse_click_xy, mouse_drag_xy, mouse_move_xy, mouse_wheelWhen elements have no accessibility label (canvas, games)
pdf--caps pdfbrowser_pdf_saveSaving pages as PDFs
devtools--caps devtoolshighlight, annotate, start/stop tracing, start/stop video, video chaptersDebugging, and recording a video of what the agent did
testing--caps testinggenerate_locator, verify_element_visible, verify_text_visible…Writing or verifying automated tests
network--caps networkbrowser_route, browser_route_list, browser_unroute, browser_network_state_setMocking API responses or testing offline behaviour
storage--caps storagecookie_*, localstorage_*, sessionstorage_*, storage_state, set_storage_stateSeeding or inspecting auth and app state
config--caps configbrowser_get_configChecking which options the server actually runs with
webmcpon by default (--no-webmcp)webmcp_<tool> for each tool the page registersApps that expose WebMCP tools to agents (Playwright 1.64+)
ℹ️
WebMCP: pages can register their own tools for agents through the experimental WebMCP browser API. Since Playwright 1.64, Playwright MCP collects them and offers each one to the agent as webmcp_<tool>, next to the built-in tools. If you test such an app, that is useful; if you don't want page-defined tools in the agent's list, start the server with --no-webmcp.
⚠️
Vision mode caveat: Coordinate-based tools (xy clicks) are fragile: if the layout changes by even a pixel, clicks will miss. Always prefer accessibility-based tools (browser_click with ref) when possible.

09Core Automation Tools

These tools are always available. Blue = read-only (observes page). Green = read-write (changes it).

🌐 Navigation
🔍 Observation
🖱️ Interaction
⏳ Waiting & Flow

10Tab Management

Manage multiple browser tabs in a single session.

11Vision Tools

Requires --caps vision. Coordinate-based mouse tools. Use only when accessibility-based tools don't work (canvas apps, games).

⚠️
These tools use pixel coordinates (x, y). They break if the layout shifts. Always prefer core tools with ref when available.
ToolParametersDescription
browser_mouse_click_xyx, y (numbers)Click at exact pixel position
browser_mouse_move_xyx, y (numbers)Move mouse to position (no click)
browser_mouse_downbutton? (default left)Press mouse button down (hold)
browser_mouse_upbutton? (default left)Release mouse button
browser_mouse_drag_xystartX, startY, endX, endYClick-drag from one coordinate to another
browser_mouse_wheeldeltaX, deltaY (numbers)Scroll the mouse wheel

12PDF Tools

Requires --caps pdf.

13Testing Tools

Requires --caps testing.

ToolKey ParametersDescription
browser_generate_locatorref (required)Generate a Playwright locator string for use in test code
browser_verify_element_visiblerole, accessibleNameAssert an element with given role + name is visible. Throws if not.
browser_verify_text_visibletextAssert specific text is visible on the page
browser_verify_list_visibleref, items[]Assert a list element contains the expected items
browser_verify_valueref, value, typeAssert an input has a specific value (use "true"/"false" for checkboxes)
EXAMPLE TEST WORKFLOWts
1. Navigate to the page2. Fill the login form3. Click submit4. Use browser_verify_text_visible to check "Welcome back, John"5. Use browser_generate_locator to get locator for the dashboard element6. Copy the generated locator into your Playwright test file

14Real Workflow Examples

Complete end-to-end examples you can copy and adapt.

1. Scrape a table from a webpage

PROMPT TO AIts
Go to https://example.com/prices, take a snapshot, find the pricing table, and return all the data in JSON format.

2. Fill and submit a form

PROMPT TO AIts
Go to https://myapp.com/register and fill in the registration form:- First name: Alice- Last name: Smith- Email: alice@example.com- Password: MySecurePass123!Then click the Register button and wait for the success message.

5. Debug a broken page

PROMPT TO AIts
Go to https://myapp.com, open the console, look for any JavaScript errors, check network requests for any failed API calls, take a screenshot, and give me a report of what's broken.

3. Screenshot & Save PDF Report

CONFIG (.vscode/mcp.json)json
{  "servers": {    "playwright": {      "command": "npx",      "args": ["@playwright/mcp@latest", "--caps", "pdf", "--output-dir", "./reports", "--headless"]    }  }}
PROMPT TO AIts
Go to https://example.com/dashboard, wait for all charts to load, take a full-page screenshot saved as dashboard.png, then save a PDF as dashboard.pdf.

6. Authenticated session with saved state

STEP 1: Save auth (run once)ts
npx playwright codegen --save-storage=auth.json https://myapp.com/login# Log in manually in the opened browser, then close it# auth.json now contains your cookies/localStorage
STEP 2: MCP config using saved authts
{  "servers": {    "playwright": {      "command": "npx",      "args": ["@playwright/mcp@latest", "--isolated", "--storage-state=auth.json"]    }  }}

7. Run in Docker (CI/CD)

docker-compose.ymlyaml
services:  playwright-mcp:    image: mcr.microsoft.com/playwright/mcp    entrypoint: node    command: cli.js --headless --browser chromium --no-sandbox --port 8931    ports:      - "8931:8931"
MCP CLIENT CONFIG (CI environment)bash
{  "mcpServers": {    "playwright": {      "url": "http://localhost:8931/mcp"    }  }}

15Best Practices

Always take a snapshot before interacting

✓ Good
codets
1. browser_snapshot()2. Find ref="e42" for Login3. browser_click({ ref: "e42" })
✗ Bad
codets
browser_click({   element: "Login button" })// Guessing: unreliable

Prefer browser_fill_form over multiple browser_type calls

✓ Efficient
codets
browser_fill_form({  fields: [    { ref: "e10", value: "Alice" },    { ref: "e11", value: "alice@x.com" }  ]})
✗ Slow
codets
browser_type({ ref: "e10", text: "Alice" })browser_type({ ref: "e11", text: "alice@x.com" })// 2 separate tool calls

Additional Golden Rules

  • →Use --isolated for test automation so sessions don't bleed into each other
  • →Use browser_wait_for with text conditions, not fixed time delays when possible
  • →Use --no-sandbox only inside Docker containers: never in production systems
  • →Use --save-trace for debugging failed runs: open with npx playwright show-trace
  • →Use --blocked-origins to block analytics/ads and speed up page loading during automation

16Troubleshooting

ProblemLikely CauseFix
Browser not found errorBrowsers not installedRun: npx playwright install chromium
Timeout on navigationPage too slowAdd --timeout-navigation 120000
Click fails / element not foundStale ref: snapshot outdatedAlways take a fresh snapshot before clicking
MCP server not showing in VS CodeConfig syntax errorValidate JSON; check the file path
SSL certificate errorsSelf-signed cert or corp proxyAdd --ignore-https-errors
Login state lostRunning in --isolated modeUse --storage-state=auth.json or remove --isolated
Server starts but no tools appearMCP client not in agent modeIn VS Code Copilot, switch chat to "Agent" mode
Docker container can't open browserMissing --no-sandbox flagAdd --no-sandbox flag in Docker only

Quick Diagnostic Checklist

  • □node --version → 18.x or higher?
  • □npx @playwright/mcp@latest --version → runs without error?
  • □.vscode/mcp.json valid JSON?
  • □VS Code Copilot chat in "Agent" mode (not "Chat")?
  • □Playwright servers listed in Ctrl+Shift+P → "MCP: List Servers"?
  • □Browsers installed? Run: npx playwright install

17References & Official Docs

Always check the official sources for the latest updates.