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

生成时间：2026-05-15 13:16:39 UTC

## 目录

- [Project Introduction](#project-introduction)
- [Getting Started](#getting-started)
- [Architecture Overview](#architecture-overview)
- [Transport Modes](#transport-modes)
- [Browser Automation Tools](#browser-automation)
- [Device Emulation](#device-emulation)
- [API Testing Tools](#api-testing)
- [Code Generation and Recording](#code-generation)
- [Docker Deployment](#docker-deployment)
- [Configuration Guide](#configuration)

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

## Project Introduction

### 相关页面

相关主题：[Getting Started](#getting-started), [Architecture Overview](#architecture-overview)

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

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

- [README.md](https://github.com/executeautomation/mcp-playwright/blob/main/README.md)
- [package.json](https://github.com/executeautomation/mcp-playwright/blob/main/package.json)
- [CHANGELOG.md](https://github.com/executeautomation/mcp-playwright/blob/main/CHANGELOG.md)
- [DOCKER.md](https://github.com/executeautomation/mcp-playwright/blob/main/DOCKER.md)
- [examples/http-mode-example.md](https://github.com/executeautomation/mcp-playwright/blob/main/examples/http-mode-example.md)
</details>

# Project Introduction

The **Playwright MCP Server** (`mcp-playwright`) is a Model Context Protocol (MCP) server implementation that provides browser automation capabilities through Playwright. It enables AI assistants like Claude, Cursor, and other MCP-compatible clients to interact with web pages through a standardized tool interface.

## Overview

The project serves as a bridge between AI assistants and browser automation, exposing Playwright's browser control capabilities as MCP tools. This allows AI agents to perform web navigation, content extraction, form interactions, and other browser-related tasks using natural language commands.

**Key Characteristics:**

| Attribute | Value |
|-----------|-------|
| Project Name | mcp-playwright |
| Package Name | @executeautomation/playwright-mcp-server |
| License | MIT |
| Node.js Version | 20+ |
| Protocol | Model Context Protocol (MCP) |

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

## Architecture

The server follows a client-server architecture where AI assistants act as MCP clients communicating with the Playwright MCP server.

```mermaid
graph TD
    A["AI Assistant<br/>(Claude, Cursor, etc.)"] -->|MCP Protocol| B["Playwright MCP Server"]
    B -->|stdin/stdout| A
    B -->|HTTP/SSE| B
    C["Browser Instances<br/>(Chromium, Firefox, WebKit)"] -->|Playwright API| B
    
    B -->|Browser Automation| C
    C -->|Page Content| B
    B -->|Tool Results| A
```

### Core Components

| Component | Purpose |
|-----------|---------|
| MCP SDK | Handles MCP protocol communication |
| Tool Handlers | Processes tool calls and executes Playwright operations |
| Browser Manager | Manages browser lifecycle and instances |
| Logging System | Captures request/response data and error tracking |

资料来源：[src/logging/middleware.ts:1-20]()

## Installation Methods

The project supports multiple installation approaches to accommodate different deployment scenarios.

### Package Managers

```bash
# npm
npm install -g @executeautomation/playwright-mcp-server

# mcp-get
npx @michaellatman/mcp-get@latest install @executeautomation/playwright-mcp-server

# Smithery (automated)
npx @smithery/cli install @executeautomation/playwright-mcp-server --client claude
```

### Claude Code

```bash
claude mcp add --transport stdio playwright npx @executeautomation/playwright-mcp-server
```

资料来源：[README.md:40-65]()

## Operation Modes

The server supports two primary operation modes based on the transport mechanism.

### STDIO Mode (Default)

STDIO mode is the recommended configuration for Claude Desktop and other clients that communicate via standard input/output streams.

```mermaid
graph LR
    A["MCP Client"] -->|"stdio"| B["Playwright MCP Server"]
    B -->|"stdio"| A
    C["Playwright<br/>Browser"] -->|Control| B
```

**Configuration Example:**

```json
{
  "mcpServers": {
    "playwright": {
      "command": "npx",
      "args": ["-y", "@executeautomation/playwright-mcp-server"]
    }
  }
}
```

> **Note:** In stdio mode, logging is automatically directed to files only to maintain clean JSON-RPC communication. Logs are written to `~/playwright-mcp-server.log`.

资料来源：[README.md:20-30]()

### HTTP Mode (Standalone Server)

HTTP mode enables the server to run as a standalone HTTP server, suitable for VS Code, custom clients, and remote deployments.

```bash
npx @executeautomation/playwright-mcp-server --port 8931
```

**Available Endpoints:**

| Endpoint | Method | Purpose |
|----------|--------|---------|
| `/sse` | GET | SSE Stream for server-sent events |
| `/messages?sessionId=<id>` | POST | Send messages to a session |
| `/mcp` | GET/POST | Unified MCP protocol endpoint |
| `/health` | GET | Health check endpoint |

**Client Configuration:**

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

资料来源：[README.md:35-55]()
资料来源：[examples/http-mode-example.md:1-30]()

## Docker Deployment

The project provides official Docker images for containerized deployments.

### Basic Usage

```bash
docker run -i --rm mcp-playwright:latest
```

### Docker Configuration

```json
{
  "mcpServers": {
    "playwright-docker": {
      "command": "docker",
      "args": ["run", "-i", "--rm", "mcp-playwright:latest"]
    }
  }
}
```

### Environment Variables

| Variable | Purpose | Default |
|----------|---------|---------|
| `PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD` | Skip browser installation | 1 |
| `NODE_ENV` | Node environment | production |

### Volume Mounts

```bash
docker run -i --rm \
  -v $(pwd)/data:/app/data \
  -v $(screenshots):/app/screenshots \
  mcp-playwright:latest
```

> **Note:** The Docker image skips browser downloads by default to reduce size (~200MB). Browsers are downloaded on first use.

资料来源：[DOCKER.md:1-80]()

## Supported Tools

The server exposes a comprehensive set of Playwright operations as MCP tools.

### Browser Control Tools

| Tool Category | Tools | Description |
|---------------|-------|-------------|
| Navigation | `playwright_navigate` | Navigate to URLs with multi-browser support |
| Interaction | `playwright_click`, `playwright_drag`, `playwright_press_key` | Element interactions |
| Content | `playwright_get_visible_text`, `playwright_get_visible_html` | Content extraction |
| Output | `playwright_save_as_pdf` | Page to PDF conversion |

### Browser Support

| Browser | Support |
|---------|---------|
| Chromium | ✅ Default |
| Firefox | ✅ Since v1.0.2 |
| WebKit | ✅ Since v1.0.2 |

资料来源：[CHANGELOG.md:1-30]()

## Dependencies

### Production Dependencies

| Package | Version | Purpose |
|---------|---------|---------|
| `@modelcontextprotocol/sdk` | 1.24.3 | MCP protocol implementation |
| `playwright` | 1.57.0 | Browser automation framework |
| `@playwright/browser-chromium` | 1.57.0 | Chromium browser |
| `@playwright/browser-firefox` | 1.57.0 | Firefox browser |
| `@playwright/browser-webkit` | 1.57.0 | WebKit browser |
| `express` | ^4.21.1 | HTTP server for HTTP mode |
| `cors` | ^2.8.5 | Cross-origin resource sharing |
| `uuid` | 11.1.0 | Session ID generation |
| `mcp-evals` | ^2.0.1 | Evaluation utilities |

### Development Dependencies

| Package | Version | Purpose |
|---------|---------|---------|
| `typescript` | ^5.8.3 | TypeScript compilation |
| `jest` | ^29.7.0 | Testing framework |
| `jest-playwright-preset` | 4.0.0 | Playwright test integration |
| `ts-jest` | ^29.2.6 | TypeScript Jest transformer |

资料来源：[package.json:20-50]()

## Logging System

The server includes a comprehensive logging system for debugging and monitoring.

### Log Location

- **STDIO Mode:** `~/playwright-mcp-server.log` (file only)
- **HTTP Mode:** Configurable via server settings

### Log Features

| Feature | Description |
|---------|-------------|
| Request Logging | Captures tool execution with sanitized arguments |
| Error Context | Includes stack traces and browser state |
| Log Rotation | Automatic rotation with configurable max files |
| Sensitive Data Redaction | Passwords, tokens, and secrets automatically masked |

资料来源：[src/logging/logger.ts:1-50]()
资料来源：[src/logging/middleware.ts:1-30]()

## Troubleshooting

### Common Issues

| Issue | Solution |
|-------|----------|
| Container exits immediately | Ensure `-i` flag is used for Docker |
| Browser not found | Use custom Dockerfile with `npx playwright install` |
| Permission issues | Use `--user $(id -u):$(id -g)` flag |
| Tool name too long | Keep names under 60 characters (server + tool name) |

> **Important:** When adding new tools, ensure tool names are short enough to not exceed the 60-character limit for combined server and tool name (`server_name:tool_name`). The server name is `playwright-mcp`.

资料来源：[README.md:15-18]()

## Version History

| Version | Date | Key Changes |
|---------|------|-------------|
| 1.0.8 | Current | Latest stable release |
| 1.0.7 | 2024-12 | Advanced screenshot and content tools |
| 1.0.2 | 2024-11-10 | Multi-browser support (Firefox, WebKit) |
| 1.0.0 | 2024-11-01 | First major release with Bearer Auth support |

资料来源：[CHANGELOG.md:1-50]()

## Next Steps

For more detailed information, refer to:

- [Installation Guide](https://executeautomation.github.io/mcp-playwright/) - Detailed setup instructions
- [API Reference](https://executeautomation.github.io/mcp-playwright/docs/playwright-web/Supported-Tools) - Complete tool documentation
- [Device Quick Reference](https://executeautomation.github.io/mcp-playwright/docs/playwright-web/Device-Quick-Reference) - Mobile device emulation
- [Prompt Guide](https://executeautomation.github.io/mcp-playwright/docs/playwright-web/Resize-Prompts-Guide) - Resize prompt strategies

---

<a id='getting-started'></a>

## Getting Started

### 相关页面

相关主题：[Project Introduction](#project-introduction), [Docker Deployment](#docker-deployment), [Configuration Guide](#configuration)

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

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

- [README.md](https://github.com/executeautomation/mcp-playwright/blob/main/README.md)
- [DOCKER.md](https://github.com/executeautomation/mcp-playwright/blob/main/DOCKER.md)
- [examples/http-mode-example.md](https://github.com/executeautomation/mcp-playwright/blob/main/examples/http-mode-example.md)
- [package.json](https://github.com/executeautomation/mcp-playwright/blob/main/package.json)
- [src/http-server.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/http-server.ts)
- [src/logging/logger.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/logging/logger.ts)
</details>

# Getting Started

This guide provides everything you need to install, configure, and run the Playwright MCP Server. The server enables AI assistants like Claude to interact with web browsers through a comprehensive set of automation tools.

## Overview

The Playwright MCP Server is a Model Context Protocol (MCP) server that provides programmatic control over Playwright browsers. It allows AI assistants to perform web automation tasks including navigation, interaction, content extraction, and screenshot capture.

**Key Features:**
- Multi-browser support (Chromium, Firefox, WebKit)
- 143 device presets for mobile emulation
- Screenshot and PDF generation
- Web scraping and content extraction
- Keyboard and mouse automation
- HTTP and stdio communication modes

资料来源：[README.md:1-45]()

## Prerequisites

Before installing the Playwright MCP Server, ensure your system meets these requirements:

| Requirement | Minimum Version | Notes |
|-------------|-----------------|-------|
| Node.js | 20.x or higher | LTS recommended |
| npm | 9.x or higher | Comes with Node.js |
| Docker (optional) | 20.x or higher | For containerized deployment |
| Playwright browsers | Latest | Auto-installed on first use |

**System Dependencies for Playwright:**
- Linux: `npx playwright install-deps`
- macOS: Xcode Command Line Tools
- Windows: Visual Studio Build Tools

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

## Installation Methods

### Method 1: npm Package (Recommended)

Install the package globally for CLI access:

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

Or use it directly with npx (no installation required):

```bash
npx -y @executeautomation/playwright-mcp-server
```

资料来源：[README.md:56-65]()

### Method 2: Docker Container

Pull the pre-built image from Docker Hub:

```bash
docker pull mcp-playwright:latest
```

Or build from source:

```bash
git clone https://github.com/executeautomation/mcp-playwright.git
cd mcp-playwright
docker build -t mcp-playwright:latest .
```

The Docker image is approximately 200MB (without browsers) and uses a Debian-based slim Node.js image.

资料来源：[DOCKER.md:80-100]()

## Configuration

### Claude Desktop

Edit your Claude Desktop configuration file:

**File Locations:**
| OS | Path |
|----|------|
| macOS | `~/Library/Application Support/Claude/claude_desktop_config.json` |
| Windows | `%APPDATA%\Claude\claude_desktop_config.json` |
| Linux | `~/.config/Claude/claude_desktop_config.json` |

**stdio Mode (Default):**
```json
{
  "mcpServers": {
    "playwright": {
      "command": "npx",
      "args": ["-y", "@executeautomation/playwright-mcp-server"]
    }
  }
}
```

资料来源：[README.md:56-65]()

### VS Code MCP Extension

For VS Code with the MCP extension, add this to your MCP settings:

```json
{
  "name": "playwright",
  "command": "npx",
  "args": ["-y", "@executeautomation/playwright-mcp-server"]
}
```

资料来源：[DOCKER.md:12-20]()

### Docker Configuration

**Basic Configuration:**
```json
{
  "mcpServers": {
    "playwright-docker": {
      "command": "docker",
      "args": ["run", "-i", "--rm", "mcp-playwright:latest"]
    }
  }
}
```

**With Environment Variables:**
```bash
docker run -i --rm \
  -e PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 \
  -e NODE_ENV=production \
  mcp-playwright:latest
```

**With Volume Mounts:**
```bash
docker run -i --rm \
  -v $(pwd)/data:/app/data \
  -v $(pwd)/screenshots:/app/screenshots \
  mcp-playwright:latest
```

资料来源：[DOCKER.md:1-50]()

## Running Modes

### stdio Mode (Interactive)

The default mode for Claude Desktop where the server communicates via stdin/stdout:

```bash
# Using npx
npx -y @executeautomation/playwright-mcp-server

# Using global installation
playwright-mcp-server
```

In stdio mode, logs are automatically directed to files only (`~/playwright-mcp-server.log`) to maintain clean JSON-RPC communication.

资料来源：[README.md:56-65]()

### HTTP Mode (Standalone Server)

For VS Code, custom clients, or remote deployments where you need a headed browser:

```bash
# Using npx
npx @executeautomation/playwright-mcp-server --port 8931

# Using global installation
playwright-mcp-server --port 8931
```

**HTTP Mode Endpoints:**

| Endpoint | Method | Description |
|----------|--------|-------------|
| `/sse` | GET | SSE stream for server-sent events |
| `/messages` | POST | Send messages (requires `sessionId` query param) |
| `/mcp` | GET/POST | Unified MCP endpoint |
| `/health` | GET | Health check |

**Security Note:** The HTTP server binds to `localhost` only (127.0.0.1) to prevent external access. For remote access, use SSH tunneling.

资料来源：[README.md:67-90]()
资料来源：[src/http-server.ts:1-50]()

**Claude Desktop HTTP Configuration:**
```json
{
  "mcpServers": {
    "playwright": {
      "url": "http://localhost:8931/mcp"
    }
  }
}
```

资料来源：[examples/http-mode-example.md:1-30]()

## Architecture Overview

```mermaid
graph TD
    subgraph "AI Assistant"
        A[Claude / Cursor / VS Code]
    end
    
    subgraph "MCP Client"
        B[MCP SDK Client]
    end
    
    subgraph "Playwright MCP Server"
        C[Transport Layer]
        D[Tool Handlers]
        E[Browser Manager]
    end
    
    subgraph "Playwright"
        F[Chromium]
        G[Firefox]
        H[WebKit]
    end
    
    A --> B
    B --> C
    C --> D
    D --> E
    E --> F
    E --> G
    E --> H
```

## Available Tools

The server exposes the following tool categories:

### Navigation Tools
| Tool | Description |
|------|-------------|
| `playwright_navigate` | Navigate to a URL with optional browser type |
| `playwright_go_back` | Navigate backward in history |
| `playwright_go_forward` | Navigate forward in history |

### Interaction Tools
| Tool | Description |
|------|-------------|
| `playwright_click` | Click on an element |
| `playwright_fill` | Fill input fields |
| `playwright_press_key` | Press keyboard keys |
| `playwright_drag` | Drag elements |

### Content Tools
| Tool | Description |
|------|-------------|
| `playwright_get_visible_text` | Extract visible text |
| `playwright_get_visible_html` | Get HTML content with filtering options |
| `playwright_evaluate` | Execute JavaScript in browser context |

### Output Tools
| Tool | Description |
|------|-------------|
| `playwright_screenshot` | Capture page screenshots |
| `playwright_save_as_pdf` | Save page as PDF |

### Device Emulation
```javascript
// Test on iPhone 13
await playwright_resize({ device: "iPhone 13" });

// Test on iPad with landscape
await playwright_resize({ device: "iPad Pro 11", orientation: "landscape" });

// Test desktop
await playwright_resize({ device: "Desktop Chrome" });
```

资料来源：[README.md:25-50]()
资料来源：[CHANGELOG.md:1-30]()

## First Steps

### 1. Verify Installation

After configuration, restart your AI client and verify the server is connected:

```
Health check endpoint (HTTP mode):
curl http://localhost:8931/health
```

Expected response:
```json
{
  "status": "ok",
  "version": "1.0.10",
  "activeSessions": 0
}
```

资料来源：[src/http-server.ts:40-48]()

### 2. Basic Browser Operations

Once connected, you can use natural language to control the browser:

```
"Navigate to https://example.com"
"Take a screenshot"
"Click on the login button"
"Fill in the search box with 'test'"
"Get the page title"
```

### 3. Device Emulation

Test responsive designs:

```
"Test on iPhone 13"
"Switch to iPad Pro view"
"Rotate to landscape"
```

资料来源：[README.md:30-45]()

## Troubleshooting

### Container Exits Immediately

MCP servers wait for input on stdin. Ensure you're running with the `-i` flag:

```bash
docker run -i --rm mcp-playwright:latest
```

资料来源：[DOCKER.md:55-60]()

### Browser Not Found

The Docker image skips browser downloads by default. Create a custom Dockerfile:

```dockerfile
FROM mcp-playwright:latest
RUN npx playwright install chromium --with-deps
```

资料来源：[DOCKER.md:65-72]()

### Permission Issues with Volumes

```bash
docker run -i --rm \
  -v $(pwd)/data:/app/data \
  --user $(id -u):$(id -g) \
  mcp-playwright:latest
```

资料来源：[DOCKER.md:75-82]()

### Connection Issues (HTTP Mode)

| Problem | Solution |
|---------|----------|
| Server not starting | Check if port 8931 is available |
| External access blocked | By design - server binds to localhost only |
| Remote access needed | Use SSH tunneling: `ssh -L 8931:localhost:8931 user@remote` |

资料来源：[README.md:103-110]()

## Logging

The server includes comprehensive logging for debugging:

**Log File Location (stdio mode):**
```
~/playwright-mcp-server.log
```

**Logged Information:**
- Tool execution requests and responses
- Error categorization (validation, system, resource)
- Request duration metrics
- Memory and uptime statistics

The logger captures:
- Request IDs for traceability
- Sanitized request bodies (sensitive fields redacted)
- Stack traces for errors
- Platform and environment information

资料来源：[src/logging/logger.ts:1-50]()
资料来源：[src/logging/middleware.ts:1-80]()

## Testing

Run the test suite to verify your installation:

```bash
# Run tests
npm test

# Run tests with coverage
npm run test:coverage

# Run custom tests
npm run test:custom
```

Tests are located in `src/__tests__` and use Jest with Playwright preset.

资料来源：[README.md:113-125]()

## Resource Limits (Docker)

Limit CPU and memory usage:

```bash
docker run -i --rm \
  --cpus="2.0" \
  --memory="2g" \
  mcp-playwright:latest
```

Or in docker-compose.yml:

```yaml
services:
  playwright-mcp:
    deploy:
      resources:
        limits:
          cpus: '2.0'
          memory: 2G
```

资料来源：[DOCKER.md:115-130]()

## Next Steps

| Topic | Description |
|-------|-------------|
| [Device Emulation](docs/playwright-web/Device-Quick-Reference) | Full list of 143 device presets |
| [Docker Deployment](DOCKER.md) | Advanced Docker configuration |
| [HTTP Mode](examples/http-mode-example.md) | Standalone server setup |
| [API Reference](https://executeautomation.github.io/mcp-playwright/) | Complete tool documentation |

---

<a id='architecture-overview'></a>

## Architecture Overview

### 相关页面

相关主题：[Project Introduction](#project-introduction), [Transport Modes](#transport-modes), [Browser Automation Tools](#browser-automation)

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

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

- [src/index.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/index.ts)
- [src/toolHandler.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/toolHandler.ts)
- [src/tools.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools.ts)
- [src/types.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/types.ts)
- [src/requestHandler.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/requestHandler.ts)
</details>

# Architecture Overview

## Introduction

The mcp-playwright project is a Model Context Protocol (MCP) server that exposes Playwright browser automation capabilities to AI assistants such as Claude. The architecture follows a modular, tool-based design pattern where each browser automation operation is exposed as a discrete tool that MCP clients can invoke through JSON-RPC calls.

The server is designed to operate in two distinct transport modes: **stdio mode** for direct integration with MCP clients like Claude Desktop, and **HTTP mode** for remote deployments, VS Code integration, or headless browser scenarios. This dual-mode architecture provides flexibility while maintaining a consistent internal structure for tool registration, execution, and logging.

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

## High-Level Architecture

The architecture consists of four primary layers that work together to process tool requests and execute browser automation tasks.

```mermaid
graph TD
    A[MCP Client<br/>Claude Desktop / VS Code] --> B[Transport Layer<br/>stdio or HTTP]
    B --> C[Request Handler<br/>requestHandler.ts]
    C --> D[Tool Handler<br/>toolHandler.ts]
    D --> E[Tool Registry<br/>tools.ts]
    E --> F[Browser Tools<br/>playwright API]
    F --> G[Chromium / Firefox / WebKit]
```

The **Transport Layer** handles the communication protocol, converting between the client's transport mechanism and the internal request format. The **Request Handler** validates and routes incoming requests to the appropriate tool. The **Tool Handler** manages tool execution, error handling, and response formatting. Finally, the **Browser Tools** layer wraps the Playwright API to provide browser automation capabilities.

资料来源：[src/index.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/index.ts)

## Core Data Structures

The type system defines the fundamental interfaces used throughout the codebase. These types establish the contract between components and ensure type safety across the architecture.

资料来源：[src/types.ts:1-17](https://github.com/executeautomation/mcp-playwright/blob/main/src/types.ts)

### Tool Interface

```typescript
export interface Tool {
  name: string;
  description: string;
  parameters: {
    type: string;
    properties: Record<string, unknown>;
    required?: string[];
  };
  handler: (args: any) => Promise<any>;
}
```

The `Tool` interface represents a single automation capability exposed to MCP clients. Each tool contains a unique `name` identifier, a human-readable `description`, a JSON Schema-compatible `parameters` definition, and an asynchronous `handler` function that executes the actual automation logic.

### ToolCall Interface

```typescript
export interface ToolCall {
  name: string;
  parameters: Record<string, unknown>;
  result?: CallToolResult;
}
```

The `ToolCall` interface tracks the lifecycle of a tool invocation, capturing the tool name, input parameters, and the computed result.

## Request Processing Pipeline

The request processing pipeline transforms incoming MCP requests into executed browser automation operations.

```mermaid
graph LR
    A[Incoming Request] --> B[Parse & Validate]
    B --> C[Route to Tool Handler]
    C --> D[Execute Tool Handler]
    D --> E{Check Result}
    E -->|Success| F[Return CallToolResult]
    E -->|Error| G[Log Error Context]
    G --> H[Return Error Response]
```

### Request Handler Component

The request handler acts as the entry point for all incoming requests. It is responsible for parsing the incoming JSON-RPC messages, validating the request structure, and delegating to the appropriate tool handler.

资料来源：[src/requestHandler.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/requestHandler.ts)

## Tool Registration and Management

The tool registry maintains a collection of all available automation tools. New tools are registered through the `BROWSER_TOOLS` array, which contains all browser-related automation operations.

```mermaid
graph TD
    A[Tool Definition<br/>src/tools/browser/*.ts] --> B[BROWSER_TOOLS Array]
    B --> C[Tool Handler Registration]
    C --> D[MCP Server<br/>Tool List]
```

### Tool Handler

The tool handler manages the execution context for all tools. It provides the following capabilities:

| Capability | Description |
|------------|-------------|
| Tool Registration | Registers tools with the MCP SDK |
| Execution Context | Provides shared state between tool invocations |
| Error Handling | Catches and formats errors from tool execution |
| Logging Integration | Integrates with the logging middleware for observability |

资料来源：[src/toolHandler.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/toolHandler.ts)

### Available Tool Categories

The tools are organized into logical categories based on their function:

| Category | Tools | Purpose |
|----------|-------|---------|
| Navigation | `playwright_navigate`, `playwright_go_back`, `playwright_reload` | Page navigation and history |
| Interaction | `playwright_click`, `playwright_fill`, `playwright_hover`, `playwright_drag` | User interaction simulation |
| Content Extraction | `playwright_get_visible_text`, `playwright_get_visible_html` | Content retrieval |
| Output | `playwright_screenshot`, `playwright_save_as_pdf` | Visual output generation |
| Emulation | `playwright_resize` | Device emulation with 143 presets |

资料来源：[CHANGELOG.md:1-30](https://github.com/executeautomation/mcp-playwright/blob/main/CHANGELOG.md)

## Logging and Observability

The logging middleware provides comprehensive observability into tool execution. It captures request context, execution duration, error details, and system metrics.

```mermaid
graph TD
    A[Tool Execution Start] --> B[Generate Request ID]
    B --> C[Log Request Start]
    C --> D[Execute Handler]
    D --> E{Result Type}
    E -->|Success| F[Log Success<br/>Duration: Xms]
    E -->|Error| G[Capture Error Context]
    G --> H[Categorize Error]
    H --> I[Log Error<br/>with Stack Trace]
```

### Error Categorization

The middleware categorizes errors into distinct types for better debugging and monitoring:

| Category | Triggers | Example Messages |
|----------|----------|-------------------|
| `validation` | Invalid parameters | "invalid", "required", "missing parameter" |
| `resource` | Browser/page issues | "closed", "disconnected", "protocol error" |
| `authentication` | Auth failures | "unauthorized", "forbidden", "access denied" |
| `rate_limit` | Rate limiting | "rate limit", "too many requests" |
| `system` | Timeout/element errors | "timeout", "element not found", "navigation" |

资料来源：[src/logging/middleware.ts:80-120](https://github.com/executeautomation/mcp-playwright/blob/main/src/logging/middleware.ts)

### Request Sanitization

The logging middleware automatically sanitizes sensitive data from tool arguments before logging:

| Field Pattern | Sanitization |
|---------------|--------------|
| `password`, `token`, `secret`, `key`, `auth` | Replaced with `[REDACTED]` |
| Request bodies > 1000 characters | Truncated with character count |

资料来源：[src/logging/middleware.ts:150-170](https://github.com/executeautomation/mcp-playwright/blob/main/src/logging/middleware.ts)

## Transport Modes

### stdio Mode

In stdio mode, the server communicates over standard input and output streams. This mode is designed for direct integration with MCP clients like Claude Desktop.

| Aspect | Configuration |
|--------|---------------|
| Launch Command | `npx -y @executeautomation/playwright-mcp-server` |
| Log Output | File only (`~/playwright-mcp-server.log`) |
| JSON-RPC | stdin/stdout streaming |

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

### HTTP Mode

HTTP mode exposes the server as a standalone HTTP server with multiple endpoints:

| Endpoint | Method | Purpose |
|----------|--------|---------|
| `/sse` | GET | Server-Sent Events stream |
| `/messages` | POST | Send messages with session ID |
| `/mcp` | GET/POST | Unified MCP protocol endpoint |
| `/health` | GET | Health check |

The default port is `8931`, configurable via the `--port` flag.

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

```mermaid
graph LR
    A[MCP Client] -->|HTTP POST /mcp| B[HTTP Server]
    B --> C[Request Handler]
    C --> D[Tool Handler]
    D --> E[Browser Automation]
    E --> F[Response]
    F --> B
    B --> A
```

## Browser Context Management

The architecture supports multiple browser engines:

| Browser | Package | Default |
|---------|---------|---------|
| Chromium | `@playwright/browser-chromium` | Yes |
| Firefox | `@playwright/browser-firefox` | No |
| WebKit | `@playwright/browser-webkit` | No |

The `browserType` parameter in `playwright_navigate` allows selection of the browser engine:

```javascript
await playwright_navigate({ 
  url: "https://example.com",
  browserType: "firefox"  // chromium, firefox, or webkit
});
```

资料来源：[CHANGELOG.md:15-20](https://github.com/executeautomation/mcp-playwright/blob/main/CHANGELOG.md)

## Deployment Architecture

### Docker Deployment

The Docker deployment provides a containerized environment for the MCP server:

```mermaid
graph TD
    A[Docker Host] --> B[mcp-playwright:latest]
    B --> C[Node.js Runtime]
    C --> D[MCP Server]
    D --> E[Playwright Browsers]
    E --> F[Chromium<br/>Firefox<br/>WebKit]
```

The Docker image is optimized for size (~200MB without browsers) and supports environment variable configuration:

| Variable | Purpose | Default |
|----------|---------|---------|
| `PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD` | Skip browser installation | 1 |
| `NODE_ENV` | Node environment | production |

资料来源：[DOCKER.md:40-60](https://github.com/executeautomation/mcp-playwright/blob/main/DOCKER.md)

### Claude Desktop Configuration

```json
{
  "mcpServers": {
    "playwright": {
      "command": "npx",
      "args": ["-y", "@executeautomation/playwright-mcp-server"]
    }
  }
}
```

For HTTP mode with remote deployments:

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

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

---

<a id='transport-modes'></a>

## Transport Modes

### 相关页面

相关主题：[Architecture Overview](#architecture-overview), [Configuration Guide](#configuration)

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

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

- [src/index.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/index.ts)
- [src/http-server.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/http-server.ts)
- [examples/http-mode-example.md](https://github.com/executeautomation/mcp-playwright/blob/main/examples/http-mode-example.md)
- [DOCKER.md](https://github.com/executeautomation/mcp-playwright/blob/main/DOCKER.md)
- [README.md](https://github.com/executeautomation/mcp-playwright/blob/main/README.md)
- [src/logging/middleware.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/logging/middleware.ts)
- [package.json](https://github.com/executeautomation/mcp-playwright/blob/main/package.json)
</details>

# Transport Modes

The mcp-playwright server supports two distinct transport modes for communicating with MCP clients: **STDIO Transport** and **HTTP/SSE Transport**. Each mode serves different deployment scenarios and client requirements.

## Overview

The transport mode determines how the MCP protocol messages are exchanged between the Playwright MCP server and connected clients. The server automatically detects the appropriate mode based on command-line arguments or environment configuration.

| Transport Mode | Use Case | Default Port | Security |
|----------------|----------|--------------|----------|
| STDIO | Local MCP clients (Claude Desktop, Cursor) | N/A | Process-bound |
| HTTP/SSE | Remote clients, headed browsers, IDE integrations | 8931 | Localhost only |

## STDIO Transport Mode

### Purpose and Architecture

STDIO (Standard Input/Output) is the default transport mode for MCP servers. It provides process-based communication where messages are exchanged through the parent process's standard input and output streams.

```mermaid
graph LR
    A[MCP Client<br/>Claude Desktop] <-->|stdin/stdout pipes| B[playwright-mcp-server<br/>STDIO Mode]
    B <-->|Playwright API| C[Browser Instance]
```

### How STDIO Mode Works

1. The MCP client spawns the server as a child process
2. JSON-RPC messages are sent via process stdin
3. Responses are received via process stdout
4. The server runs in headless mode by default
5. Logging is automatically redirected to `~/playwright-mcp-server.log`

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

### Configuration for Claude Desktop

```json
{
  "mcpServers": {
    "playwright": {
      "command": "npx",
      "args": ["-y", "@executeautomation/playwright-mcp-server"]
    }
  }
}
```

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

### Docker Considerations

When running in Docker containers, STDIO mode requires the `-i` flag to keep STDIN open for interactive communication:

```bash
docker run -i --rm mcp-playwright:latest
```

| Docker Flag | Purpose |
|-------------|---------|
| `-i` | Keep STDIN open for interactive communication |
| `--rm` | Automatically remove container when it exits |

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

## HTTP/SSE Transport Mode

### Purpose and Architecture

HTTP/SSE transport runs the MCP server as a standalone HTTP server. This mode is designed for scenarios where STDIO communication is impractical, such as:

- Running headed browsers on headless systems
- Integration with IDE worker processes
- Remote client access via HTTP
- Multi-client concurrent connections

```mermaid
graph TD
    A[MCP Client<br/>VS Code / Custom] -->|HTTP/REST| B[HTTP Server<br/>127.0.0.1:8931]
    B --> C[SSE Transport<br/>Server-Sent Events]
    B --> D[Message Handler<br/>POST /messages]
    C --> E[Session Manager]
    D --> E
    E --> F[Playwright MCP<br/>Tool Handler]
    F --> G[Browser Instance]
```

### Available Endpoints

The HTTP server exposes the following endpoints:

| Endpoint | Method | Purpose |
|----------|--------|---------|
| `/sse` | GET | Server-Sent Events stream for push notifications |
| `/messages?sessionId=<id>` | POST | Send JSON-RPC messages for a specific session |
| `/mcp` | GET | MCP unified endpoint (GET) |
| `/mcp?sessionId=<id>` | POST | MCP unified endpoint (POST) |
| `/health` | GET | Health check endpoint |

资料来源：[src/http-server.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/http-server.ts)

### Starting the HTTP Server

```bash
# Using npx
npx @executeautomation/playwright-mcp-server --port 8931

# Or after global installation
npm install -g @executeautomation/playwright-mcp-server
playwright-mcp-server --port 8931
```

资料来源：[examples/http-mode-example.md](https://github.com/executeautomation/mcp-playwright/blob/main/examples/http-mode-example.md)

### HTTP Server Output

When started successfully, the server displays:

```
==============================================
Playwright MCP Server (HTTP Mode)
==============================================
Listening: 127.0.0.1:8931 (localhost only)
Version: <version>

SECURITY: Server is bound to localhost only.
          Not accessible from external networks.

ENDPOINTS:
- SSE Stream:     GET  http://localhost:8931/sse
- Messages:       POST http://localhost:8931/messages?sessionId=<id>
- MCP (unified):  GET  http://localhost:8931/mcp
- MCP (unified):  POST http://localhost:8931/mcp?sessionId=<id>
- Health Check:   GET  http://localhost:8931/health
```

资料来源：[src/http-server.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/http-server.ts)

### Client Configuration

#### Claude Desktop (HTTP)

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

#### VS Code MCP Extension

```json
{
  "name": "playwright",
  "url": "http://localhost:8931/mcp"
}
```

#### Health Check

```bash
curl http://localhost:8931/health
```

资料来源：[examples/http-mode-example.md](https://github.com/executeautomation/mcp-playwright/blob/main/examples/http-mode-example.md)

### Security Model

The HTTP server binds exclusively to `127.0.0.1` (localhost) for security reasons:

> **SECURITY**: Server binds to localhost only. Not accessible from external networks.

For remote access, SSH tunneling is recommended:

```bash
ssh -L 8931:localhost:8931 user@remote-server
```

资料来源：[src/http-server.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/http-server.ts)

## Mode Selection

### Automatic Selection

The server automatically selects the transport mode based on:

1. **Presence of `--port` argument** → HTTP/SSE mode
2. **Absence of `--port` argument** → STDIO mode

### Health Check Response

| Field | Description |
|-------|-------------|
| `status` | Health status (`ok` when healthy) |
| `version` | Server version |
| `activeSessions` | Number of active MCP sessions |

Example response:
```json
{
  "status": "ok",
  "version": "1.0.10",
  "activeSessions": 2
}
```

## Transport Comparison

| Aspect | STDIO | HTTP/SSE |
|--------|-------|----------|
| Communication | stdin/stdout pipes | HTTP/REST |
| Multi-client | No | Yes |
| Session support | No | Yes (via sessionId) |
| Browser mode | Headless | Headless or Headed |
| Claude Desktop | ✅ Supported | ❌ Not supported |
| VS Code | ✅ Supported | ✅ Supported |
| Health endpoint | No | Yes |
| Process lifecycle | Tied to client | Independent |

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

## Logging Behavior

### STDIO Mode

- Logging automatically directed to files only
- Console output kept clean for JSON-RPC communication
- Logs written to `~/playwright-mcp-server.log`

### HTTP Mode

- Standard logging to console and file
- Request/response logging via middleware
- Error context capture including:
  - Stack traces
  - Memory usage
  - Platform information
  - Request duration

资料来源：[src/logging/middleware.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/logging/middleware.ts)

## Environment Variables

| Variable | Purpose | Applicable Modes |
|----------|---------|------------------|
| `PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD` | Skip browser binary download | Both |
| `NODE_ENV` | Set runtime environment | Both |
| `PORT` | HTTP server port (alternative to CLI) | HTTP |

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

---

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

## Browser Automation Tools

### 相关页面

相关主题：[Device Emulation](#device-emulation), [API Testing Tools](#api-testing), [Code Generation and Recording](#code-generation)

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

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

- [src/tools/browser/index.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/browser/index.ts)
- [src/tools/browser/navigation.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/browser/navigation.ts)
- [src/tools/browser/interaction.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/browser/interaction.ts)
- [src/tools/browser/screenshot.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/browser/screenshot.ts)
- [src/tools/browser/console.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/browser/console.ts)
- [src/tools/browser/output.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/browser/output.ts)
- [src/tools/browser/resize.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/browser/resize.ts)
- [src/tools/browser/useragent.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/browser/useragent.ts)
- [src/tools/browser/response.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/browser/response.ts)
- [src/tools/browser/visiblePage.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/browser/visiblePage.ts)
- [src/tools/browser/base.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/browser/base.ts)
</details>

# Browser Automation Tools

## Overview

The Browser Automation Tools constitute the core module of the mcp-playwright project, providing a comprehensive set of MCP (Model Context Protocol) tools for browser-based web automation and testing. These tools enable AI assistants and automated systems to interact with web pages programmatically, performing actions such as navigation, element interaction, content extraction, and response monitoring.

The module supports multiple browser engines (Chromium, Firefox, WebKit) and provides both headless and headed execution modes, making it suitable for a wide range of automation scenarios from simple web scraping to complex end-to-end testing.

**Architecture Overview:**

```mermaid
graph TD
    A[MCP Client] -->|JSON-RPC| B[Tool Handler]
    B --> C[Browser Tool Executor]
    C --> D[Browser Engine]
    D --> E[Chromium<br/>Firefox<br/>WebKit]
    
    F[Base Class] -->|Inheritance| C
    F --> G[Error Handling]
    F --> H[Page Validation]
    F --> I[Safe Execution]
```

## Core Components

### Tool Architecture

The browser automation tools follow an object-oriented architecture with a base class pattern. All browser tools inherit from `BrowserToolBase`, which provides common functionality including error handling, page validation, and safe execution wrappers.

**Class Hierarchy:**

```mermaid
graph TD
    A[BrowserToolBase] --> B[navigation.ts<br/>NavigateTool]
    A --> C[interaction.ts<br/>ClickTool, FillTool, etc.]
    A --> D[screenshot.ts<br/>ScreenshotTool]
    A --> E[console.ts<br/>ConsoleLogsTool]
    A --> F[output.ts<br/>PdfTool]
    A --> G[resize.ts<br/>ResizeTool]
    A --> H[useragent.ts<br/>CustomUserAgentTool]
    A --> I[response.ts<br/>ExpectResponseTool, AssertResponseTool]
    A --> J[visiblePage.ts<br/>VisibleTextTool, VisibleHtmlTool]
    
    K[ToolContext] --> A
    L[Browser, Page] --> A
```

### Base Class (BrowserToolBase)

The `BrowserToolBase` class provides the foundation for all browser tools:

| Method | Purpose |
|--------|---------|
| `ensurePage(context)` | Returns the current page or null if unavailable |
| `validatePageAvailable(context)` | Returns error response if page not initialized |
| `safeExecute(context, operation)` | Wraps browser operations with error handling |

**File Reference:** `src/tools/browser/base.ts`

## Browser Tools Registry

All browser-requiring tools are registered in the `BROWSER_TOOLS` array and exposed through the MCP tool interface:

**File Reference:** `src/tools/browser/index.ts`, `src/tools.ts`

```typescript
export const BROWSER_TOOLS = [
  "playwright_navigate",
  "playwright_screenshot",
  "playwright_click",
  "playwright_iframe_click",
  "playwright_iframe_fill",
  "playwright_fill",
  "playwright_select",
  "playwright_hover",
  "playwright_evaluate",
  "playwright_console_logs",
  "playwright_close",
  "playwright_get_visible_text",
  "playwright_get_visible_html",
  "playwright_click_and_switch_tab",
  "playwright_drag",
  "playwright_press_key",
  "playwright_save_as_pdf"
];
```

## Navigation Tools

### Navigate Tool (`playwright_navigate`)

The primary navigation tool for loading web pages in the browser.

**Parameters:**

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `url` | string | Yes | Target URL to navigate to |
| `browserType` | string | No | Browser engine: "chromium", "firefox", "webkit" (default: "chromium") |
| `width` | number | No | Viewport width in pixels (default: 1280) |
| `height` | number | No | Viewport height in pixels (default: 720) |
| `timeout` | number | No | Navigation timeout in milliseconds |
| `waitUntil` | string | No | Navigation wait condition |
| `headless` | boolean | No | Run browser in headless mode (default: false) |

**Multi-Browser Support:**

Starting from version 1.0.2, the navigate tool supports specifying the browser type:

> Multi-Browser Support: Firefox and WebKit in addition to Chromium
> New `browserType` parameter for `playwright_navigate` tool
> Supported browser types: "chromium" (default), "firefox", "webkit"
> 资料来源：[CHANGELOG.md]()

**File Reference:** `src/tools/browser/navigation.ts`

## Interaction Tools

Interaction tools enable programmatic control over browser elements, including clicking, filling forms, hovering, and keyboard input.

### Click Tool (`playwright_click`)

Clicks an element identified by a CSS selector.

**Parameters:**

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `selector` | string | Yes | CSS selector for the element to click |
| `button` | string | No | Mouse button: "left", "right", "middle" (default: "left") |
| `clickCount` | number | No | Number of clicks (default: 1) |
| `delay` | number | No | Delay in milliseconds between key down and up |
| `force` | boolean | No | Force click even if element obscured |
| `timeout` | number | No | Timeout in milliseconds |
| `noWaitAfter` | boolean | No | Don't wait for navigation after click |

### Fill Tool (`playwright_fill`)

Fills input fields with text content.

**Parameters:**

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `selector` | string | Yes | CSS selector for the input element |
| `value` | string | Yes | Text value to fill |
| `delay` | number | No | Delay between keystrokes in milliseconds |
| `noWaitAfter` | boolean | No | Don't wait for navigation after fill |

### Select Tool (`playwright_select`)

Selects options in dropdown menus (select elements).

**Parameters:**

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `selector` | string | Yes | CSS selector for the select element |
| `value` | string/array | Yes | Option value(s) to select |
| `index` | array | No | Option index(es) to select |
| `label` | string/array | No | Option label(s) to select |
| `timeout` | number | No | Timeout in milliseconds |

### Hover Tool (`playwright_hover`)

Hovers over an element.

**Parameters:**

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `selector` | string | Yes | CSS selector for the element to hover |
| `timeout` | number | No | Timeout in milliseconds |

### Keyboard Interaction

**Drag Tool (`playwright_drag`):**

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `sourceSelector` | string | Yes | CSS selector for source element |
| `targetSelector` | string | Yes | CSS selector for target element |

**Press Key Tool (`playwright_press_key`):**

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `selector` | string | No | CSS selector for element to focus |
| `key` | string | Yes | Key to press (e.g., "Enter", "Tab", "Escape") |

### iFrame Interaction

The project supports interaction with elements inside iframes through dedicated tools:

| Tool | Description |
|------|-------------|
| `playwright_iframe_click` | Click element within an iframe |
| `playwright_iframe_fill` | Fill input within an iframe |

**File Reference:** `src/tools/browser/interaction.ts`

## Screenshot Tools

### Screenshot Tool (`playwright_screenshot`)

Captures screenshots of the current page or specific elements.

**Parameters:**

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `name` | string | No | Name for the screenshot |
| `selector` | string | No | CSS selector for element to screenshot |
| `width` | number | No | Width in pixels (default: 800) |
| `height` | number | No | Height in pixels (default: 600) |
| `storeBase64` | boolean | No | Store in base64 format (default: true) |
| `fullPage` | boolean | No | Screenshot entire page (default: false) |
| `savePng` | boolean | No | Save as PNG file (default: false) |
| `downloadsDir` | string | No | Custom downloads directory path |

**File Reference:** `src/tools/browser/screenshot.ts`

## Content Extraction Tools

### Visible Text Tool (`playwright_get_visible_text`)

Extracts visible text content from the page or specific elements.

**Parameters:**

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `selector` | string | No | CSS selector to extract text from specific element |
| `includeHidden` | boolean | No | Include hidden elements (default: false) |
| `removeLineBreaks` | boolean | No | Remove line breaks (default: false) |
| `trimText` | boolean | No | Trim whitespace (default: true) |

### Visible HTML Tool (`playwright_get_visible_html`)

Retrieves HTML content from the page or elements.

**Parameters:**

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `selector` | string | No | CSS selector for specific element |
| `removeScripts` | boolean | No | Remove script tags |
| `removeComments` | boolean | No | Remove HTML comments |
| `removeStyles` | boolean | No | Remove style tags |
| `removeMeta` | boolean | No | Remove meta tags |
| `cleanHtml` | boolean | No | Apply all cleanup filters |
| `minify` | boolean | No | Minify the HTML output |

**Content Filtering Pipeline:**

```mermaid
graph LR
    A[Raw HTML] --> B{removeScripts?}
    B -->|Yes| C[Remove script tags]
    B -->|No| D[Continue]
    C --> E{removeStyles?}
    E -->|Yes| F[Remove style tags]
    E -->|No| G[Continue]
    F --> H{removeMeta?}
    H -->|Yes| I[Remove meta tags]
    H -->|No| J[Continue]
    I --> K{removeComments?}
    K -->|Yes| L[Remove comments]
    K -->|No| M[Continue]
    L --> N{minify?}
    M --> N
    N -->|Yes| O[Minify HTML]
    N -->|No| P[Return Clean HTML]
```

**File Reference:** `src/tools/browser/visiblePage.ts`

## Output Tools

### PDF Generation Tool (`playwright_save_as_pdf`)

Saves the current page as a PDF document.

**Parameters:**

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `outputPath` | string | Yes | Path where PDF will be saved |
| `name` | string | No | PDF filename (default: "page.pdf") |
| `format` | string | No | Page format: "A4", "Letter", etc. |
| `printBackground` | boolean | No | Include background graphics |
| `margin` | object | No | Page margins (top, right, bottom, left) |

**File Reference:** `src/tools/browser/output.ts`

## Console Tools

### Console Logs Tool (`playwright_console_logs`)

Retrieves console messages from the browser page.

**Parameters:**

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `type` | string | No | Filter by message type: "log", "info", "warn", "error" |
| `text` | string | No | Filter by text content (partial match) |
| `regex` | string | No | Filter by regex pattern |

**Console Message Types:**

| Type | Description |
|------|-------------|
| `log` | General console logs |
| `info` | Informational messages |
| `warn` | Warning messages |
| `error` | Error messages |

**File Reference:** `src/tools/browser/console.ts`

## Response Monitoring Tools

### Expect Response Tool (`playwright_expect_response`)

Sets up expectations for network responses.

**Parameters:**

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `url` | string | No | URL pattern to match (regex or string) |
| `statusCode` | number | No | Expected HTTP status code |
| `timeout` | number | No | Timeout in milliseconds |
| `method` | string | No | HTTP method filter |

### Assert Response Tool (`playwright_assert_response`)

Asserts that a network response meets specified criteria.

**Parameters:**

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `url` | string | No | URL pattern to match |
| `statusCode` | number | No | Expected HTTP status code |
| `method` | string | No | HTTP method filter |

**File Reference:** `src/tools/browser/response.ts`

## Viewport and Device Emulation

### Resize Tool (`playwright_resize`)

Configures viewport dimensions and enables device emulation.

**Parameters:**

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `device` | string | No | Device name for emulation (e.g., "iPhone 13", "iPad Pro 11") |
| `width` | number | No | Viewport width in pixels |
| `height` | number | No | Viewport height in pixels |
| `orientation` | string | No | Device orientation: "portrait", "landscape" |
| `scale` | number | No | Device scale factor |
| `mobile` | boolean | No | Enable mobile emulation |

**Device Emulation Features:**

- 143 real device presets including iPhone, iPad, Pixel, Galaxy, and Desktop browsers
- Automatic user-agent string configuration
- Touch event support emulation
- Device pixel ratio configuration

**Natural Language Support:**

AI assistants can use natural language prompts such as:
- "Test on iPhone 13"
- "Switch to iPad view"
- "Rotate to landscape"

**File Reference:** `src/tools/browser/resize.ts`

## User Agent Tools

### Custom User Agent Tool (`playwright_custom_user_agent`)

Sets a custom user agent string for the browser context.

**Parameters:**

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `userAgent` | string | Yes | Custom user agent string |

**File Reference:** `src/tools/browser/useragent.ts`

## Browser Lifecycle Management

### Close Tool (`playwright_close`)

Closes the current browser context and page.

**Parameters:**

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `closeBrowser` | boolean | No | Close the entire browser (default: false) |

## Error Handling

The browser tools implement comprehensive error handling through the middleware system:

**Error Categories:**

| Category | Indicators |
|----------|------------|
| `validation` | Invalid parameters, missing required fields |
| `resource` | Browser closed, page disconnected, protocol errors |
| `authentication` | Unauthorized, forbidden, access denied |
| `rate_limit` | Too many requests, throttling |
| `system` | Timeout, element not found, navigation failures |

**Enhanced Error Context:**

The logging middleware captures detailed error context including:
- Error name and message
- Stack trace
- Timestamp
- Node.js version and platform
- Memory usage statistics
- Browser state information

**File Reference:** `src/logging/middleware.ts`

## Tool Execution Flow

**Complete Tool Execution Pipeline:**

```mermaid
sequenceDiagram
    participant Client
    participant MCP_Server
    participant Middleware
    participant Tool
    participant Browser
    
    Client->>MCP_Server: Tool Request
    MCP_Server->>Middleware: Intercept Request
    Middleware->>Middleware: Log Start
    Middleware->>Tool: Execute Tool
    Tool->>Browser: Browser Operation
    Browser-->>Tool: Operation Result
    Tool-->>Middleware: Tool Response
    Middleware->>Middleware: Log Completion
    Middleware-->>Client: Response
```

## Summary

The Browser Automation Tools module provides a comprehensive, MCP-compatible interface for browser automation tasks. Key features include:

| Feature Category | Capabilities |
|------------------|--------------|
| **Navigation** | Multi-browser support (Chromium, Firefox, WebKit), configurable viewport |
| **Interaction** | Click, fill, select, hover, drag, keyboard input, iframe support |
| **Content Extraction** | Visible text, HTML with filtering/minification |
| **Output** | Screenshots, PDF generation |
| **Monitoring** | Console logs, network response expectations |
| **Emulation** | 143 device presets, custom user agents |

All tools follow a consistent pattern with base class inheritance, comprehensive error handling, and structured logging for debugging and monitoring purposes.

---

<a id='device-emulation'></a>

## Device Emulation

### 相关页面

相关主题：[Browser Automation Tools](#browser-automation)

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

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

- [src/tools/browser/resize.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/browser/resize.ts)
- [README.md](https://github.com/executeautomation/mcp-playwright/blob/main/README.md)
- [src/tools.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools.ts)
- [src/logging/middleware.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/logging/middleware.ts)
- [src/tools/browser/visiblePage.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/browser/visiblePage.ts)
- [package.json](https://github.com/executeautomation/mcp-playwright/blob/main/package.json)
</details>

# Device Emulation

Device Emulation is a core feature of the Playwright MCP Server that enables AI assistants and automated testing tools to simulate real-world mobile and desktop devices directly within the browser automation framework. By leveraging Playwright's built-in device descriptor library, the server provides **143 real device presets** with accurate viewport dimensions, user-agent strings, touch capabilities, and device pixel ratios.

## Overview

The Device Emulation system integrates with the `playwright_resize` tool to provide a seamless interface for switching between device profiles. When a device preset is selected, the system automatically configures multiple browser properties simultaneously:

- **Viewport dimensions** for accurate screen rendering
- **User-Agent strings** for proper server-side device detection
- **Touch capabilities** for mobile device simulation
- **Device pixel ratio** for high-DPI display accuracy

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

## Architecture

```mermaid
graph TD
    A[AI Assistant / MCP Client] --> B[playwright_resize Tool]
    B --> C{Device Preset?}
    C -->|Yes| D[Lookup in Playwright devices]
    C -->|No| E[Direct Dimensions]
    D --> F[Extract Device Properties]
    F --> G[page.setViewportSize]
    F --> H[page.setExtraHTTPHeaders]
    G --> I[Browser Context Updated]
    H --> I
    E --> G
```

### Component Flow

1. **Client Request**: The AI assistant or MCP client sends a `playwright_resize` call with a `device` parameter
2. **Device Lookup**: The system searches Playwright's device descriptor library using the provided name
3. **Property Extraction**: Device properties including viewport, user-agent, mobile flag, touch support, and scale factor are extracted
4. **Browser Configuration**: Playwright APIs apply the settings to the active page context

资料来源：[src/tools/browser/resize.ts:17-48](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/browser/resize.ts)

## API Reference

### Tool: `playwright_resize`

The primary tool for device emulation and viewport control.

#### Parameters

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `device` | `string` | No | Device preset name (e.g., "iPhone 13", "iPad Pro 11") |
| `width` | `number` | Conditional | Viewport width in pixels (default: 1280) |
| `height` | `number` | Conditional | Viewport height in pixels (default: 720) |
| `orientation` | `string` | No | "portrait" or "landscape" (only valid with device preset) |
| `maxLength` | `number` | No | Maximum response length for HTML content (default: 20000) |

#### Device Preset Detection

The system validates device names against Playwright's device library and returns helpful suggestions if the device is not found:

```typescript
if (!device) {
  return createErrorResponse(
    `Device "${args.device}" not found. Popular devices: ${popularDevices.join(', ')}. ` +
    `Use playwright.devices to see all ${Object.keys(devices).length} available devices.`
  );
}
```

资料来源：[src/tools/browser/resize.ts:36-43](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/browser/resize.ts)

## Supported Devices

The Playwright MCP Server includes support for **143 device presets** covering major device categories:

### Popular Devices

| Category | Devices |
|----------|---------|
| **iPhone** | iPhone 13, iPhone 13 Pro, iPhone 14, iPhone 15, iPhone 15 Pro Max |
| **iPad** | iPad Pro 11, iPad Pro 12.9, iPad Air, iPad Mini |
| **Pixel** | Pixel 5, Pixel 7, Pixel 8, Pixel 8 Pro |
| **Galaxy** | Galaxy S9+, Galaxy S10+, Galaxy S24, Galaxy S24 Ultra |
| **Desktop** | Desktop Chrome, Desktop Firefox, Desktop Safari |

### Device Properties Extracted

When using a device preset, the following properties are automatically configured:

```typescript
// Extract device properties from Playwright's device library
width = device.defaultBrowserViewport.width;
height = device.defaultBrowserViewport.height;
userAgent = device.defaultUserAgent;
isMobile = device.defaultBrowserType === 'mobile';
hasTouch = device.hasTouch;
deviceScaleFactor = device.deviceScaleFactor || 1;
```

资料来源：[src/tools/browser/resize.ts:48-54](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/browser/resize.ts)

## Orientation Support

Device emulation supports both portrait and landscape orientations. When an orientation is specified with a device preset, the width and height values are swapped:

```javascript
// Portrait orientation (default)
await playwright_resize({ device: "iPhone 13", orientation: "portrait" });

// Landscape orientation
await playwright_resize({ device: "iPad Pro 11", orientation: "landscape" });
```

### Orientation Logic

```mermaid
graph LR
    A[Device Preset] --> B{orientation === "landscape"}
    B -->|Yes| C[Swap width ↔ height]
    B -->|No| D[Keep original dimensions]
    C --> E[Apply to Viewport]
    D --> E
```

The orientation parameter is validated to ensure it is only used with device presets:

```typescript
if (args.orientation && !args.device) {
  throw new Error("Orientation can only be set when using a device preset");
}
```

资料来源：[src/tools/browser/resize.ts:71-74](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/browser/resize.ts)

## Validation Rules

The device emulation system enforces several validation constraints:

### Dimension Constraints

| Rule | Value | Error Message |
|------|-------|---------------|
| Minimum dimension | > 0 | "Width and height must be positive integers" |
| Maximum dimension | ≤ 7680 × 4320 | "Width and height must not exceed 7680x4320 (8K resolution)" |

### Parameter Constraints

| Constraint | Condition |
|------------|------------|
| Orientation requires device | `orientation` parameter cannot be used standalone |
| Device validation | Name must exist in Playwright's device library |

资料来源：[src/tools/browser/resize.ts:81-91](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/browser/resize.ts)

## Natural Language Support

The device emulation system is designed to work seamlessly with AI assistants that use natural language commands. Common prompt patterns include:

- "Test on iPhone 13"
- "Switch to iPad view"
- "Rotate to landscape"
- "Test desktop view"

These natural language commands are interpreted by the AI assistant and translated into `playwright_resize` tool calls with the appropriate device and orientation parameters.

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

## Implementation Details

### Base Class Integration

The `ResizeTool` extends `BrowserToolBase`, which provides the foundation for browser interaction:

```typescript
export class ResizeTool extends BrowserToolBase {
  async execute(args: any, context: ToolContext): Promise<ToolResponse> {
    return this.safeExecute(context, async (page) => {
      // Device emulation logic
    });
  }
}
```

### Error Handling

The implementation uses a safe execution pattern with comprehensive error handling:

```typescript
private categorizeError(error: Error): 'validation' | 'system' | 'unknown' {
  const message = error.message.toLowerCase();
  
  if (message.includes('invalid') || message.includes('validation') || message.includes('required')) {
    return 'validation';
  }
  
  if (message.includes('browser') || message.includes('page') || message.includes('connection')) {
    return 'system';
  }
  
  return 'unknown';
}
```

资料来源：[src/tools/browser/resize.ts:7-11](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/browser/resize.ts)
资料来源：[src/logging/middleware.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/logging/middleware.ts)

## Response Format

### Success Response

When device emulation is successfully applied, the response includes:

```
Browser viewport resized to iPhone 13 (390x844) [mobile, touch, 3x scale]
```

The response includes:
- Device name and dimensions
- Orientation (if specified)
- Applied features: mobile, touch, device scale factor

### Error Response

If device emulation fails, an error response is returned with:
- Specific error message explaining the failure
- Suggestions for popular devices when device name is not found
- Reference to available device count

资料来源：[src/tools/browser/resize.ts:95-120](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/browser/resize.ts)

## Tool Registration

The `playwright_resize` tool is registered in the central tools registry:

```typescript
{
  name: "playwright_resize",
  description: "Resize browser viewport with optional device emulation",
  inputSchema: {
    type: "object",
    properties: {
      device: { type: "string", description: "Device preset name" },
      width: { type: "number", description: "Viewport width in pixels" },
      height: { type: "number", description: "Viewport height in pixels" },
      orientation: { type: "string", description: "Device orientation" }
    }
  }
}
```

资料来源：[src/tools.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools.ts)

## Dependencies

The device emulation feature relies on the following package dependencies:

| Package | Version | Purpose |
|---------|---------|---------|
| `playwright` | 1.57.0 | Core browser automation with device descriptors |
| `@playwright/browser-chromium` | 1.57.0 | Chromium browser support |
| `@playwright/browser-firefox` | 1.57.0 | Firefox browser support |
| `@playwright/browser-webkit` | 1.57.0 | WebKit browser support |

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

## Usage Examples

### Basic Device Emulation

```javascript
// Test on iPhone 13
await playwright_resize({ device: "iPhone 13" });

// Result: Browser viewport resized to iPhone 13 (390x844) [mobile, touch, 2x scale]
```

### Landscape Orientation

```javascript
// iPad in landscape mode
await playwright_resize({ device: "iPad Pro 11", orientation: "landscape" });

// Result: Browser viewport resized to iPad Pro 11 (1194x834) in landscape orientation [mobile, touch, 2x scale]
```

### Desktop Browser

```javascript
// Switch to desktop Chrome view
await playwright_resize({ device: "Desktop Chrome" });

// Result: Browser viewport resized to Desktop Chrome (1280x720)
```

### Custom Dimensions

```javascript
// Direct viewport control without device preset
await playwright_resize({ width: 1920, height: 1080 });

// Result: Browser viewport resized to 1920x1080
```

## Integration with Other Tools

Device emulation settings persist across multiple tool calls within a session. Other tools that may interact with device emulation include:

| Tool | Interaction |
|------|-------------|
| `playwright_screenshot` | Captures screenshots at device resolution |
| `playwright_get_visible_html` | Extracts HTML content rendered at device viewport |
| `playwright_navigate` | Can be combined with device presets for full mobile testing |

The viewport and user-agent settings remain active until explicitly changed by another `playwright_resize` call.

资料来源：[src/tools/browser/visiblePage.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/browser/visiblePage.ts)
资料来源：[src/tools/browser/screenshot.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/browser/screenshot.ts)

---

<a id='api-testing'></a>

## API Testing Tools

### 相关页面

相关主题：[Browser Automation Tools](#browser-automation), [Code Generation and Recording](#code-generation)

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

The following source files were used to generate this page:

- [src/tools/api/index.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/api/index.ts)
- [src/tools/api/base.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/api/base.ts)
- [src/tools/api/requests.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/api/requests.ts)
- [src/tools/common/types.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/common/types.ts)
- [src/types.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/types.ts)
- [src/logging/middleware.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/logging/middleware.ts)
</details>

# API Testing Tools

## Overview

The API Testing Tools module in MCP Playwright provides a comprehensive framework for executing and validating HTTP API requests directly within the Model Context Protocol server environment. This module enables AI assistants and automated testing systems to perform REST API testing operations with full request/response tracking, assertion capabilities, and detailed logging support.

The API Testing Tools extend the MCP Playwright server's functionality beyond browser automation to include robust HTTP client capabilities. This allows for seamless integration of API testing workflows alongside browser-based UI testing, enabling end-to-end testing scenarios that span both frontend and backend interactions.

## Architecture

### High-Level Architecture

```mermaid
graph TD
    A[MCP Client Request] --> B[Tool Router]
    B --> C[API Testing Module]
    C --> D[Request Executor]
    D --> E[HTTP Client]
    E --> F[External API]
    F --> G[Response Handler]
    G --> H[Assertion Engine]
    H --> I[Tool Response]
    D --> J[Logging Middleware]
    J --> K[Request Logs]
    
    L[Request Builder] --> D
    M[Auth Handler] --> L
    N[Header Manager] --> L
```

### Module Structure

The API Testing Tools are organized into three primary components following the project's modular architecture pattern:

| Component | File | Responsibility |
|-----------|------|-----------------|
| API Index | `src/tools/api/index.ts` | Tool registration and routing |
| API Base | `src/tools/api/base.ts` | Base class with common functionality |
| Request Handler | `src/tools/api/requests.ts` | HTTP request execution and response handling |

## Core Components

### API Tool Base Class

The base class for all API tools provides common functionality that mirrors the browser tool architecture while adapting for HTTP operations. This design ensures consistency with the broader MCP Playwright tool framework.

```typescript
// Pattern inherited from browser base architecture
export abstract class ApiToolBase implements ToolHandler {
  protected server: any;
  
  constructor(server: any) {
    this.server = server;
  }
  
  abstract execute(args: any, context: ToolContext): Promise<ToolResponse>;
  
  protected ensureContext(context: ToolContext): ApiContext | null;
  protected validateRequest(args: any): ToolResponse | null;
  protected safeExecute(context: ToolContext, operation: ...): Promise<ToolResponse>;
}
```

**资料来源：** [src/tools/api/base.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/api/base.ts)

### Tool Registry and Handler

The API module registers its tools with the MCP server through the standard tool handler interface defined in the types system:

```typescript
export interface Tool {
  name: string;
  description: string;
  parameters: {
    type: string;
    properties: Record<string, unknown>;
    required?: string[];
  };
  handler: (args: any) => Promise<any>;
}
```

**资料来源：** [src/types.ts:1-15](https://github.com/executeautomation/mcp-playwright/blob/main/src/types.ts)

### Request Builder and Executor

The request handler component manages the construction and execution of HTTP requests, supporting various HTTP methods and authentication mechanisms.

**资料来源：** [src/tools/api/requests.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/api/requests.ts)

## Available API Testing Tools

### Response Expectation Tool

The `playwright_expect_response` tool allows tests to verify expected HTTP response characteristics before proceeding with further assertions. This tool enables proactive validation of API responses.

**Parameters:**

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `url` | string | Yes | Target API endpoint URL |
| `method` | string | No | HTTP method (GET, POST, PUT, DELETE, etc.) |
| `expectedStatus` | number | No | Expected HTTP status code |
| `expectedBody` | object | No | Expected response body content |
| `timeout` | number | No | Request timeout in milliseconds |

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

### Response Assertion Tool

The `playwright_assert_response` tool provides comprehensive response validation capabilities, comparing actual API responses against expected values with detailed error reporting.

**Parameters:**

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `url` | string | Yes | Target API endpoint URL |
| `expectedHeaders` | object | No | Expected response headers |
| `expectedBody` | object | No | Expected response body pattern |
| `schema` | object | No | JSON Schema for response validation |
| `exactMatch` | boolean | No | Whether to require exact body matching |

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

### Custom User Agent Tool

The `playwright_custom_user_agent` tool enables modification of the User-Agent header for API requests, supporting scenarios requiring specific client identification or browser emulation.

**Parameters:**

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `userAgent` | string | Yes | Custom User-Agent string |
| `persist` | boolean | No | Whether to persist for subsequent requests |

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

### Optional Bearer Authorization

API testing tools support optional Bearer token authentication for secured endpoints. This is configured at the request level and follows RFC 6750 specifications.

**Configuration:**

```json
{
  "url": "https://api.example.com/protected",
  "method": "GET",
  "authorization": {
    "type": "bearer",
    "token": "${API_TOKEN}"
  }
}
```

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

## Request Lifecycle

```mermaid
sequenceDiagram
    participant MCP as MCP Client
    participant API as API Tool Module
    participant LOG as Logging Middleware
    participant HTTP as HTTP Client
    participant EXT as External API
    
    MCP->>API: Tool Call Request
    API->>LOG: Log Tool Start
    LOG->>LOG: Capture Request Context
    API->>API: Validate Parameters
    API->>HTTP: Execute Request
    HTTP->>EXT: HTTP Request
    EXT-->>HTTP: HTTP Response
    HTTP-->>API: Raw Response
    API->>API: Process Response
    API->>API: Run Assertions
    API->>LOG: Log Tool Completion
    LOG-->>API: Log Entry Created
    API-->>MCP: Tool Response
```

## Logging and Monitoring

### Request Logging

The logging middleware captures detailed information about API tool executions, following the same pattern used for browser tools. Each API request generates a structured log entry with timing information and sanitized parameter data.

**Logging Context Structure:**

```typescript
interface RequestLogContext {
  method: 'TOOL_CALL';
  url: string;
  body?: any;
  statusCode?: number;
  duration?: number;
}
```

**资料来源：** [src/logging/middleware.ts:10-16](https://github.com/executeautomation/mcp-playwright/blob/main/src/logging/middleware.ts)

### Error Handling and Categorization

The logging middleware provides comprehensive error categorization for API-related errors:

| Error Category | Detection Patterns | Description |
|----------------|-------------------|-------------|
| `validation` | invalid, validation, required, missing parameter | Request validation failures |
| `resource` | browser, page, connection, closed, disconnected | Resource availability issues |
| `authentication` | unauthorized, forbidden, access denied | Auth-related failures |
| `rate_limit` | rate limit, too many requests, throttle | Rate limiting responses |

**资料来源：** [src/logging/middleware.ts:85-120](https://github.com/executeautomation/mcp-playwright/blob/main/src/logging/middleware.ts)

### Sanitization

Sensitive data within API requests is automatically sanitized in logs:

```typescript
const sensitiveFields = ['password', 'token', 'secret', 'key', 'auth'];
// These fields are replaced with '[REDACTED]' in logs
```

**资料来源：** [src/logging/middleware.ts:180-190](https://github.com/executeautomation/mcp-playwright/blob/main/src/logging/middleware.ts)

## Integration with Browser Tools

The API Testing Tools are designed to work alongside browser automation tools, enabling comprehensive end-to-end testing scenarios:

```mermaid
graph LR
    A[playwright_navigate] --> B[Browser Actions]
    B --> C[Extract Data]
    C --> D[API Validation]
    D --> E[playwright_expect_response]
    E --> F[API Assertions]
    F --> G[playwright_assert_response]
    G --> H[Test Results]
```

This integration allows for scenarios such as:

1. **Data-Driven Testing**: Extract test data from the UI using browser tools, then validate against API responses
2. **State Verification**: Use API tools to verify backend state after browser interactions
3. **Hybrid Workflows**: Combine UI automation with API validation for complete coverage

## Configuration

### Environment Variables

| Variable | Description | Default |
|----------|-------------|---------|
| `PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD` | Skip browser downloads (for API-only usage) | `0` |
| `NODE_ENV` | Node environment setting | `production` |
| `OPENAI_API_KEY` | API key for evaluation framework | - |

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

### Timeout Configuration

API tool timeouts are configurable at the tool call level and can be set per-request:

```typescript
{
  "timeout": 30000,  // 30 seconds
  "retries": 0       // No automatic retries by default
}
```

## Error Handling Patterns

### Tool Response Structure

All API tools return responses following the standard `ToolResponse` format:

```typescript
interface ToolResponse {
  content: Array<{
    type: 'text';
    text: string;
  }>;
  isError?: boolean;
}
```

**资料来源：** [src/tools/common/types.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/common/types.ts)

### Common Error Scenarios

| Scenario | Error Type | Handling |
|----------|------------|----------|
| Invalid URL | `validation` | Return error response with message |
| Connection timeout | `resource` | Log with timeout details |
| Invalid JSON response | `validation` | Include parse error in response |
| Server error (5xx) | `system` | Log with response details |

## Best Practices

1. **Use Assertions Early**: Use `playwright_expect_response` for early failure detection in test suites
2. **Sanitize Sensitive Data**: Ensure credentials are not logged by using environment variables
3. **Set Appropriate Timeouts**: Configure timeouts based on expected API response times
4. **Combine with Browser Tools**: Leverage both API and browser tools for comprehensive testing
5. **Monitor Logs**: Review logging output for performance analysis and debugging

## Related Documentation

- [HTTP Mode Example](examples/http-mode-example.md) - Running the server in HTTP mode for API testing
- [Docker Integration](DOCKER.md) - Containerized deployment for API testing workflows
- [Main README](README.md) - General MCP Playwright server documentation

---

<a id='code-generation'></a>

## Code Generation and Recording

### 相关页面

相关主题：[Browser Automation Tools](#browser-automation), [API Testing Tools](#api-testing)

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

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

- [src/tools/codegen/index.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/codegen/index.ts)
- [src/tools/codegen/recorder.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/codegen/recorder.ts)
- [src/tools/codegen/generator.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/codegen/generator.ts)
- [src/tools/codegen/types.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/tools/codegen/types.ts)
</details>

# Code Generation and Recording

The Code Generation and Recording system is a module within the MCP Playwright server that enables automatic conversion of MCP tool interactions into executable Playwright test code. This feature captures user actions performed through MCP tools during browser automation sessions and transforms them into structured test cases that can be replayed using Playwright's native test runner.

## Overview

The codegen module serves as a bridge between exploratory testing and automated test creation. When developers or AI assistants interact with web applications using MCP Playwright tools (such as `playwright_click`, `playwright_navigate`, `playwright_fill`, etc.), the codegen system records these actions with their parameters and results. Upon session completion, this recorded data can be converted into self-contained Playwright test files.

资料来源：[src/tools/codegen/index.ts:1-30]()

## Architecture

The codegen system follows a two-phase architecture: **Recording** and **Generation**.

```mermaid
graph TD
    A[MCP Tool Execution] --> B[ActionRecorder]
    B --> C[CodegenSession Store]
    C --> D[Session Actions]
    D --> E[PlaywrightGenerator]
    E --> F[Generated Test Code]
    G[CodegenOptions] --> E
    
    style A fill:#e1f5fe
    style F fill:#c8e6c9
    style B fill:#fff3e0
    style E fill:#fff3e0
```

### Core Components

| Component | File | Responsibility |
|-----------|------|-----------------|
| ActionRecorder | recorder.ts | Captures and stores tool execution data |
| PlaywrightGenerator | generator.ts | Transforms recorded sessions into test code |
| CodegenSession | types.ts | Data model for tracking a recording session |
| CodegenOptions | types.ts | Configuration for code generation behavior |

资料来源：[src/tools/codegen/types.ts:1-35]()

## Data Models

The codegen module defines several TypeScript interfaces that structure the recording and generation process.

### CodegenAction

Represents a single recorded action during a codegen session.

```typescript
export interface CodegenAction {
  toolName: string;
  parameters: Record<string, unknown>;
  timestamp: number;
  result?: unknown;
}
```

| Field | Type | Description |
|-------|------|-------------|
| toolName | string | The name of the MCP tool that was executed |
| parameters | Record<string, unknown> | Arguments passed to the tool |
| timestamp | number | Unix timestamp when the action occurred |
| result | unknown | Optional result returned by the tool execution |

资料来源：[src/tools/codegen/types.ts:1-10]()

### CodegenSession

Represents an entire recording session containing multiple actions.

```typescript
export interface CodegenSession {
  id: string;
  actions: CodegenAction[];
  startTime: number;
  endTime?: number;
  options?: CodegenOptions;
}
```

| Field | Type | Description |
|-------|------|-------------|
| id | string | Unique identifier for the session |
| actions | CodegenAction[] | Ordered list of recorded actions |
| startTime | number | Session start timestamp |
| endTime | number | Optional session end timestamp |
| options | CodegenOptions | Optional generation configuration |

资料来源：[src/tools/codegen/types.ts:12-20]()

### CodegenOptions

Configuration options that control code generation behavior.

```typescript
export interface CodegenOptions {
  outputPath?: string;
  testNamePrefix?: string;
  includeComments?: boolean;
}
```

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| outputPath | string | 'e2e' | Directory path where generated test files are written |
| testNamePrefix | string | 'Test' | Prefix added to generated test names |
| includeComments | boolean | true | Whether to include explanatory comments in generated code |

资料来源：[src/tools/codegen/types.ts:26-32]()

### CodegenResult

Output returned after generating test code from a session.

```typescript
export interface CodegenResult {
  testCode: string;
  filePath: string;
  sessionId: string;
}
```

| Field | Type | Description |
|-------|------|-------------|
| testCode | string | The generated Playwright test code |
| filePath | string | Path where the test file was or will be written |
| sessionId | string | Reference to the originating session |

资料来源：[src/tools/codegen/types.ts:34-40]()

## Available Tools

The codegen module exposes the following MCP tools for managing sessions.

### start_codegen_session

Initiates a new recording session for capturing MCP tool actions.

```typescript
export const startCodegenSession: Tool = {
  name: 'start_codegen_session',
  description: 'Start a new code generation session to record MCP tool actions',
  parameters: {
    type: 'object',
    properties: {
      options: {
        type: 'object',
        description: 'Code generation options',
        properties: {
          outputPath: { type: 'string' },
          testNamePrefix: { type: 'string' },
          includeComments: { type: 'boolean' }
        }
      }
    }
  },
  // ...
};
```

**Parameters:**

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| options | object | No | Configuration for the codegen session |
| options.outputPath | string | No | Custom output directory for generated tests |
| options.testNamePrefix | string | No | Prefix for generated test names |
| options.includeComments | boolean | No | Enable/disable code comments |

资料来源：[src/tools/codegen/index.ts:37-58]()

## PlaywrightGenerator Class

The `PlaywrightGenerator` class handles the transformation of recorded sessions into executable Playwright test code.

### Constructor and Configuration

```typescript
export class PlaywrightGenerator {
  private static readonly DEFAULT_OPTIONS: Required<CodegenOptions> = {
    outputPath: 'tests',
    testNamePrefix: 'MCP',
    includeComments: true,
  };

  private options: Required<CodegenOptions>;

  constructor(options: CodegenOptions = {}) {
    this.validateOptions(options);
    this.options = { ...PlaywrightGenerator.DEFAULT_OPTIONS, ...options };
  }
}
```

| Default Option | Value | Description |
|----------------|-------|-------------|
| outputPath | 'tests' | Default directory for generated test files |
| testNamePrefix | 'MCP' | Default prefix for test names |
| includeComments | true | Comments included by default |

资料来源：[src/tools/codegen/generator.ts:1-20]()

### Options Validation

The generator performs strict validation on provided options before initializing.

```typescript
private validateOptions(options: CodegenOptions): void {
  if (options.outputPath && typeof options.outputPath !== 'string') {
    throw new Error('outputPath must be a string');
  }
  if (options.testNamePrefix && typeof options.testNamePrefix !== 'string') {
    throw new Error('testNamePrefix must be a string');
  }
  if (options.includeComments !== undefined && typeof options.includeComments !== 'boolean') {
    throw new Error('includeComments must be a boolean');
  }
}
```

All options are validated for correct types before being applied, ensuring runtime errors are prevented during test generation.

资料来源：[src/tools/codegen/generator.ts:22-33]()

### Test Generation Process

```typescript
async generateTest(session: CodegenSession): Promise<CodegenResult> {
  if (!session || !Array.isArray(session.actions)) {
    throw new Error('Invalid session data');
  }

  const testCase = this.createTestCase(session);
  const testCode = this.generateTestCode(testCase);
  const filePath = this.getOutputFilePath(session);

  return {
    testCode,
    filePath,
    sessionId: session.id,
  };
}
```

The generation process consists of three steps:

1. **Create Test Case** - Transforms session actions into a structured `PlaywrightTestCase`
2. **Generate Test Code** - Converts the test case into Playwright test syntax
3. **Determine Output Path** - Resolves the file path based on session ID and configuration

资料来源：[src/tools/codegen/generator.ts:35-50]()

## Recording Workflow

```mermaid
sequenceDiagram
    participant User
    participant MCP as MCP Server
    participant Recorder as ActionRecorder
    participant Store as CodegenSession Store
    
    User->>MCP: start_codegen_session(options)
    MCP->>Recorder: createSession(options)
    Recorder->>Store: initialize session
    Note over Store: Session ID generated
    
    User->>MCP: playwright_click(selector)
    MCP->>Recorder: record(toolName, args, result)
    Recorder->>Store: append action
    
    User->>MCP: playwright_navigate(url)
    MCP->>Recorder: record(toolName, args, result)
    Recorder->>Store: append action
    
    User->>MCP: stop_codegen_session()
    MCP->>Recorder: finalize session
    Recorder->>Store: set endTime
```

## PlaywrightTestCase Structure

The intermediate representation used during code generation:

```typescript
export interface PlaywrightTestCase {
  name: string;
  steps: string[];
  imports: Set<string>;
}
```

| Field | Type | Description |
|-------|------|-------------|
| name | string | Test case name derived from prefix and session info |
| steps | string[] | Lines of Playwright test code |
| imports | Set<string> | Required import statements for the test |

资料来源：[src/tools/codegen/types.ts:22-26]()

## Output Path Resolution

The system uses the workspace root as the base directory for generated tests:

```typescript
const getWorkspaceRoot = () => {
  return process.cwd();
};

const DEFAULT_OPTIONS: Required<CodegenOptions> = {
  outputPath: path.join(getWorkspaceRoot(), 'e2e'),
  testNamePrefix: 'Test',
  includeComments: true
};
```

Output paths are handled as follows:
- Absolute paths are used as-is
- Relative paths are resolved from the current working directory

资料来源：[src/tools/codegen/index.ts:20-30]()

## Integration with MCP Tool Execution

The recording system intercepts MCP tool calls to capture execution data. Each recorded action preserves:

- The exact tool name (e.g., `playwright_click`, `playwright_fill`)
- All parameters passed to the tool
- The timestamp of execution
- Optional result data from the tool

This captured data enables precise reproduction of user interactions when the generated test is executed.

## Error Handling

The generator validates input at initialization and during generation:

| Validation | Condition | Error |
|------------|-----------|-------|
| Session validity | Must exist with actions array | 'Invalid session data' |
| Output path type | Must be string if provided | 'outputPath must be a string' |
| Test name type | Must be string if provided | 'testNamePrefix must be a string' |
| Comments type | Must be boolean if provided | 'includeComments must be a boolean' |

资料来源：[src/tools/codegen/generator.ts:22-33]()

## Usage Example

```bash
# Start a recording session with custom options
npx @executeautomation/playwright-mcp-server

# Within your MCP client, call:
# start_codegen_session with options { outputPath: "./tests", testNamePrefix: "E2E" }

# Perform actions using playwright_* tools
# playwright_navigate, playwright_click, etc. are recorded

# Generate test code from the session
```

The generated test code can then be executed with:

```bash
npx playwright test ./tests/generated-test.spec.ts
```

## Related Documentation

- [README.md](https://github.com/executeautomation/mcp-playwright/blob/main/README.md) - Main project documentation
- [CHANGELOG.md](https://github.com/executeautomation/mcp-playwright/blob/main/CHANGELOG.md) - Version history for codegen features
- [examples/http-mode-example.md](https://github.com/executeautomation/mcp-playwright/blob/main/examples/http-mode-example.md) - HTTP mode integration

---

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

## Docker Deployment

### 相关页面

相关主题：[Getting Started](#getting-started), [Configuration Guide](#configuration)

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

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

- [Dockerfile](https://github.com/executeautomation/mcp-playwright/blob/main/Dockerfile)
- [docker-compose.yml](https://github.com/executeautomation/mcp-playwright/blob/main/docker-compose.yml)
- [DOCKER.md](https://github.com/executeautomation/mcp-playwright/blob/main/DOCKER.md)
- [docker-build.sh](https://github.com/executeautomation/mcp-playwright/blob/main/docker-build.sh)
</details>

# Docker Deployment

## Overview

The Playwright MCP Server provides Docker containerization support, enabling isolated execution environments for browser automation tasks. Docker deployment offers consistent runtime across different systems, simplified dependency management, and easy distribution of the MCP server.

The containerized solution is designed to work with pre-built artifacts from a local build, ensuring minimal image size while maintaining full functionality for browser automation through the MCP protocol.

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

## Architecture

```mermaid
graph TD
    subgraph "Host System"
        A[Local Build Directory] -->|npm install --omit=dev| B[node_modules]
        A -->|npm run build| C[dist/]
    end
    
    subgraph "Docker Container"
        D[Dockerfile] -->|COPY| E[mcp-playwright:latest]
        B -->|Production deps| E
        C -->|Built artifacts| E
    end
    
    subgraph "Runtime Components"
        E -->|stdin/stdout| F[MCP Client]
        E -->|Browser Automation| G[Playwright Browsers]
    end
    
    F -->|JSON-RPC| H[Claude Desktop / VS Code / Custom Client]
```

## Prerequisites

| Component | Requirement | Purpose |
|-----------|-------------|---------|
| Docker | Installed on host system | Container runtime |
| Docker Compose | Optional (included with Docker Desktop) | Multi-container orchestration |
| Node.js | For building locally | Pre-build step |
| Local Build | `npm install --omit=dev && npm run build` | Generate artifacts for Docker COPY |

资料来源：[DOCKER.md:prerequisites-section](https://github.com/executeautomation/mcp-playwright/blob/main/DOCKER.md)

## Building the Docker Image

### Standard Build Process

The Dockerfile copies `node_modules` and `dist` from the local build directory directly into the image. This approach requires building artifacts locally before containerization.

```bash
# 1. Install production dependencies only
npm install --omit=dev

# 2. Build the project
npm run build

# 3. Build the Docker image
docker build -t mcp-playwright:latest .
```

### Automated Build Script

A convenience script is provided for the build process:

```bash
chmod +x docker-build.sh
./docker-build.sh
```

资料来源：[DOCKER.md:building-docker-image-section](https://github.com/executeautomation/mcp-playwright/blob/main/DOCKER.md)

### Build with Custom Tag

```bash
docker build -t mcp-playwright:1.0.6 .
```

### Building from Source Inside Docker

For environments where you prefer building inside the container:

```dockerfile
FROM node:20-alpine AS builder

WORKDIR /app
COPY package*.json ./
ENV PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1
RUN npm ci

COPY src ./src
COPY tsconfig.json ./
RUN npm run build

FROM node:20-alpine
WORKDIR /app
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/package*.json ./
RUN npm ci --only=production
CMD ["node", "dist/index.js"]
```

资料来源：[DOCKER.md:building-from-source-section](https://github.com/executeautomation/mcp-playwright/blob/main/DOCKER.md)

## Running the Server

### Interactive Mode (Recommended for MCP)

MCP servers communicate via stdin/stdout, requiring interactive mode for proper operation:

```bash
docker run -i --rm mcp-playwright:latest
```

| Flag | Purpose |
|------|---------|
| `-i` | Keep STDIN open for interactive communication |
| `--rm` | Automatically remove container when it exits |
| `mcp-playwright:latest` | Image name and tag |

资料来源：[DOCKER.md:running-the-server-section](https://github.com/executeautomation/mcp-playwright/blob/main/DOCKER.md)

### Using Docker Compose

```bash
# Start the server
docker compose run --rm playwright-mcp

# Or build and run
docker compose build
docker compose run --rm playwright-mcp
```

The provided `docker-compose.yml`:

```yaml
services:
  playwright-mcp:
    build:
      context: .
      dockerfile: Dockerfile
    image: mcp-playwright:latest
    container_name: playwright-mcp-server
    stdin_open: true
    tty: true
    environment:
      - PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1
```

资料来源：[docker-compose.yml](https://github.com/executeautomation/mcp-playwright/blob/main/docker-compose.yml)

## MCP Client Integration

### Claude Desktop Configuration

Update the Claude Desktop configuration file:

| OS | Configuration Location |
|----|----------------------|
| macOS | `~/Library/Application Support/Claude/claude_desktop_config.json` |
| Windows | `%APPDATA%\Claude\claude_desktop_config.json` |
| Linux | `~/.config/Claude/claude_desktop_config.json` |

```json
{
  "mcpServers": {
    "playwright-docker": {
      "command": "docker",
      "args": ["run", "-i", "--rm", "mcp-playwright:latest"]
    }
  }
}
```

资料来源：[DOCKER.md:claude-desktop-configuration-section](https://github.com/executeautomation/mcp-playwright/blob/main/DOCKER.md)

### VS Code MCP Extension

```json
{
  "mcpServers": {
    "playwright-docker": {
      "command": "docker",
      "args": ["run", "-i", "--rm", "mcp-playwright:latest"]
    }
  }
}
```

资料来源：[DOCKER.md:vs-code-mcp-extension-section](https://github.com/executeautomation/mcp-playwright/blob/main/DOCKER.md)

## Configuration Options

### Environment Variables

| Variable | Default | Purpose |
|----------|---------|---------|
| `PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD` | `1` | Skip browser downloads to reduce image size |
| `NODE_ENV` | `production` | Runtime environment |

#### Using Environment Variables in Docker

```bash
docker run -i --rm \
  -e PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 \
  mcp-playwright:latest
```

#### Using Environment Variables in Docker Compose

```yaml
services:
  playwright-mcp:
    environment:
      - PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1
      - NODE_ENV=production
```

资料来源：[DOCKER.md:environment-variables-section](https://github.com/executeautomation/mcp-playwright/blob/main/DOCKER.md)

### Volume Mounts

For persistent data or file sharing with the container:

```bash
docker run -i --rm \
  -v $(pwd)/data:/app/data \
  mcp-playwright:latest
```

```yaml
services:
  playwright-mcp:
    volumes:
      - ./data:/app/data
      - ./screenshots:/app/screenshots
```

资料来源：[DOCKER.md:volume-mounts-section](https://github.com/executeautomation/mcp-playwright/blob/main/DOCKER.md)

### Resource Limits

```bash
docker run -i --rm \
  --cpus="2.0" \
  --memory="2g" \
  mcp-playwright:latest
```

```yaml
services:
  playwright-mcp:
    deploy:
      resources:
        limits:
          cpus: '2.0'
          memory: 2G
```

资料来源：[DOCKER.md:resource-limits-section](https://github.com/executeautomation/mcp-playwright/blob/main/DOCKER.md)

### Custom Network Configuration

```bash
# Create custom network
docker network create mcp-network

# Run container on custom network
docker run -i --rm --network mcp-network mcp-playwright:latest
```

资料来源：[DOCKER.md:advanced-usage-section](https://github.com/executeautomation/mcp-playwright/blob/main/DOCKER.md)

## Troubleshooting

### Container Exits Immediately

MCP servers wait for input on stdin. Ensure the `-i` flag is used:

```bash
docker run -i --rm mcp-playwright:latest
```

资料来源：[DOCKER.md:troubleshooting-section](https://github.com/executeautomation/mcp-playwright/blob/main/DOCKER.md)

### Browser Not Found

The Docker image skips browser downloads by default to reduce size. Playwright downloads browsers on first use. To pre-install browsers:

```dockerfile
FROM mcp-playwright:latest

# Install Playwright browsers
RUN npx playwright install chromium --with-deps
```

资料来源：[DOCKER.md:browser-not-found-section](https://github.com/executeautomation/mcp-playwright/blob/main/DOCKER.md)

### Permission Issues

If encountering permission issues with mounted volumes:

```bash
docker run -i --rm \
  -v $(pwd)/data:/app/data \
  --user $(id -u):$(id -g) \
  mcp-playwright:latest
```

资料来源：[DOCKER.md:permission-issues-section](https://github.com/executeautomation/mcp-playwright/blob/main/DOCKER.md)

## Health Checks

Add a health check to your docker-compose.yml:

```yaml
services:
  playwright-mcp:
    healthcheck:
      test: ["CMD", "node", "-e", "process.exit(0)"]
      interval: 30s
      timeout: 10s
      retries: 3
```

资料来源：[DOCKER.md:health-checks-section](https://github.com/executeautomation/mcp-playwright/blob/main/DOCKER.md)

## Security Considerations

| Practice | Implementation |
|----------|----------------|
| Non-root user | Add `USER node` to custom Dockerfile |
| Read-only root filesystem | Run with `--read-only` flag |
| Vulnerability scanning | `docker scan mcp-playwright:latest` |

### Run as Non-root User (Recommended)

```dockerfile
FROM mcp-playwright:latest
USER node
```

### Read-only Root Filesystem

```bash
docker run -i --rm --read-only mcp-playwright:latest
```

### Vulnerability Scanning

```bash
docker scan mcp-playwright:latest
```

资料来源：[DOCKER.md:security-considerations-section](https://github.com/executeautomation/mcp-playwright/blob/main/DOCKER.md)

## Image Optimization

| Optimization | Description |
|--------------|-------------|
| Base image | Debian-based slim Node.js (~200MB) |
| Artifact strategy | Copies pre-built dist from host |
| Dependencies | Production-only via `--omit=dev` |
| Browser downloads | Skipped by default |

**Current image size**: ~200MB (without browsers)

资料来源：[DOCKER.md:image-size-optimization-section](https://github.com/executeautomation/mcp-playwright/blob/main/DOCKER.md)

## Workflow Summary

```mermaid
graph LR
    A[Local Build] -->|npm install --omit=dev| B[Dependencies]
    A -->|npm run build| C[dist/]
    B -->|COPY| D[Docker Build]
    C -->|COPY| D
    D -->|docker build| E[Image Created]
    E -->|Interactive Mode| F[MCP Server Running]
    F -->|JSON-RPC| G[MCP Client Connected]
```

## Quick Reference

| Command | Description |
|---------|-------------|
| `docker build -t mcp-playwright:latest .` | Build image |
| `docker run -i --rm mcp-playwright:latest` | Run in interactive mode |
| `docker compose up` | Run via compose |
| `docker scan mcp-playwright:latest` | Security scan |

---

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

## Configuration Guide

### 相关页面

相关主题：[Getting Started](#getting-started), [Transport Modes](#transport-modes), [Docker Deployment](#docker-deployment)

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

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

- [package.json](https://github.com/executeautomation/mcp-playwright/blob/main/package.json)
- [src/http-server.ts](https://github.com/executeautomation/mcp-playwright/blob/main/src/http-server.ts)
- [DOCKER.md](https://github.com/executeautomation/mcp-playwright/blob/main/DOCKER.md)
- [examples/http-mode-example.md](https://github.com/executeautomation/mcp-playwright/blob/main/examples/http-mode-example.md)
- [README.md](https://github.com/executeautomation/mcp-playwright/blob/main/README.md)
</details>

# Configuration Guide

This guide covers all configuration options for the mcp-playwright MCP server, including stdio mode, HTTP server mode, Docker deployment, and integration with AI assistants like Claude Desktop.

## Overview

The mcp-playwright server provides browser automation capabilities through the Model Context Protocol (MCP). It supports multiple transport modes and can be configured to work with different MCP clients. 资料来源：[package.json:1-50]()

```mermaid
graph TD
    A[MCP Client] --> B{Mode Selection}
    B --> C[Stdio Mode]
    B --> D[HTTP Mode]
    B --> E[Docker Mode]
    C --> F[stdin/stdout]
    D --> G[localhost:8931]
    E --> H[Docker Container]
    F --> I[Playwright Browser]
    G --> I
    H --> I
```

## Stdio Mode Configuration

Stdio mode is the primary transport mechanism for MCP communication, using standard input/output streams. This mode is automatically selected when running via `npx` or direct node execution. 资料来源：[README.md:1-30]()

### Claude Desktop Configuration

For Claude Desktop integration, add the server configuration to your Claude Desktop config file:

| Platform | Config Location |
|----------|-----------------|
| macOS | `~/Library/Application Support/Claude/claude_desktop_config.json` |
| Windows | `%APPDATA%\Claude\claude_desktop_config.json` |
| Linux | `~/.config/Claude/claude_desktop_config.json` |

**Configuration schema:**

```json
{
  "mcpServers": {
    "playwright": {
      "command": "npx",
      "args": ["-y", "@executeautomation/playwright-mcp-server"]
    }
  }
}
```

### VS Code MCP Extension

For VS Code with MCP extension:

```json
{
  "name": "playwright",
  "command": "npx",
  "args": ["-y", "@executeautomation/playwright-mcp-server"]
}
```

> **Note:** In stdio mode, logging is automatically directed to files only (not console) to maintain clean JSON-RPC communication. Logs are written to `~/playwright-mcp-server.log`. 资料来源：[README.md:25-27]()

## HTTP Mode Configuration

HTTP mode enables the MCP server to run as a standalone HTTP server, useful for remote deployments or IDE integrations that support HTTP transport. 资料来源：[src/http-server.ts:1-50]()

### Starting the HTTP Server

```bash
# Using npx
npx @executeautomation/playwright-mcp-server --port 8931

# Or after global installation
npm install -g @executeautomation/playwright-mcp-server
playwright-mcp-server --port 8931
```

### HTTP Server Endpoints

| Endpoint | Method | Purpose |
|----------|--------|---------|
| `/sse` | GET | SSE Stream for Server-Sent Events |
| `/messages` | POST | Send messages with session ID |
| `/mcp` | GET/POST | Unified MCP endpoint |
| `/health` | GET | Health check endpoint |

### Security Configuration

The HTTP server binds to `127.0.0.1` (localhost only) by default to prevent external network access. 资料来源：[src/http-server.ts:35-36]()

```typescript
const host = '127.0.0.1';
const httpServer = app.listen(port, host, () => {
  logger.info(`Playwright MCP HTTP server listening on ${host}:${port}`);
});
```

### Claude Desktop HTTP Configuration

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

### Health Check

```bash
curl http://localhost:8931/health
```

Response format:

```json
{
  "status": "ok",
  "version": "1.0.10",
  "activeSessions": 0
}
```

## Docker Configuration

The Docker image provides a containerized deployment option for the mcp-playwright server. 资料来源：[DOCKER.md:1-50]()

### Basic Docker Run

```bash
docker run -i --rm mcp-playwright:latest
```

| Flag | Purpose |
|------|---------|
| `-i` | Keep STDIN open for interactive communication |
| `--rm` | Automatically remove container on exit |

### Docker Compose Configuration

```yaml
services:
  playwright-mcp:
    image: mcp-playwright:latest
```

### Claude Desktop Docker Configuration

```json
{
  "mcpServers": {
    "playwright-docker": {
      "command": "docker",
      "args": ["run", "-i", "--rm", "mcp-playwright:latest"]
    }
  }
}
```

### VS Code Docker Configuration

```json
{
  "name": "playwright-docker",
  "command": "docker",
  "args": ["run", "-i", "--rm", "mcp-playwright:latest"]
}
```

## Environment Variables

Configure server behavior using environment variables. 资料来源：[DOCKER.md:20-35]()

### Available Environment Variables

| Variable | Purpose | Default |
|----------|---------|---------|
| `PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD` | Skip browser downloads during image build | `1` (enabled) |
| `NODE_ENV` | Node environment setting | `production` |

### Docker Environment Variable Examples

**Via docker run:**

```bash
docker run -i --rm \
  -e PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1 \
  -e NODE_ENV=production \
  mcp-playwright:latest
```

**Via docker-compose.yml:**

```yaml
services:
  playwright-mcp:
    environment:
      - PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1
      - NODE_ENV=production
```

## Volume Mounts

Share files and persist data between the host and container. 资料来源：[DOCKER.md:36-50]()

### Docker Volume Examples

**Via docker run:**

```bash
docker run -i --rm \
  -v $(pwd)/data:/app/data \
  -v $(pwd)/screenshots:/app/screenshots \
  mcp-playwright:latest
```

**Via docker-compose.yml:**

```yaml
services:
  playwright-mcp:
    volumes:
      - ./data:/app/data
      - ./screenshots:/app/screenshots
```

### User and Permissions

Handle permission issues with mounted volumes by specifying user:

```bash
docker run -i --rm \
  -v $(pwd)/data:/app/data \
  --user $(id -u):$(id -g) \
  mcp-playwright:latest
```

## Resource Limits

Configure CPU and memory constraints for containerized deployments. 资料来源：[DOCKER.md:85-100]()

### Docker Resource Limits

```yaml
services:
  playwright-mcp:
    deploy:
      resources:
        limits:
          cpus: '2.0'
          memory: 2G
```

**Via docker run:**

```bash
docker run -i --rm \
  --cpus="2.0" \
  --memory="2g" \
  mcp-playwright:latest
```

## Network Configuration

### Custom Network

```bash
docker network create mcp-network
docker run -i --rm --network mcp-network mcp-playwright:latest
```

### Security Considerations

| Configuration | Recommendation |
|---------------|-----------------|
| Run as non-root user | Optional but recommended |
| Read-only root filesystem | For containers not needing write access |
| Vulnerability scanning | Use `docker scan mcp-playwright:latest` |

## Health Checks

Add health check configuration to docker-compose.yml:

```yaml
services:
  playwright-mcp:
    healthcheck:
      test: ["CMD", "node", "-e", "process.exit(0)"]
      interval: 30s
      timeout: 10s
      retries: 3
```

## Troubleshooting Configuration Issues

### Container Exits Immediately

MCP servers wait for input on stdin. Ensure the `-i` flag is used:

```bash
docker run -i --rm mcp-playwright:latest
```

### Browser Not Found

The Docker image skips browser downloads by default. To pre-install browsers, create a custom Dockerfile:

```dockerfile
FROM mcp-playwright:latest
RUN npx playwright install chromium --with-deps
```

## Tool Name Length Constraints

When adding new tools, consider the combined server and tool name length. Some clients like Cursor have a 60-character limit for `server_name:tool_name`. 资料来源：[README.md:10-15]()

Current server name: `playwright-mcp`

Ensure tool names are short enough to not exceed this limit when combined.

## Image Specifications

| Aspect | Value |
|--------|-------|
| Base image | Debian-based slim Node.js (~200MB) |
| Default size | ~200MB (without browsers) |
| Dependencies | Production only (no dev dependencies) |

## Building Custom Docker Images

### Optimized Build (Recommended)

Uses pre-built artifacts from local development:

```dockerfile
FROM node:20-slim
WORKDIR /app
COPY package*.json ./
RUN npm ci --omit=dev
COPY node_modules ./node_modules
COPY dist ./dist
CMD ["node", "dist/index.js"]
```

### Full Build from Source

```dockerfile
FROM node:20-alpine AS builder
WORKDIR /app
COPY package*.json ./
ENV PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD=1
RUN npm ci

COPY src ./src
COPY tsconfig.json ./
RUN npm run build

FROM node:20-alpine
WORKDIR /app
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/package*.json ./
RUN npm ci --only=production
CMD ["node", "dist/index.js"]
```

## Dependencies Configuration

The package.json defines core dependencies for the MCP server. 资料来源：[package.json:10-35]()

### Runtime Dependencies

| Package | Version | Purpose |
|---------|---------|---------|
| `@modelcontextprotocol/sdk` | 1.24.3 | MCP protocol implementation |
| `@playwright/browser-chromium` | 1.57.0 | Chromium browser |
| `@playwright/browser-firefox` | 1.57.0 | Firefox browser |
| `@playwright/browser-webkit` | 1.57.0 | WebKit browser |
| `express` | ^4.21.1 | HTTP server framework |
| `cors` | ^2.8.5 | Cross-origin resource sharing |
| `uuid` | 11.1.0 | UUID generation |

### Development Dependencies

| Package | Version | Purpose |
|---------|---------|---------|
| `typescript` | ^5.8.3 | TypeScript compiler |
| `jest` | ^29.7.0 | Testing framework |
| `@types/node` | ^20.10.5 | Node.js type definitions |
| `@types/express` | ^4.17.21 | Express type definitions |
| `jest-playwright-preset` | 4.0.0 | Playwright Jest integration |

## Logging Configuration

In stdio mode, logs are automatically directed to files to maintain clean JSON-RPC communication. 资料来源：[README.md:27]()

Log file location: `~/playwright-mcp-server.log`

The logging middleware captures:
- Request IDs for traceability
- Tool execution timing and results
- Error categorization (validation, system, resource, authentication, rate_limit)
- Sanitized request bodies (sensitive fields redacted)

## Summary

| Transport Mode | Use Case | Config Key |
|---------------|----------|------------|
| Stdio | Claude Desktop, local MCP clients | `command: "npx"` |
| HTTP | Remote deployments, VS Code | `url: "http://localhost:8931/mcp"` |
| Docker | Containerized environments | `command: "docker"` |

---

---

## Doramagic 踩坑日志

项目：executeautomation/mcp-playwright

摘要：发现 16 个潜在踩坑项，其中 2 个为 high/blocking；最高优先级：安装坑 - 来源证据：Playwright is asking for an specific browser version.。

## 1. 安装坑 · 来源证据：Playwright is asking for an specific browser version.

- 严重度：high
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Playwright is asking for an specific browser version.
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_38465ac94a9d4fb0bd352ba5209096ac | https://github.com/executeautomation/mcp-playwright/issues/117 | 来源讨论提到 node 相关条件，需在安装/试用前复核。

## 2. 安全/权限坑 · 来源证据：How to configure proxy and storageState when launching browser in Playwright MCP?

- 严重度：high
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：How to configure proxy and storageState when launching browser in Playwright MCP?
- 对用户的影响：可能影响授权、密钥配置或安全边界。
- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_a2f7e4a410994d4195a9af9f139e0caa | https://github.com/executeautomation/mcp-playwright/issues/203 | 来源类型 github_issue 暴露的待验证使用条件。

## 3. 配置坑 · 可能修改宿主 AI 配置

- 严重度：medium
- 证据强度：source_linked
- 发现：项目面向 Claude/Cursor/Codex/Gemini/OpenCode 等宿主，或安装命令涉及用户配置目录。
- 对用户的影响：安装可能改变本机 AI 工具行为，用户需要知道写入位置和回滚方法。
- 建议检查：列出会写入的配置文件、目录和卸载/回滚步骤。
- 防护动作：涉及宿主配置目录时必须给回滚路径，不能只给安装命令。
- 证据：capability.host_targets | github_repo:898077246 | https://github.com/executeautomation/mcp-playwright | host_targets=mcp_host, claude, cursor

## 4. 配置坑 · 来源证据：Add Clarvia AEO score badge to README (AEO 32/100)

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：Add Clarvia AEO score badge to README (AEO 32/100)
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_74959d07d5f74165bcd9cae829d384ce | https://github.com/executeautomation/mcp-playwright/issues/212 | 来源类型 github_issue 暴露的待验证使用条件。

## 5. 配置坑 · 来源证据：Add policy enforcement for browser automation and HTTP request tools

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：Add policy enforcement for browser automation and HTTP request tools
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_23a30d245f794b8db40c1d031b8be565 | https://github.com/executeautomation/mcp-playwright/issues/216 | 来源类型 github_issue 暴露的待验证使用条件。

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

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

## 7. 运行坑 · 来源证据：How to pass in the `--ignore-https-errors` parameter?

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个运行相关的待验证问题：How to pass in the `--ignore-https-errors` parameter?
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_47d5e333819d49b4b8ce2abb9484b23d | https://github.com/executeautomation/mcp-playwright/issues/202 | 来源类型 github_issue 暴露的待验证使用条件。

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

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

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

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

## 10. 安全/权限坑 · 存在安全注意事项

- 严重度：medium
- 证据强度：source_linked
- 发现：No sandbox install has been executed yet; downstream must verify before user use.
- 对用户的影响：用户安装前需要知道权限边界和敏感操作。
- 建议检查：转成明确权限清单和安全审查提示。
- 防护动作：安全注意事项必须面向用户前置展示。
- 证据：risks.safety_notes | github_repo:898077246 | https://github.com/executeautomation/mcp-playwright | No sandbox install has been executed yet; downstream must verify before user use.

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

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

## 12. 安全/权限坑 · 来源证据：Feature Request: Add browser context persistence for login state (userDataDir/storageState)

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

## 13. 安全/权限坑 · 来源证据：Free MCP security scan report for @executeautomation/playwright-mcp-server

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Free MCP security scan report for @executeautomation/playwright-mcp-server
- 对用户的影响：可能影响授权、密钥配置或安全边界。
- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_9720dc9967444ed08710cdb0660a212a | https://github.com/executeautomation/mcp-playwright/issues/211 | 来源讨论提到 node 相关条件，需在安装/试用前复核。

## 14. 安全/权限坑 · 来源证据：Security Advisory: SSRF, Prompt Injection, and Arbitrary JavaScript Execution via Browser Automation Tools

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Security Advisory: SSRF, Prompt Injection, and Arbitrary JavaScript Execution via Browser Automation Tools
- 对用户的影响：可能影响授权、密钥配置或安全边界。
- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_ced642164084421f84bbb63681653057 | https://github.com/executeautomation/mcp-playwright/issues/209 | 来源类型 github_issue 暴露的待验证使用条件。

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

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

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

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

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