Playwright MCP Automation
Overview
Use this skill whenever an agent must drive a real browser session via the Playwright MCP server. It covers standing up the MCP daemon, wiring it into your MCP client, and running reliable automation loops (login → navigate → act → verify). Pair these instructions with the upstream repo (
) for the latest binaries.
Bundled resources
Quick start (once per host)
- 1. Install prerequisites
- Ensure Node.js ≥ 18.
- Install Playwright browsers and system deps once:
npx playwright install chromium
# Linux only: installs missing libraries (x11, fonts, etc.)
sudo npx playwright install-deps chromium
- 2. Launch the MCP server
- Fast path: run scripts/start_playwright_mcp.sh from this skill directory. Override with PWMCP_BROWSER, PWMCP_PORT, etc.
- Need custom flags? Copy-paste from references/setup.md §2–5.
- 3. Register the server with your agent
- Local STDIO client:
{
"mcpServers": {
"playwright": {
"command": "npx",
"args": ["@playwright/mcp@latest", "--browser=chromium", "--user-data-dir=/home/ai/.cache/playwright/mcp-profile", "--allowed-hosts=*", "--snapshot-mode=incremental"]
}
}
}
- Remote HTTP transport: expose --port/--host then set "url": "http://HOST:PORT/mcp".
- 4. Sanity check
- Call browser_navigate to https://example.com, then browser_snapshot. If the tree renders, automation is ready.
Core workflow
Follow this loop for every task. Refer to references/tools.md for exact tool signatures.
1. Plan & prep
- - Clarify success criteria (e.g., "reach checkout confirmation", "download CSV").
- Decide on headed vs headless mode. Use headed when debugging CAPTCHAs/visual states.
- Make sure secrets (login cookies, OTP hooks) are available. If not, fall back to manual storage-state provisioning.
2. Navigate & observe
- 1.
browser_navigate to the starting URL. - Immediately
browser_snapshot to capture the accessibility tree. - If layout depends on viewport/device, adjust via launch flags (
--device, --viewport-size) or call browser_resize.
3. Interact deterministically
Use semantic tools whenever possible:
- - Inputs/buttons:
browser_click, browser_type, browser_fill_form. - Dropdowns:
browser_select_option. - Dynamic menus/tooltips:
browser_hover → browser_wait_for. - Multi-step flows (wizards, carts): after every step,
browser_snapshot + assert expected text before proceeding. - When markup lacks good roles, enable
--caps=vision and fall back to browser_mouse_* tools, but only as a last resort. - For brittle sequences (e.g., injecting JS, intercepting fetch), wrap logic inside
browser_run_code:
CODEBLOCK2
4. Handle waits & retries
- - Prefer
browser_wait_for with text / textGone over arbitrary sleeps. - On timeout, fetch a fresh snapshot, confirm element existence, then retry once before escalating.
- Capture console/network logs (
browser_console_messages, browser_network_requests) to debug API errors or CSP blocks.
5. Verify & capture artefacts
- - Collect evidence via
browser_snapshot and, if needed, browser_take_screenshot or browser_pdf_save (enable --caps=pdf). - For multi-tab flows, list tabs via
browser_tabs and ensure the correct tab is selected before final actions. - Always
browser_close at the end of unattended runs to release the browser.
Authentication & state strategies
- 1. Persistent profile (default script)
- Keeps cookies/localStorage inside PWMCP_PROFILE. Great for daily automations.
- Rotate profile path per task to avoid cross-site contamination.
- 2. Storage-state bootstrap
- Use Playwright CLI or manual login to create storage.json. Launch with --storage-state=/path/to/storage.json (see setup reference §4).
- Update file whenever passwords change.
- 3. Secrets file
- Launch with --secrets path/.env so MCP can expose sensitive values via secrets.get. Include API keys or 2FA tokens there instead of SKILL files.
- 4. Browser extension bridge
- When you must reuse an already-signed-in Chrome profile, install the Playwright MCP Bridge extension and launch with --extension. Follow upstream README for pairing.
Resilience checklist
- - CAPTCHA / MFA: Surface snapshots promptly so a human can intervene or provide MFA codes. Document fallback in your agent conversation.
- Slow sites: Increase
--timeout-action/--timeout-navigation, or stage requests via browser_wait_for { time }. - Resource throttling: Use headless mode and disable
--save-video/--save-trace unless debugging. - Logging: Save snapshots to files (
browser_snapshot filename) for audit trails, especially when producing evidence (e.g., order confirmations).
When to read the references/scripts
Keep SKILL.md lean by offloading details to the references. Update references/scripts whenever the upstream Playwright MCP release adds new capabilities (vision, pdf, devtools, etc.).
Playwright MCP 自动化
概述
当代理需要通过 Playwright MCP 服务器驱动真实浏览器会话时,请使用此技能。它涵盖了启动 MCP 守护进程、将其接入 MCP 客户端以及运行可靠的自动化循环(登录→导航→操作→验证)的完整流程。请结合上游仓库(
)获取最新二进制文件。
捆绑资源
快速开始(每台主机仅需一次)
- 1. 安装前置依赖
- 确保 Node.js ≥ 18。
- 安装 Playwright 浏览器及系统依赖(仅需一次):
bash
npx playwright install chromium
# 仅限 Linux:安装缺失的库(x11、字体等)
sudo npx playwright install-deps chromium
- 2. 启动 MCP 服务器
- 快速方式:从本技能目录运行 scripts/startplaywrightmcp.sh。可通过 PWMCPBROWSER、PWMCPPORT 等变量覆盖。
- 需要自定义参数?从 references/setup.md §2–5 复制。
- 3. 向代理注册服务器
- 本地 STDIO 客户端:
json
{
mcpServers: {
playwright: {
command: npx,
args: [@playwright/mcp@latest, --browser=chromium, --user-data-dir=/home/ai/.cache/playwright/mcp-profile, --allowed-hosts=*, --snapshot-mode=incremental]
}
}
}
- 远程 HTTP 传输:暴露 --port/--host,然后设置 url: http://HOST:PORT/mcp。
- 4. 健康检查
- 调用 browsernavigate 访问 https://example.com,然后调用 browsersnapshot。如果渲染出树结构,则自动化环境准备就绪。
核心工作流程
每个任务都遵循此循环。具体工具签名请参考 references/tools.md。
1. 规划与准备
- - 明确成功标准(例如:到达结账确认页面、下载 CSV 文件)。
- 决定使用有头模式还是无头模式。调试验证码/视觉状态时使用有头模式。
- 确保密钥(登录 cookies、OTP 钩子)可用。如果不可用,则回退到手动存储状态配置。
2. 导航与观察
- 1. 使用 browsernavigate 导航到起始 URL。
- 立即使用 browsersnapshot 捕获无障碍树。
- 如果布局依赖于视口/设备,通过启动参数(--device、--viewport-size)或调用 browser_resize 进行调整。
3. 确定性交互
尽可能使用语义化工具:
- - 输入框/按钮:browserclick、browsertype、browserfillform。
- 下拉菜单:browserselectoption。
- 动态菜单/提示框:browserhover → browserwaitfor。
- 多步骤流程(向导、购物车):每步之后,先 browsersnapshot 并断言预期文本,再继续。
- 当标记缺乏良好角色时,启用 --caps=vision 并回退到 browsermouse* 工具,但仅作为最后手段。
- 对于脆弱的序列(例如注入 JS、拦截 fetch),将逻辑封装在 browserruncode 中:
js
async (page) => {
await page.waitForSelector(text=Place order);
await page.getByRole(button, { name: Place order }).click();
return await page.getByTestId(order-number).innerText();
}
4. 处理等待与重试
- - 优先使用带 text / textGone 参数的 browserwaitfor,而非任意休眠。
- 超时时,获取新的快照,确认元素存在,然后重试一次,再升级处理。
- 捕获控制台/网络日志(browserconsolemessages、browsernetworkrequests)以调试 API 错误或 CSP 拦截。
5. 验证与捕获产物
- - 通过 browsersnapshot 收集证据,必要时使用 browsertakescreenshot 或 browserpdfsave(需启用 --caps=pdf)。
- 对于多标签页流程,通过 browsertabs 列出标签页,并在最终操作前确保选择了正确的标签页。
- 无人值守运行结束时,务必调用 browser_close 释放浏览器。
认证与状态策略
- 1. 持久化配置文件(默认脚本)
- 将 cookies/localStorage 保存在 PWMCP_PROFILE 中。适合日常自动化。
- 每个任务轮换配置文件路径,避免跨站点污染。
- 2. 存储状态引导
- 使用 Playwright CLI 或手动登录创建 storage.json。使用 --storage-state=/path/to/storage.json 启动(参见设置参考 §4)。
- 密码更改时更新文件。
- 3. 密钥文件
- 使用 --secrets path/.env 启动,使 MCP 能通过 secrets.get 暴露敏感值。将 API 密钥或 2FA 令牌放在此处,而非技能文件中。
- 4. 浏览器扩展桥接
- 当需要重用已登录的 Chrome 配置文件时,安装 Playwright MCP Bridge 扩展并使用 --extension 启动。按照上游 README 进行配对。
弹性检查清单
- - 验证码 / 多因素认证:及时提供快照,以便人工干预或提供 MFA 代码。在代理对话中记录回退方案。
- 慢速网站:增加 --timeout-action/--timeout-navigation,或通过 browserwaitfor { time } 分阶段请求。
- 资源限制:使用无头模式,除非调试,否则禁用 --save-video/--save-trace。
- 日志记录:将快照保存到文件(browser_snapshot filename)用于审计追踪,特别是在生成证据时(例如订单确认)。
何时阅读参考/脚本
通过将细节卸载到参考文件中,保持 SKILL.md 简洁。当上游 Playwright MCP 版本添加新功能(视觉、PDF、开发者工具等)时,更新参考/脚本。