高效Playwright MCP工具

一个优化Playwright MCP的工具,通过`getOutline`和`searchSnapshot`功能显著减少令牌使用量(节约约95%),适用于浏览器自动化和前端调试场景。

  • by ekuznetski
  • JavaScript
  • 本地部署
  • 更新于
在 GitHub 查看 ekuznetski/better-playwright-mcp

使用说明

更好的剧作家MCP

令牌高效剧作家MCP getOutline 和 searchSnapshot -与完整快照相比,可节省约95%的令牌。

这是一把叉子 李维拉斯/更好的剧作家mcp 应用了关键修复。

代币节省

方法 行 字符 节省
官方剧作家MCP(完整快照) 673 ~42000 -
更好的剧作家(getOutline) 48 ~2100 95%

已应用修复程序

1.快照Bug修复

原始包装 page._snapshotForAI() 回报 { full: "..." } 在较新的Playwright版本中,对象而不是字符串,导致 snapshot.split is not a function 错误。

// 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.缺少MCP服务器

原始的npm包引用 dist/mcp-server.js 这是不存在的。这个叉子包括一个合适的MCP包装(index.mjs).

3.MCP SDK API兼容性

MCP SDK(v1.0+)从基于字符串的请求处理程序更改为基于模式的请求处理函数。此分叉使用新的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) => {...});

需求

  • Node.js>=18.0.0

安装

全局安装(推荐)

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

按项目安装

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

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

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

设置

步骤1:启动HTTP服务器

HTTP服务器必须正在运行,MCP才能工作。

# If installed globally
better-playwright-server

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

# Or with npx
npx better-playwright-server

默认情况下,服务器在端口3102上运行。集 PORT 环境变量发生变化。

步骤2:配置MCP

克劳德代码(项目配置)

创建 .mcp.json 在项目根目录中:

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

克劳德代码(全局配置)

添加 ~/.claude.json:

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

可用工具

工具 说明
create_page 创建一个新的浏览器页面并导航到URL。返回 pageId.
get_outline 获取压缩的页面结构(最多约200行)。 95%的代币节省。
search_snapshot 使用正则表达式搜索页面内容。仅返回匹配的行(最多100行)。
click 按引用ID单击元素(例如“e5”、“e12”)。
type_text 按引用ID在元素中键入文本
hover 通过引用ID将鼠标悬停在元素上
navigate 导航到URL
screenshot 对页面进行截图。
press_key 按键盘键(Enter、Tab、Escape等)。
scroll_to_top 滚动到页面顶部。
scroll_to_bottom 滚动到页面底部。
get_console_messages 获取浏览器控制台日志和JS错误。支持 clear: true 以冲洗缓冲液。
list_pages 列出所有打开的浏览器页面。
close_page 关闭浏览器页面。

AI代理使用指南

推荐的工作流程

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.

何时使用每种工具

  • get_outline --了解页面结构的第一步,最多200行
  • search_snapshot --当你知道要查找什么文本/元素时,令牌效率会高得多
  • get_console_messages --在页面加载或交互以捕获JS错误后,调试日志
  • screenshot --仅当视觉布局很重要时;由于图像而花费代币
  • press_key --对于Enter(提交表单)、Escape(关闭模式)、Tab(关注下一个字段)

调试前端问题

# 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)

查找元素

参考文献 get_outline 看起来像 [ref=e5].直接在中使用ref 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")

将HTTP服务器作为后台服务运行

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

环境变量

变量 默认值 描述
PORT 3102 HTTP服务器端口
BETTER_PLAYWRIGHT_URL http://localhost:3102 MCP连接到HTTP服务器的URL

故障排除

MCP未连接/“架构缺少方法文字”

如果您在Claude Code尝试连接时看到此错误:

Error: Schema is missing a method literal

这意味着MCP SDK API发生了变化。确保您拥有此软件包的最新版本:

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

该修复程序使用基于模式的处理程序,而不是基于字符串的处理程序(请参阅上面的“应用修复程序”部分)。

服务器未启动

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

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

ripgrep二进制文件缺失

如果你看到 /bin/sh: .../rg: No such file or directory:

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

连接被拒绝

在使用MCP工具之前,请确保HTTP服务器正在运行:

better-playwright-server

服务器应输出: Better Playwright HTTP server running on port 3102

许可证

麻省理工学院

积分