Blog/

Playwright

Playwright MCP: What it is and How to Use it

AI agents can now drive a real browser through Playwright. Learn about Playwright MCP, its benefits, how to get started with it, and where it fits next to a real test suite.

Sauce Labs Author

Sauce Labs Author

July 10, 2026

The browser just became something you can hand to an agent. Playwright MCP is Microsoft’s open-source Model Context Protocol server that lets AI agents drive a real browser through Playwright, reading pages as structured accessibility snapshots instead of screenshots. 

This guide covers what Playwright MCP is, how the server works, how to configure it for Claude Desktop, Claude Code, VS Code, and Cursor, and where it fits next to your committed test suite.

What is Playwright MCP?

Playwright MCP is an open-source MCP server from Microsoft that exposes Playwright’s browser automation capabilities as tools an AI agent can call. Instead of a human writing Playwright scripts, an AI model issues tool calls (go to a URL, click this element, read the page, submit a form) and the server executes them in a real browser.

The Model Context Protocol (MCP) is an open standard for connecting AI models to tools and data sources. It defines how a model asks for a tool, how the tool responds, and how the conversation tracks state. Like Sauce MCP, which exposes the Sauce Labs platform to agents, Playwright MCP exposes browser control as tools any MCP-compatible client can call.

Agents interact with accessibility snapshots — structured representations of the page’s content and interactive elements — rather than pixels. The agent doesn’t need a vision model to understand the page. It reads the same tree of roles, names, and values a screen reader uses, and acts on that structure. The result is faster and cheaper than screenshot-based approaches (no large image tokens) and, without a vision model guessing at pixels, more deterministic too.

However, Playwright MCP is not a replacement for a deterministic regression suite. Agent-driven browser sessions are exploratory and nondeterministic by nature. Where MCP fits relative to committed test code is covered later in this guide.

How does Playwright MCP work?

The architecture has two sides: a server that hosts the browser, and a client that sends tool calls.

The server runs as a process on your machine (or in a container). It launches a browser instance through Playwright and exposes tools like navigation, clicking, typing, reading snapshots, monitoring network traffic, evaluating scripts, and more. The server manages the browser session, including page state, cookies, and context isolation.

The client is whatever AI application connects to the server. Claude Desktop, Claude Code, VS Code with Copilot, and Cursor all support MCP. The client sends a tool call (e.g., “go to this URL”), the server executes it in the browser, and the server returns the result, such as the page’s accessibility snapshot, a list of network requests, or a confirmation that the click succeeded.

Tool categories span the full range of browser interactions. Core automation covers page navigation, clicking, typing, form filling, file uploads, and dialogs. Network tools list and inspect requests, mock routes, and toggle offline mode. Tab management handles multiple pages. Storage tools read and write cookies, localStorage, and sessionStorage. Optional capabilities (enabled with the --caps flag) add vision-based coordinate interaction, PDF generation, devtools features like tracing and video recording, and test assertion tools for generating locators and verifying element visibility.

The accessibility snapshot deserves emphasis because it’s central to how agents interact with pages through Playwright MCP. When the agent calls browser_snapshot, the server returns a tree of every element on the page, including its role (button, link, textbox, heading), its accessible name, its current value, and a reference identifier the agent uses in subsequent tool calls. A snapshot is cheaper and more reliable than sending a screenshot and asking a vision model to find the login button. The agent reads “button ‘Log in’” and issues a click on that reference.

Transport runs in two modes. Stdio mode is the default, where the MCP client spawns the server as a subprocess and exchanges JSON-RPC messages on stdin and stdout, and is the lowest-latency option. It also works for Claude Code, Cursor, and any client running on the same machine. HTTP mode, enabled with the --port flag, lets the server listen on a network port for SSE connections. Use HTTP mode when the client runs in a different container, VM, or on a remote machine. For remote clients, also pass --host 0.0.0.0 and set --allowed-hosts. 

Session state follows the browser’s lifecycle. By default, the server uses a persistent user profile tied to the workspace, so cookies and storage survive between sessions. The --isolated flag switches to ephemeral profiles that start clean every time. Each connected client gets its own context.

Installing and configuring Playwright MCP

To get started with Playwright MCP, follow the steps below.

Prerequisites: Node.js 18 or newer and one of the supported MCP clients.

The standard configuration works across most clients. Add this to your client’s MCP configuration file:

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

The configuration tells the client to spawn the Playwright MCP server via npx whenever a session starts.

Claude Code

Use the CLI to register the server directly:

claude mcp add playwright npx @playwright/mcp@latest

Claude Code uses stdio transport by default, which is the recommended mode. By default, the agentic coding tool stores the server at local scope in ~/.claude.json, available only to you in the current project. Add --scope project to write it to a .mcp.json file the whole team can share.

Claude Desktop

Follow the MCP install guide at modelcontextprotocol.io and add the standard configuration above to your Claude Desktop settings. The server starts automatically when you begin a conversation that uses browser tools.

VS Code

Install via the VS Code CLI:

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

Or go to the MCP settings in VS Code and add the standard configuration manually. The Playwright MCP server then becomes available to GitHub Copilot’s agent mode.

Cursor

Go to Cursor Settings, then MCP, then Add new MCP Server. Set the type to command and the command to npx @playwright/mcp@latest. Cursor reads configuration from ~/.cursor/mcp.json (global) or .cursor/mcp.json (per project).

Configuration options

Once the server is running, flags control its behavior. A few common ones:

--browser selects the browser engine: chrome, firefox, webkit, or msedge. The default is chromium.

--headless runs the browser without a visible window. The default is headed mode, which is useful for watching what the agent does.

--isolated starts each session with a clean, ephemeral profile. No cookies or storage carry over from previous sessions.

--storage-state path/to/state.json loads saved cookies and local storage into an isolated session, useful for starting authenticated.

--user-data-dir path/to/profile sets a persistent browser profile directory for sessions that need to preserve state across runs.

--caps enables optional tool capabilities. Values include vision (coordinate-based interactions and screenshots), pdf (page-to-PDF), devtools (tracing and video), and network (route mocking and network state control).

--port 8931 switches from stdio to HTTP/SSE transport, listening on the specified port. Connect clients with "url": "http://localhost:8931/mcp" in the config.

Docker

For containerized environments, a Docker image runs headless Chromium:

{
  "mcpServers": {
    "playwright": {
      "command": "docker",
      "args": ["run", "-i", "--rm", "--init", "--pull=always",
              "mcr.microsoft.com/playwright/mcp"]
    }
  }
}

What you can do with it

Playwright MCP turns natural language into browser actions. Here are the workflows that work well.

Exploratory testing by prompt. Tell the agent to walk through a user flow and report what it finds — the way you’d brief a new tester, not write a script. “Go to staging.example.com, log in with the test account, add three items to the cart, go to checkout, and tell me if anything looks wrong.” The agent opens each page, reads accessibility snapshots at each step, and reports its findings. Briefing an agent is faster than writing a throwaway script and more structured than doing it by hand.

Test generation. The agent explores the application, then writes Playwright test code based on what it observed. “Go to the signup page, fill out the form, submit it, verify the confirmation message, then write a Playwright test that covers this flow.” The generated code uses real locators from the page, not guesses, because the agent read the actual accessibility tree. Review and commit the output as you would any generated code.

Bug reproduction. Paste a bug report into the chat. The agent follows the steps, captures the state at each point, and confirms whether the bug reproduces. “Follow these steps from the ticket: go to /settings, click Edit Profile, clear the name field, click Save, and check whether the error message appears.” The agent returns the accessibility snapshot at the failure point, which is more useful for debugging than a screenshot alone.

Verification during development. After making a UI change, ask the agent to check it without writing a script. “Open localhost:3000/dashboard and verify that the new chart component renders with the correct axis labels.” The agent opens the page, reads the content, and confirms or flags discrepancies. A quick agent check fills the gap between saving a file and writing a formal test.

Network monitoring and script evaluation. The agent can list network requests, inspect headers and response bodies, mock routes, and evaluate JavaScript on the page. Those tools help with checking API responses during a flow, verifying that analytics events fire, or testing how the UI handles a mocked error response. For example, the agent can set up a route mock that returns a 500 error from an API endpoint, then walk through the user flow and report how the application handles the failure. Combined with the browser_evaluate tool, the agent can also read application state from the DOM or JavaScript variables to verify behavior that is not visible in the accessibility tree.

Data entry and form testing. The browser_fill_form tool fills multiple form fields in one call, which makes form-heavy workflows efficient to test through an agent. Ask the agent to fill a registration form with valid data, submit it, then fill it again with invalid data (e.g., empty required fields, a malformed email, password too short, or a duplicate username) and report which validation messages appear. Variation testing like that is tedious to script manually and well suited to an agent that can read the results and adapt.

Where MCP fits next to a real test suite

Playwright MCP and the Playwright test runner solve different problems, and using one for the other’s job creates friction.

MCP workflows are for exploration, generation, and triage. An agent browsing the app to find issues, generating test code, reproducing a bug report, or verifying a quick change is using MCP well. These are tasks where nondeterminism is acceptable, and the value is speed and flexibility.

Microsoft also ships @playwright/cli alongside the MCP server, as another way for agents to drive a browser. The CLI exposes browser automation as shell commands rather than MCP tool calls, and coding agents with filesystem access (Claude Code, Copilot, Cursor) often prefer it because it’s more token-efficient. Choose MCP when the agent needs persistent browser context and iterative reasoning over page state. Choose the CLI when the agent is executing a defined sequence and token cost matters.

Committed test code, run by the Playwright Test runner, is for repeatability. A regression suite that runs on every pull request needs deterministic execution, controlled data, and predictable timing. Agent-driven sessions add token cost and latency, and a test runner has no use for their nondeterminism. 

Agent-driven browser automation is also the wrong tool for load or performance testing. An MCP session drives one browser. Performance testing requires hundreds or thousands of concurrent connections, which is a fundamentally different architecture.

DimensionPlaywright MCP workflowPlaywright Test runner
Primary useExploration, generation, triageRegression, CI gating, repeatability
Execution modelAgent decides next step per page stateScript runs deterministically start to finish
SpeedSeconds per step (LLM round trip)Milliseconds per step
Token costVaries by task and context useNone; ordinary test execution needs no LLM
ParallelismOne browser per sessionWorkers and sharding in config
OutputFindings, generated code, evidencePass/fail, coverage, execution logs
Best forAd hoc checks, prototyping tests, reproductionCommitted suites, CI/CD, cross-browser at scale

Tests an agent generates locally still need cross-browser coverage before they're trusted for gating. Sauce Labs runs the resulting Playwright suites at scale with video, logs, and network captures on every run, so the code an agent writes on one browser gets validated across the real matrix.

Security and reliability practices

Playwright MCP is not a security boundary. Microsoft says this plainly in the repo, and the MCP specification’s security guidance applies.

Restrict allowed origins. The --allowed-origins flag limits which origins the browser can request. The --blocked-origins flag blocks specific origins. Use both to keep the agent from navigating to domains outside your application. These filters reduce accidental navigation but don’t block redirects and aren’t a security boundary. 

Use isolated sessions. The --isolated flag starts each session with no saved state. Without it, two agent sessions on the same server share cookies and storage, which leaks state between tasks.

Be cautious with evaluate. The browser_evaluate tool runs arbitrary JavaScript in the page context. Treat it like eval(). If the agent is operating on untrusted pages, the risk of injection is real.

Log and audit agent decisions. Every tool call the agent makes is visible in the MCP client’s conversation. For team workflows, save session logs so someone can review what the agent did, especially if it generated code that will be committed.

Human review before merging generated tests. Agent-generated test code should go through the same pull request review and CI gates as human-written code. Generation is not verification.

Troubleshooting common errors

“Server not found” or connection failures. The most common cause is the Node.js version. Playwright MCP requires Node 18 or newer. Check the version with node --version. If the version is correct, verify that npx can reach the npm registry because corporate proxies sometimes block it. For HTTP transport, confirm the port isn’t in use and the client’s URL matches the server’s --port setting.

Version mismatches between MCP and browsers. Playwright downloads browser binaries separately from the npm package. If you see missing or incompatible browser errors, install the browsers that match the Playwright version your MCP server uses. Pin to a specific version (for example, @playwright/mcp@0.0.74) to avoid unexpected upgrades. 

Client shows zero tools or a stale tool list. Restart both the server process and the client. Cursor and VS Code cache the tool list at startup; a server update without a client restart leaves the tool list stale. In Cursor, clearing the MCP cache in settings resolves most cases.

Headed mode fails in CI or headless environments. The default is headed mode, which requires a display. Pass --headless when running in CI, Docker, or any environment without a GUI. The Docker image runs headless Chromium by default.

Corporate proxy blocks browser downloads. Playwright downloads browser binaries from its CDN during installation. If a corporate proxy blocks this, set the PLAYWRIGHT_BROWSERS_PATH and HTTPS_PROXY environment variables, or download the browsers on a machine with access and copy them to the restricted environment.

Concurrent sessions conflict on the same workspace. Persistent profiles are tied to the workspace hash. Two MCP clients sharing the same workspace will conflict because only one browser can use a persistent profile at a time. Start additional clients with --isolated or point each at a different --user-data-dir.

How Sauce Labs fits agentic browser automation

The tests an agent writes locally run on one browser and one OS, at whatever viewport happened to be open. Sauce Labs runs the resulting Playwright suites across the real matrix.

Playwright tests generated through MCP sessions can run on Sauce Labs across Chromium, Chrome, Firefox, and WebKit on Windows and macOS, using saucectl and your existing test files. Add a saucectl config.yml to your Playwright project and run saucectl run to execute the suite on Sauce Labs. If you'd rather keep running npx playwright test locally, the Sauce Labs Playwright reporter uploads those results to your account.

Every session produces debugging artifacts, including video recordings, screenshots, and command logs. When a test the agent generated passes locally but fails on WebKit or Firefox, the artifacts show exactly where the behavior diverges. The artifacts close the gap between “the agent said it works” and “we verified it works across the configurations our users run.”

Test analytics on the Sauce Labs platform track whether agent-generated tests are stable or flaky across builds. A test that was generated in 30 seconds but flakes 10% of the time across browsers is worse than no test at all. Sauce AI for Insights surfaces that pattern before the test erodes trust in the suite.

Sauce Labs also runs its own Sauce MCP server, so the coding agent that drives Playwright MCP locally can work with the Sauce Labs platform directly, from generating tests with Sauce AI for Test Authoring to running them at scale. Agentic testing then stretches from local exploration to cloud-scale validation in one workflow.

Start driving browsers with an agent

The setup only requires four easy steps:

  1. Install the server (npx @playwright/mcp@latest).
  2. Connect your client (Claude Code, VS Code, Cursor, or Claude Desktop).
  3. Run one navigation task to confirm the connection.
  4. Ask the agent to generate a test from the session.

The generated test is regular Playwright code. Commit it and run it in CI, then validate it across browsers and devices. The agent’s work ends there, and the infrastructure’s work begins.

Try Sauce Labs free or book a demo to run your agent-generated Playwright suites on real infrastructure.

On This Page

Free trial

Sign up Free

Start testing smarter with the world's largest continuous testing cloud — now with AI built in.

Start Testing

Keep reading.

VIEW ALL POSTS
Playwright
VIEW ALL POSTS