chrome-devtools-mcp 1.10.1 → 1.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/README.md +72 -20
  2. package/build/src/BrowserManager.js +155 -27
  3. package/build/src/McpContext.js +598 -200
  4. package/build/src/McpPage.js +513 -131
  5. package/build/src/McpResponse.js +291 -116
  6. package/build/src/McpWorker.js +66 -0
  7. package/build/src/SlimMcpResponse.js +5 -1
  8. package/build/src/TextSnapshot.js +40 -20
  9. package/build/src/ToolHandler.js +306 -147
  10. package/build/src/bin/chrome-devtools-mcp-main.js +13 -10
  11. package/build/src/bin/chrome-devtools-mcp.js +1 -1
  12. package/build/src/bin/chrome-devtools.js +34 -44
  13. package/build/src/collectors/PageCollector.js +13 -9
  14. package/build/src/collectors/ServiceWorkerCollector.js +20 -13
  15. package/build/src/collectors/constants.js +7 -0
  16. package/build/src/config/ConfigLocator.js +70 -0
  17. package/build/src/config/ConfigParser.js +159 -0
  18. package/build/src/config/ConfigWatcher.js +94 -0
  19. package/build/src/config/ServerConfig.js +251 -0
  20. package/build/src/config/browser-options.js +15 -17
  21. package/build/src/config/category-options.js +15 -30
  22. package/build/src/config/cli-commands.js +165 -5
  23. package/build/src/config/cli-options.js +441 -58
  24. package/build/src/config/mcp-options.js +212 -264
  25. package/build/src/config/puppeteer-options.js +67 -0
  26. package/build/src/config/tool-options.js +60 -0
  27. package/build/src/daemon/client.js +84 -44
  28. package/build/src/daemon/daemon.js +59 -45
  29. package/build/src/daemon/utils.js +46 -12
  30. package/build/src/devtools/DevToolsCommentBridge.js +71 -11
  31. package/build/src/devtools/DevtoolsUtils.js +52 -15
  32. package/build/src/devtools/McpHostBindingAdapter.js +0 -1
  33. package/build/src/formatters/CommentFormatter.js +4 -13
  34. package/build/src/formatters/ConsoleFormatter.js +29 -2
  35. package/build/src/formatters/CssFormatter.js +3 -2
  36. package/build/src/formatters/HeapSnapshotFormatter.js +111 -57
  37. package/build/src/formatters/IssueFormatter.js +33 -32
  38. package/build/src/formatters/NetworkFormatter.js +62 -22
  39. package/build/src/formatters/RemoteObjectFormatter.js +231 -0
  40. package/build/src/formatters/SnapshotFormatter.js +44 -7
  41. package/build/src/index.js +285 -88
  42. package/build/src/processors/ChunkedTraceParser.js +11 -11
  43. package/build/src/processors/HeapSnapshotManager.js +455 -156
  44. package/build/src/processors/PerformanceTrace.js +9 -9
  45. package/build/src/telemetry/ClearcutLogger.js +1 -1
  46. package/build/src/telemetry/transformation.js +7 -11
  47. package/build/src/telemetry/watchdog/main.js +1 -1
  48. package/build/src/third_party/THIRD_PARTY_NOTICES +399 -689
  49. package/build/src/third_party/bundled-packages.json +7 -8
  50. package/build/src/third_party/cli.js +9239 -0
  51. package/build/src/third_party/devtools-formatter-worker.js +4299 -2517
  52. package/build/src/third_party/devtools-heap-snapshot-worker.js +1298 -22
  53. package/build/src/third_party/index.js +132003 -146852
  54. package/build/src/third_party/issue-descriptions/cookieWarnMetadataGrantRead.md +0 -1
  55. package/build/src/third_party/issue-descriptions/cookieWarnMetadataGrantReadOptOut.md +5 -0
  56. package/build/src/third_party/issue-descriptions/cookieWarnMetadataGrantSet.md +0 -1
  57. package/build/src/third_party/issue-descriptions/cookieWarnMetadataGrantSetOptOut.md +5 -0
  58. package/build/src/third_party/issue-descriptions/deprecation.md +1 -1
  59. package/build/src/third_party/issue-descriptions/genericGeolocationPromptWithoutUserGesture.md +5 -0
  60. package/build/src/third_party/issue-descriptions/sriValidationFailedIntegrityMismatch.md +2 -0
  61. package/build/src/third_party/lighthouse-devtools-mcp-bundle.js +54576 -52174
  62. package/build/src/tools/ToolDefinition.js +102 -12
  63. package/build/src/tools/comments.js +62 -4
  64. package/build/src/tools/console.js +6 -4
  65. package/build/src/tools/css.js +5 -2
  66. package/build/src/tools/emulation.js +22 -8
  67. package/build/src/tools/extensions.js +5 -0
  68. package/build/src/tools/input.js +29 -9
  69. package/build/src/tools/lighthouse.js +136 -12
  70. package/build/src/tools/memory.js +166 -59
  71. package/build/src/tools/network.js +5 -4
  72. package/build/src/tools/pages.js +52 -7
  73. package/build/src/tools/performance.js +28 -7
  74. package/build/src/tools/pwa.js +7 -0
  75. package/build/src/tools/screencast.js +74 -33
  76. package/build/src/tools/screenshot.js +52 -21
  77. package/build/src/tools/script.js +125 -40
  78. package/build/src/tools/slim/tools.js +27 -13
  79. package/build/src/tools/snapshot.js +13 -3
  80. package/build/src/tools/thirdPartyDeveloper.js +9 -5
  81. package/build/src/tools/tools.js +35 -22
  82. package/build/src/tools/webmcp.js +11 -6
  83. package/build/src/types.js +11 -0
  84. package/build/src/utils/TaskRunner.js +136 -0
  85. package/build/src/utils/WaitForHelper.js +15 -2
  86. package/build/src/utils/bytes.js +2 -12
  87. package/build/src/utils/check-for-updates.js +2 -2
  88. package/build/src/utils/disclaimers.js +27 -0
  89. package/build/src/utils/errorHandling.js +20 -0
  90. package/build/src/utils/keyboard.js +14 -2
  91. package/build/src/utils/logger.js +84 -5
  92. package/build/src/utils/resourceType.js +27 -0
  93. package/build/src/utils/text.js +44 -0
  94. package/build/src/utils/timeout.js +14 -0
  95. package/build/src/utils/url.js +140 -3
  96. package/build/src/version.js +1 -1
  97. package/package.json +16 -11
  98. package/skills/a11y-debugging/SKILL.md +7 -12
  99. package/skills/chrome-devtools/SKILL.md +2 -2
  100. package/skills/chrome-devtools-cli/SKILL.md +18 -15
  101. package/skills/cookie-debugging/SKILL.md +8 -5
  102. package/skills/debug-optimize-lcp/SKILL.md +1 -1
  103. package/skills/troubleshooting/SKILL.md +5 -6
@@ -4,36 +4,39 @@
4
4
  * Copyright 2026 Google LLC
5
5
  * SPDX-License-Identifier: Apache-2.0
6
6
  */
7
- process.title = 'chrome-devtools';
8
7
  import process from 'node:process';
9
8
  import { startDaemon, stopDaemon, sendCommand, handleResponse, verifyDaemonVersion, } from '../daemon/client.js';
10
9
  import { isDaemonRunning, serializeArgs, assertValidSessionId, } from '../daemon/utils.js';
11
- import { logDisclaimers } from '../index.js';
12
- import { hideBin, yargs } from '../third_party/index.js';
10
+ import { logDisclaimers } from '../utils/disclaimers.js';
11
+ import { hideBin, yargs } from '../third_party/cli.js';
13
12
  import { checkForUpdates } from '../utils/check-for-updates.js';
14
13
  import { VERSION } from '../version.js';
15
- import { buildCommand } from '../config/cli-commands.js';
14
+ import { buildCommand, getCommandArgSpec, shieldLiteralArgs, } from '../config/cli-commands.js';
16
15
  import { commands } from '../config/cli-options.js';
17
- import { mcpOptions, parseArguments, getMcpOptionsForViaCli, } from '../config/mcp-options.js';
16
+ import { getCliOptions } from '../config/mcp-options.js';
17
+ import { ConfigParser } from '../config/ConfigParser.js';
18
+ process.title = 'chrome-devtools';
18
19
  await checkForUpdates('Run `npm install -g chrome-devtools-mcp@latest` and `chrome-devtools start` to update and restart the daemon.');
19
20
  const DEFAULT_CLI_ARGS = ['--viaCli'];
20
- async function start(args, sessionId) {
21
+ async function start(args, sessionId, stopExisting = false) {
21
22
  const combinedArgs = [...DEFAULT_CLI_ARGS, ...args];
23
+ // Validates the arguments and the config file before starting the daemon.
24
+ const parsedArgs = new ConfigParser(VERSION, [
25
+ process.execPath,
26
+ process.argv[1],
27
+ ...combinedArgs,
28
+ ]).parse();
29
+ if (stopExisting && isDaemonRunning(sessionId)) {
30
+ await stopDaemon(sessionId);
31
+ }
22
32
  await startDaemon(combinedArgs, sessionId);
23
- logDisclaimers(parseArguments(VERSION, combinedArgs));
33
+ logDisclaimers(parsedArgs);
24
34
  }
25
- function getCliOptions() {
26
- const options = {
27
- ...getMcpOptionsForViaCli(),
28
- };
29
- // Missing CLI serialization.
30
- delete options.viewport;
31
- // Change the defaults for the CLI.
32
- delete options.experimentalStructuredContent;
33
- delete options.experimentalInteropTools;
34
- return options;
35
- }
36
- const y = yargs(hideBin(process.argv))
35
+ const { argv: cliArgs, restore: restoreLiteralArg } = shieldLiteralArgs(hideBin(process.argv), commandName => {
36
+ const commandDef = commands[commandName];
37
+ return commandDef ? getCommandArgSpec(commandDef.args) : undefined;
38
+ });
39
+ const y = yargs(cliArgs)
37
40
  .locale('en') // Force English to ensure error string matching works in .fail, all custom messages we output are in English anyways
38
41
  .scriptName('chrome-devtools')
39
42
  .showHelpOnFail(true)
@@ -66,7 +69,8 @@ const y = yargs(hideBin(process.argv))
66
69
  console.error('1. Required parameters MUST be passed as positional arguments (without flags).');
67
70
  console.error(' - INCORRECT: chrome-devtools click --pageId 1 --uid "1_2"');
68
71
  console.error(' - CORRECT: chrome-devtools click 1 "1_2"');
69
- console.error('2. Optional parameters are passed as double-dash options/flags (e.g. --dblClick true).');
72
+ console.error(' - CORRECT: chrome-devtools evaluate_script "() => document.title" --pageId 1');
73
+ console.error('2. Optional parameters are passed as double-dash options/flags (e.g. --dblClick true), except optional positional parameters shown in command help.');
70
74
  console.error('3. Make sure to escape quotes properly for your shell environment.');
71
75
  console.error('Run `chrome-devtools <command> --help` to see exact positional and optional parameters.');
72
76
  console.error('=========================================');
@@ -81,25 +85,8 @@ y.command('start', 'Start or restart chrome-devtools-mcp', y => y
81
85
  .options(getCliOptions())
82
86
  .example('$0 start --browserUrl http://localhost:9222', 'Start the server connecting to an existing browser')
83
87
  .strict(), async (argv) => {
84
- if (isDaemonRunning(argv.sessionId)) {
85
- await stopDaemon(argv.sessionId);
86
- }
87
- // Defaults but we do not want to affect the yargs conflict resolution.
88
- if (argv.isolated === undefined &&
89
- argv.userDataDir === undefined &&
90
- !argv.autoConnect &&
91
- !argv.browserUrl &&
92
- !argv.wsEndpoint) {
93
- argv.isolated = true;
94
- }
95
- if (argv.headless === undefined &&
96
- !argv.autoConnect &&
97
- !argv.browserUrl &&
98
- !argv.wsEndpoint) {
99
- argv.headless = true;
100
- }
101
88
  const args = serializeArgs(getCliOptions(), argv);
102
- await start(args, argv.sessionId);
89
+ await start(args, argv.sessionId, /* stopExisting= */ true);
103
90
  process.exit(0);
104
91
  }).strict(); // Re-enable strict validation for other commands; this is applied to the yargs instance itself
105
92
  y.command('status', 'Checks if chrome-devtools-mcp is running', y => y, async (argv) => {
@@ -151,7 +138,7 @@ for (const [commandName, commandDef] of Object.entries(commands)) {
151
138
  : opt.type === 'array'
152
139
  ? 'array'
153
140
  : 'string';
154
- if (opt.required) {
141
+ if (opt.positional) {
155
142
  const options = {
156
143
  describe: opt.description,
157
144
  type: type,
@@ -170,7 +157,9 @@ for (const [commandName, commandDef] of Object.entries(commands)) {
170
157
  type: type,
171
158
  };
172
159
  if (opt.default !== undefined) {
173
- options.default = opt.default;
160
+ // Document the default in --help without populating argv, so the
161
+ // daemon applies its current tool schema and config defaults.
162
+ options.defaultDescription = JSON.stringify(opt.default);
174
163
  }
175
164
  if (opt.enum) {
176
165
  options.choices = opt.enum;
@@ -181,16 +170,17 @@ for (const [commandName, commandDef] of Object.entries(commands)) {
181
170
  }, async (argv) => {
182
171
  const sessionId = argv.sessionId;
183
172
  try {
184
- const versionWarningPromise = isDaemonRunning(sessionId)
173
+ const daemonRunning = isDaemonRunning(sessionId);
174
+ const versionWarningPromise = daemonRunning
185
175
  ? verifyDaemonVersion(sessionId, VERSION)
186
176
  : Promise.resolve(undefined);
187
- if (!isDaemonRunning(sessionId)) {
188
- await start(serializeArgs(mcpOptions, argv), sessionId);
177
+ if (!daemonRunning) {
178
+ await start([], sessionId);
189
179
  }
190
180
  const commandArgs = {};
191
181
  for (const argName of Object.keys(args)) {
192
182
  if (argName in argv) {
193
- commandArgs[argName] = argv[argName];
183
+ commandArgs[argName] = restoreLiteralArg(argv[argName]);
194
184
  }
195
185
  }
196
186
  const response = await sendCommand({
@@ -4,15 +4,18 @@
4
4
  * SPDX-License-Identifier: Apache-2.0
5
5
  */
6
6
  import { FakeIssuesManager } from '../devtools/DevtoolsUtils.js';
7
- import { DevTools, FrameEvent } from '../third_party/index.js';
7
+ import { DevTools, FrameEvent, } from '../third_party/index.js';
8
8
  import { createIdGenerator, stableIdSymbol, } from '../utils/id.js';
9
9
  import { logger } from '../utils/logger.js';
10
+ import { DEFAULT_MAX_NAVIGATION_SAVED } from './constants.js';
10
11
  export class UncaughtError {
11
12
  details;
12
13
  targetId;
13
- constructor(details, targetId) {
14
+ session;
15
+ constructor(details, targetId, session) {
14
16
  this.details = details;
15
17
  this.targetId = targetId;
18
+ this.session = session;
16
19
  }
17
20
  }
18
21
  export class PageCollector {
@@ -20,15 +23,16 @@ export class PageCollector {
20
23
  #listeners;
21
24
  #pendingSameDocumentNavigation = false;
22
25
  #frameNavigatedWithinDocumentTarget;
23
- maxNavigationSaved = 3;
26
+ maxNavigationSaved;
24
27
  /**
25
28
  * This maps a Page to a list of navigations with a sub-list
26
29
  * of all collected resources.
27
30
  * The newer navigations come first.
28
31
  */
29
32
  storage = [[]];
30
- constructor(page, listeners, maxResourcesPerNavigation) {
33
+ constructor(page, listeners, { maxResourcesPerNavigation, maxNavigationSaved = DEFAULT_MAX_NAVIGATION_SAVED, } = {}) {
31
34
  this.pptrPage = page;
35
+ this.maxNavigationSaved = maxNavigationSaved;
32
36
  this.#attachFrameNavigatedWithinDocumentListener();
33
37
  const idGenerator = createIdGenerator();
34
38
  const listenerMap = listeners(value => {
@@ -129,8 +133,8 @@ export class PageCollector {
129
133
  export class ConsoleCollector extends PageCollector {
130
134
  static MAX_MESSAGES_PER_NAVIGATION = 10_000;
131
135
  #subscriber;
132
- constructor(page, listeners, maxMessagesPerNavigation = ConsoleCollector.MAX_MESSAGES_PER_NAVIGATION) {
133
- super(page, listeners, maxMessagesPerNavigation);
136
+ constructor(page, listeners, { maxResourcesPerNavigation = ConsoleCollector.MAX_MESSAGES_PER_NAVIGATION, maxNavigationSaved, } = {}) {
137
+ super(page, listeners, { maxResourcesPerNavigation, maxNavigationSaved });
134
138
  this.#subscriber = new PageEventSubscriber(this.pptrPage);
135
139
  this.#subscriber.subscribe();
136
140
  }
@@ -190,7 +194,7 @@ class PageEventSubscriber {
190
194
  this.#page.emit('devtoolsAggregatedIssue', event.data);
191
195
  };
192
196
  #onExceptionThrown = (event) => {
193
- this.#page.emit('uncaughtError', new UncaughtError(event.exceptionDetails, this.#targetId));
197
+ this.#page.emit('uncaughtError', new UncaughtError(event.exceptionDetails, this.#targetId, this.#session));
194
198
  };
195
199
  // On navigation, we reset issue aggregation.
196
200
  #onFrameNavigated = (frame) => {
@@ -259,14 +263,14 @@ class PageEventSubscriber {
259
263
  }
260
264
  export class NetworkCollector extends PageCollector {
261
265
  static MAX_REQUESTS_PER_NAVIGATION = 1_000;
262
- constructor(page, maxRequestsPerNavigation = NetworkCollector.MAX_REQUESTS_PER_NAVIGATION, listeners = collect => {
266
+ constructor(page, { maxResourcesPerNavigation = NetworkCollector.MAX_REQUESTS_PER_NAVIGATION, maxNavigationSaved, } = {}, listeners = collect => {
263
267
  return {
264
268
  request: req => {
265
269
  collect(req);
266
270
  },
267
271
  };
268
272
  }) {
269
- super(page, listeners, maxRequestsPerNavigation);
273
+ super(page, listeners, { maxResourcesPerNavigation, maxNavigationSaved });
270
274
  }
271
275
  splitAfterNavigation() {
272
276
  const requests = this.storage[0];
@@ -4,7 +4,7 @@
4
4
  * SPDX-License-Identifier: Apache-2.0
5
5
  */
6
6
  import { UncaughtError } from './PageCollector.js';
7
- import { createIdGenerator, stableIdSymbol } from '../utils/id.js';
7
+ import { createIdGenerator, stableIdSymbol, } from '../utils/id.js';
8
8
  const CHROME_EXTENSION_PREFIX = 'chrome-extension://';
9
9
  export class ServiceWorkerSubscriber {
10
10
  #target;
@@ -37,7 +37,7 @@ export class ServiceWorkerSubscriber {
37
37
  const url = this.#target.url();
38
38
  const extensionId = extractExtensionId(url);
39
39
  if (extensionId) {
40
- this.#callback(new UncaughtError(event.exceptionDetails, extensionId));
40
+ this.#callback(new UncaughtError(event.exceptionDetails, extensionId, this.#session));
41
41
  }
42
42
  };
43
43
  }
@@ -69,9 +69,7 @@ export class ServiceWorkerConsoleCollector {
69
69
  this.#browser.off('targetdestroyed', this.#onTargetDestroyed);
70
70
  for (const subscriber of this.#serviceWorkerSubscribers.values()) {
71
71
  subscriber.unsubscribe().catch(err => {
72
- if (err instanceof Error &&
73
- !err.message.includes('Target closed') &&
74
- !err.message.includes('Session closed')) {
72
+ if (!isIgnoredTargetError(err)) {
75
73
  // Swallow error as we are tearing down the system
76
74
  }
77
75
  });
@@ -91,33 +89,35 @@ export class ServiceWorkerConsoleCollector {
91
89
  const subscriber = new ServiceWorkerSubscriber(target, item => {
92
90
  this.addLog(extensionId, item);
93
91
  });
92
+ this.#serviceWorkerSubscribers.set(target, subscriber);
94
93
  try {
95
94
  await subscriber.subscribe();
95
+ if (this.#serviceWorkerSubscribers.get(target) !== subscriber) {
96
+ await subscriber.unsubscribe();
97
+ }
96
98
  }
97
99
  catch (err) {
98
- if (err instanceof Error &&
99
- !err.message.includes('Target closed') &&
100
- !err.message.includes('Session closed')) {
100
+ if (this.#serviceWorkerSubscribers.get(target) === subscriber) {
101
+ this.#serviceWorkerSubscribers.delete(target);
102
+ }
103
+ if (!isIgnoredTargetError(err)) {
101
104
  throw err;
102
105
  }
103
106
  }
104
- this.#serviceWorkerSubscribers.set(target, subscriber);
105
107
  }
106
108
  };
107
109
  #onTargetDestroyed = async (target) => {
108
110
  const subscriber = this.#serviceWorkerSubscribers.get(target);
109
111
  if (subscriber) {
112
+ this.#serviceWorkerSubscribers.delete(target);
110
113
  try {
111
114
  await subscriber.unsubscribe();
112
115
  }
113
116
  catch (err) {
114
- if (err instanceof Error &&
115
- !err.message.includes('Target closed') &&
116
- !err.message.includes('Session closed')) {
117
+ if (!isIgnoredTargetError(err)) {
117
118
  throw err;
118
119
  }
119
120
  }
120
- this.#serviceWorkerSubscribers.delete(target);
121
121
  }
122
122
  };
123
123
  addLog(extensionId, log) {
@@ -168,4 +168,11 @@ function extractExtensionId(origin) {
168
168
  function isExtensionOrigin(origin) {
169
169
  return origin.startsWith(CHROME_EXTENSION_PREFIX);
170
170
  }
171
+ function isIgnoredTargetError(err) {
172
+ return (err instanceof Error &&
173
+ (err.message.includes('Target closed') ||
174
+ err.message.includes('Session closed') ||
175
+ err.message.includes('No target with given id found') ||
176
+ err.message.includes('No session with given id')));
177
+ }
171
178
  //# sourceMappingURL=ServiceWorkerCollector.js.map
@@ -0,0 +1,7 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+ export const DEFAULT_MAX_NAVIGATION_SAVED = 3;
7
+ //# sourceMappingURL=constants.js.map
@@ -0,0 +1,70 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+ import fs from 'node:fs';
7
+ import os from 'node:os';
8
+ import path from 'node:path';
9
+ export const CONFIG_FILE_NAME = 'cd4a.config.json';
10
+ /**
11
+ * Turns off config file discovery, for example in tests. A config file passed
12
+ * via `--config` is still used.
13
+ */
14
+ export const NO_CONFIG_DISCOVERY_ENV = 'CHROME_DEVTOOLS_MCP_NO_CONFIG_DISCOVERY';
15
+ function isFile(filePath) {
16
+ try {
17
+ return fs.statSync(filePath, { throwIfNoEntry: false })?.isFile() ?? false;
18
+ }
19
+ catch {
20
+ return false;
21
+ }
22
+ }
23
+ /**
24
+ * Finds the config file in the predefined locations. The first existing file
25
+ * wins, config files are not merged.
26
+ *
27
+ * Locations, from highest to lowest priority:
28
+ * 1. `${PLUGIN_DATA}/cd4a.config.json`
29
+ * 2. The global config: `$XDG_CONFIG_HOME/cd4a/config.json` on macOS and
30
+ * Linux, `%LOCALAPPDATA%/Google/cd4a/config.json` on Windows, with a
31
+ * fallback to `~/.config/cd4a/config.json`.
32
+ *
33
+ * An explicit `--config` takes precedence over all of them and is handled by
34
+ * the ConfigParser. Discovery is turned off if the
35
+ * `CHROME_DEVTOOLS_MCP_NO_CONFIG_DISCOVERY` env variable is set.
36
+ */
37
+ export class ConfigLocator {
38
+ getSearchPaths(env = process.env) {
39
+ const searchPaths = [];
40
+ const pluginData = env['PLUGIN_DATA'];
41
+ if (pluginData) {
42
+ searchPaths.push(path.join(pluginData, CONFIG_FILE_NAME));
43
+ }
44
+ searchPaths.push(this.getGlobalConfigPath(env));
45
+ return searchPaths;
46
+ }
47
+ getGlobalConfigPath(env = process.env, platform = process.platform, homedir = os.homedir()) {
48
+ if (platform === 'win32') {
49
+ const localAppData = env['LOCALAPPDATA'];
50
+ if (localAppData) {
51
+ return path.join(localAppData, 'Google', 'cd4a', 'config.json');
52
+ }
53
+ }
54
+ else {
55
+ // Per the XDG Base Directory spec, relative paths must be ignored.
56
+ const xdgConfigHome = env['XDG_CONFIG_HOME'];
57
+ if (xdgConfigHome && path.isAbsolute(xdgConfigHome)) {
58
+ return path.join(xdgConfigHome, 'cd4a', 'config.json');
59
+ }
60
+ }
61
+ return path.join(homedir, '.config', 'cd4a', 'config.json');
62
+ }
63
+ locate(env = process.env, checkIsFile = isFile) {
64
+ if (env[NO_CONFIG_DISCOVERY_ENV]) {
65
+ return undefined;
66
+ }
67
+ return this.getSearchPaths(env).find(filePath => checkIsFile(filePath));
68
+ }
69
+ }
70
+ //# sourceMappingURL=ConfigLocator.js.map
@@ -0,0 +1,159 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+ import { readFileSync } from 'node:fs';
7
+ import { yargs, hideBin, } from '../third_party/cli.js';
8
+ import { getErrorMessage } from '../utils/errorHandling.js';
9
+ import { ConfigLocator } from './ConfigLocator.js';
10
+ import { mcpOptions, CLI_EXAMPLES, stripYargsPositionalArgs, withoutDefaults, } from './mcp-options.js';
11
+ import { ServerConfig } from './ServerConfig.js';
12
+ function isPlainObject(value) {
13
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
14
+ }
15
+ export class ConfigParser {
16
+ version;
17
+ argv;
18
+ env;
19
+ exitProcess;
20
+ #configPath;
21
+ #cliArgs;
22
+ #usageStatisticsNoticeShown = false;
23
+ configLocator;
24
+ constructor(version, argv = process.argv, env = process.env, exitProcess = true, configLocator) {
25
+ this.version = version;
26
+ this.argv = argv;
27
+ this.env = env;
28
+ this.exitProcess = exitProcess;
29
+ this.configLocator = configLocator ?? new ConfigLocator();
30
+ }
31
+ /**
32
+ * The config file resolved by the last `parse()` call, if any.
33
+ */
34
+ get configPath() {
35
+ return this.#configPath;
36
+ }
37
+ buildCliParser(options = mcpOptions) {
38
+ const yargsInstance = yargs(hideBin(this.argv));
39
+ return yargsInstance
40
+ .scriptName('npx chrome-devtools-mcp@latest')
41
+ .parserConfiguration({
42
+ 'strip-aliased': true,
43
+ 'strip-dashed': true,
44
+ })
45
+ .options(options)
46
+ .showHelpOnFail(false, 'Specify --help for available options')
47
+ .example(CLI_EXAMPLES)
48
+ .wrap(Math.min(120, yargsInstance.terminalWidth()))
49
+ .help()
50
+ .version(this.version);
51
+ }
52
+ /**
53
+ * Step 1: parses the CLI flags without applying defaults, so the result only
54
+ * contains what the user passed. `--help` and `--version` print and exit the
55
+ * process; parse errors throw.
56
+ */
57
+ parseCliArgs() {
58
+ const parsed = this.buildCliParser(withoutDefaults(mcpOptions))
59
+ .fail(false)
60
+ .parseSync();
61
+ return stripYargsPositionalArgs(parsed);
62
+ }
63
+ /**
64
+ * Step 2: reads the JSON config file and runs it through yargs to reject
65
+ * unknown keys and apply coercions, without applying defaults.
66
+ */
67
+ static parseConfigFile(configPath, rawContent) {
68
+ try {
69
+ const fileContent = JSON.parse(rawContent ?? readFileSync(configPath, 'utf-8'));
70
+ if (!isPlainObject(fileContent)) {
71
+ throw new Error('Config must be a JSON object');
72
+ }
73
+ const configOptions = withoutDefaults(mcpOptions);
74
+ delete configOptions.config;
75
+ const parsed = yargs([])
76
+ .parserConfiguration({
77
+ 'strip-aliased': true,
78
+ 'camel-case-expansion': false,
79
+ })
80
+ .options(configOptions)
81
+ .help(false)
82
+ .version(false)
83
+ .config(fileContent)
84
+ .strict()
85
+ .fail(false)
86
+ .exitProcess(false)
87
+ .parseSync([]);
88
+ return stripYargsPositionalArgs(parsed);
89
+ }
90
+ catch (err) {
91
+ throw new Error(`Invalid JSON config file: ${getErrorMessage(err)}`);
92
+ }
93
+ }
94
+ parseConfigFile(configPath, rawContent) {
95
+ return ConfigParser.parseConfigFile(configPath, rawContent);
96
+ }
97
+ warnUnknownArgs(cliArgs) {
98
+ const allowedArgs = new Set(Object.keys(mcpOptions));
99
+ const unknownArgs = Object.keys(cliArgs).filter(arg => !allowedArgs.has(arg));
100
+ if (unknownArgs.length > 0) {
101
+ console.error(`Unknown arguments: ${unknownArgs.map(arg => `--${arg}`)}`);
102
+ }
103
+ }
104
+ /**
105
+ * Parses CLI arguments and the config file into a layered
106
+ * {@link ServerConfig}.
107
+ */
108
+ parseConfig() {
109
+ try {
110
+ const cliArgs = this.parseCliArgs();
111
+ this.#cliArgs = cliArgs;
112
+ this.#configPath = cliArgs.config ?? this.configLocator.locate(this.env);
113
+ this.warnUnknownArgs(cliArgs);
114
+ return this.#resolveConfig(cliArgs);
115
+ }
116
+ catch (error) {
117
+ if (this.exitProcess) {
118
+ console.error(getErrorMessage(error));
119
+ process.exit(1);
120
+ }
121
+ throw error;
122
+ }
123
+ }
124
+ parse() {
125
+ return this.parseConfig().resolved;
126
+ }
127
+ /**
128
+ * Re-reads the config file resolved by `parse()` and merges it with the CLI
129
+ * arguments again into a new {@link ServerConfig}. Unlike `parseConfig()`, it
130
+ * does not discover a new config file and throws on invalid configuration
131
+ * instead of exiting the process.
132
+ */
133
+ reloadConfig() {
134
+ this.#cliArgs ??= this.parseCliArgs();
135
+ return this.#resolveConfig(this.#cliArgs);
136
+ }
137
+ /**
138
+ * Re-reads the config file resolved by `parse()` and merges it with the CLI
139
+ * arguments again. Unlike `parse()`, it does not discover a new config file
140
+ * and throws on invalid configuration instead of exiting the process.
141
+ */
142
+ reload() {
143
+ return this.reloadConfig().resolved;
144
+ }
145
+ #resolveConfig(cliArgs) {
146
+ const configPath = this.#configPath;
147
+ const fileArgs = configPath ? this.parseConfigFile(configPath) : {};
148
+ const config = ServerConfig.create({
149
+ cliArgs,
150
+ fileArgs,
151
+ configPath,
152
+ env: this.env,
153
+ suppressUsageStatisticsNotice: this.#usageStatisticsNoticeShown,
154
+ });
155
+ this.#usageStatisticsNoticeShown = true;
156
+ return config;
157
+ }
158
+ }
159
+ //# sourceMappingURL=ConfigParser.js.map
@@ -0,0 +1,94 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+ import fs from 'node:fs';
7
+ import path from 'node:path';
8
+ import { DevTools } from '../third_party/index.js';
9
+ import { getErrorMessage } from '../utils/errorHandling.js';
10
+ import { logger } from '../utils/logger.js';
11
+ const DEFAULT_DEBOUNCE_MS = 200;
12
+ /**
13
+ * Returns undefined if the file cannot be read, for example while it is being
14
+ * replaced.
15
+ */
16
+ function readContent(filePath) {
17
+ try {
18
+ return fs.readFileSync(filePath, 'utf8');
19
+ }
20
+ catch {
21
+ return undefined;
22
+ }
23
+ }
24
+ /**
25
+ * Watches a config file and calls `onChange` with the new content after it was
26
+ * modified.
27
+ *
28
+ * - Symlinks are resolved once on start, and the directory of the real file is
29
+ * watched. Watching the directory instead of the file keeps working when
30
+ * editors save atomically by replacing the file.
31
+ * - Events are debounced because some platforms emit several events for a
32
+ * single change.
33
+ * - Some platforms do not report the file name, such events are not filtered.
34
+ * - `onChange` is only called if the content changed. For example, macOS can
35
+ * report events that happened shortly before the watcher was started.
36
+ */
37
+ export class ConfigWatcher {
38
+ #configPath;
39
+ #onChange;
40
+ #debounceMs;
41
+ #watcher;
42
+ #debounced;
43
+ #content;
44
+ #pending = Promise.resolve();
45
+ constructor(configPath, onChange, options = {}) {
46
+ this.#configPath = configPath;
47
+ this.#onChange = onChange;
48
+ this.#debounceMs = options.debounceMs ?? DEFAULT_DEBOUNCE_MS;
49
+ }
50
+ /**
51
+ * Starts watching the config file. Throws if `configPath` does not exist.
52
+ */
53
+ start() {
54
+ if (this.#watcher) {
55
+ return;
56
+ }
57
+ const realPath = fs.realpathSync(this.#configPath);
58
+ const fileName = path.basename(realPath);
59
+ this.#content = readContent(realPath);
60
+ this.#debounced = DevTools.Common.Debouncer.debounce(() => {
61
+ const content = readContent(realPath);
62
+ if (content === undefined || content === this.#content) {
63
+ return;
64
+ }
65
+ this.#content = content;
66
+ this.#pending = this.#pending
67
+ .then(() => this.#onChange(content))
68
+ .catch(err => {
69
+ console.error(`Failed to apply ${this.#configPath}:`, err);
70
+ });
71
+ }, this.#debounceMs);
72
+ this.#watcher = fs.watch(path.dirname(realPath), { persistent: false }, (_eventType, changedFileName) => {
73
+ if (changedFileName !== null && changedFileName !== fileName) {
74
+ return;
75
+ }
76
+ this.#debounced?.();
77
+ });
78
+ this.#watcher.on('error', err => {
79
+ console.error(`Stopped watching ${this.#configPath}: ${getErrorMessage(err)}`);
80
+ this.dispose();
81
+ });
82
+ logger?.(`Watching ${realPath} for config changes`);
83
+ }
84
+ dispose() {
85
+ this.#debounced?.cancel();
86
+ this.#debounced = undefined;
87
+ this.#watcher?.close();
88
+ this.#watcher = undefined;
89
+ }
90
+ [Symbol.dispose]() {
91
+ this.dispose();
92
+ }
93
+ }
94
+ //# sourceMappingURL=ConfigWatcher.js.map