Skip to main content
Glama
mcp-playwright

mcp-playwright

by vnikhilk

mcp-playwright

License: MIT Node.js MCP Playwright

A starter template for building MCP (Model Context Protocol) servers with Playwright browser automation, for use with Claude 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?

  2. When Do You Need This?

  3. Architecture

  4. Prerequisites

  5. Install

  6. Configure MCP in Claude Code

  7. Verify It Works

  8. Using the Skill

  9. Adding Your Own Tools

  10. Browser Sessions (Login)

  11. Directory Map

  12. Concepts Explained

  13. Troubleshooting

  14. Contributing


Related MCP server: Glance

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:

    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

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:

npm install
npx playwright install chromium
npm run build

Configure MCP in Claude Code

Get your server path:

echo "$(pwd)/dist/server.js"

Option A — User-level (active across all your projects)

Edit ~/.claude/claude_desktop_config.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:

{
  "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

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

// 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

import { registerMyTools } from "./tools/my-tool.js";
registerMyTools(server);

3. Build and restart

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:

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:

"login:my-site": "npm run build && node dist/tools/my-tool.js --login"

Run once:

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

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.

Available Tools

2 tools
browser_get_textC

Navigate to a URL and return the visible text content of the page.

Inputs: url (required), selector.

browser_screenshotA

Navigate to a URL and take a full-page screenshot. Returns the saved file path.

Inputs: url (required), filename.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    B3.2/5.0

    Scored across 2 tools

    Disambiguation4/5

    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.

    Naming Consistency4/5

    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.

    Tool Count3/5

    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.

    Completeness2/5

    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.

    Maintenance

    ActivityInactive
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      B
      quality
      A
      maintenance
      Enables Claude and other MCP clients to drive a real browser by opening pages, clicking elements, filling form fields, capturing PNG screenshots, and extracting visible text. It runs as a lightweight Node process over stdio with lazy-loaded Playwright for fast startup.
      5
      2
      MIT
    • A
      license
      Not graded
      quality
      Not graded
      maintenance
      Enables Claude Code to control a real browser for navigating, clicking, typing, capturing screenshots, running multi-step E2E tests, assertions, visual regression, and session recording from the terminal.
      106 npm
      MIT
    • A
      license
      Not graded
      quality
      A
      maintenance
      Enables Claude Code to drive a real browser, so you can navigate, click, type, screenshot, and run multi-step test scenarios with assertions, visual regression, and console/network monitoring straight from the terminal.
      106 npm
      MIT
    • A
      license
      Not graded
      quality
      A
      maintenance
      Gives Claude Code a real browser so it can navigate, click, type, screenshot, and assert against web pages directly from the terminal. Enables multi-step test scenarios, visual regression checks, session recording, and console/network error monitoring with security controls.
      106 npm
      MIT