Better Playwright MCP

Better Playwright MCP

Token-efficient browser automation MCP server using Playwright, with getOutline and searchSnapshot to save ~95% tokens compared to full snapshots.

Category
访问服务器

README

Better Playwright MCP

Token-efficient Playwright MCP with getOutline and searchSnapshot - saves ~95% tokens vs full snapshots.

This is a fork of livoras/better-playwright-mcp with critical fixes applied.

Token Savings

Method Lines Characters Savings
Official Playwright MCP (full snapshot) 673 ~42,000 -
Better Playwright (getOutline) 48 ~2,100 95%

Fixes Applied

1. Snapshot Bug Fix

The original package's page._snapshotForAI() returns { full: "..." } object instead of string in newer Playwright versions, causing snapshot.split is not a function error.

// Before (broken):
const snapshot = await pageInfo.page._snapshotForAI();

// After (fixed):
const rawSnapshot = await pageInfo.page._snapshotForAI();
const snapshot = typeof rawSnapshot === 'string' ? rawSnapshot : rawSnapshot?.full ?? '';

2. Missing MCP Server

The original npm package references dist/mcp-server.js which doesn't exist. This fork includes a proper MCP wrapper (index.mjs).

3. MCP SDK API Compatibility

The MCP SDK (v1.0+) changed from string-based to schema-based request handlers. This fork uses the new API:

// Old API (broken with MCP SDK v1.0+):
server.setRequestHandler('tools/list', async () => {...});
server.setRequestHandler('tools/call', async (req) => {...});

// New API (fixed):
import {
  ListToolsRequestSchema,
  CallToolRequestSchema,
} from '@modelcontextprotocol/sdk/types.js';

server.setRequestHandler(ListToolsRequestSchema, async () => {...});
server.setRequestHandler(CallToolRequestSchema, async (req) => {...});

Requirements

  • Node.js >= 18.0.0

Installation

Global Installation (Recommended)

npm install -g github:ekuznetski/better-playwright-mcp

Per-Project Installation

# npm
npm install github:ekuznetski/better-playwright-mcp

# pnpm
pnpm add github:ekuznetski/better-playwright-mcp

# yarn
yarn add github:ekuznetski/better-playwright-mcp

Setup

Step 1: Start HTTP Server

The HTTP server must be running for the MCP to work.

# If installed globally
better-playwright-server

# If installed per-project
./node_modules/.bin/better-playwright-server

# Or with npx
npx better-playwright-server

By default, the server runs on port 3102. Set PORT environment variable to change.

Step 2: Configure MCP

Claude Code (Project Config)

Create .mcp.json in your project root:

{
  "mcpServers": {
    "better-playwright": {
      "command": "better-playwright-mcp",
      "env": {
        "BETTER_PLAYWRIGHT_URL": "http://localhost:3102"
      }
    }
  }
}

Claude Code (Global Config)

Add to ~/.claude.json:

{
  "mcpServers": {
    "better-playwright": {
      "command": "better-playwright-mcp",
      "env": {
        "BETTER_PLAYWRIGHT_URL": "http://localhost:3102"
      }
    }
  }
}

Available Tools

Tool Description
create_page Create a new browser page and navigate to URL. Returns pageId.
get_outline Get compressed page structure (max ~200 lines). 95% token savings.
search_snapshot Search page content with regex. Returns only matching lines (max 100).
click Click element by ref ID (e.g., "e5", "e12").
type_text Type text into element by ref ID.
hover Hover over element by ref ID.
navigate Navigate to URL.
screenshot Take screenshot of page.
press_key Press keyboard key (Enter, Tab, Escape, etc.).
scroll_to_top Scroll to top of page.
scroll_to_bottom Scroll to bottom of page.
get_console_messages Get browser console logs and JS errors. Supports clear: true to flush buffer.
list_pages List all open browser pages.
close_page Close browser page.

Usage Guide for AI Agents

Recommended workflow

1. create_page(name: "app", url: "http://localhost:3000")
   -> Returns pageId: "abc-123"

2. get_outline(pageId: "abc-123")
   -> Returns compressed page structure with element refs like [ref=e5]
   -> Use this to understand layout and find clickable elements

3. search_snapshot(pageId: "abc-123", pattern: "Submit|Login")
   -> Returns only lines matching the pattern — much faster than get_outline for targeted search

4. click(pageId: "abc-123", ref: "e5")
   -> Clicks element. Always get ref from get_outline or search_snapshot first.

5. get_console_messages(pageId: "abc-123", clear: true)
   -> Check for JS errors or logs after interaction. Pass clear: true to flush buffer.

When to use each tool

  • get_outline — first step to understand page structure, max ~200 lines
  • search_snapshot — when you know what text/element to find, much more token-efficient
  • get_console_messages — after page load or interactions to catch JS errors, debug logs
  • screenshot — only when visual layout matters; costs tokens due to image
  • press_key — for Enter (submit form), Escape (close modal), Tab (focus next field)

Debugging frontend issues

# After clicking a button or navigating, always check console:
get_console_messages(pageId: "abc-123")

# Expected output:
# [12:34:56.123] [LOG] Component mounted
# [12:34:56.200] [ERROR] Uncaught TypeError: Cannot read property 'id' of undefined

# To avoid accumulating old logs, clear after reading:
get_console_messages(pageId: "abc-123", clear: true)

Finding elements

Refs in get_outline look like [ref=e5]. Use the ref directly in click, type_text, hover.

# Find a specific button:
search_snapshot(pageId: "abc-123", pattern: "Submit")
-> button "Submit" [ref=e42]

click(pageId: "abc-123", ref: "e42")

Running HTTP Server as Background Service

macOS (launchd)

cat > ~/Library/LaunchAgents/com.better-playwright.plist << 'EOF'
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.better-playwright</string>
    <key>ProgramArguments</key>
    <array>
        <string>/usr/local/bin/better-playwright-server</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
    <key>KeepAlive</key>
    <true/>
</dict>
</plist>
EOF

launchctl load ~/Library/LaunchAgents/com.better-playwright.plist

Linux (systemd)

mkdir -p ~/.config/systemd/user

cat > ~/.config/systemd/user/better-playwright.service << 'EOF'
[Unit]
Description=Better Playwright HTTP Server

[Service]
ExecStart=/usr/local/bin/better-playwright-server
Restart=always

[Install]
WantedBy=default.target
EOF

systemctl --user enable better-playwright
systemctl --user start better-playwright

Environment Variables

Variable Default Description
PORT 3102 HTTP server port
BETTER_PLAYWRIGHT_URL http://localhost:3102 URL for MCP to connect to HTTP server

Troubleshooting

MCP not connecting / "Schema is missing a method literal"

If you see this error when Claude Code tries to connect:

Error: Schema is missing a method literal

This means the MCP SDK API changed. Ensure you have the latest version of this package:

npm update -g github:ekuznetski/better-playwright-mcp

The fix uses schema-based handlers instead of string-based ones (see "Fixes Applied" section above).

Server not starting

# Check if port is in use
lsof -i :3102

# Kill existing process
lsof -ti :3102 | xargs kill -9

ripgrep binary missing

If you see /bin/sh: .../rg: No such file or directory:

cd node_modules/@vscode/ripgrep && npm run postinstall

Connection refused

Make sure the HTTP server is running before using the MCP tools:

better-playwright-server

The server should output: Better Playwright HTTP server running on port 3102

License

MIT

Credits

推荐服务器

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 模型以安全和受控的方式获取实时的网络信息。

官方
精选