Skip to main content
Glama
SJMakin

even-better-playwright-mcp

by SJMakin

even-better-playwright-mcp

The best of all worlds Playwright MCP server - combining intelligent DOM compression, code execution, visual labels, and advanced DevTools capabilities.

Features

  • ๐ŸŽญ Full Playwright API - Execute any Playwright code via the execute tool

  • ๐Ÿ—๏ธ 90%+ DOM Compression - SimHash-based list folding and wrapper removal

  • ๐Ÿ“ Ref-Based Elements - Stable [ref=e1] identifiers with aria-ref selectors

  • ๐Ÿ” Enhanced Search & Diff - Search snapshots with regex, track changes with diff mode

  • ๐ŸŽฏ Visual Labels - Vimium-style overlays for screenshot-based interaction

  • ๐Ÿ”ง Advanced DevTools - Debugger, live editor, styles inspection, React source finding

  • ๐ŸŒ Network Capture - Request/response interception with analytics filtering

  • โฑ๏ธ Smart Page Load - Intelligent wait that filters analytics and stuck requests

  • ๐Ÿ“ Browser Console Logs - Persistent per-page logging with search and filtering

  • ๐Ÿงน Clean HTML - Get LLM-friendly HTML with search and diff capabilities

  • ๐Ÿ”’ Sandboxed Execution - Safe VM with scoped file system and module allowlist

Related MCP server: MCP Playwright Server

Installation

npm install -g even-better-playwright-mcp

Or use directly with npx:

npx even-better-playwright-mcp

Configuration

Add to your MCP client settings (e.g., Claude Desktop's claude_desktop_config.json):

{
  "mcpServers": {
    "playwright": {
      "command": "npx",
      "args": ["even-better-playwright-mcp"]
    }
  }
}

CLI Options

Usage: even-better-playwright-mcp [options]

Options:
  --browser <browser>       Browser to use: chromium, firefox, webkit (default: chromium)
  --headless               Run browser in headless mode (default: false)
  --cdp-endpoint <url>     Connect to existing browser via CDP endpoint
  --user-data-dir <path>   Use persistent browser profile directory
  -h, --help               Show help message

Examples

# Basic usage (launches Chromium in headed mode)
even-better-playwright-mcp

# Use Firefox in headless mode
even-better-playwright-mcp --browser firefox --headless

# Connect to existing Chrome instance
even-better-playwright-mcp --cdp-endpoint ws://localhost:9222

# Use persistent profile
even-better-playwright-mcp --user-data-dir ./browser-profile

Tools

1. snapshot - Get Page Structure

Get compressed accessibility snapshot with ref IDs for element targeting.

Returns: DOM tree with [ref=e1], [ref=e2] etc.
Use refs with execute tool: await $('e1').click()
Call again after navigation (refs become stale).

Options:

  • compress (boolean, default: true) - Enable smart compression (~90% token reduction)

  • search (string | RegExp) - Search pattern to filter results with 5 lines of context

  • showDiff (boolean, default: false) - Show changes since last snapshot

Example output:

### Page Info
- URL: https://example.com
- Title: Example Domain

### Accessibility Snapshot
- document [ref=e1]
  - heading "Example Domain" [level=1] [ref=e2]
  - paragraph [ref=e3]: This domain is for use in illustrative examples...
  - link "More information..." [ref=e4]

2. browser_execute - Run Playwright Code

Execute any Playwright code with full API access. This is the main tool for browser automation.

Scope variables:

  • page - Current Playwright page

  • context - Browser context

  • state - Persistent object across calls

  • $('e5') - Shorthand for page.locator('aria-ref=e5')

  • accessibilitySnapshot() - Get current page snapshot

  • waitForPageLoad() - Smart page load detection (filters analytics/ads)

  • getLatestLogs() - Get browser console logs with search/filtering

  • clearAllLogs() - Clear all stored console logs

  • getCleanHTML() - Get cleaned HTML with search and diff

  • getLocatorStringForElement() - Generate selector string from element

Common patterns:

// Navigate
await page.goto('https://example.com')

// Click by ref (from snapshot)
await $('e5').click()

// Fill input
await $('e12').fill('search query')

// Get text
const text = await $('e3').textContent()

// Wait for network (smart detection, filters analytics/ads)
const result = await waitForPageLoad({ timeout: 30000 })
// => { success: true, waitTimeMs: 1234, pendingRequests: [] }

// Screenshot
await page.screenshot({ path: 'screenshot.png' })

Advanced - DevTools access:

// Get CDP session for debugging
const cdp = await getCDPSession({ page })
const dbg = createDebugger({ cdp })

// Set breakpoint
await dbg.setBreakpoint({ file: 'app.js', line: 42 })

// Inspect styles
const styles = await getStylesForLocator({ locator: $('e5') })

// Find React component source
const source = await getReactSource({ locator: $('e5') })
// => { fileName: 'Button.tsx', lineNumber: 42 }

Browser Console Logs:

// Get latest 50 console logs from current page
const logs = await getLatestLogs({ count: 50 })

// Search logs with regex
const errorLogs = await getLatestLogs({ search: /error|warning/i })

// Get logs from all pages
const allLogs = await getLatestLogs()

// Clear all stored logs
clearAllLogs()

HTML Utilities:

// Get cleaned HTML from page or element
const html = await getCleanHTML({
  locator: page,  // or $('e5') for specific element
  maxContentLen: 500
})

// Search within HTML
const forms = await getCleanHTML({
  locator: page,
  search: 'form'
})

// Track HTML changes
const diff = await getCleanHTML({
  locator: page,
  showDiffSinceLastCall: true
})

// Generate readable selector for element
const button = $('e5')
const selector = await getLocatorStringForElement(button)
// => "page.getByRole('button', { name: 'Submit' })"

Safe modules via require(): path, url, crypto, buffer, util, assert, os, fs (sandboxed)

3. screenshot - Capture Page Image

Capture screenshots with optional visual ref labels.

Options:

  • ref (string) - Screenshot specific element by ref

  • fullPage (boolean) - Capture entire scrollable area

  • withLabels (boolean) - Show Vimium-style ref labels

Label colors by role:

Color

Role

Yellow

links

Orange

buttons

Coral

text inputs

Pink

checkboxes, radios

Blue

images, videos

4. browser_search_snapshot - Search Content

Search the last captured snapshot using regex patterns.

Options:

  • pattern (string) - Regex pattern to search for

  • ignoreCase (boolean, default: false) - Case-insensitive matching

  • lineLimit (number, default: 100) - Maximum lines to return

Example:

Pattern: "button|link"
Result:
- link "Contact Us" [ref=e15]
- button "Submit" [ref=e23]
- link "Privacy Policy" [ref=e31]

5. browser_network_requests - Capture Network Traffic

Get captured network requests with automatic filtering of analytics and ads.

Options:

  • includeStatic (boolean, default: false) - Include images, CSS, fonts

  • limit (number, default: 50) - Max requests to return (most recent)

  • clear (boolean, default: false) - Clear captured requests after returning

Features:

  • Automatically starts capturing on first call

  • Filters analytics/tracking domains (Google Analytics, Facebook Pixel, etc.)

  • Captures request/response bodies (up to 50KB)

  • Shows status codes, timing, and response previews

Example:

Network Requests (127 total, showing last 50):

POST https://api.example.com/login [200] (245ms)
  POST: {"email":"user@example.com","password":"***"}
  RESPONSE: {"token":"eyJ...","user":{"id":123,"name":"John"}}

GET https://api.example.com/profile [200] (89ms)
  RESPONSE: {"id":123,"name":"John","email":"user@example.com"}

Workflow

Basic Automation

  1. Get page structure

    Use: snapshot tool
    โ†’ See all interactive elements with refs
  2. Interact with elements

    Use: execute tool
    Code: await $('e5').click()
  3. After navigation, refresh refs

    Use: snapshot tool again
    โ†’ Refs are stale after navigation

Visual Automation

  1. Take labeled screenshot

    Use: screenshot tool with withLabels: true
    โ†’ See visual labels overlaid on elements
  2. Identify element from image

    Label shows: "e5" on a button
  3. Click using ref

    Use: execute tool
    Code: await $('e5').click()

Architecture

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚                     even-better-playwright-mcp                  โ”‚
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚  CORE                                                           โ”‚
โ”‚  โ”œโ”€โ”€ aria-ref selector system ([ref=e1], [ref=e2], etc.)       โ”‚
โ”‚  โ”œโ”€โ”€ page._snapshotForAI() for accessibility snapshots         โ”‚
โ”‚  โ””โ”€โ”€ Standard Playwright browser automation                     โ”‚
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚  ENHANCED SNAPSHOT                                              โ”‚
โ”‚  โ”œโ”€โ”€ SimHash-based list folding (compress 48 items โ†’ 2 lines)  โ”‚
โ”‚  โ”œโ”€โ”€ Useless wrapper removal                                    โ”‚
โ”‚  โ”œโ”€โ”€ Regex-powered content search with context                  โ”‚
โ”‚  โ””โ”€โ”€ Diff tracking (compare snapshots over time)                โ”‚
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚  CODE EXECUTION                                                 โ”‚
โ”‚  โ”œโ”€โ”€ browser_execute tool (run Playwright code in VM sandbox)  โ”‚
โ”‚  โ”œโ”€โ”€ Sandboxed require (safe module allowlist)                  โ”‚
โ”‚  โ”œโ”€โ”€ Scoped file system (cwd, /tmp only)                       โ”‚
โ”‚  โ””โ”€โ”€ Console log capture and forwarding                         โ”‚
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚  PERSISTENT LOGGING                                             โ”‚
โ”‚  โ”œโ”€โ”€ Per-page browser console capture (5000 log limit)         โ”‚
โ”‚  โ”œโ”€โ”€ Logs persist across executions and reconnections          โ”‚
โ”‚  โ”œโ”€โ”€ Search logs with regex and context                         โ”‚
โ”‚  โ””โ”€โ”€ Auto-clear on navigation                                   โ”‚
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚  NETWORK & PAGE UTILITIES                                       โ”‚
โ”‚  โ”œโ”€โ”€ Network capture with analytics filtering                   โ”‚
โ”‚  โ”œโ”€โ”€ Smart page load (filters stuck/analytics requests)        โ”‚
โ”‚  โ”œโ”€โ”€ Clean HTML extraction with search/diff                     โ”‚
โ”‚  โ””โ”€โ”€ Selector string generation from elements                   โ”‚
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚  ADVANCED DEVTOOLS                                              โ”‚
โ”‚  โ”œโ”€โ”€ Debugger class (breakpoints, step, inspect variables)     โ”‚
โ”‚  โ”œโ”€โ”€ Editor class (live code editing without reload)           โ”‚
โ”‚  โ”œโ”€โ”€ Styles inspection (CSS like DevTools panel)               โ”‚
โ”‚  โ””โ”€โ”€ React source finding (component file/line locations)      โ”‚
โ”œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ค
โ”‚  VISUAL OVERLAYS                                                โ”‚
โ”‚  โ”œโ”€โ”€ Vimium-style labels on interactive elements               โ”‚
โ”‚  โ”œโ”€โ”€ Color-coded by role (links=yellow, buttons=orange, etc.)  โ”‚
โ”‚  โ””โ”€โ”€ Screenshot with visible ref labels                         โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Ref System

All projects use the same ref system built into Playwright:

  • Snapshots generate refs like [ref=e1]

  • Selectors use page.locator('aria-ref=e1')

  • Shorthand $('e1') in execute tool

Important: Refs become stale after navigation. Always call snapshot again after page.goto() or clicking links that navigate.

Compression Algorithm

The snapshot compression achieves ~90% token reduction:

Original DOM (5000+ lines)
    โ†“ removeUselessWrappers()
    โ†“ truncateText(50 chars)
    โ†“ detectSimilarPatterns(SimHash)
    โ†“ foldLists()
Compressed (<500 lines)

Example:

Before:
- listitem [ref=e234]: Product 1 - Description...
- listitem [ref=e235]: Product 2 - Description...
- listitem [ref=e236]: Product 3 - Description...
... (48 items)

After:
- listitem [ref=e234]: Product 1 - Description...
- listitem (... and 47 more similar) [refs: e235, e236, ...]

Error Handling

The execute tool provides contextual hints:

  • Stale ref: "Page may have navigated. Refs are stale after navigation. Call snapshot tool to get fresh refs."

  • Timeout: "Operation timed out. Try increasing timeout or check if element exists/is visible."

  • Hidden element: "Element may be hidden or covered by another element. Try scrolling or closing overlays."

  • Connection lost: "Browser connection lost. The browser may have been closed - try again to relaunch."

Programmatic Usage

The server can be used as a library with full programmatic control:

import { createServerInstance, BrowserManager } from 'even-better-playwright-mcp';

// Create server instance with custom config
const { server, browserManager, cleanup } = createServerInstance({
  browser: 'chromium',
  headless: true,
  isolated: true,  // Force ephemeral context
  launchOptions: {
    slowMo: 50,
    args: ['--disable-blink-features=AutomationControlled']
  },
  contextOptions: {
    viewport: { width: 1920, height: 1080 },
    userAgent: 'Custom User Agent'
  }
});

// Connect your transport
await server.connect(transport);

// Cleanup when done
await cleanup();

BrowserConfig Options

  • browser - Browser type: 'chromium', 'firefox', 'webkit'

  • headless - Run in headless mode

  • cdpEndpoint - Connect to existing browser via CDP

  • userDataDir - Persistent browser profile directory

  • isolated - Force ephemeral context (overrides userDataDir)

  • launchOptions - Pass-through to Playwright's browser.launch()

  • contextOptions - Pass-through to browser.newContext()

Multi-Session Support

Each BrowserManager instance has isolated state:

  • Independent browser/context/page

  • Separate network capture

  • Isolated console logs

  • Per-instance persistent state

// Create multiple isolated sessions
const session1 = createServerInstance({ browser: 'chromium' });
const session2 = createServerInstance({ browser: 'firefox' });

// Each has its own browser and state
await session1.browserManager.getPage();
await session2.browserManager.getPage();

Development

Building from Source

git clone https://github.com/your-repo/even-better-playwright-mcp
cd even-better-playwright-mcp
npm install
npm run build

Running Tests

The project includes comprehensive end-to-end tests:

# Build first
npm run build

# Run e2e tests
npm run test:e2e

# Run all tests
npm test

Test Coverage: 15 tests covering all MCP tools against Hacker News

  • Tool discovery and validation

  • Browser automation (navigate, click, fill forms)

  • Accessibility snapshots with ref system

  • Screenshot capture

  • Network request monitoring

  • Persistent state management

  • Error and timeout handling

  • Full end-to-end workflows

See test/README.md for detailed test documentation.

Project Structure

even-better-playwright-mcp/
โ”œโ”€โ”€ bin/
โ”‚   โ””โ”€โ”€ cli.ts                  # CLI entry point with arg parsing
โ”œโ”€โ”€ src/
โ”‚   โ”œโ”€โ”€ index.ts                # MCP server factory (createServerInstance)
โ”‚   โ”œโ”€โ”€ browser.ts              # BrowserManager class (refactored!)
โ”‚   โ”œโ”€โ”€ vm-context.ts           # VM sandbox setup
โ”‚   โ”œโ”€โ”€ tools/
โ”‚   โ”‚   โ”œโ”€โ”€ snapshot.ts         # Snapshot tool (compressed + search + diff)
โ”‚   โ”‚   โ”œโ”€โ”€ execute.ts          # Execute tool (main)
โ”‚   โ”‚   โ”œโ”€โ”€ screenshot.ts       # Screenshot tool (with labels)
โ”‚   โ”‚   โ”œโ”€โ”€ search.ts           # Search tool
โ”‚   โ”‚   โ””โ”€โ”€ network.ts          # Network capture tool
โ”‚   โ”œโ”€โ”€ utils/
โ”‚   โ”‚   โ”œโ”€โ”€ smart-outline.ts    # DOM compression
โ”‚   โ”‚   โ”œโ”€โ”€ list-detector.ts    # Pattern detection
โ”‚   โ”‚   โ”œโ”€โ”€ dom-simhash.ts      # SimHash implementation
โ”‚   โ”‚   โ”œโ”€โ”€ scoped-fs.ts        # Sandboxed file system
โ”‚   โ”‚   โ”œโ”€โ”€ search.ts           # Regex search
โ”‚   โ”‚   โ”œโ”€โ”€ browser-logs.ts     # Persistent console logging
โ”‚   โ”‚   โ”œโ”€โ”€ clean-html.ts       # HTML cleaning with search/diff
โ”‚   โ”‚   โ”œโ”€โ”€ locator-string.ts   # Selector generation
โ”‚   โ”‚   โ”œโ”€โ”€ wait-for-page-load.ts  # Smart page load detection
โ”‚   โ”‚   โ”œโ”€โ”€ network-capture.ts  # Network request capture
โ”‚   โ”‚   โ””โ”€โ”€ console-capture.ts  # Console log capture
โ”‚   โ”œโ”€โ”€ devtools/
โ”‚   โ”‚   โ”œโ”€โ”€ cdp-session.ts      # CDP connection
โ”‚   โ”‚   โ”œโ”€โ”€ debugger.ts         # Debugger class
โ”‚   โ”‚   โ”œโ”€โ”€ editor.ts           # Live editor
โ”‚   โ”‚   โ”œโ”€โ”€ styles.ts           # CSS inspection
โ”‚   โ”‚   โ””โ”€โ”€ react-source.ts     # React locations
โ”‚   โ””โ”€โ”€ visual/
โ”‚       โ””โ”€โ”€ aria-labels.ts      # Vimium-style overlays
โ”œโ”€โ”€ test/
โ”‚   โ”œโ”€โ”€ e2e.test.js            # Comprehensive E2E test suite
โ”‚   โ””โ”€โ”€ README.md              # Test documentation
โ”œโ”€โ”€ package.json
โ”œโ”€โ”€ tsconfig.json
โ””โ”€โ”€ README.md

Recent Refactoring (v0.1.0)

The codebase was refactored from global module-level state to a clean, testable architecture:

Before: Global functions and singletons

import { getPage, getContext } from './browser.js';
const page = await getPage(); // Global state

After: Dependency injection with BrowserManager

const browserManager = new BrowserManager(config);
const page = await browserManager.getPage(); // Instance state

Benefits:

  • โœ… Multi-session support (multiple isolated browsers)

  • โœ… Better testability (no global state)

  • โœ… Library-friendly API (clean exports)

  • โœ… Full Playwright configuration control

  • โœ… Flexible browser lifecycle management

All tool handlers now use factory functions with dependency injection:

const handleSnapshot = createSnapshotHandler(browserManager);
const handleExecute = createExecuteHandler(browserManager);

Acknowledgments

This project combines the best ideas from:

License

MIT

Available Tools

5 tools
browser_executeA

Execute Playwright code with these in scope:

  • page - Current Playwright page

  • context - Browser context, access all pages via context.pages()

  • state - Persistent object across calls (e.g., state.myPage = await context.newPage())

  • $('e5') - Shorthand for page.locator('aria-ref=e5')

  • accessibilitySnapshot() - Get current page snapshot

  • require - Load Node.js modules (path, url, crypto, buffer, util, assert, os, fs)

  • Node.js globals: setTimeout, setInterval, fetch, URL, Buffer, crypto, etc.

Rules

  • Multiple calls: Use multiple execute calls for complex logic - helps understand intermediate state and isolate failures

  • Never close: Never call browser.close() or context.close(). Only close pages you created or if user asks

  • No bringToFront: Never call unless user asks - it's disruptive and unnecessary

  • Check state after actions: Always verify page state after clicking/submitting (see next section)

  • Clean up listeners: Call page.removeAllListeners() at end to prevent leaks

  • Wait for load: Use page.waitForLoadState('domcontentloaded') not page.waitForEvent('load') - waitForEvent times out if already loaded

  • Avoid timeouts: Prefer proper waits over page.waitForTimeout() - there are better ways

Checking Page State

After any action (click, submit, navigate), verify what happened:

console.log('url:', page.url()); console.log(await accessibilitySnapshot().then(x => x.split('\n').slice(0, 30).join('\n')));

For visually complex pages (grids, galleries, dashboards), use screenshotWithAccessibilityLabels({ page }) instead.

Accessibility Snapshots

await accessibilitySnapshot()  // Full snapshot
await accessibilitySnapshot({ search: /button|submit/i })  // Filter results
await accessibilitySnapshot({ showDiffSinceLastCall: true })  // Show changes

Example output:

- banner [ref=e3]:
    - link "Home" [ref=e5] [cursor=pointer]:
        - /url: /
    - navigation [ref=e12]:
        - link "Docs" [ref=e13] [cursor=pointer]

Use aria-ref to interact - NO quotes around the ref value:

await page.locator('aria-ref=e13').click()  // or: await $('e13').click()

For pagination: (await accessibilitySnapshot()).split('\n').slice(0, 50).join('\n')

Choosing snapshot method:

  • Use accessibilitySnapshot for simple pages, text search, token efficiency

  • Use screenshotWithAccessibilityLabels for complex visual layouts, spatial position matters

Selector Best Practices

For unknown sites: use accessibilitySnapshot() with aria-ref For development (with source access), prefer:

  1. [data-testid="submit"] - explicit test attributes

  2. getByRole('button', { name: 'Save' }) - semantic

  3. getByText('Sign in'), getByLabel('Email') - user-facing

  4. input[name="email"] - semantic HTML

  5. Avoid: classes/IDs that change frequently

If locator matches multiple elements (strict mode violation), use .first(), .last(), or .nth(n):

await page.locator('button').first().click()
await page.locator('li').nth(3).click()  // 4th item (0-indexed)

Working with Pages

const pages = context.pages().filter(x => x.url().includes('localhost'));
state.newPage = await context.newPage(); await state.newPage.goto('https://example.com');

Navigation

await page.goto('https://example.com', { waitUntil: 'domcontentloaded' });
await waitForPageLoad({ page, timeout: 5000 });

Common Patterns

Popups: const [popup] = await Promise.all([page.waitForEvent('popup'), page.click('a[target=_blank]')]); await popup.waitForLoadState(); Downloads: const [download] = await Promise.all([page.waitForEvent('download'), page.click('button.download')]); await download.saveAs('/tmp/' + download.suggestedFilename()); iFrames: const frame = page.frameLocator('#my-iframe'); await frame.locator('button').click(); Dialogs: page.on('dialog', async d => { await d.accept(); }); await page.click('button'); Load files: const fs = require('fs'); const content = fs.readFileSync('./data.txt', 'utf-8'); await page.locator('textarea').fill(content);

page.evaluate

Code inside page.evaluate() runs in the browser - use plain JavaScript only. console.log inside evaluate runs in browser, not visible here:

const title = await page.evaluate(() => document.title);
console.log('Title:', title);  // Log outside evaluate

Utility Functions

  • getLatestLogs({ page?, count?, search? }) - Get browser console logs

  • getCleanHTML({ locator, search?, showDiffSinceLastCall?, includeStyles? }) - Get cleaned HTML

  • waitForPageLoad({ page, timeout? }) - Smart load detection (ignores analytics/ads)

  • getCDPSession() - Get CDP session for raw Chrome DevTools Protocol commands

  • getLocatorStringForElement(locator) - Get stable selector from ephemeral aria-ref

  • getReactSource({ locator }) - Get React component source location (dev mode only)

  • getStylesForLocator({ locator, cdp }) - Inspect CSS styles (read styles-api resource first)

  • createDebugger({ cdp }) - Set breakpoints, step through code (read debugger-api resource first)

  • createEditor({ cdp }) - View/edit page scripts and CSS (read editor-api resource first)

  • screenshotWithAccessibilityLabels({ page }) - Screenshot with Vimium-style visual labels (yellow=links, orange=buttons, coral=inputs)

Network Interception

For scraping/reverse-engineering APIs, intercept network instead of scrolling DOM:

state.requests = []; state.responses = [];
page.on('request', req => { if (req.url().includes('/api/')) state.requests.push({ url: req.url(), method: req.method(), headers: req.headers() }); });
page.on('response', async res => { if (res.url().includes('/api/')) { try { state.responses.push({ url: res.url(), status: res.status(), body: await res.json() }); } catch {} } });

Then trigger actions and analyze: console.log('Captured', state.responses.length, 'API calls'); Clean up when done: page.removeAllListeners('request'); page.removeAllListeners('response');

IMPORTANT: After navigation, refs are stale - call snapshot tool again.

ParametersJSON Schema
NameRequiredDescriptionDefault
codeYesPlaywright code with {page, context, state, $} in scope. Should be concise - use ; for multiple statements.
timeoutNoTimeout in milliseconds (default: 30000)

TDQS

A4.6/5.0
Behavior5/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden of behavioral disclosure. It thoroughly describes behavioral traits, including rules for multiple calls, cleanup (e.g., removeAllListeners), load waiting strategies, timeout avoidance, and state verification after actions. It also covers navigation handling, common patterns, and utility functions, providing comprehensive operational context.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness2/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is excessively long and poorly structured, with extensive code examples, utility function listings, and detailed best practices that could be better organized or referenced elsewhere. It lacks front-loading of critical information, burying key usage guidelines in sections like 'Rules' and 'Checking Page State', making it less efficient for quick understanding.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness5/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the complexity of the tool (executing Playwright code with multiple behavioral nuances) and the absence of annotations and output schema, the description is highly complete. It covers purpose, usage guidelines, behavioral transparency, parameter semantics through examples, and extensive operational details, ensuring the agent has all necessary context to use the tool effectively.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The schema description coverage is 100%, so the baseline is 3. The description adds significant value by explaining the semantics of the 'code' parameter in detail, such as the available in-scope objects (page, context, state, $) and examples of usage patterns. However, it does not explicitly mention the 'timeout' parameter, which is documented in the schema, leaving a minor gap.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description starts with a clear verb ('Execute') and resource ('Playwright code'), specifying exactly what the tool does. It distinguishes itself from siblings like browser_network_requests, browser_search_snapshot, screenshot, and snapshot by focusing on code execution rather than network monitoring, searching, or visual capture.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines5/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides explicit guidance on when to use this tool versus alternatives, such as recommending multiple execute calls for complex logic, avoiding browser.close() unless specified, and using accessibilitySnapshot for simple pages versus screenshotWithAccessibilityLabels for complex layouts. It also contrasts with siblings by emphasizing code execution over other browser interactions.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

browser_network_requestsA

Get captured network requests from the browser. Automatically starts capturing when first called. Use includeStatic:true to include images/CSS/fonts. Returns recent requests with status, timing, and response previews.

ParametersJSON Schema
NameRequiredDescriptionDefault
includeStaticNoWhether to include successful static resources like images, fonts, scripts, etc. Defaults to false.
limitNoMaximum number of requests to return (most recent). Defaults to 50.
clearNoClear captured requests after returning them. Defaults to false.

TDQS

A4.2/5.0
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden of behavioral disclosure. It effectively describes key traits: the tool automatically initiates capture on first call, returns recent requests with status/timing/response previews, and includes a parameter (clear) that affects state by optionally clearing captured data. However, it lacks details on rate limits, error handling, or authentication needs.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is front-loaded with the core purpose, followed by key behavioral details and parameter usage, all in three concise sentences with zero wasted words. Each sentence adds essential information, making it efficient and well-structured for quick understanding.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's moderate complexity (3 parameters, no output schema, no annotations), the description is largely complete: it covers purpose, automatic behavior, key parameter usage, and return content. However, it lacks details on output format specifics (e.g., structure of 'response previews') and potential side effects beyond clearing, which could be beneficial for full contextual understanding.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so the schema already documents all parameters (includeStatic, limit, clear) with their types and defaults. The description adds minimal value by mentioning includeStatic's effect ('to include images/CSS/fonts') but does not provide additional syntax or format details beyond the schema. This meets the baseline for high schema coverage.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose with specific verbs ('Get captured network requests from the browser') and distinguishes it from sibling tools like browser_execute or screenshot by focusing on network monitoring rather than execution or visual capture. It specifies the resource (network requests) and the action (retrieval with automatic capture initiation).

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides clear context for when to use the tool (e.g., 'Automatically starts capturing when first called' and 'Use includeStatic:true to include images/CSS/fonts'), but it does not explicitly state when not to use it or name alternatives among sibling tools. This gives practical guidance without full exclusion criteria.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

browser_search_snapshotA

Search current snapshot with regex.

Requires: Call snapshot first. Returns: Matching lines with refs.

Options:

  • pattern: Regex pattern to search for

  • ignoreCase: Case-insensitive matching (default: false)

  • lineLimit: Max lines to return (default: 100)

Use this to find specific elements in large pages without re-reading the entire snapshot.

ParametersJSON Schema
NameRequiredDescriptionDefault
patternYesRegex pattern to search for in the snapshot
ignoreCaseNoWhether to ignore case when matching
lineLimitNoMaximum number of lines to return (1-100)

TDQS

A4.4/5.0
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries full burden and does well by specifying prerequisites, return format ('Matching lines with refs'), and practical use case. It doesn't mention rate limits or error conditions, but covers key behavioral aspects like dependency on snapshot and output format.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Well-structured with clear sections: purpose statement, requirements, returns, options list, and usage context. Every sentence adds value with no redundancy. The options section efficiently documents parameters without repeating schema details unnecessarily.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a tool with no annotations and no output schema, the description provides good context about prerequisites, practical use case, and what to expect in returns. It could benefit from more detail about the 'refs' in return values or error handling, but covers the essentials well given the tool's complexity.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so the schema already documents all parameters thoroughly. The description lists parameters with brief explanations but adds minimal value beyond what's in the schema. The baseline of 3 is appropriate since the schema does the heavy lifting.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool searches a snapshot with regex, specifying both the action (search) and resource (current snapshot). It distinguishes from siblings like browser_execute or screenshot by focusing on text search within snapshots rather than execution or visual capture.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines5/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

Explicitly states 'Requires: Call snapshot first' as a prerequisite and provides context for when to use it ('to find specific elements in large pages without re-reading the entire snapshot'). This clearly differentiates it from tools like browser_network_requests or screenshot that serve different purposes.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

screenshotA

Capture page screenshot.

Options:

  • ref: Screenshot specific element by ref (e.g., 'e5')

  • fullPage: Capture entire scrollable area

  • withLabels: Show Vimium-style ref labels on interactive elements

When withLabels is used, labels are color-coded by role:

  • Yellow: links

  • Orange: buttons

  • Coral: text inputs

  • Pink: checkboxes/radios

  • Blue: images/videos

ParametersJSON Schema
NameRequiredDescriptionDefault
refNoElement ref from snapshot to screenshot. If not provided, screenshots the viewport.
fullPageNoTake full page screenshot instead of viewport.
withLabelsNoShow Vimium-style ref labels on interactive elements in the screenshot.

TDQS

A3.9/5.0
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden of behavioral disclosure. It does well by explaining the visual output behavior when 'withLabels' is used (color-coding by element role), which goes beyond the basic screenshot functionality. However, it doesn't mention potential side effects, performance implications, or error conditions.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is perfectly structured and concise. It starts with the core purpose, then presents options in a clear bulleted format, and provides specific details about the color-coding system. Every sentence earns its place with no wasted words, and information is front-loaded appropriately.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a tool with 3 parameters, 100% schema coverage, but no annotations or output schema, the description does quite well. It explains the tool's purpose, parameter usage, and visual output behavior. The main gap is lack of information about return values or error handling, but given the context, it's reasonably complete.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The schema description coverage is 100%, so the baseline would be 3. However, the description adds significant value by explaining the practical meaning of parameters: 'ref' screenshots specific elements, 'fullPage' captures scrollable areas, and 'withLabels' shows interactive element labels with detailed color-coding. This provides context beyond the schema's technical descriptions.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose with 'Capture page screenshot' - a specific verb+resource combination. However, it doesn't explicitly differentiate from sibling tools like 'snapshot' or 'browser_search_snapshot', which might have overlapping functionality. The purpose is clear but lacks sibling differentiation.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides implied usage guidance through the 'Options' section, explaining what each parameter does. However, it doesn't explicitly state when to use this tool versus alternatives like 'snapshot' or provide clear exclusions. The guidance is present but not comprehensive about tool selection.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

snapshotA

Get compressed accessibility snapshot with ref IDs.

Returns: DOM tree with [ref=e1], [ref=e2] etc. Use refs with execute tool: await $('e1').click() Call again after navigation (refs become stale).

Options:

  • compress: Enable smart compression (default: true) Reduces token usage by ~90% via list folding and wrapper removal.

  • search: Search pattern (string or regex) to filter results with context

  • showDiff: Show changes since last snapshot (useful for tracking page updates)

ParametersJSON Schema
NameRequiredDescriptionDefault
compressNoWhether to compress the snapshot using smart outline
searchNoSearch pattern (string or regex) to filter snapshot results
showDiffNoShow diff since last snapshot call

TDQS

A4.2/5.0
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries full burden and adds valuable behavioral context beyond the input schema. It discloses that refs become stale after navigation, explains the token reduction benefit of compression (~90%), and describes how refs are used with execute tool. It doesn't mention rate limits, authentication needs, or error conditions, but provides substantial operational guidance for a tool with no annotations.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is appropriately sized and well-structured. It front-loads the core purpose, then provides return format details, usage notes, and parameter explanations in logical sections. Every sentence adds value: the first states purpose, the next two explain ref usage, and the parameter section clarifies options with practical benefits. No wasted words or redundancy.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given 3 parameters with 100% schema coverage and no output schema, the description provides good contextual completeness. It explains the return format (DOM tree with refs), ref usage patterns, navigation constraints, and practical benefits of parameters. For a tool with no annotations and no output schema, it covers most essential context, though it could mention error cases or performance characteristics more explicitly.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so the schema already documents all parameters thoroughly. The description adds minimal value beyond the schema: it restates the purpose of 'search' and 'showDiff' similarly to the schema, and adds the token reduction percentage for 'compress'. Since the schema does heavy lifting, baseline 3 is appropriate with marginal description enhancement.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose: 'Get compressed accessibility snapshot with ref IDs.' It specifies the verb ('Get'), resource ('compressed accessibility snapshot'), and key output characteristic ('with ref IDs'). It distinguishes from siblings by focusing on accessibility snapshots with ref IDs, unlike browser_execute (execution), browser_network_requests (network data), browser_search_snapshot (search-focused), or screenshot (visual capture).

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides clear context for when to use the tool: 'Call again after navigation (refs become stale)' and implies usage for tracking page updates via showDiff. However, it doesn't explicitly state when NOT to use this tool or name specific alternatives among siblings (e.g., when to use browser_search_snapshot instead). The guidance is helpful but lacks explicit exclusions or named alternatives.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

TDQS

A4.3/5.0
Disambiguation5/5

Each tool has a distinct and non-overlapping purpose: browser_execute runs code, browser_network_requests captures network data, browser_search_snapshot searches snapshots, screenshot captures images, and snapshot retrieves accessibility data. There is no ambiguity in their functions.

Naming Consistency5/5

All tool names follow a consistent snake_case pattern with a 'browser_' prefix for three tools and simple nouns for the others, creating a clear and predictable naming scheme. The structure is uniform and easy to understand.

Tool Count5/5

With 5 tools, the server is well-scoped for browser automation, covering execution, network monitoring, snapshot searching, screenshot capture, and accessibility snapshot retrieval. Each tool serves a unique and essential function without redundancy.

Completeness4/5

The tool set provides comprehensive coverage for browser automation tasks, including interaction, monitoring, and inspection. A minor gap exists in lacking a dedicated tool for browser context/page management (e.g., opening/closing pages), but this is mitigated by instructions within browser_execute.

Maintenance

ActivityInactive
ResponsivenessNo issues

Resources

Unclaimed servers have limited discoverability.

Looking for Admin?

If you are the server author, to access and configure the admin panel.

Related MCP Connectors

Related MCP Servers

  • A
    license
    B
    quality
    D
    maintenance
    A browser automation server providing Playwright capabilities for controlling web browsers, capturing screenshots, extracting content, and performing complex interactions through an MCP interface.
    6
    Apache 2.0
  • A
    license
    Not graded
    quality
    D
    maintenance
    An MCP server that enables AI-powered browser automation, web scraping, and testing using Playwright across Chromium, Firefox, and WebKit. It allows users to perform actions like navigation, clicking, typing, and taking screenshots through natural language interfaces.
    15
    MIT
  • A
    license
    A
    quality
    A
    maintenance
    A high-performance browser automation MCP server that provides AI agents with a fast, persistent Chromium instance via Playwright. It features reference-based element interaction, snapshot diffing, and manual handoff capabilities to handle complex tasks like CAPTCHAs.
    61
    18
    32
    MIT

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/SJMakin/even-better-playwright-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server