CLAUDE.md•6.95 kB
# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## Project Overview
chrome-devtools-mcp is an MCP (Model Context Protocol) server that enables AI coding agents to control and inspect a live Chrome browser. It acts as a bridge between MCP clients (like Claude, Cursor, Copilot) and Chrome DevTools, exposing 27 tools across categories: input automation, navigation, emulation, performance, network, and debugging.
## Build & Development Commands
```bash
# Install dependencies
npm ci
# Build (clean, compile TypeScript, post-build processing, rollup)
npm run build
# Type checking without emitting files
npm run typecheck
# Format code (ESLint + Prettier)
npm run format
# Check formatting without fixing
npm run check-format
# Start the MCP server
npm run start
# Start with debug logging
npm run start-debug
# Run all tests
npm test
# Run only tests marked with test.only
npm run test:only
# Run only tests without rebuilding first
npm run test:only:no-build
# Update test snapshots
npm run test:update-snapshots
# Generate tool reference documentation
npm run docs:generate
# Full docs generation (build + generate + format)
npm run docs
```
## Testing
The project uses Node.js built-in test runner. Test files are in `tests/` directory mirroring the `src/` structure.
**Run a single test file:**
```bash
npm run build && node --require ./build/tests/setup.js --no-warnings=ExperimentalWarning --test-reporter spec --test-force-exit --test build/tests/path/to/file.test.js
```
**Run specific test with test.only:**
```bash
npm run test:only
```
## Architecture
### Entry Point Flow
1. `src/index.ts` - Node version validation, imports main
2. `src/main.ts` - Server setup, tool registration, stdio transport
3. `src/cli.ts` - CLI argument parsing (yargs)
4. `src/browser.ts` - Browser launch/connection via Puppeteer
### Core Components
**McpContext** (`src/McpContext.ts`)
- Central state management for browser sessions
- Manages pages, snapshots, network/console collectors
- Handles emulation states (CPU throttling, network conditions)
- Provides methods for page selection, element lookup by UID, dialog handling
- Implements timeout adjustments based on throttling multipliers
**McpResponse** (`src/McpResponse.ts`)
- Response builder for MCP tool handlers
- Aggregates content (text, images, network requests, console messages)
- Handles pagination and filtering
- Converts internal data structures to MCP-compatible JSON
**Tool Definition Pattern** (`src/tools/ToolDefinition.ts`)
- All tools use `defineTool()` helper
- Each tool exports a ToolDefinition object with:
- `name`: snake_case tool name
- `description`: Tool purpose
- `annotations`: category, readOnlyHint
- `schema`: Zod schema for parameters
- `handler`: async (request, response, context) => Promise<void>
**Tool Categories** (`src/tools/categories.ts`)
- INPUT_AUTOMATION: click, drag, fill, press_key, hover, etc.
- NAVIGATION: list_pages, new_page, navigate_page, select_page, close_page, wait_for
- EMULATION: emulate_cpu, emulate_network, resize_page
- PERFORMANCE: performance_start_trace, performance_stop_trace, performance_analyze_insight
- NETWORK: list_network_requests, get_network_request
- DEBUGGING: evaluate_script, take_screenshot, take_snapshot, list_console_messages, get_console_message
### Tool Organization
Each category has its own file in `src/tools/`:
- `pages.ts` - Navigation tools
- `input.ts` - Input automation
- `emulation.ts` - Emulation controls
- `performance.ts` - Performance tracing
- `network.ts` - Network inspection
- `console.ts` - Console message access
- `screenshot.ts` - Screenshot capture
- `script.ts` - JavaScript evaluation
- `snapshot.ts` - Accessibility tree snapshots
### Key Utilities
**PageCollector** (`src/PageCollector.ts`)
- Generic collector for page-scoped resources (network requests, console messages)
- Maintains stable IDs for resources across tool calls
- Supports preserved items (pinned for later access)
**WaitForHelper** (`src/WaitForHelper.ts`)
- Waits for page events after actions (network idle, DOM mutations, etc.)
- Adjusts timeouts based on CPU/network throttling
**DevTools Integration** (`src/DevtoolsUtils.ts`, `src/DevToolsConnectionAdapter.ts`)
- Manages connection to Chrome DevTools frontend
- Handles performance trace processing via bundled DevTools code
- Extracts insights from performance recordings
**Trace Processing** (`src/trace-processing/parse.ts`)
- Processes Chrome DevTools Performance traces
- Extracts metrics, insights, and timeline data
- Uses bundled DevTools frontend code for analysis
### Bundling & Third-Party Code
**Rollup Configuration** (`rollup.config.mjs`)
- Bundles Puppeteer and its dependencies
- Creates standalone executable with all deps in `build/node_modules`
- Uses cleanup plugin to remove unnecessary code
**Third-Party Wrapper** (`src/third_party/index.ts`)
- Re-exports Puppeteer, MCP SDK, and other dependencies
- Single import point for external libraries
**DevTools Frontend** (`chrome-devtools-frontend` npm package)
- Bundled Chrome DevTools code for trace processing
- See `src/devtools.d.ts` for type definitions
## Adding a New Tool
1. Choose appropriate file in `src/tools/` based on category
2. Define tool using `defineTool()` helper
3. Export the tool definition
4. Tool automatically registered in `src/main.ts` via Object.values() import
5. Run `npm run docs` to regenerate tool reference documentation
6. Add tests in `tests/tools/`
## Documentation Generation
Tool reference docs are auto-generated from tool definitions:
- `scripts/generate-docs.ts` - Extracts tool metadata and generates markdown
- Updates `docs/tool-reference.md` and README.md tool list
- Run `npm run docs` after tool changes
## Browser Connection Modes
**Launched Mode** (default)
- Server starts Chrome with puppeteer.launch()
- Uses persistent user data dir: `~/.cache/chrome-devtools-mcp/chrome-profile-$CHANNEL`
- Can use `--isolated` flag for temporary profile
**Connected Mode** (`--browserUrl` or `--wsEndpoint`)
- Connects to existing Chrome instance
- Requires Chrome started with `--remote-debugging-port`
- Supports custom WebSocket headers for auth
## Important Notes
- All tool calls are serialized via Mutex to prevent race conditions
- Tools must call `await getContext()` to lazily initialize browser connection
- Response builder methods (`setIncludePages`, `setIncludeNetworkRequests`, etc.) control what data is included in tool responses
- Snapshot UIDs format: `{snapshotId}_{nodeId}` - stale snapshots rejected
- Network requests and console messages have stable IDs for cross-tool reference
- Dialog handling is page-specific via event listeners in McpContext
- Timeouts auto-adjust based on CPU throttling and network emulation
- DevTools windows are hidden from page list unless `--experimentalDevtools` enabled