Skip to content

Chrome DevTools for coding agents

16.7 KB
Raw Blame
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

import {DEFAULT_MAX_NAVIGATION_SAVED} from '../collectors/constants.js';
import type {YargsOptions} from '../third_party/index.js';
import os from 'node:os';
import path from 'node:path';

import {
  getCategoryOptions,
  type CategoryArguments,
  type McpOption,
  type McpOptionsFor,
} from './category-options.js';
import {getBrowserOptions, type BrowserArguments} from './browser-options.js';
import {
  puppeteerOptions,
  type PuppeteerArguments,
} from './puppeteer-options.js';
import {toolOptions, type ToolArguments} from './tool-options.js';

export interface McpArguments
  extends
    CategoryArguments,
    BrowserArguments,
    PuppeteerArguments,
    ToolArguments {
  logFile?: string;
  pageIdRouting: boolean;
  devtoolsComments: boolean;
  experimentalDevtools: boolean;
  experimentalVision: boolean;
  memoryDebugging: boolean;
  experimentalStructuredContent: boolean;
  experimentalToonFormat: boolean;
  experimentalDataFormat?: 'default' | 'toon' | 'gcf';
  experimentalIncludeAllPages: boolean;
  experimentalInteropTools: boolean;
  experimentalScreencast: boolean;
  experimentalFfmpegPath?: string;
  screencastFps?: number;
  performanceCrux: boolean;
  usageStatistics: boolean;
  javascriptEvaluation: boolean;
  fileNavigations: boolean;
  sourceMaps: boolean;
  maxNavigationSaved: number;
  clearcutEndpoint?: string;
  clearcutForceFlushIntervalMs?: number;
  clearcutIncludePidHeader: boolean;
  slim: boolean;
  viaCli: boolean;
  redactNetworkHeaders: boolean;
  allowUnrestrictedPaths: boolean;
  filesystemRoot?: string[];
  config?: string;
  watchConfig: boolean;
}

export type ParsedArguments = {
  [K in keyof McpArguments]: McpArguments[K];
};

export type McpOptions = McpOptionsFor<ParsedArguments, McpOption>;

export const DEFAULT_FILESYSTEM_ROOT: string[] = [os.tmpdir()];
// Each retained navigation can hold up to 1,000 network requests and 10,000
// console messages, so the history is capped to avoid running out of memory.
export const MAX_NAVIGATION_SAVED_LIMIT = 25;

export const mcpOptions: McpOptions = {
  ...getCategoryOptions(),
  ...getBrowserOptions(),
  ...puppeteerOptions,
  ...toolOptions,
  logFile: {
    type: 'string',
    describe:
      'Path to a file to write debug logs to. Set the env variable `NODE_DEBUG` to `*` to enable verbose logs. Useful for submitting bug reports.',
  },
  pageIdRouting: {
    type: 'boolean',
    describe:
      'Require pageId on page-scoped tools and route requests by page ID (useful for concurrent agent sessions). Use --no-page-id-routing to disable.',
    default: true,
    reloadable: true,
  },
  devtoolsComments: {
    type: 'boolean',
    describe:
      'Whether to enable DevTools comments tools. Internal WIP feature.',
    hidden: true,
    default: false,
    reloadable: true,
  },
  experimentalDevtools: {
    type: 'boolean',
    default: false,
    describe:
      'Whether to enable automation over DevTools targets. This exposes the DevTools UI to input tools, including the Console, which can evaluate JavaScript in the inspected page. --no-javascript-evaluation does not restrict this path.',
  },
  experimentalVision: {
    type: 'boolean',
    default: false,
    describe:
      'Whether to enable coordinate-based tools such as click_at(x,y). Usually requires a computer-use model able to produce accurate coordinates by looking at screenshots.',
    reloadable: true,
  },
  memoryDebugging: {
    type: 'boolean',
    default: false,
    describe: 'Whether to enable memory debugging tools.',
    alias: 'experimentalMemory',
    reloadable: true,
  },
  experimentalStructuredContent: {
    type: 'boolean',
    default: false,
    describe: 'Whether to output structured formatted content.',
    reloadable: true,
  },
  experimentalToonFormat: {
    type: 'boolean',
    default: false,
    describe:
      'Deprecated: use --experimentalDataFormat=toon instead. Whether to format structured data using TOON (requires @toon-format/toon).',
    hidden: true,
    reloadable: true,
  },
  experimentalDataFormat: {
    type: 'string',
    defaultDescription: 'default',
    describe:
      'Override format for structured data in text responses. Default uses built-in formatters. "toon" (requires @toon-format/toon) or "gcf" (requires @blackwell-systems/gcf) replace structured content with the specified encoding.',
    choices: ['default', 'toon', 'gcf'],
    hidden: true,
    reloadable: true,
  },
  experimentalIncludeAllPages: {
    type: 'boolean',
    default: false,
    describe:
      'Whether to include all kinds of pages such as webviews or background pages as pages.',
    reloadable: true,
  },
  experimentalInteropTools: {
    type: 'boolean',
    default: false,
    describe: 'Whether to enable interoperability tools',
    hidden: true,
    reloadable: true,
  },
  experimentalScreencast: {
    type: 'boolean',
    default: false,
    describe:
      'Use the legacy ffmpeg-based screencast implementation instead of the built-in Chrome recorder. Install ffmpeg https://www.ffmpeg.org/download.html and ensure it is available in the MCP server PATH. This option is deprecated and will be removed in favour of dependency-free screencast commands that are available by default.',
    reloadable: true,
  },
  experimentalFfmpegPath: {
    type: 'string',
    describe:
      'Path to ffmpeg executable for legacy screencast recording (requires --experimentalScreencast).',
    reloadable: true,
  },
  screencastFps: {
    type: 'number',
    alias: 'experimentalScreencastFps',
    describe:
      'Frames per second to use for screencast recording. Lower values reduce file size and encoding load.',
    reloadable: true,
    coerce: (value: number | undefined): number | undefined => {
      if (value === undefined) {
        return;
      }
      if (!Number.isInteger(value) || value <= 0) {
        throw new Error(
          `Invalid screencastFps ${value}. Expected a positive integer.`,
        );
      }
      return value;
    },
  },
  performanceCrux: {
    type: 'boolean',
    default: true,
    describe:
      'Set to false to disable sending URLs from performance traces to CrUX API to get field performance data.',
    reloadable: true,
  },
  usageStatistics: {
    type: 'boolean',
    default: true,
    describe:
      'Set to false to opt-out of usage statistics collection. Google collects usage data to improve the tool, handled under the Google Privacy Policy (https://policies.google.com/privacy). This is independent from Chrome browser metrics. Disabled if `CHROME_DEVTOOLS_MCP_NO_USAGE_STATISTICS` or `CI` env variables are set.',
  },
  javascriptEvaluation: {
    type: 'boolean',
    default: true,
    describe:
      'Set to false to disable the server entry points for evaluating caller-provided JavaScript: evaluation tools (evaluate_script, set_logpoints, and slim evaluate) are disabled, the initScript parameter in navigate_page is turned off, and navigating to javascript:, data:, or vbscript: URLs is disallowed. This is not a JavaScript sandbox: page scripts and JavaScript triggered through other permitted browser interactions (e.g. clicks or typing) still run. If --experimentalDevtools is also enabled, the DevTools UI, including the Console that evaluates code in the inspected page, can be automated and is not restricted by this option. The client remains responsible for validating tool calls and parameters.',
    reloadable: true,
  },
  fileNavigations: {
    type: 'boolean',
    default: true,
    describe:
      'Set to false to disallow navigating to file: URLs. When disabled, new_page, navigate_page, the slim navigate tool, install_pwa and launch_pwa reject file: URLs, including view-source: URLs that target them. This restricts navigations the server performs. It is not a filesystem sandbox: it does not affect pages the browser already had open when the server connected, and the browser can reach the filesystem by other means. Use OS sandboxing for full filesystem confinement.',
    reloadable: true,
  },
  sourceMaps: {
    type: 'boolean',
    default: true,
    describe:
      'Whether to enable source maps in DevTools. Use --no-source-maps to disable.',
    reloadable: true,
  },
  maxNavigationSaved: {
    type: 'number',
    default: DEFAULT_MAX_NAVIGATION_SAVED,
    describe: `Number of navigations (including the current one) for which network requests and console messages are retained per page. Must be between 1 and ${MAX_NAVIGATION_SAVED_LIMIT}. For earlier navigations, request URLs, status codes, and request and response headers are retained, which is sufficient to trace redirect hops, but response bodies are generally no longer available.`,
    coerce: (value: number | undefined): number | undefined => {
      if (value === undefined) {
        return;
      }
      if (
        !Number.isInteger(value) ||
        value <= 0 ||
        value > MAX_NAVIGATION_SAVED_LIMIT
      ) {
        throw new Error(
          `Invalid maxNavigationSaved ${value}. Expected an integer between 1 and ${MAX_NAVIGATION_SAVED_LIMIT}.`,
        );
      }
      return value;
    },
  },
  clearcutEndpoint: {
    type: 'string',
    hidden: true,
    describe: 'Endpoint for Clearcut telemetry.',
  },
  clearcutForceFlushIntervalMs: {
    type: 'number',
    hidden: true,
    describe: 'Force flush interval in milliseconds (for testing).',
  },
  clearcutIncludePidHeader: {
    type: 'boolean',
    default: false,
    hidden: true,
    describe: 'Include watchdog PID in Clearcut request headers (for testing).',
  },
  slim: {
    type: 'boolean',
    default: false,
    describe:
      'Exposes a "slim" set of 3 tools covering navigation, script execution and screenshots only. Useful for basic browser tasks.',
    reloadable: true,
  },
  viaCli: {
    type: 'boolean',
    default: false,
    describe:
      'Set by Chrome DevTools CLI if the MCP server is started via the CLI client (this arg exists for usage stats)',
    hidden: true,
  },
  redactNetworkHeaders: {
    type: 'boolean',
    describe:
      'If true, redacts some of the network headers considered sensitive before returning to the client.',
    default: false,
    reloadable: true,
  },
  allowUnrestrictedPaths: {
    type: 'boolean',
    default: false,
    deprecated: 'Use --workspace=/ instead.',
    describe:
      'If set, disables the default path restriction that applies when the MCP client does not negotiate ' +
      'the roots capability. By default, tools that read or write local files are restricted to the OS temp directory when ' +
      'no roots are configured. Use this only when connecting a trusted local client that does not implement ' +
      'MCP roots and requires access to paths outside the temp directory.',
    reloadable: true,
  },
  filesystemRoot: {
    type: 'array',
    string: true,
    alias: 'workspace',
    default: DEFAULT_FILESYSTEM_ROOT,
    defaultDescription: 'OS temp directory',
    describe:
      'A directory that filesystem tools are allowed to access. May be specified more than once.',
    reloadable: true,
  },
  config: {
    type: 'string',
    describe: 'Path to JSON configuration file.',
    coerce: (configPath: string | undefined): string | undefined => {
      if (!configPath) {
        return;
      }
      return path.resolve(configPath);
    },
  },
  watchConfig: {
    type: 'boolean',
    default: false,
    describe:
      'Watch the config file for changes and apply them without restarting. Tools (except --categoryExtensions) are enabled, disabled and updated on the fly; options used to launch or connect to the browser still require a restart.',
  },
};

export const mcpOptionsForViaCli: McpOptions = {
  ...mcpOptions,
  headless: {
    ...mcpOptions.headless,
    default: true,
  },
  memoryDebugging: {
    ...mcpOptions.memoryDebugging,
    default: true,
  },
  categoryExtensions: {
    ...mcpOptions.categoryExtensions,
    defaultDescription:
      'true unless autoConnect, browserUrl or wsEndpoint is set',
  },
  experimentalStructuredContent: {
    ...mcpOptions.experimentalStructuredContent,
    default: true,
  },
  isolated: {
    ...mcpOptions.isolated,
    description:
      'If specified, creates a temporary user-data-dir that is automatically cleaned up after the browser is closed. Defaults to true unless userDataDir is provided.',
    defaultDescription:
      'true unless userDataDir, autoConnect, browserUrl or wsEndpoint is set',
  },
};

export function getCliOptions(): Partial<
  Record<keyof McpOptions, YargsOptions>
> {
  const options: Partial<Record<keyof McpOptions, YargsOptions>> =
    withoutDefaults(mcpOptionsForViaCli);

  // Missing CLI serialization.
  delete options.viewport;

  // The CLI is generated for the full mode with pageId routing, not slim mode.
  delete options.slim;
  delete options.pageIdRouting;

  // Change the defaults for the CLI.
  delete options.experimentalStructuredContent;
  delete options.experimentalInteropTools;

  return options;
}

export const CLI_EXAMPLES: Array<[string, string]> = [
  [
    '$0 --browserUrl http://127.0.0.1:9222',
    'Connect to an existing browser instance via HTTP',
  ],
  [
    '$0 --wsEndpoint ws://127.0.0.1:9222/devtools/browser/abc123',
    'Connect to an existing browser instance via WebSocket',
  ],
  [
    `$0 --wsEndpoint ws://127.0.0.1:9222/devtools/browser/abc123 --wsHeaders '{"Authorization":"Bearer token"}'`,
    'Connect via WebSocket with custom headers',
  ],
  ['$0 --channel beta', 'Use Chrome Beta installed on this system'],
  ['$0 --channel canary', 'Use Chrome Canary installed on this system'],
  ['$0 --channel dev', 'Use Chrome Dev installed on this system'],
  ['$0 --channel stable', 'Use stable Chrome installed on this system'],
  ['$0 --logFile /tmp/log.txt', 'Save logs to a file'],
  ['$0 --help', 'Print CLI options'],
  [
    '$0 --viewport 1280x720',
    'Launch Chrome with the initial viewport size of 1280x720px',
  ],
  [
    `$0 --chrome-arg='--no-sandbox' --chrome-arg='--disable-setuid-sandbox'`,
    'Launch Chrome without sandboxes. Use with caution.',
  ],
  [
    `$0 --ignore-default-chrome-arg='--disable-extensions'`,
    'Disable the default arguments provided by Puppeteer. Use with caution.',
  ],
  ['$0 --no-category-emulation', 'Disable tools in the emulation category'],
  ['$0 --no-category-performance', 'Disable tools in the performance category'],
  ['$0 --no-category-network', 'Disable tools in the network category'],
  ['$0 --user-data-dir=/tmp/user-data-dir', 'Use a custom user data directory'],
  [
    '$0 --auto-connect',
    'Connect to a stable Chrome instance (Chrome 144+) running instead of launching a new instance',
  ],
  [
    '$0 --auto-connect --channel=canary',
    'Connect to a canary Chrome instance (Chrome 144+) running instead of launching a new instance',
  ],
  [
    '$0 --no-usage-statistics',
    'Do not send usage statistics https://github.com/ChromeDevTools/chrome-devtools-mcp#usage-statistics.',
  ],
  [
    '$0 --no-performance-crux',
    'Disable CrUX (field data) integration in performance tools.',
  ],
  ['$0 --no-source-maps', 'Disable source maps in DevTools.'],
  [
    '$0 --no-javascript-evaluation',
    'Disable server JavaScript evaluation entry points (evaluation tools, initScript in navigate_page, and navigating to javascript:, data:, or vbscript: URLs). Page scripts still run.',
  ],
  [
    '$0 --slim',
    'Only 3 tools: navigation, JavaScript execution and screenshot',
  ],
];

export const CONFLICTING_ARGS: Array<Array<keyof McpOptions>> = [
  ['channel', 'executablePath', 'browserUrl', 'wsEndpoint'],
  ['userDataDir', 'browserUrl', 'wsEndpoint'],
  ['userDataDir', 'isolated'],
  ['autoConnect', 'isolated'],
  ['autoConnect', 'executablePath'],
  ['blockedUrlPattern', 'allowedUrlPattern'],
  ['allowUnrestrictedPaths', 'filesystemRoot'],
  ['categoryPwa', 'autoConnect'],
  ['categoryPwa', 'browserUrl', 'wsEndpoint'],
];

export const IMPLICATIONS: Array<[keyof McpOptions, keyof McpOptions]> = [
  ['wsHeaders', 'wsEndpoint'],
  ['experimentalFfmpegPath', 'experimentalScreencast'],
];

export function withoutDefaults(
  options: Record<string, YargsOptions>,
): Record<string, YargsOptions> {
  const result: Record<string, YargsOptions> = {};
  for (const [key, option] of Object.entries(options)) {
    const copy: YargsOptions = {...option};
    if (copy.default !== undefined) {
      copy.defaultDescription ??= JSON.stringify(copy.default);
      delete copy.default;
    }
    result[key] = copy;
  }
  return result;
}

export function stripYargsPositionalArgs<T extends {_?: unknown; $0?: unknown}>(
  parsed: T,
): {
  [
    K in keyof T as string extends K ? never : K extends '_' | '$0' ? never : K
  ]: T[K];
} {
  const copy = {...parsed};
  delete copy._;
  delete copy.$0;
  return copy;
}

export function isReloadableOption(name: keyof McpOptions): boolean {
  const option: McpOption = mcpOptions[name];
  return option.reloadable === true;
}