# https://github.com/ChromeDevTools/chrome-devtools-mcp 项目说明书

生成时间：2026-05-15 14:02:19 UTC

## 目录

- [Project Overview](#overview)
- [Installation and Setup](#installation)
- [Configuration Reference](#configuration)
- [System Architecture](#system-architecture)
- [MCP Protocol Integration](#mcp-protocol)
- [Input and Navigation Automation Tools](#automation-tools)
- [Debugging and Inspection Tools](#debugging-tools)
- [Performance Analysis Tools](#performance-tools)
- [CLI Reference](#cli-reference)
- [Telemetry and Monitoring](#telemetry)

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

## Project Overview

### 相关页面

相关主题：[Installation and Setup](#installation), [System Architecture](#system-architecture), [Configuration Reference](#configuration)

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

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

- [AGENTS.md](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/AGENTS.md)
- [skills/chrome-devtools-cli/SKILL.md](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/skills/chrome-devtools-cli/SKILL.md)
- [skills/debug-optimize-lcp/SKILL.md](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/skills/debug-optimize-lcp/SKILL.md)
- [skills/a11y-debugging/SKILL.md](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/skills/a11y-debugging/SKILL.md)
- [skills/debug-optimize-lcp/references/optimization-strategies.md](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/skills/debug-optimize-lcp/references/optimization-strategies.md)
- [scripts/eval_scenarios/snapshot_test.ts](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/scripts/eval_scenarios/snapshot_test.ts)
- [scripts/eval_scenarios/performance_test.ts](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/scripts/eval_scenarios/performance_test.ts)
- [src/tools/ToolDefinition.ts](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/src/tools/ToolDefinition.ts)
- [src/McpResponse.ts](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/src/McpResponse.ts)
- [src/tools/webmcp.ts](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/src/tools/webmcp.ts)
- [src/PageCollector.ts](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/src/PageCollector.ts)
</details>

# Project Overview

## Introduction

The **chrome-devtools-mcp** project is a Model Context Protocol (MCP) server and command-line interface (CLI) for Chrome DevTools. It provides a comprehensive bridge that enables AI assistants, automated testing systems, and developer tools to programmatically control and interact with Chrome browser instances through Chrome DevTools Protocol (CDP).

资料来源：[AGENTS.md](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/AGENTS.md)

## Core Purpose and Scope

The project serves as an abstraction layer that exposes Chrome DevTools capabilities as MCP tools, making browser automation accessible through a standardized protocol. This enables use cases including:

- **AI-Powered Browser Automation**: Allowing language models to control browsers for research, testing, and data extraction
- **Performance Analysis**: Capturing traces, analyzing Largest Contentful Paint (LCP), and measuring page load metrics
- **Accessibility Auditing**: Running automated accessibility checks and inspecting the accessibility tree
- **End-to-End Testing**: Automating user interactions including navigation, form filling, and element inspection
- **WebMCP Tool Execution**: Running custom tools exposed by web pages through the WebMCP protocol

资料来源：[skills/chrome-devtools-cli/SKILL.md](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/skills/chrome-devtools-cli/SKILL.md)

## Architecture Overview

The system follows a layered architecture with distinct components:

```mermaid
graph TD
    A[CLI / AI Agent] --> B[MCP Server]
    B --> C[Tool Registry]
    C --> D[CDP Client]
    D --> E[Chrome Browser]
    F[WebMCP Tools] -.-> B
    G[PageCollector] --> H[Event Listeners]
    H --> E
```

### Component Layers

| Layer | Purpose | Key Files |
|-------|---------|-----------|
| **MCP Protocol** | Standardized communication interface | `src/McpResponse.ts` |
| **Tool System** | Tool definitions and schema validation | `src/tools/ToolDefinition.ts` |
| **CDP Bridge** | Chrome DevTools Protocol communication | `src/PageCollector.ts` |
| **Skills Layer** | Domain-specific tool groupings | `skills/*/SKILL.md` |

资料来源：[src/McpResponse.ts](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/src/McpResponse.ts) and [src/PageCollector.ts](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/src/PageCollector.ts)

## Tool Categories

The project organizes tools into the following categories:

| Category | Description | Example Tools |
|----------|-------------|---------------|
| **Navigation** | Page navigation and management | `navigate_page`, `new_page`, `close_page`, `select_page` |
| **Inspection** | Page content and state inspection | `take_snapshot`, `take_screenshot`, `evaluate_script` |
| **Interaction** | User simulation | `type_text`, `press_key`, `fill_form`, `upload_file` |
| **Performance** | Performance measurement and tracing | `performance_start_trace`, `performance_stop_trace`, `take_memory_snapshot` |
| **Emulation** | Browser environment simulation | `emulate`, `resize_page` |
| **Network** | Network request inspection | (Network-related tools) |
| **Accessibility** | A11y auditing | Lighthouse-based accessibility audits |
| **WEBMCP** | Dynamic page-exposed tools | `list_webmcp_tools`, `execute_webmcp_tool` |

资料来源：[skills/chrome-devtools-cli/SKILL.md](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/skills/chrome-devtools-cli/SKILL.md)

## Page Management System

The `PageCollector` class manages multiple browser pages using Chrome's target lifecycle:

```mermaid
graph LR
    A[Browser Instance] -->|targetcreated| B[PageCollector]
    A -->|targetdestroyed| B
    B --> C[WeakMap Storage]
    C --> D[Navigation History]
    D --> E[Resource Tracking]
```

Key characteristics:
- **Multiple Page Support**: Manages several open pages simultaneously
- **Navigation History**: Stores up to 3 recent navigations per page (`maxNavigationSaved = 3`)
- **Resource Tracking**: Collects resources per navigation sub-list
- **Event-Driven**: Listens to Chrome target lifecycle events

资料来源：[src/PageCollector.ts](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/src/PageCollector.ts)

## Tool Definition System

The tool system uses TypeScript and Zod for schema validation. Two primary tool types exist:

### Global Tools

Tools that operate independently of page context:

```typescript
export function defineTool<Schema extends zod.ZodRawShape>(
  definition: ToolDefinition<Schema>,
): DefinedTool<Schema>;
```

### Page-Scoped Tools

Tools that require a selected page context:

```typescript
export function definePageTool<Schema extends zod.ZodRawShape>(
  definition: PageToolDefinition<Schema>,
): DefinedPageTool<Schema>;
```

#### Page Scope Schema

```typescript
export const pageIdSchema = {
  pageId: zod.number().optional().describe('Targets a specific page by ID.'),
};
```

#### Timeout Schema

```typescript
export const timeoutSchema = {
  timeout: zod
    .number()
    .int()
    .optional()
    .describe(
      `Maximum wait time in milliseconds. If set to 0, the default timeout will be used.`,
    ),
};
```

资料来源：[src/tools/ToolDefinition.ts](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/src/tools/ToolDefinition.ts)

## WebMCP Integration

WebMCP enables web pages to expose custom tools that can be discovered and executed by this MCP server. The system provides two tools:

| Tool | Purpose |
|------|---------|
| `list_webmcp_tools` | Lists all WebMCP tools the current page exposes |
| `execute_webmcp_tool` | Executes a named WebMCP tool with optional JSON parameters |

```typescript
export const listWebMcpTools = definePageTool({
  name: 'list_webmcp_tools',
  description: `Lists all WebMCP tools the page exposes.`,
  annotations: {
    category: ToolCategory.WEBMCP,
    readOnlyHint: true,
  },
  schema: {},
  blockedByDialog: false,
});
```

资料来源：[src/tools/webmcp.ts](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/src/tools/webmcp.ts)

## Navigation Tools

The project provides comprehensive navigation capabilities:

### Basic Navigation

| Command | Description |
|---------|-------------|
| `new_page` | Creates a new page, optionally at a specified URL |
| `navigate_page` | Navigates the selected page to a URL or performs back/reload |
| `select_page` | Selects a page as the context for future tool calls |
| `close_page` | Closes a page by index |

### Navigation Options

```typescript
interface NavigationOptions {
  url?: string;                    // Target URL
  type?: 'navigate' | 'back' | 'reload';
  timeout?: number;                // Navigation timeout in ms
  ignoreCache?: boolean;          // Ignore cache on reload
  bringToFront?: boolean;         // Bring page to front after selection
  background?: boolean;            // Create page in background
  isolatedContext?: string;       // Isolated world context name
  handleBeforeUnload?: 'accept' | 'dismiss';
  initScript?: string;             // JavaScript to run after navigation
}
```

资料来源：[skills/chrome-devtools-cli/SKILL.md](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/skills/chrome-devtools-cli/SKILL.md)

## Performance Analysis Tools

### Tracing Workflow

```mermaid
graph LR
    A[performance_start_trace] --> B[User Interactions]
    B --> C[performance_stop_trace]
    C --> D[Trace Analysis]
    D --> E[insight_analyze_insight]
```

### Available Performance Tools

| Tool | Purpose |
|------|---------|
| `performance_start_trace` | Starts performance trace recording |
| `performance_stop_trace` | Stops the active trace |
| `performance_analyze_insight` | Gets details on specific Performance Insights |
| `take_memory_snapshot` | Captures memory heapsnapshot |

### LCP Optimization Debugging

The project includes specialized tools for debugging Largest Contentful Paint issues:

1. **Identify LCP Element**: Extract element tag, id, className, URL, and timing data
2. **Audit Common Issues**: Check for lazy-loaded images in viewport, missing fetchpriority
3. **Optimization Strategies**: Preload, fetchpriority, modern formats, critical CSS inlining

资料来源：[skills/debug-optimize-lcp/SKILL.md](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/skills/debug-optimize-lcp/SKILL.md) and [skills/debug-optimize-lcp/references/optimization-strategies.md](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/skills/debug-optimize-lcp/references/optimization-strategies.md)

## Accessibility Debugging Tools

### Core A11y Workflow

```mermaid
graph TD
    A[Lighthouse Audit] --> B{Analyze Score}
    B -->|Score < 1| C[Review Failed Audits]
    B -->|Pass| D[Snapshot Tree]
    C --> D
    D --> E[Check Semantics]
    E --> F[Verify Labels]
    F --> G[Test Keyboard Nav]
```

### Key Capabilities

- **Automated Audits**: Run Lighthouse accessibility audits with JSON report output
- **Accessibility Tree Inspection**: Use `take_snapshot` to capture the semantic structure
- **Semantic Analysis**: Verify heading hierarchy, ARIA landmarks
- **Label Verification**: Ensure all form inputs have associated labels
- **Keyboard Navigation**: Test focus management using `press_key` with Tab navigation

资料来源：[skills/a11y-debugging/SKILL.md](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/skills/a11y-debugging/SKILL.md)

## Evaluation Framework

The project includes a test framework for verifying tool usage correctness:

```typescript
export interface TestScenario {
  prompt: string;           // The prompt to send to the model
  maxTurns: number;        // Maximum conversation turns
  htmlRoute?: {            // Optional custom HTML for testing
    path: string;
    htmlContent: string;
  };
  expectations: (calls: ToolCall[]) => void;  // Validation function
}
```

### Example Test Scenarios

| Scenario | Purpose |
|----------|---------|
| `snapshot_test.ts` | Verifies navigation followed by snapshot capture |
| `performance_test.ts` | Verifies navigation followed by trace start |
| `fill_select_and_checkboxes_test.ts` | Verifies form interaction patterns |

资料来源：[scripts/eval_scenarios/snapshot_test.ts](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/scripts/eval_scenarios/snapshot_test.ts) and [scripts/eval_scenarios/performance_test.ts](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/scripts/eval_scenarios/performance_test.ts)

## Response Format

The MCP response system supports structured output with multiple content sections:

| Section | Content |
|---------|---------|
| `toolDefinitions` | List of available tools with schemas |
| `webmcpTools` | Page-exposed WebMCP tools |
| `networkRequests` | Captured network requests (when enabled) |
| `pagination` | Pagination metadata for large result sets |

```typescript
structuredContent.webmcpTools = data.webmcpTools.map(
  ({name, description, inputSchema, annotations}) => ({
    name,
    description,
    inputSchema,
    annotations,
  }),
);
```

资料来源：[src/McpResponse.ts](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/src/McpResponse.ts)

## Build and Development

### Available npm Scripts

| Script | Purpose |
|--------|---------|
| `npm run build` | Compile TypeScript and verify build |
| `npm run test` | Build and run all tests |
| `npm run test <path>` | Build and run a single test file |
| `npm run format` | Fix formatting and show linting errors |
| `npm run gen` | Generate tool reference documentation |

### TypeScript Guidelines

The project enforces strict TypeScript practices:

- **No `any` type**: Use proper generics and unknown types
- **No `as` keyword**: Use type guards and type predicates
- **No `!` operator**: Use explicit null checks
- **No `// @ts-ignore`**: Fix actual type issues
- **Prefer `for..of`**: Over `forEach` for better type inference

资料来源：[AGENTS.md](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/AGENTS.md)

## Installation

The CLI can be installed globally via npm:

```bash
npm i chrome-devtools-mcp@latest -g
chrome-devtools status  # Verify installation
```

Troubleshooting tips include ensuring the global npm `bin` directory is in PATH and avoiding `sudo` by using node version managers.

资料来源：[skills/chrome-devtools-cli/references/installation.md](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/skills/chrome-devtools-cli/references/installation.md)

## Summary

The chrome-devtools-mcp project provides a powerful bridge between AI assistants and Chrome DevTools, enabling programmatic browser control through a well-structured MCP interface. Its comprehensive tool system covers navigation, inspection, interaction, performance analysis, and accessibility auditing, while the WebMCP integration allows dynamic tool exposure from web pages. The TypeScript-based architecture with Zod schema validation ensures type safety and developer productivity, making it suitable for both automated testing and AI-driven browser interactions.

---

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

## Installation and Setup

### 相关页面

相关主题：[Project Overview](#overview), [Configuration Reference](#configuration)

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

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

- [AGENTS.md](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/AGENTS.md)
- [CONTRIBUTING.md](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/CONTRIBUTING.md)
- [skills/chrome-devtools-cli/references/installation.md](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/skills/chrome-devtools-cli/references/installation.md)
- [skills/chrome-devtools-cli/SKILL.md](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/skills/chrome-devtools-cli/SKILL.md)
- [package.json](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/package.json)
</details>

# Installation and Setup

This page covers all methods for installing and configuring the **chrome-devtools-mcp** project, including global CLI usage, local development setup, and MCP server integration.

## Overview

The chrome-devtools-mcp project provides two primary interfaces:

1. **CLI Tool** (`chrome-devtools`) - A command-line interface for terminal-based browser automation
2. **MCP Server** - A Model Context Protocol server for integrating Chrome DevTools into AI assistants

The installation approach depends on your use case:

| Use Case | Recommended Method | Installation Command |
|----------|-------------------|---------------------|
| Terminal automation | Global CLI | `npm i chrome-devtools-mcp@latest -g` |
| AI assistant integration | MCP Server | Clone and build from source |
| Development contribution | Local development | Clone, install dependencies, build |

资料来源：[skills/chrome-devtools-cli/references/installation.md:1-5]()

## Prerequisites

### Node.js Version Requirement

The project requires a specific Node.js version defined in `.nvmrc`. Before installation, ensure you have the correct version:

```bash
# Check the required Node.js version
cat .nvmrc
```

Using a Node version manager (such as nvm) is strongly recommended to avoid permission errors and manage multiple Node versions.

资料来源：[CONTRIBUTING.md:31-35]()

### System Requirements

- **Operating System**: macOS, Linux, or Windows with WSL
- **Chrome/Chromium**: Chrome browser must be installed on the system
- **npm**: Node Package Manager (included with Node.js)
- **Optional**: ffmpeg (required only for experimental screencast feature)

## Method 1: Global CLI Installation

### Installation

Install the package globally to make the `chrome-devtools` command available system-wide:

```bash
npm i chrome-devtools-mcp@latest -g
```

资料来源：[skills/chrome-devtools-cli/references/installation.md:5]()

### Verification

After installation, verify the setup:

```bash
chrome-devtools status
```

A successful output indicates the CLI is properly installed and accessible.

资料来源：[skills/chrome-devtools-cli/references/installation.md:7]()

## Method 2: Local Development Setup

For contributing to the project or running the latest development version:

### Workflow Diagram

```mermaid
graph TD
    A[Clone Repository] --> B[Check Node.js Version]
    B --> C{nvm installed?}
    C -->|No| D[Install nvm]
    C -->|Yes| E[Run nvm use]
    D --> E
    E --> F[Run npm ci]
    F --> G[Run npm run build]
    G --> H[Verify with npm run test]
    H --> I[Setup Complete]
```

### Step-by-Step Instructions

#### 1. Clone the Repository

```bash
git clone https://github.com/ChromeDevTools/chrome-devtools-mcp.git
cd chrome-devtools-mcp
```

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

#### 2. Set Node.js Version

```bash
nvm use
```

This reads the version from `.nvmrc` and switches to the correct Node.js version.

#### 3. Install Dependencies

```bash
npm ci
```

The `npm ci` command performs a clean install using the exact versions from `package-lock.json`, ensuring consistency across environments.

资料来源：[CONTRIBUTING.md:36]()

#### 4. Build the Project

```bash
npm run build
```

This command runs TypeScript compilation (`tsc`) and verifies the build succeeds. The build output is placed in the `build/` directory.

资料来源：[AGENTS.md:5]()

### Available npm Scripts

| Script | Purpose |
|--------|---------|
| `npm run build` | Compile TypeScript and test build |
| `npm run test` | Build and run all tests |
| `npm run test <path>` | Build and run a single test file |
| `npm run format` | Fix formatting and show linting errors |

资料来源：[AGENTS.md:5-10]()

## Method 3: MCP Server Configuration

For integrating with AI assistants that support the Model Context Protocol.

### Configuration Schema

```json
{
  "mcpServers": {
    "chrome-devtools": {
      "command": "node",
      "args": ["/path-to/build/src/bin/chrome-devtools-mcp.js"]
    }
  }
}
```

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

### MCP Server Binary Location

After building, the MCP server executable is located at:

```
build/src/bin/chrome-devtools-mcp.js
```

### Using with Inspector

Test the MCP server using the official inspector:

```bash
npx @modelcontextprotocol/inspector node /build/src/bin/chrome-devtools-mcp.js
```

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

### VS Code SSH Configuration

When running the inspector with VS Code SSH, two ports are spawned:

| Port | Purpose |
|------|---------|
| 6274 | Primary service (auto-forwarded by VS Code) |
| 6277 | Secondary service (requires manual forwarding) |

Manual port forwarding may be required for port 6277.

资料来源：[CONTRIBUTING.md:54-58]()

## Service Management

The CLI includes service management commands:

```bash
chrome-devtools start   # Start or restart chrome-devtools-mcp
chrome-devtools status  # Check if chrome-devtools-mcp is running
chrome-devtools stop    # Stop chrome-devtools-mcp if running
```

资料来源：[skills/chrome-devtools-cli/SKILL.md:67-70]()

For AI workflows, the background server starts implicitly on first tool call—do not manually run `start`/`status`/`stop` before each use.

## CLI Arguments and Configuration

Configure the MCP server behavior using CLI arguments in your MCP configuration:

```bash
npx chrome-devtools-mcp@latest --help
```

### Common Configuration Flags

| Flag | Description | Example |
|------|-------------|---------|
| `--categoryExtensions` | Enable Chrome extension support | `--categoryExtensions` |
| `--experimentalVision` | Enable experimental vision tools | `--experimentalVision=true` |
| `--experimentalScreencast` | Enable screencast (requires ffmpeg) | `--experimentalScreencast=true` |
| `--categoryExperimentalWebmcp` | Enable experimental WebMCP tools | `--categoryExperimentalWebmcp=true` |

资料来源：[skills/chrome-devtools-cli/SKILL.md:1-3]()

## TypeScript Development Guidelines

When developing or contributing to this project, adhere to strict TypeScript rules:

| Rule | Description |
|------|-------------|
| No `any` type | Use explicit types |
| No `as` keyword | Use type guards or proper casting |
| No `!` operator | Avoid non-null assertions |
| No `@ts-ignore` | Fix actual type errors |
| Prefer `for..of` | Over `forEach` |

资料来源：[AGENTS.md:13-20]()

## Troubleshooting

### Command Not Found

If `chrome-devtools` is not recognized after installation:

1. Ensure your global npm `bin` directory is in your system's `PATH`
2. Restart your terminal or source your shell configuration file (e.g., `.bashrc`, `.zshrc`)

资料来源：[skills/chrome-devtools-cli/references/installation.md:11-13]()

### Permission Errors

If you encounter `EACCES` or permission errors during installation:

- **Do not** use `sudo`
- Use a node version manager like `nvm`
- Or configure npm to use a different global directory

资料来源：[skills/chrome-devtools-cli/references/installation.md:16-19]()

### Old Version Running

If an outdated version is running:

```bash
chrome-devtools stop && npm uninstall -g chrome-devtools-mcp
npm i chrome-devtools-mcp@latest -g
```

资料来源：[skills/chrome-devtools-cli/references/installation.md:22-25]()

### Debug Logging

To write debug logs to `log.txt` in the working directory, see the debugging section in CONTRIBUTING.md.

资料来源：[CONTRIBUTING.md:62-63]()

## Lighthouse Dependency Updates

The project bundles Lighthouse for performance auditing. To update the Lighthouse dependency:

1. Update the Lighthouse version in `package.json`
2. Run `npm install`
3. Check out the corresponding Lighthouse repository revision to a sibling directory (`../lighthouse`)
4. Run `npm run update-lighthouse` (requires yarn)
5. Commit the bundle

资料来源：[CONTRIBUTING.md:24-29]()

## Quick Reference

```bash
# Global CLI installation
npm i chrome-devtools-mcp@latest -g

# Verify installation
chrome-devtools status

# Development setup
git clone https://github.com/ChromeDevTools/chrome-devtools-mcp.git
cd chrome-devtools-mcp
nvm use
npm ci
npm run build
npm run test

# MCP server configuration
{
  "mcpServers": {
    "chrome-devtools": {
      "command": "node",
      "args": ["/path-to/build/src/bin/chrome-devtools-mcp.js"]
    }
  }
}

---

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

## Configuration Reference

### 相关页面

相关主题：[Installation and Setup](#installation), [CLI Reference](#cli-reference), [MCP Protocol Integration](#mcp-protocol)

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

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

- [src/bin/chrome-devtools-mcp-cli-options.ts](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/src/bin/chrome-devtools-mcp-cli-options.ts)
- [src/bin/chrome-devtools-mcp-main.ts](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/src/bin/chrome-devtools-mcp-main.ts)
- [puppeteer.config.cjs](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/puppeteer.config.cjs)
- [.mcp.json](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/.mcp.json)
</details>

# Configuration Reference

This page documents all configuration options available for the `chrome-devtools-mcp` project, covering CLI arguments, MCP server initialization, Puppeteer browser settings, and MCP client configuration files.

## Overview

The `chrome-devtools-mcp` project supports multiple layers of configuration:

1. **CLI Arguments** - Command-line flags passed when starting the MCP server or CLI
2. **Puppeteer Configuration** - Browser launch and connection settings
3. **MCP Client Configuration** - JSON configuration for connecting MCP clients

Configuration flows through the application as follows:

```mermaid
graph TD
    A[CLI Arguments] --> B[chrome-devtools-mcp-cli-options.ts]
    B --> C[ParsedArguments Type]
    C --> D[chrome-devtools-mcp-main.ts]
    D --> E[Puppeteer Launch]
    F[.mcp.json] --> G[MCP Client]
    G --> H[MCP Server Connection]
```

## CLI Configuration

The MCP server accepts numerous command-line arguments for customization. These are defined in `src/bin/chrome-devtools-mcp-cli-options.ts` and typed via the `ParsedArguments` interface.

### General Options

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `--port` | `number` | `6274` | Port for the MCP server to listen on |
| `--host` | `string` | `"127.0.0.1"` | Host address to bind |
| `--log-file` | `string` | `undefined` | Path to write debug logs |
| `--help` | `boolean` | `false` | Show help message |

资料来源：[src/bin/chrome-devtools-mcp-cli-options.ts](src/bin/chrome-devtools-mcp-cli-options.ts)

### Browser Connection Options

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `--browserUrl` | `string` | `undefined` | Connect to an existing Chrome instance at this URL |
| `--autoConnect` | `boolean` | `true` | Automatically connect to existing Chrome |
| `--browserPath` | `string` | `undefined` | Custom path to Chrome executable |
| `--userDataDir` | `string` | `undefined` | Chrome profile directory path |

资料来源：[src/bin/chrome-devtools-mcp-cli-options.ts](src/bin/chrome-devtools-mcp-cli-options.ts)

### Browser Launch Options

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `--headless` | `boolean` | `true` | Run Chrome in headless mode |
| `--sandbox` | `boolean` | `true` | Enable Chrome sandbox mode |
| `--noFirstRun` | `boolean` | `true` | Skip first-run dialogs |
| `--windowSize` | `string` | `"1920x1080"` | Default window dimensions |

资料来源：[src/bin/chrome-devtools-mcp-cli-options.ts](src/bin/chrome-devtools-mcp-cli-options.ts)

### MCP Server Categories

The MCP server organizes tools into categories. Categories can be enabled or disabled using `--category*` flags:

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `--categoryNavigation` | `boolean` | `true` | Navigation tools (navigate_page, new_page) |
| `--categoryInteraction` | `boolean` | `true` | Interaction tools (click, fill, type) |
| `--categoryInspection` | `boolean` | `true` | Inspection tools (take_snapshot, take_screenshot) |
| `--categoryPerformance` | `boolean` | `true` | Performance tools (traces, profiles) |
| `--categoryNetwork` | `boolean` | `true` | Network tools (network_interceptor) |
| `--categoryExtensions` | `boolean` | `false` | Chrome extension management |
| `--categoryExperimental` | `boolean` | `false` | Experimental tools |
| `--categoryExperimentalWebmcp` | `boolean` | `false` | WebMCP integration tools |
| `--categoryDebugging` | `boolean` | `false` | Debugging utilities |

```bash
# Enable extension support
chrome-devtools-mcp --categoryExtensions=true

# Enable experimental features
chrome-devtools-mcp --categoryExperimental=true --experimentalVision=true
```

资料来源：[src/tools/categories.ts](src/tools/categories.ts) 资料来源：[skills/chrome-devtools/SKILL.md](skills/chrome-devtools/SKILL.md)

### Experimental Features

Experimental features require explicit enabling via CLI flags:

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `--experimentalVision` | `boolean` | `false` | Enable coordinate-based clicking (click_at) |
| `--experimentalScreencast` | `boolean` | `false` | Enable screencast recording |

```bash
# Start with experimental vision mode
chrome-devtools-mcp --experimentalVision=true
```

资料来源：[skills/chrome-devtools-cli/SKILL.md](skills/chrome-devtools-cli/SKILL.md)

### Debugging Options

| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `--verbose` | `boolean` | `false` | Enable verbose logging |
| `DEBUG` | `env` | `undefined` | Debug categories filter |

```sh
# Run with debug logging to log.txt
npx @modelcontextprotocol/inspector node /build/src/bin/chrome-devtools-mcp.js --log-file=/path/to/log.txt
```

资料来源：[CONTRIBUTING.md](CONTRIBUTING.md)

## Puppeteer Configuration

The project uses Puppeteer for browser automation. Configuration is defined in `puppeteer.config.cjs` and can be overridden via CLI arguments.

### Configuration File Structure

```javascript
// puppeteer.config.cjs
module.exports = {
  puppeteer: {
    // Browser launch arguments
    args: [
      '--no-sandbox',
      '--disable-setuid-sandbox',
      '--disable-dev-shm-usage',
    ],
    // Default launch settings
    headless: true,
  }
};
```

### Default Browser Arguments

The following Chromium arguments are passed by default:

| Argument | Purpose |
|----------|---------|
| `--no-sandbox` | Disable sandbox (may be overridden by `--sandbox`) |
| `--disable-setuid-sandbox` | Prevent setuid complications |
| `--disable-dev-shm-usage` | Avoid shared memory issues in containers |
| `--disable-web-security` | Disable web security for testing |
| `--ash-no-nudges` | Disable Ash nudges |

### Connection Modes

The MCP server supports two browser connection modes:

```mermaid
graph TD
    A[Start chrome-devtools-mcp] --> B{--browserUrl provided?}
    B -->|Yes| C[Remote Connection Mode]
    B -->|No| D[Launch Mode]
    D --> E{--userDataDir provided?}
    E -->|Yes| F[Use existing profile]
    E -->|No| G[Create temporary profile]
    C --> H[Connect via CDP WebSocket]
    F --> I[Puppeteer.launch]
    G --> I
```

1. **Launch Mode** (default): Puppeteer launches a new Chrome instance
2. **Remote Connection Mode**: Connect to an existing Chrome via `--browserUrl`

资料来源：[src/bin/chrome-devtools-mcp-main.ts](src/bin/chrome-devtools-mcp-main.ts)

## MCP Client Configuration

The `.mcp.json` file provides configuration for MCP clients connecting to the server.

### Example Configuration

```json
{
  "mcpServers": {
    "chrome-devtools": {
      "command": "npx",
      "args": ["chrome-devtools-mcp@latest"],
      "env": {}
    }
  }
}
```

### Extended Configuration Example

```json
{
  "mcpServers": {
    "chrome-devtools": {
      "command": "node",
      "args": [
        "/path/to/chrome-devtools-mcp/build/src/bin/chrome-devtools-mcp.js",
        "--port", "6274",
        "--headless", "false",
        "--categoryExtensions", "true"
      ],
      "env": {}
    }
  }
}
```

### Configuration for Remote Connection

To connect to a specific Chrome instance:

```json
{
  "mcpServers": {
    "chrome-devtools": {
      "command": "npx",
      "args": [
        "chrome-devtools-mcp@latest",
        "--browserUrl", "http://localhost:9222",
        "--autoConnect", "true"
      ]
    }
  }
}
```

资料来源：[.mcp.json](.mcp.json)

## Tool Categories and Annotations

Tools are annotated with metadata that affects their availability based on configuration:

### Category Reference

| Category | Flag | Description |
|----------|------|-------------|
| `NAVIGATION` | `--categoryNavigation` | Page navigation and management |
| `INTERACTION` | `--categoryInteraction` | User interaction (clicks, fills) |
| `INSPECTION` | `--categoryInspection` | Page inspection (snapshots, screenshots) |
| `PERFORMANCE` | `--categoryPerformance` | Performance profiling |
| `NETWORK` | `--categoryNetwork` | Network request handling |
| `EXTENSIONS` | `--categoryExtensions` | Chrome extension management |
| `EXPERIMENTAL` | `--categoryExperimental` | Experimental tools |
| `EXPERIMENTAL_WEBMCP` | `--categoryExperimentalWebmcp` | WebMCP integration |
| `DEBUGGING` | `--categoryDebugging` | Debug utilities |

### Tool Annotation Schema

```typescript
interface ToolAnnotation {
  title?: string;
  category?: ToolCategory;
  conditions?: string[];  // Required flags for tool availability
  readOnlyHint?: boolean; // Indicates if tool modifies browser state
}
```

Tools marked with `readOnlyHint: false` may be blocked in read-only MCP modes.

```mermaid
graph LR
    A[Tool Annotation] --> B[readOnlyHint]
    A --> C[category]
    A --> D[conditions]
    B --> E{Client Mode}
    C --> F[Category Filter]
    D --> G[Flag Check]
    E -->|Plan/ReadOnly| H[Only readOnlyHint=true]
    E -->|Normal| I[All tools]
```

资料来源：[src/tools/ToolDefinition.ts](src/tools/ToolDefinition.ts) 资料来源：[skills/troubleshooting/SKILL.md](skills/troubleshooting/SKILL.md)

## Environment Variables

| Variable | Description |
|----------|-------------|
| `DEBUG` | Controls debug logging categories (e.g., `DEBUG=*`) |
| `PUPPETEER_SKIP_DOWNLOAD` | Skip Puppeteer browser download |
| `PUPPETEER_EXECUTABLE_PATH` | Custom Chrome executable path |

## Configuration Precedence

Configuration values are resolved in the following order (highest to lowest):

1. **CLI Arguments** - Explicit flags passed at runtime
2. **Environment Variables** - Set in shell or `.env` files
3. **Configuration Files** - `.mcp.json`, `puppeteer.config.cjs`
4. **Default Values** - Built-in defaults in source code

```mermaid
graph TD
    A[Configuration Resolution] --> B[CLI Arguments]
    A --> C[Environment Variables]
    A --> D[Config Files]
    A --> E[Defaults]
    B --> F[Final Config]
    C --> F
    D --> F
    E --> F
    style B fill:#ff9999
    style F fill:#99ff99
```

## Quick Reference

### Minimal Configuration

```bash
# Default settings (headless, localhost:6274)
npx chrome-devtools-mcp@latest
```

### Common Configurations

```bash
# Visible browser with extensions
chrome-devtools-mcp --headless=false --categoryExtensions=true

# Remote Chrome connection
chrome-devtools-mcp --browserUrl=http://localhost:9222

# Custom port
chrome-devtools-mcp --port=9000
```

## Troubleshooting Configuration Issues

| Symptom | Likely Cause | Solution |
|---------|--------------|----------|
| Only 9 tools available | Read-only mode enforced by MCP client | Disable read-only/Plan mode in client |
| Extension tools missing | `--categoryExtensions` not enabled | Add `--categoryExtensions=true` |
| New profile created instead of connecting | Incorrect `--browserUrl` or typo in flags | Verify URL and check for flag typos like `--autoBronnect` |
| `chrome-devtools` command not found | PATH not configured | Ensure npm global bin is in PATH |

资料来源：[skills/troubleshooting/SKILL.md](skills/troubleshooting/SKILL.md)

---

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

## System Architecture

### 相关页面

相关主题：[Project Overview](#overview), [MCP Protocol Integration](#mcp-protocol), [Telemetry and Monitoring](#telemetry)

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

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

- [src/tools/ToolDefinition.ts](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/src/tools/ToolDefinition.ts)
- [src/PageCollector.ts](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/src/PageCollector.ts)
- [src/tools/webmcp.ts](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/src/tools/webmcp.ts)
- [src/tools/categories.ts](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/src/tools/categories.ts)
- [src/browser.ts](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/src/browser.ts)
- [AGENTS.md](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/AGENTS.md)
</details>

# System Architecture

## Overview

The `chrome-devtools-mcp` project implements a Model Context Protocol (MCP) server that provides programmatic control over Chrome DevTools through a well-defined architecture of interconnected components. The system enables AI assistants and CLI tools to interact with a headless Chrome browser instance by exposing browser operations as typed tools with schema validation.

The architecture follows a layered design pattern with clear separation between the protocol layer (MCP), the tool definition system, browser management, and page-level interactions. This modular approach allows for extensibility while maintaining type safety and consistent behavior across all exposed functionality.

资料来源：[AGENTS.md]()

## High-Level Architecture

```mermaid
graph TD
    subgraph "Client Layer"
        CLI[CLI Tool<br>chrome-devtools]
        AI[AI Assistant<br>MCP Client]
    end

    subgraph "MCP Protocol Layer"
        MCP[MCP Server<br>Protocol Handler]
        TDEF[Tool Definitions<br>Registry]
    end

    subgraph "Tool System"
        PAGES[Page Tools<br>Context-Aware]
        GLOB[Global Tools<br>Browser-Level]
    end

    subgraph "Browser Layer"
        CHROME[Chrome Browser<br>Puppeteer/CDP]
        PAGES_BROWSER[Pages<br>Target Management]
    end

    CLI --> MCP
    AI --> MCP
    MCP --> TDEF
    TDEF --> PAGES
    TDEF --> GLOB
    MCP --> CHROME
    CHROME --> PAGES_BROWSER
```

## Core Components

### 1. Tool Definition System

The tool definition system is the foundation of the MCP server's extensibility. It provides factory functions for creating both page-scoped and global tools with automatic schema validation.

| Component | File | Purpose |
|-----------|------|---------|
| `defineTool` | `src/tools/ToolDefinition.ts:11-30` | Factory for global tools |
| `definePageTool` | `src/tools/ToolDefinition.ts:52-90` | Factory for page-scoped tools |
| `ToolCategory` | `src/tools/categories.ts` | Tool categorization enum |

The `defineTool` function supports two invocation patterns:

```typescript
// Direct tool definition
defineTool({
  name: 'tool_name',
  schema: { /* zod schema */ },
  handler: async (request, response, context) => { /* ... */ }
});

// Factory pattern with arguments
defineTool((args?: Args) => ({
  name: 'tool_name',
  schema: { /* zod schema using args */ },
  handler: async (request, response, context) => { /* ... */ }
}));
```

资料来源：[src/tools/ToolDefinition.ts:11-30]()

### 2. Page Scoped Tools

Page-scoped tools are tools that operate within the context of a specific browser page. They receive an additional `page` property in the request object and have access to the page's DOM, JavaScript context, and rendering state.

```typescript
export function definePageTool<
  Schema extends zod.ZodRawShape,
  Args extends ParsedArguments = ParsedArguments,
>(
  definition:
    | PageToolDefinition<Schema>
    | ((args?: Args) => PageToolDefinition<Schema>),
): DefinedPageTool<Schema> | ((args?: Args) => DefinedPageTool<Schema>)
```

The returned tool automatically receives the `pageScoped: true` marker, which the MCP server uses to route requests appropriately. Each page-scoped tool handler receives:

- `request`: Contains both the parsed schema arguments and `{ page: ContextPage }`
- `response`: Response object for sending results back to the client
- `context`: Full context object with browser and session information

资料来源：[src/tools/ToolDefinition.ts:52-90]()

### 3. Page Collector Pattern

The `PageCollector` class manages the lifecycle of browser pages and collects events/data from them. It implements the observer pattern for tracking page creation and destruction.

```mermaid
graph TD
    subgraph "PageCollector Lifecycle"
        INIT[init(pages: Page[])]
        ADD[addPage(page)]
        LISTEN[Start Event Listeners]
    end

    subgraph "Event Handling"
        CREATED[targetcreated<br>Event]
        DESTROYED[targetdestroyed<br>Event]
    end

    subgraph "Storage"
        STORAGE[(WeakMap&lt;Page,<br>Array&lt;Array&lt;WithSymbolId&lt;T&gt;&gt;&gt;&gt;)]
    end

    INIT --> ADD
    ADD --> LISTEN
    CREATED --> ADD
    LISTEN --> STORAGE
```

Key characteristics of the `PageCollector`:

| Property | Description |
|----------|-------------|
| `#browser` | Reference to the Puppeteer Browser instance |
| `#listenersInitializer` | Factory function for creating event listeners |
| `#listeners` | WeakMap tracking active listeners per page |
| `maxNavigationSaved` | Maximum navigations to retain (default: 3) |
| `storage` | WeakMap storing collected data per page |

资料来源：[src/PageCollector.ts]()

### 4. Browser Management

The browser module (`src/browser.ts`) handles the initialization and lifecycle of the Puppeteer-based Chrome browser instance. It provides the foundation for all page operations and CDP (Chrome DevTools Protocol) interactions.

The browser layer is responsible for:

- Launching headless Chrome with appropriate flags
- Managing browser context and isolated worlds
- Coordinating page creation and destruction
- Providing access to CDP sessions for advanced operations

资料来源：[src/browser.ts]()

### 5. WebMCP Tool System

The WebMCP system allows pages to expose their own tools to the MCP server, enabling dynamic tool discovery and execution from web applications.

```mermaid
graph LR
    WEB[Web Application<br>Exposes Tools]
    MCP[MCP Server]
    EXEC[execute_webmcp_tool]
    LIST[list_webmcp_tools]

    WEB --> LIST
    LIST --> WEB
    WEB --> EXEC
    EXEC --> WEB
```

Two primary tools manage WebMCP functionality:

| Tool | Purpose |
|------|---------|
| `list_webmcp_tools` | Enumerates all WebMCP tools exposed by the current page |
| `execute_webmcp_tool` | Invokes a named WebMCP tool with optional parameters |

```typescript
export const listWebMcpTools = definePageTool({
  name: 'list_webmcp_tools',
  description: `Lists all WebMCP tools the page exposes.`,
  annotations: {
    category: ToolCategory.WEBMCP,
    readOnlyHint: true,
  },
  schema: {},
  blockedByDialog: false,
  handler: async (_request, response, _context) => {
    response.setListWebMcpTools();
  },
});
```

资料来源：[src/tools/webmcp.ts]()

## Tool Categories

Tools are organized into categories for logical grouping and documentation purposes. The category system enables documentation generation and tool discovery.

| Category | Description |
|----------|-------------|
| `WEBMCP` | Tools exposed by web pages themselves |
| Navigation | Page navigation and history operations |
| Input | Form filling, clicking, keyboard input |
| Capture | Screenshots, snapshots, memory profiling |
| Network | Network request inspection and manipulation |
| Performance | Tracing, profiling, performance insights |

资料来源：[src/tools/categories.ts]()

## Request/Response Flow

```mermaid
sequenceDiagram
    participant Client
    participant MCP as MCP Server
    participant TDEF as Tool Definitions
    participant HANDLER as Tool Handler
    participant BROWSER as Browser/Page

    Client->>MCP: Tool Request (with args)
    MCP->>TDEF: Lookup Tool Definition
    TDEF-->>MCP: Schema + Handler Reference
    MCP->>MCP: Validate Arguments (Zod)
    MCP->>HANDLER: Invoke Handler(request, response, context)
    HANDLER->>BROWSER: CDP Commands / Puppeteer API
    BROWSER-->>HANDLER: Result
    HANDLER-->>MCP: Update Response
    MCP-->>Client: JSON-RPC Response
```

## Tool Schema System

All tool parameters are validated using Zod schemas, ensuring type safety and providing automatic OpenAPI-style documentation.

```typescript
// Schema definition example
schema: {
  toolName: zod.string().describe('The name of the WebMCP tool to execute'),
  input: zod
    .string()
    .optional()
    .describe('The JSON-stringified parameters to pass to the WebMCP tool'),
}
```

The schema system supports:

- **Required/Optional detection**: Automatically determines if fields are required based on Zod type
- **Type transformations**: Applied via `.transform()` for input normalization
- **Descriptions**: Extracted for documentation generation
- **Enumerations**: Validated against allowed values

Common schema utilities include:

| Schema | File | Purpose |
|--------|------|---------|
| `pageIdSchema` | `ToolDefinition.ts:95-97` | Optional page targeting |
| `timeoutSchema` | `ToolDefinition.ts:99-107` | Timeout with zero-to-undefined transform |
| `viewportTransform` | `ToolDefinition.ts` | Viewport dimension parsing |

资料来源：[src/tools/ToolDefinition.ts:95-107]()

## Error Handling Patterns

The architecture defines specific error constants for expected failure conditions:

```typescript
export const CLOSE_PAGE_ERROR =
  'The last open page cannot be closed. It is fine to keep it open.';
```

This error message indicates that the MCP server intentionally allows users to keep the final browser page open rather than forcing closure, which is a deliberate UX decision for browser automation workflows.

## Type Safety Guarantees

The codebase enforces strict TypeScript practices to maintain type safety:

| Rule | Rationale |
|------|-----------|
| No `any` type | Prevents untyped data flow |
| No `as` casting | Avoids bypass of type checking |
| No `!` assertions | Prevents unsafe assumptions |
| No `// @ts-ignore` | Maintains full type coverage |
| Prefer `for..of` over `forEach` | Better async/await compatibility |

资料来源：[AGENTS.md]()

## Build and Test Infrastructure

```mermaid
graph LR
    subgraph "Build Commands"
        BUILD[npm run build<br>tsc compilation]
        TEST[npm run test<br>Build + Run Tests]
        FORMAT[npm run format<br>Fix linting]
        GEN[npm run gen<br>Generate Docs]
    end

    subgraph "Output Artifacts"
        JS[JavaScript<br>/build/src]
        TYPES[Type Declarations<br>/build/src]
        DOCS[Markdown Docs<br>/skills/*]
    end

    BUILD --> JS
    BUILD --> TYPES
    TEST --> JS
    GEN --> DOCS
```

The project uses a standardized build pipeline that ensures type correctness at compile time and provides consistent tooling for development tasks.

## Summary

The chrome-devtools-mcp system architecture provides:

1. **Extensible Tool System**: Factory functions for creating typed, validated tools
2. **Page Context Awareness**: Automatic injection of page context into tool handlers
3. **Event-Driven Page Management**: Observer pattern for tracking browser page lifecycle
4. **Schema Validation**: Zod-based runtime validation with compile-time type inference
5. **WebMCP Integration**: Bidirectional tool exposure between server and web pages
6. **Strict Type Safety**: No escape hatches for type checking, ensuring reliability

This architecture enables reliable browser automation while maintaining the flexibility needed for diverse use cases ranging from simple navigation to complex performance profiling and accessibility debugging.

---

<a id='mcp-protocol'></a>

## MCP Protocol Integration

### 相关页面

相关主题：[System Architecture](#system-architecture), [Input and Navigation Automation Tools](#automation-tools), [Debugging and Inspection Tools](#debugging-tools)

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

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

- [src/index.ts](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/src/index.ts)
- [src/McpResponse.ts](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/src/McpResponse.ts)
- [src/tools/ToolDefinition.ts](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/src/tools/ToolDefinition.ts)
- [src/tools/webmcp.ts](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/src/tools/webmcp.ts)
- [src/tools/categories.ts](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/src/tools/categories.ts)
- [scripts/generate-docs.ts](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/scripts/generate-docs.ts)
</details>

# MCP Protocol Integration

## Overview

The `chrome-devtools-mcp` project implements a Model Context Protocol (MCP) server that enables AI assistants and MCP clients to interact with Chrome DevTools programmatically. This integration provides a standardized interface for browser automation, debugging, and performance analysis through a collection of well-defined tools.

The MCP protocol serves as the communication layer between AI assistants and the Chrome browser, allowing tools to be discovered, invoked, and executed remotely. The server handles tool registration, request routing, response formatting, and maintains state across multiple browser pages.

资料来源：[src/index.ts:1-50](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/src/index.ts)

## Architecture

### High-Level System Design

```mermaid
graph TD
    MCP_CLIENT["MCP Client / AI Assistant"]
    MCP_SERVER["MCP Server<br/>(chrome-devtools-mcp)"]
    TOOL_REGISTRY["Tool Registry"]
    BROWSER["Chrome Browser"]
    CDP["Chrome DevTools Protocol"]
    
    MCP_CLIENT -->|"Call Tool Request"| MCP_SERVER
    MCP_SERVER -->|"Tool Definitions"| MCP_CLIENT
    MCP_SERVER --> TOOL_REGISTRY
    TOOL_REGISTRY -->|"Handler Execution"| MCP_SERVER
    MCP_SERVER -->|"CDP Commands"| BROWSER
    BROWSER --> CDP
```

### Tool Registration Flow

```mermaid
graph TD
    START["Server Initialization"] --> CREATE_TOOLS["createTools()"]
    CREATE_TOOLS --> REGISTER["registerTool()"]
    REGISTER --> DEFINE["definePageTool()"]
    DEFINE --> SCHEMA["Schema Validation"]
    SCHEMA --> HANDLER["Handler Mapping"]
    HANDLER --> READY["Tool Available"]
    
    STYLE REGISTER fill:#90EE90
    STYLE READY fill:#98FB98
```

The MCP server initializes by invoking `createTools()` which returns an array of tool definitions. Each tool is then registered with the MCP server using the protocol's `setRequestHandler()` method. Tools are defined using `definePageTool()` which establishes the tool name, description, input schema, annotations, and handler function.

资料来源：[src/index.ts:40-65](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/src/index.ts)

## Tool Definition System

### ToolDefinition.ts Pattern

Tools are defined using the `definePageTool()` function which creates a structured tool definition with type-safe schemas. The definition includes metadata, validation rules, and the execution handler.

```typescript
export const listWebMcpTools = definePageTool({
  name: 'list_webmcp_tools',
  description: `Lists all WebMCP tools the page exposes.`,
  annotations: {
    category: ToolCategory.WEBMCP,
    readOnlyHint: true,
  },
  schema: {},
  blockedByDialog: false,
  handler: async (_request, response, _context) => {
    response.setListWebMcpTools();
  },
});
```

资料来源：[src/tools/webmcp.ts:15-27](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/src/tools/webmcp.ts)

### Tool Definition Structure

| Property | Type | Description |
|----------|------|-------------|
| `name` | `string` | Unique identifier for the tool |
| `description` | `string` | Human-readable description for the MCP client |
| `annotations` | `ToolAnnotations` | Metadata about the tool's behavior |
| `schema` | `ZodSchema` | Input validation schema |
| `blockedByDialog` | `boolean` | Whether the tool waits for dialog dismissal |
| `handler` | `AsyncHandler` | Function that executes the tool |

### Tool Annotations

The annotation system provides additional metadata about tools that MCP clients can use for tool selection, permission handling, and UI display.

```typescript
interface ToolAnnotations {
  category?: ToolCategory;
  readOnlyHint?: boolean;
  conditions?: string[];
  // Additional annotation properties...
}
```

| Annotation | Type | Purpose |
|------------|------|---------|
| `category` | `ToolCategory` | Groups tools into logical categories |
| `readOnlyHint` | `boolean` | Indicates if tool doesn't modify browser state |
| `conditions` | `string[]` | Flags required for this tool to execute |

资料来源：[src/tools/ToolDefinition.ts](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/src/tools/ToolDefinition.ts)

## Tool Categories

Tools are organized into categories that help MCP clients understand their purpose and scope.

```mermaid
graph TD
    TOOLS["All Tools"]
    NAV["Navigation<br/>(navigate, new_page, close)"]
    INPUT["Input Automation<br/>(click, fill, type_text)"]
    EMULATE["Emulation<br/>(viewport, userAgent)"]
    PERFORMANCE["Performance<br/>(trace, analyze)"]
    NETWORK["Network<br/>(requests, cookies)"]
    WEBMCP["WebMCP<br/>(page-exposed tools)"]
    
    TOOLS --> NAV
    TOOLS --> INPUT
    TOOLS --> EMULATE
    TOOLS --> PERFORMANCE
    TOOLS --> NETWORK
    TOOLS --> WEBMCP
```

### Available Categories

| Category | Enum Value | Description |
|----------|-------------|-------------|
| Navigation | `ToolCategory.NAVIGATION` | Page navigation and management |
| Input Automation | `ToolCategory.INPUT` | Element interaction and form input |
| Emulation | `ToolCategory.EMULATION` | Browser environment simulation |
| Performance | `ToolCategory.PERFORMANCE` | Tracing and performance analysis |
| Network | `ToolCategory.NETWORK` | Network request inspection |
| WebMCP | `ToolCategory.WEBMCP` | Tools exposed by the web page |
| Accessibility | `ToolCategory.A11Y` | Accessibility auditing |
| Debug | `ToolCategory.DEBUG` | JavaScript debugging tools |

资料来源：[src/tools/categories.ts](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/src/tools/categories.ts)

## Response System

### McpResponse Architecture

The response system formats tool execution results into structured MCP responses that include both human-readable markdown and machine-parseable structured content.

```mermaid
graph LR
    REQUEST["Tool Request"] --> HANDLER["Tool Handler"]
    HANDLER --> RESPONSE["McpResponse"]
    RESPONSE -->|Text Content| MARKDOWN["Markdown Output"]
    RESPONSE -->|Structured Data| JSON["JSON / Structured"]
    
    subgraph Response Components
        TOOL_DEFS["Tool Definitions"]
        NETWORK["Network Requests"]
        PAGINATION["Pagination Info"]
        WEBMCP_TOOLS["WebMCP Tools"]
    end
    
    RESPONSE --> TOOL_DEFS
    RESPONSE --> NETWORK
    RESPONSE --> PAGINATION
    RESPONSE --> WEBMCP_TOOLS
```

### Response Formatting Features

| Feature | Description |
|---------|-------------|
| **Tool Definitions** | Lists all available tools with their schemas |
| **Network Requests** | Includes network waterfall data when requested |
| **Pagination** | Handles large result sets with pagination info |
| **WebMCP Tools** | Lists tools exposed by the current web page |
| **Structured Content** | Provides machine-readable data alongside text |

资料来源：[src/McpResponse.ts:50-120](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/src/McpResponse.ts)

### Structured Content Model

The `structuredContent` object provides programmatic access to response data:

```typescript
interface StructuredContent {
  webmcpTools?: WebMcpToolInfo[];
  networkRequests?: NetworkRequest[];
  pagination?: PaginationInfo;
  [key: string]: unknown;
}
```

### Pagination Support

When handling large datasets (e.g., network requests), the response includes pagination metadata:

```typescript
const paginationData = this.#dataWithPagination(
  requests,
  this.#networkRequestsOptions.pagination,
);
structuredContent.pagination = paginationData.pagination;
```

资料来源：[src/McpResponse.ts:150-180](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/src/McpResponse.ts)

## WebMCP Integration

WebMCP enables web pages to expose custom tools that MCP clients can discover and invoke. This creates a two-way communication channel where the browser can extend its capabilities based on the loaded page.

```mermaid
graph TD
    MCP_CLIENT["MCP Client"]
    SERVER["MCP Server"]
    CHROME["Chrome Browser"]
    WEB_PAGE["Web Page"]
    
    subgraph Discovery Flow
        CLIENT_LIST["list_webmcp_tools"]
        SERVER -->|"Query"| CHROME
        CHROME --> WEB_PAGE
        WEB_PAGE -->|"Exposes tools"| CHROME
        CHROME -->|"Tool list"| SERVER
        SERVER -->|"Tool names"| CLIENT_LIST
    end
    
    subgraph Execution Flow
        EXEC["execute_webmcp_tool"]
        CLIENT -->|"toolName + input"| SERVER
        SERVER -->|"Forward"| CHROME
        CHROME --> WEB_PAGE
        WEB_PAGE -->|"Execute"| RESULT["Result"]
    end
```

### WebMCP Tools

| Tool | Description | Parameters |
|------|-------------|------------|
| `list_webmcp_tools` | Lists all tools exposed by the current page | None |
| `execute_webmcp_tool` | Invokes a WebMCP tool exposed by the page | `toolName`, `input` (JSON string) |

The `execute_webmcp_tool` accepts input as a JSON string which is parsed and passed to the page-exposed tool:

```typescript
let input: Record<string, unknown> = {};
if (request.params.input) {
  try {
    const parsed = JSON.parse(request.params.input);
    if (typeof parsed === 'object' && parsed !== null) {
      input = parsed;
    }
  } catch (error) {
    // Handle parse error
  }
}
```

资料来源：[src/tools/webmcp.ts:29-60](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/src/tools/webmcp.ts)

## Tool Documentation Generation

The repository includes a documentation generation system that parses tool definitions and produces formatted markdown:

```mermaid
graph TD
    SOURCE["Tool Source Files"]
    PARSER["Documentation Parser"]
    ANNOTATIONS["Parse Annotations"]
    SCHEMA["Parse Input Schema"]
    CROSSLINKS["Add Cross-References"]
    OUTPUT["Markdown Documentation"]
    
    SOURCE --> PARSER
    PARSER --> ANNOTATIONS
    PARSER --> SCHEMA
    ANNOTATIONS --> CROSSLINKS
    SCHEMA --> CROSSLINKS
    CROSSLINKS --> OUTPUT
```

### Schema Documentation

Properties are sorted by required status first, then alphabetically:

```typescript
const propertyNames = Object.keys(properties).sort((a, b) => {
  const aRequired = required.includes(a);
  const bRequired = required.includes(b);
  if (aRequired && !bRequired) return -1;
  if (!aRequired && bRequired) return 1;
  return a.localeCompare(b);
});
```

Required properties are marked with `**(required)**` and optional properties with `_(optional)_`.

资料来源：[scripts/generate-docs.ts:100-140](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/scripts/generate-docs.ts)

## Server Initialization

### Startup Sequence

```mermaid
sequenceDiagram
    participant CLI as CLI / MCP Client
    participant Server as MCP Server
    participant Tools as Tool Registry
    participant Browser as Chrome Browser
    
    CLI->>Server: Initialize with args
    Server->>Server: parseArguments()
    Server->>Tools: createTools()
    Tools->>Server: Tool definitions
    loop For each tool
        Server->>Server: registerTool()
    end
    Server->>Server: loadIssueDescriptions()
    Server->>CLI: Server ready
```

### Tool Registration Implementation

```typescript
const tools = createTools(serverArgs);
for (const tool of tools) {
  server.setRequestHandler(
    {name: tool.name, description: tool.description, ...},
    async (params) => {
      return await toolHandler.handle(params);
    },
  );
}
```

资料来源：[src/index.ts:45-60](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/src/index.ts)

## Configuration and Flags

The MCP server accepts various configuration options that affect tool behavior:

| Flag | Description | Default |
|------|-------------|---------|
| `--slim` | Disables non-essential features | `false` |
| `--performanceCrux` | Enable CrUX API for performance data | `true` |
| `--usageStatistics` | Enable anonymous usage collection | `true` |
| `--browser-url` | Direct browser connection URL | - |
| `--autoConnect` | Auto-handshake with running Chrome | `false` |
| `--logFile` | Debug log file path | - |

### Disclaimer System

The server logs disclaimers on startup to inform users about data exposure:

```typescript
export const logDisclaimers = (args) => {
  console.error(`chrome-devtools-mcp exposes content of the browser instance...`);
  
  if (!args.slim && args.performanceCrux) {
    console.error(`Performance tools may send trace URLs to Google CrUX API...`);
  }
};
```

资料来源：[src/index.ts:70-90](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/src/index.ts)

## Type Safety

The codebase enforces strict TypeScript practices:

| Rule | Enforcement |
|------|-------------|
| No `any` type | All types must be explicitly defined |
| No `as` casts | Use type guards and transforms |
| No `!` assertions | Use conditional checks |
| No `@ts-ignore` | Code must compile cleanly |
| No `@ts-nocheck` | Full type checking required |

Tools use Zod schemas for runtime validation, ensuring that the runtime behavior matches the TypeScript types:

```typescript
schema: {
  toolName: zod.string().describe('The name of the WebMCP tool to execute'),
  input: zod.string().optional().describe('The JSON-stringified parameters...'),
},
```

资料来源：[src/tools/webmcp.ts:30-40](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/src/tools/webmcp.ts)

---

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

## Input and Navigation Automation Tools

### 相关页面

相关主题：[Debugging and Inspection Tools](#debugging-tools), [Performance Analysis Tools](#performance-tools), [Configuration Reference](#configuration)

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

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

- [src/tools/input.ts](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/src/tools/input.ts)
- [src/tools/pages.ts](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/src/tools/pages.ts)
- [src/tools/emulation.ts](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/src/tools/emulation.ts)
- [src/WaitForHelper.ts](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/src/WaitForHelper.ts)
- [src/utils/keyboard.ts](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/src/utils/keyboard.ts)
- [docs/tool-reference.md](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/docs/tool-reference.md)
- [skills/chrome-devtools-cli/SKILL.md](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/skills/chrome-devtools-cli/SKILL.md)
- [skills/chrome-devtools/SKILL.md](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/skills/chrome-devtools/SKILL.md)
</details>

# Input and Navigation Automation Tools

## Overview

The Input and Navigation Automation Tools constitute the core interaction layer of the `chrome-devtools-mcp` project, enabling programmatic control over browser pages through the Chrome DevTools Protocol (CDP). These tools allow AI agents and automated scripts to simulate real user interactions including keyboard input, mouse actions, page navigation, and environment emulation.

**资料来源:** [skills/chrome-devtools/SKILL.md](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/skills/chrome-devtools/SKILL.md)

## Architecture

The automation system is organized into three primary tool categories that work in concert to provide comprehensive browser control:

```mermaid
graph TD
    A[chrome-devtools-mcp Tools] --> B[Input Tools]
    A --> C[Navigation Tools]
    A --> D[Emulation Tools]
    
    B --> B1[click]
    B --> B2[fill]
    B --> B3[type_text]
    B --> B4[press_key]
    B --> B5[hover]
    B --> B6[drag]
    B --> B7[upload_file]
    
    C --> C1[navigate_page]
    C --> C2[new_page]
    C --> C3[select_page]
    C --> C4[close_page]
    C --> C5[list_pages]
    
    D --> D1[emulate]
    D --> D2[resize_page]
    
    E[WaitForHelper] --> B
    E --> C
```

**资料来源:** [src/tools/ToolDefinition.ts](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/src/tools/ToolDefinition.ts)

## Input Tools

Input tools provide the capability to simulate user interactions with page elements. All input operations require a valid element `uid` obtained from a previous `take_snapshot` call.

**资料来源:** [skills/chrome-devtools-cli/SKILL.md](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/skills/chrome-devtools-cli/SKILL.md)

### Core Input Operations

| Tool | Purpose | Key Parameters |
|------|---------|----------------|
| `click` | Click on an element | `uid` (required), `dblClick`, `includeSnapshot` |
| `fill` | Fill text into input/select | `uid` (required), `value` (required), `includeSnapshot` |
| `type_text` | Type text character by character | `text` (required), `submitKey`, `includeSnapshot` |
| `press_key` | Press a key or combination | `key` (required), `includeSnapshot` |
| `hover` | Hover over an element | `uid` (required), `includeSnapshot` |
| `drag` | Drag element to destination | `src` (required), `dst` (required), `includeSnapshot` |
| `upload_file` | Upload file via input element | `uid` (required), `filePath` (required), `includeSnapshot` |

**资料来源:** [src/tools/input.ts](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/src/tools/input.ts)

### Keyboard Handling

The keyboard system supports complex key combinations through a modifier parsing mechanism defined in `src/utils/keyboard.ts`:

```typescript
// Key format: "Control+A", "Control+Shift+R", "Alt+F4"
const tokens = parseKey(request.params.key);
const [key, ...modifiers] = tokens;
```

**资料来源:** [src/utils/keyboard.ts](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/src/utils/keyboard.ts)

Supported modifiers:
- `Control`
- `Shift`
- `Alt`
- `Meta`

### Interaction Workflow

```mermaid
sequenceDiagram
    participant Agent as AI Agent
    participant Snapshot as take_snapshot
    participant Input as Input Tool
    participant Page as Chrome Page
    
    Agent->>Page: navigate_page / new_page
    Agent->>Snapshot: take_snapshot
    Snapshot-->>Agent: Element UIDs
    Agent->>Input: click uid="1_5"
    Input->>Page: CDP Input.dispatchMouseEvent
    Page-->>Input: Mouse click confirmed
    Input-->>Agent: Result response
```

**资料来源:** [skills/chrome-devtools/SKILL.md](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/skills/chrome-devtools/SKILL.md)

### Common Input Patterns

**Typing with Submit:**
```bash
chrome-devtools type_text "hello" --submitKey "Enter"
```

**Click with Snapshot:**
```bash
chrome-devtools click "uid" --includeSnapshot true
```

**Pressing Key Combinations:**
```bash
chrome-devtools press_key "Control+A" --includeSnapshot true
```

**资料来源:** [skills/chrome-devtools-cli/SKILL.md](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/skills/chrome-devtools-cli/SKILL.md)

## Navigation Tools

Navigation tools manage page lifecycle and context within the browser instance.

**资料来源:** [src/tools/pages.ts](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/src/tools/pages.ts)

### Page Management Operations

| Tool | Purpose | Key Parameters |
|------|---------|----------------|
| `navigate_page` | Navigate current page to URL | `url` (required), `type`, `ignoreCache`, `timeout`, `handleBeforeUnload`, `initScript` |
| `new_page` | Create new page/tab | `url`, `background`, `timeout`, `isolatedContext` |
| `select_page` | Set active page context | `pageId` (required), `bringToFront` |
| `close_page` | Close page by index | `pageId` (optional) |
| `list_pages` | List all open pages | - |

**资料来源:** [src/tools/pages.ts](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/src/tools/pages.ts)

### Navigation Types

The `navigate_page` tool supports multiple navigation types:

```typescript
type: "navigate" | "reload" | "back" | "forward"
```

| Type | Behavior |
|------|----------|
| `navigate` | Default navigation to specified URL |
| `reload` | Reload current page (supports `ignoreCache`) |
| `back` | Navigate to previous page in history |
| `forward` | Navigate to next page in history |

**资料来源:** [src/tools/pages.ts](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/src/tools/pages.ts)

### Before Unload Handling

When navigating away from a page with pending changes, the browser may display a "before unload" dialog:

```bash
chrome-devtools navigate_page --url "https://example.com" --handleBeforeUnload "accept"
```

| Option | Behavior |
|--------|----------|
| `accept` | Proceed with navigation, dismiss dialog |
| `dismiss` | Cancel navigation |

**资料来源:** [skills/chrome-devtools-cli/SKILL.md](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/skills/chrome-devtools-cli/SKILL.md)

### Multi-Page Context Management

Pages are managed with a zero-based index system. The `select_page` tool changes the active page context for subsequent tool calls:

```bash
# List pages to see available pages
chrome-devtools list_pages

# Select page by index
chrome-devtools select_page 1 --bringToFront true
```

**资料来源:** [skills/chrome-devtools/SKILL.md](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/skills/chrome-devtools/SKILL.md)

### Isolated Contexts

New pages can be created with isolated JavaScript contexts, useful for testing extensions or isolated scripts:

```bash
chrome-devtools new_page "https://example.com" --isolatedContext "ctx"
```

**资料来源:** [src/tools/pages.ts](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/src/tools/pages.ts)

### Page Lifecycle

```mermaid
stateDiagram-v2
    [*] --> created: new_page
    created --> active: select_page
    active --> background: select_page (other)
    background --> active: select_page (bringToFront)
    active --> closed: close_page
    closed --> [*]
    
    active --> navigating: navigate_page
    navigating --> active: Load complete
```

**资料来源:** [src/PageCollector.ts](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/src/PageCollector.ts)

## Emulation Tools

Emulation tools control browser environment settings including network conditions, CPU throttling, geolocation, viewport, and user agent.

**资料来源:** [src/tools/emulation.ts](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/src/tools/emulation.ts)

### Emulation Capabilities

| Capability | Parameters | Description |
|------------|------------|-------------|
| Network Conditions | `networkConditions` | Preset: "Offline", "Slow 3G", "Fast 3G", etc. |
| CPU Throttling | `cpuThrottlingRate` | Multiplier (e.g., 4 = 4x slowdown) |
| Geolocation | `geolocation` | Coordinates in format "lat,lng" |
| Color Scheme | `colorScheme` | "light" or "dark" |
| Viewport | `viewport` | Format: "WIDTHxHEIGHT" (e.g., "1920x1080") |
| User Agent | `userAgent` | Custom UA string |

**资料来源:** [src/tools/emulation.ts](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/src/tools/emulation.ts)

### Emulation Commands

**Network Emulation:**
```bash
chrome-devtools emulate --networkConditions "Offline"
```

**Multiple Emulations:**
```bash
chrome-devtools emulate --cpuThrottlingRate 4 --geolocation "0x0"
```

**Visual Emulation:**
```bash
chrome-devtools emulate --colorScheme "dark" --viewport "1920x1080"
```

**User Agent Spoofing:**
```bash
chrome-devtools emulate --userAgent "Mozilla/5.0..."
```

**资料来源:** [skills/chrome-devtools-cli/SKILL.md](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/skills/chrome-devtools-cli/SKILL.md)

### Page Resize

The `resize_page` tool resizes the selected page's window:

```bash
chrome-devtools resize_page 1920 1080
```

**资料来源:** [src/tools/emulation.ts](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/src/tools/emulation.ts)

## WaitForHelper

The `WaitForHelper` module provides synchronization mechanisms to ensure page elements are ready before interactions occur.

**资料来源:** [src/WaitForHelper.ts](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/src/WaitForHelper.ts)

### Wait Strategies

| Strategy | Description |
|----------|-------------|
| `wait_for` | Generic wait for specified duration or condition |
| Event-based | Wait for navigation, network idle, or element state |
| Timeout handling | Configurable timeout with default fallback |

**资料来源:** [skills/chrome-devtools/SKILL.md](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/skills/chrome-devtools/SKILL.md)

### Recommended Workflow

The official workflow ensures reliable automation:

1. **Navigate**: Use `navigate_page` or `new_page`
2. **Wait**: Use `wait_for` if you know what to look for
3. **Snapshot**: Use `take_snapshot` to understand page structure
4. **Interact**: Use element `uid`s from snapshot for `click`, `fill`, etc.

**资料来源:** [skills/chrome-devtools/SKILL.md](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/skills/chrome-devtools/SKILL.md)

## Tool Configuration Schema

All tools follow a consistent schema pattern defined in `src/tools/ToolDefinition.ts`:

```typescript
export const timeoutSchema = {
  timeout: zod
    .number()
    .int()
    .optional()
    .describe(
      `Maximum wait time in milliseconds. If set to 0, the default timeout will be used.`,
    )
    .transform(value => {
      return value && value <= 0 ? undefined : value;
    }),
};

export const pageIdSchema = {
  pageId: zod.number().optional().describe('Targets a specific page by ID.'),
};
```

**资料来源:** [src/tools/ToolDefinition.ts](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/src/tools/ToolDefinition.ts)

### IncludeSnapshot Pattern

Many input tools support the `includeSnapshot` flag to return an updated page snapshot after the action:

```bash
chrome-devtools click "id" --includeSnapshot true
```

When `true`, the response includes the full accessibility tree, allowing chaining without an explicit `take_snapshot` call.

**资料来源:** [skills/chrome-devtools-cli/SKILL.md](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/skills/chrome-devtools-cli/SKILL.md)

## Error Handling

### Dialog Blocking

Some input tools are blocked when a dialog is present:

```typescript
blockedByDialog: true,
```

In such cases, use `handle_dialog` first:

```bash
chrome-devtools handle_dialog accept
chrome-devtools handle_dialog dismiss --promptText "hi"
```

**资料来源:** [src/tools/input.ts](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/src/tools/input.ts)

### Page Closure Restrictions

The last open page cannot be closed:

```typescript
export const CLOSE_PAGE_ERROR =
  'The last open page cannot be closed. It is fine to keep it open.';
```

**资料来源:** [src/tools/ToolDefinition.ts](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/src/tools/ToolDefinition.ts)

## CLI Usage

All tools are accessible via the `chrome-devtools` CLI:

```bash
chrome-devtools <tool> [arguments] [flags]
```

### Help System

```bash
chrome-devtools take_snapshot --help
```

### Output Formats

By default, output is in Markdown. Use `--output-format=json` for JSON output:

```bash
chrome-devtools list_pages --output-format=json
```

**资料来源:** [skills/chrome-devtools-cli/SKILL.md](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/skills/chrome-devtools-cli/SKILL.md)

## Tool Categories

Tools are organized into categories for documentation and navigation:

| Category | Description |
|----------|-------------|
| `INPUT` | Keyboard, mouse, and element interactions |
| `NAVIGATION` | Page lifecycle and context management |
| `EMULATION` | Browser environment control |
| `INSPECTION` | Page inspection and snapshots |
| `PERFORMANCE` | Performance tracing and analysis |
| `NETWORK` | Network request inspection |

**资料来源:** [docs/tool-reference.md](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/docs/tool-reference.md)

## Testing and Validation

The repository includes test scenarios that validate tool behavior:

```typescript
expectations: calls => {
  assert.ok(
    calls[0].name === 'navigate_page' || calls[0].name === 'new_page',
  );
  assert.strictEqual(calls[1].name, 'take_snapshot');
  assert.strictEqual(calls[2].name, 'fill_form');
}
```

**资料来源:** [scripts/eval_scenarios/fill_select_and_checkboxes_test.ts](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/scripts/eval_scenarios/fill_select_and_checkboxes_test.ts)

## Summary

The Input and Navigation Automation Tools provide a comprehensive API for browser automation through:

- **Input Tools**: Simulate user interactions with precise element targeting
- **Navigation Tools**: Full page lifecycle management including multi-page contexts
- **Emulation Tools**: Control browser environment for testing various conditions
- **WaitForHelper**: Synchronization primitives for reliable automation

These tools work together to enable reliable browser automation workflows suitable for testing, scraping, and AI agent interactions.

---

<a id='debugging-tools'></a>

## Debugging and Inspection Tools

### 相关页面

相关主题：[Input and Navigation Automation Tools](#automation-tools), [Performance Analysis Tools](#performance-tools)

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

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

- [src/tools/snapshot.ts](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/src/tools/snapshot.ts)
- [src/tools/screenshot.ts](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/src/tools/screenshot.ts)
- [src/tools/network.ts](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/src/tools/network.ts)
- [src/tools/console.ts](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/src/tools/console.ts)
- [src/tools/memory.ts](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/src/tools/memory.ts)
- [src/formatters/ConsoleFormatter.ts](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/src/formatters/ConsoleFormatter.ts)
- [src/formatters/NetworkFormatter.ts](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/src/formatters/NetworkFormatter.ts)
- [src/formatters/SnapshotFormatter.ts](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/src/formatters/SnapshotFormatter.ts)
</details>

# Debugging and Inspection Tools

## Overview

The Debugging and Inspection Tools in chrome-devtools-mcp provide comprehensive capabilities for examining browser page state, accessibility trees, console output, network activity, and memory usage. These tools serve as the primary interface for automated debugging, accessibility auditing, and performance analysis workflows.

The inspection layer is built on Chrome DevTools Protocol (CDP) and exposes both programmatic and visual inspection capabilities through a unified MCP (Model Context Protocol) interface. All tools operate on the currently selected page context, enabling sequential inspection workflows.

## Architecture

```mermaid
graph TD
    subgraph "Inspection Layer"
        SNAP[Snapshot Tools]
        SCR[Screen Tools]
        NET[Network Tools]
        CON[Console Tools]
        MEM[Memory Tools]
    end
    
    subgraph "Formatting Layer"
        SF[SnapshotFormatter]
        NF[NetworkFormatter]
        CF[ConsoleFormatter]
    end
    
    subgraph "CDP Integration"
        CDP[Chrome DevTools Protocol]
        PUP[CDP Puppeteer Bridge]
    end
    
    SNAP --> SF
    SCR --> CDP
    NET --> NF
    CON --> CF
    MEM --> CDP
    
    SF --> PUP
    NF --> PUP
    CF --> PUP
    PUP --> CDP
    
    style SNAP fill:#e1f5fe
    style SCR fill:#e1f5fe
    style NET fill:#e1f5fe
    style CON fill:#e1f5fe
    style MEM fill:#e1f5fe
```

## Page Snapshot Tools

### take_snapshot

The primary inspection tool that captures the accessibility tree of the currently selected page. The snapshot provides a text-based representation of page structure with unique element identifiers (UIDs) used for subsequent interaction.

**Parameters:**

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `verbose` | boolean | No | Include all available information from the full a11y tree. Default: `false` |
| `filePath` | string | No | Absolute or relative path to save snapshot output instead of attaching to response |

**Key Features:**

- Returns element hierarchy with unique `uid` identifiers
- Indicates which element is selected in DevTools Elements panel
- Supports output to file for large snapshots
- Based on accessibility tree, not raw DOM (reflects what assistive technologies perceive)
- Marked as `blockedByDialog: true` to handle browser dialogs gracefully

**Source:** [src/tools/snapshot.ts:17-43]()

### wait_for

Suspends execution until a specified condition is met on the page, enabling synchronization with dynamic content loading.

**Source:** [src/tools/snapshot.ts:45+]()

## Console Tools

### list_console_messages

Retrieves console output and browser-issued accessibility audits from the current page. This tool captures both developer-initiated logs and automatic Chrome accessibility checks.

**Use Cases:**

- Capturing `console.log`, `console.error`, and other console methods
- Detecting browser-issued accessibility issues
- Preserving messages from page load that occurred before inspection
- Filtering by message types (`log`, `warn`, `error`, `info`, `debug`, `issue`)

**Source:** [src/tools/console.ts]()

### Console Output Types

| Type | Description | Typical Use |
|------|-------------|-------------|
| `log` | General information | Debug output |
| `warn` | Warning messages | Non-critical issues |
| `error` | Error messages | Failures and exceptions |
| `info` | Informational messages | Status updates |
| `debug` | Debug-level details | Verbose debugging |
| `issue` | Browser a11y audits | Accessibility violations |

The console formatter (`ConsoleFormatter.ts`) processes raw CDP messages into structured, human-readable output with proper formatting of objects and arrays.

**Source:** [src/formatters/ConsoleFormatter.ts]()

## Network Inspection Tools

### Network Monitoring

The network inspection subsystem captures HTTP traffic, WebSocket communications, and resource loading timing. Network tools are essential for debugging API calls, identifying slow resources, and analyzing request/response patterns.

**Source:** [src/tools/network.ts]()

**Network Formatter:** [src/formatters/NetworkFormatter.ts]()

### Network Parameters

| Parameter | Type | Description |
|-----------|------|-------------|
| `pageIdx` | number | Page index for pagination |
| `pageSize` | number | Number of items per page |
| `types` | string[] | Filter by resource types (document, stylesheet, image, script, xhr, etc.) |
| `includePreservedMessages` | boolean | Include messages from before tool invocation |

## Memory Inspection Tools

### take_memory_snapshot

Captures V8 heap memory snapshots for debugging memory leaks and analyzing memory consumption patterns. Heap snapshots are saved in Chrome's standard `.heapsnapshot` format.

**Parameters:**

| Parameter | Type | Required | Description |
|-----------|------|----------|-------------|
| `filePath` | string | Yes | Target path for the snapshot file |

**Use Cases:**

- Identifying memory leaks
- Analyzing object retention paths
- Comparing heap states before/after operations
- Finding detached DOM trees

**Source:** [src/tools/memory.ts]()

## Screenshot Tools

### take_screenshot

Captures visual representation of the current page state. Unlike snapshots, screenshots provide pixel-level fidelity for visual inspection when accessibility tree information is insufficient.

**Use Cases:**

- Visual debugging when structure is unclear
- Capturing rendered UI state
- Documenting bug reproductions
- Inspecting CSS-dependent layouts

**Source:** [src/tools/screenshot.ts]()

## Snapshot Formatting

The SnapshotFormatter (`SnapshotFormatter.ts`) transforms raw accessibility tree data into human-readable hierarchical text format.

**Output Structure:**

```
uid=1_0 RootWebArea "Example Domain" url="https://example.com/"
  uid=1_1 heading "Example Domain" level="1"
  uid=1_2 paragraph "Some content text"
```

**Key Formatting Features:**

- Hierarchical indentation reflecting DOM tree structure
- UID assignment following CDP node IDs
- Role-based element classification (heading, paragraph, button, etc.)
- Attribute inclusion for semantic details
- ARIA property preservation

**Source:** [src/formatters/SnapshotFormatter.ts]()

## Workflow Patterns

### Standard Inspection Workflow

```mermaid
graph LR
    A[Navigate to Page] --> B[wait_for Condition]
    B --> C[take_snapshot]
    C --> D{Issue Found?}
    D -->|Yes| E[Take Screenshot]
    E --> F[Check Console Logs]
    F --> G[Document Findings]
    D -->|No| H[Continue Testing]
    
    style A fill:#c8e6c9
    style C fill:#bbdefb
    style F fill:#fff9c4
```

### Accessibility Audit Workflow

1. **Lighthouse Audit**: Run comprehensive accessibility audit via MCP tools
2. **Console Inspection**: Check for browser-issued `issue` type messages
3. **Snapshot Analysis**: Verify heading hierarchy, ARIA labels, semantic landmarks
4. **Form Input Verification**: Ensure all inputs have associated labels
5. **Focus Navigation**: Test keyboard navigation with `press_key` tool

**Source:** [skills/a11y-debugging/SKILL.md]()

## Tool Categories

All inspection tools are categorized under `ToolCategory.DEBUGGING` for organizational purposes and MCP tool discovery.

**Source:** [src/tools/snapshot.ts:10]()

### Category Matrix

| Tool | Category | Read-Only | Blocked by Dialog |
|------|----------|-----------|-------------------|
| `take_snapshot` | DEBUGGING | false* | true |
| `wait_for` | DEBUGGING | true | true |
| `list_console_messages` | DEBUGGING | true | false |
| `take_memory_snapshot` | DEBUGGING | true | true |
| `take_screenshot` | DEBUGGING | true | true |

*Note: `take_snapshot` is not read-only due to the `filePath` parameter allowing file system writes.

## Integration with Input Automation

Inspection tools work in conjunction with input automation tools to enable test-verify workflows:

```mermaid
graph TD
    INSPECT[Inspection Tools] <-->|UID feedback| INTERACT[Input Automation]
    
    INSPECT --> SNAP[Snapshot with UIDs]
    INTERACT --> CLICK[click uid]
    INTERACT --> FILL[fill uid "text"]
    INTERACT --> HOVER[hover uid]
    
    SNAP --> ELEM[Element UIDs]
    ELEM --> CLICK
    ELEM --> FILL
    ELEM --> HOVER
```

**Source:** [skills/chrome-devtools/SKILL.md]()

## Best Practices

1. **Prefer Snapshots over Screenshots**: Text snapshots are faster, machine-parseable, and more reliable for automation
2. **Use File Output for Large Data**: Specify `filePath` parameter when capturing large snapshots or traces
3. **Wait Before Inspecting**: Always use `wait_for` when content loads dynamically
4. **Check Console First**: Browser-issued issues often reveal accessibility problems without manual investigation
5. **Keep Snapshots Current**: Element UIDs may change after page mutations—take fresh snapshots before interactions

## Output Formats

All inspection tools support multiple output formats via the `--output-format` flag:

| Format | Use Case |
|--------|----------|
| `markdown` (default) | Human-readable output with formatting |
| `json` | Structured data for programmatic processing |

**Source:** [skills/chrome-devtools-cli/SKILL.md]()

## Error Handling

Inspection tools handle common failure scenarios:

- **Dialog Blocking**: Tools with `blockedByDialog: true` will wait if a browser dialog appears
- **Page Context Missing**: Operations fail gracefully if no page is selected
- **Path Validation**: File operations validate paths before writing
- **Timeout Handling**: Configurable timeouts prevent indefinite waits

**Source:** [src/tools/snapshot.ts:28-31]()

---

<a id='performance-tools'></a>

## Performance Analysis Tools

### 相关页面

相关主题：[Debugging and Inspection Tools](#debugging-tools), [Telemetry and Monitoring](#telemetry)

<details>
<summary>Related Source Files</summary>

The following source files were used to generate this documentation:

- [src/tools/lighthouse.ts](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/src/tools/lighthouse.ts)
- [src/tools/performance.ts](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/src/tools/performance.ts)
- [src/HeapSnapshotManager.ts](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/src/HeapSnapshotManager.ts)
- [src/formatters/HeapSnapshotFormatter.ts](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/src/formatters/HeapSnapshotFormatter.ts)
- [src/trace-processing/parse.ts](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/src/trace-processing/parse.ts)
- [skills/debug-optimize-lcp/SKILL.md](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/skills/debug-optimize-lcp/SKILL.md)
- [skills/chrome-devtools-cli/SKILL.md](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/skills/chrome-devtools-cli/SKILL.md)
</details>

# Performance Analysis Tools

The chrome-devtools-mcp repository provides a comprehensive suite of performance analysis tools through the Chrome DevTools Protocol integration. These tools enable automated performance auditing, runtime tracing, memory profiling, and network condition emulation.

## Overview

Performance Analysis Tools in chrome-devtools-mcp encompass four primary domains:

| Domain | Primary Tools | Purpose |
|--------|---------------|---------|
| **Lighthouse Auditing** | `lighthouse_audit` | Accessibility, SEO, best practices scoring |
| **Performance Tracing** | `performance_start_trace`, `performance_stop_trace` | Chrome tracing with DevTools performance data |
| **Memory Profiling** | `take_memory_snapshot`, `HeapSnapshotManager` | JavaScript heap analysis |
| **Trace Processing** | `parse.ts` | Processing and parsing of trace events |

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

## Architecture

The performance analysis system follows a layered architecture:

```mermaid
graph TD
    subgraph "CLI Layer"
        CLI[CLI Commands<br/>chrome-devtools CLI]
    end
    
    subgraph "Tool Layer"
        LH[Lighthouse Audit Tool]
        PT[Performance Trace Tools]
        MS[Memory Snapshot Tools]
    end
    
    subgraph "Protocol Layer"
        CDP[Chrome DevTools Protocol]
    end
    
    subgraph "Processing Layer"
        HSP[Heap Snapshot Parser]
        TRP[Trace Event Parser]
        FMT[Result Formatters]
    end
    
    subgraph "Output Layer"
        JSON[JSON Reports]
        HTML[HTML Reports]
        SNAP[Heap Snapshots]
    end
    
    CLI --> LH
    CLI --> PT
    CLI --> MS
    
    LH --> CDP
    PT --> CDP
    MS --> CDP
    
    MS --> HSP
    PT --> TRP
    
    HSP --> FMT
    TRP --> FMT
    
    FMT --> JSON
    FMT --> HTML
    HSP --> SNAP
```

## Lighthouse Audit Tool

The `lighthouse_audit` tool provides automated accessibility, SEO, and best practices auditing.

### Tool Definition

```typescript
export const lighthouseAudit = definePageTool({
  name: 'lighthouse_audit',
  description: `Get Lighthouse score and reports for accessibility, SEO, best practices, and agentic browsing. This excludes performance.`,
  schema: {
    mode: zod.enum(['navigation', 'snapshot']).default('navigation'),
    device: zod.enum(['desktop', 'mobile']).default('desktop'),
    outputDirPath: zod.string().optional(),
  },
});
```

资料来源：[src/tools/lighthouse.ts:19-40]()

### Audit Categories

| Category | Description | Default Enabled |
|----------|-------------|-----------------|
| `accessibility` | WCAG compliance, ARIA labels, color contrast | Yes |
| `seo` | Meta tags, crawlability, mobile friendliness | Yes |
| `best-practices` | HTTPS usage, no deprecated APIs | Yes |
| `agentic-browsing` | AI agent compatibility checks | Yes |

### Parameters

| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| `mode` | `navigation` \| `snapshot` | No | `navigation` | `navigation` reloads & audits; `snapshot` analyzes current state |
| `device` | `desktop` \| `mobile` | No | `desktop` | Device emulation type |
| `outputDirPath` | string | No | temp file | Directory for JSON reports |

### Usage Workflow

```mermaid
graph LR
    A[Start Audit] --> B{Mode?}
    B -->|navigation| C[Reload Page]
    B -->|snapshot| D[Analyze Current State]
    C --> E[Run Lighthouse]
    D --> E
    E --> F[Generate JSON Report]
    F --> G[Parse Results]
    G --> H[Return Scores & Failed Audits]
```

资料来源：[src/tools/lighthouse.ts:40-60]()

## Performance Tracing

The performance tracing system captures Chrome DevTools performance data for deep analysis.

### Available Tools

| Tool | Purpose |
|------|---------|
| `performance_start_trace` | Begin recording performance trace |
| `performance_stop_trace` | Stop recording and return trace data |
| `performance_analyze_insight` | Get details on specific Performance Insights |

### Trace Configuration

| Parameter | Type | Description |
|-----------|------|-------------|
| `filePath` | string | Optional path to save trace file (`.gz` format) |
| `reload` | boolean | Whether to reload the page before tracing |

### LCP Analysis

The trace system integrates with LCP (Largest Contentful Paint) debugging:

```javascript
async () => {
  return await new Promise(resolve => {
    new PerformanceObserver(list => {
      const entries = list.getEntries();
      const last = entries[entries.length - 1];
      resolve({
        element: last.element?.tagName,
        id: last.element?.id,
        className: last.element?.className,
        url: last.url,
        startTime: last.startTime,
        renderTime: last.renderTime,
        loadTime: last.loadTime,
        size: last.size,
      });
    }).observe({type: 'largest-contentful-paint', buffered: true});
  });
};
```

资料来源：[skills/debug-optimize-lcp/references/lcp-snippets.md:1-30]()

### LCP Subpart Breakdown

LCP is measured across four subparts that sum to 100%:

| Subpart | Target | Root Cause | Fixes |
|---------|--------|------------|-------|
| TTFB | ~40% | Slow server response | Minimize redirects, CDN caching, bfcache eligibility |
| Resource Load Delay | ~10% | Late discovery | Remove lazy-loading, add preload/fetchpriority |
| Resource Load Duration | ~40% | Large/slow resource | WebP/AVIF formats, CDN, compression |
| Element Render Delay | <10% | Render blocking | Inline critical CSS, defer JS, break long tasks |

资料来源：[skills/debug-optimize-lcp/SKILL.md:1-50]()

## Memory Profiling

The memory profiling system captures and analyzes JavaScript heap snapshots.

### Heap Snapshot Manager

The `HeapSnapshotManager` class handles snapshot lifecycle:

```typescript
export class PageCollector<T> {
  #browser: Browser;
  protected storage = new WeakMap<Page, Array<Array<WithSymbolId<T>>>>();
  protected maxNavigationSaved = 3;
  
  async init(pages: Page[]) {
    for (const page of pages) {
      this.addPage(page);
    }
  }
}
```

资料来源：[src/PageCollector.ts:1-50]()

### Snapshot Operations

| Operation | CLI Command | Description |
|-----------|-------------|-------------|
| Capture | `take_memory_snapshot "./path.snap"` | Capture heap snapshot to file |
| Format | `HeapSnapshotFormatter` | Parse and format snapshot data |
| Analyze | Manual inspection | View node counts, shallow sizes, retainer paths |

### Heap Snapshot Data Structure

The system processes snapshots with the following structure:

| Field | Type | Description |
|-------|------|-------------|
| nodes | Node[] | Array of heap nodes |
| edges | Edge[] | References between nodes |
| strings | string[] | String table for node names |
| trace_tree | TraceNode | Sampling profile data |

资料来源：[src/formatters/HeapSnapshotFormatter.ts:1-30]()

## Trace Processing

The trace processing module parses Chrome DevTools trace events.

### Parser Functions

```typescript
interface ParsedTraceEvent {
  name: string;
  cat: string;
  ph: string;
  ts: number;
  dur?: number;
  args?: Record<string, unknown>;
}
```

资料来源：[src/trace-processing/parse.ts:1-20]()

### Supported Event Types

| Event Type | Phase Code | Description |
|------------|------------|-------------|
| Duration | B/E | Begin/End of an operation |
| Complete | X | Operation with known duration |
| Instant | i | Point-in-time event |
| Counter | C | Numeric value at a point |
| Async | b/n/t | Asynchronous operations |
| Sample | P | CPU sampling profile |

### Trace File Format

Trace files can be saved in two formats:

| Format | Extension | Compression |
|--------|-----------|-------------|
| JSON | `.json` | None |
| Perfetto | `.gz` | gzip |

## CLI Commands

The performance tools are accessible via the `chrome-devtools` CLI:

### Performance Commands

```bash
# Start tracing with optional reload
chrome-devtools performance_start_trace true false

# Start trace and save to file
chrome-devtools performance_start_trace true true --filePath trace.gz

# Stop trace and optionally save
chrome-devtools performance_stop_trace
chrome-devtools performance_stop_trace --filePath "t.json"

# Analyze Performance Insights
chrome-devtools performance_analyze_insight "1" "LCPBreakdown"
```

资料来源：[skills/chrome-devtools-cli/SKILL.md:1-100]()

### Memory Commands

```bash
# Capture heap snapshot
chrome-devtools take_memory_snapshot "./snap.heapsnapshot"
```

### Emulation Commands

For realistic performance testing under constrained conditions:

```bash
# Network throttling
chrome-devtools emulate --networkConditions "Fast 3G"

# CPU throttling
chrome-devtools emulate --cpuThrottlingRate 4

# Combined emulation
chrome-devtools emulate --networkConditions "Slow 3G" --cpuThrottlingRate 4
```

资料来源：[skills/chrome-devtools-cli/SKILL.md:80-120]()

## Common Performance Issues

### LCP Issues Checklist

| Issue | Detection | Fix |
|-------|-----------|-----|
| Lazy-loaded LCP image | `loading="lazy"` on viewport images | Remove lazy-loading |
| Missing fetchpriority | `<img>` without `fetchpriority` | Add `fetchpriority="high"` |
| Missing preload | LCP image not in HTML | Add `<link rel="preload">` |
| Render-blocking CSS | Stylesheets in `<head>` | Inline critical CSS |
| Large LCP resource | Slow load duration | Compress, use WebP/AVIF |

资料来源：[skills/debug-optimize-lcp/references/optimization-strategies.md:1-50]()

### JavaScript Snippet for Issue Detection

```javascript
() => {
  const issues = [];

  // Check for lazy-loaded images in viewport
  document.querySelectorAll('img[loading="lazy"]').forEach(img => {
    const rect = img.getBoundingClientRect();
    if (rect.top < window.innerHeight) {
      issues.push({
        issue: 'lazy-loaded image in viewport',
        element: img.outerHTML.substring(0, 200),
        fix: 'Remove loading="lazy" from this image'
      });
    }
  });

  return issues;
};
```

资料来源：[skills/debug-optimize-lcp/references/lcp-snippets.md:35-55]()

## Test Scenarios

The repository includes test scenarios for performance tools:

```typescript
export const scenario: TestScenario = {
  prompt: 'Check the performance of https://developers.chrome.com',
  maxTurns: 2,
  expectations: calls => {
    assert.strictEqual(calls.length, 2);
    assert.ok(
      calls[0].name === 'navigate_page' || calls[0].name === 'new_page',
    );
    assert.ok(calls[1].name === 'performance_start_trace');
  },
};
```

资料来源：[scripts/eval_scenarios/performance_test.ts:1-25]()

## Related Documentation

- [Lighthouse Documentation](https://developer.chrome.com/docs/lighthouse)
- [Chrome DevTools Performance Panel](https://developer.chrome.com/docs/devtools/performance)
- [Memory Profiling](https://developer.chrome.com/docs/devtools/memory-problems)
- [LCP Web.dev Guide](https://web.dev/articles/lcp)

---

<a id='cli-reference'></a>

## CLI Reference

### 相关页面

相关主题：[Configuration Reference](#configuration), [Installation and Setup](#installation), [System Architecture](#system-architecture)

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

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

- [src/bin/chrome-devtools.ts](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/src/bin/chrome-devtools.ts)
- [src/bin/chrome-devtools-cli-options.ts](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/src/bin/chrome-devtools-cli-options.ts)
- [src/tools/slim/tools.ts](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/src/tools/slim/tools.ts)
- [docs/cli.md](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/docs/cli.md)
- [docs/slim-tool-reference.md](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/docs/slim-tool-reference.md)
</details>

# CLI Reference

The `chrome-devtools-mcp` CLI provides a command-line interface for interacting with Chrome DevTools, enabling browser automation, page manipulation, performance analysis, and network inspection directly from the terminal.

## Overview

The CLI is built on top of the Model Context Protocol (MCP) and serves as the primary interface for users who prefer terminal-based workflows over programmatic SDK integration. It wraps the MCP server functionality into a user-friendly command structure.

```mermaid
graph TD
    A[User Terminal] -->|chrome-devtools command| B[CLI Entry Point]
    B --> C[chrome-devtools-cli-options.ts]
    C --> D[Argument Parsing]
    D --> E[chrome-devtools-mcp Server]
    E --> F[Chrome Browser Instance]
    F --> G[Page Context]
    G --> H[Tool Execution]
    H --> I[Response Output]
```

资料来源：[skills/chrome-devtools-cli/SKILL.md]()

## Command Structure

The general command syntax follows:

```bash
chrome-devtools <tool> [arguments] [flags]
```

### Global Flags

| Flag | Description |
|------|-------------|
| `--help` | Display help message for any command |
| `--output-format=json` | Return output in JSON format instead of Markdown |
| `--viaCli` | Internal flag for CLI-to-server communication |

资料来源：[skills/chrome-devtools-cli/SKILL.md]()

## Service Management Commands

These commands control the lifecycle of the chrome-devtools-mcp server.

```bash
chrome-devtools start   # Start or restart chrome-devtools-mcp
chrome-devtools status  # Check if chrome-devtools-mcp is running
chrome-devtools stop    # Stop chrome-devtools-mcp if any
```

The background server starts implicitly on first tool call. Users should **not** run `start`/`status`/`stop` before each use.

资料来源：[skills/chrome-devtools-cli/SKILL.md]()

## Navigation Commands

### Page Navigation

| Command | Description |
|---------|-------------|
| `navigate_page --url "https://example.com"` | Navigate the currently selected page to a URL |
| `navigate_page --type "reload" --ignoreCache true` | Reload page ignoring cache |
| `navigate_page --url "https://example.com" --timeout 5000` | Navigate with a timeout |
| `navigate_page --handleBeforeUnload "accept"` | Handle before unload dialog |
| `navigate_page --type "back" --initScript "foo()"` | Navigate back and run an init script |

### Page Management

| Command | Description |
|---------|-------------|
| `new_page "https://example.com"` | Create a new page |
| `new_page "https://example.com" --background true --timeout 5000` | Create new page in background |
| `new_page "https://example.com" --isolatedContext "ctx"` | Create page with isolated context |
| `select_page 1` | Select a page as context for future tool calls |
| `select_page 1 --bringToFront true` | Select page and bring it to front |
| `close_page 1` | Close a page by its index |
| `list_pages` | List all pages open in the browser |

资料来源：[skills/chrome-devtools-cli/SKILL.md]()

## Input Automation Commands

These commands interact with elements identified by `uid` from snapshot operations.

### Element Interaction

| Command | Description |
|---------|-------------|
| `take_snapshot` | Take a text snapshot of the page to get UIDs |
| `click "id"` | Click on the provided element |
| `click "id" --dblClick true --includeSnapshot true` | Double click and return snapshot |
| `hover "id"` | Hover over the provided element |
| `hover "id" --includeSnapshot true` | Hover and return snapshot |
| `drag "src" "dst"` | Drag an element onto another element |
| `fill "id" "text"` | Type text into an input or select an option |

### Keyboard and Text Input

| Command | Description |
|---------|-------------|
| `press_key "Enter"` | Press a key or key combination |
| `press_key "Control+A" --includeSnapshot true` | Press a key and return snapshot |
| `type_text "hello"` | Type text using keyboard into a focused input |
| `type_text "hello" --submitKey "Enter"` | Type text and press a submit key |

### File Upload

| Command | Description |
|---------|-------------|
| `upload_file "id" "file.txt"` | Upload a file through a provided element |
| `upload_file "id" "file.txt" --includeSnapshot true` | Upload and return snapshot |

### Dialog Handling

| Command | Description |
|---------|-------------|
| `handle_dialog accept` | Accept a browser dialog |
| `handle_dialog dismiss --promptText "hi"` | Dismiss a dialog with prompt text |

资料来源：[skills/chrome-devtools-cli/SKILL.md]()

## Emulation Commands

### Network Conditions

```bash
chrome-devtools emulate --networkConditions "Offline"
```

### Performance Emulation

```bash
chrome-devtools emulate --cpuThrottlingRate 4 --geolocation "0x0"
```

### Visual Emulation

```bash
chrome-devtools emulate --colorScheme "dark" --viewport "1920x1080"
chrome-devtools emulate --userAgent "Mozilla/5.0..."
chrome-devtools resize_page 1920 1080
```

资料来源：[skills/chrome-devtools-cli/SKILL.md]()

## Performance Commands

### Tracing

| Command | Description |
|---------|-------------|
| `performance_start_trace true false` | Start performance trace recording |
| `performance_start_trace true true --filePath t.gz` | Start trace and save to compressed file |
| `performance_stop_trace` | Stop the active performance trace |
| `performance_stop_trace --filePath "t.json"` | Stop trace and save to file |

### Analysis

| Command | Description |
|---------|-------------|
| `performance_analyze_insight "1" "LCPBreakdown"` | Get details on a Performance Insight |
| `take_memory_snapshot "./snap.heapsnapshot"` | Capture a memory heapsnapshot |

资料来源：[skills/chrome-devtools-cli/SKILL.md]()

## Extension Management Commands

| Command | Description |
|---------|-------------|
| `list_extensions` | List all installed Chrome extensions |
| `install_extension "/path/to/extension"` | Install a Chrome extension |
| `uninstall_extension "extension_id"` | Uninstall a Chrome extension |
| `reload_extension "extension_id"` | Reload an unpacked Chrome extension |
| `trigger_extension_action "extension_id"` | Trigger the default action of an extension |

资料来源：[skills/chrome-devtools-cli/SKILL.md]()

## Experimental Features

Experimental tools require specific flags during server startup:

```bash
--experimentalVision=true   # Enable coordinate-based clicking
--experimentalScreencast=true # Enable screencast (requires ffmpeg)
--categoryExperimentalWebmcp=true # Enable WebMCP tools
```

### Experimental Commands

| Command | Description | Required Flag |
|---------|-------------|---------------|
| `click_at 100 200` | Click at coordinates | `--experimentalVision=true` |
| `screencast_start` | Start screencast recording | `--experimentalScreencast=true` |
| `screencast_stop` | Stop active screencast | `--experimentalScreencast=true` |
| `list_webmcp_tools` | List all WebMCP tools | `--categoryExperimentalWebmcp=true` |

资料来源：[skills/chrome-devtools-cli/SKILL.md]()

## WebMCP Tools

WebMCP tools are exposed by the page itself and allow pages to define custom tools that the CLI can invoke.

```bash
chrome-devtools list_webmcp_tools    # List all WebMCP tools the page exposes
chrome-devtools execute_webmcp_tool "toolName" --input '{"key": "value"}'
```

资料来源：[src/tools/webmcp.ts]()

## Tool Categories

The CLI tools are organized into categories that can be enabled or disabled:

| Category | Description | Default |
|----------|-------------|---------|
| Navigation | Page navigation and management | On |
| Interaction | Element click, fill, hover, drag | On |
| Input | Keyboard, text input, file upload | On |
| Emulation | Network, device, viewport emulation | On |
| Performance | Tracing, memory, insights | On |
| Extensions | Chrome extension management | Off |
| Experimental | Vision, screencast, WebMCP | Off |
| WebMCP | Page-exposed tools | Off |

Categories can be enabled via CLI flags:

```bash
chrome-devtools --categoryExtensions=true <tool>
```

资料来源：[skills/chrome-devtools/SKILL.md]()

## Snapshot Format

The `take_snapshot` command returns a hierarchical tree structure:

```
uid=1_0 RootWebArea "Example Domain" url="https://example.com/"
  uid=1_1 heading "Example Domain" level="1"
  uid=1_2 link "Learn more" href="https://example.com/about"
```

Each element has a unique `uid` for interaction. The format shows:
- Element type (RootWebArea, heading, link, etc.)
- Text content
- Attributes (level, href, url)
- Unique identifier (uid) for command targeting

资料来源：[skills/chrome-devtools-cli/SKILL.md]()

## Workflow Patterns

```mermaid
graph LR
    A[navigate_page] --> B[wait_for]
    B --> C[take_snapshot]
    C --> D{Get uid}
    D --> E[Interact with element]
    E --> F[click/fill/hover]
    F --> G[includeSnapshot?]
    G -->|Yes| C
    G -->|No| H[Continue]
```

### Before Interacting with a Page

1. **Navigate**: Use `navigate_page` or `new_page`
2. **Wait**: Use `wait_for` to ensure content is loaded
3. **Snapshot**: Use `take_snapshot` to understand page structure
4. **Interact**: Use element `uid`s from snapshot for commands

### Efficient Data Retrieval

- Use `filePath` parameter for large outputs (screenshots, snapshots, traces)
- Use pagination (`pageIdx`, `pageSize`) and filtering (`types`) to minimize data
- Set `includeSnapshot: false` on input actions unless you need updated page state

资料来源：[skills/chrome-devtools/SKILL.md]()

## Slim Mode

The `--slim` mode provides a minimal set of tools focused on core navigation and interaction, without additional features like performance tracing or extensions.

Available slim tools include essential navigation and element interaction commands.

资料来源：[docs/slim-tool-reference.md]()

## CLI Options Configuration

The CLI accepts the following configuration options (from `src/bin/chrome-devtools-cli-options.ts`):

| Option | Type | Description |
|--------|------|-------------|
| `--slim` | boolean | Enable slim mode with reduced toolset |
| `--chromePath` | string | Path to Chrome executable |
| `--userDataDir` | string | Chrome profile directory |
| `--port` | number | Server port |
| `--host` | string | Server host |
| `--experimentalVision` | boolean | Enable vision-based tools |
| `--experimentalScreencast` | boolean | Enable screencast |
| `--categoryExtensions` | boolean | Enable extension tools |
| `--categoryExperimentalWebmcp` | boolean | Enable WebMCP tools |

资料来源：[src/bin/chrome-devtools-cli-options.ts]()

## MCP Server Integration

```mermaid
sequenceDiagram
    participant User
    participant CLI
    participant MCPServer
    participant Chrome
    
    User->>CLI: chrome-devtools navigate_page
    CLI->>MCPServer: Tool Request
    MCPServer->>Chrome: CDP Command
    Chrome-->>MCPServer: CDP Response
    MCPServer-->>CLI: Tool Response
    CLI-->>User: Formatted Output
```

The CLI communicates with the MCP server using the Model Context Protocol over stdio transport. The server spawns Chrome as a child process and manages CDP (Chrome DevTools Protocol) connections.

资料来源：[scripts/generate-cli.ts]()

## Installation

```bash
npm i chrome-devtools-mcp@latest -g
chrome-devtools status  # Verify installation
```

### Troubleshooting

| Issue | Solution |
|-------|----------|
| Command not found | Ensure global npm `bin` directory is in PATH |
| Permission errors | Use node version manager (nvm) instead of sudo |
| Old version running | Run `chrome-devtools stop && npm uninstall -g chrome-devtools-mcp` |

资料来源：[skills/chrome-devtools-cli/references/installation.md]()

## Development Scripts

From `package.json`:

| Script | Command | Purpose |
|--------|---------|---------|
| `build` | `tsc && test build` | Compile TypeScript and verify build |
| `test` | `build && run all tests` | Run complete test suite |
| `test <path>` | `build && run single test` | Run specific test file |
| `format` | `fix formatting` | Apply formatting and show linting errors |
| `gen` | `generate documentation` | Regenerate tool reference docs |

资料来源：[AGENTS.md]()

## TypeScript Rules

The codebase follows strict TypeScript guidelines:

- No `any` type
- No `as` keyword for type casting
- No `!` operator for type assertion
- No `// @ts-ignore` comments
- Prefer `for..of` over `forEach`

资料来源：[AGENTS.md]()

---

<a id='telemetry'></a>

## Telemetry and Monitoring

### 相关页面

相关主题：[System Architecture](#system-architecture), [Configuration Reference](#configuration)

# Telemetry and Monitoring

## Overview

The chrome-devtools-mcp project implements a telemetry and monitoring system located in the `src/telemetry/` directory. This system is responsible for collecting, logging, and persisting usage metrics and error data from the MCP server operations.

## System Architecture

The telemetry system comprises several interconnected components that work together to capture and report server behavior:

```mermaid
graph TD
    A[Tool Execution] --> B[Metrics Registry]
    A --> C[Clearcut Logger]
    B --> D[Persistence Layer]
    C --> D
    D --> E[Metrics Export]
    F[Watchdog Client] --> C
    G[Errors Module] --> C
```

## Core Components

### 1. Metrics Registry (`metricsRegistry.ts`)

The metrics registry tracks tool call statistics and flag usage across the MCP server. It maintains counters and aggregations for:

- Tool invocation counts
- Flag usage patterns
- Performance-related metrics

The registry is populated by data defined in `tool_call_metrics.json` and `flag_usage_metrics.json`, which define the specific metrics to be tracked.

**资料来源:** [src/telemetry/metricsRegistry.ts](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/src/telemetry/metricsRegistry.ts)

### 2. Clearcut Logger (`ClearcutLogger.ts`)

ClearcutLogger is the primary logging mechanism for telemetry data. It handles:

- Structured logging of events
- Connection to telemetry backends
- Batch processing of log entries

**资料来源:** [src/telemetry/ClearcutLogger.ts](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/src/telemetry/ClearcutLogger.ts)

### 3. Watchdog Client (`WatchdogClient.ts`)

The WatchdogClient provides health monitoring functionality for the MCP server. It:

- Monitors server responsiveness
- Tracks resource utilization
- Reports health status to external monitoring systems

**资料来源:** [src/telemetry/WatchdogClient.ts](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/src/telemetry/WatchdogClient.ts)

### 4. Errors Module (`errors.ts`)

The errors module handles error telemetry and reporting:

- Captures error conditions during tool execution
- Categorizes errors by type and severity
- Provides structured error data for logging

**资料来源:** [src/telemetry/errors.ts](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/src/telemetry/errors.ts)

### 5. Persistence Layer (`persistence.ts`)

The persistence module manages storage of telemetry data:

- Buffers metrics before transmission
- Handles local caching of data
- Manages data retention policies

**资料来源:** [src/telemetry/persistence.ts](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/src/telemetry/persistence.ts)

### 6. Types (`types.ts`)

Central type definitions for all telemetry components including:

- Metric data structures
- Log entry formats
- Configuration interfaces

**资料来源:** [src/telemetry/types.ts](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/src/telemetry/types.ts)

## Metrics Configuration

### Tool Call Metrics (`tool_call_metrics.json`)

This JSON file defines which tools should have their invocations tracked. The format includes tool names and associated metadata for metrics collection.

**资料来源:** [src/telemetry/tool_call_metrics.json](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/src/telemetry/tool_call_metrics.json)

### Flag Usage Metrics (`flag_usage_metrics.json`)

This configuration file tracks usage patterns of command-line flags and configuration options passed to the MCP server.

**资料来源:** [src/telemetry/flag_usage_metrics.json](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/src/telemetry/flag_usage_metrics.json)

## Data Flow

```mermaid
sequenceDiagram
    participant User as User/Tool
    participant Registry as Metrics Registry
    participant Logger as Clearcut Logger
    participant Persistence as Persistence Layer
    participant Backend as Telemetry Backend

    User->>Registry: Record metric
    Registry->>Persistence: Buffer data
    User->>Logger: Log event
    Logger->>Persistence: Batch events
    Persistence->>Backend: Flush data
    Backend-->>Persistence: Acknowledge
```

## Integration with Tool System

The telemetry system integrates with the tool definition infrastructure defined in `ToolDefinition.ts`. Tool execution flows through the telemetry system enabling automatic metrics collection.

**资料来源:** [src/tools/ToolDefinition.ts:1-75](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/src/tools/ToolDefinition.ts)

## WaitForHelper Integration

The `WaitForHelper` class handles navigation and event timing which feeds into performance telemetry. It tracks navigation events and DOM stability which are essential for understanding tool execution performance.

**资料来源:** [src/WaitForHelper.ts:1-60](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/src/WaitForHelper.ts)

## PageCollector Event Monitoring

The `PageCollector` class monitors page lifecycle events that contribute to telemetry data:

- Target creation/destruction events
- Navigation events
- Resource loading patterns

**资料来源:** [src/PageCollector.ts:1-60](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/src/PageCollector.ts)

## Debug Logging

For troubleshooting telemetry issues, the project supports debug logging via the `DEBUG` environment variable. To write debug logs to a file:

```sh
npx @modelcontextprotocol/inspector node /build/src/bin/chrome-devtools-mcp.js --log-file=/your/desired/path/log.txt
```

**资料来源:** [CONTRIBUTING.md](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/CONTRIBUTING.md)

## Configuration Options

| Option | Description | Default |
|--------|-------------|---------|
| `DEBUG` | Enable debug categories | undefined |
| `--log-file` | Output debug logs to file | stdout |
| Telemetry flags | Per-metric enable/disable | Enabled |

## Best Practices

1. **Review metrics before adding new ones** - Ensure the metric provides meaningful insight
2. **Use structured logging** - Prefer the ClearcutLogger for consistency
3. **Handle telemetry failures gracefully** - Telemetry should not block tool execution
4. **Test metrics collection** - Verify metrics are recorded correctly in test scenarios

**资料来源:** [CONTRIBUTING.md](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/CONTRIBUTING.md)

## Related Documentation

- [AGENTS.md](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/AGENTS.md) - General project instructions
- [CONTRIBUTING.md](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/CONTRIBUTING.md) - Debugging and development guide
- [skills/chrome-devtools/SKILL.md](https://github.com/ChromeDevTools/chrome-devtools-mcp/blob/main/skills/chrome-devtools/SKILL.md) - Tool usage patterns

---

---

## Doramagic 踩坑日志

项目：ChromeDevTools/chrome-devtools-mcp

摘要：发现 18 个潜在踩坑项，其中 1 个为 high/blocking；最高优先级：配置坑 - 来源证据：performance_start_trace records 'CPU throttling: none / Network throttling: none' despite emulate setting throttling —…。

## 1. 配置坑 · 来源证据：performance_start_trace records 'CPU throttling: none / Network throttling: none' despite emulate setting throttling —…

- 严重度：high
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个配置相关的待验证问题：performance_start_trace records 'CPU throttling: none / Network throttling: none' despite emulate setting throttling — measurements come back partially or full…
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_644cef1d4144424abe63f24528f5d082 | https://github.com/ChromeDevTools/chrome-devtools-mcp/issues/1955 | 来源讨论提到 macos 相关条件，需在安装/试用前复核。

## 2. 安装坑 · 来源证据：Auto-connect doesn't work on WSL with mirrored networking (Chrome on Windows host)

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Auto-connect doesn't work on WSL with mirrored networking (Chrome on Windows host)
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_3275fc356e284918a94cf8c2c037caee | https://github.com/ChromeDevTools/chrome-devtools-mcp/issues/2004 | 来源讨论提到 windows 相关条件，需在安装/试用前复核。

## 3. 安装坑 · 来源证据：Update check hardcodes registry.npmjs.org, ignoring user's npm registry configuration

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：Update check hardcodes registry.npmjs.org, ignoring user's npm registry configuration
- 对用户的影响：可能阻塞安装或首次运行。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_1946d257bfb04c23a67250da4d584631 | https://github.com/ChromeDevTools/chrome-devtools-mcp/issues/1943 | 来源讨论提到 node 相关条件，需在安装/试用前复核。

## 4. 安装坑 · 来源证据：chrome-devtools-mcp: v0.20.1

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

## 5. 安装坑 · 来源证据：chrome-devtools-mcp: v0.22.0

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

## 6. 配置坑 · 来源证据：chrome-devtools-mcp: v0.21.0

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

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

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

## 8. 运行坑 · 来源证据：chrome-devtools-mcp: v0.20.0

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

## 9. 运行坑 · 来源证据：chrome-devtools-mcp: v0.24.0

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

## 10. 运行坑 · 来源证据：chrome-devtools-mcp: v0.26.0

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

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

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

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

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

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

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

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

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

## 15. 安全/权限坑 · 来源证据：Close empty-object tool schemas for stricter MCP client validation

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安全/权限相关的待验证问题：Close empty-object tool schemas for stricter MCP client validation
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_2af67f120a9d4486998a92da71a92cb9 | https://github.com/ChromeDevTools/chrome-devtools-mcp/issues/2049 | 来源类型 github_issue 暴露的待验证使用条件。

## 16. 安全/权限坑 · 来源证据：chrome-devtools-mcp: v0.25.0

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

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

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

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

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

<!-- canonical_name: ChromeDevTools/chrome-devtools-mcp; human_manual_source: deepwiki_human_wiki -->
