Playwright MCP (AI agent điều khiển trình duyệt qua Model Context Protocol)
automationplaywright
Playwright MCP là server MCP chính thức của Microsoft, expose các tool (browser_navigate, browser_click, browser_snapshot...) để AI agent (Claude Code, Copilot, Cursor) điều khiển trình duyệt thật. Điểm khác biệt: nó trả về accessibility tree dạng text với element ref thay vì ảnh màn hình — nhanh, rẻ token, deterministic hơn. Ứng dụng cho QA: khám phá app, sinh draft test, tái hiện bug.
Khái niệm & Bản chất
- MCP = chuẩn giao thức tool cho AI: Model Context Protocol (Anthropic mở) cho phép AI client (Claude Code, VS Code Copilot, Cursor...) gọi tool bên ngoài qua JSON-RPC; Playwright MCP là server implement bằng chính Playwright.
- Cơ chế snapshot, không phải vision: agent gọi
browser_navigate→ server trả accessibility tree dạng YAML với mỗi element gánref(e1,e2...) → agent gọibrowser_click(element, ref)— không OCR ảnh, không đoán tọa độ. - Khác agent 'computer-use': điều khiển qua screenshot + toạ độ pixel chậm, tốn token, hay hallucinate vị trí; snapshot-based nhanh, chính xác, ít token — vì nó 'đọc' trang chứ không 'nhìn' trang.
- Bộ tool đầy đủ: navigate/back/forward, click, type, fill_form, select_option, hover, drag, press_key, snapshot, take_screenshot, wait_for, evaluate JS, console_messages, network_requests, quản lý tabs/windows, pdf, resize.
Cách hoạt động & API chính
- Chạy server:
npx @playwright/mcp@latest— đăng ký vào MCP client qua config JSON (mcpServers), client tự spawn process khi cần. - Option hữu ích:
--browser chromium|firefox|webkit|msedge|chrome,--headed(nhìn thấy browser chạy),--isolated(profile sạch mỗi session),--storage-state <file>(login sẵn),--caps=vision(bật tool screenshot),--allowed-origins/--blocked-origins(giới hạn domain),--output-dir(nơi lưu file tải về). - Luồng điển hình của agent:
browser_navigate→ (tự động trả snapshot) → đọc ref →browser_click/browser_type→ snapshot mới → lặp;browser_snapshotgọi thủ công khi cần refresh state. refchỉ sống trong snapshot hiện tại: trang đổi DOM → ref cũ vô nghĩa, phải snapshot lại — agent tự xử lý nhưng hiểu để debug khi lệnh fail 'element not found'.- Tool chẩn đoán:
browser_console_messagesđọc console,browser_network_requestsliệt kê request đã bắn — agent tự xem lỗi API/JS khi UI không đúng.
Ví dụ & Cú pháp thực tế
- Đăng ký MCP server (VS Code
mcp.json/ config Claude): ``jsonc { "mcpServers": { "playwright": { "command": "npx", "args": ["@playwright/mcp@latest", "--isolated", "--browser", "chromium"] } } }`` - Prompt kiểu 'exploratory + sinh test':
``
text Mở https://staging.hoctest.com/login, đăng nhập qa@x.com / Pass123, vào trang đặt hàng, thử mua 1 sản phẩm. Ghi lại các bước đã thực hiện và sinh file spec Playwright TypeScript với locator ổn định (getByRole).`` // Agent tự: navigate → snapshot → click/type theo ref → xuất draft test - Tái hiện bug từ report:
``
text Bug: user báo lỗi sau khi apply mã giảm giá. Vào https://staging.app/cart, thêm sản phẩm 'Áo QA' vào giỏ, nhập mã 'SALE50', bấm Apply — đọc console error và request /api/coupon rồi báo lại status code + response.`` // Dùng browser_console_messages + browser_network_requests tự chẩn đoán - Bỏ qua login bằng storage-state:
``
bash # lưu auth state 1 lần (script login sẵn rồi storageState ra file) npx playwright codegen --save-storage=auth.json https://staging.app # rồi cấu hình MCP: "args": ["@playwright/mcp@latest", "--storage-state", "auth.json"]``
Best practices & Khi nào dùng
- Dùng cho exploratory & draft: khám phá app mới, smoke nhanh flow mới ship, sinh draft spec để kỹ sư review — KHÔNG thay regression suite.
--isolatedcho session sạch: tránh cookie/storage lần trước làm kết quả lệch;--storage-statekhi cần nhảy thẳng vào trang sau auth.- Giới hạn domain bằng
--allowed-origins: trỏ agent vàohttps://staging.*— chặn nó lạc ra domain ngoài hay site production. - Output là draft, phải refactor: agent hay dùng ref/selector tạm — chuyển sang
getByRole, thêmexpectđúng chuẩn, gom vào POM trước khi commit. - Kết hợp tool chẩn đoán: khi UI 'trông sai', bảo agent check
browser_console_messages+browser_network_requests— thường thấy ngay API 500 hoặc JS error.
Gotchas, So sánh & Lưu ý
- Non-deterministic: cùng 1 prompt có thể chạy khác nhau mỗi lần — test do agent sinh phải chạy verify + review trước khi đưa vào suite; đừng trust output 100%.
- Snapshot phụ thuộc accessibility tree: trang canvas/WebGL/game/a11y kém → snapshot 'mù' gần như trống — bật
--caps=visionđể agent fallback sang screenshot. - Tốn token nhanh: snapshot trang lớn rất dài, agent loop nhiều bước → context đầy; chia nhiệm vụ nhỏ, dùng
--isolatedreset session. - Session là credential thật: agent giữ browser đã login — KHÔNG trỏ vào production với quyền thật; coi storage-state như mật khẩu, không commit lên git.
refbị stale sau mỗi thay đổi DOM: lỗi 'ref not found' = trang đã re-render — đây là hành vi đúng, agent cần snapshot lại.- MCP là cầu nối, không phải framework test: nó cho AI 'đôi tay' trên browser — khác hẳn
playwright testchạy deterministic; so với tự build custom tool (page.evaluate, API riêng) thì MCP đã chuẩn hoá sẵn tool + snapshot — khỏi build lại bánh xe, đổi lại kém linh hoạt nếu cần domain-tool riêng.
