Cette page est affichée en anglais. Une traduction française est en cours.
MCP ConfigsMay 11, 2026·21 min de lecture

Playwright MCP — Browser Automation Server

Playwright MCP is an MCP server for browser automation via Playwright snapshots. Add via npx in Claude Code/Codex to run deterministic actions.

MCP Hub
MCP Hub · Community
Prêt pour agents

Staging sûr pour cet actif

Cet actif est d'abord staged. Le prompt copié demande à l'agent d'inspecter les fichiers staged avant d'activer scripts, config MCP ou config globale.

Stage only · 17/100Policy : staging
Surface agent
Tout agent MCP/CLI
Type
Mcp Config
Installation
Stage only
Confiance
Confiance : Established
Point d'entrée
Asset
Commande de staging sûr
npx -y tokrepo@latest install 7f3a756c-8ec2-4b20-8ad6-99bfc5155af3 --target codex

Stage les fichiers d'abord; l'activation exige la revue du README et du plan staged.

Introduction

Playwright MCP is a verified GitHub-backed asset sourced from microsoft/playwright-mcp with 32,355 stars and a Apache-2.0 license snapshot. Best for: agents that need deterministic browser automation without vision models, using structured accessibility snapshots. Works with: Node.js 18+, any MCP client (Claude Code/Codex/Cursor/etc.). Setup time: 5 minutes.

Quantitative notes

  • Node.js 18+ requirement (repo)
  • npx @playwright/mcp@latest install path (repo)

Quick Use

  1. Install the verified entrypoint:
claude mcp add playwright npx @playwright/mcp@latest
  1. Run a first local check:
codex mcp add playwright npx "@playwright/mcp@latest"
  1. Add a repeatable verification step:
In your MCP client, list servers/tools and confirm Playwright appears

Intro

Playwright MCP is a verified GitHub-backed asset sourced from microsoft/playwright-mcp with 32,355 stars and a Apache-2.0 license snapshot. Best for: agents that need deterministic browser automation without vision models, using structured accessibility snapshots. Works with: Node.js 18+, any MCP client (Claude Code/Codex/Cursor/etc.). Setup time: 5 minutes.

Quantitative notes

  • Node.js 18+ requirement (repo)
  • npx @playwright/mcp@latest install path (repo)

Deep Dive

What it solves

Use this when you need a repeatable, team-shareable workflow instead of one-off agent prompts. The goal is to make installation, first-run validation, and rollback predictable.

Minimal mental model

  • Treat the GitHub repo as the source of truth: install instructions, configs, and upgrade paths live there.
  • Keep your first run small: one command, one verification, one rollback plan.
  • Capture a baseline: setup time, first successful run, and one real task completed end-to-end.

Safe rollout checklist

  1. Verify source: confirm repo URL, stars, and license match what you expect.
  2. Install using the Quick Use commands above.
  3. Prove it works with the verification command; save the output in a note or issue.
  4. Operationalize: document owner, upgrade command, and rollback command.

Troubleshooting (common)

  • Install succeeds but nothing shows up

    • Likely cause: the tool needs a restart/reload (CLI/IDE) or a config file in the right path.
    • Fix: restart the client, then re-run the verification step.
  • Works on one machine, fails on another

    • Likely cause: Node/Python/Docker versions differ or missing system dependencies.
    • Fix: pin versions (Node/Python), and copy a minimal known-good config.
  • Token cost or latency is worse than expected

    • Likely cause: tool schemas or verbose outputs get injected into context.
    • Fix: prefer smaller steps, cache results, and keep tool responses concise when possible.

FAQ

Q: MCP vs CLI—when should I pick MCP? A: The repo explains MCP is useful when you want persistent state and rich introspection; CLI can be more token-efficient for coding agents.

Q: Do I need a vision model? A: The repo positions it as accessibility-tree based automation; you still validate outcomes, but it doesn't require screenshot reasoning by default.

Q: How do I keep it stable in CI? A: Pin Node + Playwright versions and keep browser dependencies consistent across environments.


Source & Thanks

GitHub: https://github.com/microsoft/playwright-mcp Owner avatar: https://avatars.githubusercontent.com/u/6154722?v=4 License (SPDX): Apache-2.0 Stars (verified via api.github.com/repos/microsoft/playwright-mcp): 32,355


Playwright MCP——基于 Playwright 的浏览器 MCP

Playwright MCP 是基于 Playwright 的 MCP Server:通过可访问性树而非截图驱动浏览器自动化,适合可重复的网页操作与自愈脚本。用 npx 添加到 Claude Code/Codex 配置后即可调用工具。

快速使用

  1. 安装(以仓库为准):
claude mcp add playwright npx @playwright/mcp@latest
  1. 首次运行/检查:
codex mcp add playwright npx "@playwright/mcp@latest"
  1. 可重复验证:
In your MCP client, list servers/tools and confirm Playwright appears

简介

Playwright MCP 已核验来源于 microsoft/playwright-mcp(32,355 stars,许可证 Apache-2.0)。适合:需要确定性网页自动化、希望基于结构化可访问性树而非截图/视觉模型的 agent。兼容:Node.js 18+;任意 MCP client(Claude Code/Codex/Cursor 等)。装机时间:5 分钟。

量化信息

  • 需要 Node.js 18+(仓库)
  • 用 npx @playwright/mcp@latest 安装(仓库)

深度说明

解决什么问题

把“找到项目 → 安装 → 首次验证 → 回滚/升级”变成可复用流程,避免只靠一次性提示词或截图操作。

最小心智模型

  • GitHub 仓库是事实来源:安装、配置、升级、已知问题都以它为准。
  • 第一次只做最小闭环:一个命令安装、一个命令验证、一个可回滚方案。
  • 记录基线:装机耗时、首次成功输出、完成 1 个真实任务的证据。

安全推广清单

  1. 核验来源:确认仓库 URL / stars / license 与预期一致。
  2. 按“快速使用”完成安装与首次检查。
  3. 跑通“验证命令”,把输出留档。
  4. 标注 owner,并写清升级/回滚步骤。

常见排障

  • 装了但看不到效果

    • 常见原因:需要重启 CLI/IDE 或配置文件路径不对。
    • 处理:重启后再跑一遍“验证命令”。
  • 一台机器能跑,另一台不行

    • 常见原因:Node/Python/Docker 版本差异或缺少系统依赖。
    • 处理:固定版本,并拷贝最小可用配置。
  • token 成本/延迟超预期

    • 常见原因:工具 schema 或输出过长被塞进上下文。
    • 处理:拆小步骤、缓存结果、尽量让工具输出更短。

FAQ

Q: MCP 和 CLI 怎么选? A: 仓库说明:需要持续状态/丰富内省时选 MCP;纯高频命令型工作流用 CLI 可能更省 token。

Q: 需要视觉模型吗? A: 它基于可访问性树,不依赖截图推理;仍建议用可重复的验证步骤确认结果。

Q: CI 里怎么更稳定? A: 固定 Node 与 Playwright 版本,并保证浏览器依赖在各环境一致。


来源与感谢

GitHub:https://github.com/microsoft/playwright-mcp Owner avatar:https://avatars.githubusercontent.com/u/6154722?v=4 许可证(SPDX):Apache-2.0 GitHub stars(已通过 api.github.com/repos/microsoft/playwright-mcp 核验):32,355

Playwright MCP Companion: Setup and Safety Guide

Bilingual companion guide for the Playwright MCP server: install, verify, permissions, limits and troubleshooting.

Quick Use

  1. Install the verified entrypoint with the Claude Code CLI:
claude mcp add playwright npx @playwright/mcp@latest
  1. Add the same server with the Codex CLI:
codex mcp add playwright npx "@playwright/mcp@latest"
  1. Verify by hand: in your MCP client, list servers/tools and confirm Playwright appears. This is a manual check inside the client, not a shell command, so it is written as plain prose rather than a code block.

If your client is not covered above, add the standard mcpServers block from the original README to that client's MCP configuration file, with "command": "npx" and "args": ["@playwright/mcp@latest"].

How to set it up

Playwright MCP is a Model Context Protocol server from microsoft/playwright-mcp that gives MCP clients browser automation through Playwright. It drives pages with Playwright's accessibility tree rather than pixels, so no vision model is needed by default and actions are more deterministic than screenshot-based approaches.

Inputs you need before starting:

  • Node.js 18 or newer, available on PATH so npx can resolve the package.
  • An MCP client that supports stdio servers: VS Code, Cursor, Windsurf, Claude Desktop, Goose, Grok, Junie or similar.
  • Write access to that client's MCP configuration file, plus a backup copy of it.

Expected result: after installation the client lists a server named playwright and exposes browser tools such as browser_navigate and browser_snapshot. There is no upstream test-suite result recorded here: this asset is a configuration record, its snapshot contains no files, and nothing was executed when it was published.

This companion guide adds what the original README does not gather in one place: how to choose between MCP and the Playwright CLI, which permissions you are actually granting, how to roll back, and how to reproduce one machine's setup on another.

Permission note: the MCP server runs commands through your client, and the source risk profile marks this asset as modifying global or client-level configuration. Back up configuration before you edit it.

Source reviewed; runtime not tested.

Prerequisites and permissions

  • Adding a server edits your client's MCP configuration file. Back it up first; removing the entry is the rollback.
  • The default profile is persistent, so logged-in browser state is written to disk under ms-playwright in your user cache directory. Use --isolated or a distinct --user-data-dir when you do not want that, or when several MCP clients share one workspace.
  • File access is restricted to workspace roots by default and file:// navigation is blocked. --allow-unrestricted-file-access removes that guardrail; the README states it is a convenience guard, not a secure boundary.
  • --allowed-origins and --blocked-origins are not security boundaries and do not affect redirects.
  • Secrets passed with --secrets are a convenience for keeping sensitive strings out of tool responses, not a security feature. Review any secrets you supply and avoid putting credentials in prompts.
  • One persistent profile can only be used by one browser instance at a time, so concurrent clients in the same workspace conflict.

Choosing MCP or the CLI

The upstream README is explicit, and it affects cost:

  • CLI plus SKILLS suits coding agents: fewer tokens, because large tool schemas and verbose accessibility trees are not loaded into context.
  • MCP suits long-running agentic loops that need persistent browser state, iterative reasoning over page structure, exploratory automation or self-healing tests, where continuous browser context is worth the token cost.

If your main job is editing a codebase while occasionally driving a browser, the CLI path is usually the cheaper default. It is worth checking the upstream README's note about Playwright CLI with SKILLS before committing to one approach.

Safe rollout checklist

  1. Confirm the source: repository, license (Apache-2.0) and the exact install command you intend to use.
  2. Install with the command in Quick Use for your client.
  3. Restart the client if the server does not appear, then list servers/tools again.
  4. Record a baseline: install time, first successful tool call, one real task completed end to end.
  5. Write down the upgrade path (a restart re-resolves @latest) and the rollback path (delete the server entry or restore your config backup).
  6. In CI, pin Node and Playwright versions instead of relying on @latest, and keep browser dependencies consistent across machines.

Options worth knowing

Option Practical effect
--headless Runs without a visible window; headed by default.
--isolated In-memory profile; storage state is lost when the session closes.
--storage-state <path> Loads cookies and local storage into an isolated context.
--user-data-dir <path> Chooses where the persistent profile lives.
--browser <browser> chrome, firefox, webkit or msedge.
--device <device> Emulates e.g. "iPhone 15"; cannot be combined with --mobile.
--mobile Generic mobile emulation, lighter pages, fewer tokens.
--caps <caps> Opts in to vision, pdf, devtools and other capabilities.
--allowed-hosts <hosts...> Hosts the server may serve from; DNS rebinding protection, not CORS.
--port <port> Serves over HTTP instead of stdio, e.g. --port 8931.
--idle-timeout <timeout> Closes the browser after inactivity and relaunches it on the next call.
--no-sandbox Disables the browser sandbox; avoid unless you understand the trade-off.

Most options have a PLAYWRIGHT_MCP_* environment-variable equivalent, and all of them can be set in a JSON file referenced with --config path/to/config.json.

Troubleshooting

  • Installed but nothing shows up: restart the client, then list servers/tools again.
  • Works on one machine, fails on another: pin Node and Playwright versions and compare the configs.
  • Two clients clash in one workspace: a persistent profile allows one browser instance at a time, so start extra clients with --isolated or a separate --user-data-dir.
  • Headed browser fails without a display: run the server with --port 8931 and point the client at http://localhost:8931/mcp, or run the upstream Docker image (headless chromium only in that example).
  • Token or latency cost above expectations: prefer browser_find and --snapshot-mode none over full snapshots, and keep tool responses short.

What is not covered here

  • No upstream benchmark or test-suite result is reproduced, because the snapshot records none.
  • Installation files are not part of this asset: the snapshot lists no files, so there is nothing to inspect locally.
  • This guide does not claim any paid capability, account or hosted service.

FAQ / 常见问题

MCP or CLI for a coding agent? The README says coding agents increasingly favour CLI plus SKILLS for token efficiency, while MCP stays relevant for persistent-state, exploratory or self-healing loops.

Do I need a vision model? No. Automation runs on the accessibility tree, not screenshot reasoning. Coordinate-based vision tools exist but are opt-in with --caps=vision.

Is it safe to let the agent browse logged-in sites? The persistent profile keeps your sessions, and Playwright MCP is explicitly not a security boundary. Prefer isolated contexts, restricted origins and client-level permissions when you need real security.

Does adding it change my global config? Yes. MCP server entries live in client configuration files. Back up the file before editing and remove the entry to roll back.

Source and thanks

Thanks to the Playwright maintainers at Microsoft. The original English README and its complete Chinese translation are supplied separately by the section translator; this guide is companion material, not a replacement for them.

Source reviewed; runtime not tested.

Complete upstream material

Playwright MCP

A Model Context Protocol (MCP) server that provides browser automation capabilities using Playwright. This server enables LLMs to interact with web pages through structured accessibility snapshots, bypassing the need for screenshots or visually-tuned models.

Playwright MCP vs Playwright CLI

This package provides MCP interface into Playwright. If you are using a coding agent, you might benefit from using the CLI+SKILLS instead.

  • CLI: Modern coding agents increasingly favor CLI–based workflows exposed as SKILLs over MCP because CLI invocations are more token-efficient: they avoid loading large tool schemas and verbose accessibility trees into the model context, allowing agents to act through concise, purpose-built commands. This makes CLI + SKILLs better suited for high-throughput coding agents that must balance browser automation with large codebases, tests, and reasoning within limited context windows.
    Learn more about Playwright CLI with SKILLS.

  • MCP: MCP remains relevant for specialized agentic loops that benefit from persistent state, rich introspection, and iterative reasoning over page structure, such as exploratory automation, self-healing tests, or long-running autonomous workflows where maintaining continuous browser context outweighs token cost concerns.

Key Features

  • Fast and lightweight. Uses Playwright's accessibility tree, not pixel-based input.
  • LLM-friendly. No vision models needed, operates purely on structured data.
  • Deterministic tool application. Avoids ambiguity common with screenshot-based approaches.

Requirements

  • Node.js 18 or newer
  • VS Code, Cursor, Windsurf, Claude Desktop, Goose, Grok, Junie or any other MCP client

Getting started

First, install the Playwright MCP server with your client.

Standard config works in most of the tools:

{
  "mcpServers": {
    "playwright": {
      "command": "npx",
      "args": [
        "@playwright/mcp@latest"
      ]
    }
  }
}

Install in VS Code Install in VS Code Insiders

Amp

Add via the Amp VS Code extension settings screen or by updating your settings.json file:

"amp.mcpServers": {
  "playwright": {
    "command": "npx",
    "args": [
      "@playwright/mcp@latest"
    ]
  }
}

Amp CLI Setup:

Add via the amp mcp add command below

amp mcp add playwright -- npx @playwright/mcp@latest
Antigravity

Add via the Antigravity settings or by updating your configuration file:

{
  "mcpServers": {
    "playwright": {
      "command": "npx",
      "args": [
        "@playwright/mcp@latest"
      ]
    }
  }
}
Claude Code

Use the Claude Code CLI to add the Playwright MCP server:

claude mcp add playwright npx @playwright/mcp@latest
Claude Desktop

Follow the MCP install guide, use the standard config above.

Cline

Follow the instruction in the section Configuring MCP Servers

Example: Local Setup

Add the following to your cline_mcp_settings.json file:

{
  "mcpServers": {
    "playwright": {
      "type": "stdio",
      "command": "npx",
      "timeout": 30,
      "args": [
        "-y",
        "@playwright/mcp@latest"
      ],
      "disabled": false
    }
  }
}
Codex

Use the Codex CLI to add the Playwright MCP server:

codex mcp add playwright npx "@playwright/mcp@latest"

Alternatively, create or edit the configuration file ~/.codex/config.toml and add:

[mcp_servers.playwright]
command = "npx"
args = ["@playwright/mcp@latest"]

For more information, see the Codex MCP documentation.

Copilot

Use the Copilot CLI to interactively add the Playwright MCP server:

/mcp add

Alternatively, create or edit the configuration file ~/.copilot/mcp-config.json and add:

{
  "mcpServers": {
    "playwright": {
      "type": "local",
      "command": "npx",
      "tools": [
        "*"
      ],
      "args": [
        "@playwright/mcp@latest"
      ]
    }
  }
}

For more information, see the Copilot CLI documentation.

Cursor

Click the button to install:

Install in Cursor

Or install manually:

Go to Cursor Settings -> MCP -> Add new MCP Server. Name to your liking, use command type with the command npx @playwright/mcp@latest. You can also verify config or add command like arguments via clicking Edit.

Factory

Use the Factory CLI to add the Playwright MCP server:

droid mcp add playwright "npx @playwright/mcp@latest"

Alternatively, type /mcp within Factory droid to open an interactive UI for managing MCP servers.

For more information, see the Factory MCP documentation.

Gemini CLI

Follow the MCP install guide, use the standard config above.

Goose

Click the button to install:

Install in Goose

Or install manually:

Go to Advanced settings -> Extensions -> Add custom extension. Name to your liking, use type STDIO, and set the command to npx @playwright/mcp. Click "Add Extension".

Grok

Use the Grok CLI to add the Playwright MCP server:

grok mcp add playwright -- npx @playwright/mcp@latest

Alternatively, create or edit the configuration file ~/.grok/config.toml and add:

[mcp_servers.playwright]
command = "npx"
args = ["@playwright/mcp@latest"]

For more information, see the Grok MCP documentation.

Junie

To add the Playwright MCP server in Junie CLI:

  1. Type /mcp
  2. Press Ctrl+A to add a new MCP server
  3. Select Playwright from the list

Alternatively, add to .junie/mcp/mcp.json:

{
  "mcpServers": {
    "Playwright": {
      "command": "npx",
      "args": [
        "-y",
        "@playwright/mcp@latest"
      ]
    }
  }
}

For more information, see the Junie MCP configuration documentation.

Kiro

Add to Kiro

Follow the MCP Servers documentation. For example in .kiro/settings/mcp.json:

{
  "mcpServers": {
    "playwright": {
      "command": "npx",
      "args": [
        "@playwright/mcp@latest"
      ]
    }
  }
}
LM Studio

Click the button to install:

Add MCP Server playwright to LM Studio

Or install manually:

Go to Program in the right sidebar -> Install -> Edit mcp.json. Use the standard config above.

opencode

Follow the MCP Servers documentation. For example in ~/.config/opencode/opencode.json:

{
  "$schema": "https://opencode.ai/config.json",
  "mcp": {
    "playwright": {
      "type": "local",
      "command": [
        "npx",
        "@playwright/mcp@latest"
      ],
      "enabled": true
    }
  }
}
Qodo Gen

Open Qodo Gen chat panel in VSCode or IntelliJ → Connect more tools → + Add new MCP → Paste the standard config above.

Click Save.

VS Code

Click the button to install:

Install in VS Code Install in VS Code Insiders

Or install manually:

Follow the MCP install guide, use the standard config above. You can also install the Playwright MCP server using the VS Code CLI:

# For VS Code
code --add-mcp '{"name":"playwright","command":"npx","args":["@playwright/mcp@latest"]}'

After installation, the Playwright MCP server will be available for use with your GitHub Copilot agent in VS Code.

Warp

Go to Settings -> AI -> Manage MCP Servers -> + Add to add an MCP Server. Use the standard config above.

Alternatively, use the slash command /add-mcp in the Warp prompt and paste the standard config from above:

{
  "mcpServers": {
    "playwright": {
      "command": "npx",
      "args": [
        "@playwright/mcp@latest"
      ]
    }
  }
}
Windsurf

Follow Windsurf MCP documentation. Use the standard config above.

Configuration

Playwright MCP server supports following arguments. They can be provided in the JSON configuration above, as a part of the "args" list:

Option Description
--allowed-hosts <hosts...> comma-separated list of hosts this server is allowed to serve from. Defaults to the host the server is bound to. Pass '*' to disable the host check.
env PLAYWRIGHT_MCP_ALLOWED_HOSTS
--allowed-origins semicolon-separated list of TRUSTED origins to allow the browser to request. Default is to allow all. Important: does not serve as a security boundary and does not affect redirects.
env PLAYWRIGHT_MCP_ALLOWED_ORIGINS
--allow-unrestricted-file-access allow access to files outside of the workspace roots. Also allows unrestricted access to file:// URLs. By default access to file system is restricted to workspace root directories (or cwd if no roots are configured) only, and navigation to file:// URLs is blocked.
env PLAYWRIGHT_MCP_ALLOW_UNRESTRICTED_FILE_ACCESS
--blocked-origins semicolon-separated list of origins to block the browser from requesting. Blocklist is evaluated before allowlist. If used without the allowlist, requests not matching the blocklist are still allowed. Important: does not serve as a security boundary and does not affect redirects.
env PLAYWRIGHT_MCP_BLOCKED_ORIGINS
--block-service-workers block service workers
env PLAYWRIGHT_MCP_BLOCK_SERVICE_WORKERS
--browser browser or chrome channel to use, possible values: chrome, firefox, webkit, msedge.
env PLAYWRIGHT_MCP_BROWSER
--caps comma-separated list of additional capabilities to enable, possible values: vision, pdf, devtools.
env PLAYWRIGHT_MCP_CAPS
--cdp-endpoint CDP endpoint to connect to.
env PLAYWRIGHT_MCP_CDP_ENDPOINT
--cdp-header <headers...> CDP headers to send with the connect request, multiple can be specified.
env PLAYWRIGHT_MCP_CDP_HEADERS
--cdp-timeout timeout in milliseconds for connecting to CDP endpoint, defaults to 30000ms
env PLAYWRIGHT_MCP_CDP_TIMEOUT
--codegen specify the language to use for code generation, possible values: "typescript", "python", "java", "csharp", "none". Default is "typescript".
env PLAYWRIGHT_MCP_CODEGEN
--config path to the configuration file.
env PLAYWRIGHT_MCP_CONFIG
--console-level level of console messages to return: "error", "warning", "info", "debug". Each level includes the messages of more severe levels.
env PLAYWRIGHT_MCP_CONSOLE_LEVEL
--device device to emulate, for example: "iPhone 15"
env PLAYWRIGHT_MCP_DEVICE
--mobile emulate a generic mobile device (Pixel 10 for Chromium, iPhone 17 for WebKit). Mobile pages are usually lighter, which saves tokens. Cannot be combined with --device.
env PLAYWRIGHT_MCP_MOBILE
--executable-path path to the browser executable.
env PLAYWRIGHT_MCP_EXECUTABLE_PATH
--extension Connect to a running browser instance (Edge/Chrome only). Requires the "Playwright Extension" to be installed.
env PLAYWRIGHT_MCP_EXTENSION
--endpoint Bound browser endpoint to connect to.
env PLAYWRIGHT_MCP_ENDPOINT
--file-paths how file paths are rendered in tool results, "relative" to the workspace root or "absolute". Default is "relative".
env PLAYWRIGHT_MCP_FILE_PATHS
--grant-permissions <permissions...> List of permissions to grant to the browser context, for example "geolocation", "clipboard-read", "clipboard-write".
env PLAYWRIGHT_MCP_GRANT_PERMISSIONS
--headless run browser in headless mode, headed by default
env PLAYWRIGHT_MCP_HEADLESS
--host host to bind server to. Default is localhost. Use 0.0.0.0 to bind to all interfaces.
env PLAYWRIGHT_MCP_HOST
--idle-timeout close the browser after this many milliseconds without a completed tool call, the next tool call relaunches it. Defaults to one hour for headless browsers, never for headed ones, 0 disables.
env PLAYWRIGHT_MCP_IDLE_TIMEOUT
--ignore-https-errors ignore https errors
env PLAYWRIGHT_MCP_IGNORE_HTTPS_ERRORS
--init-page <path...> path to TypeScript file to evaluate on Playwright page object
env PLAYWRIGHT_MCP_INIT_PAGE
--init-script <path...> path to JavaScript file to add as an initialization script. The script will be evaluated in every page before any of the page's scripts. Can be specified multiple times.
env PLAYWRIGHT_MCP_INIT_SCRIPT
--isolated keep the browser profile in memory, do not save it to disk.
env PLAYWRIGHT_MCP_ISOLATED
--image-responses whether to send image responses to the client. Can be "allow", "omit" or "only". With "only", a response that carries an image consists of the image parts alone, without the text part. Defaults to "allow".
env PLAYWRIGHT_MCP_IMAGE_RESPONSES
--no-sandbox disable the sandbox for all process types that are normally sandboxed.
env PLAYWRIGHT_MCP_NO_SANDBOX
--no-webmcp do not collect or expose the tools that a page registers through the WebMCP API.
env PLAYWRIGHT_MCP_WEBMCP=false
--output-dir path to the directory for automatically named output files, for example a screenshot taken without an explicit file name. Files with an explicit name are resolved against the workspace root instead and are not affected by this option.
env PLAYWRIGHT_MCP_OUTPUT_DIR
--output-max-size Threshold for evicting old output files, in bytes.
env PLAYWRIGHT_MCP_OUTPUT_MAX_SIZE
--port port to listen on for SSE transport.
env PLAYWRIGHT_MCP_PORT
--profile-dir-name name of the profile directory in the user data dir to connect to with --extension, for example "Profile 1". Defaults to the last used profile that has the extension installed.
env PLAYWRIGHT_MCP_PROFILE_DIR_NAME
--proxy-bypass comma-separated domains to bypass proxy, for example ".com,chromium.org,.domain.com"
env PLAYWRIGHT_MCP_PROXY_BYPASS
--proxy-server specify proxy server, for example "http://myproxy:3128" or "socks5://myproxy:8080"
env PLAYWRIGHT_MCP_PROXY_SERVER
--sandbox enable the sandbox for all process types that are normally not sandboxed.
env PLAYWRIGHT_MCP_SANDBOX
--save-session Whether to save the Playwright MCP session into the output directory.
env PLAYWRIGHT_MCP_SAVE_SESSION
--secrets path to a file containing secrets in the dotenv format
env PLAYWRIGHT_MCP_SECRETS_FILE
--shared-browser-context reuse the same browser context between all connected HTTP clients.
env PLAYWRIGHT_MCP_SHARED_BROWSER_CONTEXT
--snapshot-boxes include each element's bounding box as [box=x,y,width,height] in snapshots. Coordinates are viewport-relative, in CSS pixels.
env PLAYWRIGHT_MCP_SNAPSHOT_BOXES
--snapshot-mode when taking snapshots for responses, specifies the mode to use. Can be "full" or "none". Default is "full".
env PLAYWRIGHT_MCP_SNAPSHOT_MODE
--storage-state path to the storage state file for isolated sessions.
env PLAYWRIGHT_MCP_STORAGE_STATE
--test-id-attribute specify the attribute to use for test ids, defaults to "data-testid"
env PLAYWRIGHT_MCP_TEST_ID_ATTRIBUTE
--timeout-action specify action timeout in milliseconds, defaults to 5000ms
env PLAYWRIGHT_MCP_TIMEOUT_ACTION
--timeout-navigation specify navigation timeout in milliseconds, defaults to 60000ms
env PLAYWRIGHT_MCP_TIMEOUT_NAVIGATION
--timeout-settle how long to wait after each action for triggered work to settle, in milliseconds, defaults to 500ms
env PLAYWRIGHT_MCP_TIMEOUT_SETTLE
--user-agent specify user agent string
env PLAYWRIGHT_MCP_USER_AGENT
--user-data-dir path to the user data directory. If not specified, a temporary directory will be created.
env PLAYWRIGHT_MCP_USER_DATA_DIR
--viewport-size specify browser viewport size in pixels, for example "1280x720"
env PLAYWRIGHT_MCP_VIEWPORT_SIZE

User profile

You can run Playwright MCP with persistent profile like a regular browser (default), in isolated contexts for testing sessions, or connect to your existing browser using the browser extension.

Persistent profile

All the logged in information will be stored in the persistent profile, you can delete it between sessions if you'd like to clear the offline state. Persistent profile is located at the following locations and you can override it with the --user-data-dir argument.

# Windows
%USERPROFILE%\AppData\Local\ms-playwright\mcp-{channel}-{workspace-hash}

# macOS
- ~/Library/Caches/ms-playwright/mcp-{channel}-{workspace-hash}

# Linux
- ~/.cache/ms-playwright/mcp-{channel}-{workspace-hash}

{workspace-hash} is derived from the MCP client's workspace root, so different projects get separate profiles automatically.

[!IMPORTANT] A persistent profile can only be used by one browser instance at a time, so concurrent MCP clients sharing the same workspace will conflict. To run several clients in parallel, start each additional client with --isolated or point it at a distinct --user-data-dir.

Isolated

In the isolated mode, each session is started in the isolated profile. Every time you ask MCP to close the browser, the session is closed and all the storage state for this session is lost. You can provide initial storage state to the browser via the config's contextOptions or via the --storage-state argument. Learn more about the storage state here.

{
  "mcpServers": {
    "playwright": {
      "command": "npx",
      "args": [
        "@playwright/mcp@latest",
        "--isolated",
        "--storage-state={path/to/storage.json}"
      ]
    }
  }
}

Browser Extension

The Playwright MCP Chrome Extension allows you to connect to existing browser tabs and leverage your logged-in sessions and browser state. See microsoft/playwright › packages/extension for installation and setup instructions.

Initial state

There are multiple ways to provide the initial state to the browser context or a page.

For the storage state, you can either:

  • Start with a user data directory using the --user-data-dir argument. This will persist all browser data between the sessions.
  • Start with a storage state file using the --storage-state argument. This will load cookies and local storage from the file into an isolated browser context.

For the page state, you can use:

  • --init-page to point to a TypeScript file that will be evaluated on the Playwright page object. This allows you to run arbitrary code to set up the page.
// init-page.ts
export default async ({ page }) => {
  await page.context().grantPermissions(['geolocation']);
  await page.context().setGeolocation({ latitude: 37.7749, longitude: -122.4194 });
  await page.setViewportSize({ width: 1280, height: 720 });
};
  • --init-script to point to a JavaScript file that will be added as an initialization script. The script will be evaluated in every page before any of the page's scripts. This is useful for overriding browser APIs or setting up the environment.
// init-script.js
window.isPlaywrightMCP = true;

Configuration file

The Playwright MCP server can be configured using a JSON configuration file. You can specify the configuration file using the --config command line option:

npx @playwright/mcp@latest --config path/to/config.json
Configuration file schema
{
  /**
   * The browser to use.
   */
  browser?: {
    /**
     * The type of browser to use.
     */
    browserName?: 'chromium' | 'firefox' | 'webkit';

    /**
     * Keep the browser profile in memory, do not save it to disk.
     */
    isolated?: boolean;

    /**
     * Path to a user data directory for browser profile persistence.
     * Temporary directory is created by default.
     */
    userDataDir?: string;

    /**
     * Launch options passed to
     * @see https://playwright.dev/docs/api/class-browsertype#browser-type-launch-persistent-context
     *
     * This is useful for settings options like `channel`, `headless`, `executablePath`, etc.
     */
    launchOptions?: playwright.LaunchOptions;

    /**
     * Context options for the browser context.
     *
     * This is useful for settings options like `viewport`.
     */
    contextOptions?: playwright.BrowserContextOptions;

    /**
     * Chrome DevTools Protocol endpoint to connect to an existing browser instance in case of Chromium family browsers.
     */
    cdpEndpoint?: string;

    /**
     * CDP headers to send with the connect request.
     */
    cdpHeaders?: Record<string, string>;

    /**
     * Timeout in milliseconds for connecting to CDP endpoint. Defaults to 30000 (30 seconds). Pass 0 to disable timeout.
     */
    cdpTimeout?: number;

    /**
     * Remote endpoint to connect to an existing Playwright server. May be a
     * WebSocket URL string, or a [ConnectOptions] object that mirrors the
     * `connectOptions` shape used by the test runner. When passed as an object,
     * `exposeNetwork`, `headers`, `slowMo`, and `timeout` are forwarded to the
     * underlying connect call.
     */
    remoteEndpoint?: string | playwright.ConnectOptions & { endpoint: string };

    /**
     * Paths to TypeScript files to add as initialization scripts for Playwright page.
     */
    initPage?: string[];

    /**
     * Paths to JavaScript files to add as initialization scripts.
     * The scripts will be evaluated in every page before any of the page's scripts.
     */
    initScript?: string[];
  },

  /**
   * Connect to a running browser instance (Edge/Chrome only). If specified, `browser`
   * config is ignored.
   * Requires the "Playwright Extension" to be installed.
   */
  extension?: boolean;

  server?: {
    /**
     * The port to listen on for SSE or MCP transport.
     */
    port?: number;

    /**
     * The host to bind the server to. Default is localhost. Use 0.0.0.0 to bind to all interfaces.
     */
    host?: string;

    /**
     * The hosts this server is allowed to serve from. Defaults to the host server is bound to.
     * This is not for CORS, but rather for the DNS rebinding protection.
     */
    allowedHosts?: string[];
  },

  /**
   * List of enabled tool capabilities. Possible values:
   *   - 'core': Core browser automation features.
   *   - 'pdf': PDF generation and manipulation.
   *   - 'vision': Coordinate-based interactions.
   *   - 'devtools': Developer tools features.
   */
  capabilities?: ToolCapability[];

  /**
   * Whether to save the Playwright session into the output directory.
   */
  saveSession?: boolean;

  /**
   * Whether to collect and expose the tools that a page registers through the
   * experimental WebMCP API. Enabled by default.
   */
  webmcp?: boolean;

  /**
   * Reuse the same browser context between all connected HTTP clients.
   */
  sharedBrowserContext?: boolean;

  /**
   * Secrets are used to replace matching plain text in the tool responses to prevent the LLM
   * from accidentally getting sensitive data. It is a convenience and not a security feature,
   * make sure to always examine information coming in and from the tool on the client.
   */
  secrets?: Record<string, string>;

  /**
   * The directory for automatically named output files, for example a screenshot taken without an
   * explicit file name. Files with an explicit name are resolved against the workspace root instead
   * and are not affected by this option.
   */
  outputDir?: string;

  /**
   * Threshold for evicting old output files, in bytes.
   */
  outputMaxSize?: number;

  console?: {
    /**
     * The level of console messages to return. Each level includes the messages of more severe levels. Defaults to "info".
     */
    level?: 'error' | 'warning' | 'info' | 'debug';
  },

  network?: {
    /**
     * List of origins to allow the browser to request. Default is to allow all. Origins matching both `allowedOrigins` and `blockedOrigins` will be blocked.
     *
     * Supported formats:
     * - Full origin: `https://example.com:8080` - matches only that origin
     * - Wildcard port: `http://localhost:*` - matches any port on localhost with http protocol
     */
    allowedOrigins?: string[];

    /**
     * List of origins to block the browser to request. Origins matching both `allowedOrigins` and `blockedOrigins` will be blocked.
     *
     * Supported formats:
     * - Full origin: `https://example.com:8080` - matches only that origin
     * - Wildcard port: `http://localhost:*` - matches any port on localhost with http protocol
     */
    blockedOrigins?: string[];
  };

  /**
   * Specify the attribute to use for test ids, defaults to "data-testid".
   */
  testIdAttribute?: string;

  timeouts?: {
    /*
     * Configures default action timeout: https://playwright.dev/docs/api/class-page#page-set-default-timeout. Defaults to 5000ms.
     */
    action?: number;

    /*
     * Configures default navigation timeout: https://playwright.dev/docs/api/class-page#page-set-default-navigation-timeout. Defaults to 60000ms.
     */
    navigation?: number;

    /**
     * Configures default expect timeout: https://playwright.dev/docs/test-timeouts#expect-timeout. Defaults to 5000ms.
     */
    expect?: number;

    /**
     * How long to wait after each action for triggered work (navigations, requests) to settle before responding. Defaults to 500ms.
     */
    settle?: number;

    /**
     * Close the browser after this many milliseconds without a tool call, and relaunch it on the next one.
     * Defaults to one hour for headless browsers Playwright launched, and to no timeout for headed or attached ones. Pass 0 to disable.
     * The CLI shuts the whole session down instead of relaunching.
     */
    idle?: number;
  };

  /**
   * Whether to send image responses to the client. Can be "allow", "omit", or "only". Defaults to "allow".
   * With "only", a response that carries an image consists of the image parts alone, without the text part.
   */
  imageResponses?: 'allow' | 'omit' | 'only';

  /**
   * How file paths are rendered in tool results. Can be "relative" to the workspace root or "absolute". Defaults to "relative".
   */
  filePaths?: 'relative' | 'absolute';

  snapshot?: {
    /**
     * When taking snapshots for responses, specifies the mode to use.
     */
    mode?: 'full' | 'none';

    /**
     * Whether to include each element's bounding box as [box=x,y,width,height] in snapshots.
     * Coordinates are viewport-relative, in CSS pixels (Element.getBoundingClientRect).
     */
    boxes?: boolean;
  };

  /**
   * allowUnrestrictedFileAccess acts as a guardrail to prevent the LLM from accidentally
   * wandering outside its intended workspace. It is a convenience defense to catch unintended
   * file access, not a secure boundary; a deliberate attempt to reach other directories can be
   * easily worked around, so always rely on client-level permissions for true security.
   */
  allowUnrestrictedFileAccess?: boolean;

  /**
   * Specify the language to use for code generation.
   */
  codegen?: 'typescript' | 'python' | 'java' | 'csharp' | 'none';
}

Standalone MCP server

When running headed browser on system w/o display or from worker processes of the IDEs, run the MCP server from environment with the DISPLAY and pass the --port flag to enable HTTP transport.

npx @playwright/mcp@latest --port 8931

And then in MCP client config, set the url to the HTTP endpoint:

{
  "mcpServers": {
    "playwright": {
      "url": "http://localhost:8931/mcp"
    }
  }
}

Security

Playwright MCP is not a security boundary. See MCP Security Best Practices for guidance on securing your deployment.

Docker

NOTE: The Docker implementation only supports headless chromium at the moment.

{
  "mcpServers": {
    "playwright": {
      "command": "docker",
      "args": ["run", "-i", "--rm", "--init", "--pull=always", "mcr.microsoft.com/playwright/mcp"]
    }
  }
}

Or If you prefer to run the container as a long-lived service instead of letting the MCP client spawn it, use:

docker run -d -i --rm --init --pull=always \
  --entrypoint node \
  --name playwright \
  -p 8931:8931 \
  mcr.microsoft.com/playwright/mcp \
  /app/cli.js --headless --browser chromium --no-sandbox --port 8931 --host 0.0.0.0

The server will listen on host port 8931 and can be reached by any MCP client.

You can build the Docker image yourself.

docker build -t mcr.microsoft.com/playwright/mcp .
Programmatic usage
import http from 'http';

import { createConnection } from '@playwright/mcp';
import { SSEServerTransport } from '@modelcontextprotocol/sdk/server/sse.js';

http.createServer(async (req, res) => {
  // ...

  // Creates a headless Playwright MCP server with SSE transport
  const connection = await createConnection({ browser: { launchOptions: { headless: true } } });
  const transport = new SSEServerTransport('/messages', res);
  await connection.connect(transport);

  // ...
});

Tools

Core automation
  • browser_click
    • Title: Click
    • Description: Perform click on a web page
    • Parameters:
      • element (string, optional): Human-readable element description used to obtain permission to interact with the element
      • target (string): Exact target element reference from the page snapshot, or a unique element selector
      • doubleClick (boolean, optional): Whether to perform a double click instead of a single click
      • button (string, optional): Button to click, defaults to left
      • modifiers (array, optional): Modifier keys to press
    • Read-only: false
  • browser_close
    • Title: Close browser
    • Description: Close the page
    • Parameters: None
    • Read-only: false
  • browser_console_messages
    • Title: Get console messages
    • Description: Returns all console messages
    • Parameters:
      • level (string): Level of the console messages to return. Each level includes the messages of more severe levels. Defaults to "info".
      • all (boolean, optional): Return all console messages since the beginning of the session, not just since the last navigation. Defaults to false.
      • filename (string, optional): File name to save the console messages to. Relative file names are resolved against the workspace root. If not provided, messages are returned as text.
    • Read-only: true
  • browser_drag
    • Title: Drag mouse
    • Description: Perform drag and drop between two elements
    • Parameters:
      • startElement (string, optional): Human-readable source element description used to obtain the permission to interact with the element
      • startTarget (string): Exact target element reference from the page snapshot, or a unique element selector
      • endElement (string, optional): Human-readable target element description used to obtain the permission to interact with the element
      • endTarget (string): Exact target element reference from the page snapshot, or a unique element selector
    • Read-only: false
  • browser_drop
    • Title: Drop files or data onto an element
    • Description: Drop files or MIME-typed data onto an element, as if dragged from outside the page. At least one of "paths" or "data" must be provided.
    • Parameters:
      • element (string, optional): Human-readable element description used to obtain permission to interact with the element
      • target (string): Exact target element reference from the page snapshot, or a unique element selector
      • paths (array, optional): Absolute paths to files to drop onto the element.
      • data (object, optional): Data to drop, as a map of MIME type to string value (e.g. {"text/plain": "hello", "text/uri-list": "https://example.com"}).
    • Read-only: false
  • browser_emulate_media
    • Title: Emulate media features
    • Description: Emulate CSS media features for the page, for example switch between the light and dark color scheme. Omitted parameters are left unchanged; null clears an override.
    • Parameters:
      • colorScheme (optional): Emulates the prefers-color-scheme media feature
      • reducedMotion (optional): Emulates the prefers-reduced-motion media feature
      • forcedColors (optional): Emulates the forced-colors media feature
      • contrast (optional): Emulates the prefers-contrast media feature
      • media (optional): Changes the CSS media type of the page
    • Read-only: false
  • browser_evaluate
    • Title: Evaluate JavaScript
    • Description: Evaluate JavaScript expression on page or element
    • Parameters:
      • element (string, optional): Human-readable element description used to obtain permission to interact with the element
      • target (string, optional): Exact target element reference from the page snapshot, or a unique element selector
      • function (string): () => { /* code / } or (element) => { / code */ } when element is provided
      • filename (string, optional): File name to save the result to. Relative file names are resolved against the workspace root. If not provided, result is returned as text.
    • Read-only: false
  • browser_file_upload
    • Title: Upload files
    • Description: Upload one or multiple files
    • Parameters:
      • paths (array, optional): The absolute paths to the files to upload. Can be single file or multiple files. If omitted, file chooser is cancelled.
    • Read-only: false
  • browser_fill_form
    • Title: Fill form
    • Description: Fill multiple form fields
    • Parameters:
      • fields (array): Fields to fill in
    • Read-only: false
  • browser_find
    • Title: Find in page snapshot
    • Description: Search the accessibility snapshot of the current page for text or a regular expression. Returns matching snapshot nodes with a few lines of surrounding context (like search snippets), each shown under its path from the root of the tree, which is cheaper than capturing the whole snapshot when you only need to locate an element and its ref.
    • Parameters:
      • text (string, optional): Plain text to search for in the page snapshot (case-insensitive substring match). Provide either text or regex, not both.
      • regex (string, optional): Regular expression to search for in the page snapshot. Matching is case-sensitive by default; wrap the pattern in slashes to add flags, e.g. "/error/i" for case-insensitive. Provide either text or regex, not both.
      • filename (string, optional): Save results to a file instead of returning them in the response. Relative file names are resolved against the workspace root.
    • Read-only: true
  • browser_handle_dialog
    • Title: Handle a dialog
    • Description: Handle a dialog
    • Parameters:
      • accept (boolean): Whether to accept the dialog.
      • promptText (string, optional): The text of the prompt in case of a prompt dialog.
    • Read-only: false
  • browser_hover
    • Title: Hover mouse
    • Description: Hover over element on page
    • Parameters:
      • element (string, optional): Human-readable element description used to obtain permission to interact with the element
      • target (string): Exact target element reference from the page snapshot, or a unique element selector
    • Read-only: false
  • browser_navigate
    • Title: Navigate to a URL
    • Description: Navigate to a URL
    • Parameters:
      • url (string): The URL to navigate to
    • Read-only: false
  • browser_navigate_back
    • Title: Go back
    • Description: Go back to the previous page in the history
    • Parameters: None
    • Read-only: false
  • browser_network_request
    • Title: Show network request details
    • Description: Returns full details (headers and body) of a single network request, or a single part if part is set. Use the number from browser_network_requests.
    • Parameters:
      • index (integer): 1-based index of the request, as printed by browser_network_requests.
      • part (string, optional): Return only this part of the request. Omit to return full details.
      • filename (string, optional): File name to save the result to. Relative file names are resolved against the workspace root. If not provided, output is returned as text.
    • Read-only: true
  • browser_network_requests
    • Title: List network requests
    • Description: Returns a numbered list of network requests since loading the page. Use browser_network_request with the number to get full details.
    • Parameters:
      • static (boolean): Whether to include successful static resources like images, fonts, scripts, etc. Defaults to false.
      • filter (string, optional): Only return requests whose URL matches this regexp (e.g. "/api/.*user").
      • filename (string, optional): File name to save the network requests to. Relative file names are resolved against the workspace root. If not provided, requests are returned as text.
    • Read-only: true
  • browser_press_key
    • Title: Press a key
    • Description: Press a key on the keyboard
    • Parameters:
      • key (string): Name of the key to press or a character to generate, such as ArrowLeft or a
    • Read-only: false
  • browser_resize
    • Title: Resize browser window
    • Description: Resize the browser window
    • Parameters:
      • width (number): Width of the browser window
      • height (number): Height of the browser window
    • Read-only: false
  • browser_run_code_unsafe
    • Title: Run Playwright code (unsafe)
    • Description: Run a Playwright code snippet. Unsafe: executes arbitrary JavaScript in the Playwright server process and is RCE-equivalent.
    • Parameters:
      • code (string, optional): A JavaScript function containing Playwright code to execute. It will be invoked with a single argument, page, which you can use for any page interaction. For example: async (page) => { await page.getByRole('button', { name: 'Submit' }).click(); return await page.title(); }
      • filename (string, optional): Load code from the specified file. Relative file names are resolved against the workspace root. If both code and filename are provided, code will be ignored.
    • Read-only: false
  • browser_select_option
    • Title: Select option
    • Description: Select an option in a dropdown
    • Parameters:
      • element (string, optional): Human-readable element description used to obtain permission to interact with the element
      • target (string): Exact target element reference from the page snapshot, or a unique element selector
      • values (array): Array of values to select in the dropdown. This can be a single value or multiple values.
    • Read-only: false
  • browser_snapshot
    • Title: Page snapshot
    • Description: Capture accessibility snapshot of the current page, this is better than screenshot
    • Parameters:
      • target (string, optional): Exact target element reference from the page snapshot, or a unique element selector
      • filename (string, optional): Save snapshot to a file instead of returning it in the response. Relative file names are resolved against the workspace root.
      • depth (number, optional): Limit the depth of the snapshot tree
      • boxes (boolean, optional): Include each element's bounding box as [box=x,y,width,height] in the snapshot. Coordinates are viewport-relative, in CSS pixels (Element.getBoundingClientRect)
    • Read-only: true
  • browser_take_screenshot
    • Title: Take a screenshot
    • Description: Take a screenshot of the current page. You can't perform actions based on the screenshot, use browser_snapshot for actions.
    • Parameters:
      • element (string, optional): Human-readable element description used to obtain permission to interact with the element
      • target (string, optional): Exact target element reference from the page snapshot, or a unique element selector
      • type (string, optional): Image format for the screenshot. If unset, inferred from the filename extension, otherwise png.
      • filename (string, optional): File name to save the screenshot to. Relative file names are resolved against the workspace root. If not specified, the screenshot is saved into the output directory as page-{timestamp}.{png|jpeg|webp}.
      • fullPage (boolean, optional): When true, takes a screenshot of the full scrollable page, instead of the currently visible viewport. Cannot be used with element screenshots.
      • scale (string): Image resolution scale. "css" produces a screenshot sized in CSS pixels (smaller, consistent across devices). "device" produces a high-resolution screenshot using device pixels (larger, accounts for the device pixel ratio). Default is css.
    • Read-only: true
  • browser_type
    • Title: Type text
    • Description: Type text into editable element
    • Parameters:
      • element (string, optional): Human-readable element description used to obtain permission to interact with the element
      • target (string): Exact target element reference from the page snapshot, or a unique element selector
      • text (string): Text to type into the element
      • submit (boolean, optional): Whether to submit entered text (press Enter after)
      • slowly (boolean, optional): Whether to type one character at a time. Useful for triggering key handlers in the page. By default entire text is filled in at once.
    • Read-only: false
  • browser_wait_for
    • Title: Wait for
    • Description: Wait for text to appear or disappear or a specified time to pass
    • Parameters:
      • time (number, optional): The time to wait in seconds, at most 30
      • text (string, optional): The text to wait for
      • textGone (string, optional): The text to wait for to disappear
    • Read-only: false
Tab management
  • browser_tabs
    • Title: Manage tabs
    • Description: List, create, close, or select a browser tab.
    • Parameters:
      • action (string): Operation to perform
      • index (number, optional): Tab index, used for close/select. If omitted for close, current tab is closed.
      • url (string, optional): URL to navigate to in the new tab, used for new.
    • Read-only: false
Browser installation
Configuration (opt-in via --caps=config)
  • browser_get_config
    • Title: Get config
    • Description: Get the final resolved config after merging CLI options, environment variables and config file.
    • Parameters: None
    • Read-only: true
Network (opt-in via --caps=network)
  • browser_network_state_set
    • Title: Set network state
    • Description: Sets the browser network state to online or offline. When offline, all network requests will fail.
    • Parameters:
      • state (string): Set to "offline" to simulate offline mode, "online" to restore network connectivity
    • Read-only: false
  • browser_route
    • Title: Mock network requests
    • Description: Set up a route to mock network requests matching a URL pattern
    • Parameters:
      • pattern (string): URL pattern to match (e.g., "/api/users", "/*.{png,jpg}")
      • status (number, optional): HTTP status code to return (default: 200)
      • body (string, optional): Response body (text or JSON string)
      • contentType (string, optional): Content-Type header (e.g., "application/json", "text/html")
      • headers (array, optional): Headers to add in "Name: Value" format
      • removeHeaders (string, optional): Comma-separated list of header names to remove from request
    • Read-only: false
  • browser_route_list
    • Title: List network routes
    • Description: List all active network routes
    • Parameters: None
    • Read-only: true
  • browser_unroute
    • Title: Remove network routes
    • Description: Remove network routes matching a pattern (or all routes if no pattern specified)
    • Parameters:
      • pattern (string, optional): URL pattern to unroute (omit to remove all routes)
    • Read-only: false
Storage (opt-in via --caps=storage)
  • browser_cookie_clear
    • Title: Clear cookies
    • Description: Clear all cookies
    • Parameters: None
    • Read-only: false
  • browser_cookie_delete
    • Title: Delete cookie
    • Description: Delete a specific cookie
    • Parameters:
      • name (string): Cookie name to delete
    • Read-only: false
  • browser_cookie_get
    • Title: Get cookie
    • Description: Get a specific cookie by name
    • Parameters:
      • name (string): Cookie name to get
    • Read-only: true
  • browser_cookie_list
    • Title: List cookies
    • Description: List all cookies (optionally filtered by domain/path)
    • Parameters:
      • domain (string, optional): Filter cookies by domain
      • path (string, optional): Filter cookies by path
    • Read-only: true
  • browser_cookie_set
    • Title: Set cookie
    • Description: Set a cookie with optional flags (domain, path, expires, httpOnly, secure, sameSite)
    • Parameters:
      • name (string): Cookie name
      • value (string): Cookie value
      • domain (string, optional): Cookie domain
      • path (string, optional): Cookie path
      • expires (number, optional): Cookie expiration as Unix timestamp
      • httpOnly (boolean, optional): Whether the cookie is HTTP only
      • secure (boolean, optional): Whether the cookie is secure
      • sameSite (string, optional): Cookie SameSite attribute
    • Read-only: false
  • browser_localstorage_clear
    • Title: Clear localStorage
    • Description: Clear all localStorage
    • Parameters: None
    • Read-only: false
  • browser_localstorage_delete
    • Title: Delete localStorage item
    • Description: Delete a localStorage item
    • Parameters:
      • key (string): Key to delete
    • Read-only: false
  • browser_localstorage_get
    • Title: Get localStorage item
    • Description: Get a localStorage item by key
    • Parameters:
      • key (string): Key to get
    • Read-only: true
  • browser_localstorage_list
    • Title: List localStorage
    • Description: List all localStorage key-value pairs
    • Parameters: None
    • Read-only: true
  • browser_localstorage_set
    • Title: Set localStorage item
    • Description: Set a localStorage item
    • Parameters:
      • key (string): Key to set
      • value (string): Value to set
    • Read-only: false
  • browser_sessionstorage_clear
    • Title: Clear sessionStorage
    • Description: Clear all sessionStorage
    • Parameters: None
    • Read-only: false
  • browser_sessionstorage_delete
    • Title: Delete sessionStorage item
    • Description: Delete a sessionStorage item
    • Parameters:
      • key (string): Key to delete
    • Read-only: false
  • browser_sessionstorage_get
    • Title: Get sessionStorage item
    • Description: Get a sessionStorage item by key
    • Parameters:
      • key (string): Key to get
    • Read-only: true
  • browser_sessionstorage_list
    • Title: List sessionStorage
    • Description: List all sessionStorage key-value pairs
    • Parameters: None
    • Read-only: true
  • browser_sessionstorage_set
    • Title: Set sessionStorage item
    • Description: Set a sessionStorage item
    • Parameters:
      • key (string): Key to set
      • value (string): Value to set
    • Read-only: false
  • browser_set_storage_state
    • Title: Restore storage state
    • Description: Restore storage state (cookies, local storage) from a file. This clears existing cookies and local storage before restoring.
    • Parameters:
      • filename (string): Path to the storage state file to restore from. Relative file names are resolved against the workspace root.
    • Read-only: false
  • browser_storage_state
    • Title: Save storage state
    • Description: Save storage state (cookies, local storage) to a file for later reuse
    • Parameters:
      • filename (string, optional): File name to save the storage state to. Relative file names are resolved against the workspace root. If not specified, the storage state is saved into the output directory as storage-state-{timestamp}.json.
    • Read-only: true
DevTools (opt-in via --caps=devtools)
  • browser_annotate
    • Title: Annotate the current page
    • Description: Open the Playwright Dashboard in annotation mode for the current page and wait for the user to draw annotations. Returns the annotated screenshot, ARIA snapshot, and the list of annotations.
    • Parameters: None
    • Read-only: true
  • browser_hide_highlight
    • Title: Hide element highlight
    • Description: Remove a highlight overlay previously added for the element.
    • Parameters:
      • element (string, optional): Human-readable element description used when adding the highlight; must match the value passed to browser_highlight.
      • target (string, optional): Exact target element reference from the page snapshot, or a unique element selector
    • Read-only: true
  • browser_highlight
    • Title: Highlight element
    • Description: Show a persistent highlight overlay around the element on the page.
    • Parameters:
      • element (string, optional): Human-readable element description used to obtain permission to interact with the element
      • target (string): Exact target element reference from the page snapshot, or a unique element selector
      • style (string, optional): Additional inline CSS applied to the highlight overlay, e.g. "outline: 2px dashed red".
    • Read-only: true
  • browser_resume
    • Title: Resume paused script execution
    • Description: Resume script execution after it was paused. When called with step set to true, execution will pause again before the next action.
    • Parameters:
      • step (boolean, optional): When true, execution will pause again before the next action, allowing step-by-step debugging.
      • location (string, optional): Pause execution at a specific :, e.g. "example.spec.ts:42".
    • Read-only: false
  • browser_start_recording
    • Title: Start recording user actions
    • Description: Start recording actions that the user performs in the browser as Playwright code. Use it when the user wants to demonstrate a flow manually. Call browser_stop_recording when the user says they are done to retrieve the recorded actions.
    • Parameters: None
    • Read-only: true
  • browser_start_tracing
    • Title: Start tracing
    • Description: Start trace recording
    • Parameters: None
    • Read-only: true
  • browser_start_video
    • Title: Start video
    • Description: Start video recording
    • Parameters:
      • filename (string, optional): File name to save the video to. Relative file names are resolved against the workspace root. If not specified, the video is saved into the output directory as video-{timestamp}.webm.
      • size (object, optional): Video size
      • fps (number, optional): Video frame rate in frames per second, defaults to 25
      • cursor (boolean, optional): Render an animated mouse cursor that travels to each action point. Paces actions by 800ms so that the cursor has time to travel.
    • Read-only: true
  • browser_stop_recording
    • Title: Stop recording user actions
    • Description: Stop the recording started with browser_start_recording and return the recorded actions as Playwright code.
    • Parameters: None
    • Read-only: true
  • browser_stop_tracing
    • Title: Stop tracing
    • Description: Stop trace recording
    • Parameters: None
    • Read-only: true
  • browser_stop_video
    • Title: Stop video
    • Description: Stop video recording
    • Parameters: None
    • Read-only: true
  • browser_video_chapter
    • Title: Video chapter
    • Description: Add a chapter marker to the video recording. Shows a full-screen chapter card with blurred backdrop.
    • Parameters:
      • title (string): Chapter title
      • description (string, optional): Chapter description
      • duration (number, optional): Duration in milliseconds to show the chapter card
    • Read-only: true
  • browser_video_hide_actions
    • Title: Hide action overlays
    • Description: Stop annotating actions performed on the page.
    • Parameters: None
    • Read-only: true
  • browser_video_show_actions
    • Title: Show action overlays
    • Description: Annotate subsequent actions performed on the page with a callout that names the action and, when styled, marks the action point and highlights the target element. Useful while video recording or screencasting.
    • Parameters:
      • duration (number, optional): How long each action annotation stays on screen, in milliseconds. Defaults to 500.
      • position (string, optional): Where to place the action title relative to the page. Defaults to top-right.
      • cursor (string, optional): Cursor decoration for pointer actions. "pointer" (default) animates a mouse pointer from the previous action point to the next one; "none" disables the cursor decoration.
      • style (object, optional): Styles of the action decorations.
    • Read-only: true
Coordinate-based (opt-in via --caps=vision)
  • browser_mouse_click_xy
    • Title: Click
    • Description: Click mouse button at a given position
    • Parameters:
      • x (number): X coordinate
      • y (number): Y coordinate
      • button (string, optional): Button to click, defaults to left
      • clickCount (number, optional): Number of clicks, defaults to 1
      • delay (number, optional): Time to wait between mouse down and mouse up in milliseconds, defaults to 0
    • Read-only: false
  • browser_mouse_down
    • Title: Press mouse down
    • Description: Press mouse down
    • Parameters:
      • button (string, optional): Button to press, defaults to left
    • Read-only: false
  • browser_mouse_drag_xy
    • Title: Drag mouse
    • Description: Drag left mouse button to a given position
    • Parameters:
      • startX (number): Start X coordinate
      • startY (number): Start Y coordinate
      • endX (number): End X coordinate
      • endY (number): End Y coordinate
    • Read-only: false
  • browser_mouse_move_xy
    • Title: Move mouse
    • Description: Move mouse to a given position
    • Parameters:
      • x (number): X coordinate
      • y (number): Y coordinate
    • Read-only: false
  • browser_mouse_up
    • Title: Press mouse up
    • Description: Press mouse up
    • Parameters:
      • button (string, optional): Button to press, defaults to left
    • Read-only: false
  • browser_mouse_wheel
    • Title: Scroll mouse wheel
    • Description: Scroll mouse wheel
    • Parameters:
      • deltaX (number): X delta
      • deltaY (number): Y delta
    • Read-only: false
PDF generation (opt-in via --caps=pdf)
  • browser_pdf_save
    • Title: Save as PDF
    • Description: Save page as PDF
    • Parameters:
      • filename (string, optional): File name to save the pdf to. Relative file names are resolved against the workspace root. If not specified, the pdf is saved into the output directory as page-{timestamp}.pdf.
    • Read-only: true
Test assertions (opt-in via --caps=testing)
  • browser_generate_locator
    • Title: Create locator for element
    • Description: Generate locator for the given element to use in tests
    • Parameters:
      • element (string, optional): Human-readable element description used to obtain permission to interact with the element
      • target (string): Exact target element reference from the page snapshot, or a unique element selector
    • Read-only: true
  • browser_verify_element_visible
    • Title: Verify element visible
    • Description: Verify element is visible on the page
    • Parameters:
      • role (string): ROLE of the element. Can be found in the snapshot like this: - {ROLE} "Accessible Name":
      • accessibleName (string): ACCESSIBLE_NAME of the element. Can be found in the snapshot like this: - role "{ACCESSIBLE_NAME}"
    • Read-only: false
  • browser_verify_list_visible
    • Title: Verify list visible
    • Description: Verify list is visible on the page
    • Parameters:
      • element (string): Human-readable list description
      • target (string): Exact target element reference that points to the list
      • items (array): Items to verify
    • Read-only: false
  • browser_verify_text_visible
    • Title: Verify text visible
    • Description: Verify text is visible on the page. Prefer browser_verify_element_visible if possible.
    • Parameters:
      • text (string): TEXT to verify. Can be found in the snapshot like this: - role "Accessible Name": {TEXT} or like this: - text: {TEXT}
    • Read-only: false
  • browser_verify_value
    • Title: Verify value
    • Description: Verify element value
    • Parameters:
      • type (string): Type of the element
      • element (string): Human-readable element description
      • target (string): Exact target element reference from the page snapshot
      • value (string): Value to verify. For checkbox, use "true" or "false".
    • Read-only: false

Source and license

Source · License · f183dad4a52965583e3cc1d59b88cdc279e2e57d

                             Apache License
                       Version 2.0, January 2004
                    http://www.apache.org/licenses/

TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

  1. Definitions.

    "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.

    "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.

    "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.

    "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.

    "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.

    "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.

    "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).

    "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.

    "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."

    "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.

  2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.

  3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.

  4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:

    (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.

  5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.

  6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.

  7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.

  8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.

  9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.

END OF TERMS AND CONDITIONS

APPENDIX: How to apply the Apache License to your work.

  To apply the Apache License to your work, attach the following
  boilerplate notice, with the fields enclosed by brackets "[]"
  replaced with your own identifying information. (Don't include
  the brackets!)  The text should be enclosed in the appropriate
  comment syntax for the file format. We also recommend that a
  file or class name and description of purpose be included on the
  same "printed page" as the copyright notice for easier
  identification within third-party archives.

Copyright (c) Microsoft Corporation.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.


Playwright MCP 配套指南:安装与安全使用

Playwright MCP 服务器双语配套指南:安装、验证、权限边界、限制与常见排障。

快速使用

  1. 用 Claude Code CLI 安装已核验的入口:
claude mcp add playwright npx @playwright/mcp@latest
  1. 用 Codex CLI 添加同一个服务器:
codex mcp add playwright npx "@playwright/mcp@latest"
  1. 手工验证:在你的 MCP 客户端里列出 servers/tools,确认出现 Playwright。这是在客户端内部进行的手工检查,不是 shell 命令,因此以普通文字说明,而不放进代码块。

如果你的客户端不在上面两类里,就把原 README 的标准 mcpServers 配置块写进该客户端的 MCP 配置文件,其中 "command": "npx"、"args": ["@playwright/mcp@latest"]。

安装设置

Playwright MCP 是来自 microsoft/playwright-mcp 的 Model Context Protocol 服务器,让 MCP 客户端通过 Playwright 实现浏览器自动化。它用 Playwright 的可访问性树而不是像素来驱动页面,因此默认不需要视觉模型,操作也比截图方案更具确定性。

开始前你需要准备:

  • Node.js 18 或更新版本,并在 PATH 中,便于 npx 解析该包。
  • 一个支持 stdio 服务器的 MCP 客户端:VS Code、Cursor、Windsurf、Claude Desktop、Goose、Grok、Junie 等。
  • 对该客户端 MCP 配置文件的写权限,以及一份备份。

预期结果:安装后客户端会列出名为 playwright 的服务器,并暴露 browser_navigate、browser_snapshot 等浏览器工具。这里没有记录上游测试套件的结果:该资产只是一份配置记录,其快照中没有任何文件,发布时也未执行任何内容。

本配套指南补充原 README 没有集中说明的内容:如何在 MCP 与 Playwright CLI 之间取舍、你实际授予了哪些权限、如何回滚,以及如何把一台机器上的配置复现到另一台。

权限提示:MCP 服务器通过你的客户端执行命令,来源风险档案把该资产标记为会修改全局或客户端级配置。修改配置前请先备份。

来源已核验;未做运行时测试。

前置条件与权限

  • 添加服务器会修改客户端的 MCP 配置文件。请先备份;删除该条目即为回滚。
  • 默认使用持久化 profile,浏览器登录状态会写到用户缓存目录下 ms-playwright 相关路径。不希望保留时,或同一工作区有多个 MCP 客户端时,请用 --isolated 或独立的 --user-data-dir。
  • 默认限制在工作区根目录内的文件访问,并阻止 file:// 导航。--allow-unrestricted-file-access 会移除这道护栏;README 明确说明它只是便利性防护,不是安全边界。
  • --allowed-origins 与 --blocked-origins 不是安全边界,也不影响重定向。
  • 通过 --secrets 传入的密钥只是避免敏感字符串出现在工具响应里的便利手段,不是安全特性。请检查你提供的任何密钥,不要把凭据写进提示词。
  • 一份持久化 profile 同时只能被一个浏览器实例使用,因此同一工作区内的并发客户端会冲突。

选 MCP 还是 CLI

上游 README 对此说得很明确,而这直接影响成本:

  • CLI + SKILLS 适合编码 agent:不把庞大的工具 schema 和冗长的可访问性树加载进上下文,更省 token。
  • MCP 适合需要持久浏览器状态、对页面结构反复推理、探索式自动化或自愈测试的长时间 agent 循环,此时持续保留浏览器上下文的价值超过 token 成本。

如果你的主要工作是改代码、偶尔开浏览器,CLI 通常是更省钱的默认选择。在定下方案前,值得先看上游 README 关于 Playwright CLI with SKILLS 的说明。

安全落地清单

  1. 核对来源:仓库、许可证(Apache-2.0)、以及你打算使用的确切安装命令。
  2. 用“快速使用”中对应客户端的命令安装。
  3. 如果服务器没出现就重启客户端,再重新列出 servers/tools。
  4. 记录基线:安装耗时、首次成功的工具调用、完整跑通的 1 个真实任务。
  5. 写下升级路径(重启会重新解析 @latest)与回滚路径(删掉该服务器条目或还原配置备份)。
  6. CI 中不要依赖 @latest,固定 Node 与 Playwright 版本,并保证各机器浏览器依赖一致。

值得了解的参数

参数 实际作用
--headless 无可见窗口运行;默认是有界面模式。
--isolated 内存中的 profile,会话结束即丢失存储状态。
--storage-state <path> 把 cookies 与 localStorage 载入隔离上下文。
--user-data-dir <path> 指定持久化 profile 的位置。
--browser <browser> chrome、firefox、webkit 或 msedge。
--device <device> 模拟设备,如 "iPhone 15";不能与 --mobile 同时使用。
--mobile 通用移动端模拟,页面更轻、更省 token。
--caps <caps> 按需开启 vision、pdf、devtools 等能力。
--allowed-hosts <hosts...> 允许服务器服务的 host,用于防 DNS rebinding,不是 CORS。
--port <port> 改用 HTTP 传输,例如 --port 8931。
--idle-timeout <timeout> 空闲后关闭浏览器,下次调用时重新启动。
--no-sandbox 关闭浏览器沙箱;不了解后果时不要使用。

大多数参数都有对应的 PLAYWRIGHT_MCP_* 环境变量,也都可以写进用 --config path/to/config.json 引用的 JSON 文件。

常见排障

  • 装了但看不到:重启客户端,再列出 servers/tools。
  • 一台机器能跑、另一台不行:固定 Node 与 Playwright 版本,并对比两边配置差异。
  • 同一工作区两个客户端冲突:持久化 profile 同时只能被一个浏览器实例使用;额外客户端请用 --isolated 或不同的 --user-data-dir。
  • 无显示环境下有界面浏览器失败:用 --port 8931 启动服务器,并让客户端连接 http://localhost:8931/mcp,或使用上游 Docker 镜像(该示例仅支持无界面 chromium)。
  • token 或延迟超预期:优先用 browser_find 和 --snapshot-mode none 代替完整快照,并让工具输出更简短。

本文未涵盖的内容

  • 没有复现任何上游基准或测试套件结果,因为快照中没有记录。
  • 安装文件不属于本资产:快照未列出任何文件,因此本地也没有可检查的内容。
  • 本指南不声称任何付费能力、账号或托管服务。

常见问题

编码 agent 该选 MCP 还是 CLI? README 指出编码 agent 越来越倾向 CLI + SKILLS 以节省 token,而 MCP 更适合需要持久状态、探索式或自愈循环的场景。

需要视觉模型吗? 不需要。自动化基于可访问性树,而非截图推理。基于坐标的视觉工具确实存在,但需通过 --caps=vision 主动开启。

让 agent 浏览已登录网站安全吗? 持久化 profile 会保留你的登录会话,而 Playwright MCP 明确不是安全边界。真正需要安全时,应使用隔离上下文、限制来源并依赖客户端级别的权限控制。

添加它会改我的全局配置吗? 会。MCP 服务器条目存放在客户端配置文件里。修改前先备份,删除该条目即可回滚。

来源与感谢

感谢微软 Playwright 维护团队。原始英文 README 及其完整中文翻译由章节翻译器单独提供;本指南是配套材料,不替代它们。

来源已核验;未做运行时测试。

完整上游材料译文

Playwright MCP

一个 Model Context Protocol (MCP) 服务器,使用 Playwright 提供浏览器自动化能力。该服务器使 LLM 能够通过结构化可访问性快照与网页交互,无需截图或视觉微调模型。

Playwright MCP 与 Playwright CLI 对比

本包提供了 Playwright 的 MCP 接口。如果你使用编码 agent,改用 CLI+SKILLS 可能更有利。

  • CLI:现代编码 agent 越来越倾向于以 SKILL 形式暴露的基于 CLI 的工作流,而非 MCP,因为 CLI 调用更省 token:它们避免将庞大的工具 schema 和冗长的可访问性树加载进模型上下文,让 agent 通过简洁、专用的命令来行动。这使 CLI + SKILLs 更适合必须在有限上下文窗口内平衡浏览器自动化与大型代码库、测试和推理的高吞吐量编码 agent。
    了解关于 Playwright CLI with SKILLS 的更多信息。

  • MCP:MCP 对于受益于持久状态、丰富内省以及对页面结构反复推理的专门 agent 循环仍然相关,例如探索式自动化、自愈测试,或维持持续浏览器上下文的价值超过 token 成本考虑的长时间自主工作流。

关键特性

  • 快速轻量。使用 Playwright 的可访问性树,而非基于像素的输入。
  • 对 LLM 友好。不需要视觉模型,完全基于结构化数据运行。
  • 确定性的工具应用。避免了基于截图方法常见的歧义。

要求

  • Node.js 18 或更新版本
  • VS Code、Cursor、Windsurf、Claude Desktop、Goose、Grok、Junie 或任何其他 MCP 客户端

快速开始

首先,在你的客户端上安装 Playwright MCP 服务器。

标准配置在大多数工具中可用:

{
  "mcpServers": {
    "playwright": {
      "command": "npx",
      "args": [
        "@playwright/mcp@latest"
      ]
    }
  }
}

Install in VS Code Install in VS Code Insiders

Amp

通过 Amp VS Code 扩展的设置界面添加,或更新你的 settings.json 文件:

"amp.mcpServers": {
  "playwright": {
    "command": "npx",
    "args": [
      "@playwright/mcp@latest"
    ]
  }
}

Amp CLI 设置:

通过下面的 amp mcp add 命令添加

amp mcp add playwright -- npx @playwright/mcp@latest
Antigravity

通过 Antigravity 设置添加,或更新你的配置文件:

{
  "mcpServers": {
    "playwright": {
      "command": "npx",
      "args": [
        "@playwright/mcp@latest"
      ]
    }
  }
}
Claude Code

使用 Claude Code CLI 添加 Playwright MCP 服务器:

claude mcp add playwright npx @playwright/mcp@latest
Claude Desktop

按照 MCP 安装指南操作,使用上面的标准配置。

Cline

按照配置 MCP 服务器一节的说明操作

示例:本地设置

将以下内容添加到你的 cline_mcp_settings.json 文件中:

{
  "mcpServers": {
    "playwright": {
      "type": "stdio",
      "command": "npx",
      "timeout": 30,
      "args": [
        "-y",
        "@playwright/mcp@latest"
      ],
      "disabled": false
    }
  }
}
Codex

使用 Codex CLI 添加 Playwright MCP 服务器:

codex mcp add playwright npx "@playwright/mcp@latest"

或者,创建或编辑配置文件 ~/.codex/config.toml 并添加:

[mcp_servers.playwright]
command = "npx"
args = ["@playwright/mcp@latest"]

更多信息参见 Codex MCP 文档。

Copilot

使用 Copilot CLI 交互式地添加 Playwright MCP 服务器:

/mcp add

或者,创建或编辑配置文件 ~/.copilot/mcp-config.json 并添加:

{
  "mcpServers": {
    "playwright": {
      "type": "local",
      "command": "npx",
      "tools": [
        "*"
      ],
      "args": [
        "@playwright/mcp@latest"
      ]
    }
  }
}

更多信息参见 Copilot CLI 文档。

Cursor

点击按钮安装:

在 Cursor 中安装

或手动安装:

前往 Cursor Settings -> MCP -> Add new MCP Server。名称随你喜欢,类型选 command,命令用 npx @playwright/mcp@latest。你也可以点击 Edit 来核对配置或添加命令参数。

Factory

使用 Factory CLI 添加 Playwright MCP 服务器:

droid mcp add playwright "npx @playwright/mcp@latest"

另外,在 Factory droid 中输入 /mcp 可打开一个用于管理 MCP 服务器的交互式界面。

更多信息请参阅 Factory MCP 文档。

Gemini CLI

按照 MCP 安装指南操作,使用上面的标准配置。

Goose

点击按钮安装:

Install in Goose

或手动安装:

进入 Advanced settings -> Extensions -> Add custom extension。随意命名,类型选择 STDIO,并将 command 设为 npx @playwright/mcp。点击 "Add Extension"。

Grok

使用 Grok CLI 添加 Playwright MCP 服务器:

grok mcp add playwright -- npx @playwright/mcp@latest

或者,创建或编辑配置文件 ~/.grok/config.toml 并添加:

[mcp_servers.playwright]
command = "npx"
args = ["@playwright/mcp@latest"]

更多信息请参见 Grok MCP 文档。

Junie

在 Junie CLI 中添加 Playwright MCP 服务器:

  1. 输入 /mcp
  2. 按 Ctrl+A 添加新的 MCP 服务器
  3. 从列表中选择 Playwright

或者,添加到 .junie/mcp/mcp.json:

{
  "mcpServers": {
    "Playwright": {
      "command": "npx",
      "args": [
        "-y",
        "@playwright/mcp@latest"
      ]
    }
  }
}

更多信息请参见 Junie MCP 配置文档。

Kiro

Add to Kiro

请遵循 MCP Servers 文档。例如在 .kiro/settings/mcp.json 中:

{
  "mcpServers": {
    "playwright": {
      "command": "npx",
      "args": [
        "@playwright/mcp@latest"
      ]
    }
  }
}
LM Studio

点击按钮安装:

Add MCP Server playwright to LM Studio

或手动安装:

在右侧边栏中进入 Program -> Install -> Edit mcp.json。使用上面的标准配置。

opencode

请遵循 MCP Servers 文档。例如在 ~/.config/opencode/opencode.json 中:

{
  "$schema": "https://opencode.ai/config.json",
  "mcp": {
    "playwright": {
      "type": "local",
      "command": [
        "npx",
        "@playwright/mcp@latest"
      ],
      "enabled": true
    }
  }
}
Qodo Gen

在 VSCode 或 IntelliJ 中打开 Qodo Gen 聊天面板 → Connect more tools → + Add new MCP → 粘贴上面的标准配置。

点击 Save。

VS Code

点击按钮进行安装:

Install in VS Code Install in VS Code Insiders

或手动安装:

按照 MCP 安装指南,使用上面的标准配置。你也可以使用 VS Code CLI 安装 Playwright MCP 服务器:

# For VS Code
code --add-mcp '{"name":"playwright","command":"npx","args":["@playwright/mcp@latest"]}'

安装后,Playwright MCP 服务器将可在 VS Code 中与你的 GitHub Copilot agent 一起使用。

Warp

转到 Settings -> AI -> Manage MCP Servers -> + Add 来添加 MCP 服务器。使用上面的标准配置。

或者,在 Warp 提示符中使用斜杠命令 /add-mcp,并粘贴上面的标准配置:

{
  "mcpServers": {
    "playwright": {
      "command": "npx",
      "args": [
        "@playwright/mcp@latest"
      ]
    }
  }
}
Windsurf

请遵循 Windsurf MCP 文档。使用上面的标准配置。

配置

Playwright MCP 服务器支持以下参数。它们可以在上面的 JSON 配置中提供,作为 "args" 列表的一部分:

参数 说明
--allowed-hosts <hosts...> 允许此服务器服务的 host 的逗号分隔列表。默认值为服务器所绑定的 host。传入 '*' 可禁用 host 检查。
环境变量 PLAYWRIGHT_MCP_ALLOWED_HOSTS
--allowed-origins 允许浏览器请求的受信任来源的分号分隔列表。默认允许全部。重要提示:它不是安全边界,并且不影响重定向。
环境变量 PLAYWRIGHT_MCP_ALLOWED_ORIGINS
--allow-unrestricted-file-access 允许访问工作区根目录之外的文件。同时允许对 file:// URL 的无限制访问。默认情况下,对文件系统的访问仅限于工作区根目录(如果未配置根目录,则为 cwd),并且阻止导航到 file:// URL。
环境变量 PLAYWRIGHT_MCP_ALLOW_UNRESTRICTED_FILE_ACCESS
--blocked-origins 阻止浏览器请求的来源的分号分隔列表。黑名单在允许列表之前进行判断。如果仅使用黑名单而不使用允许列表,与黑名单不匹配的请求仍然会被允许。重要提示:它不是安全边界,并且不影响重定向。
环境变量 PLAYWRIGHT_MCP_BLOCKED_ORIGINS
--block-service-workers 阻止 service workers
环境变量 PLAYWRIGHT_MCP_BLOCK_SERVICE_WORKERS
--browser 要使用的浏览器或 chrome 渠道,可能的值:chrome、firefox、webkit、msedge。
环境变量 PLAYWRIGHT_MCP_BROWSER
--caps 要启用的附加功能的逗号分隔列表,可能的值:vision、pdf、devtools。
环境变量 PLAYWRIGHT_MCP_CAPS
--cdp-endpoint 要连接的 CDP 端点。
环境变量 PLAYWRIGHT_MCP_CDP_ENDPOINT
--cdp-header <headers...> 随连接请求发送的 CDP 头,可以指定多个。
环境变量 PLAYWRIGHT_MCP_CDP_HEADERS
--cdp-timeout 连接到 CDP 端点的超时时间(毫秒),默认 30000ms
环境变量 PLAYWRIGHT_MCP_CDP_TIMEOUT
--codegen 指定用于代码生成的语言,可能的值:"typescript"、"python"、"java"、"csharp"、"none"。默认是 "typescript"。
环境变量 PLAYWRIGHT_MCP_CODEGEN
--config 配置文件的路径。
环境变量 PLAYWRIGHT_MCP_CONFIG
--console-level 要返回的控制台消息级别:"error"、"warning"、"info"、"debug"。每个级别包含更严重级别的消息。
环境变量 PLAYWRIGHT_MCP_CONSOLE_LEVEL
--device 要模拟的设备,例如:"iPhone 15"
环境变量 PLAYWRIGHT_MCP_DEVICE
--mobile 模拟通用移动设备(Chromium 使用 Pixel 10,WebKit 使用 iPhone 17)。移动页面通常更轻,可节省 token。不能与 --device 同时使用。
环境变量 PLAYWRIGHT_MCP_MOBILE
--executable-path 浏览器可执行文件的路径。
环境变量 PLAYWRIGHT_MCP_EXECUTABLE_PATH
--extension 连接到正在运行的浏览器实例(仅 Edge/Chrome)。需要安装 "Playwright Extension"。
环境变量 PLAYWRIGHT_MCP_EXTENSION

| --endpoint | 要连接的受控浏览器端点。
环境变量 PLAYWRIGHT_MCP_ENDPOINT | | --file-paths | 文件路径在工具结果中的呈现方式,可设为相对工作区根目录的 "relative" 或 "absolute"。默认为 "relative"。
环境变量 PLAYWRIGHT_MCP_FILE_PATHS | | --grant-permissions <permissions...> | 授予浏览器上下文的权限列表,例如 "geolocation"、"clipboard-read"、"clipboard-write"。
环境变量 PLAYWRIGHT_MCP_GRANT_PERMISSIONS | | --headless | 以无头模式运行浏览器,默认为有头模式
环境变量 PLAYWRIGHT_MCP_HEADLESS | | --host | 服务器绑定的主机。默认为 localhost。使用 0.0.0.0 绑定到所有接口。
环境变量 PLAYWRIGHT_MCP_HOST | | --idle-timeout | 在没有已完成工具调用的这段时间(毫秒)后关闭浏览器,下一次工具调用会重新启动它。无头浏览器默认为一小时,有头浏览器默认为从不关闭,0 表示禁用。
环境变量 PLAYWRIGHT_MCP_IDLE_TIMEOUT | | --ignore-https-errors | 忽略 https 错误
环境变量 PLAYWRIGHT_MCP_IGNORE_HTTPS_ERRORS | | --init-page <path...> | 在 Playwright page 对象上求值的 TypeScript 文件路径
环境变量 PLAYWRIGHT_MCP_INIT_PAGE | | --init-script <path...> | 要作为初始化脚本添加的 JavaScript 文件路径。该脚本将在页面的任何脚本之前在每个页面中求值。可多次指定。
环境变量 PLAYWRIGHT_MCP_INIT_SCRIPT | | --isolated | 将浏览器配置文件保留在内存中,不保存到磁盘。
环境变量 PLAYWRIGHT_MCP_ISOLATED | | --image-responses | 是否向客户端发送图像响应。可为 "allow"、"omit" 或 "only"。使用 "only" 时,携带图像的响应仅由图像部分组成,不含文本部分。默认为 "allow"。
环境变量 PLAYWRIGHT_MCP_IMAGE_RESPONSES | | --no-sandbox | 为所有通常受沙箱保护的进程类型禁用沙箱。
环境变量 PLAYWRIGHT_MCP_NO_SANDBOX | | --no-webmcp | 不收集或暴露页面通过 WebMCP API 注册的工具。
环境变量 PLAYWRIGHT_MCP_WEBMCP=false | | --output-dir | 自动命名输出文件(例如未指定文件名的截图)的目录路径。显式命名的文件则相对于工作区根目录解析,不受此选项影响。
环境变量 PLAYWRIGHT_MCP_OUTPUT_DIR | | --output-max-size | 淘汰旧输出文件的阈值,以字节为单位。
环境变量 PLAYWRIGHT_MCP_OUTPUT_MAX_SIZE | | --port | 用于 SSE 传输的监听端口。
环境变量 PLAYWRIGHT_MCP_PORT | | --profile-dir-name | 在用户数据目录中通过 --extension 连接的配置文件目录的名称,例如 "Profile 1"。默认为最后一个已安装该扩展的已用配置文件。
环境变量 PLAYWRIGHT_MCP_PROFILE_DIR_NAME | | --proxy-bypass | 绕过代理的逗号分隔域名,例如 ".com,chromium.org,.domain.com"
环境变量 PLAYWRIGHT_MCP_PROXY_BYPASS | | --proxy-server | 指定代理服务器,例如 "http://myproxy:3128" 或 "socks5://myproxy:8080"
环境变量 PLAYWRIGHT_MCP_PROXY_SERVER | | --sandbox | 为所有通常不受沙箱保护的进程类型启用沙箱。
环境变量 PLAYWRIGHT_MCP_SANDBOX | | --save-session | 是否将 Playwright MCP 会话保存到输出目录。
环境变量 PLAYWRIGHT_MCP_SAVE_SESSION |

| --secrets | 指向包含 dotenv 格式密钥的文件的路径
env PLAYWRIGHT_MCP_SECRETS_FILE | | --shared-browser-context | 在所有已连接的 HTTP 客户端之间复用同一个浏览器上下文。
env PLAYWRIGHT_MCP_SHARED_BROWSER_CONTEXT | | --snapshot-boxes | 在快照中以 [box=x,y,width,height] 形式包含每个元素的边界框。坐标相对于视口,单位为 CSS 像素。
env PLAYWRIGHT_MCP_SNAPSHOT_BOXES | | --snapshot-mode | 在生成响应快照时,指定要使用的模式。可以是 "full" 或 "none"。默认为 "full"。
env PLAYWRIGHT_MCP_SNAPSHOT_MODE | | --storage-state | 用于隔离会话的存储状态文件路径。
env PLAYWRIGHT_MCP_STORAGE_STATE | | --test-id-attribute | 指定用于测试 id 的属性,默认为 "data-testid"
env PLAYWRIGHT_MCP_TEST_ID_ATTRIBUTE | | --timeout-action | 指定操作超时时间,以毫秒为单位,默认为 5000ms
env PLAYWRIGHT_MCP_TIMEOUT_ACTION | | --timeout-navigation | 指定导航超时时间,以毫秒为单位,默认为 60000ms
env PLAYWRIGHT_MCP_TIMEOUT_NAVIGATION | | --timeout-settle | 每次操作后等待触发的任务稳定下来的时长,以毫秒为单位,默认为 500ms
env PLAYWRIGHT_MCP_TIMEOUT_SETTLE | | --user-agent | 指定用户代理字符串
env PLAYWRIGHT_MCP_USER_AGENT | | --user-data-dir | 用户数据目录的路径。如果未指定,将创建一个临时目录。
env PLAYWRIGHT_MCP_USER_DATA_DIR | | --viewport-size | 指定浏览器视口大小,以像素为单位,例如 "1280x720"
env PLAYWRIGHT_MCP_VIEWPORT_SIZE |

用户配置文件

你可以像使用普通浏览器一样以持久化配置文件(默认)运行 Playwright MCP,也可以在隔离上下文中运行以进行测试会话,或者使用浏览器扩展连接到现有的浏览器。

持久化配置文件

所有登录信息都将存储在持久化配置文件中,如果你希望清除离线状态,可以在会话之间删除它。 持久化配置文件位于以下位置,你可以使用 --user-data-dir 参数覆盖它。

# Windows
%USERPROFILE%\AppData\Local\ms-playwright\mcp-{channel}-{workspace-hash}

# macOS
- ~/Library/Caches/ms-playwright/mcp-{channel}-{workspace-hash}

# Linux
- ~/.cache/ms-playwright/mcp-{channel}-{workspace-hash}

{workspace-hash} 派生自 MCP 客户端的工作区根目录,因此不同的项目会自动获得独立的 profile。

[!IMPORTANT] 一份持久化 profile 同时只能被一个浏览器实例使用,因此共享同一工作区的并发 MCP 客户端会发生冲突。要并行运行多个客户端,请为每个额外的客户端使用 --isolated 启动,或将其指向一个不同的 --user-data-dir。

隔离模式

在隔离模式下,每个会话都在隔离的 profile 中启动。每次你让 MCP 关闭浏览器时,该会话就会关闭,此会话的所有存储状态都会丢失。你可以通过配置的 contextOptions 或通过 --storage-state 参数为浏览器提供初始存储状态。在此处进一步了解存储状态 here。

{
  "mcpServers": {
    "playwright": {
      "command": "npx",
      "args": [
        "@playwright/mcp@latest",
        "--isolated",
        "--storage-state={path/to/storage.json}"
      ]
    }
  }
}

浏览器扩展

Playwright MCP Chrome 扩展允许你连接现有的浏览器标签页,并利用你已登录的会话和浏览器状态。安装与设置说明请参见 microsoft/playwright › packages/extension。

初始状态

有多种方式可以为浏览器上下文或页面提供初始状态。

对于存储状态,你可以:

  • 使用 --user-data-dir 参数从用户数据目录启动。这样会在各会话之间持久保存所有浏览器数据。
  • 使用 --storage-state 参数从存储状态文件启动。这样会把文件中的 cookies 和 localStorage 载入到隔离的浏览器上下文中。

对于页面状态,你可以:

  • 使用 --init-page 指向一个 TypeScript 文件,该文件会在 Playwright 页面对象上求值。这允许你运行任意代码来设置页面。
// init-page.ts
export default async ({ page }) => {
  await page.context().grantPermissions(['geolocation']);
  await page.context().setGeolocation({ latitude: 37.7749, longitude: -122.4194 });
  await page.setViewportSize({ width: 1280, height: 720 });
};
  • --init-script 指向一个 JavaScript 文件,该文件将作为初始化脚本添加。该脚本会在每个页面的任何脚本执行之前,在每个页面中被求值。 这对于覆盖浏览器 API 或设置环境非常有用。
// init-script.js
window.isPlaywrightMCP = true;

配置文件

Playwright MCP 服务器可以通过 JSON 配置文件进行配置。你可以使用 --config 命令行选项指定该配置文件:

npx @playwright/mcp@latest --config path/to/config.json
配置文件架构
{
  /**
   * The browser to use.
   */
  browser?: {
    /**
     * The type of browser to use.
     */
    browserName?: 'chromium' | 'firefox' | 'webkit';

    /**
     * Keep the browser profile in memory, do not save it to disk.
     */
    isolated?: boolean;

    /**
     * Path to a user data directory for browser profile persistence.
     * Temporary directory is created by default.
     */
    userDataDir?: string;

    /**
     * Launch options passed to
     * @see https://playwright.dev/docs/api/class-browsertype#browser-type-launch-persistent-context
     *
     * This is useful for settings options like `channel`, `headless`, `executablePath`, etc.
     */
    launchOptions?: playwright.LaunchOptions;

    /**
     * Context options for the browser context.
     *
     * This is useful for settings options like `viewport`.
     */
    contextOptions?: playwright.BrowserContextOptions;

    /**
     * Chrome DevTools Protocol endpoint to connect to an existing browser instance in case of Chromium family browsers.
     */
    cdpEndpoint?: string;

    /**
     * CDP headers to send with the connect request.
     */
    cdpHeaders?: Record<string, string>;

    /**
     * Timeout in milliseconds for connecting to CDP endpoint. Defaults to 30000 (30 seconds). Pass 0 to disable timeout.
     */
    cdpTimeout?: number;

    /**
     * Remote endpoint to connect to an existing Playwright server. May be a
     * WebSocket URL string, or a [ConnectOptions] object that mirrors the
     * `connectOptions` shape used by the test runner. When passed as an object,
     * `exposeNetwork`, `headers`, `slowMo`, and `timeout` are forwarded to the
     * underlying connect call.
     */
    remoteEndpoint?: string | playwright.ConnectOptions & { endpoint: string };

    /**
     * Paths to TypeScript files to add as initialization scripts for Playwright page.
     */
    initPage?: string[];

    /**
     * Paths to JavaScript files to add as initialization scripts.
     * The scripts will be evaluated in every page before any of the page's scripts.
     */
    initScript?: string[];
  },

  /**
   * Connect to a running browser instance (Edge/Chrome only). If specified, `browser`
   * config is ignored.
   * Requires the "Playwright Extension" to be installed.
   */
  extension?: boolean;

  server?: {
    /**
     * The port to listen on for SSE or MCP transport.
     */
    port?: number;

    /**
     * The host to bind the server to. Default is localhost. Use 0.0.0.0 to bind to all interfaces.
     */
    host?: string;

    /**
     * The hosts this server is allowed to serve from. Defaults to the host server is bound to.
     * This is not for CORS, but rather for the DNS rebinding protection.
     */
    allowedHosts?: string[];
  },

  /**
   * List of enabled tool capabilities. Possible values:
   *   - 'core': Core browser automation features.
   *   - 'pdf': PDF generation and manipulation.
   *   - 'vision': Coordinate-based interactions.
   *   - 'devtools': Developer tools features.
   */
  capabilities?: ToolCapability[];

  /**
   * Whether to save the Playwright session into the output directory.
   */
  saveSession?: boolean;

  /**
   * Whether to collect and expose the tools that a page registers through the
   * experimental WebMCP API. Enabled by default.
   */
  webmcp?: boolean;

  /**
   * Reuse the same browser context between all connected HTTP clients.
   */
  sharedBrowserContext?: boolean;

  /**
   * Secrets are used to replace matching plain text in the tool responses to prevent the LLM
   * from accidentally getting sensitive data. It is a convenience and not a security feature,
   * make sure to always examine information coming in and from the tool on the client.
   */
  secrets?: Record<string, string>;

  /**
   * The directory for automatically named output files, for example a screenshot taken without an
   * explicit file name. Files with an explicit name are resolved against the workspace root instead
   * and are not affected by this option.
   */
  outputDir?: string;

  /**
   * Threshold for evicting old output files, in bytes.
   */
  outputMaxSize?: number;

  console?: {
    /**
     * The level of console messages to return. Each level includes the messages of more severe levels. Defaults to "info".
     */
    level?: 'error' | 'warning' | 'info' | 'debug';
  },

  network?: {
    /**
     * List of origins to allow the browser to request. Default is to allow all. Origins matching both `allowedOrigins` and `blockedOrigins` will be blocked.
     *
     * Supported formats:
     * - Full origin: `https://example.com:8080` - matches only that origin
     * - Wildcard port: `http://localhost:*` - matches any port on localhost with http protocol
     */
    allowedOrigins?: string[];

    /**
     * List of origins to block the browser to request. Origins matching both `allowedOrigins` and `blockedOrigins` will be blocked.
     *
     * Supported formats:
     * - Full origin: `https://example.com:8080` - matches only that origin
     * - Wildcard port: `http://localhost:*` - matches any port on localhost with http protocol
     */
    blockedOrigins?: string[];
  };

  /**
   * Specify the attribute to use for test ids, defaults to "data-testid".
   */
  testIdAttribute?: string;

  timeouts?: {
    /*
     * Configures default action timeout: https://playwright.dev/docs/api/class-page#page-set-default-timeout. Defaults to 5000ms.
     */
    action?: number;

    /*
     * Configures default navigation timeout: https://playwright.dev/docs/api/class-page#page-set-default-navigation-timeout. Defaults to 60000ms.
     */
    navigation?: number;

    /**
     * Configures default expect timeout: https://playwright.dev/docs/test-timeouts#expect-timeout. Defaults to 5000ms.
     */
    expect?: number;

    /**
     * How long to wait after each action for triggered work (navigations, requests) to settle before responding. Defaults to 500ms.
     */
    settle?: number;

    /**
     * Close the browser after this many milliseconds without a tool call, and relaunch it on the next one.
     * Defaults to one hour for headless browsers Playwright launched, and to no timeout for headed or attached ones. Pass 0 to disable.
     * The CLI shuts the whole session down instead of relaunching.
     */
    idle?: number;
  };

  /**
   * Whether to send image responses to the client. Can be "allow", "omit", or "only". Defaults to "allow".
   * With "only", a response that carries an image consists of the image parts alone, without the text part.
   */
  imageResponses?: 'allow' | 'omit' | 'only';

  /**
   * How file paths are rendered in tool results. Can be "relative" to the workspace root or "absolute". Defaults to "relative".
   */
  filePaths?: 'relative' | 'absolute';

  snapshot?: {
    /**
     * When taking snapshots for responses, specifies the mode to use.
     */
    mode?: 'full' | 'none';

    /**
     * Whether to include each element's bounding box as [box=x,y,width,height] in snapshots.
     * Coordinates are viewport-relative, in CSS pixels (Element.getBoundingClientRect).
     */
    boxes?: boolean;
  };

  /**
   * allowUnrestrictedFileAccess acts as a guardrail to prevent the LLM from accidentally
   * wandering outside its intended workspace. It is a convenience defense to catch unintended
   * file access, not a secure boundary; a deliberate attempt to reach other directories can be
   * easily worked around, so always rely on client-level permissions for true security.
   */
  allowUnrestrictedFileAccess?: boolean;

  /**
   * Specify the language to use for code generation.
   */
  codegen?: 'typescript' | 'python' | 'java' | 'csharp' | 'none';
}

独立 MCP 服务器

在没有显示器的系统上,或从 IDE 的工作进程中以有界面模式运行浏览器时, 请在带有 DISPLAY 的环境中运行 MCP 服务器,并传入 --port 标志以启用 HTTP 传输。

npx @playwright/mcp@latest --port 8931

然后在 MCP 客户端配置中,把 url 设置为该 HTTP 端点:

{
  "mcpServers": {
    "playwright": {
      "url": "http://localhost:8931/mcp"
    }
  }
}

安全

Playwright MCP 不是安全边界。关于如何保护你的部署,请参阅 MCP 安全最佳实践。

Docker

注意: 目前 Docker 实现仅支持无界面 chromium。

{
  "mcpServers": {
    "playwright": {
      "command": "docker",
      "args": ["run", "-i", "--rm", "--init", "--pull=always", "mcr.microsoft.com/playwright/mcp"]
    }
  }
}

或者,如果你想以长时间运行的服务方式运行容器,而不是让 MCP 客户端启动它,请使用:

docker run -d -i --rm --init --pull=always \
  --entrypoint node \
  --name playwright \
  -p 8931:8931 \
  mcr.microsoft.com/playwright/mcp \
  /app/cli.js --headless --browser chromium --no-sandbox --port 8931 --host 0.0.0.0

服务器将监听主机端口 8931,任何 MCP 客户端都可以访问。

你可以自行构建 Docker 镜像。

docker build -t mcr.microsoft.com/playwright/mcp .
编程式用法
import http from 'http';

import { createConnection } from '@playwright/mcp';
import { SSEServerTransport } from '@modelcontextprotocol/sdk/server/sse.js';

http.createServer(async (req, res) => {
  // ...

  // Creates a headless Playwright MCP server with SSE transport
  const connection = await createConnection({ browser: { launchOptions: { headless: true } } });
  const transport = new SSEServerTransport('/messages', res);
  await connection.connect(transport);

  // ...
});

工具

核心自动化
  • browser_click
    • 标题:点击
    • 描述:在网页上执行点击
    • 参数:
      • element(字符串,可选):人类可读的元素描述,用于获取与该元素交互的权限
      • target(字符串):来自页面快照的精确目标元素引用,或唯一元素选择器
      • doubleClick(布尔值,可选):是否执行双击而非单击
      • button(字符串,可选):要点击的按钮,默认为左键
      • modifiers(数组,可选):要按下的修饰键
    • 只读:false
  • browser_close
    • 标题:关闭浏览器
    • 描述:关闭页面
    • 参数:无
    • 只读:false
  • browser_console_messages
    • 标题:获取控制台消息
    • 描述:返回所有控制台消息
    • 参数:
      • level(字符串):要返回的控制台消息级别。每个级别都包含更严重级别的消息。默认为 "info"。
      • all(布尔值,可选):返回自会话开始以来的所有控制台消息,而不仅仅是自上次导航以来的消息。默认为 false。
      • filename(字符串,可选):保存控制台消息的文件名。相对文件名相对于工作区根目录解析。如果未提供,消息将以文本形式返回。
    • 只读:true
  • browser_drag
    • 标题:拖动鼠标
    • 描述:在两个元素之间执行拖放
    • 参数:
      • startElement(字符串,可选):人类可读的源元素描述,用于获取与该元素交互的权限
      • startTarget(字符串):来自页面快照的精确目标元素引用,或唯一元素选择器
      • endElement(字符串,可选):人类可读的目标元素描述,用于获取与该元素交互的权限
      • endTarget(字符串):来自页面快照的精确目标元素引用,或唯一元素选择器
    • 只读:false
  • browser_drop
    • 标题:将文件或数据拖放到元素上
    • 描述:将文件或 MIME 类型的数据拖放到元素上,如同从页面外部拖入一样。必须至少提供 "paths" 或 "data" 之一。
    • 参数:
      • element(字符串,可选):人类可读的元素描述,用于获取与该元素交互的权限
      • target(字符串):来自页面快照的精确目标元素引用,或唯一元素选择器
      • paths(数组,可选):要拖放到元素上的文件的绝对路径。
      • data(对象,可选):要拖放的数据,为 MIME 类型到字符串值的映射(例如 {"text/plain": "hello", "text/uri-list": "https://example.com"})。
    • 只读:false
  • browser_emulate_media

    • 标题:模拟媒体特性
    • 描述:为页面模拟 CSS 媒体特性,例如在浅色和深色配色方案之间切换。省略的参数保持不变;null 会清除覆盖。
    • 参数:
  • colorScheme(可选):模拟 prefers-color-scheme 媒体特性

    • reducedMotion(可选):模拟 prefers-reduced-motion 媒体特性
    • forcedColors(可选):模拟 forced-colors 媒体特性
    • contrast(可选):模拟 prefers-contrast 媒体特性
    • media(可选):更改页面的 CSS 媒体类型
    • 只读:false
  • browser_evaluate
    • 标题:评估 JavaScript
    • 描述:在页面或元素上评估 JavaScript 表达式
    • 参数:
      • element(string,可选):用于获取与元素交互权限的人类可读元素描述
      • target(string,可选):页面快照中的确切目标元素引用,或唯一元素选择器
      • function(string):() => { /* code / },当提供 element 时为 (element) => { / code */ }
      • filename(string,可选):保存结果的文件名。相对文件名将相对于工作区根目录解析。如果未提供,结果将作为文本返回。
    • 只读:false
  • browser_file_upload
    • 标题:上传文件
    • 描述:上传一个或多个文件
    • 参数:
      • paths(array,可选):要上传的文件的绝对路径。可以是单个文件或多个文件。如果省略,文件选择器将被取消。
    • 只读:false
  • browser_fill_form
    • 标题:填写表单
    • 描述:填写多个表单字段
    • 参数:
      • fields(array):要填写的字段
    • 只读:false
  • browser_find
    • 标题:在页面快照中查找
    • 描述:在当前页面的可访问性快照中搜索文本或正则表达式。返回匹配的快照节点及其周围几行上下文(类似搜索片段),每个节点显示在其从树根开始的路径下,当你只需要定位一个元素及其 ref 时,这比捕获整个快照更经济。
    • 参数:
      • text(string,可选):在页面快照中搜索的纯文本(不区分大小写的子字符串匹配)。提供 text 或 regex 之一,不要同时提供两者。
      • regex(string,可选):在页面快照中搜索的正则表达式。默认区分大小写;用斜杠包裹模式以添加标志,例如 "/error/i" 表示不区分大小写。提供 text 或 regex 之一,不要同时提供两者。
      • filename(string,可选):将结果保存到文件,而不是在响应中返回。相对文件名将相对于工作区根目录解析。
    • 只读:true
  • browser_handle_dialog
    • 标题:处理对话框 -描述:处理对话框
    • 参数:
      • accept(boolean):是否接受对话框。
      • promptText(string,可选):提示对话框情况下的提示文本。
    • 只读:false
  • browser_hover

    • 标题:悬停鼠标
    • 描述:在页面元素上悬停
    • 参数:
      • element(string,可选):用于获取与元素交互权限的人类可读元素描述
  • target (string):页面快照中的精确目标元素引用,或唯一元素选择器

    • 只读:false
  • browser_navigate
    • 标题:导航到 URL
    • 描述:导航到 URL
    • 参数:
      • url (string):要导航到的 URL
    • 只读:false
  • browser_navigate_back
    • 标题:返回
    • 描述:返回历史记录中的上一页
    • 参数:无
    • 只读:false
  • browser_network_request
    • 标题:显示网络请求详情
    • 描述:返回单个网络请求的完整详情(请求头和请求体),如果设置了 part,则只返回其中一部分。请使用 browser_network_requests 中的编号。
    • 参数:
      • index (integer):请求的基于 1 的索引,由 browser_network_requests 打印。
      • part (string,可选):只返回请求的该部分。省略则返回完整详情。
      • filename (string,可选):将结果保存到的文件名。相对文件名会相对于工作区根目录解析。如果未提供,输出以文本形式返回。
    • 只读:true
  • browser_network_requests
    • 标题:列出网络请求
    • 描述:返回自页面加载以来的网络请求的编号列表。使用 browser_network_request 并带上编号以获取完整详情。
    • 参数:
      • static (boolean):是否包含成功的静态资源,如图片、字体、脚本等。默认为 false。
      • filter (string,可选):只返回 URL 匹配此正则表达式的请求(例如 "/api/.*user")。
      • filename (string,可选):将网络请求保存到的文件名。相对文件名会相对于工作区根目录解析。如果未提供,请求以文本形式返回。
    • 只读:true
  • browser_press_key
    • 标题:按键
    • 描述:在键盘上按下一个键
    • 参数:
      • key (string):要按下的键的名称,或要生成的字符,例如 ArrowLeft 或 a
    • 只读:false
  • browser_resize
    • 标题:调整浏览器窗口大小
    • 描述:调整浏览器窗口大小
    • 参数:
      • width (number):浏览器窗口宽度
      • height (number):浏览器窗口高度
    • 只读:false
  • browser_run_code_unsafe
    • 标题:运行 Playwright 代码(不安全)
    • 描述:运行 Playwright 代码片段。不安全:在 Playwright 服务器进程中执行任意 JavaScript,等同于 RCE。
    • 参数:
      • code (string,可选):包含要执行的 Playwright 代码的 JavaScript 函数。它将以单个参数 page 调用,你可以用它进行任何页面交互。例如:async (page) => { await page.getByRole('button', { name: 'Submit' }).click(); return await page.title(); }
      • filename (string,可选):从指定文件加载代码。相对文件名会相对于工作区根目录解析。如果同时提供了 code 和 filename,则 code 将被忽略。
    • 只读:false
  • browser_select_option
    • 标题:选择选项
    • 描述:在下拉框中选择一个选项
    • 参数:
      • element(string,可选):人类可读的元素描述,用于获取与该元素交互的权限
      • target(string):页面快照中的确切目标元素引用,或一个唯一的元素选择器
      • values(array):要在下拉框中选择的值数组。可以是单个值或多个值。
    • 只读:false
  • browser_snapshot
    • 标题:页面快照
    • 描述:捕获当前页面的可访问性快照,这比截图更好
    • 参数:
      • target(string,可选):页面快照中的确切目标元素引用,或一个唯一的元素选择器
      • filename(string,可选):将快照保存到文件,而不是在响应中返回。相对文件名会相对于工作区根目录解析。
      • depth(number,可选):限制快照树的深度
      • boxes(boolean,可选):在快照中以 [box=x,y,width,height] 形式包含每个元素的边界框。坐标相对于视口,以 CSS 像素为单位(Element.getBoundingClientRect)
    • 只读:true
  • browser_take_screenshot
    • 标题:拍摄屏幕截图
    • 描述:拍摄当前页面的屏幕截图。你不能基于截图执行操作,请使用 browser_snapshot 来执行操作。
    • 参数:
      • element(string,可选):人类可读的元素描述,用于获取与该元素交互的权限
      • target(string,可选):页面快照中的确切目标元素引用,或一个唯一的元素选择器
      • type(string,可选):屏幕截图的图像格式。如果未设置,则从文件扩展名推断,否则为 png。
      • filename(string,可选):保存屏幕截图的文件名。相对文件名会相对于工作区根目录解析。如果未指定,屏幕截图将保存到输出目录中,命名为 page-{timestamp}.{png|jpeg|webp}。
      • fullPage(boolean,可选):为 true 时,拍摄整个可滚动页面的屏幕截图,而不是当前可见视口。不能与元素屏幕截图一起使用。
      • scale(string):图像分辨率缩放。"css" 生成以 CSS 像素为单位的屏幕截图(更小,跨设备一致)。"device" 生成使用设备像素的高分辨率屏幕截图(更大,考虑设备像素比)。默认为 css。
    • 只读:true
  • browser_type
    • 标题:输入文本
    • 描述:将文本输入到可编辑元素中
    • 参数:
      • element(string,可选):人类可读的元素描述,用于获取与该元素交互的权限
      • target(string):页面快照中的确切目标元素引用,或一个唯一的元素选择器
      • text(string):要输入到元素中的文本
      • submit(boolean,可选):是否提交输入的文本(之后按 Enter)
      • slowly(boolean,可选):是否一次输入一个字符。用于触发页面中的按键处理器很有用。默认情况下,整个文本会一次填充完成。
    • 只读:false
  • browser_wait_for
    • 标题:Wait for
    • 描述:等待文本出现或消失,或等待指定时间过去
    • 参数:
      • time(number,可选):等待的秒数,最多 30
      • text(string,可选):要等待出现的文本
      • textGone(string,可选):要等待消失的文本
    • 只读:false
标签页管理
  • browser_tabs
    • 标题:Manage tabs
    • 描述:列出、创建、关闭或选择浏览器标签页。
    • 参数:
      • action(string):要执行的操作
      • index(number,可选):标签页索引,用于 close/select。若 close 时省略,则关闭当前标签页。
      • url(string,可选):在新标签页中导航到的 URL,用于 new。
    • 只读:false
浏览器安装
配置(通过 --caps=config 主动开启)
  • browser_get_config
    • 标题:Get config
    • 描述:在合并 CLI 选项、环境变量和配置文件后,获取最终解析出的配置。
    • 参数:无
    • 只读:true
网络(通过 --caps=network 主动开启)
  • browser_network_state_set
    • 标题:Set network state
    • 描述:将浏览器网络状态设为在线或离线。离线时,所有网络请求都会失败。
    • 参数:
      • state(string):设为 "offline" 以模拟离线模式,设为 "online" 以恢复网络连接
    • 只读:false
  • browser_route
    • 标题:Mock network requests
    • 描述:设置路由,以模拟匹配某个 URL 模式的网络请求
    • 参数:
      • pattern(string):要匹配的 URL 模式(例如 "/api/users"、"/*.{png,jpg}")
      • status(number,可选):要返回的 HTTP 状态码(默认:200)
      • body(string,可选):响应体(文本或 JSON 字符串)
      • contentType(string,可选):Content-Type 头(例如 "application/json"、"text/html")
      • headers(array,可选):以 "Name: Value" 格式添加的请求头
      • removeHeaders(string,可选):要从请求中移除的请求头名称的逗号分隔列表
    • 只读:false
  • browser_route_list
    • 标题:List network routes
    • 描述:列出所有活动中的网络路由
    • 参数:无
    • 只读:true
  • browser_unroute
    • 标题:Remove network routes
    • 描述:移除匹配某个模式的网络路由(若未指定模式,则移除所有路由)
    • 参数:
      • pattern(string,可选):要取消路由的 URL 模式(省略则移除所有路由)
    • 只读:false
存储(通过 --caps=storage 主动开启)
  • browser_cookie_clear
    • 标题:清除 cookies
    • 描述:清除所有 cookies
    • 参数:无
    • 只读:false
  • browser_cookie_delete
    • 标题: 删除 cookie
    • 描述: 删除指定的 cookie
    • 参数:
      • name (string): 要删除的 cookie 名称
    • 只读: false
  • browser_cookie_get
    • 标题: 获取 cookie
    • 描述: 按名称获取指定的 cookie
    • 参数:
      • name (string): 要获取的 cookie 名称
    • 只读: true
  • browser_cookie_list
    • 标题: 列出 cookie
    • 描述: 列出所有 cookie(可选按 domain/path 过滤)
    • 参数:
      • domain (string, optional): 按 domain 过滤 cookie
      • path (string, optional): 按 path 过滤 cookie
    • 只读: true
  • browser_cookie_set
    • 标题: 设置 cookie
    • 描述: 设置带可选标志(domain、path、expires、httpOnly、secure、sameSite)的 cookie
    • 参数:
      • name (string): cookie 名称
      • value (string): cookie 值
      • domain (string, optional): cookie domain
      • path (string, optional): cookie path
      • expires (number, optional): cookie 过期时间,Unix 时间戳
      • httpOnly (boolean, optional): cookie 是否为 HTTP only
      • secure (boolean, optional): cookie 是否 secure
      • sameSite (string, optional): cookie SameSite 属性
    • 只读: false
  • browser_localstorage_clear
    • 标题: 清空 localStorage
    • 描述: 清空所有 localStorage
    • 参数:无
    • 只读: false
  • browser_localstorage_delete
    • 标题: 删除 localStorage 项
    • 描述: 删除一个 localStorage 项
    • 参数:
      • key (string): 要删除的键
    • 只读: false
  • browser_localstorage_get
    • 标题: 获取 localStorage 项
    • 描述: 按键获取一个 localStorage 项
    • 参数:
      • key (string): 要获取的键
    • 只读: true
  • browser_localstorage_list
    • 标题: 列出 localStorage
    • 描述: 列出所有 localStorage 键值对
    • 参数:无
    • 只读: true
  • browser_localstorage_set
    • 标题: 设置 localStorage 项
    • 描述: 设置一个 localStorage 项
    • 参数:
      • key (string): 要设置的键
      • value (string): 要设置的值
    • 只读: false
  • browser_sessionstorage_clear
    • 标题: 清空 sessionStorage
    • 描述: 清空所有 sessionStorage
    • 参数:无
    • 只读: false
  • browser_sessionstorage_delete
    • 标题: 删除 sessionStorage 项
    • 描述: 删除一个 sessionStorage 项
    • 参数:
      • key (string): 要删除的键
    • 只读: false
  • browser_sessionstorage_get
    • 标题: 获取 sessionStorage 项
    • 描述: 按键获取一个 sessionStorage 项
    • 参数:
      • key (string): 要获取的键
    • 只读: true
  • browser_sessionstorage_list

  • 标题:列出 sessionStorage

    • 描述:列出所有 sessionStorage 键值对
    • 参数:无
    • 只读:true
  • browser_sessionstorage_set
    • 标题:设置 sessionStorage 项
    • 描述:设置一个 sessionStorage 项
    • 参数:
      • key (string): 要设置的键
      • value (string): 要设置的值
    • 只读:false
  • browser_set_storage_state
    • 标题:恢复存储状态
    • 描述:从文件恢复存储状态(cookies、本地存储)。在恢复之前,这会清除现有的 cookies 和本地存储。
    • 参数:
      • filename (string): 要从中恢复的存储状态文件的路径。相对文件名将相对于工作区根目录进行解析。
    • 只读:false
  • browser_storage_state
    • 标题:保存存储状态
    • 描述:将存储状态(cookies、本地存储)保存到文件以便后续重用
    • 参数:
      • filename (string, optional): 保存存储状态的文件名。相对文件名将相对于工作区根目录进行解析。如果未指定,存储状态将作为 storage-state-{timestamp}.json 保存到输出目录中。
    • 只读:true
DevTools(通过 --caps=devtools 选择加入)
  • browser_annotate
    • 标题:注释当前页面
    • 描述:以注释模式打开当前页面的 Playwright Dashboard,并等待用户绘制注释。返回带注释的截图、ARIA 快照以及注释列表。
    • 参数:无
    • 只读:true
  • browser_hide_highlight
    • 标题:隐藏元素高亮
    • 描述:移除之前为元素添加的高亮叠加层。
    • 参数:
      • element (string, optional): 添加高亮时使用的可读元素描述;必须与传递给 browser_highlight 的值匹配。
      • target (string, optional): 来自页面快照的确切目标元素引用,或唯一的元素选择器
    • 只读:true
  • browser_highlight
    • 标题:高亮元素
    • 描述:在页面上的元素周围显示持久的高亮叠加层。
    • 参数:
      • element (string, optional): 用于获取与该元素交互权限的可读元素描述
      • target (string): 来自页面快照的确切目标元素引用,或唯一的元素选择器
      • style (string, optional): 应用于高亮叠加层的额外内联 CSS,例如 "outline: 2px dashed red"。
    • 只读:true
  • browser_resume
    • 标题:恢复暂停的脚本执行
    • 描述:在脚本暂停后恢复执行。当调用时将 step 设置为 true 时,将在下一个操作之前再次暂停执行。
    • 参数:
      • step (boolean, optional): 当为 true 时,将在下一个操作之前再次暂停执行,从而允许逐步调试。
      • location (string, optional): 在特定的 : 处暂停执行,例如 "example.spec.ts:42"。
    • 只读:false
  • browser_start_recording
    • 标题:开始录制用户操作
    • 描述:开始将用户在浏览器中执行的操作录制为 Playwright 代码。当用户希望手动演示某个流程时使用。当用户表示已完成时,调用 browser_stop_recording 以获取录制的操作。
    • 参数:无
    • 只读:true
  • browser_start_tracing
    • 标题:开始跟踪
    • 描述:开始跟踪录制
    • 参数:无
    • 只读:true
  • browser_start_video
    • 标题:开始视频
    • 描述:开始视频录制
    • 参数:
      • filename(string,可选):保存视频的文件名。相对文件名将相对于工作区根目录解析。如果未指定,视频将以 video-{timestamp}.webm 保存到输出目录中。
      • size(object,可选):视频尺寸
      • fps(number,可选):视频帧率,单位为帧每秒,默认为 25
      • cursor(boolean,可选):渲染一个动画鼠标光标,移动到每个操作点。将操作节奏放慢 800ms,以便光标有时间移动。
    • 只读:true
  • browser_stop_recording
    • 标题:停止录制用户操作
    • 描述:停止由 browser_start_recording 启动的录制,并将录制的操作作为 Playwright 代码返回。
    • 参数:无
    • 只读:true
  • browser_stop_tracing
    • 标题:停止跟踪
    • 描述:停止跟踪录制
    • 参数:无
    • 只读:true
  • browser_stop_video
    • 标题:停止视频
    • 描述:停止视频录制
    • 参数:无
    • 只读:true
  • browser_video_chapter
    • 标题:视频章节
    • 描述:向视频录制添加章节标记。显示带有模糊背景的全屏章节卡片。
    • 参数:
      • title(string):章节标题
      • description(string,可选):章节描述
      • duration(number,可选):显示章节卡片的时长,单位为毫秒
    • 只读:true
  • browser_video_hide_actions
    • 标题:隐藏操作叠加层
    • 描述:停止对页面上执行的操作进行标注。
    • 参数:无
    • 只读:true
  • browser_video_show_actions

    • 标题:显示操作叠加层
    • 描述:用标注对页面上后续执行的操作进行注释,标注会指明操作名称,并且在有样式时标记操作点并高亮目标元素。在视频录制或屏幕录制时很有用。
    • 参数:
      • duration(number,可选):每个操作标注在屏幕上停留的时长,单位为毫秒。默认为 500。
      • position(string,可选):操作标题相对于页面的放置位置。默认为右上角。
  • cursor(字符串,可选):指针操作的游标装饰。“pointer”(默认值)会从上一个动作点动画显示鼠标指针到下一个点;“none”禁用游标装饰。

    • style(对象,可选):操作装饰的样式。
    • 只读:true
基于坐标(通过 --caps=vision 选择加入)
  • browser_mouse_click_xy
    • 标题:点击
    • 描述:在给定位置点击鼠标按钮
    • 参数:
      • x(数字):X 坐标
      • y(数字):Y 坐标
      • button(字符串,可选):要点击的按钮,默认为左键
      • clickCount(数字,可选):点击次数,默认为 1
      • delay(数字,可选):鼠标按下和鼠标松开之间等待的时间(毫秒),默认为 0
    • 只读:false
  • browser_mouse_down
    • 标题:按下鼠标
    • 描述:按下鼠标
    • 参数:
      • button(字符串,可选):要按下的按钮,默认为左键
    • 只读:false
  • browser_mouse_drag_xy
    • 标题:拖动鼠标
    • 描述:将鼠标左键拖动到给定位置
    • 参数:
      • startX(数字):起始 X 坐标
      • startY(数字):起始 Y 坐标
      • endX(数字):结束 X 坐标
      • endY(数字):结束 Y 坐标
    • 只读:false
  • browser_mouse_move_xy
    • 标题:移动鼠标
    • 描述:将鼠标移动到给定位置
    • 参数:
      • x(数字):X 坐标
      • y(数字):Y 坐标
    • 只读:false
  • browser_mouse_up
    • 标题:释放鼠标
    • 描述:释放鼠标
    • 参数:
      • button(字符串,可选):要释放的按钮,默认为左键
    • 只读:false
  • browser_mouse_wheel
    • 标题:滚动鼠标滚轮
    • 描述:滚动鼠标滚轮
    • 参数:
      • deltaX(数字):X 轴增量
      • deltaY(数字):Y 轴增量
    • 只读:false
PDF 生成(通过 --caps=pdf 选择加入)
  • browser_pdf_save
    • 标题:另存为 PDF
    • 描述:将页面保存为 PDF
    • 参数:
      • filename(字符串,可选):保存 PDF 的文件名。相对文件名将根据工作区根目录解析。如果未指定,PDF 将保存到输出目录中,文件名为 page-{timestamp}.pdf。
    • 只读:true
测试断言(通过 --caps=testing 选择加入)
  • browser_generate_locator
    • 标题:为元素创建定位器
    • 描述:为给定元素生成定位器以用于测试
    • 参数:
      • element(字符串,可选):用于获取与元素交互权限的人类可读元素描述
      • target(字符串):来自页面快照的确切目标元素引用,或唯一的元素选择器
    • 只读:true
  • browser_verify_element_visible

  • 标题: 验证元素可见

    • 描述: 验证元素在页面上可见
    • 参数:
      • role (string): 元素的 ROLE。可在快照中这样找到:- {ROLE} "Accessible Name":
      • accessibleName (string): 元素的 ACCESSIBLE_NAME。可在快照中这样找到:- role "{ACCESSIBLE_NAME}"
    • 只读: false
  • browser_verify_list_visible
    • 标题: 验证列表可见
    • 描述: 验证列表在页面上可见
    • 参数:
      • element (string): 人类可读的列表描述
      • target (string): 指向该列表的精确目标元素引用
      • items (array): 要验证的项
    • 只读: false
  • browser_verify_text_visible
    • 标题: 验证文本可见
    • 描述: 验证文本在页面上可见。如有可能,优先使用 browser_verify_element_visible。
    • 参数:
      • text (string): 要验证的 TEXT。可在快照中这样找到:- role "Accessible Name": {TEXT} 或这样:- text: {TEXT}
    • 只读: false
  • browser_verify_value
    • 标题: 验证值
    • 描述: 验证元素的值
    • 参数:
      • type (string): 元素类型
      • element (string): 人类可读的元素描述
      • target (string): 来自页面快照的精确目标元素引用
      • value (string): 要验证的值。对于复选框,使用 "true" 或 "false"。
    • 只读: false

来源与许可证

Source · License · f183dad4a52965583e3cc1d59b88cdc279e2e57d

                             Apache License
                       Version 2.0, January 2004
                    http://www.apache.org/licenses/

TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION

  1. Definitions.

    "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.

    "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.

    "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.

    "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.

    "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.

    "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.

    "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).

    "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.

    "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."

    "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.

  2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.

  3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.

  4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:

    (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.

  5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.

  6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.

  7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.

  8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.

  9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.

END OF TERMS AND CONDITIONS

APPENDIX: How to apply the Apache License to your work.

  To apply the Apache License to your work, attach the following
  boilerplate notice, with the fields enclosed by brackets "[]"
  replaced with your own identifying information. (Don't include
  the brackets!)  The text should be enclosed in the appropriate
  comment syntax for the file format. We also recommend that a
  file or class name and description of purpose be included on the
  same "printed page" as the copyright notice for easier
  identification within third-party archives.

Copyright (c) Microsoft Corporation.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

   http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

🙏

Source et remerciements

GitHub: https://github.com/microsoft/playwright-mcp Owner avatar: https://avatars.githubusercontent.com/u/6154722?v=4 License (SPDX): Apache-2.0 Stars (verified via api.github.com/repos/microsoft/playwright-mcp): 32,355


Playwright MCP——基于 Playwright 的浏览器 MCP

Playwright MCP 是基于 Playwright 的 MCP Server:通过可访问性树而非截图驱动浏览器自动化,适合可重复的网页操作与自愈脚本。用 npx 添加到 Claude Code/Codex 配置后即可调用工具。

Fil de discussion

Connectez-vous pour rejoindre la discussion.
Aucun commentaire pour l'instant. Soyez le premier à partager votre avis.

Actifs similaires