mcp-playwright
# mcp-playwright
[](LICENSE)
[](https://nodejs.org)
[](https://modelcontextprotocol.io)
[](https://playwright.dev)
A starter template for building [MCP (Model Context Protocol)](https://modelcontextprotocol.io) servers with [Playwright](https://playwright.dev) browser automation, for use with [Claude Code](https://claude.ai/code).
Clone this repo, add your own tools, and Claude can control a browser as part of any agentic workflow.
---
## Table of Contents
1. [What Is This?](#what-is-this)
2. [When Do You Need This?](#when-do-you-need-this)
3. [Architecture](#architecture)
4. [Prerequisites](#prerequisites)
5. [Install](#install)
6. [Configure MCP in Claude Code](#configure-mcp-in-claude-code)
7. [Verify It Works](#verify-it-works)
8. [Using the Skill](#using-the-skill)
9. [Adding Your Own Tools](#adding-your-own-tools)
10. [Browser Sessions (Login)](#browser-sessions-login)
11. [Directory Map](#directory-map)
12. [Concepts Explained](#concepts-explained)
13. [Troubleshooting](#troubleshooting)
14. [Contributing](#contributing)
---
## What Is This?
Three things in one repo:
| Layer | What it is | File |
|---|---|---|
| **MCP Server** | A Node.js process Claude Code talks to over stdio | `src/server.ts` |
| **Playwright** | Browser automation library — runs inside tool handlers | `src/browser.ts` + `src/tools/` |
| **Claude Skill** | Slash command that scaffolds and extends the server | `.claude/skills/build-mcp-playwright/` |
Two example tools are included to show the pattern:
- `browser_screenshot` — navigate to a URL, save a full-page screenshot
- `browser_get_text` — navigate to a URL, return the visible text
Replace or extend these with your own automation.
---
## When Do You Need This?
Use this repo when your automation task hits all three conditions:
| Condition | Meaning |
|---|---|
| **Requires a browser** | The data or action only exists behind a web UI |
| **No API** | The only interface is the website itself — no REST/GraphQL endpoint |
| **Needs login** | The content is behind authentication |
### Why not just use curl or bash?
curl works for simple public pages. It breaks the moment you have login, JavaScript rendering, or multi-step UI flows.
| Scenario | curl / bash | Playwright |
|---|---|---|
| Public static page | ✓ | ✓ |
| Page requires login | ✗ OAuth/SSO is too complex to replicate | ✓ logs in like a human |
| Content loaded by JavaScript | ✗ gets the empty HTML shell, not the rendered data | ✓ waits for JS to finish |
| Multi-step flow (click → modal → fill → submit) | ✗ stateless, can't interact | ✓ drives the full flow |
| Cloudflare / bot protection | ✗ blocked immediately | ✓ runs real Chrome, harder to detect |
| Single-page app (React, Angular) | ✗ sees `<div id="root"></div>` | ✓ sees the fully rendered DOM |
**If you can do it with curl — use curl.** If any ✗ row applies, you need a real browser.
### The tool pattern
Every tool you build follows the same skeleton:
```
1. Load saved session → already logged in, no credentials in code
2. Navigate to page → go to the right URL
3. Interact with UI → click, fill, read, scrape, download
4. Return to Claude → result back as text Claude can reason over
```
This repo is that skeleton. You bring the use case.
---
## Architecture
**One MCP server. One Playwright browser. Unlimited tools.**
```
┌──────────────────────────────────────────────────────────────┐
│ YOUR TERMINAL │
│ │
│ You: "take a screenshot of example.com" │
│ │ │
│ ▼ │
│ ┌────────────────────────────────────────┐ │
│ │ CLAUDE CODE (CLI) │ │
│ │ │ │
│ │ Decides to call: browser_screenshot │ │
│ │ with { url: "https://example.com" } ──┼──┐ │
│ └────────────────────────────────────────┘ │ │
│ │ MCP │
│ │ stdio │
│ ┌───────────────────────────────────────────▼──────────┐ │
│ │ MCP SERVER (src/server.ts) │ │
│ │ One process — all tools registered │ │
│ │ │ │
│ │ browser_screenshot ──► src/tools/example.ts │ │
│ │ browser_get_text ──► src/tools/example.ts │ │
│ │ your_tool ──► src/tools/your-tool.ts │ │
│ │ │ │ │
│ │ ▼ │ │
│ │ ┌─────────────────────────────────┐ │ │
│ │ │ src/browser.ts (singleton) │ │ │
│ │ │ CDP → reuse your real Chrome │ │ │
│ │ │ or launch headless Chromium │ │ │
│ │ └───────────────┬─────────────────┘ │ │
│ └───────────────────┼─────────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌───────────────────────────────┐ │
│ │ PLAYWRIGHT + CHROME │ │
│ │ Opens the browser │ │
│ │ Interacts with the page │ │
│ │ Returns result to Claude │ │
│ └───────────────────────────────┘ │
└──────────────────────────────────────────────────────────────┘
```
| Question | Answer |
|---|---|
| How many MCP servers? | **One** — `src/server.ts`, single Node.js process |
| Is Playwright a server? | **No** — it's a library that runs inside tool handlers |
| How does Claude call a tool? | stdin message → server routes to handler → result over stdout |
| Do I need a port or HTTP? | **No** — stdio transport, fully local |
| What is CDP reuse? | If Chrome is open, Playwright connects to it and inherits your real sessions |
---
## Prerequisites
- **Node.js v20+** — `node -v` to check
- **Google Chrome** — installed at the default location
- **Claude Code CLI**:
```bash
npm install -g @anthropic-ai/claude-code
claude --version
```
> **Platform note:** The MCP server is cross-platform. Desktop notifications in the example tools use macOS APIs and silently no-op on other platforms.
---
## Install
```bash
git clone https://github.com/your-org/mcp-playwright.git
cd mcp-playwright
chmod +x setup.sh
./setup.sh
```
`setup.sh` checks dependencies, runs `npm install`, installs Playwright Chromium, builds the TypeScript, and prints the exact MCP config snippet for your machine.
**Manual install:**
```bash
npm install
npx playwright install chromium
npm run build
```
---
## Configure MCP in Claude Code
Get your server path:
```bash
echo "$(pwd)/dist/server.js"
```
### Option A — User-level (active across all your projects)
Edit `~/.claude/claude_desktop_config.json`:
```json
{
"mcpServers": {
"mcp-playwright": {
"command": "node",
"args": ["/absolute/path/to/mcp-playwright/dist/server.js"]
}
}
}
```
### Option B — Project-level (only active in this directory)
Create `.mcp.json` in the project root:
```json
{
"mcpServers": {
"mcp-playwright": {
"command": "node",
"args": ["/absolute/path/to/mcp-playwright/dist/server.js"]
}
}
}
```
Restart Claude Code after either option. `setup.sh` prints the ready-to-paste snippet.
---
## Verify It Works
```bash
claude --mcp-debug
```
You should see `mcp-playwright` listed with `browser_screenshot` and `browser_get_text`. Then test:
```
take a screenshot of https://example.com
```
---
## Using the Skill
```
/build-mcp-playwright
```
Scaffolds new tools, wires them into the server, and fixes build issues. Invoke from Claude Code in this project directory.
```
# Scaffold a new tool
/build-mcp-playwright my-tool "describe what it should do"
# Check build and get next steps
/build-mcp-playwright
```
See `.claude/skills/build-mcp-playwright/README.md` for full docs.
---
## Adding Your Own Tools
### 1. Create a tool file
```typescript
// src/tools/my-tool.ts
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod";
import { getContext } from "../browser.js";
import { debugScreenshot } from "../utils/screenshot.js";
export function registerMyTools(server: McpServer) {
server.tool(
"my_tool_name",
"What this tool does — Claude reads this to decide when to use it",
{
url: z.string().url().describe("URL to navigate to"),
},
async ({ url }) => {
const ctx = await getContext();
const page = await ctx.newPage();
try {
await page.goto(url);
const result = await page.title();
return { content: [{ type: "text" as const, text: result }] };
} catch (err) {
const shot = await debugScreenshot(page, "my-tool-error");
return { content: [{ type: "text" as const, text: `Error: ${err}\n${shot}` }] };
} finally {
await page.close();
await ctx.close();
}
}
);
}
```
### 2. Register in `src/server.ts`
```typescript
import { registerMyTools } from "./tools/my-tool.js";
registerMyTools(server);
```
### 3. Build and restart
```bash
npm run build
# restart Claude Code
```
---
## Browser Sessions (Login)
Save a session once. Every future run loads it automatically.
### Save a session
Add a `--login` block to your tool file:
```typescript
if (process.argv.includes("--login")) {
(async () => {
const { chromium } = await import("playwright");
const browser = await chromium.launch({ headless: false, channel: "chrome" });
const ctx = await browser.newContext();
const { loginWithPrompt } = await import("../utils/auth.js");
await loginWithPrompt(ctx, "my-site", "https://my-site.com/login", async (page) => {
return page.url().includes("my-site.com/dashboard");
});
await browser.close();
})();
}
```
Add to `package.json` scripts:
```json
"login:my-site": "npm run build && node dist/tools/my-tool.js --login"
```
Run once:
```bash
npm run login:my-site
# Chrome opens → log in manually → press Enter → session saved to sessions/my-site.json
```
### Load a session in your tool
```typescript
const ctx = await getContext("my-site"); // loads sessions/my-site.json automatically
```
Sessions live in `sessions/` which is gitignored. They are never committed.
---
## Directory Map
```
mcp-playwright/
│
├── README.md
├── CLAUDE.md # Claude Code project instructions
├── CONTRIBUTING.md
├── LICENSE
├── setup.sh # One-command install + MCP config printer
├── package.json
├── tsconfig.json
├── .gitignore
│
├── .github/
│ └── ISSUE_TEMPLATE/
│ ├── bug_report.md
│ └── feature_request.md
│
├── .claude/
│ └── skills/
│ └── build-mcp-playwright/
│ ├── SKILL.md # Invoked with /build-mcp-playwright
│ └── README.md
│
├── src/
│ ├── server.ts # MCP entry point — register tools here
│ ├── browser.ts # Playwright singleton: CDP reuse + session loading
│ ├── tools/
│ │ └── example.ts # Starter tools: browser_screenshot, browser_get_text
│ └── utils/
│ ├── auth.ts # loginWithPrompt() — interactive session saver
│ └── screenshot.ts # debugScreenshot() — capture page state on failure
│
├── sessions/ # Saved browser sessions — gitignored, never commit
│ └── .gitkeep
│
└── dist/ # Compiled JS — gitignored
```
---
## Concepts Explained
### What is MCP?
MCP (Model Context Protocol) is a standard that lets Claude call tools defined in your own code.
```
Claude Code ←→ MCP Server ←→ Your Playwright tools
```
Without MCP, Claude can only use built-in tools (Read, Write, Bash). With MCP, Claude can call any function you define.
### stdio vs HTTP transport
This repo uses **stdio**: Claude Code spawns the server as a child process, communication over stdin/stdout — no port, no network, fully local.
HTTP transport exists for remote/cloud-hosted MCP servers. Not what this repo does.
### CDP Reuse
`browser.ts` first tries to connect to your already-open Chrome via CDP (port 9222). If Chrome is running and logged into sites, Playwright inherits those sessions for free. Falls back to headless Chromium if Chrome isn't open.
### Skill vs Agent
- **Skill** (`SKILL.md`) — instructions Claude follows when you invoke `/skill-name`
- **Agent** — Claude taking multi-step autonomous actions using tools
The `/build-mcp-playwright` skill makes Claude act like an agent: it reads your request, scaffolds files, runs the build, and iterates until it works.
---
## Troubleshooting
| Problem | Fix |
|---|---|
| `mcp-playwright` not in Claude | `claude --mcp-debug` → check `dist/server.js` exists → `npm run build` → restart Claude Code |
| Tool call fails silently | Check `debug-screenshots/` for a captured failure state |
| Bot detection / Cloudflare | Set `headless: false` in `getBrowser()` to watch live; re-run login script |
| Session expired | Re-run `npm run login:<site>` |
| `chrome not found` | Install Google Chrome, or remove `channel: "chrome"` in `browser.ts` to use bundled Chromium |
| CDP connection refused | Chrome isn't running — server falls back to headless automatically |
| TypeScript build errors | Imports must use `.js` extension (`../browser.js` not `../browser`) — required for ESM |
---
## Contributing
See [CONTRIBUTING.md](CONTRIBUTING.md).
TDQS
Scored across 2 tools
Both tools share the same navigation preamble but produce clearly different outputs (image file vs. text), so an agent can distinguish them by intent. The only mild overlap is the navigate-to-URL step, which does not create real misselection risk.
Both tools use a consistent snake_case browser_ prefix, making the set easy to scan. Minor deviation: browser_screenshot omits an explicit verb while browser_get_text follows a verb_noun pattern.
Two tools is thin for something branded as a Playwright/browser server, which implies rich interaction. It is not egregious, but the surface feels under-scoped relative to the name.
Only read-only navigation and content extraction are available; there is no click, type/fill, wait, evaluate, or session-close capability. For a browser automation server this is a significant gap that will block most interactive workflows.