chrome-devtools-mcp 1.11.0 → 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 (72) hide show
  1. package/README.md +72 -20
  2. package/build/src/BrowserManager.js +27 -18
  3. package/build/src/McpContext.js +435 -87
  4. package/build/src/McpPage.js +189 -59
  5. package/build/src/McpResponse.js +61 -44
  6. package/build/src/TextSnapshot.js +37 -18
  7. package/build/src/ToolHandler.js +256 -135
  8. package/build/src/bin/chrome-devtools-mcp-main.js +6 -4
  9. package/build/src/bin/chrome-devtools.js +4 -4
  10. package/build/src/collectors/PageCollector.js +13 -9
  11. package/build/src/collectors/ServiceWorkerCollector.js +2 -2
  12. package/build/src/collectors/constants.js +7 -0
  13. package/build/src/config/ConfigParser.js +44 -149
  14. package/build/src/config/ConfigWatcher.js +3 -2
  15. package/build/src/config/ServerConfig.js +251 -0
  16. package/build/src/config/browser-options.js +13 -4
  17. package/build/src/config/cli-options.js +35 -19
  18. package/build/src/config/mcp-options.js +61 -35
  19. package/build/src/config/puppeteer-options.js +4 -2
  20. package/build/src/daemon/client.js +3 -3
  21. package/build/src/daemon/daemon.js +7 -3
  22. package/build/src/daemon/utils.js +2 -1
  23. package/build/src/devtools/DevToolsCommentBridge.js +28 -5
  24. package/build/src/devtools/DevtoolsUtils.js +49 -12
  25. package/build/src/formatters/ConsoleFormatter.js +28 -1
  26. package/build/src/formatters/HeapSnapshotFormatter.js +14 -18
  27. package/build/src/formatters/NetworkFormatter.js +54 -15
  28. package/build/src/formatters/RemoteObjectFormatter.js +231 -0
  29. package/build/src/formatters/SnapshotFormatter.js +13 -3
  30. package/build/src/index.js +256 -104
  31. package/build/src/processors/HeapSnapshotManager.js +390 -128
  32. package/build/src/third_party/THIRD_PARTY_NOTICES +542 -445
  33. package/build/src/third_party/bundled-packages.json +2 -2
  34. package/build/src/third_party/cli.js +9239 -0
  35. package/build/src/third_party/devtools-formatter-worker.js +3089 -2438
  36. package/build/src/third_party/devtools-heap-snapshot-worker.js +172 -1
  37. package/build/src/third_party/index.js +52247 -55764
  38. package/build/src/third_party/lighthouse-devtools-mcp-bundle.js +54576 -52174
  39. package/build/src/tools/ToolDefinition.js +90 -12
  40. package/build/src/tools/comments.js +42 -3
  41. package/build/src/tools/console.js +6 -4
  42. package/build/src/tools/css.js +1 -0
  43. package/build/src/tools/emulation.js +5 -4
  44. package/build/src/tools/extensions.js +5 -0
  45. package/build/src/tools/input.js +21 -6
  46. package/build/src/tools/lighthouse.js +24 -8
  47. package/build/src/tools/memory.js +59 -53
  48. package/build/src/tools/network.js +5 -4
  49. package/build/src/tools/pages.js +48 -6
  50. package/build/src/tools/performance.js +7 -4
  51. package/build/src/tools/pwa.js +7 -0
  52. package/build/src/tools/screencast.js +3 -1
  53. package/build/src/tools/screenshot.js +23 -7
  54. package/build/src/tools/script.js +38 -6
  55. package/build/src/tools/slim/tools.js +21 -5
  56. package/build/src/tools/snapshot.js +13 -3
  57. package/build/src/tools/thirdPartyDeveloper.js +3 -1
  58. package/build/src/tools/webmcp.js +2 -0
  59. package/build/src/utils/TaskRunner.js +136 -0
  60. package/build/src/utils/WaitForHelper.js +1 -1
  61. package/build/src/utils/bytes.js +2 -12
  62. package/build/src/utils/check-for-updates.js +1 -1
  63. package/build/src/utils/disclaimers.js +27 -0
  64. package/build/src/utils/keyboard.js +14 -2
  65. package/build/src/utils/logger.js +69 -0
  66. package/build/src/utils/resourceType.js +27 -0
  67. package/build/src/utils/text.js +29 -0
  68. package/build/src/utils/timeout.js +14 -0
  69. package/build/src/utils/url.js +41 -0
  70. package/build/src/version.js +1 -1
  71. package/package.json +5 -4
  72. package/skills/a11y-debugging/SKILL.md +3 -8
@@ -58,13 +58,15 @@ var __disposeResources = (this && this.__disposeResources) || (function (Suppres
58
58
  import { McpResponse } from './McpResponse.js';
59
59
  import { SlimMcpResponse } from './SlimMcpResponse.js';
60
60
  import { ClearcutLogger } from './telemetry/ClearcutLogger.js';
61
- import { zod } from './third_party/index.js';
61
+ import { ProtocolError, ProtocolErrorCode, 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
+ import { isAvailableInMode, isBrowserlessTool, isPageScopedTool, isSlimTool, } from './tools/ToolDefinition.js';
65
+ import { getErrorMessage } from './utils/errorHandling.js';
65
66
  import { logger } from './utils/logger.js';
66
67
  import { fileURLToPath, pathToFileURL } from 'node:url';
67
- import { isLocalhost } from './utils/url.js';
68
+ import { isDeepStrictEqual } from 'node:util';
69
+ import { isLocalBrowserEndpoint } from './utils/url.js';
68
70
  /**
69
71
  * Upper bound on how long a tool call may wait to acquire the browser
70
72
  * (connect/launch and McpContext initialization). A connect attempt on a
@@ -87,63 +89,64 @@ function buildDisabledMessage(toolName, flag, categoryLabel) {
87
89
  : `requires ${flag.startsWith('--experimental') ? 'experimental feature' : 'flag'} ${flag} and`;
88
90
  return `Tool ${toolName} ${reason} is currently disabled. Enable it by running chrome-devtools start ${flag}=true. For more information check the README.`;
89
91
  }
90
- function getToolStatusInfo(tool, serverArgs) {
92
+ function getDisabledReason(tool, serverArgs) {
91
93
  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
- };
94
+ return isSlimTool(tool)
95
+ ? `Tool ${tool.name} is only available with --slim.`
96
+ : `Tool ${tool.name} is not available with --slim.`;
99
97
  }
100
98
  const category = tool.annotations.category;
101
99
  if (category) {
102
100
  const flag = categoryToFlagName(category);
103
101
  if (!serverArgs[flag]) {
104
- return {
105
- disabled: true,
106
- reason: buildDisabledMessage(tool.name, `--${flag}`, labels[category]),
107
- };
102
+ return buildDisabledMessage(tool.name, `--${flag}`, labels[category]);
108
103
  }
109
104
  }
110
105
  for (const condition of tool.annotations.conditions || []) {
111
106
  if (!serverArgs[condition]) {
112
- return {
113
- disabled: true,
114
- reason: buildDisabledMessage(tool.name, `--${condition}`),
115
- };
107
+ return buildDisabledMessage(tool.name, `--${condition}`);
116
108
  }
117
109
  }
118
- return { disabled: false };
110
+ return undefined;
119
111
  }
120
- function isPageScopedTool(tool) {
121
- return 'pageScoped' in tool && tool.pageScoped === true;
122
- }
123
- async function validateAndResolvePathOrUrl(filePathOrUrl, context) {
112
+ async function validateAndResolvePathOrUrl(filePathOrUrl, context, allowUrl) {
124
113
  if (filePathOrUrl.trim().length === 0) {
125
114
  return undefined;
126
115
  }
116
+ let url;
127
117
  try {
128
- const url = new URL(filePathOrUrl);
118
+ url = new URL(filePathOrUrl);
119
+ }
120
+ catch {
121
+ // Not a URL; fall through and validate it as a regular file path.
122
+ }
123
+ if (url) {
129
124
  if (url.protocol === 'file:') {
130
125
  return pathToFileURL(await context.validatePath(fileURLToPath(url))).href;
131
126
  }
132
127
  if (['http:', 'https:', 'ws:', 'wss:'].includes(url.protocol)) {
133
- return filePathOrUrl;
128
+ // Only pass a remote URL through unchanged for parameters whose sink
129
+ // actually fetches the URL or hands it to the browser (allowUrl). For a
130
+ // filesystem-path parameter, a value that merely looks like an http/ws
131
+ // URL must still be rejected outright: `new URL()` accepts
132
+ // `http://x/../../etc/passwd`, and the downstream filesystem API (e.g.
133
+ // Puppeteer's uploadFile) path.resolve()s that non-absolute string into
134
+ // an absolute host path, which would bypass validatePath (workspace
135
+ // roots and the temp-dir fallback) if it fell through to it unchanged.
136
+ if (allowUrl) {
137
+ return filePathOrUrl;
138
+ }
139
+ throw new Error('This parameter expects a file path, not a URL.');
134
140
  }
135
141
  }
136
- catch {
137
- // Suppress parsing errors for regular file paths.
138
- }
139
142
  return await context.validatePath(filePathOrUrl);
140
143
  }
141
- function isLocalBrowser(context) {
142
- if (context.browser.process()) {
144
+ function isLocalBrowser(browser) {
145
+ if (browser.process()) {
143
146
  return true;
144
147
  }
145
- const wsEndpoint = context.browser.wsEndpoint();
146
- if (wsEndpoint && isLocalhost(wsEndpoint)) {
148
+ const wsEndpoint = browser.wsEndpoint();
149
+ if (wsEndpoint && isLocalBrowserEndpoint(wsEndpoint)) {
147
150
  return true;
148
151
  }
149
152
  return false;
@@ -160,19 +163,23 @@ function shouldValidateFile(option, isLocal) {
160
163
  }
161
164
  return false;
162
165
  }
163
- async function validateToolFiles(tool, params, context) {
164
- const isLocal = isLocalBrowser(context);
166
+ /**
167
+ * `isLocal` tells whether files are accessed on the machine the server runs on,
168
+ * which is always the case for browserless tools.
169
+ */
170
+ async function validateToolFiles(tool, params, context, isLocal) {
165
171
  for (const [key, option] of Object.entries(tool.verifyFilesSchema)) {
166
172
  if (shouldValidateFile(option, isLocal)) {
173
+ const allowUrl = option !== true && option.allowUrl === true;
167
174
  const val = params[key];
168
175
  if (typeof val === 'string') {
169
- params[key] = await validateAndResolvePathOrUrl(val, context);
176
+ params[key] = await validateAndResolvePathOrUrl(val, context, allowUrl);
170
177
  }
171
178
  else if (Array.isArray(val)) {
172
179
  const updated = [];
173
180
  for (const item of val) {
174
181
  if (typeof item === 'string') {
175
- const resolved = await validateAndResolvePathOrUrl(item, context);
182
+ const resolved = await validateAndResolvePathOrUrl(item, context, allowUrl);
176
183
  if (resolved !== undefined) {
177
184
  updated.push(resolved);
178
185
  }
@@ -186,28 +193,89 @@ async function validateToolFiles(tool, params, context) {
186
193
  }
187
194
  }
188
195
  }
196
+ function toInputJsonSchema(schema) {
197
+ return zod.toJSONSchema(schema, { io: 'input', unrepresentable: 'any' });
198
+ }
199
+ function formatValidationError(toolName, error) {
200
+ const details = error.issues
201
+ .map(issue => `${issue.path.length > 0 ? `${issue.path.join('.')}: ` : ''}${issue.message}`)
202
+ .join(', ');
203
+ return `Input validation error: Invalid arguments for tool ${toolName}: ${details}`;
204
+ }
205
+ function errorResult(text) {
206
+ return {
207
+ content: [{ type: 'text', text }],
208
+ isError: true,
209
+ };
210
+ }
211
+ /**
212
+ * The page id a page tool call targets, or `undefined` when the call targets
213
+ * the selected page. `args` can be the raw or the parsed arguments.
214
+ */
215
+ function routedPageId(tool, serverArgs, args) {
216
+ if (!serverArgs.pageIdRouting || isSlimTool(tool)) {
217
+ return undefined;
218
+ }
219
+ const { pageId } = args;
220
+ return typeof pageId === 'number' && Number.isInteger(pageId)
221
+ ? pageId
222
+ : undefined;
223
+ }
189
224
  export class ToolHandler {
190
- tool;
191
- serverArgs;
192
225
  getContext;
193
- toolMutex;
194
226
  abandonPendingBrowserAttemptOnTimeout;
195
- inputSchema;
196
- registeredInputSchema;
197
- disabled;
198
- disabledReason;
199
- constructor(tool, serverArgs, getContext, toolMutex, abandonPendingBrowserAttemptOnTimeout) {
200
- this.tool = tool;
201
- this.serverArgs = serverArgs;
227
+ #tool;
228
+ #config;
229
+ #registeredInputSchema;
230
+ #disabled = false;
231
+ #disabledReason;
232
+ constructor(tool, config, getContext, abandonPendingBrowserAttemptOnTimeout) {
202
233
  this.getContext = getContext;
203
- this.toolMutex = toolMutex;
204
234
  this.abandonPendingBrowserAttemptOnTimeout = abandonPendingBrowserAttemptOnTimeout;
205
- const { disabled, reason, unavailableInMode } = getToolStatusInfo(tool, serverArgs);
206
- this.disabledReason = reason;
207
- this.disabled =
208
- disabled && (Boolean(unavailableInMode) || !serverArgs.viaCli);
209
- this.inputSchema = tool.schema;
210
- this.registeredInputSchema = zod.object(this.inputSchema).strict();
235
+ this.#tool = tool;
236
+ this.#config = config;
237
+ this.#registeredInputSchema = zod.object(tool.schema).strict();
238
+ this.#updateStatus(tool);
239
+ }
240
+ get registeredInputSchema() {
241
+ return this.#registeredInputSchema;
242
+ }
243
+ /**
244
+ * Whether the tool is hidden from the client.
245
+ */
246
+ get disabled() {
247
+ return this.#disabled;
248
+ }
249
+ #updateStatus(tool) {
250
+ const serverArgs = this.#config.resolved;
251
+ this.#disabledReason = getDisabledReason(tool, serverArgs);
252
+ this.#disabled =
253
+ Boolean(this.#disabledReason) &&
254
+ (!isAvailableInMode(tool, serverArgs) || !serverArgs.viaCli);
255
+ }
256
+ /**
257
+ * Replaces the tool definition and re-evaluates its status against the
258
+ * current server config. Callers must pause the task runner, so calls that
259
+ * are already waiting run with the new state. Returns true if the tool
260
+ * listing visible to the client changed.
261
+ */
262
+ update(tool) {
263
+ const previousTool = this.#tool;
264
+ const previousDisabled = this.#disabled;
265
+ const previousInputSchema = this.#registeredInputSchema;
266
+ const nextInputSchema = zod.object(tool.schema).strict();
267
+ this.#tool = tool;
268
+ this.#registeredInputSchema = nextInputSchema;
269
+ this.#updateStatus(tool);
270
+ if (previousDisabled !== this.#disabled) {
271
+ return true;
272
+ }
273
+ if (this.#disabled) {
274
+ return false;
275
+ }
276
+ return (previousTool.description !== tool.description ||
277
+ !isDeepStrictEqual(previousTool.annotations, tool.annotations) ||
278
+ !isDeepStrictEqual(toInputJsonSchema(previousInputSchema), toInputJsonSchema(nextInputSchema)));
211
279
  }
212
280
  /**
213
281
  * Races a promise against TOOL_CALL_TIMEOUT_MS, calling onTimeout() if the
@@ -216,7 +284,7 @@ export class ToolHandler {
216
284
  * it cannot block subsequent tool calls.
217
285
  */
218
286
  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.`);
287
+ 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
288
  let timer;
221
289
  const timeout = new Promise((_, reject) => {
222
290
  timer = setTimeout(() => reject(timeoutError), TOOL_CALL_TIMEOUT_MS);
@@ -235,79 +303,130 @@ export class ToolHandler {
235
303
  clearTimeout(timer);
236
304
  }
237
305
  }
238
- handle = async (params) => {
306
+ #dataFormat(serverArgs) {
307
+ // --experimentalDataFormat takes precedence over the legacy
308
+ // --experimentalToonFormat.
309
+ return (serverArgs.experimentalDataFormat ??
310
+ (serverArgs.experimentalToonFormat ? 'toon' : 'default'));
311
+ }
312
+ /**
313
+ * Browserless tools never establish a browser connection, so they also never
314
+ * wait for one under TOOL_CALL_TIMEOUT_MS.
315
+ */
316
+ async #runBrowserlessTool(tool, params, response, context) {
317
+ try {
318
+ await validateToolFiles(tool, params, context, true);
319
+ await tool.handler({ params }, response, context);
320
+ }
321
+ catch (err) {
322
+ response.setError(err);
323
+ }
324
+ return await response.handle(context, this.#dataFormat(this.#config.resolved));
325
+ }
326
+ async #runBrowserTool(tool, params, response, context, onTelemetryData) {
327
+ // ensureBrowser() has no cancellation mechanism, so this timeout only
328
+ // stops us from waiting — the attempt itself keeps running abandoned.
329
+ // abandonPendingBrowserAttemptOnTimeout() tells BrowserManager to
330
+ // discard that attempt if it succeeds later instead of handing it to a
331
+ // subsequent caller — see BrowserManager#abandonPendingAttempt()'s doc
332
+ // comment for the full mechanism.
333
+ const browser = await this.#raceWithTimeout(context.ensureBrowser(), () => this.abandonPendingBrowserAttemptOnTimeout());
334
+ logger?.(`${tool.name} browser: resolved`);
335
+ if (context.consumeReconnectNotice()) {
336
+ response.setReconnectNotice();
337
+ }
338
+ let page;
339
+ try {
340
+ await validateToolFiles(tool, params, context, isLocalBrowser(browser));
341
+ if (isPageScopedTool(tool)) {
342
+ const pageId = routedPageId(tool, this.#config.resolved, params);
343
+ page =
344
+ pageId !== undefined
345
+ ? context.getPageById(pageId)
346
+ : context.getSelectedMcpPage();
347
+ await page?.init({ emulateFocus: true });
348
+ response.setPage(page);
349
+ if (tool.blockedByDialog) {
350
+ page.throwIfDialogOpen();
351
+ }
352
+ await tool.handler({
353
+ params,
354
+ page,
355
+ }, response, context);
356
+ }
357
+ else {
358
+ await tool.handler({
359
+ params,
360
+ }, response, context);
361
+ }
362
+ }
363
+ catch (err) {
364
+ response.setError(err);
365
+ }
366
+ onTelemetryData(await context.getDevToolsData(page), context.getSelectedMcpPageUrl(page));
367
+ return await response.handle(context, this.#dataFormat(this.#config.resolved));
368
+ }
369
+ /**
370
+ * The queue the call runs on. `'none'` tools run outside the runner.
371
+ * `'page'` tools run on the queue of the page named by `rawArgs.pageId`
372
+ * when page id routing applies; every other call runs on the context
373
+ * queue.
374
+ */
375
+ #queueFor(context, rawArgs) {
376
+ const tool = this.#tool;
377
+ switch (tool.concurrency) {
378
+ case 'none':
379
+ return undefined;
380
+ case 'page': {
381
+ const pageId = routedPageId(tool, this.#config.resolved, rawArgs);
382
+ return pageId !== undefined
383
+ ? context.pageTaskQueue(pageId)
384
+ : context.taskQueue;
385
+ }
386
+ default:
387
+ return context.taskQueue;
388
+ }
389
+ }
390
+ handle = async (rawArgs = {}, options) => {
239
391
  const env_1 = { stack: [], error: void 0, hasError: false };
240
392
  try {
241
- const guard = __addDisposableResource(env_1, await this.toolMutex.acquire(), false);
242
- if (this.disabledReason) {
243
- return {
244
- content: [
245
- {
246
- type: 'text',
247
- text: this.disabledReason,
248
- },
249
- ],
250
- isError: true,
251
- };
393
+ const context = await this.getContext();
394
+ let queueGuard;
395
+ try {
396
+ queueGuard = await this.#queueFor(context, rawArgs)?.scheduleTask();
397
+ }
398
+ catch (err) {
399
+ // The queue was disposed while the call waited, e.g. the page closed.
400
+ return errorResult(getErrorMessage(err));
252
401
  }
402
+ const guard = __addDisposableResource(env_1, queueGuard, false);
403
+ if (options?.viaMcp && this.#disabled) {
404
+ throw new ProtocolError(ProtocolErrorCode.InvalidParams, `Tool ${this.#tool.name} disabled`);
405
+ }
406
+ if (this.#disabledReason) {
407
+ return errorResult(this.#disabledReason);
408
+ }
409
+ const tool = this.#tool;
410
+ const parseResult = this.#registeredInputSchema.safeParse(rawArgs);
411
+ if (!parseResult.success) {
412
+ return errorResult(formatValidationError(tool.name, parseResult.error));
413
+ }
414
+ const params = parseResult.data;
253
415
  const startTime = Date.now();
254
416
  let success = false;
255
417
  let devToolsData;
256
418
  let pageUrl;
257
419
  try {
258
- logger?.(`${this.tool.name} request: ${JSON.stringify(params, null, ' ')}`);
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());
266
- logger?.(`${this.tool.name} context: resolved`);
267
- const response = this.serverArgs.slim
268
- ? new SlimMcpResponse(this.serverArgs)
269
- : new McpResponse(this.serverArgs);
270
- response.setRedactNetworkHeaders(this.serverArgs.redactNetworkHeaders);
271
- if (context.consumeReconnectNotice()) {
272
- response.setReconnectNotice();
273
- }
274
- let page;
275
- try {
276
- await validateToolFiles(this.tool, params, context);
277
- if (isPageScopedTool(this.tool)) {
278
- const pageId = typeof params.pageId === 'number' ? params.pageId : undefined;
279
- page =
280
- this.serverArgs.pageIdRouting &&
281
- pageId !== undefined &&
282
- !isSlimTool(this.tool)
283
- ? context.getPageById(pageId)
284
- : context.getSelectedMcpPage();
285
- await page?.init();
286
- response.setPage(page);
287
- if (this.tool.blockedByDialog) {
288
- page.throwIfDialogOpen();
289
- }
290
- await this.tool.handler({
291
- params,
292
- page,
293
- }, response, context);
294
- }
295
- else {
296
- await this.tool.handler({
297
- params,
298
- }, response, context);
299
- }
300
- }
301
- catch (err) {
302
- response.setError(err);
303
- }
304
- devToolsData = await context.getDevToolsData(page);
305
- pageUrl = context.getSelectedMcpPageUrl(page);
306
- // --experimentalDataFormat takes precedence over the legacy
307
- // --experimentalToonFormat.
308
- const dataFormat = this.serverArgs.experimentalDataFormat ??
309
- (this.serverArgs.experimentalToonFormat ? 'toon' : 'default');
310
- const { content, structuredContent } = await response.handle(context, dataFormat);
420
+ logger?.(`${tool.name} request: ${JSON.stringify(params, null, ' ')}`);
421
+ const response = isSlimTool(tool)
422
+ ? new SlimMcpResponse(this.#config)
423
+ : new McpResponse(this.#config);
424
+ const { content, structuredContent } = isBrowserlessTool(tool)
425
+ ? await this.#runBrowserlessTool(tool, params, response, context)
426
+ : await this.#runBrowserTool(tool, params, response, context, (data, url) => {
427
+ devToolsData = data;
428
+ pageUrl = url;
429
+ });
311
430
  const result = {
312
431
  content,
313
432
  };
@@ -315,32 +434,34 @@ export class ToolHandler {
315
434
  result.isError = true;
316
435
  }
317
436
  success = true;
318
- if (this.serverArgs.experimentalStructuredContent) {
437
+ if (this.#config.resolved.experimentalStructuredContent) {
319
438
  result.structuredContent = structuredContent;
320
439
  }
321
440
  return result;
322
441
  }
323
442
  catch (err) {
324
- logger?.(`${this.tool.name} error:`, err, err?.stack);
443
+ logger?.(`${tool.name} error:`, err, err?.stack);
325
444
  let errorText = err && 'message' in err ? err.message : String(err);
326
- if ('cause' in err && err.cause) {
327
- errorText += `\nCause: ${err.cause.message}`;
445
+ let cause = err && typeof err === 'object' && 'cause' in err
446
+ ? err.cause
447
+ : undefined;
448
+ const seenCauses = new Set([err]);
449
+ while (cause &&
450
+ typeof cause === 'object' &&
451
+ !seenCauses.has(cause) &&
452
+ 'message' in cause &&
453
+ typeof cause.message === 'string') {
454
+ seenCauses.add(cause);
455
+ errorText += `\nCause: ${cause.message}`;
456
+ cause = 'cause' in cause ? cause.cause : undefined;
328
457
  }
329
- return {
330
- content: [
331
- {
332
- type: 'text',
333
- text: errorText,
334
- },
335
- ],
336
- isError: true,
337
- };
458
+ return errorResult(errorText);
338
459
  }
339
460
  finally {
340
461
  void ClearcutLogger.get()?.logToolInvocation({
341
- toolName: this.tool.name,
462
+ toolName: tool.name,
342
463
  params,
343
- schema: this.inputSchema,
464
+ schema: tool.schema,
344
465
  success,
345
466
  latencyMs: Date.now() - startTime,
346
467
  devToolsData,
@@ -6,11 +6,12 @@
6
6
  import '../utils/polyfill.js';
7
7
  import process from 'node:process';
8
8
  import { BrowserManager } from '../BrowserManager.js';
9
- import { McpServer, logDisclaimers } from '../index.js';
9
+ import { McpServer } from '../index.js';
10
10
  import { ClearcutLogger } from '../telemetry/ClearcutLogger.js';
11
11
  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
+ import { logDisclaimers } from '../utils/disclaimers.js';
14
15
  import { logger, saveLogsToFile } from '../utils/logger.js';
15
16
  import { setupUnhandledRejectionHandler } from '../utils/errorHandling.js';
16
17
  import { VERSION } from '../version.js';
@@ -18,16 +19,17 @@ import { mcpOptions } from '../config/mcp-options.js';
18
19
  import { ConfigParser } from '../config/ConfigParser.js';
19
20
  await checkForUpdates('Run `npm install chrome-devtools-mcp@latest` to update.');
20
21
  const configParser = new ConfigParser(VERSION);
21
- export const args = configParser.parse();
22
+ const serverConfig = configParser.parseConfig();
23
+ const args = serverConfig.resolved;
22
24
  const logFile = args.logFile ? saveLogsToFile(args.logFile) : undefined;
23
25
  setupUnhandledRejectionHandler(() => {
24
26
  process.exit(1);
25
27
  });
26
28
  logger?.(`Starting Chrome DevTools MCP Server v${VERSION}`);
27
- const browserManager = new BrowserManager(args, {
29
+ const browserManager = new BrowserManager(serverConfig, {
28
30
  logFile,
29
31
  });
30
- const serverPromise = McpServer.from(args, {
32
+ const serverPromise = McpServer.from(serverConfig, {
31
33
  browserManager,
32
34
  });
33
35
  // Shutdown on stdin EOF (stdio MCP convention — the client closes the
@@ -7,13 +7,13 @@
7
7
  import process from 'node:process';
8
8
  import { startDaemon, stopDaemon, sendCommand, handleResponse, verifyDaemonVersion, } from '../daemon/client.js';
9
9
  import { isDaemonRunning, serializeArgs, assertValidSessionId, } from '../daemon/utils.js';
10
- import { logDisclaimers } from '../index.js';
11
- import { hideBin, yargs } from '../third_party/index.js';
10
+ import { logDisclaimers } from '../utils/disclaimers.js';
11
+ import { hideBin, yargs } from '../third_party/cli.js';
12
12
  import { checkForUpdates } from '../utils/check-for-updates.js';
13
13
  import { VERSION } from '../version.js';
14
14
  import { buildCommand, getCommandArgSpec, shieldLiteralArgs, } from '../config/cli-commands.js';
15
15
  import { commands } from '../config/cli-options.js';
16
- import { mcpOptions, getCliOptions } from '../config/mcp-options.js';
16
+ import { getCliOptions } from '../config/mcp-options.js';
17
17
  import { ConfigParser } from '../config/ConfigParser.js';
18
18
  process.title = 'chrome-devtools';
19
19
  await checkForUpdates('Run `npm install -g chrome-devtools-mcp@latest` and `chrome-devtools start` to update and restart the daemon.');
@@ -175,7 +175,7 @@ for (const [commandName, commandDef] of Object.entries(commands)) {
175
175
  ? verifyDaemonVersion(sessionId, VERSION)
176
176
  : Promise.resolve(undefined);
177
177
  if (!daemonRunning) {
178
- await start(serializeArgs(mcpOptions, argv), sessionId);
178
+ await start([], sessionId);
179
179
  }
180
180
  const commandArgs = {};
181
181
  for (const argName of Object.keys(args)) {
@@ -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
  }
@@ -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