chrome-devtools-mcp 1.10.0 → 1.11.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 (86) hide show
  1. package/build/src/BrowserManager.js +132 -13
  2. package/build/src/McpContext.js +188 -138
  3. package/build/src/McpPage.js +348 -96
  4. package/build/src/McpResponse.js +234 -76
  5. package/build/src/McpWorker.js +66 -0
  6. package/build/src/SlimMcpResponse.js +5 -1
  7. package/build/src/TextSnapshot.js +3 -2
  8. package/build/src/ToolHandler.js +80 -42
  9. package/build/src/bin/chrome-devtools-mcp-main.js +8 -7
  10. package/build/src/bin/chrome-devtools-mcp.js +1 -1
  11. package/build/src/bin/chrome-devtools.js +31 -41
  12. package/build/src/collectors/ServiceWorkerCollector.js +18 -11
  13. package/build/src/config/ConfigLocator.js +70 -0
  14. package/build/src/config/ConfigParser.js +264 -0
  15. package/build/src/config/ConfigWatcher.js +93 -0
  16. package/build/src/config/browser-options.js +2 -13
  17. package/build/src/config/category-options.js +15 -30
  18. package/build/src/config/cli-commands.js +165 -5
  19. package/build/src/config/cli-options.js +410 -43
  20. package/build/src/config/mcp-options.js +156 -234
  21. package/build/src/config/puppeteer-options.js +65 -0
  22. package/build/src/config/tool-options.js +60 -0
  23. package/build/src/daemon/client.js +81 -41
  24. package/build/src/daemon/daemon.js +55 -45
  25. package/build/src/daemon/utils.js +44 -11
  26. package/build/src/devtools/DevToolsCommentBridge.js +43 -6
  27. package/build/src/devtools/DevtoolsUtils.js +3 -3
  28. package/build/src/devtools/McpHostBindingAdapter.js +0 -1
  29. package/build/src/formatters/CommentFormatter.js +4 -13
  30. package/build/src/formatters/ConsoleFormatter.js +1 -1
  31. package/build/src/formatters/CssFormatter.js +3 -2
  32. package/build/src/formatters/HeapSnapshotFormatter.js +104 -46
  33. package/build/src/formatters/IssueFormatter.js +33 -32
  34. package/build/src/formatters/NetworkFormatter.js +12 -11
  35. package/build/src/formatters/SnapshotFormatter.js +31 -4
  36. package/build/src/index.js +54 -9
  37. package/build/src/processors/ChunkedTraceParser.js +11 -11
  38. package/build/src/processors/HeapSnapshotManager.js +121 -84
  39. package/build/src/processors/PerformanceTrace.js +9 -9
  40. package/build/src/telemetry/ClearcutLogger.js +1 -1
  41. package/build/src/telemetry/transformation.js +7 -11
  42. package/build/src/telemetry/watchdog/main.js +1 -1
  43. package/build/src/third_party/THIRD_PARTY_NOTICES +10 -367
  44. package/build/src/third_party/bundled-packages.json +7 -8
  45. package/build/src/third_party/devtools-formatter-worker.js +1193 -62
  46. package/build/src/third_party/devtools-heap-snapshot-worker.js +1126 -21
  47. package/build/src/third_party/index.js +8087 -19416
  48. package/build/src/third_party/issue-descriptions/cookieWarnMetadataGrantRead.md +0 -1
  49. package/build/src/third_party/issue-descriptions/cookieWarnMetadataGrantReadOptOut.md +5 -0
  50. package/build/src/third_party/issue-descriptions/cookieWarnMetadataGrantSet.md +0 -1
  51. package/build/src/third_party/issue-descriptions/cookieWarnMetadataGrantSetOptOut.md +5 -0
  52. package/build/src/third_party/issue-descriptions/deprecation.md +1 -1
  53. package/build/src/third_party/issue-descriptions/genericGeolocationPromptWithoutUserGesture.md +5 -0
  54. package/build/src/third_party/issue-descriptions/sriValidationFailedIntegrityMismatch.md +2 -0
  55. package/build/src/third_party/lighthouse-devtools-mcp-bundle.js +3 -3
  56. package/build/src/tools/ToolDefinition.js +16 -4
  57. package/build/src/tools/comments.js +20 -1
  58. package/build/src/tools/css.js +4 -2
  59. package/build/src/tools/emulation.js +17 -4
  60. package/build/src/tools/input.js +8 -3
  61. package/build/src/tools/lighthouse.js +112 -4
  62. package/build/src/tools/memory.js +129 -28
  63. package/build/src/tools/pages.js +5 -2
  64. package/build/src/tools/performance.js +21 -3
  65. package/build/src/tools/screencast.js +71 -32
  66. package/build/src/tools/screenshot.js +29 -14
  67. package/build/src/tools/script.js +90 -37
  68. package/build/src/tools/slim/tools.js +6 -8
  69. package/build/src/tools/thirdPartyDeveloper.js +6 -4
  70. package/build/src/tools/tools.js +35 -22
  71. package/build/src/tools/webmcp.js +9 -6
  72. package/build/src/types.js +11 -0
  73. package/build/src/utils/WaitForHelper.js +14 -1
  74. package/build/src/utils/check-for-updates.js +1 -1
  75. package/build/src/utils/errorHandling.js +20 -0
  76. package/build/src/utils/logger.js +15 -5
  77. package/build/src/utils/text.js +15 -0
  78. package/build/src/utils/url.js +99 -3
  79. package/build/src/version.js +1 -1
  80. package/package.json +14 -10
  81. package/skills/a11y-debugging/SKILL.md +4 -4
  82. package/skills/chrome-devtools/SKILL.md +2 -2
  83. package/skills/chrome-devtools-cli/SKILL.md +18 -15
  84. package/skills/cookie-debugging/SKILL.md +8 -5
  85. package/skills/debug-optimize-lcp/SKILL.md +1 -1
  86. package/skills/troubleshooting/SKILL.md +5 -6
@@ -6,9 +6,13 @@
6
6
  import { McpResponse } from './McpResponse.js';
7
7
  export class SlimMcpResponse extends McpResponse {
8
8
  async handle(_context) {
9
+ const error = this.error;
10
+ const responseText = error
11
+ ? [...this.responseLines, `Error: ${error.message}`].join('\n')
12
+ : this.responseLines.join('\n');
9
13
  const text = {
10
14
  type: 'text',
11
- text: this.responseLines.join('\n'),
15
+ text: responseText,
12
16
  };
13
17
  return {
14
18
  content: [text],
@@ -157,14 +157,15 @@ export class TextSnapshot {
157
157
  }
158
158
  // TODO: index by backendNodeId instead.
159
159
  const queue = [this.root];
160
- while (queue.length) {
161
- const current = queue.pop();
160
+ let current = queue.pop();
161
+ while (current) {
162
162
  if (current.backendNodeId === cdpBackendNodeId) {
163
163
  return current.id;
164
164
  }
165
165
  for (const child of current.children) {
166
166
  queue.push(child);
167
167
  }
168
+ current = queue.pop();
168
169
  }
169
170
  return;
170
171
  }
@@ -61,9 +61,26 @@ import { ClearcutLogger } from './telemetry/ClearcutLogger.js';
61
61
  import { zod } from './third_party/index.js';
62
62
  import { labels } from './tools/categories.js';
63
63
  import { categoryToFlagName } from './config/category-options.js';
64
+ import { isAvailableInMode, isSlimTool } from './tools/ToolDefinition.js';
64
65
  import { logger } from './utils/logger.js';
65
66
  import { fileURLToPath, pathToFileURL } from 'node:url';
66
67
  import { isLocalhost } from './utils/url.js';
68
+ /**
69
+ * Upper bound on how long a tool call may wait to acquire the browser
70
+ * (connect/launch and McpContext initialization). A connect attempt on a
71
+ * half-open socket can hang without ever failing; this bound turns that into
72
+ * a clear error and abandons the attempt so the next call starts fresh.
73
+ *
74
+ * This does not bound the tool's own work. A slow but valid call (a long
75
+ * `wait_for` timeout, an `evaluate_script` awaiting a slow promise, a
76
+ * Lighthouse audit) must finish on its own terms without the browser being
77
+ * closed underneath it. A transport that dies mid-call is detected by the
78
+ * WebSocket keep-alive configured in BrowserManager#connect(), which rejects
79
+ * the in-flight CDP calls and fires `disconnected`.
80
+ */
81
+ export const TOOL_CALL_TIMEOUT_MS = 60_000;
82
+ class ToolCallTimeoutError extends Error {
83
+ }
67
84
  function buildDisabledMessage(toolName, flag, categoryLabel) {
68
85
  const reason = categoryLabel
69
86
  ? `is in category ${categoryLabel} which`
@@ -71,6 +88,15 @@ function buildDisabledMessage(toolName, flag, categoryLabel) {
71
88
  return `Tool ${toolName} ${reason} is currently disabled. Enable it by running chrome-devtools start ${flag}=true. For more information check the README.`;
72
89
  }
73
90
  function getToolStatusInfo(tool, serverArgs) {
91
+ if (!isAvailableInMode(tool, serverArgs)) {
92
+ return {
93
+ disabled: true,
94
+ unavailableInMode: true,
95
+ reason: isSlimTool(tool)
96
+ ? `Tool ${tool.name} is only available with --slim.`
97
+ : `Tool ${tool.name} is not available with --slim.`,
98
+ };
99
+ }
74
100
  const category = tool.annotations.category;
75
101
  if (category) {
76
102
  const flag = categoryToFlagName(category);
@@ -94,24 +120,16 @@ function getToolStatusInfo(tool, serverArgs) {
94
120
  function isPageScopedTool(tool) {
95
121
  return 'pageScoped' in tool && tool.pageScoped === true;
96
122
  }
97
- function formatArgumentNames(names) {
98
- return names.map(name => `"${name}"`).join(', ');
99
- }
100
- function buildUnknownArgumentsMessage(toolName, unknownArgumentNames, expectedArgumentNames) {
101
- const unknownLabel = unknownArgumentNames.length === 1 ? 'argument' : 'arguments';
102
- const expectedArguments = expectedArgumentNames.length
103
- ? `Expected arguments: ${formatArgumentNames(expectedArgumentNames)}.`
104
- : 'This tool does not accept any arguments.';
105
- const correction = unknownArgumentNames.length === 1 ? 'Remove it' : 'Remove them';
106
- return `Unknown ${unknownLabel} for tool "${toolName}": ${formatArgumentNames(unknownArgumentNames)}. ${expectedArguments} ${correction} and retry.`;
107
- }
108
123
  async function validateAndResolvePathOrUrl(filePathOrUrl, context) {
124
+ if (filePathOrUrl.trim().length === 0) {
125
+ return undefined;
126
+ }
109
127
  try {
110
128
  const url = new URL(filePathOrUrl);
111
129
  if (url.protocol === 'file:') {
112
130
  return pathToFileURL(await context.validatePath(fileURLToPath(url))).href;
113
131
  }
114
- else if (['http:', 'https:', 'ws:', 'wss:'].includes(url.protocol)) {
132
+ if (['http:', 'https:', 'ws:', 'wss:'].includes(url.protocol)) {
115
133
  return filePathOrUrl;
116
134
  }
117
135
  }
@@ -154,7 +172,10 @@ async function validateToolFiles(tool, params, context) {
154
172
  const updated = [];
155
173
  for (const item of val) {
156
174
  if (typeof item === 'string') {
157
- updated.push(await validateAndResolvePathOrUrl(item, context));
175
+ const resolved = await validateAndResolvePathOrUrl(item, context);
176
+ if (resolved !== undefined) {
177
+ updated.push(resolved);
178
+ }
158
179
  }
159
180
  else {
160
181
  throw new Error('Unexpected non-string value as a file path or URL');
@@ -170,28 +191,54 @@ export class ToolHandler {
170
191
  serverArgs;
171
192
  getContext;
172
193
  toolMutex;
194
+ abandonPendingBrowserAttemptOnTimeout;
173
195
  inputSchema;
174
196
  registeredInputSchema;
175
197
  disabled;
176
198
  disabledReason;
177
- constructor(tool, serverArgs, getContext, toolMutex) {
199
+ constructor(tool, serverArgs, getContext, toolMutex, abandonPendingBrowserAttemptOnTimeout) {
178
200
  this.tool = tool;
179
201
  this.serverArgs = serverArgs;
180
202
  this.getContext = getContext;
181
203
  this.toolMutex = toolMutex;
182
- const { disabled, reason } = getToolStatusInfo(tool, serverArgs);
204
+ this.abandonPendingBrowserAttemptOnTimeout = abandonPendingBrowserAttemptOnTimeout;
205
+ const { disabled, reason, unavailableInMode } = getToolStatusInfo(tool, serverArgs);
183
206
  this.disabledReason = reason;
184
- this.disabled = disabled && !serverArgs.viaCli;
207
+ this.disabled =
208
+ disabled && (Boolean(unavailableInMode) || !serverArgs.viaCli);
185
209
  this.inputSchema = tool.schema;
186
- this.registeredInputSchema = zod.object(this.inputSchema).loose();
210
+ this.registeredInputSchema = zod.object(this.inputSchema).strict();
187
211
  }
188
- unknownArgumentNames(params) {
189
- return Object.keys(params).filter(key => !Object.hasOwn(this.inputSchema, key));
212
+ /**
213
+ * Races a promise against TOOL_CALL_TIMEOUT_MS, calling onTimeout() if the
214
+ * timer wins. The loser of the race is left running — there is no way to
215
+ * cancel a pending connect/launch — but since nothing is left awaiting it,
216
+ * it cannot block subsequent tool calls.
217
+ */
218
+ async #raceWithTimeout(promise, onTimeout) {
219
+ const timeoutError = new ToolCallTimeoutError(`Tool "${this.tool.name}" timed out after ${TOOL_CALL_TIMEOUT_MS}ms waiting for the browser connection to be established. The connection attempt will be retried automatically on the next tool call.`);
220
+ let timer;
221
+ const timeout = new Promise((_, reject) => {
222
+ timer = setTimeout(() => reject(timeoutError), TOOL_CALL_TIMEOUT_MS);
223
+ timer.unref?.();
224
+ });
225
+ try {
226
+ return await Promise.race([promise, timeout]);
227
+ }
228
+ catch (err) {
229
+ if (err === timeoutError) {
230
+ onTimeout();
231
+ }
232
+ throw err;
233
+ }
234
+ finally {
235
+ clearTimeout(timer);
236
+ }
190
237
  }
191
238
  handle = async (params) => {
192
239
  const env_1 = { stack: [], error: void 0, hasError: false };
193
240
  try {
194
- const _guard = __addDisposableResource(env_1, await this.toolMutex.acquire(), false);
241
+ const guard = __addDisposableResource(env_1, await this.toolMutex.acquire(), false);
195
242
  if (this.disabledReason) {
196
243
  return {
197
244
  content: [
@@ -203,25 +250,19 @@ export class ToolHandler {
203
250
  isError: true,
204
251
  };
205
252
  }
206
- const unknownArgumentNames = this.unknownArgumentNames(params);
207
- if (unknownArgumentNames.length) {
208
- return {
209
- content: [
210
- {
211
- type: 'text',
212
- text: buildUnknownArgumentsMessage(this.tool.name, unknownArgumentNames, Object.keys(this.inputSchema)),
213
- },
214
- ],
215
- isError: true,
216
- };
217
- }
218
253
  const startTime = Date.now();
219
254
  let success = false;
220
255
  let devToolsData;
221
256
  let pageUrl;
222
257
  try {
223
258
  logger?.(`${this.tool.name} request: ${JSON.stringify(params, null, ' ')}`);
224
- const context = await this.getContext();
259
+ // ensureBrowser() has no cancellation mechanism, so this timeout only
260
+ // stops us from waiting — the attempt itself keeps running abandoned.
261
+ // abandonPendingBrowserAttemptOnTimeout() tells BrowserManager to
262
+ // discard that attempt if it succeeds later instead of handing it to a
263
+ // subsequent caller — see BrowserManager#abandonPendingAttempt()'s doc
264
+ // comment for the full mechanism.
265
+ const context = await this.#raceWithTimeout(this.getContext(), () => this.abandonPendingBrowserAttemptOnTimeout());
225
266
  logger?.(`${this.tool.name} context: resolved`);
226
267
  const response = this.serverArgs.slim
227
268
  ? new SlimMcpResponse(this.serverArgs)
@@ -238,9 +279,10 @@ export class ToolHandler {
238
279
  page =
239
280
  this.serverArgs.pageIdRouting &&
240
281
  pageId !== undefined &&
241
- !this.serverArgs.slim
282
+ !isSlimTool(this.tool)
242
283
  ? context.getPageById(pageId)
243
284
  : context.getSelectedMcpPage();
285
+ await page?.init();
244
286
  response.setPage(page);
245
287
  if (this.tool.blockedByDialog) {
246
288
  page.throwIfDialogOpen();
@@ -261,14 +303,10 @@ export class ToolHandler {
261
303
  }
262
304
  devToolsData = await context.getDevToolsData(page);
263
305
  pageUrl = context.getSelectedMcpPageUrl(page);
264
- // Resolve data format: --experimentalDataFormat takes precedence, fall back to legacy --experimentalToonFormat
265
- let dataFormat = 'default';
266
- if (this.serverArgs.experimentalDataFormat) {
267
- dataFormat = this.serverArgs.experimentalDataFormat;
268
- }
269
- else if (this.serverArgs.experimentalToonFormat) {
270
- dataFormat = 'toon';
271
- }
306
+ // --experimentalDataFormat takes precedence over the legacy
307
+ // --experimentalToonFormat.
308
+ const dataFormat = this.serverArgs.experimentalDataFormat ??
309
+ (this.serverArgs.experimentalToonFormat ? 'toon' : 'default');
272
310
  const { content, structuredContent } = await response.handle(context, dataFormat);
273
311
  const result = {
274
312
  content,
@@ -12,16 +12,17 @@ import { computeFlagUsage } from '../telemetry/flagUtils.js';
12
12
  import { StdioServerTransport } from '../third_party/index.js';
13
13
  import { checkForUpdates } from '../utils/check-for-updates.js';
14
14
  import { logger, saveLogsToFile } from '../utils/logger.js';
15
+ import { setupUnhandledRejectionHandler } from '../utils/errorHandling.js';
15
16
  import { VERSION } from '../version.js';
16
- import { mcpOptions, parseArguments } from '../config/mcp-options.js';
17
+ import { mcpOptions } from '../config/mcp-options.js';
18
+ import { ConfigParser } from '../config/ConfigParser.js';
17
19
  await checkForUpdates('Run `npm install chrome-devtools-mcp@latest` to update.');
18
- export const args = parseArguments(VERSION);
20
+ const configParser = new ConfigParser(VERSION);
21
+ export const args = configParser.parse();
19
22
  const logFile = args.logFile ? saveLogsToFile(args.logFile) : undefined;
20
- if (process.env['CHROME_DEVTOOLS_MCP_CRASH_ON_UNCAUGHT'] !== 'true') {
21
- process.on('unhandledRejection', (reason, promise) => {
22
- logger?.('Unhandled promise rejection', promise, reason);
23
- });
24
- }
23
+ setupUnhandledRejectionHandler(() => {
24
+ process.exit(1);
25
+ });
25
26
  logger?.(`Starting Chrome DevTools MCP Server v${VERSION}`);
26
27
  const browserManager = new BrowserManager(args, {
27
28
  logFile,
@@ -4,8 +4,8 @@
4
4
  * Copyright 2025 Google LLC
5
5
  * SPDX-License-Identifier: Apache-2.0
6
6
  */
7
- process.title = 'chrome-devtools-mcp';
8
7
  import { version } from 'node:process';
8
+ process.title = 'chrome-devtools-mcp';
9
9
  const [major, minor] = version.substring(1).split('.').map(Number);
10
10
  if (major === 20 && minor < 19) {
11
11
  console.error(`ERROR: \`chrome-devtools-mcp\` does not support Node ${process.version}. Please upgrade to Node 20.19.0 LTS or a newer LTS.`);
@@ -4,7 +4,6 @@
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';
@@ -12,28 +11,32 @@ import { logDisclaimers } from '../index.js';
12
11
  import { hideBin, yargs } from '../third_party/index.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 { mcpOptions, 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)) {
177
+ if (!daemonRunning) {
188
178
  await start(serializeArgs(mcpOptions, argv), 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({
@@ -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,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