Better Playwright MCP
B

Better Playwright MCP

An optimized Playwright MCP server that uses a client-server architecture to achieve browser automation. Through an innovative semantic snapshot algorithm, it significantly reduces the amount of page content transmission, while retaining key elements and reducing token consumption by 90%.
2.5 points
9.0K

Installation

Copy the following command to your Client for configuration
Note: Your key is sensitive information, do not share it with anyone.

๐Ÿš€ better-playwright-mcp

A better Playwright MCP (Model Context Protocol) server that uses a client-server architecture for browser automation.

๐Ÿš€ Quick Start

To get started with better-playwright-mcp, you need to install it globally and then start both the MCP server and the HTTP server.

Installation

npm install -g better-playwright-mcp

Starting the Servers

  1. Start the HTTP server
npx better-playwright-mcp server
  1. In another terminal, start the MCP server
npx better-playwright-mcp

โœจ Features

  • ๐ŸŽฏ 90% token reduction through semantic HTML snapshots
  • ๐ŸŽญ Full Playwright browser automation via MCP
  • ๐Ÿ—๏ธ Client-server architecture for better separation of concerns
  • ๐Ÿ›ก๏ธ Stealth mode to avoid detection
  • ๐Ÿ“ Hash-based element identifiers for precise targeting
  • ๐Ÿ’พ Persistent browser profiles
  • ๐Ÿš€ Optimized for long-running automation tasks
  • ๐Ÿ“Š Token-aware output with automatic truncation

๐Ÿ“ฆ Installation

npm install -g better-playwright-mcp

๐Ÿ’ป Usage Examples

Default Mode (MCP)

The MCP server requires an HTTP server to be running. You need to start both:

Step 1: Start the HTTP server

npx better-playwright-mcp server

Step 2: In another terminal, start the MCP server

npx better-playwright-mcp

The MCP server will:

  1. Start listening on stdio for MCP protocol messages
  2. Connect to the HTTP server on port 3102
  3. Route browser automation commands through the HTTP server

Options:

  • --snapshot-dir <path> - Directory to save snapshots

Standalone HTTP Server Mode

You can also run the HTTP server independently (useful for debugging or custom integrations):

npx better-playwright-mcp server

Options:

  • -p, --port <number> - Server port (default: 3102)
  • --host <string> - Server host (default: localhost)
  • --headless - Run browser in headless mode
  • --chromium - Use Chromium instead of Chrome
  • --no-user-profile - Do not use persistent user profile
  • --user-data-dir <path> - User data directory
  • --snapshot-dir <path> - Directory to save snapshots

๐Ÿ“š Documentation

Why Better?

Traditional browser automation tools send entire page HTML to AI assistants, which quickly exhausts token limits and makes complex web interactions impractical. better-playwright-mcp solves this with an innovative semantic snapshot algorithm that reduces page content by up to 90% while preserving all meaningful elements.

The Problem

  • Full page HTML often exceeds 100K+ tokens
  • Most HTML is noise: inline styles, tracking scripts, invisible elements
  • AI assistants have limited context windows (even with 200K limits)
  • Complex web automation becomes impossible after just a few page loads

Our Solution: Semantic Snapshots

Our core innovation is a multi-stage pruning algorithm that:

  1. Identifies meaningful elements - Interactive elements (buttons, inputs), semantic HTML5 tags, and text-containing elements
  2. Generates unique identifiers - Each element gets a hash-based xp attribute derived from its XPath for precise targeting
  3. Removes invisible content - Elements with display:none, zero dimensions, or hidden parents are marked and removed
  4. Unwraps useless wrappers - Eliminates divs and spans that only wrap other elements
  5. Strips unnecessary attributes - Keeps only essential attributes like href, value, placeholder

Result: A clean, semantic representation that typically uses only 10% of the original tokens while maintaining full functionality.

Architecture

This project implements a unique two-tier architecture:

  1. MCP Server - Communicates with AI assistants via Model Context Protocol
  2. HTTP Server - Runs in the background to control the actual browser instances
AI Assistant <--[MCP Protocol]--> MCP Server <--[HTTP]--> HTTP Server <---> Browser

This design allows the MCP server to remain lightweight while delegating browser control to a dedicated HTTP service.

MCP Tools

When used with AI assistants, the following tools are available:

Page Management

  • createPage - Create a new browser page with name and description
  • activatePage - Activate a specific page by ID
  • closePage - Close a specific page
  • listPages - List all managed pages with titles and URLs
  • closeAllPages - Close all managed pages
  • listPagesWithoutId - List unmanaged browser pages
  • closePagesWithoutId - Close all unmanaged pages
  • closePageByIndex - Close page by index

Browser Actions

  • browserClick - Click an element using its xp identifier
  • browserType - Type text into an element
  • browserHover - Hover over an element
  • browserSelectOption - Select options in a dropdown
  • browserPressKey - Press keyboard keys
  • browserFileUpload - Upload files to file input
  • browserHandleDialog - Handle browser dialogs (alert, confirm, prompt)
  • browserNavigate - Navigate to a URL
  • browserNavigateBack - Go back to previous page
  • browserNavigateForward - Go forward to next page
  • scrollToBottom - Scroll to bottom of page/element
  • scrollToTop - Scroll to top of page/element
  • waitForTimeout - Wait for specified milliseconds
  • waitForSelector - Wait for element to appear

Snapshot & Utilities

  • getPageSnapshot - Get semantic HTML snapshot with xp identifiers
  • getScreenshot - Take a screenshot (PNG/JPEG)
  • getPDFSnapshot - Generate PDF of the page
  • getElementHTML - Get HTML of specific element
  • downloadImage - Download image from URL
  • captureSnapshot - Capture full page with automatic scrolling

How It Works

Semantic Snapshots in Action

Before (original HTML):

<div class="wrapper" style="padding: 20px; margin: 10px;">
  <div class="container">
    <div class="inner">
      <button class="btn btn-primary" onclick="handleClick()" 
              style="background: blue; color: white;">
        Click me
      </button>
    </div>
  </div>
</div>

After (semantic snapshot):

button xp=3fa2b8c1 Click me

The algorithm:

  • Removes unnecessary wrapper divs
  • Strips inline styles and event handlers
  • Adds unique identifier (xp attribute) - a hash of the element's XPath
  • Preserves only meaningful content

Diff-Based Optimization

To reduce data transfer and token usage:

  • First snapshot is always complete
  • Subsequent snapshots only include changes (diffs)
  • Automatic caching for performance

Stealth Features

Browser instances are configured with:

  • Custom user agent strings
  • Disabled automation indicators
  • WebGL vendor spoofing
  • Canvas fingerprint protection

๐Ÿ”ง Technical Details

Development

Prerequisites

  • Node.js >= 18.0.0
  • TypeScript
  • Chrome or Chromium browser

Building from Source

# Clone the repository
git clone https://github.com/yourusername/better-playwright-mcp.git
cd better-playwright-mcp

# Install dependencies
npm install

# Build the project
npm run build

# Run in development mode
npm run dev

Project Structure

better-playwright-mcp/
โ”œโ”€โ”€ src/
โ”‚   โ”œโ”€โ”€ index.ts                 # MCP mode entry point
โ”‚   โ”œโ”€โ”€ server.ts                # HTTP server mode entry point
โ”‚   โ”œโ”€โ”€ playwright-mcp.ts        # MCP server implementation
โ”‚   โ”œโ”€โ”€ client/
โ”‚   โ”‚   โ””โ”€โ”€ playwright-client.ts # HTTP client for MCPโ†’HTTP communication
โ”‚   โ”œโ”€โ”€ server/
โ”‚   โ”‚   โ””โ”€โ”€ playwright-server.ts # HTTP server controlling browsers
โ”‚   โ”œโ”€โ”€ extractor/
โ”‚   โ”‚   โ”œโ”€โ”€ parse2.ts           # HTML parsing with xp identifier generation
โ”‚   โ”‚   โ”œโ”€โ”€ simplify-html.ts    # HTML simplification
โ”‚   โ”‚   โ””โ”€โ”€ utils.ts            # Extraction utilities
โ”‚   โ””โ”€โ”€ utils/
โ”‚       โ””โ”€โ”€ token-limiter.ts    # Token counting and limiting
โ”œโ”€โ”€ bin/
โ”‚   โ””โ”€โ”€ cli.js                  # CLI entry point
โ”œโ”€โ”€ package.json
โ”œโ”€โ”€ tsconfig.json
โ”œโ”€โ”€ CLAUDE.md                   # Instructions for AI assistants
โ””โ”€โ”€ README.md

Troubleshooting

Common Issues

  1. MCP server not connecting

    • Ensure the HTTP server is accessible on port 3102
    • Check firewall settings
    • Try running with DEBUG=* npx better-playwright-mcp
  2. Browser not launching

    • Ensure Chrome or Chromium is installed
    • Try using --chromium flag
    • Check system resources
  3. Token limit exceeded

    • Snapshots are automatically truncated to 20,000 tokens
    • Use targeted selectors to reduce snapshot size
    • Consider using screenshot instead of snapshot for visual inspection

Debug Mode

Enable detailed logging:

DEBUG=* npx better-playwright-mcp

Logs and Records

Operation records are saved to:

  • macOS/Linux: /tmp/playwright-records/
  • Windows: %TEMP%\playwright-records\

Each page has its own directory with timestamped operation logs.

๐Ÿ“„ License

This project is licensed under the MIT license.

๐Ÿค Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

Alternatives

R
Rsdoctor
Rsdoctor is a build analysis tool specifically designed for the Rspack ecosystem, fully compatible with webpack. It provides visual build analysis, multi - dimensional performance diagnosis, and intelligent optimization suggestions to help developers improve build efficiency and engineering quality.
TypeScript
8.7K
5 points
N
Next Devtools MCP
The Next.js development tools MCP server provides Next.js development tools and utilities for AI programming assistants such as Claude and Cursor, including runtime diagnostics, development automation, and document access functions.
TypeScript
8.4K
5 points
T
Testkube
Testkube is a test orchestration and execution framework for cloud-native applications, providing a unified platform to define, run, and analyze tests. It supports existing testing tools and Kubernetes infrastructure.
Go
6.2K
5 points
M
MCP Windbg
An MCP server that integrates AI models with WinDbg/CDB for analyzing Windows crash dump files and remote debugging, supporting natural language interaction to execute debugging commands.
Python
8.6K
5 points
R
Runno
Runno is a collection of JavaScript toolkits for securely running code in multiple programming languages in environments such as browsers and Node.js. It achieves sandboxed execution through WebAssembly and WASI, supports languages such as Python, Ruby, JavaScript, SQLite, C/C++, and provides integration methods such as web components and MCP servers.
TypeScript
6.5K
5 points
N
Netdata
Netdata is an open-source real-time infrastructure monitoring platform that provides second-level metric collection, visualization, machine learning-driven anomaly detection, and automated alerts. It can achieve full-stack monitoring without complex configuration.
Go
9.6K
5 points
M
MCP Server
The Mapbox MCP Server is a model context protocol server implemented in Node.js, providing AI applications with access to Mapbox geospatial APIs, including functions such as geocoding, point - of - interest search, route planning, isochrone analysis, and static map generation.
TypeScript
7.7K
4 points
U
Uniprof
Uniprof is a tool that simplifies CPU performance analysis. It supports multiple programming languages and runtimes, does not require code modification or additional dependencies, and can perform one-click performance profiling and hotspot analysis through Docker containers or the host mode.
TypeScript
8.3K
4.5 points
N
Notion Api MCP
Certified
A Python-based MCP Server that provides advanced to-do list management and content organization functions through the Notion API, enabling seamless integration between AI models and Notion.
Python
18.9K
4.5 points
M
Markdownify MCP
Markdownify is a multi-functional file conversion service that supports converting multiple formats such as PDFs, images, audio, and web page content into Markdown format.
TypeScript
32.2K
5 points
G
Gitlab MCP Server
Certified
The GitLab MCP server is a project based on the Model Context Protocol that provides a comprehensive toolset for interacting with GitLab accounts, including code review, merge request management, CI/CD configuration, and other functions.
TypeScript
21.7K
4.3 points
D
Duckduckgo MCP Server
Certified
The DuckDuckGo Search MCP Server provides web search and content scraping services for LLMs such as Claude.
Python
63.1K
4.3 points
U
Unity
Certified
UnityMCP is a Unity editor plugin that implements the Model Context Protocol (MCP), providing seamless integration between Unity and AI assistants, including real - time state monitoring, remote command execution, and log functions.
C#
27.0K
5 points
F
Figma Context MCP
Framelink Figma MCP Server is a server that provides access to Figma design data for AI programming tools (such as Cursor). By simplifying the Figma API response, it helps AI more accurately achieve one - click conversion from design to code.
TypeScript
57.6K
4.5 points
G
Gmail MCP Server
A Gmail automatic authentication MCP server designed for Claude Desktop, supporting Gmail management through natural language interaction, including complete functions such as sending emails, label management, and batch operations.
TypeScript
19.9K
4.5 points
C
Context7
Context7 MCP is a service that provides real-time, version-specific documentation and code examples for AI programming assistants. It is directly integrated into prompts through the Model Context Protocol to solve the problem of LLMs using outdated information.
TypeScript
85.3K
4.7 points