Chrome DevTools for coding agents
feat: discover the config file in predefined locations (#2876)
Nikolay Vitkov02c0112cd57e
diff --git a/docs/configuration.md b/docs/configuration.mdindex 877ce433..05e8596b 100644--- a/docs/configuration.md+++ b/docs/configuration.md@@ -258,6 +258,40 @@ Pass them via the `args` property in the JSON configuration. For example:}```+## Configuration file++Instead of passing flags, you can put the options in a JSON file. Keys use the+camelCase option names:++```json+{+ "headless": true,+ "channel": "canary",+ "memoryDebugging": true,+ "blockedUrlPattern": ["*://*.example.com/*"]+}+```++The server uses the first config file it finds in the following locations,+from highest to lowest priority. Config files are not merged.++1. The path passed via `--config`.+2. `cd4a.config.json` in the current working directory.+3. `cd4a.config.json` in the `$PLUGIN_DATA` directory, when running as an+ [agent plugin](https://agent-plugins.org/specification).+4. The global config file:+ - macOS and Linux: `$XDG_CONFIG_HOME/cd4a/config.json`, falling back to+ `~/.config/cd4a/config.json`.+ - Windows: `%LOCALAPPDATA%/Google/cd4a/config.json`, falling back to+ `~/.config/cd4a/config.json`.++Flags passed on the command line take precedence over the values in the config+file.++Set the `CHROME_DEVTOOLS_MCP_NO_CONFIG_DISCOVERY` env variable to turn off the+search for config files, for example in tests. A config file passed via+`--config` is still used.+## Connecting via WebSocket with custom headersYou can connect directly to a Chrome WebSocket endpoint and include custom headers (e.g., for authentication):diff --git a/scripts/test.js b/scripts/test.jsindex a18d0b4b..b3190162 100644--- a/scripts/test.js+++ b/scripts/test.js@@ -93,6 +93,7 @@ async function runTests(attempt) {CHROME_DEVTOOLS_MCP_NO_USAGE_STATISTICS: true,CHROME_DEVTOOLS_MCP_CRASH_ON_UNCAUGHT: true,CHROME_DEVTOOLS_MCP_NO_UPDATE_CHECKS: true,+ CHROME_DEVTOOLS_MCP_NO_CONFIG_DISCOVERY: true,...(process.env['RUNNER_DEBUG'] === '1'? {NODE_DEBUG: 'puppeteer:*'}: {}),diff --git a/src/bin/chrome-devtools-mcp-main.ts b/src/bin/chrome-devtools-mcp-main.tsindex 4342192b..f91bbf2a 100644--- a/src/bin/chrome-devtools-mcp-main.ts+++ b/src/bin/chrome-devtools-mcp-main.ts@@ -25,7 +25,8 @@ await checkForUpdates('Run `npm install chrome-devtools-mcp@latest` to update.',);-export const args = new ConfigParser(VERSION).parse();+const configParser = new ConfigParser(VERSION);+export const args = configParser.parse();const logFile = args.logFile ? saveLogsToFile(args.logFile) : undefined;diff --git a/src/bin/chrome-devtools.ts b/src/bin/chrome-devtools.tsindex ca302bea..812ba369 100644--- a/src/bin/chrome-devtools.ts+++ b/src/bin/chrome-devtools.ts@@ -33,6 +33,7 @@ import {VERSION} from '../version.js';import {buildCommand} from '../config/cli-commands.js';import {commands} from '../config/cli-options.js';import {mcpOptions, getCliOptions} from '../config/mcp-options.js';+import {ConfigParser} from '../config/ConfigParser.js';await checkForUpdates(@@ -43,6 +44,7 @@ const DEFAULT_CLI_ARGS = ['--viaCli'];async function start(args: string[], sessionId: string, stopExisting = false) {const combinedArgs = [...DEFAULT_CLI_ARGS, ...args];+ // Validates the arguments and the config file before starting the daemon.const parsedArgs = new ConfigParser(VERSION, [process.execPath,process.argv[1],diff --git a/src/config/ConfigLocator.ts b/src/config/ConfigLocator.tsnew file mode 100644index 00000000..e6b8ff5a--- /dev/null+++ b/src/config/ConfigLocator.ts@@ -0,0 +1,82 @@+/**+ * @license+ * Copyright 2026 Google LLC+ * SPDX-License-Identifier: Apache-2.0+ */++import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';++export const CONFIG_FILE_NAME = 'cd4a.config.json';++/**+ * Turns off config file discovery, for example in tests. A config file passed+ * via `--config` is still used.+ */+export const NO_CONFIG_DISCOVERY_ENV =+ 'CHROME_DEVTOOLS_MCP_NO_CONFIG_DISCOVERY';++function isFile(filePath: string): boolean {+ try {+ return fs.statSync(filePath, {throwIfNoEntry: false})?.isFile() ?? false;+ } catch {+ return false;+ }+}++/**+ * Finds the config file in the predefined locations. The first existing file+ * wins, config files are not merged.+ *+ * Locations, from highest to lowest priority:+ * 1. `${CWD}/cd4a.config.json`+ * 2. `${PLUGIN_DATA}/cd4a.config.json`+ * 3. The global config: `$XDG_CONFIG_HOME/cd4a/config.json` on macOS and+ * Linux, `%LOCALAPPDATA%/Google/cd4a/config.json` on Windows, with a+ * fallback to `~/.config/cd4a/config.json`.+ *+ * An explicit `--config` takes precedence over all of them and is handled by+ * the ConfigParser. Discovery is turned off if the+ * `CHROME_DEVTOOLS_MCP_NO_CONFIG_DISCOVERY` env variable is set.+ */+export class ConfigLocator {+ getSearchPaths(cwd = process.cwd(), env = process.env): string[] {+ const searchPaths = [path.join(cwd, CONFIG_FILE_NAME)];+ const pluginData = env['PLUGIN_DATA'];+ if (pluginData) {+ searchPaths.push(path.join(pluginData, CONFIG_FILE_NAME));+ }+ searchPaths.push(this.getGlobalConfigPath(env));+ return searchPaths;+ }++ getGlobalConfigPath(+ env = process.env,+ platform = process.platform,+ homedir = os.homedir(),+ ): string {+ if (platform === 'win32') {+ const localAppData = env['LOCALAPPDATA'];+ if (localAppData) {+ return path.join(localAppData, 'Google', 'cd4a', 'config.json');+ }+ } else {+ // Per the XDG Base Directory spec, relative paths must be ignored.+ const xdgConfigHome = env['XDG_CONFIG_HOME'];+ if (xdgConfigHome && path.isAbsolute(xdgConfigHome)) {+ return path.join(xdgConfigHome, 'cd4a', 'config.json');+ }+ }+ return path.join(homedir, '.config', 'cd4a', 'config.json');+ }++ locate(env = process.env, checkIsFile = isFile): string | undefined {+ if (env[NO_CONFIG_DISCOVERY_ENV]) {+ return undefined;+ }+ return this.getSearchPaths(undefined, env).find(filePath =>+ checkIsFile(filePath),+ );+ }+}diff --git a/src/config/ConfigParser.ts b/src/config/ConfigParser.tsindex 2e25dfa7..0182e49c 100644--- a/src/config/ConfigParser.ts+++ b/src/config/ConfigParser.ts@@ -19,6 +19,7 @@ import {DEFAULT_FILESYSTEM_ROOT,withoutDefaults,} from './mcp-options.js';+import {ConfigLocator} from './ConfigLocator.js';function isPlainObject(value: unknown): value is Record<string, unknown> {return typeof value === 'object' && value !== null && !Array.isArray(value);@@ -38,12 +39,21 @@ function stripYargsPositionalArgs<T extends {_?: unknown; $0?: unknown}>(export type ParsedArguments = InferredOptionTypes<typeof mcpOptions>;export class ConfigParser {+ #configPath?: string;+ public readonly configLocator: ConfigLocator;++ /**+ * @param configLocator Finds the config file when `--config` is not passed.+ * Config file discovery is off without it, for example in tests.+ */constructor(private version: string,private argv = process.argv,private env = process.env,private exitProcess = true,- ) {}+ ) {+ this.configLocator = new ConfigLocator();+ }buildCliParser(options: Record<string, YargsOptions> = mcpOptions) {const yargsInstance = yargs(hideBin(this.argv));@@ -216,15 +226,9 @@ export class ConfigParser {parse(): ParsedArguments {try {const cliArgs = this.parseCliArgs();- const configPath = cliArgs.config;- const configFileArgs =- typeof configPath === 'string' ? this.parseConfigFile(configPath) : {};- // Step 3: merges the explicit inputs. The CLI wins over the config file.- const explicitArgs = {...configFileArgs, ...cliArgs};+ this.#configPath = cliArgs.config ?? this.configLocator?.locate(this.env);this.warnUnknownArgs(cliArgs);- this.validateConflicts(explicitArgs);- this.validateImplications(explicitArgs);- return this.applyDefaults(explicitArgs);+ return this.#resolve(cliArgs);} catch (error) {if (this.exitProcess) {console.error(getErrorMessage(error));@@ -233,4 +237,27 @@ export class ConfigParser {throw error;}}++ /**+ * Re-reads the config file resolved by `parse()` and merges it with the CLI+ * arguments again. Unlike `parse()`, it does not discover a new config file+ * and throws on invalid configuration instead of exiting the process.+ */+ reload(): ParsedArguments {+ return this.#resolve(this.parseCliArgs());+ }++ #resolve(cliArgs: Partial<ParsedArguments>): ParsedArguments {+ const configPath = this.#configPath;+ const configFileArgs = configPath ? this.parseConfigFile(configPath) : {};+ // Step 3: merges the explicit inputs. The CLI wins over the config file.+ const explicitArgs = {+ ...configFileArgs,+ ...cliArgs,+ ...(configPath ? {config: configPath} : {}),+ };+ this.validateConflicts(explicitArgs);+ this.validateImplications(explicitArgs);+ return this.applyDefaults(explicitArgs);+ }}diff --git a/src/daemon/daemon.ts b/src/daemon/daemon.tsindex ff06b211..7557fa6e 100644--- a/src/daemon/daemon.ts+++ b/src/daemon/daemon.ts@@ -16,6 +16,7 @@ import process from 'node:process';import {BrowserManager} from '../BrowserManager.js';import {mcpOptions} from '../config/mcp-options.js';+import {ConfigParser} from '../config/ConfigParser.js';import {McpServer} from '../index.js';import {ClearcutLogger} from '../telemetry/ClearcutLogger.js';@@ -139,7 +140,8 @@ let server: Server | null = null;async function setupMCPServer() {logger?.(`Starting Chrome DevTools MCP Server v${VERSION}`);- const args = new ConfigParser(VERSION).parse();+ const configParser = new ConfigParser(VERSION);+ const args = configParser.parse();const logFile = args.logFile ? saveLogsToFile(args.logFile) : undefined;const browserManager = new BrowserManager(args, {logFile,diff --git a/tests/config/ConfigLocator.test.ts b/tests/config/ConfigLocator.test.tsnew file mode 100644index 00000000..2fa3b90f--- /dev/null+++ b/tests/config/ConfigLocator.test.ts@@ -0,0 +1,156 @@+/**+ * @license+ * Copyright 2026 Google LLC+ * SPDX-License-Identifier: Apache-2.0+ */++import assert from 'node:assert';+import path from 'node:path';+import {describe, it} from 'node:test';++import {ConfigLocator} from '../../src/config/ConfigLocator.js';++const HOME = path.resolve('/home/user');+const CWD = path.resolve('/work/project');+const PLUGIN_DATA = path.resolve('/plugins/data/chrome-devtools');+const XDG_CONFIG_HOME = path.resolve('/xdg/config');++const CWD_CONFIG = path.join(CWD, 'cd4a.config.json');+const PLUGIN_CONFIG = path.join(PLUGIN_DATA, 'cd4a.config.json');+const XDG_CONFIG = path.join(XDG_CONFIG_HOME, 'cd4a', 'config.json');+const HOME_CONFIG = path.join(HOME, '.config', 'cd4a', 'config.json');++class TestConfigLocator extends ConfigLocator {+ #files: Set<string>;+ #env: NodeJS.ProcessEnv;+ #platform: NodeJS.Platform;++ constructor(+ existingFiles: string[],+ env: NodeJS.ProcessEnv = {},+ platform: NodeJS.Platform = 'linux',+ ) {+ super();+ this.#files = new Set(existingFiles);+ this.#env = env;+ this.#platform = platform;+ }++ override getSearchPaths(cwd = CWD, env = this.#env): string[] {+ return super.getSearchPaths(cwd, env);+ }++ override getGlobalConfigPath(+ env = this.#env,+ platform = this.#platform,+ homedir = HOME,+ ): string {+ return super.getGlobalConfigPath(env, platform, homedir);+ }++ override locate(+ env = this.#env,+ checkIsFile = (filePath: string) => this.#files.has(filePath),+ ): string | undefined {+ return super.locate(env, checkIsFile);+ }+}++describe('ConfigLocator', () => {+ describe('getGlobalConfigPath', () => {+ it('falls back to ~/.config on Linux and macOS', () => {+ for (const platform of ['linux', 'darwin'] as const) {+ assert.strictEqual(+ new TestConfigLocator([], {}, platform).getGlobalConfigPath(),+ HOME_CONFIG,+ );+ }+ });++ it('respects XDG_CONFIG_HOME', () => {+ assert.strictEqual(+ new TestConfigLocator([], {XDG_CONFIG_HOME}).getGlobalConfigPath(),+ XDG_CONFIG,+ );+ });++ it('ignores a relative XDG_CONFIG_HOME', () => {+ assert.strictEqual(+ new TestConfigLocator([], {+ XDG_CONFIG_HOME: 'relative',+ }).getGlobalConfigPath(),+ HOME_CONFIG,+ );+ });++ it('uses LOCALAPPDATA on Windows', () => {+ const localAppData = path.resolve('/AppData/Local');+ assert.strictEqual(+ new TestConfigLocator(+ [],+ {LOCALAPPDATA: localAppData},+ 'win32',+ ).getGlobalConfigPath(),+ path.join(localAppData, 'Google', 'cd4a', 'config.json'),+ );+ });++ it('falls back to ~/.config on Windows without LOCALAPPDATA', () => {+ assert.strictEqual(+ new TestConfigLocator([], {}, 'win32').getGlobalConfigPath(),+ HOME_CONFIG,+ );+ });+ });++ describe('locate', () => {+ it('returns undefined when no config file exists', () => {+ assert.strictEqual(+ new TestConfigLocator([], {PLUGIN_DATA}).locate(),+ undefined,+ );+ });++ it('returns undefined when discovery is turned off', () => {+ assert.strictEqual(+ new TestConfigLocator([CWD_CONFIG, PLUGIN_CONFIG, HOME_CONFIG], {+ PLUGIN_DATA,+ CHROME_DEVTOOLS_MCP_NO_CONFIG_DISCOVERY: 'true',+ }).locate(),+ undefined,+ );+ });++ it('prefers the config file in the current working directory', () => {+ assert.strictEqual(+ new TestConfigLocator([CWD_CONFIG, PLUGIN_CONFIG, HOME_CONFIG], {+ PLUGIN_DATA,+ }).locate(),+ CWD_CONFIG,+ );+ });++ it('prefers the plugin data config over the global config', () => {+ assert.strictEqual(+ new TestConfigLocator([PLUGIN_CONFIG, HOME_CONFIG], {+ PLUGIN_DATA,+ }).locate(),+ PLUGIN_CONFIG,+ );+ });++ it('skips the plugin data config when PLUGIN_DATA is not set', () => {+ assert.strictEqual(+ new TestConfigLocator([PLUGIN_CONFIG, HOME_CONFIG]).locate(),+ HOME_CONFIG,+ );+ });++ it('does not use ~/.config when XDG_CONFIG_HOME is set', () => {+ assert.strictEqual(+ new TestConfigLocator([HOME_CONFIG], {XDG_CONFIG_HOME}).locate(),+ undefined,+ );+ });+ });+});diff --git a/tests/config/mcp-options.test.ts b/tests/config/mcp-options.test.tsindex 33976f13..92a1bb7c 100644--- a/tests/config/mcp-options.test.ts+++ b/tests/config/mcp-options.test.ts@@ -5,10 +5,12 @@*/import assert from 'node:assert';+import fs from 'node:fs';import {afterEach, describe, it} from 'node:test';import sinon from 'sinon';+import {ConfigLocator} from '../../src/config/ConfigLocator.js';import {ConfigParser} from '../../src/config/ConfigParser.js';import {DEFAULT_FILESYSTEM_ROOT} from '../../src/config/mcp-options.js';import {createTempFile} from '../utils.js';@@ -18,6 +20,13 @@ describe('mcp-options steps', () => {const parser = new ConfigParser('0.0.0');+ describe('constructor', () => {+ it('initializes configLocator', () => {+ const testParser = new ConfigParser('0.0.0');+ assert.ok(testParser.configLocator instanceof ConfigLocator);+ });+ });+describe('parseCliArgs', () => {it('returns only explicitly passed flags', () => {const args = new ConfigParser('0.0.0', [@@ -172,10 +181,114 @@ describe('mcp-options steps', () => {it('turns off usage statistics in CI', () => {sinon.stub(console, 'error');- const args = new ConfigParser('0.0.0', [], {CI: 'true'}).applyDefaults({+ const args = new ConfigParser('0.0.0', [], {+ CI: 'true',+ }).applyDefaults({usageStatistics: true,});assert.strictEqual(args.usageStatistics, false);});});++ describe('config discovery', () => {+ it('does not discover a config file without a locator', () => {+ const parser = new ConfigParser('0.0.0', ['node', 'main.js'], {}, false);+ sinon.stub(parser.configLocator, 'locate').returns(undefined);+ assert.strictEqual(parser.parse().config, undefined);+ });++ it('uses the config file found by the locator', () => {+ using configFile = createTempFile(+ JSON.stringify({headless: true}),+ 'cd4a.config.json',+ );+ const parser = new ConfigParser('0.0.0', ['node', 'main.js'], {}, false);+ const locateStub = sinon+ .stub(parser.configLocator, 'locate')+ .returns(configFile.path);++ const args = parser.parse();++ assert.strictEqual(args.headless, true);+ assert.strictEqual(args.config, configFile.path);+ sinon.assert.calledOnce(locateStub);+ });++ it('prefers --config over a discovered config file', () => {+ using configFile = createTempFile(+ JSON.stringify({headless: true}),+ 'cd4a.explicit.config.json',+ );+ const parser = new ConfigParser(+ '0.0.0',+ ['node', 'main.js', '--config', configFile.path],+ {},+ false,+ );+ const locateStub = sinon.stub(parser.configLocator, 'locate');++ assert.strictEqual(parser.parse().headless, true);+ sinon.assert.notCalled(locateStub);+ });+ });++ describe('reload', () => {+ function createParser(configPath: string, argv: string[] = []) {+ const parser = new ConfigParser(+ '0.0.0',+ ['node', 'main.js', ...argv],+ {},+ false,+ );+ const locateStub = sinon+ .stub(parser.configLocator, 'locate')+ .returns(configPath);+ return {parser, locateStub};+ }++ it('re-reads the config file without discovering it again', () => {+ using configFile = createTempFile(+ JSON.stringify({memoryDebugging: false}),+ 'cd4a.config.json',+ );+ const {parser, locateStub} = createParser(configFile.path);+ assert.strictEqual(parser.parse().memoryDebugging, false);++ fs.writeFileSync(+ configFile.path,+ JSON.stringify({memoryDebugging: true}),+ );++ assert.strictEqual(parser.reload().memoryDebugging, true);+ sinon.assert.calledOnce(locateStub);+ });++ it('keeps CLI arguments over the config file', () => {+ using configFile = createTempFile(+ JSON.stringify({headless: false}),+ 'cd4a.config.json',+ );+ const {parser} = createParser(configFile.path, ['--headless']);+ parser.parse();++ fs.writeFileSync(+ configFile.path,+ JSON.stringify({headless: false, memoryDebugging: true}),+ );+ const args = parser.reload();++ assert.strictEqual(args.headless, true);+ assert.strictEqual(args.memoryDebugging, true);+ });++ it('throws on an invalid config file', () => {+ using configFile = createTempFile('{}', 'cd4a.config.json');+ const {parser} = createParser(configFile.path);+ parser.parse();++ fs.writeFileSync(configFile.path, '{');++ assert.throws(() => parser.reload(), /Invalid JSON config file/);+ });+ });});