Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Some links on this page are affiliate links: if you buy through them we may earn a commission, at no extra cost to you.

The practical answer: use Playwright MCP when you want an AI agent to control a live browser from natural-language instructions, and use Playwright Codegen when you want maintainable test source for review and CI. They complement each other: MCP explores and performs a task through accessibility snapshots; Codegen records the same kind of flow as Playwright code with resilient locators and assertions.

You need Node.js 20 or newer and an MCP-capable client for the MCP workflow. The examples below use a disposable TodoMVC page first, then show how to turn a verified flow into a durable test.

Choose the right AI workflow

Need Best fit What you receive Review before reuse
Explore a site, investigate a bug, or complete a bounded task Playwright MCP Live browser actions driven by an LLM using structured accessibility snapshots Check every action, permission, account, and piece of data
Create repeatable regression coverage Playwright Codegen Playwright test code with generated locators and optional assertions Rename tests, improve fixtures and assertions, and replace throwaway data
Move from exploration to CI Both MCP for discovery, Codegen and human-edited tests for automation Run deterministic tests in an isolated environment before CI

MCP is flexible because the model decides the next browser action from the current page state. Codegen is repeatable because the resulting source executes the same steps every run. Neither removes the need for engineering review.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Set up Playwright MCP

Prerequisites

  • Install Node.js 20 or newer.
  • Use an MCP-capable client. The official examples include VS Code, Cursor, Windsurf, Claude Desktop, and Claude Code.
  • Have a test URL and, preferably, a disposable or read-only account.

Add the MCP server

Add a server entry to your client’s MCP configuration. The standard command is npx @playwright/mcp@latest. A typical configuration has this shape:

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

Save the configuration where your client expects MCP servers, restart the client, and confirm that Playwright tools are available. Client-specific file locations and restart steps vary, so use the labels shown by your client rather than copying a path from another operating system.

Run a bounded first session

  1. Open a new conversation with the Playwright MCP tools enabled.
  2. Give the agent one URL, one task, and an observable success condition.
  3. State that it must use a test account and avoid destructive actions.
  4. Ask it to report the final page state and any failed step.

For example:

Open https://demo.playwright.dev/todomvc/.
Add a todo named "AI browser check".
Confirm that the item appears in the list and report the visible count.
Do not delete existing items or navigate away.

The agent normally calls browser_navigate, then receives an accessibility snapshot containing element names and references. It can use those references for clicking, typing, and checking results without requiring a vision model.

What Playwright MCP can do

The getting-started workflow exposes browser operations for:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • Navigation, clicks, typing, form filling, and dropdown selection.
  • Screenshots, keyboard and mouse input, dialogs, tabs, and windows.
  • Network-request inspection and route mocking.
  • Saving and restoring storage state.

Because the model receives a fresh accessibility snapshot after actions, prompts should describe intent and constraints, not brittle coordinates. Ask for a specific role, label, or visible outcome when several controls look similar.

Use direct Playwright code only in trusted setups

For sequences that are awkward to express as individual tool calls, the server documents browser_run_code_unsafe. It executes direct Playwright scripts and is explicitly equivalent to remote code execution. Enable it only for clients and projects you trust. Treat every generated script as unreviewed code: inspect URLs, commands, file access, and data handling before running it. Keep credentials out of prompts, isolate test accounts, and never experiment against production data.

Generate maintainable tests with Codegen

Record a flow

  1. From your project directory, run:
npx playwright codegen https://demo.playwright.dev/todomvc/
  1. Playwright opens a browser and the Inspector.
  2. Perform the user journey exactly as a tester would: click, fill fields, submit, and navigate.
  3. Use the Inspector’s locator picker to inspect important targets.
  4. Add visibility, text, or value assertions while recording when they represent real requirements.
  5. Stop recording, review the generated code, and copy it into your test suite.

Codegen prioritizes role, text, and test-id locators and attempts to make them unique when multiple elements match. A generated locator is a starting point, not proof that the test expresses the right business intent.

Turn recorded code into a real test

Replace generic test names with a requirement, provide controlled fixtures, and assert the outcome rather than merely replaying clicks. For example, a cleaned-up test might look like:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
import { test, expect } from '@playwright/test';

test('user can add a todo', async ({ page }) => {
  await page.goto('https://demo.playwright.dev/todomvc/');
  await page.getByPlaceholder('What needs to be done?').fill('AI browser check');
  await page.getByPlaceholder('What needs to be done?').press('Enter');
  await expect(page.getByText('AI browser check')).toBeVisible();
});

Keep locators tied to user-facing meaning where possible. If a generated selector depends on an unstable class or DOM position, replace it with a role, accessible name, label, or deliberate test ID. Add assertions for errors and empty states when those are part of the requirement.

Emulate devices and reuse authentication safely

Codegen can capture viewport size, device emulation, color scheme, geolocation, language, and timezone. Specify the option that matches the scenario you need rather than assuming a desktop default. For an already authenticated session, load browser state:

npx playwright codegen https://example.test 
  --load-storage=auth.json

The storage file can contain cookies, local storage, and IndexedDB, including credentials or session tokens. Keep it local, add it to .gitignore, restrict access, and delete it when it is no longer needed. Do not commit it or paste its contents into an AI conversation.

Prompting patterns that reduce mistakes

Define scope and success

Include the URL, starting state, exact actions, success condition, and prohibited actions. “Check whether checkout shows an error for an expired card in the test environment” is safer than “test checkout.”

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Separate observation from mutation

Ask the agent to inspect the page first, list the controls it found, and then perform one approved mutation. This catches wrong environments and unexpected login pages before data changes occur.

Require a report

Have the agent return the final URL, visible success evidence, and the first failed action. A report makes an exploratory run useful even when the task does not complete.

Security, permissions, and review

  • Use a disposable account with the minimum permissions required.
  • Block production domains in the client or test harness when possible.
  • Never place API keys, passwords, or storage-state contents in prompts.
  • Review network inspection and route-mocking instructions before enabling them.
  • Keep browser_run_code_unsafe disabled unless the MCP client is trusted and scripts are reviewed.
  • Promote only human-reviewed Codegen output into CI.

An accessibility snapshot gives the model structured page context, but it does not establish that a button is safe to press. Authorization and test-data controls remain your responsibility.

Troubleshooting

The client shows no Playwright tools

Check that Node.js is 20 or newer, the command is exactly npx @playwright/mcp@latest, and the JSON configuration uses the client’s expected top-level key. Restart the client after editing the file. Read the client log for an npx or package-download error.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The agent cannot find a control

Ask it to inspect the latest accessibility snapshot and identify the element by role and accessible name. A control inside an iframe, a closed shadow root, or a custom canvas may not appear as expected; use a test-friendly label or a reviewed direct Playwright script.

The page is blank or keeps loading

Verify the URL outside the agent, check authentication and network access, and try a fresh context. Wait for a meaningful selector instead of relying on a fixed delay. If the site depends on third-party scripts, reproduce the same network conditions in your test environment.

Generated locators are flaky

Inspect the locator picker result, then replace positional or CSS-class selectors with role, text, label, or test-id locators. Add an assertion that distinguishes the intended element when names are duplicated.

Authentication disappears

Regenerate the storage state in the same environment, confirm that the account is still valid, and ensure the file path is correct. Treat the file as sensitive and avoid sharing it in logs.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The test passes locally but fails in CI

Compare browser version, viewport, timezone, locale, environment data, and network permissions. Remove hidden dependencies on a developer’s saved session, add explicit readiness assertions, and capture a trace or screenshot at the failing step for diagnosis.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

If your goal is a clean image or PDF rather than an interactive test, ScreenshotNeo provides a single HTTP call. It accepts cookie and consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; each cleanup step can be disabled. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and billing status. Its MCP server provides take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients.

See the complete parameter reference in the ScreenshotNeo documentation. A cURL capture is:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

The same request in Python:

import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)

And Node.js:

const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

You can also request full-page or element captures, dark mode, device presets, retina scale, PDF paper and page ranges, custom CSS or JavaScript, clicks, waits, blocked resources, headers, cookies, user agents, authorization, timezone, geolocation, transparent backgrounds, resizing, chosen cache TTLs, signed links, asynchronous webhooks, bulk capture of up to 100 URLs per call, and usage data. Every feature is included on every plan. The Free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000. Create a free ScreenshotNeo account to try it.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Practical decision checklist

  • Choose MCP for bounded, exploratory browser work where natural-language control is valuable.
  • Choose Codegen when the result must live in version control and run repeatedly.
  • Use both when an agent discovers the path and a human hardens it into a test.
  • Keep unsafe code, credentials, and production data outside untrusted experiments.
  • For static screenshots or PDFs, use a screenshot API instead of maintaining a browser session.

Frequently Asked Questions

Does Playwright MCP require a vision model?

No. Its documented interaction model gives the LLM structured accessibility snapshots, allowing it to select elements and issue browser actions without a vision model.

Can Codegen replace a test review?

No. It records actions and suggests locators, but a developer still needs to verify intent, test data, assertions, and stability before CI use.

When should I use an MCP browser session instead of an API screenshot?

Use MCP when the agent must interact with forms, navigation, dialogs, or application state. Use an API screenshot when you need a repeatable image or PDF without maintaining browser setup.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.