# https://github.com/microsoft/playwright-mcp 项目说明书

生成时间：2026-05-15 08:14:48 UTC

## 目录

- [Introduction to Playwright MCP](#introduction)
- [Key Concepts](#key-concepts)
- [Installation Guide](#installation-guide)
- [MCP Client Integration](#client-integration)
- [Browser Configuration](#browser-configuration)
- [Security Settings](#security-settings)
- [Docker Deployment](#docker-deployment)
- [Programmatic Usage](#programmatic-usage)
- [User Profiles and Session Management](#user-profiles)
- [Troubleshooting](#troubleshooting)

<a id='introduction'></a>

## Introduction to Playwright MCP

### 相关页面

相关主题：[Key Concepts](#key-concepts), [Installation Guide](#installation-guide)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [README.md](https://github.com/microsoft/playwright-mcp/blob/main/README.md)
- [package.json](https://github.com/microsoft/playwright-mcp/blob/main/package.json)
- [config.d.ts](https://github.com/microsoft/playwright-mcp/blob/main/config.d.ts)
- [server.json](https://github.com/microsoft/playwright-mcp/blob/main/server.json)
- [cli.js](https://github.com/microsoft/playwright-mcp/blob/main/cli.js)
- [index.js](https://github.com/microsoft/playwright-mcp/blob/main/index.js)
- [CONTRIBUTING.md](https://github.com/microsoft/playwright-mcp/blob/main/CONTRIBUTING.md)
</details>

# Introduction to Playwright MCP

Playwright MCP (Model Context Protocol) is a server implementation that exposes [Playwright](https://playwright.dev) browser automation capabilities through the MCP protocol. It enables AI models and tools to interact with web browsers using a standardized interface.

## Overview

Playwright MCP acts as a bridge between AI systems and web browsers, providing a comprehensive set of tools for:

- Browser automation and scraping
- UI testing and verification
- Network request monitoring
- PDF generation
- Vision-based interactions
- Storage state management

**Package Information**

| Property | Value |
|----------|-------|
| Package Name | `@playwright/mcp` |
| MCP Server Name | `io.github.microsoft/playwright-mcp` |
| Current Version | `0.0.75` |
| License | Apache-2.0 |
| Node Requirement | `>=18` |
| Transport Protocol | stdio |

资料来源：[package.json:3-15](https://github.com/microsoft/playwright-mcp/blob/main/package.json), [server.json:1-15](https://github.com/microsoft/playwright-mcp/blob/main/server.json)

## Architecture

The Playwright MCP implementation follows a layered architecture where the MCP server delegates browser operations to Playwright's core automation engine.

```mermaid
graph TD
    A[AI Client / MCP Host] -->|MCP Protocol| B[Playwright MCP Server]
    B -->|STDIO Transport| C[playwright-core]
    C -->|Browser Automation| D[Chromium / Firefox / WebKit]
    C -->|PDF Generation| E[PDF Renderer]
    C -->|Vision API| F[Image Processing]
```

资料来源：[index.js:1-25](https://github.com/microsoft/playwright-mcp/blob/main/index.js), [cli.js:1-35](https://github.com/microsoft/playwright-mcp/blob/main/cli.js)

### Source Code Location

> [!IMPORTANT]
> The core implementation has been migrated to the [Playwright monorepo](https://github.com/microsoft/playwright). The source code is now located at:
>
> `packages/playwright/src/mcp`

This repository (`microsoft/playwright-mcp`) serves as the npm distribution package and coordination point.

资料来源：[src/README.md:1-5](https://github.com/microsoft/playwright-mcp/blob/main/src/README.md)

## Tool Capabilities

Playwright MCP organizes its functionality into capability groups. Each capability can be individually enabled or disabled through configuration.

| Capability | Description |
|------------|-------------|
| `config` | Server configuration and initialization |
| `core` | Core browser operations |
| `core-navigation` | Page navigation and URL handling |
| `core-tabs` | Tab/window management |
| `core-input` | Form input and user interactions |
| `core-install` | Browser installation |
| `network` | Network request/response monitoring |
| `pdf` | PDF document generation |
| `storage` | Session state persistence |
| `testing` | Test assertion utilities |
| `vision` | Screenshot and visual verification |
| `devtools` | Developer tools integration |

资料来源：[config.d.ts:25-40](https://github.com/microsoft/playwright-mcp/blob/main/config.d.ts)

## Configuration Options

The server behavior can be customized through the `Config` type defined in `config.d.ts`.

### Browser Configuration

```typescript
browser?: {
  browserName?: 'chromium' | 'firefox' | 'webkit';
  isolated?: boolean;
  userDataDir?: string;
  launchOptions?: object;
}
```

| Option | Type | Description |
|--------|------|-------------|
| `browserName` | string | Browser type: chromium, firefox, or webkit |
| `isolated` | boolean | Keep browser profile in memory only |
| `userDataDir` | string | Path for browser profile persistence |

资料来源：[config.d.ts:48-75](https://github.com/microsoft/playwright-mcp/blob/main/config.d.ts)

### Network Configuration

```typescript
network?: {
  allowedOrigins?: string[];
  blockedOrigins?: string[];
}
```

Supported origin formats:
- Full origin: `https://example.com:8080`
- Wildcard port: `http://localhost:*`

资料来源：[config.d.ts:100-115](https://github.com/microsoft/playwright-mcp/blob/main/config.d.ts)

### Console Configuration

```typescript
console?: {
  level?: 'error' | 'warning' | 'info' | 'debug';
}
```

资料来源：[config.d.ts:95-98](https://github.com/microsoft/playwright-mcp/blob/main/config.d.ts)

## CLI Usage

The Playwright MCP CLI is available via `cli.js` and supports several commands:

```bash
# Run with default settings
node cli.js

# Install browser binaries
node cli.js install-browser

# Show version
node cli.js --version

# Show help
node cli.js --help
```

The CLI is built on top of `playwright-core` and leverages its command-line utilities.

资料来源：[cli.js:1-35](https://github.com/microsoft/playwright-mcp/blob/main/cli.js)

## Entry Point

The main entry point exports the `createConnection` function which establishes the MCP connection:

```javascript
const { tools } = require('playwright-core/lib/coreBundle');
module.exports = { createConnection: tools.createConnection };
```

资料来源：[index.js:1-25](https://github.com/microsoft/playwright-mcp/blob/main/index.js)

## Package Scripts

| Script | Purpose |
|--------|---------|
| `npm test` | Run all Playwright tests |
| `npm run ctest` | Run tests in Chrome only |
| `npm run ftest` | Run tests in Firefox only |
| `npm run wtest` | Run tests in WebKit only |
| `npm run lint` | Generate/update README |
| `npm run roll` | Update Playwright version |
| `npm run docker-build` | Build Docker image |
| `npm run docker-run` | Run Docker container |

资料来源：[package.json:18-35](https://github.com/microsoft/playwright-mcp/blob/main/package.json)

## Testing

Tests are located in the `tests` directory and organized under `tests/mcp`. To run the test suite:

```bash
# Fast path - Chrome only
npm run ctest

# Full path - All browsers
npm run mcp-test
```

Test execution uses Playwright itself, applying the same testing patterns documented in the official [Playwright testing guide](https://playwright.dev/docs/running-tests#running-tests).

资料来源：[CONTRIBUTING.md:45-60](https://github.com/microsoft/playwright-mcp/blob/main/CONTRIBUTING.md), [playwright.config.ts:1-30](https://github.com/microsoft/playwright-mcp/blob/main/playwright.config.ts)

## Development Workflow

```mermaid
graph LR
    A[Fork Repository] --> B[Clone playwright monorepo]
    B --> C[npm ci && npm run watch]
    C --> D[npx playwright install]
    D --> E[Make Changes]
    E --> F[npm run flint]
    F --> G[Add Tests]
    G --> H[Open PR]
```

1. **Clone**: `git clone https://github.com/microsoft/playwright`
2. **Install**: `npm ci && npx playwright install`
3. **Develop**: Make changes in `packages/playwright/src/mcp`
4. **Lint**: `npm run flint`
5. **Test**: `npm run mcp-ctest` (fast) or `npm run mcp-test` (full)
6. **Commit**: Follow [Semantic Commit Messages](https://www.conventionalcommits.org/en/v1.0.0/) format
7. **PR**: Submit pull request for review

资料来源：[CONTRIBUTING.md:10-55](https://github.com/microsoft/playwright-mcp/blob/main/CONTRIBUTING.md)

## Commit Convention

Commits must follow semantic format:

```
<label>(<scope>): <description>

[optional body]

[optional footer with fixes/references]
```

**Labels:**
- `fix` - Bug fixes
- `feat` - New features
- `docs` - Documentation changes
- `test` - Test-only changes
- `devops` - CI/build changes
- `chore` - Maintenance tasks

Branch naming for fixes: `fix-<issue-number>`

资料来源：[CONTRIBUTING.md:55-90](https://github.com/microsoft/playwright-mcp/blob/main/CONTRIBUTING.md)

## Version Management

The `roll.js` script handles Playwright version updates across the project:

```javascript
// Key functions in roll.js
updatePlaywrightVersion(version)  // Update package.json
copyConfig()                      // Sync config.d.ts from monorepo
```

To roll to a new Playwright version:
1. Run `npm run roll`
2. Create branch: `git checkout -b roll-pw-<suffix>`
3. Run tests: `npm test`
4. Commit and open PR

资料来源：[roll.js:1-50](https://github.com/microsoft/playwright-mcp/blob/main/roll.js)

## Summary

Playwright MCP provides a production-ready integration layer that brings Playwright's powerful browser automation capabilities to AI systems via the Model Context Protocol. With support for multiple browsers, comprehensive tool coverage, and enterprise-grade features like isolated browser contexts and network filtering, it serves as a robust foundation for AI-driven web interactions.

The project's move to the main Playwright monorepo ensures tight integration with Playwright's development cycle and guarantees that the MCP tools remain synchronized with the latest browser automation features.

---

<a id='key-concepts'></a>

## Key Concepts

### 相关页面

相关主题：[Introduction to Playwright MCP](#introduction), [Browser Configuration](#browser-configuration)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [CLAUDE.md](https://github.com/microsoft/playwright-mcp/blob/main/CLAUDE.md)
- [CONTRIBUTING.md](https://github.com/microsoft/playwright-mcp/blob/main/CONTRIBUTING.md)
- [config.d.ts](https://github.com/microsoft/playwright-mcp/blob/main/config.d.ts)
- [package.json](https://github.com/microsoft/playwright-mcp/blob/main/package.json)
- [cli.js](https://github.com/microsoft/playwright-mcp/blob/main/cli.js)
- [playwright.config.ts](https://github.com/microsoft/playwright-mcp/blob/main/playwright.config.ts)
- [roll.js](https://github.com/microsoft/playwright-mcp/blob/main/roll.js)
- [update-readme.js](https://github.com/microsoft/playwright-mcp/blob/main/update-readme.js)
</details>

# Key Concepts

Playwright MCP (Model Context Protocol) is a server implementation that exposes Playwright browser automation capabilities through the MCP protocol. It enables AI assistants and other MCP clients to interact with web pages through a standardized tool interface, supporting automation, testing, and web scraping workflows.

## Architecture Overview

The Playwright MCP server acts as a bridge between MCP clients and Playwright's browser automation engine. The core implementation resides in the [Playwright monorepo](https://github.com/microsoft/playwright) at `packages/playwright/src/mcp`, while this repository serves as the distribution package and configuration layer.

```mermaid
graph TD
    A[MCP Client<br>e.g., AI Assistant] --> B[Playwright MCP Server]
    B --> C[Playwright Core]
    C --> D[Chromium]
    C --> E[Firefox]
    C --> F[WebKit]
    
    B --> G[Browser Context]
    G --> H[Pages/Tabs]
    H --> I[DOM Elements]
    
    J[Config Options] --> B
    K[Tool Capabilities] --> B
```

资料来源：[CONTRIBUTING.md:40-44](https://github.com/microsoft/playwright-mcp/blob/main/CONTRIBUTING.md)

## Tool Capabilities System

The MCP server organizes its functionality into discrete capabilities that can be enabled or disabled based on use case requirements.

### Capability Types

| Capability | Description | Default |
|------------|-------------|---------|
| `config` | Server configuration management | Enabled |
| `core` | Core browser automation (navigation, clicks, input) | Enabled |
| `core-navigation` | Advanced navigation control | Enabled |
| `core-tabs` | Multiple tab/window management | Enabled |
| `core-input` | Form input handling | Enabled |
| `core-install` | Browser installation | Enabled |
| `network` | Network request interception | Opt-in |
| `pdf` | PDF generation | Opt-in |
| `storage` | Session storage management | Opt-in |
| `testing` | Test assertions | Opt-in |
| `vision` | Screenshot and visual comparisons | Opt-in |
| `devtools` | Developer tools integration | Opt-in |

资料来源：[config.d.ts:45-56](https://github.com/microsoft/playwright-mcp/blob/main/config.d.ts)

### Opt-in Capabilities

Capabilities not listed in the `core` group require explicit enablement via the `--caps` configuration option. For example:

```bash
--caps=network,storage,testing
```

Opt-in capabilities are documented with the following pattern in user-facing documentation:

```
Capability Title (opt-in via --caps=capability-name)
```

资料来源：[update-readme.js:120-123](https://github.com/microsoft/playwright-mcp/blob/main/update-readme.js)

## Browser Configuration

### Browser Types

| Option | Description |
|--------|-------------|
| `chromium` | Chromium-based browser (default) |
| `firefox` | Mozilla Firefox |
| `webkit` | WebKit/Safari engine |

### Browser Isolation

```typescript
browser?: {
  browserName?: 'chromium' | 'firefox' | 'webkit';
  isolated?: boolean;      // Keep profile in memory only
  userDataDir?: string;    // Custom profile persistence path
};
```

- **isolated (default: true)**: Browser profile is kept in memory, not saved to disk
- **userDataDir**: Path for browser profile persistence across sessions

资料来源：[config.d.ts:8-17](https://github.com/microsoft/playwright-mcp/blob/main/config.d.ts)

## Network Security

### Origin-Based Filtering

| Configuration | Purpose |
|--------------|---------|
| `allowedOrigins` | Whitelist of permitted origins |
| `blockedOrigins` | Blacklist of denied origins |

When an origin matches both lists, it will be **blocked**.

**Supported formats:**
- Full origin: `https://example.com:8080` - matches exact origin
- Wildcard port: `http://localhost:*` - matches any port with specified protocol

资料来源：[config.d.ts:20-35](https://github.com/microsoft/playwright-mcp/blob/main/config.d.ts)

## Timeouts

| Timeout | Default | Description |
|---------|---------|-------------|
| `action` | 5000ms | Default action timeout |
| `navigation` | 60000ms | Default navigation timeout |
| `expect` | 5000ms | Default assertion/expect timeout |

Configuration location: `timeouts` in the Config type.

资料来源：[config.d.ts:47-62](https://github.com/microsoft/playwright-mcp/blob/main/config.d.ts)

## Session Management

### Save Session

The `saveSession` option controls whether Playwright session data is persisted to the output directory.

### Shared Browser Context

When `sharedBrowserContext` is enabled, the same browser context is reused across all connected HTTP clients, enabling state sharing between requests.

```typescript
saveSession?: boolean;
sharedBrowserContext?: boolean;
```

资料来源：[config.d.ts:65-70](https://github.com/microsoft/playwright-mcp/blob/main/config.d.ts)

## Secrets Management

Secrets provide a mechanism to redact sensitive information from tool responses before sending them to clients.

```typescript
secrets?: Record<string, string>;
```

**Important**: Secrets replacement is a convenience feature, not a security measure. Always examine incoming and outgoing data on the client side.

资料来源：[config.d.ts:75-80](https://github.com/microsoft/playwright-mcp/blob/main/config.d.ts)

## Console Logging

| Level | Description |
|-------|-------------|
| `error` | Only error messages |
| `warning` | Errors and warnings |
| `info` | Informational messages (default) |
| `debug` | All messages including debug |

```typescript
console?: {
  level?: 'error' | 'warning' | 'info' | 'debug';
}
```

资料来源：[config.d.ts:91-96](https://github.com/microsoft/playwright-mcp/blob/main/config.d.ts)

## Image Responses

Controls whether image responses are sent to MCP clients:

| Value | Behavior |
|-------|----------|
| `allow` | Always send images |
| `omit` | Never send images |
| `auto` | Send images if client can display them (default) |

```typescript
imageResponses?: 'allow' | 'omit' | 'auto';
```

资料来源：[config.d.ts:64](https://github.com/microsoft/playwright-mcp/blob/main/config.d.ts)

## Output Directory

Files generated during MCP operations (screenshots, downloads, traces) are saved to the configured output directory:

```typescript
outputDir?: string;
```

资料来源：[config.d.ts:83](https://github.com/microsoft/playwright-mcp/blob/main/config.d.ts)

## Test ID Attribute

Specify a custom attribute to use for test identification:

```typescript
testIdAttribute?: string;  // Default: "data-testid"
```

资料来源：[config.d.ts:43](https://github.com/microsoft/playwright-mcp/blob/main/config.d.ts)

## Command-Line Interface

### CLI Entry Point

The CLI is implemented in `cli.js` and supports several commands:

```javascript
const { tools, libCli } = require('playwright-core/lib/coreBundle');
tools.decorateMCPCommand(p, packageJSON.version);
```

### Available Commands

| Command | Description |
|---------|-------------|
| Standard MCP tools | Browser automation operations |
| `install-browser` | Install Playwright browsers |

The CLI can forward `install-browser` to `playwright install` for browser installation.

资料来源：[cli.js:24-30](https://github.com/microsoft/playwright-mcp/blob/main/cli.js)

## Configuration Precedence

Environment variables take precedence over default values. The mapping follows this pattern:

| CLI Option | Environment Variable |
|------------|---------------------|
| `--secrets` | `PLAYWRIGHT_MCP_SECRETS_FILE` |
| `--output-dir` | `PLAYWRIGHT_MCP_OUTPUT_DIR` |
| Other options | `PLAYWRIGHT_MCP_<NAME>` (uppercase, hyphen → underscore) |

Example: `--browser-name` → `PLAYWRIGHT_MCP_BROWSER_NAME`

资料来源：[update-readme.js:86-90](https://github.com/microsoft/playwright-mcp/blob/main/update-readme.js)

## Build and Release Workflow

### Version Management

The package version is defined in `package.json`:

```json
{
  "name": "@playwright/mcp",
  "version": "0.0.75"
}
```

### Rolling Playwright Versions

The `roll.js` script handles updating Playwright dependencies:

1. Updates `playwright`, `playwright-core`, and `@playwright/test` versions
2. Copies `config.d.ts` from the Playwright monorepo
3. Regenerates README documentation

```bash
npm run roll
```

资料来源：[roll.js:1-30](https://github.com/microsoft/playwright-mcp/blob/main/roll.js)

### Branch Naming Convention

| Purpose | Pattern |
|---------|---------|
| Rolling Playwright | `roll-pw-<version-suffix>` |
| Issue fixes | `fix-<issue-number>` |

资料来源：[CLAUDE.md:5](https://github.com/microsoft/playwright-mcp/blob/main/CLAUDE.md)

## Testing Infrastructure

### Test Configuration

Tests are configured via `playwright.config.ts`:

```typescript
projects: [
  { name: 'chrome' },
  ...process.env.MCP_IN_DOCKER ? [{
    name: 'chromium-docker',
    grep: /browser_navigate|browser_click/,
    use: {
      mcpBrowser: 'chromium',
      mcpMode: 'docker' as const
    }
  }] : [],
]
```

### Test Commands

| Command | Scope |
|---------|-------|
| `npm test` | All tests across all browsers |
| `npm run ctest` | Chrome only (fast path) |
| `npm run ftest` | Firefox only |
| `npm run wtest` | WebKit only |
| `npm run dtest` | Docker-based Chromium |

MCP tests are located in `tests/mcp` directory within the Playwright monorepo.

资料来源：[playwright.config.ts:22-38](https://github.com/microsoft/playwright-mcp/blob/main/playwright.config.ts)
资料来源：[CONTRIBUTING.md:67-72](https://github.com/microsoft/playwright-mcp/blob/main/CONTRIBUTING.md)

### Test Requirements

- Tests must be **hermetic** (self-contained, no external dependencies)
- Must work on all three platforms: macOS, Linux, Windows
- Tests are required for new functionality (exceptions for pure refactoring)

资料来源：[CONTRIBUTING.md:83-85](https://github.com/microsoft/playwright-mcp/blob/main/CONTRIBUTING.md)

## Commit Conventions

### Semantic Commit Format

```
label(namespace): title

description

footer
```

### Labels

| Label | Purpose |
|-------|---------|
| `fix` | Bug fixes |
| `feat` | New features |
| `docs` | Documentation-only changes |
| `test` | Test-only changes |
| `devops` | CI or build changes |
| `chore` | Miscellaneous (default) |

### Example

```
fix(proxy): handle SOCKS proxy authentication

Fixes: https://github.com/microsoft/playwright/issues/39562
```

资料来源：[CONTRIBUTING.md:11-31](https://github.com/microsoft/playwright-mcp/blob/main/CONTRIBUTING.md)

## Contribution Workflow

```mermaid
graph LR
    A[File Issue] --> B[Get Assignment]
    B --> C[Clone Repository]
    C --> D[Create Branch]
    D --> E[Implement Changes]
    E --> F[Add Tests]
    F --> G[Run Tests]
    G --> H{Linter Pass?}
    H -->|No| I[Fix Issues]
    I --> G
    H -->|Yes| J[Commit Changes]
    J --> K[Open PR]
    K --> L[Code Review]
    L --> M[Merge]
```

### Submission Requirements

- **Issue required**: Every contribution needs a corresponding GitHub issue
- **Prior approval**: Unsolicited PRs will be closed
- **Human oversight**: Low-quality AI contributions without human review will be closed

资料来源：[CONTRIBUTING.md:41-52](https://github.com/microsoft/playwright-mcp/blob/main/CONTRIBUTING.md)

## Documentation Generation

The `update-readme.js` script automatically generates documentation sections:

1. **Tools section**: Lists all MCP tools grouped by capability
2. **Options section**: CLI options from `--help` output
3. **Config section**: TypeScript Config type definition

Generated sections are delimited by markers:
```markdown
<!--- Tools generated by update-readme.js -->
...
<!--- End of tools generated section --->
```

Run `npm run lint` to regenerate documentation.

资料来源：[update-readme.js:1-150](https://github.com/microsoft/playwright-mcp/blob/main/update-readme.js)

---

<a id='installation-guide'></a>

## Installation Guide

### 相关页面

相关主题：[MCP Client Integration](#client-integration), [Docker Deployment](#docker-deployment)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [package.json](https://github.com/microsoft/playwright-mcp/blob/main/package.json)
- [CLAUDE.md](https://github.com/microsoft/playwright-mcp/blob/main/CLAUDE.md)
- [CONTRIBUTING.md](https://github.com/microsoft/playwright-mcp/blob/main/CONTRIBUTING.md)
- [cli.js](https://github.com/microsoft/playwright-mcp/blob/main/cli.js)
- [config.d.ts](https://github.com/microsoft/playwright-mcp/blob/main/config.d.ts)
- [playwright.config.ts](https://github.com/microsoft/playwright-mcp/blob/main/playwright.config.ts)
</details>

# Installation Guide

This guide covers all aspects of installing, configuring, and setting up the Playwright MCP (Model Context Protocol) server for development and production use.

## Overview

Playwright MCP is an npm package (`@playwright/mcp`) that provides browser automation tools via the MCP protocol. It enables AI assistants to interact with web browsers through a standardized interface, supporting capabilities like navigation, clicking, input handling, network interception, and testing assertions.

资料来源：[package.json:1-15]()

## System Requirements

### Runtime Requirements

| Requirement | Version | Description |
|-------------|---------|-------------|
| Node.js | >= 18 | JavaScript runtime environment |
| npm | Latest | Package manager (bundled with Node.js) |

The package explicitly declares its Node.js engine requirement in `package.json`:

```json
"engines": {
  "node": ">=18"
}
```

资料来源：[package.json:12-14]()

### Browser Dependencies

Playwright MCP requires browser binaries to function. The supported browsers are:

| Browser | Support Level | Notes |
|---------|---------------|-------|
| Chromium | Full | Primary development browser |
| Firefox | Full | Cross-browser testing |
| WebKit | Full | Safari compatibility testing |

## Installation Methods

### From npm (Global Installation)

For CLI usage across the system:

```bash
npm install -g @playwright/mcp
```

This makes the `playwright` command available globally:

```bash
playwright --help
```

资料来源：[cli.js:23-26]()

### From npm (Project Installation)

For use as a project dependency:

```bash
npm install @playwright/mcp
```

### Using npx (No Installation)

For one-time execution without installing globally:

```bash
npx @playwright/mcp [options]
```

## CLI Options

The MCP server accepts the following command-line options:

| Option | Environment Variable | Description |
|--------|---------------------|-------------|
| `--secrets <file>` | `PLAYWRIGHT_MCP_SECRETS_FILE` | Path to secrets file |
| `--browser <browser>` | `PLAYWRIGHT_MCP_BROWSER` | Browser to use (chromium, firefox, webkit) |
| `--caps <capabilities>` | `PLAYWRIGHT_MCP_CAPS` | Enable additional capabilities |
| `--output-dir <path>` | `PLAYWRIGHT_MCP_OUTPUT_DIR` | Directory for output files |
| `--config <file>` | `PLAYWRIGHT_MCP_CONFIG` | Path to config file |
| `--install-browser` | N/A | Install browser binaries |
| `--version` | N/A | Show version information |
| `--help` | N/A | Show help message |

资料来源：[update-readme.js:89-111]()

### Environment Variable Mapping

Every CLI option can be configured via environment variables by prefixing the option name with `PLAYWRIGHT_MCP_` and converting dashes to underscores:

```bash
export PLAYWRIGHT_MCP_BROWSER=chromium
export PLAYWRIGHT_MCP_OUTPUT_DIR=/tmp/playwright-output
export PLAYWRIGHT_MCP_SECRETS_FILE=./secrets.json
```

## Configuration File

### Config File Format

Create a TypeScript config file (e.g., `config.ts`) with the following structure:

```typescript
import type { Config } from '@playwright/mcp';

const config: Config = {
  browser: {
    browserName: 'chromium',
    isolated: true,
  },
  capabilities: ['core', 'network'],
  outputDir: '/tmp/playwright-output',
  timeouts: {
    action: 5000,
    navigation: 60000,
    expect: 5000,
  },
};

export default config;
```

### Configuration Options

#### Browser Configuration

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `browserName` | `'chromium' \| 'firefox' \| 'webkit'` | `'chromium'` | Browser type to launch |
| `isolated` | `boolean` | `false` | Keep browser profile in memory |
| `userDataDir` | `string` | `undefined` | Custom browser profile directory |

资料来源：[config.d.ts:18-40]()

#### Capabilities Configuration

The following tool capabilities are available:

| Capability | Description | Notes |
|------------|-------------|-------|
| `core` | Core navigation and interaction tools | Always enabled |
| `core-navigation` | Page navigation tools | Enabled by default |
| `core-tabs` | Tab management tools | Enabled by default |
| `core-input` | Input handling tools | Enabled by default |
| `core-install` | Browser installation tools | Enabled by default |
| `network` | Network request interception | Opt-in via `--caps=network` |
| `pdf` | PDF generation | Opt-in via `--caps=pdf` |
| `storage` | Storage and cookie management | Opt-in via `--caps=storage` |
| `testing` | Test assertion tools | Opt-in via `--caps=testing` |
| `vision` | Coordinate-based interactions | Opt-in via `--caps=vision` |
| `devtools` | Developer tools features | Opt-in via `--caps=devtools` |
| `config` | Configuration tools | Always enabled |

资料来源：[config.d.ts:48-65]()

#### Timeout Configuration

| Option | Default | Description |
|--------|---------|-------------|
| `timeouts.action` | `5000ms` | Default action timeout |
| `timeouts.navigation` | `60000ms` | Default navigation timeout |
| `timeouts.expect` | `5000ms` | Default expect timeout |

资料来源：[config.d.ts:83-97]()

#### Network Configuration

| Option | Type | Description |
|--------|------|-------------|
| `network.allowedOrigins` | `string[]` | Allowed request origins |
| `network.blockedOrigins` | `string[]` | Blocked request origins |

Origins can be specified as full URLs (`https://example.com:8080`) or with wildcard ports (`http://localhost:*`).

资料来源：[config.d.ts:99-114]()

## Development Setup

### Clone the Repository

> [!WARNING]
> The core of the Playwright MCP was moved to the [Playwright monorepo](https://github.com/microsoft/playwright).

Clone the Playwright repository where Playwright MCP source is now located:

```bash
git clone https://github.com/microsoft/playwright
cd playwright
```

资料来源：[CONTRIBUTING.md:33-43]()

### Install Dependencies

Install all project dependencies:

```bash
npm ci
```

### Install Browser Binaries

Download and install the required browser binaries:

```bash
npx playwright install
```

Or install specific browsers:

```bash
npx playwright install chromium
npx playwright install firefox
npx playwright install webkit
```

资料来源：[CONTRIBUTING.md:44-50]()

### Development Workflow

#### Watch Mode

For active development with automatic rebuilding:

```bash
npm run watch
```

#### Run Tests

Run all MCP tests in Chromium (fast path):

```bash
npm run mcp-ctest
```

Run all tests in three browsers (slow path):

```bash
npm run mcp-test
```

#### Linting

Check code quality using the linter:

```bash
npm run flint
```

资料来源：[CONTRIBUTING.md:51-70]()

### Test Directory Structure

Tests for Playwright MCP are located at:

```
tests/mcp/
```

To list test files:

```bash
ls -la tests/mcp
```

资料来源：[CONTRIBUTING.md:59-66]()

## Docker Installation

### Build the Docker Image

```bash
npm run docker-build
```

This creates a Docker image named `playwright-mcp-dev:latest`.

### Run the Docker Container

```bash
npm run docker-run
```

This starts an interactive session with port 8080 exposed.

### Docker Test Mode

Run tests within Docker using Chromium:

```bash
npm run dtest
```

资料来源：[package.json:23-30]()

## Testing Your Installation

### Verify CLI Access

```bash
playwright --version
```

Expected output:
```
Version <version-number>
```

### Verify MCP Connection

Test that the MCP server starts correctly:

```bash
playwright --help
```

### Run Test Suite

Execute the test suite to verify functionality:

```bash
npm test
```

Only proceed with deployment if all tests pass.

资料来源：[CLAUDE.md:4-5]()

## Package Scripts Reference

| Script | Purpose |
|--------|---------|
| `npm run build` | Build the project (echoes "OK") |
| `npm run lint` | Run update-readme.js script |
| `npm run test` | Run all Playwright tests |
| `npm run ctest` | Run Chrome tests only |
| `npm run ftest` | Run Firefox tests only |
| `npm run wtest` | Run WebKit tests only |
| `npm run dtest` | Run Docker-based tests |
| `npm run roll` | Update Playwright version |
| `npm run npm-publish` | Lint, test, and publish |
| `npm run docker-build` | Build Docker image |
| `npm run docker-run` | Run Docker container |
| `npm run docker-rm` | Remove Docker container |

资料来源：[package.json:18-35]()

## Troubleshooting

### Node.js Version Error

If you see an engine version error, ensure you have Node.js 18 or later:

```bash
node --version
# Should be >= 18.0.0
```

### Browser Installation Failure

If browser installation fails, try with elevated permissions or check network connectivity:

```bash
npx playwright install --with-deps
```

### Test Failures

1. Ensure all dependencies are installed: `npm ci`
2. Ensure browsers are installed: `npx playwright install`
3. Verify Node.js version: `node --version`
4. Clear any cached state and retry

### Permission Errors

For global installations, you may need sudo on Unix systems:

```bash
sudo npm install -g @playwright/mcp
```

Or use a Node version manager like `nvm` to avoid permission issues.

---

<a id='client-integration'></a>

## MCP Client Integration

### 相关页面

相关主题：[Installation Guide](#installation-guide), [Browser Configuration](#browser-configuration)

<details>
<summary>Relevant Source Files</summary>

以下源码文件用于生成本页说明：

- [config.d.ts](https://github.com/microsoft/playwright-mcp/blob/main/config.d.ts)
- [server.json](https://github.com/microsoft/playwright-mcp/blob/main/server.json)
- [package.json](https://github.com/microsoft/playwright-mcp/blob/main/package.json)
- [cli.js](https://github.com/microsoft/playwright-mcp/blob/main/cli.js)
- [CONTRIBUTING.md](https://github.com/microsoft/playwright-mcp/blob/main/CONTRIBUTING.md)
- [update-readme.js](https://github.com/microsoft/playwright-mcp/blob/main/update-readme.js)
- [playwright.config.ts](https://github.com/microsoft/playwright-mcp/blob/main/playwright.config.ts)
</details>

# MCP Client Integration

## Overview

MCP Client Integration refers to the mechanism by which the Playwright MCP (Model Context Protocol) server exposes browser automation capabilities as tools that can be consumed by LLM clients. The integration provides a bridge between the MCP protocol and Playwright's browser automation APIs, enabling AI agents to control browsers through a standardized interface.

The MCP server implementation has been moved to the [Playwright monorepo](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/tools/mcp), while this repository (`microsoft/playwright-mcp`) serves as a distribution package and coordination point for the MCP tooling.

资料来源：[src/README.md](https://github.com/microsoft/playwright-mcp/blob/main/src/README.md)

## Architecture

### System Components

The MCP Client Integration consists of several interconnected components:

```mermaid
graph TD
    A["MCP Client<br/>(LLM Agent)"] --> B["Playwright MCP Server"]
    B --> C["playwright-core<br/>coreBundle"]
    B --> D["playwright-core<br/>tools Bundle"]
    C --> E["Browser Process"]
    D --> E
    E --> F["Page/Document"]
    
    G["CLI Entry Point<br/>(cli.js)"] --> B
    H["Configuration<br/>(config.d.ts)"] --> B
    I["server.json<br/>(Transport Config)"] --> B
```

### Transport Layer

The MCP server uses STDIO transport by default, as specified in the server manifest:

```json
{
  "transport": {
    "type": "stdio"
  }
}
```

资料来源：[server.json:13](https://github.com/microsoft/playwright-mcp/blob/main/server.json)

## Configuration Reference

### Config Type Definition

The `Config` type in `config.d.ts` defines all available configuration options for the MCP server:

```typescript
export type ToolCapability =
  | 'config'
  | 'core'
  | 'core-navigation'
  | 'core-tabs'
  | 'core-input'
  | 'core-install'
  | 'network'
  | 'pdf'
  | 'storage'
  | 'testing'
  | 'vision'
  | 'devtools';
```

资料来源：[config.d.ts:20-30](https://github.com/microsoft/playwright-mcp/blob/main/config.d.ts)

### Configuration Options Table

| Category | Option | Type | Default | Description |
|----------|--------|------|---------|-------------|
| **Browser** | `browser.browserName` | `'chromium' \| 'firefox' \| 'webkit'` | - | Browser type to use |
| **Browser** | `browser.isolated` | `boolean` | - | Keep profile in memory only |
| **Browser** | `browser.userDataDir` | `string` | - | Persistent profile directory |
| **Browser** | `browser.launchOptions` | `object` | - | Browser launch options |
| **Network** | `network.allowedOrigins` | `string[]` | All | Allowed request origins |
| **Network** | `network.blockedOrigins` | `string[]` | - | Blocked request origins |
| **Timeouts** | `timeouts.action` | `number` | 5000ms | Default action timeout |
| **Timeouts** | `timeouts.navigation` | `number` | 60000ms | Default navigation timeout |
| **Timeouts** | `timeouts.expect` | `number` | 5000ms | Default expect timeout |
| **Output** | `imageResponses` | `'allow' \| 'omit' \| 'auto'` | `'auto'` | Image response handling |
| **Output** | `outputDir` | `string` | - | Directory for output files |
| **Session** | `saveSession` | `boolean` | - | Save Playwright session to output |
| **Session** | `sharedBrowserContext` | `boolean` | - | Reuse context between clients |
| **Server** | `server.port` | `number` | - | SSE/MCP transport port |
| **Server** | `server.host` | `string` | - | Server bind host |
| **Server** | `server.allowedHosts` | `string[]` | - | Allowed serving hosts |

资料来源：[config.d.ts:31-150](https://github.com/microsoft/playwright-mcp/blob/main/config.d.ts)

### Secrets Management

The configuration supports secrets replacement for sensitive data:

```typescript
secrets?: Record<string, string>;
```

Secrets are used to replace matching plain text in tool responses to prevent LLMs from accidentally receiving sensitive information. This is a convenience feature, not a security mechanism.

资料来源：[config.d.ts:145-150](https://github.com/microsoft/playwright-mcp/blob/main/config.d.ts)

## Capabilities System

### Capability Types

Capabilities control which tool categories are exposed to the MCP client:

| Capability | Purpose |
|------------|---------|
| `core` | Core browser automation features |
| `core-navigation` | Navigation-related tools |
| `core-tabs` | Tab management tools |
| `core-input` | Input handling tools |
| `core-install` | Browser installation tools |
| `network` | Network request/response tools |
| `pdf` | PDF generation and manipulation |
| `storage` | Storage/state management tools |
| `testing` | Testing utilities |
| `vision` | Coordinate-based interactions |
| `devtools` | Developer tools features |
| `config` | Configuration tools |

资料来源：[config.d.ts:20-29](https://github.com/microsoft/playwright-mcp/blob/main/config.d.ts)

### Capability Enablement

Capabilities are specified in the `capabilities` array:

```typescript
capabilities?: ToolCapability[];
```

Only listed capabilities will be enabled. If not specified, all capabilities may be available.

## Tool Schema and Generation

### Tool Information Extraction

The `update-readme.js` script parses compiled modules to extract tool information for documentation:

```javascript
async function updateTools(content) {
  console.log('Loading tool information from compiled modules...');
  const generatedLines = /** @type {string[]} */ ([]);
  for (const [capability, tools] of Object.entries(toolsByCapability)) {
    generatedLines.push(`<details>\n<summary><b>${capability}</b></summary>`);
    for (const tool of tools)
      generatedLines.push(...formatToolForReadme(tool.schema));
    generatedLines.push(`</details>`);
  }
  // ...
}
```

资料来源：[update-readme.js:95-108](https://github.com/microsoft/playwright-mcp/blob/main/update-readme.js)

### Tool Schema Structure

Each tool follows a standardized schema format:

```javascript
function formatToolForReadme(tool) {
  const lines = /** @type {string[]} */ ([]);
  lines.push(`- **${tool.name}**`);
  lines.push(`  - Title: ${tool.title}`);
  lines.push(`  - Description: ${tool.description}`);
  
  const inputSchema = tool.inputSchema ? tool.inputSchema.toJSONSchema() : {};
  if (inputSchema.properties) {
    lines.push(`  - Parameters:`);
    Object.entries(inputSchema.properties).forEach(([name, param]) => {
      lines.push(`    - \`${name}\`: ${param.description}`);
    });
  }
  lines.push(`  - Read-only: **${tool.type === 'readOnly'}**`);
  return lines;
}
```

资料来源：[update-readme.js:145-167](https://github.com/microsoft/playwright-mcp/blob/main/update-readme.js)

### Config Schema Documentation

The config schema is extracted from `config.d.ts` and embedded into README:

```javascript
async function updateConfig(content) {
  const configPath = path.join(__dirname, 'config.d.ts');
  const configContent = await fs.promises.readFile(configPath, 'utf-8');
  const configTypeMatch = configContent.match(/export type Config = (\{[\s\S]*?\n\});/);
  // ...
}
```

资料来源：[update-readme.js:115-126](https://github.com/microsoft/playwright-mcp/blob/main/update-readme.js)

## CLI Interface

### Command-Line Entry Point

The CLI is implemented in `cli.js` and provides the primary interface for running the MCP server:

```javascript
const { program } = require('playwright-core/lib/utilsBundle');
const { tools, libCli } = require('playwright-core/lib/coreBundle');

const packageJSON = require('./package.json');
const p = program.version('Version ' + packageJSON.version).name('Playwright MCP');
tools.decorateMCPCommand(p, packageJSON.version);

void program.parseAsync(process.argv);
```

资料来源：[cli.js:24-33](https://github.com/microsoft/playwright-mcp/blob/main/cli.js)

### CLI Commands

| Command | Description |
|---------|-------------|
| `install-browser` | Install Playwright browsers |
| MCP tools | Exposed via decorated command |

The CLI leverages Playwright's built-in command decoration system from `playwright-core`:

```javascript
tools.decorateMCPCommand(p, packageJSON.version);
```

资料来源：[cli.js:29](https://github.com/microsoft/playwright-mcp/blob/main/cli.js)

### CLI Options Generation

Options are dynamically generated from the CLI help output:

```javascript
async function updateOptions(content) {
  execSync('node cli.js --help > help.txt');
  const lines = output.toString().split('\n');
  // Parse option lines starting with '  --'
  for (let line of lines) {
    if (line.startsWith('  --')) {
      const l = line.substring('  --'.length);
      const gapIndex = l.indexOf('  ');
      const name = l.substring(0, gapIndex).trim();
      const value = l.substring(gapIndex).trim();
      options.push({ name, value });
    }
  }
}
```

资料来源：[update-readme.js:52-65](https://github.com/microsoft/playwright-mcp/blob/main/update-readme.js)

## Testing

### Test Configuration

The project uses Playwright's test framework with a dedicated MCP test configuration:

```typescript
import { defineConfig } from '@playwright/test';

export default defineConfig<TestOptions>({
  testDir: './tests',
  fullyParallel: true,
  forbidOnly: !!process.env.CI,
  workers: process.env.CI ? 2 : undefined,
  reporter: 'list',
  projects: [
    { name: 'chrome' },
  ],
});
```

资料来源：[playwright.config.ts:17-30](https://github.com/microsoft/playwright-mcp/blob/main/playwright.config.ts)

### Test Commands

| Command | Description |
|---------|-------------|
| `npm test` | Run all MCP tests |
| `npm run ctest` | Run tests in Chromium only |
| `npm run ftest` | Run tests in Firefox only |
| `npm run wtest` | Run tests in WebKit only |
| `npm run dtest` | Run tests in Docker (Chromium) |

资料来源：[package.json:15-22](https://github.com/microsoft/playwright-mcp/blob/main/package.json)

### Test Requirements

Tests must be:
- **Hermetic**: No external service dependencies
- **Cross-platform**: Work on macOS, Linux, and Windows
- **Covered by tests**: New functionality requires corresponding tests

资料来源：[CONTRIBUTING.md](https://github.com/microsoft/playwright-mcp/blob/main/CONTRIBUTING.md)

## Workflow: README Generation

The README is auto-generated from multiple sources:

```mermaid
graph LR
    A["config.d.ts"] --> D["updateReadme()"]
    B["CLI --help"] --> D
    C["Tool Schemas"] --> D
    D --> E["README.md"]
```

### Generation Pipeline

```javascript
async function updateReadme() {
  const readmePath = path.join(__dirname, 'README.md');
  const readmeContent = await fs.promises.readFile(readmePath, 'utf-8');
  const withTools = await updateTools(readmeContent);
  const withOptions = await updateOptions(withTools);
  const withConfig = await updateConfig(withOptions);
  await fs.promises.writeFile(readmePath, withConfig, 'utf-8');
}
```

资料来源：[update-readme.js:130-139](https://github.com/microsoft/playwright-mcp/blob/main/update-readme.js)

## Development Workflow

### Local Development

```bash
# Clone the Playwright monorepo (source location)
git clone https://github.com/microsoft/playwright
cd playwright

# Install dependencies and run watch mode
npm ci
npm run watch
npx playwright install

# Navigate to MCP source
cd packages/playwright/src/mcp
```

资料来源：[CONTRIBUTING.md](https://github.com/microsoft/playwright-mcp/blob/main/CONTRIBUTING.md)

### Rolling Playwright Updates

The repository maintains synchronization with the Playwright core:

```bash
# Run roll script to update dependencies
npm run roll
# This bumps playwright, playwright-core, @playwright/test
# Refreshes config.d.ts
# Regenerates README
```

资料来源：[CLAUDE.md](https://github.com/microsoft/playwright-mcp/blob/main/CLAUDE.md)

### Linting

Before submitting changes, run the linter:

```bash
npm run lint
```

This executes `update-readme.js` to validate and regenerate documentation.

资料来源：[package.json:14](https://github.com/microsoft/playwright-mcp/blob/main/package.json)

## Package Information

### NPM Package Details

| Property | Value |
|----------|-------|
| Package Name | `@playwright/mcp` |
| MCP Name | `io.github.microsoft/playwright-mcp` |
| Node Engine | `>=18` |
| License | Apache-2.0 |
| Transport | STDIO |

资料来源：[package.json:1-12](https://github.com/microsoft/playwright-mcp/blob/main/package.json)

---

<a id='browser-configuration'></a>

## Browser Configuration

### 相关页面

相关主题：[User Profiles and Session Management](#user-profiles), [Security Settings](#security-settings)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [config.d.ts](https://github.com/microsoft/playwright-mcp/blob/main/config.d.ts)
- [playwright.config.ts](https://github.com/microsoft/playwright-mcp/blob/main/playwright.config.ts)
- [README.md](https://github.com/microsoft/playwright-mcp/blob/main/README.md)
- [package.json](https://github.com/microsoft/playwright-mcp/blob/main/package.json)
- [cli.js](https://github.com/microsoft/playwright-mcp/blob/main/cli.js)
</details>

# Browser Configuration

## Overview

Browser Configuration in playwright-mcp defines how the Playwright MCP server manages browser instances for automation tasks. The configuration is defined through the `Config` type in `config.d.ts` and controls browser selection, launch behavior, session persistence, and security policies.

资料来源：[config.d.ts:48-120]()

```mermaid
graph TD
    A[Browser Configuration] --> B[Browser Selection]
    A --> C[Launch Options]
    A --> D[Session Management]
    A --> E[Network Security]
    A --> F[Server Binding]
    
    B --> B1[chromium]
    B --> B2[firefox]
    B --> B3[webkit]
    
    C --> C1[User Data Dir]
    C --> C2[Init Scripts]
    C --> C3[Launch Params]
```

## Browser Type Selection

### Supported Browsers

The configuration supports three browser engines:

| Browser | Identifier | Notes |
|---------|------------|-------|
| Chromium | `chromium` | Default, best compatibility |
| Firefox | `firefox` | Gecko-based engine |
| WebKit | `webkit` | Safari engine port |

资料来源：[config.d.ts:57-64]()

### Configuration Properties

```typescript
browser?: {
  browserName?: 'chromium' | 'firefox' | 'webkit';
  isolated?: boolean;
  userDataDir?: string;
  launchOptions?: Record<string, any>;
  initPage?: string[];
  initScript?: string[];
}
```

| Property | Type | Default | Description |
|----------|------|---------|-------------|
| `browserName` | `'chromium' \| 'firefox' \| 'webkit'` | `chromium` | Browser engine to launch |
| `isolated` | `boolean` | `false` | Keep browser profile in memory only |
| `userDataDir` | `string` | system temp | Custom profile directory path |
| `launchOptions` | `Record<string, any>` | `{}` | Playwright launch options |
| `initPage` | `string[]` | `[]` | TypeScript initialization scripts |
| `initScript` | `string[]` | `[]` | JavaScript initialization scripts |

资料来源：[config.d.ts:48-87]()

## Profile Management

### Isolated Mode

When `isolated: true`, the browser profile is kept entirely in memory without persisting to disk. This provides:

- Better privacy between sessions
- Clean state for each automation run
- No leftover browser data

### Custom User Data Directory

The `userDataDir` option allows specifying a persistent profile location:

```typescript
{
  browser: {
    userDataDir: '/path/to/custom/profile'
  }
}
```

If not specified, the system creates a temporary directory automatically.

资料来源：[config.d.ts:68-75]()

## Initialization Scripts

Initialization scripts run before any page content, enabling you to inject polyfills, modify prototypes, or set up testing utilities.

### TypeScript Scripts (`initPage`)

Paths to TypeScript files that are added as initialization scripts:

```typescript
{
  browser: {
    initPage: ['./setup.ts', './fixtures.ts']
  }
}
```

### JavaScript Scripts (`initScript`)

Paths to JavaScript files evaluated in every page before page scripts:

```typescript
{
  browser: {
    initScript: ['./polyfills.js', './mocks.js']
  }
}
```

Both script types are evaluated in every page created within the browser context.

资料来源：[config.d.ts:81-87]()

## Extension Support

Playwright MCP can connect to a running browser instance using the Playwright Extension (Chrome/Edge only):

```typescript
{
  extension: true
}
```

When `extension` is enabled:
- The `browser` configuration is ignored
- Requires the "Playwright Extension" browser add-on to be installed
- Connects to the browser's debugging port

资料来源：[config.d.ts:89-93]()

## Server Configuration

The server section controls network binding for the MCP transport:

```typescript
server?: {
  port?: number;
  host?: string;
  allowedHosts?: string[];
}
```

| Property | Type | Default | Description |
|----------|------|---------|-------------|
| `port` | `number` | undefined | Port for SSE or MCP transport |
| `host` | `string` | `localhost` | Bind address; use `0.0.0.0` for all interfaces |
| `allowedHosts` | `string[]` | server host | DNS rebinding protection |

资料来源：[config.d.ts:95-107]()

## Capability Management

Capabilities control which tool sets are enabled for the MCP server:

```typescript
capabilities?: ToolCapability[];
```

| Capability | Description |
|-------------|-------------|
| `config` | Configuration tools |
| `core` | Core browser automation |
| `core-navigation` | Navigation operations |
| `core-tabs` | Tab management |
| `core-input` | Input handling |
| `core-install` | Browser installation |
| `network` | Network request tools |
| `pdf` | PDF generation |
| `storage` | Storage APIs |
| `testing` | Testing utilities |
| `vision` | Coordinate-based interactions |
| `devtools` | Developer tools |

资料来源：[config.d.ts:33-46]()

## Session Management

### Save Session

When enabled, the Playwright session state is persisted to the output directory:

```typescript
{
  saveSession: true
}
```

资料来源：[config.d.ts:115-117]()

### Shared Browser Context

Multiple HTTP clients can share the same browser context:

```typescript
{
  sharedBrowserContext: true
}
```

This is useful for environments where multiple requests need to share session state.

资料来源：[config.d.ts:119-121]()

## Security Configuration

### Network Origins

Control which origins the browser can request:

```typescript
network?: {
  allowedOrigins?: string[];
  blockedOrigins?: string[];
}
```

**Supported formats:**
- Full origin: `https://example.com:8080` - matches only that exact origin
- Wildcard port: `http://localhost:*` - matches any port on localhost with http

Origins matching both lists will be blocked.

资料来源：[config.d.ts:151-165]()

### Secrets Management

Secrets replace matching plain text in tool responses to prevent sensitive data exposure:

```typescript
{
  secrets: {
    API_KEY: 'sk-xxxxx',
    DB_PASSWORD: 'secret123'
  }
}
```

> Note: This is a convenience feature, not a security measure. Always examine incoming data.

资料来源：[config.d.ts:123-129]()

### Console Level

Control console message verbosity:

```typescript
console?: {
  level?: 'error' | 'warning' | 'info' | 'debug';
}
```

Each level includes messages from more severe levels. Defaults to `info`.

资料来源：[config.d.ts:140-146]()

## Timeout Configuration

Configure default timeouts for various operations:

```typescript
timeouts?: {
  action?: number;      // Default: 5000ms
  navigation?: number; // Default: 60000ms
  expect?: number;     // Default: 5000ms
}
```

资料来源：[config.d.ts:131-144]()

## Test Configuration

The test suite uses a dedicated Playwright configuration:

```typescript
// playwright.config.ts
export default defineConfig<TestOptions>({
  testDir: './tests',
  fullyParallel: true,
  forbidOnly: !!process.env.CI,
  workers: process.env.CI ? 2 : undefined,
  projects: [
    { name: 'chrome' },
    ...process.env.MCP_IN_DOCKER ? [{
      name: 'chromium-docker',
      grep: /browser_navigate|browser_click/,
      use: {
        mcpBrowser: 'chromium',
        mcpMode: 'docker' as const
      }
    }] : [],
  ],
});
```

The configuration supports:
- Running tests across browser projects
- Docker-based testing environment
- CI-specific constraints (`forbidOnly`, limited workers)

资料来源：[playwright.config.ts:1-34]()

## CLI Usage

The CLI provides commands for running and managing the MCP server:

```bash
# Run with custom config
npx playwright-mcp --config my-config.json

# Install browser
npx playwright-mcp install-browser
```

The CLI is decorated using Playwright's core tools and supports the MCP transport protocol.

资料来源：[cli.js:1-35]()

## Complete Configuration Example

```typescript
import type { Config } from './config';

const config: Config = {
  browser: {
    browserName: 'chromium',
    isolated: true,
    initScript: ['./setup.js'],
  },
  server: {
    port: 8080,
    host: 'localhost',
  },
  capabilities: ['core', 'network', 'pdf'],
  saveSession: false,
  sharedBrowserContext: true,
  secrets: {
    API_KEY: process.env.API_KEY || '',
  },
  outputDir: './output',
  network: {
    allowedOrigins: ['https://example.com'],
    blockedOrigins: ['https://malicious.com'],
  },
  console: {
    level: 'info',
  },
  timeouts: {
    action: 5000,
    navigation: 30000,
    expect: 3000,
  },
};
```

## Configuration Schema Summary

| Section | Key Properties | File Source |
|---------|----------------|-------------|
| Browser | `browserName`, `isolated`, `userDataDir`, `launchOptions` | `config.d.ts:48-87` |
| Extension | `extension: boolean` | `config.d.ts:89-93` |
| Server | `port`, `host`, `allowedHosts` | `config.d.ts:95-107` |
| Capabilities | `capabilities[]` | `config.d.ts:109-113` |
| Session | `saveSession`, `sharedBrowserContext` | `config.d.ts:115-121` |
| Security | `secrets`, `network` | `config.d.ts:123-165` |
| Timeouts | `timeouts.action`, `timeouts.navigation`, `timeouts.expect` | `config.d.ts:131-144` |
| Console | `console.level` | `config.d.ts:140-146` |

## Related Commands

| Command | Purpose |
|---------|---------|
| `npm run roll` | Update Playwright version and regenerate config |
| `npm test` | Run test suite across all browsers |
| `npm run ctest` | Run tests in Chromium only |
| `npm run docker-run` | Start MCP in Docker container |

资料来源：[package.json:8-27]()

---

<a id='security-settings'></a>

## Security Settings

### 相关页面

相关主题：[Browser Configuration](#browser-configuration), [Docker Deployment](#docker-deployment)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [config.d.ts](https://github.com/microsoft/playwright-mcp/blob/main/config.d.ts)
- [SECURITY.md](https://github.com/microsoft/playwright-mcp/blob/main/SECURITY.md)
- [README.md](https://github.com/microsoft/playwright-mcp/blob/main/README.md)
- [package.json](https://github.com/microsoft/playwright-mcp/blob/main/package.json)
- [playwright.config.ts](https://github.com/microsoft/playwright-mcp/blob/main/playwright.config.ts)
</details>

# Security Settings

Playwright MCP provides comprehensive security settings to protect sensitive data, control browser access, and prevent unauthorized network requests. These settings are configurable through the `Config` type defined in `config.d.ts`.

## Overview

The Playwright MCP server handles browser automation with built-in security mechanisms that address common attack vectors including:

- DNS rebinding attacks
- Unauthorized network access
- Sensitive data exposure
- Session hijacking

All security configurations are optional and have sensible defaults. Administrators should review and configure these settings based on their deployment environment and security requirements.

## Configuration Schema

Security settings are defined within the main `Config` type. The following table summarizes available security-related configuration options:

| Configuration Section | Purpose | Default |
|----------------------|---------|---------|
| `browser.isolated` | Keep browser profile in memory | `false` |
| `browser.userDataDir` | Browser profile storage location | Temporary directory |
| `network.allowedOrigins` | Permitted request origins | All origins |
| `network.blockedOrigins` | Blocked request origins | None |
| `secrets` | Sensitive data replacement | None |
| `server.allowedHosts` | DNS rebinding protection | Server host only |
| `console.level` | Console message filtering | `"info"` |
| `imageResponses` | Image response handling | `"auto"` |

## Network Security

### Origin-Based Access Control

Playwright MCP implements origin-based network filtering to control which websites the browser can access.

```typescript
network?: {
  allowedOrigins?: string[];
  blockedOrigins?: string[];
};
```

**Supported Formats:**

| Format | Example | Description |
|--------|---------|-------------|
| Full origin | `https://example.com:8080` | Matches exact origin with port |
| Wildcard port | `http://localhost:*` | Matches any port on localhost with HTTP |
| Protocol wildcard | `https://*` | Matches any origin with HTTPS |

**Origin Matching Rules:**

1. Origins specified in `blockedOrigins` take precedence over `allowedOrigins`
2. If an origin matches both lists, it will be **blocked**
3. If only `allowedOrigins` is set, only those origins are accessible
4. If only `blockedOrigins` is set, all origins except blocked are accessible
5. If neither is set, all origins are accessible

**Example Configuration:**

```typescript
{
  network: {
    // Allow only specific domains
    allowedOrigins: [
      'https://myapp.example.com',
      'https://api.example.com:8080',
      'http://localhost:*'  // Allow any localhost port for development
    ],
    // Block specific origins
    blockedOrigins: [
      'https://malicious-site.com'
    ]
  }
}
```

### Browser Isolation

Browser isolation ensures that browser profiles and session data are not persisted to disk, reducing the attack surface.

```typescript
browser?: {
  browserName?: 'chromium' | 'firefox' | 'webkit';
  isolated?: boolean;
  userDataDir?: string;
};
```

| Option | Type | Description |
|--------|------|-------------|
| `isolated` | `boolean` | When `true`, keeps browser profile in memory without disk persistence |
| `userDataDir` | `string` | Custom path for browser profile storage |

**Security Implications:**

- `isolated: true` - Maximum security, no persistent data
- `isolated: false` - Session persistence, faster subsequent launches

## Secrets Management

The secrets configuration provides a convenience mechanism to redact sensitive information from tool responses before they reach the client.

```typescript
secrets?: Record<string, string>;
```

**How It Works:**

1. Define key-value pairs where the key is the pattern to find and value is the replacement
2. All occurrences of the key in tool response text are replaced with the value
3. This is a **convenience feature**, not a security boundary

**Important Security Note:**

> 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.
> 资料来源：[config.d.ts](https://github.com/microsoft/playwright-mcp/blob/main/config.d.ts)

**Example Configuration:**

```typescript
{
  secrets: {
    'sk-1234567890abcdef': '[API_KEY_REDACTED]',
    'my-secret-token': '[TOKEN_REDACTED]',
    'password123': '[PASSWORD_REDACTED]'
  }
}
```

### Data Flow Diagram

```mermaid
graph TD
    A[Browser Automation] --> B[Tool Response Generated]
    B --> C{Secrets Configured?}
    C -->|Yes| D[Scan Response for Secret Patterns]
    C -->|No| E[Return Original Response]
    D --> F{Pattern Match Found?}
    F -->|Yes| G[Replace with Redacted Value]
    F -->|No| E
    G --> H[Return Sanitized Response]
    E --> H
```

## Server Security

### Host-Based Access Control

The server configuration includes protection against DNS rebinding attacks through the `allowedHosts` option.

```typescript
server?: {
  port?: number;
  host?: string;
  allowedHosts?: string[];
};
```

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `port` | `number` | 8080 | Port to listen on |
| `host` | `string` | localhost | Binding interface |
| `allowedHosts` | `string[]` | Server host | Hosts allowed to connect |

**DNS Rebinding Protection:**

The `allowedHosts` setting protects against DNS rebinding attacks where a malicious domain resolves to your server's IP address. By default, only the host the server is bound to is allowed.

**Example Configuration:**

```typescript
{
  server: {
    port: 8080,
    host: '0.0.0.0',  // Bind to all interfaces
    allowedHosts: [
      'localhost',
      '127.0.0.1',
      'my-secure-domain.com'
    ]
  }
}
```

## Console Security

Console message filtering controls what level of browser console output is exposed to clients.

```typescript
console?: {
  level?: 'error' | 'warning' | 'info' | 'debug';
};
```

**Log Levels:**

| Level | Includes | Description |
|-------|----------|-------------|
| `error` | Error messages only | Most restrictive |
| `warning` | Errors + Warnings | Recommended for production |
| `info` | Errors + Warnings + Info | Default level |
| `debug` | All messages | Development only |

**Security Consideration:**

Lower log levels reduce information leakage but may hide important diagnostic information. Choose the appropriate level based on your environment.

## Image Response Handling

Control how image responses are handled to prevent potential information disclosure through image metadata.

```typescript
imageResponses?: 'allow' | 'omit' | 'auto';
```

| Option | Description |
|--------|-------------|
| `allow` | Always send image responses to client |
| `omit` | Never send image responses |
| `auto` | Send images only if client can display them (default) |

## Timeouts and Resource Limits

Timeouts help prevent resource exhaustion attacks and ensure predictable behavior.

```typescript
timeouts?: {
  action?: number;      // Default: 5000ms
  navigation?: number; // Default: 60000ms
  expect?: number;     // Default: 5000ms
};
```

**Security Benefits:**

- Prevents hanging operations from consuming resources
- Limits exposure time for potentially malicious pages
- Enables faster failure detection

## Security Architecture

```mermaid
graph TD
    subgraph "Client Layer"
        A[MCP Client]
    end
    
    subgraph "Security Middleware"
        B[Host Validation]
        C[Origin Filtering]
        D[Secrets Replacement]
    end
    
    subgraph "Browser Layer"
        E[Playwright Browser]
        F[Isolated Context]
    end
    
    A --> B
    B --> C
    C --> D
    D --> E
    E --> F
    
    style A fill:#f9f,stroke:#333
    style B fill:#ff9,stroke:#333
    style C fill:#ff9,stroke:#333
    style D fill:#ff9,stroke:#333
```

## Security Best Practices

### Production Deployment

1. **Enable Browser Isolation**
   ```typescript
   { browser: { isolated: true } }
   ```

2. **Configure Origin Restrictions**
   ```typescript
   { network: { allowedOrigins: ['https://your-domain.com'] } }
   ```

3. **Use Appropriate Console Level**
   ```typescript
   { console: { level: 'warning' } }  // Production
   ```

4. **Set Server Host Restrictions**
   ```typescript
   { server: { allowedHosts: ['your-domain.com'] } }
   ```

5. **Configure Reasonable Timeouts**
   ```typescript
   { timeouts: { action: 5000, navigation: 30000 } }
   ```

### Development Considerations

- Use `console.level: 'debug'` only in development
- Consider `imageResponses: 'auto'` for performance
- Use `isolated: false` for faster iteration

## Reporting Security Issues

Microsoft maintains a security response process for reporting vulnerabilities.

**Please do not report security vulnerabilities through public GitHub issues.**

Instead, report them to the Microsoft Security Response Center (MSRC):

- **Online:** [https://msrc.microsoft.com/create-report](https://aka.ms/security.md/msrc/create-report)
- **Email:** [secure@microsoft.com](mailto:secure@microsoft.com) (PGP encryption available)

Response timeline: You should receive a response within 24 hours.
 资料来源：[SECURITY.md](https://github.com/microsoft/playwright-mcp/blob/main/SECURITY.md)

## Complete Security Configuration Example

```typescript
import { createConnection } from '@playwright/mcp';

const connection = createConnection({
  browser: {
    browserName: 'chromium',
    isolated: true  // Maximum security
  },
  
  network: {
    allowedOrigins: [
      'https://trusted-app.example.com',
      'http://localhost:*'  // Development only
    ],
    blockedOrigins: [
      'https://untrusted-source.com'
    ]
  },
  
  secrets: {
    'sk-api-key': '[REDACTED]',
    'password': '[REDACTED]'
  },
  
  server: {
    port: 8080,
    host: '127.0.0.1',
    allowedHosts: ['localhost', '127.0.0.1']
  },
  
  console: {
    level: 'warning'  // Only errors and warnings
  },
  
  imageResponses: 'auto',
  
  timeouts: {
    action: 5000,
    navigation: 30000,
    expect: 3000
  }
});
```

## Related Documentation

- [Playwright MCP README](https://github.com/microsoft/playwright-mcp/blob/main/README.md) - Main project documentation
- [Config Type Definition](https://github.com/microsoft/playwright-mcp/blob/main/config.d.ts) - Complete configuration types
- [Playwright Documentation](https://playwright.dev/docs/api/class-browser) - Browser automation reference

---

<a id='docker-deployment'></a>

## Docker Deployment

### 相关页面

相关主题：[Programmatic Usage](#programmatic-usage), [Installation Guide](#installation-guide)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [CONTRIBUTING.md](https://github.com/microsoft/playwright-mcp/blob/main/CONTRIBUTING.md)
- [CLAUDE.md](https://github.com/microsoft/playwright-mcp/blob/main/CLAUDE.md)
- [package.json](https://github.com/microsoft/playwright-mcp/blob/main/package.json)
- [playwright.config.ts](https://github.com/microsoft/playwright-mcp/blob/main/playwright.config.ts)
- [config.d.ts](https://github.com/microsoft/playwright-mcp/blob/main/config.d.ts)
</details>

# Docker Deployment

This page documents the Docker deployment capabilities for Playwright MCP, including container-based development, testing, and runtime configuration.

## Overview

Playwright MCP supports Docker-based deployment to provide isolated, consistent browser automation environments. The Docker integration enables:

- Containerized browser testing
- Isolated development environments
- Consistent CI/CD pipelines
- Cross-platform browser automation

Docker support is configured through npm scripts defined in `package.json` and dedicated test configurations in `playwright.config.ts`.

## Docker Scripts

The project provides three npm scripts for managing Docker containers:

| Script | Command | Purpose |
|--------|---------|---------|
| `docker-build` | `docker build --no-cache -t playwright-mcp-dev:latest .` | Build the Docker image with no cache |
| `docker-rm` | `docker rm playwright-mcp-dev` | Remove the existing container |
| `docker-run` | `docker run -it -p 8080:8080 --name playwright-mcp-dev playwright-mcp-dev:latest` | Run the container interactively |

### Building the Docker Image

```bash
npm run docker-build
```

This creates an image tagged as `playwright-mcp-dev:latest`. The `--no-cache` flag ensures a fresh build.

### Running the Container

```bash
npm run docker-run
```

The container maps port 8080 for external access and runs in interactive mode (`-it`).

### Cleaning Up

```bash
npm run docker-rm
```

Removes the container to allow fresh deployments.

资料来源：[package.json:17-19](https://github.com/microsoft/playwright-mcp/blob/main/package.json)

## Docker Test Configuration

Playwright MCP includes dedicated configuration for running tests within Docker containers using Chromium.

### Chromium Docker Project

```typescript
{
  name: 'chromium-docker',
  grep: /browser_navigate|browser_click/,
  use: {
    mcpBrowser: 'chromium',
    mcpMode: 'docker' as const
  }
}
```

| Parameter | Value | Description |
|-----------|-------|-------------|
| `name` | `chromium-docker` | Project identifier for Docker-based Chromium tests |
| `grep` | `/browser_navigate\|browser_click/` | Test filter for Docker-specific tests |
| `mcpBrowser` | `chromium` | Browser type for Docker testing |
| `mcpMode` | `docker` | Execution mode set to Docker |

### Running Docker Tests

```bash
MCP_IN_DOCKER=1 playwright test --project=chromium-docker
```

The `MCP_IN_DOCKER` environment variable enables Docker-specific test behavior.

资料来源：[playwright.config.ts:27-34](https://github.com/microsoft/playwright-mcp/blob/main/playwright.config.ts)
资料来源：[CONTRIBUTING.md:58-60](https://github.com/microsoft/playwright-mcp/blob/main/CONTRIBUTING.md)

## Browser Configuration for Docker

The `config.d.ts` file defines browser options that can be configured for Docker deployments.

### Browser Configuration Schema

```typescript
browser?: {
  browserName?: 'chromium' | 'firefox' | 'webkit';
  isolated?: boolean;
  userDataDir?: string;
  launchOptions?: Record<string, unknown>;
};
```

| Option | Type | Description |
|--------|------|-------------|
| `browserName` | `chromium \| firefox \| webkit` | Browser type to use in container |
| `isolated` | `boolean` | Keep browser profile in memory (default: true for containers) |
| `userDataDir` | `string` | Path to persist browser profile across sessions |
| `launchOptions` | `Record<string, unknown>` | Browser-specific launch arguments |

### Docker-Specific Browser Settings

For containerized environments, consider these recommended configurations:

| Scenario | Recommended Settings |
|----------|----------------------|
| Ephemeral testing | `isolated: true`, no `userDataDir` |
| Session persistence | `userDataDir: '/data/browser-profile'` |
| Headless CI | `launchOptions: { headless: true }` |

资料来源：[config.d.ts:28-45](https://github.com/microsoft/playwright-mcp/blob/main/config.d.ts)

## Network Configuration for Containers

Playwright MCP supports fine-grained network control for browser instances within Docker:

### Allowed and Blocked Origins

```typescript
network?: {
  allowedOrigins?: string[];
  blockedOrigins?: string[];
};
```

| Parameter | Description |
|-----------|-------------|
| `allowedOrigins` | List of origins the browser is permitted to request |
| `blockedOrigins` | List of origins to block (takes precedence over allowed) |

### Origin Format Examples

| Format | Example | Matches |
|--------|---------|---------|
| Full origin | `https://example.com:8080` | Exact origin and port |
| Wildcard port | `http://localhost:*` | Any port on localhost with HTTP |
| Protocol wildcard | `https://*.example.com` | All subdomains |

> **Note:** Origins matching both `allowedOrigins` and `blockedOrigins` will be blocked.

资料来源：[config.d.ts:70-85](https://github.com/microsoft/playwright-mcp/blob/main/config.d.ts)

## Server Configuration for Docker

The server can be configured to run within Docker containers:

```typescript
server?: {
  port?: number;
  host?: string;
  allowedHosts?: string[];
};
```

| Parameter | Default | Description |
|-----------|---------|-------------|
| `port` | `8080` | Port for SSE or MCP transport |
| `host` | `localhost` | Bind address (use `0.0.0.0` for Docker) |
| `allowedHosts` | Same as host | Allowed serving hosts (DNS rebinding protection) |

### Docker Server Deployment

For containerized deployments, configure the server to bind to all interfaces:

```typescript
{
  server: {
    host: '0.0.0.0',
    port: 8080,
    allowedHosts: ['*']
  }
}
```

资料来源：[config.d.ts:117-130](https://github.com/microsoft/playwright-mcp/blob/main/config.d.ts)

## Architecture Overview

```mermaid
graph TD
    A[Developer Machine] --> B[Docker Container]
    B --> C[Playwright MCP Server]
    C --> D[Browser Instance]
    D --> E[Web Application]
    
    F[CI/CD Pipeline] --> B
    G[External Client] --> |HTTP:8080| B
    
    style B fill:#e1f5fe
    style C fill:#f3e5f5
    style D fill:#fff3e0
```

## Deployment Workflow

```mermaid
graph LR
    A[Build Image] --> B[Create Container]
    B --> C[Run Tests or Server]
    C --> D{Pass?}
    D -->|Yes| E[Success]
    D -->|No| F[Debug & Fix]
    F --> A
    
    G[Clean Up] --> H[Remove Container]
    G --> I[Remove Image]
```

## Environment Variables

| Variable | Description | Example |
|----------|-------------|---------|
| `MCP_IN_DOCKER` | Enables Docker-specific test behavior | `1` |
| `CI` | Indicates CI environment (limits workers) | `true` |

资料来源：[CONTRIBUTING.md:58-60](https://github.com/microsoft/playwright-mcp/blob/main/CONTRIBUTING.md)
资料来源：[playwright.config.ts:13](https://github.com/microsoft/playwright-mcp/blob/main/playwright.config.ts)

## Complete Docker Workflow Example

```bash
# 1. Build the Docker image
npm run docker-build

# 2. Remove any existing container
npm run docker-rm

# 3. Run the container
npm run docker-run

# 4. In another terminal, run Docker-specific tests
MCP_IN_DOCKER=1 npm run dtest

# 5. Clean up when done
npm run docker-rm
```

## Limitations and Considerations

1. **No Dockerfile in Repository**: The repository does not include a `Dockerfile`. Users must create their own based on project requirements.
2. **Browser Installation**: When building custom Docker images, ensure browsers are installed using `npx playwright install`.
3. **Port Mapping**: The default configuration exposes port 8080; adjust as needed for your environment.
4. **Browser Compatibility**: Docker testing is limited to Chromium (`chromium-docker` project).

资料来源：[CLAUDE.md:11-16](https://github.com/microsoft/playwright-mcp/blob/main/CLAUDE.md)

## Related Configuration

| Configuration File | Purpose |
|-------------------|---------|
| `config.d.ts` | TypeScript definitions for all config options |
| `playwright.config.ts` | Test runner configuration |
| `package.json` | npm scripts for Docker operations |
| `server.json` | MCP server metadata and transport |

---

<a id='programmatic-usage'></a>

## Programmatic Usage

### 相关页面

相关主题：[Docker Deployment](#docker-deployment), [MCP Client Integration](#client-integration)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [index.js](https://github.com/microsoft/playwright-mcp/blob/main/index.js)
- [cli.js](https://github.com/microsoft/playwright-mcp/blob/main/cli.js)
- [package.json](https://github.com/microsoft/playwright-mcp/blob/main/package.json)
- [config.d.ts](https://github.com/microsoft/playwright-mcp/blob/main/config.d.ts)
- [CONTRIBUTING.md](https://github.com/microsoft/playwright-mcp/blob/main/CONTRIBUTING.md)
- [src/README.md](https://github.com/microsoft/playwright-mcp/blob/main/src/README.md)
</details>

# Programmatic Usage

This page documents how to programmatically use Playwright MCP (Model Context Protocol) to integrate Playwright browser automation capabilities into your applications.

## Overview

Playwright MCP provides browser automation tools that can be used by Large Language Models (LLMs) through the MCP protocol. The package exposes a `createConnection` function that enables programmatic integration with MCP-compatible clients.

The core implementation resides in the [Playwright monorepo](https://github.com/microsoft/playwright/blob/main/packages/playwright-core/src/tools/mcp), while this repository serves as the distribution package for the MCP tools.

资料来源：[src/README.md:1-3](https://github.com/microsoft/playwright-mcp/blob/main/src/README.md)

## Entry Points

Playwright MCP provides two primary entry points for programmatic usage:

| Entry Point | File | Purpose |
|-------------|------|---------|
| Module | `index.js` | Programmatic import for Node.js applications |
| CLI | `cli.js` | Command-line interface for direct execution |

资料来源：[index.js:1-30](https://github.com/microsoft/playwright-mcp/blob/main/index.js)
资料来源：[cli.js:1-45](https://github.com/microsoft/playwright-mcp/blob/main/cli.js)

### Module Import

The primary module export provides the `createConnection` function:

```javascript
const { createConnection } = require('@playwright/mcp');
```

资料来源：[index.js:27-29](https://github.com/microsoft/playwright-mcp/blob/main/index.js)

The `createConnection` function is sourced from `playwright-core/lib/coreBundle`, which contains the core MCP implementation including tool definitions and connection handling logic.

### CLI Usage

The CLI can be invoked directly via Node.js:

```bash
node cli.js [command] [options]
```

The CLI is decorated with Playwright's MCP command utilities, which handle transport negotiation and tool invocation.

资料来源：[cli.js:24-28](https://github.com/microsoft/playwright-mcp/blob/main/cli.js)

## Configuration

Playwright MCP accepts configuration through the `Config` type defined in `config.d.ts`.

### Tool Capabilities

Tool capabilities define which browser automation features are enabled:

```typescript
export type ToolCapability =
  | 'config'
  | 'core'
  | 'core-navigation'
  | 'core-tabs'
  | 'core-input'
  | 'core-install'
  | 'network'
  | 'pdf'
  | 'storage'
  | 'testing'
  | 'vision'
  | 'devtools';
```

资料来源：[config.d.ts:17-30](https://github.com/microsoft/playwright-mcp/blob/main/config.d.ts)

| Capability | Description |
|------------|-------------|
| `core` | Core browser automation features |
| `core-navigation` | Page navigation operations |
| `core-tabs` | Browser tab management |
| `core-input` | Input handling and form interaction |
| `core-install` | Browser installation |
| `network` | Network request interception |
| `pdf` | PDF generation and manipulation |
| `storage` | Local storage and session management |
| `testing` | Test-related utilities |
| `vision` | Coordinate-based interactions |
| `devtools` | Developer tools features |
| `config` | Configuration management |

### Browser Configuration

```typescript
browser?: {
  browserName?: 'chromium' | 'firefox' | 'webkit';
  isolated?: boolean;
  userDataDir?: string;
  launchOptions?: object;
}
```

资料来源：[config.d.ts:32-56](https://github.com/microsoft/playwright-mcp/blob/main/config.d.ts)

### Timeout Configuration

```typescript
timeouts?: {
  action?: number;      // Default: 5000ms
  navigation?: number;  // Default: 60000ms
  expect?: number;       // Default: 5000ms
}
```

资料来源：[config.d.ts:98-110](https://github.com/microsoft/playwright-mcp/blob/main/config.d.ts)

### Server Configuration

```typescript
server?: {
  port?: number;
  host?: string;
  allowedHosts?: string[];
}
```

资料来源：[config.d.ts:146-156](https://github.com/microsoft/playwright-mcp/blob/main/config.d.ts)

## Architecture

```mermaid
graph TD
    A[Client Application] -->|MCP Protocol| B[playwright-mcp]
    B --> C[createConnection]
    C --> D[playwright-core]
    D --> E[Browser Automation]
    E --> F[Chromium]
    E --> G[Firefox]
    E --> H[WebKit]
    
    I[CLI User] -->|cli.js| B
    J[Module User] -->|index.js| B
```

## Available NPM Scripts

The `package.json` defines the following scripts for working with Playwright MCP:

| Script | Command | Purpose |
|--------|---------|---------|
| `test` | `playwright test` | Run all tests |
| `ctest` | `playwright test --project=chrome` | Run Chrome-only tests |
| `ftest` | `playwright test --project=firefox` | Run Firefox-only tests |
| `wtest` | `playwright test --project=webkit` | Run WebKit-only tests |
| `lint` | `node update-readme.js` | Regenerate README |
| `build` | `echo OK` | Build step (no-op) |
| `roll` | `node roll.js` | Update Playwright version |

资料来源：[package.json:13-24](https://github.com/microsoft/playwright-mcp/blob/main/package.json)

## Package Metadata

| Property | Value |
|----------|-------|
| Package Name | `@playwright/mcp` |
| MCP Name | `io.github.microsoft/playwright-mcp` |
| Node.js Requirement | `>=18` |
| License | Apache-2.0 |

资料来源：[package.json:1-16](https://github.com/microsoft/playwright-mcp/blob/main/package.json)

## Browser Installation

Playwright MCP supports an `install-browser` command through the CLI:

```bash
node cli.js install-browser
```

This delegates to Playwright's browser installation mechanism, decorated via `libCli.decorateProgram`.

资料来源：[cli.js:17-22](https://github.com/microsoft/playwright-mcp/blob/main/cli.js)

## Extension Mode

Playwright MCP supports connecting to a running browser instance through the Microsoft Edge/Chrome Playwright Extension:

```typescript
extension?: boolean;
```

When enabled, this allows connection to an existing browser instance rather than launching a new one.

资料来源：[config.d.ts:134-140](https://github.com/microsoft/playwright-mcp/blob/main/config.d.ts)

## Network Configuration

Control browser network access through origin-based filtering:

```typescript
network?: {
  allowedOrigins?: string[];   // List of allowed origins
  blockedOrigins?: string[];   // List of blocked origins
}
```

Supported formats:
- Full origin: `https://example.com:8080`
- Wildcard port: `http://localhost:*`

资料来源：[config.d.ts:190-204](https://github.com/microsoft/playwright-mcp/blob/main/config.d.ts)

## Session Management

| Option | Type | Description |
|--------|------|-------------|
| `saveSession` | boolean | Save Playwright session to output directory |
| `sharedBrowserContext` | boolean | Reuse browser context across HTTP clients |

资料来源：[config.d.ts:166-173](https://github.com/microsoft/playwright-mcp/blob/main/config.d.ts)

## Console Configuration

```typescript
console?: {
  level?: 'error' | 'warning' | 'info' | 'debug';
}
```

资料来源：[config.d.ts:182-187](https://github.com/microsoft/playwright-mcp/blob/main/config.d.ts)

---

<a id='user-profiles'></a>

## User Profiles and Session Management

### 相关页面

相关主题：[Browser Configuration](#browser-configuration), [Troubleshooting](#troubleshooting)

<details>
<summary>Relevant Source Files</summary>

The following source files were used to generate this page:

- [config.d.ts](https://github.com/microsoft/playwright-mcp/blob/main/config.d.ts)
- [package.json](https://github.com/microsoft/playwright-mcp/blob/main/package.json)
- [server.json](https://github.com/microsoft/playwright-mcp/blob/main/server.json)
- [cli.js](https://github.com/microsoft/playwright-mcp/blob/main/cli.js)
- [roll.js](https://github.com/microsoft/playwright-mcp/blob/main/roll.js)
- [CONTRIBUTING.md](https://github.com/microsoft/playwright-mcp/blob/main/CONTRIBUTING.md)
</details>

# User Profiles and Session Management

## Overview

User Profiles and Session Management in Playwright MCP controls how browser instances are created, persisted, and shared across multiple HTTP clients and tool invocations. This system enables sophisticated browser automation scenarios while maintaining security and resource efficiency.

The MCP server supports:
- **Isolated browser instances** per request
- **Persistent user data directories** for profile retention
- **Shared browser contexts** across clients
- **Session saving and restoration**
- **Secrets masking** in responses

资料来源：[config.d.ts:22-40]()

## Architecture

```mermaid
graph TD
    A[MCP Client] -->|HTTP/STDIO| B[Playwright MCP Server]
    B --> C[Browser Manager]
    C --> D{Shared Context?}
    D -->|Yes| E[Single Browser Context]
    D -->|No| F[Per-Client Context]
    E --> G[Browser Instance]
    F --> G
    G --> H[User Data Directory]
    G --> I[Session Files]
    H -->|Persistence| J[Output Directory]
```

### Core Components

| Component | Purpose | Configuration Key |
|-----------|---------|-------------------|
| Browser Manager | Creates and manages browser instances | `browser.*` |
| Session Manager | Handles session save/restore | `saveSession` |
| Context Pool | Manages shared vs isolated contexts | `sharedBrowserContext` |
| Secrets Handler | Masks sensitive data in responses | `secrets` |

资料来源：[config.d.ts:1-50]()

## Browser Configuration

### Browser Type Selection

The MCP server supports three browser engines:

```typescript
browser?: {
  browserName?: 'chromium' | 'firefox' | 'webkit';
}
```

| Browser | Engine | Use Case |
|---------|--------|----------|
| `chromium` | Blink | General automation, Chrome/Edge compatibility |
| `firefox` | Gecko | Cross-browser testing, Firefox-specific features |
| `webkit` | WebKit | Safari compatibility testing |

资料来源：[config.d.ts:24-30]()

### User Data Directory

The user data directory stores browser profile data including cookies, local storage, and session state.

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

**Behavior:**
- When `userDataDir` is unspecified, a temporary directory is created automatically
- Persistent directories survive browser restarts
- Useful for maintaining login sessions across tool invocations

资料来源：[config.d.ts:38-43]()

### Isolated Mode

When `isolated: true`, browser profiles are kept entirely in memory without disk persistence.

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

| Mode | Persistence | Security | Performance |
|------|-------------|----------|-------------|
| `isolated: true` | Memory only | Higher | Faster startup |
| `isolated: false` | Disk (userDataDir) | Standard | Slower startup |

资料来源：[config.d.ts:32-37]()

## Session Management

### Session Saving

The `saveSession` option controls whether Playwright sessions are persisted to the output directory.

```typescript
export type Config = {
  /**
   * Whether to save the Playwright session into the output directory.
   */
  saveSession?: boolean;
}
```

**Use cases:**
- Debugging failed automation workflows
- Resuming interrupted sessions
- Analyzing browser state post-execution

资料来源：[config.d.ts:83-87]()

### Output Directory

Sessions and output files are saved to the configured output directory.

```typescript
export type Config = {
  /**
   * The directory to save output files.
   */
  outputDir?: string;
}
```

**Default behavior:** If not specified, the MCP server uses a platform-specific temporary directory.

资料来源：[config.d.ts:95-99]()

## Browser Context Management

### Shared Browser Context

When multiple HTTP clients connect to the MCP server, `sharedBrowserContext` determines whether they share a single browser context or receive isolated contexts.

```typescript
export type Config = {
  /**
   * Reuse the same browser context between all connected HTTP clients.
   */
  sharedBrowserContext?: boolean;
}
```

```mermaid
graph LR
    A[Client 1] -->|MCP| B{sharedBrowserContext}
    C[Client 2] -->|MCP| B
    D[Client N] -->|MCP| B
    
    B -->|true| E[Shared Context]
    B -->|false| F[Client 1 Context]
    B -->|false| G[Client 2 Context]
    B -->|false| H[Client N Context]
```

| Setting | Pros | Cons |
|---------|------|------|
| `sharedBrowserContext: true` | Resource efficient, shared cookies/auth | State bleeding between clients |
| `sharedBrowserContext: false` | Complete isolation | Higher resource usage |

资料来源：[config.d.ts:89-94]()

## Secrets Management

The secrets system prevents sensitive data from being exposed to LLM clients.

```typescript
export type Config = {
  /**
   * 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>;
}
```

**Key characteristics:**
- **Not a security feature** - Use proper authentication for actual security
- Pattern matching replaces plain text in responses
- Prevents LLM accidental exposure of sensitive information

资料来源：[config.d.ts:100-106]()

## Configuration Schema

### Complete Config Type

```typescript
export type Config = {
  browser?: {
    browserName?: 'chromium' | 'firefox' | 'webkit';
    isolated?: boolean;
    userDataDir?: string;
    // ... launch options
  };
  
  capabilities?: ToolCapability[];
  saveSession?: boolean;
  sharedBrowserContext?: boolean;
  secrets?: Record<string, string>;
  outputDir?: string;
  
  console?: {
    level?: 'error' | 'warning' | 'info' | 'debug';
  };
  
  network?: {
    allowedOrigins?: string[];
    blockedOrigins?: string[];
  };
  
  testIdAttribute?: string;
  
  timeouts?: {
    action?: number;
    navigation?: number;
    expect?: number;
  };
  
  imageResponses?: 'allow' | 'omit';
  
  // ... additional options
};
```

资料来源：[config.d.ts:1-180]()

## Tool Capabilities

The MCP server exposes browser automation through categorized tool capabilities:

| Capability | Description |
|------------|-------------|
| `config` | Configuration management |
| `core` | Core browser automation |
| `core-navigation` | Page navigation and routing |
| `core-tabs` | Tab/window management |
| `core-input` | Form input handling |
| `core-install` | Browser installation |
| `network` | Network request interception |
| `pdf` | PDF generation |
| `storage` | Storage management |
| `testing` | Test-related tools |
| `vision` | Coordinate-based interactions |
| `devtools` | Developer tools features |

资料来源：[config.d.ts:13-26]()

## Server Configuration

The MCP server uses STDIO transport by default for optimal integration with MCP clients.

```json
{
  "name": "io.github.microsoft/playwright-mcp",
  "description": "Playwright Tools for MCP",
  "version": "0.0.75",
  "packages": [
    {
      "registryType": "npm",
      "identifier": "@playwright/mcp",
      "version": "0.0.75",
      "transport": {
        "type": "stdio"
      }
    }
  ]
}
```

资料来源：[server.json:1-15]()

## CLI Options

The MCP server can be configured via command-line arguments:

```bash
node cli.js --help
```

Key CLI commands:
- `install-browser` - Install required browser binaries
- Standard Playwright CLI options for browser management

资料来源：[cli.js:1-35]()

## Best Practices

### Security Recommendations

1. **Do not rely on secrets masking for security** - Treat it as UI/UX convenience only
2. **Use isolated mode** for untrusted content
3. **Configure network restrictions** using `allowedOrigins` and `blockedOrigins`

### Performance Optimization

| Scenario | Recommended Setting |
|----------|---------------------|
| Single client, high throughput | `sharedBrowserContext: true` |
| Multiple clients requiring isolation | `sharedBrowserContext: false` |
| Resource-constrained environment | `isolated: true` |
| Need session persistence | `saveSession: true`, specify `outputDir` |

### Testing Workflow

For testing MCP functionality:

```bash
# Fast path - Chromium only
npm run ctest

# Full test suite - All browsers
npm run mcp-test

# Docker environment
npm run dtest
```

资料来源：[package.json:18-25]()

## Rolling Updates

The Playwright version can be updated while maintaining configuration compatibility:

```bash
npm run roll
```

This command:
1. Updates `playwright`, `playwright-core`, and `@playwright/test` versions
2. Refreshes `config.d.ts` from the Playwright monorepo
3. Regenerates the README documentation

资料来源：[roll.js:1-40](), [CLAUDE.md:1-35]()

---

<a id='troubleshooting'></a>

## Troubleshooting

### 相关页面

相关主题：[User Profiles and Session Management](#user-profiles), [Browser Configuration](#browser-configuration)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [CLAUDE.md](https://github.com/microsoft/playwright-mcp/blob/main/CLAUDE.md)
- [CONTRIBUTING.md](https://github.com/microsoft/playwright-mcp/blob/main/CONTRIBUTING.md)
- [package.json](https://github.com/microsoft/playwright-mcp/blob/main/package.json)
- [playwright.config.ts](https://github.com/microsoft/playwright-mcp/blob/main/playwright.config.ts)
- [cli.js](https://github.com/microsoft/playwright-mcp/blob/main/cli.js)
</details>

# Troubleshooting

This page documents common issues, debugging strategies, and resolution steps when working with Playwright MCP.

## Overview

Troubleshooting in Playwright MCP primarily involves:

- Test execution failures
- Browser launch and context issues
- MCP tool invocation problems
- Configuration mismatches
- Dependency and version compatibility

## Common Issues and Resolutions

### Test Failures

#### All Tests Failing

If all tests fail, verify the test environment is properly configured:

```bash
# Ensure dependencies are installed
npm ci

# Install Playwright browsers
npx playwright install

# Run tests in a single browser (faster feedback)
npm run ctest
```

**Source:** [package.json:11](https://github.com/microsoft/playwright-mcp/blob/main/package.json#L11)

#### Cross-Browser Test Inconsistencies

Playwright MCP tests run in Chromium, Firefox, and WebKit. If failures occur in specific browsers:

```bash
# Test individual browsers
npm run ctest   # Chrome only
npm run ftest   # Firefox only
npm run wtest   # WebKit only
```

Tests should be hermetic and work on all three platforms: macOS, Linux, and Windows. 资料来源：[CONTRIBUTING.md:71-72](https://github.com/microsoft/playwright-mcp/blob/main/CONTRIBUTING.md#L71-L72)

### Browser Launch Issues

#### Persistent Context Problems

The `isolated` option controls whether browser profiles are saved to disk:

```typescript
{
  browser: {
    isolated: true   // Keeps profile in memory
  }
}
```

Default behavior creates temporary directories for user data. 资料来源：[config.d.ts:35-38](https://github.com/microsoft/playwright-mcp/blob/main/config.d.ts#L35-L38)

#### Network Requests Blocked

Configure allowed and blocked origins in the `network` section:

```typescript
{
  network: {
    allowedOrigins: ['https://example.com:8080'],
    blockedOrigins: ['https://ads.example.com']
  }
}
```

Origins matching both lists will be blocked. 资料来源：[config.d.ts:100-112](https://github.com/microsoft/playwright-mcp/blob/main/config.d.ts#L100-L112)

### MCP Tool Invocation Errors

#### Tool Not Found

MCP tools are exposed through the connection interface. Ensure the server is properly initialized:

```javascript
const { createConnection } = require('@playwright/mcp');
```

The `createConnection` function is exported from the core bundle. 资料来源：[index.js:27-28](https://github.com/microsoft/playwright-mcp/blob/main/index.js#L27-L28)

### Configuration Schema Errors

TypeScript errors related to `Config` type indicate schema mismatches. The `config.d.ts` file defines the expected structure:

```typescript
export type Config = {
  browser?: { ... };
  timeouts?: { ... };
  capabilities?: ToolCapability[];
  secrets?: Record<string, string>;
  outputDir?: string;
  console?: { level?: 'error' | 'warning' | 'info' | 'debug' };
  network?: { allowedOrigins?: string[]; blockedOrigins?: string[] };
}
```

## Debugging Strategies

### Enabling Debug Logs

Configure console log levels to control verbosity:

```typescript
{
  console: {
    level: 'debug'  // 'error' | 'warning' | 'info' | 'debug'
  }
}
```

Default level is `'info'`. 资料来源：[config.d.ts:88-91](https://github.com/microsoft/playwright-mcp/blob/main/config.d.ts#L88-L91)

### Timeouts Configuration

Adjust timeouts for slow environments:

```typescript
{
  timeouts: {
    action: 10000,     // Default: 5000ms
    navigation: 120000, // Default: 60000ms
    expect: 10000      // Default: 5000ms
  }
}
```

资料来源：[config.d.ts:64-77](https://github.com/microsoft/playwright-mcp/blob/main/config.d.ts#L64-L77)

### Saving Sessions for Analysis

Enable `saveSession` to persist Playwright session data for debugging:

```typescript
{
  saveSession: true
}
```

Sessions are saved to the configured `outputDir`. 资料来源：[config.d.ts:81-84](https://github.com/microsoft/playwright-mcp/blob/main/config.d.ts#L81-L84)

## Docker Environment Issues

When running tests in Docker containers:

```bash
# Build Docker image
npm run docker-build

# Run container
npm run docker-run

# Execute tests in Docker
npm run dtest
```

Docker tests run with `MCP_IN_DOCKER=1` environment variable. 资料来源：[package.json:16-18](https://github.com/microsoft/playwright-mcp/blob/main/package.json#L16-L18)

## Version Rollback Problems

If rolling Playwright causes issues:

1. The `roll.js` script updates dependencies and regenerates configuration
2. After running `npm run roll`, always run tests before committing

```bash
npm run roll
npm test  # Must pass before proceeding
```

If tests fail after a roll, revert changes and investigate the version bump. 资料来源：[CLAUDE.md:12-14](https://github.com/microsoft/playwright-mcp/blob/main/CLAUDE.md#L12-L14)

## Contributing Troubleshooting

### PR Closed Without Review

> **Unsolicited PRs:** Pull requests submitted without a linked issue or prior approval will be closed. 资料来源：[CONTRIBUTING.md:29-30](https://github.com/microsoft/playwright-mcp/blob/main/CONTRIBUTING.md#L29-L30)

Always file an issue first before submitting changes.

### Linting Failures

Run the linter before submitting:

```bash
npm run lint
```

This also regenerates the README documentation. 资料来源：[package.json:9](https://github.com/microsoft/playwright-mcp/blob/main/package.json#L9)

## Workflow Diagram

```mermaid
graph TD
    A[Start] --> B{Issue?</B]
    B -->|Yes| C[File GitHub Issue]
    B -->|No| D[Check Existing Issues]
    C --> E{Assigned?}
    D --> E
    E -->|Yes| F[Create Branch]
    E -->|No| G[Wait for Assignment]
    G --> E
    F --> H[Make Changes]
    H --> I[Add Tests]
    I --> J[Run Tests]
    J -->|Pass| K[Run Linter]
    J -->|Fail| L[Debug & Fix]
    L --> J
    K -->|Pass| M[Commit Changes]
    K -->|Fail| N[Fix Lint Errors]
    N --> K
    M --> O[Open PR]
```

## Quick Reference Commands

| Command | Purpose | Source |
|---------|---------|--------|
| `npm test` | Run all tests | [package.json:10](https://github.com/microsoft/playwright-mcp/blob/main/package.json#L10) |
| `npm run ctest` | Chrome-only tests | [package.json:11](https://github.com/microsoft/playwright-mcp/blob/main/package.json#L11) |
| `npm run lint` | Regenerate docs | [package.json:9](https://github.com/microsoft/playwright-mcp/blob/main/package.json#L9) |
| `npm run roll` | Bump Playwright version | [package.json:20](https://github.com/microsoft/playwright-mcp/blob/main/package.json#L20) |
| `npm run docker-build` | Build Docker image | [package.json:17](https://github.com/microsoft/playwright-mcp/blob/main/package.json#L17) |

## Getting Help

If issues persist after following this guide:

1. Search existing [GitHub Issues](https://github.com/microsoft/playwright-mcp/issues)
2. Check the [Playwright Documentation](https://playwright.dev/docs)
3. Review the [main Playwright repository](https://github.com/microsoft/playwright) for upstream issues

The core of Playwright MCP was moved to the [Playwright monorepo](https://github.com/microsoft/playwright). 资料来源：[CONTRIBUTING.md:23-24](https://github.com/microsoft/playwright-mcp/blob/main/CONTRIBUTING.md#L23-L24)

---

---

## Doramagic 踩坑日志

项目：microsoft/playwright-mcp

摘要：发现 21 个潜在踩坑项，其中 0 个为 high/blocking；最高优先级：身份坑 - 仓库名和安装名不一致。

## 1. 身份坑 · 仓库名和安装名不一致

- 严重度：medium
- 证据强度：runtime_trace
- 发现：仓库名 `playwright-mcp` 与安装入口 `@playwright/mcp@latest` 不完全一致。
- 对用户的影响：用户照着仓库名搜索包或照着包名找仓库时容易走错入口。
- 建议检查：在 npm/PyPI/GitHub 上确认包名映射和官方 README 说明。
- 复现命令：`npx @playwright/mcp@latest`
- 防护动作：页面必须同时展示 repo 名和真实安装入口，避免用户搜索错包。
- 证据：identity.distribution | github_repo:952688112 | https://github.com/microsoft/playwright-mcp | repo=playwright-mcp; install=@playwright/mcp@latest

## 2. 安装坑 · 来源证据：Bad entrypoint in docker example

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Bad entrypoint in docker example
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_948f818745694481b19e883b3992d78b | https://github.com/microsoft/playwright-mcp/issues/1609 | 来源讨论提到 node 相关条件，需在安装/试用前复核。

## 3. 安装坑 · 来源证据：v0.0.72

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：v0.0.72
- 对用户的影响：可能阻塞安装或首次运行。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_2e67eb76e3c643e0a52a97e42eca4cb8 | https://github.com/microsoft/playwright-mcp/releases/tag/v0.0.72 | 来源类型 github_release 暴露的待验证使用条件。

## 4. 配置坑 · 来源证据：v0.0.69

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：v0.0.69
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_6767d649d4934031b85ab0c5ffc2b324 | https://github.com/microsoft/playwright-mcp/releases/tag/v0.0.69 | 来源讨论提到 node 相关条件，需在安装/试用前复核。

## 5. 配置坑 · 来源证据：v0.0.71

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：v0.0.71
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_d5bcb1704c0e4a6fb375b18cda153fdd | https://github.com/microsoft/playwright-mcp/releases/tag/v0.0.71 | 来源类型 github_release 暴露的待验证使用条件。

## 6. 配置坑 · 来源证据：v0.0.73

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：v0.0.73
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_a0d6aead61ad4c52ab738c6b556f2e27 | https://github.com/microsoft/playwright-mcp/releases/tag/v0.0.73 | 来源类型 github_release 暴露的待验证使用条件。

## 7. 能力坑 · 能力判断依赖假设

- 严重度：medium
- 证据强度：source_linked
- 发现：README/documentation is current enough for a first validation pass.
- 对用户的影响：假设不成立时，用户拿不到承诺的能力。
- 建议检查：将假设转成下游验证清单。
- 防护动作：假设必须转成验证项；没有验证结果前不能写成事实。
- 证据：capability.assumptions | github_repo:952688112 | https://github.com/microsoft/playwright-mcp | README/documentation is current enough for a first validation pass.

## 8. 运行坑 · 来源证据：[Bug] Running multiple parallel async browsers in --isolated mode leaves orphan browsers. This has started happening af…

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个运行相关的待验证问题：[Bug] Running multiple parallel async browsers in --isolated mode leaves orphan browsers. This has started happening after Release v0.0.69.
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_e8f29958fbbe48ce8381daa23333bdf4 | https://github.com/microsoft/playwright-mcp/issues/1607 | 来源讨论提到 python 相关条件，需在安装/试用前复核。

## 9. 运行坑 · 来源证据：v0.0.67

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个运行相关的待验证问题：v0.0.67
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_3b13c720c21346bab9c08783c91acb95 | https://github.com/microsoft/playwright-mcp/releases/tag/v0.0.67 | 来源类型 github_release 暴露的待验证使用条件。

## 10. 运行坑 · 来源证据：v0.0.68

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个运行相关的待验证问题：v0.0.68
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_c53eae5fa6a94d2e86bc60cf6b164d16 | https://github.com/microsoft/playwright-mcp/releases/tag/v0.0.68 | 来源类型 github_release 暴露的待验证使用条件。

## 11. 运行坑 · 来源证据：v0.0.74

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个运行相关的待验证问题：v0.0.74
- 对用户的影响：可能阻塞安装或首次运行。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_2c41b3bf29434fb48d51cb9ffc766fc2 | https://github.com/microsoft/playwright-mcp/releases/tag/v0.0.74 | 来源类型 github_release 暴露的待验证使用条件。

## 12. 运行坑 · 来源证据：v0.0.75

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个运行相关的待验证问题：v0.0.75
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_4e21e73e13dc471f90365f431d541143 | https://github.com/microsoft/playwright-mcp/releases/tag/v0.0.75 | 来源类型 github_release 暴露的待验证使用条件。

## 13. 维护坑 · 维护活跃度未知

- 严重度：medium
- 证据强度：source_linked
- 发现：未记录 last_activity_observed。
- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。
- 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。
- 防护动作：维护活跃度未知时，推荐强度不能标为高信任。
- 证据：evidence.maintainer_signals | github_repo:952688112 | https://github.com/microsoft/playwright-mcp | last_activity_observed missing

## 14. 安全/权限坑 · 下游验证发现风险项

- 严重度：medium
- 证据强度：source_linked
- 发现：no_demo
- 对用户的影响：下游已经要求复核，不能在页面中弱化。
- 建议检查：进入安全/权限治理复核队列。
- 防护动作：下游风险存在时必须保持 review/recommendation 降级。
- 证据：downstream_validation.risk_items | github_repo:952688112 | https://github.com/microsoft/playwright-mcp | no_demo; severity=medium

## 15. 安全/权限坑 · 存在评分风险

- 严重度：medium
- 证据强度：source_linked
- 发现：no_demo
- 对用户的影响：风险会影响是否适合普通用户安装。
- 建议检查：把风险写入边界卡，并确认是否需要人工复核。
- 防护动作：评分风险必须进入边界卡，不能只作为内部分数。
- 证据：risks.scoring_risks | github_repo:952688112 | https://github.com/microsoft/playwright-mcp | no_demo; severity=medium

## 16. 安全/权限坑 · 来源证据：VS Code installation buttons don't seem to work

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：VS Code installation buttons don't seem to work
- 对用户的影响：可能影响授权、密钥配置或安全边界。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_37c3461084f34d05856db207d12f8d9a | https://github.com/microsoft/playwright-mcp/issues/1608 | 来源类型 github_issue 暴露的待验证使用条件。

## 17. 安全/权限坑 · 来源证据：[Bug]: Windows taskkill output can pollute MCP stdio transport

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：[Bug]: Windows taskkill output can pollute MCP stdio transport
- 对用户的影响：可能影响授权、密钥配置或安全边界。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_789c261c74274d9d9a84d4b1fbf30d14 | https://github.com/microsoft/playwright-mcp/issues/1611 | 来源讨论提到 windows 相关条件，需在安装/试用前复核。

## 18. 安全/权限坑 · 来源证据：[Disclosure] Clarify browser/network action boundary in Playwright MCP server docs

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：[Disclosure] Clarify browser/network action boundary in Playwright MCP server docs
- 对用户的影响：可能影响授权、密钥配置或安全边界。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_fc2b3d242d67495f81f1bb1877e22f84 | https://github.com/microsoft/playwright-mcp/issues/1617 | 来源类型 github_issue 暴露的待验证使用条件。

## 19. 安全/权限坑 · 来源证据：[Feature Request] Support clientCertificates option for mTLS authentication

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：[Feature Request] Support clientCertificates option for mTLS authentication
- 对用户的影响：可能影响授权、密钥配置或安全边界。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_b6f82bec73944aa5869030ad7db55b0c | https://github.com/microsoft/playwright-mcp/issues/1456 | 来源类型 github_issue 暴露的待验证使用条件。

## 20. 维护坑 · issue/PR 响应质量未知

- 严重度：low
- 证据强度：source_linked
- 发现：issue_or_pr_quality=unknown。
- 对用户的影响：用户无法判断遇到问题后是否有人维护。
- 建议检查：抽样最近 issue/PR，判断是否长期无人处理。
- 防护动作：issue/PR 响应未知时，必须提示维护风险。
- 证据：evidence.maintainer_signals | github_repo:952688112 | https://github.com/microsoft/playwright-mcp | issue_or_pr_quality=unknown

## 21. 维护坑 · 发布节奏不明确

- 严重度：low
- 证据强度：source_linked
- 发现：release_recency=unknown。
- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。
- 建议检查：确认最近 release/tag 和 README 安装命令是否一致。
- 防护动作：发布节奏未知或过期时，安装说明必须标注可能漂移。
- 证据：evidence.maintainer_signals | github_repo:952688112 | https://github.com/microsoft/playwright-mcp | release_recency=unknown

<!-- canonical_name: microsoft/playwright-mcp; human_manual_source: deepwiki_human_wiki -->
