Better Playwright MCP

Better Playwright MCP

A client-server browser automation solution that reduces HTML token usage by up to 90% through semantic snapshots, enabling complex web interactions without exhausting AI context windows.

Category
访问服务器

Tools

createPage

创建新的浏览器页面

listPages

列出所有管理的页面(包含标题和URL)

browserFileUpload

上传文件到指定元素

getElementHTML

通过xp引用获取元素的outerHTML结构,用于调试选择器

getScreenshot

获取页面截图并保存到临时目录,返回文件路径

activatePage

激活指定的页面

closePage

关闭指定的页面

closeAllPages

关闭所有管理的页面

listPagesWithoutId

列出所有未被管理的页面

closePagesWithoutId

关闭所有未被管理的页面

closePageByIndex

通过索引关闭页面

browserClick

点击页面元素

browserType

在页面元素中输入文本

browserHover

悬停在页面元素上

browserSelectOption

在下拉框中选择选项

browserPressKey

按键盘按键

browserHandleDialog

处理浏览器对话框

browserNavigate

导航到指定URL

browserNavigateBack

返回到上一页

browserNavigateForward

前进到下一页

scrollToBottom

滚动到页面或元素底部

scrollToTop

滚动到页面或元素顶部

waitForTimeout

等待指定毫秒数

waitForSelector

等待指定选择器的元素出现

getPDFSnapshot

获取页面的PDF快照

getPageSnapshot

获取页面的语义化简化快照,返回清晰的缩进结构

downloadImage

下载图片到本地临时目录,返回本地文件路径

captureSnapshot

捕获网页的完整快照,支持滚动、等待和自动修剪功能

README

better-playwright-mcp

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

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.

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

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

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

Examples

Creating and Navigating Pages

// MCP Tool Usage
{
  "tool": "createPage",
  "arguments": {
    "name": "shopping",
    "description": "Amazon shopping page",
    "url": "https://amazon.com"
  }
}

// Returns: { pageId: "uuid", snapshot: "..." }

Interacting with Elements

// Click on element using its xp identifier
{
  "tool": "browserClick",
  "arguments": {
    "pageId": "uuid",
    "ref": "3fa2b8c1"  // The xp attribute value from snapshot
  }
}

// Type text into input field
{
  "tool": "browserType",
  "arguments": {
    "pageId": "uuid",
    "ref": "xp456",
    "text": "search query",
    "submit": true  // Press Enter after typing
  }
}

Capturing Page State

// Get semantic snapshot
{
  "tool": "getPageSnapshot",
  "arguments": {
    "pageId": "uuid"
  }
}

// Take screenshot
{
  "tool": "getScreenshot",
  "arguments": {
    "pageId": "uuid",
    "fullPage": true,
    "type": "png"
  }
}

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.

Contributing

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

License

MIT

推荐服务器

Baidu Map

Baidu Map

百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。

官方
精选
JavaScript
Playwright MCP Server

Playwright MCP Server

一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。

官方
精选
TypeScript
Magic Component Platform (MCP)

Magic Component Platform (MCP)

一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。

官方
精选
本地
TypeScript
Audiense Insights MCP Server

Audiense Insights MCP Server

通过模型上下文协议启用与 Audiense Insights 账户的交互,从而促进营销洞察和受众数据的提取和分析,包括人口统计信息、行为和影响者互动。

官方
精选
本地
TypeScript
VeyraX

VeyraX

一个单一的 MCP 工具,连接你所有喜爱的工具:Gmail、日历以及其他 40 多个工具。

官方
精选
本地
graphlit-mcp-server

graphlit-mcp-server

模型上下文协议 (MCP) 服务器实现了 MCP 客户端与 Graphlit 服务之间的集成。 除了网络爬取之外,还可以将任何内容(从 Slack 到 Gmail 再到播客订阅源)导入到 Graphlit 项目中,然后从 MCP 客户端检索相关内容。

官方
精选
TypeScript
Kagi MCP Server

Kagi MCP Server

一个 MCP 服务器,集成了 Kagi 搜索功能和 Claude AI,使 Claude 能够在回答需要最新信息的问题时执行实时网络搜索。

官方
精选
Python
e2b-mcp-server

e2b-mcp-server

使用 MCP 通过 e2b 运行代码。

官方
精选
Neon MCP Server

Neon MCP Server

用于与 Neon 管理 API 和数据库交互的 MCP 服务器

官方
精选
Exa MCP Server

Exa MCP Server

模型上下文协议(MCP)服务器允许像 Claude 这样的 AI 助手使用 Exa AI 搜索 API 进行网络搜索。这种设置允许 AI 模型以安全和受控的方式获取实时的网络信息。

官方
精选