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
@@ -6,17 +6,19 @@
6
6
  import { CommentFormatter, } from './formatters/CommentFormatter.js';
7
7
  import { ConsoleFormatter } from './formatters/ConsoleFormatter.js';
8
8
  import { CssFormatter, resolveContainerQueries, } from './formatters/CssFormatter.js';
9
- import { HeapSnapshotFormatter, isEdgeLike, isNodeLike, } from './formatters/HeapSnapshotFormatter.js';
9
+ import { collectRankedContexts, formatName, HeapSnapshotFormatter, isEdgeLike, isNodeLike, } from './formatters/HeapSnapshotFormatter.js';
10
10
  import { IssueFormatter } from './formatters/IssueFormatter.js';
11
11
  import { NetworkFormatter } from './formatters/NetworkFormatter.js';
12
12
  import { SnapshotFormatter } from './formatters/SnapshotFormatter.js';
13
13
  import { UncaughtError } from './collectors/PageCollector.js';
14
14
  import { TextSnapshot } from './TextSnapshot.js';
15
- import { DevTools, getToonEncode, getGcfEncode } from './third_party/index.js';
15
+ import { DevTools, getToonEncode, getGcfEncode, } from './third_party/index.js';
16
16
  import { handleDialog, listPages } from './tools/pages.js';
17
17
  import { getInsightOutput, getTraceSummary, } from './processors/PerformanceTrace.js';
18
18
  import { stableIdSymbol } from './utils/id.js';
19
19
  import { paginate } from './utils/pagination.js';
20
+ import { getFilterableResourceType } from './utils/resourceType.js';
21
+ import { truncateText } from './utils/text.js';
20
22
  const { formatBytesToKb } = DevTools.I18n.ByteUtilities;
21
23
  export class McpResponse {
22
24
  #includePages = false;
@@ -40,9 +42,8 @@ export class McpResponse {
40
42
  #listWebMcpTools;
41
43
  #devToolsData;
42
44
  #tabId;
43
- #args;
45
+ #config;
44
46
  #page;
45
- #redactNetworkHeaders = true;
46
47
  #error;
47
48
  #attachedWaitForResult;
48
49
  #reconnectNotice = false;
@@ -50,15 +51,12 @@ export class McpResponse {
50
51
  get #deviceScope() {
51
52
  return this.#page?.viewport?.isMobile ? 'PHONE' : 'DESKTOP';
52
53
  }
53
- constructor(args) {
54
- this.#args = args;
54
+ constructor(config) {
55
+ this.#config = config;
55
56
  }
56
57
  setPage(page) {
57
58
  this.#page = page;
58
59
  }
59
- setRedactNetworkHeaders(value) {
60
- this.#redactNetworkHeaders = value;
61
- }
62
60
  /**
63
61
  * Surfaces a one-time note that the browser reconnected and page ids changed.
64
62
  * Set by the tool handler when the context reports a pending reconnect notice.
@@ -74,11 +72,14 @@ export class McpResponse {
74
72
  }
75
73
  setIncludePages(value) {
76
74
  this.#includePages = value;
77
- if (this.#args.categoryExtensions) {
75
+ if (this.#config.resolved.categoryExtensions) {
78
76
  this.#includeExtensionServiceWorkers = value;
79
77
  this.#includeExtensionPages = value;
80
78
  }
81
79
  }
80
+ setIncludeExtensionServiceWorkers(value) {
81
+ this.#includeExtensionServiceWorkers = value;
82
+ }
82
83
  includeSnapshot(params) {
83
84
  this.#snapshotParams = params ?? {
84
85
  verbose: false,
@@ -100,7 +101,7 @@ export class McpResponse {
100
101
  }
101
102
  this.#networkRequestsOptions = {
102
103
  include: value,
103
- pagination: options?.pageSize !== undefined || options?.pageIdx !== undefined
104
+ pagination: options?.pageSize !== undefined
104
105
  ? {
105
106
  pageSize: options.pageSize,
106
107
  pageIdx: options.pageIdx,
@@ -118,7 +119,7 @@ export class McpResponse {
118
119
  }
119
120
  this.#consoleDataOptions = {
120
121
  include: value,
121
- pagination: options?.pageSize !== undefined || options?.pageIdx !== undefined
122
+ pagination: options?.pageSize !== undefined
122
123
  ? {
123
124
  pageSize: options.pageSize,
124
125
  pageIdx: options.pageIdx,
@@ -210,9 +211,10 @@ export class McpResponse {
210
211
  include: true,
211
212
  aggregateData,
212
213
  pagination: options,
214
+ formatOptions: options,
213
215
  };
214
216
  }
215
- setHeapSnapshotStats(stats, staticData, nativeContextSizes, retainedByContextSummary) {
217
+ setHeapSnapshotStats(stats, staticData, nativeContextSizes, retainedByContextSummary, options) {
216
218
  this.#heapSnapshotOptions = {
217
219
  ...this.#heapSnapshotOptions,
218
220
  include: true,
@@ -220,6 +222,7 @@ export class McpResponse {
220
222
  staticData,
221
223
  nativeContextSizes,
222
224
  retainedByContextSummary,
225
+ formatOptions: options,
223
226
  };
224
227
  }
225
228
  setHeapSnapshotNodes(nodes, options) {
@@ -228,6 +231,7 @@ export class McpResponse {
228
231
  include: true,
229
232
  nodes,
230
233
  pagination: options,
234
+ formatOptions: options,
231
235
  };
232
236
  }
233
237
  setHeapSnapshotDuplicateStrings(duplicateStrings, options) {
@@ -236,41 +240,58 @@ export class McpResponse {
236
240
  include: true,
237
241
  duplicateStrings,
238
242
  pagination: options,
243
+ formatOptions: options,
239
244
  };
240
245
  }
241
- setHeapSnapshotRetainingPaths(retainingPaths) {
246
+ setHeapSnapshotRetainingPaths(retainingPaths, options) {
242
247
  this.#heapSnapshotOptions = {
243
248
  ...this.#heapSnapshotOptions,
244
249
  include: true,
245
250
  retainingPaths,
251
+ formatOptions: options,
246
252
  };
247
253
  }
248
- setHeapSnapshotDominators(dominators) {
254
+ setHeapSnapshotDominators(dominators, options) {
249
255
  this.#heapSnapshotOptions = {
250
256
  ...this.#heapSnapshotOptions,
251
257
  include: true,
252
258
  dominators,
259
+ formatOptions: options,
253
260
  };
254
261
  }
255
- setHeapSnapshotClassDiffs(classDiffs) {
262
+ setHeapSnapshotClassDiffs(diff, options) {
256
263
  this.#heapSnapshotOptions = {
257
264
  ...this.#heapSnapshotOptions,
258
265
  include: true,
259
- classDiffs,
266
+ diff,
267
+ pagination: options,
268
+ formatOptions: options,
260
269
  };
261
270
  }
262
- setHeapSnapshotDetailedClassDiff(detailedClassDiff) {
271
+ setHeapSnapshotDetailedClassDiff(detailedClassDiff, options) {
263
272
  this.#heapSnapshotOptions = {
264
273
  ...this.#heapSnapshotOptions,
265
274
  include: true,
266
275
  detailedClassDiff,
276
+ pagination: options,
277
+ formatOptions: options,
267
278
  };
268
279
  }
269
- setHeapSnapshotObjectDetails(objectInfo) {
280
+ setHeapSnapshotObjectDetails(objectInfo, options) {
270
281
  this.#heapSnapshotOptions = {
271
282
  ...this.#heapSnapshotOptions,
272
283
  include: true,
273
284
  objectInfo,
285
+ formatOptions: options,
286
+ };
287
+ }
288
+ setHeapSnapshotContextAnalysis(contextAnalysis, options) {
289
+ this.#heapSnapshotOptions = {
290
+ ...this.#heapSnapshotOptions,
291
+ include: true,
292
+ contextAnalysis,
293
+ contextAnalysisOptions: options,
294
+ formatOptions: options,
274
295
  };
275
296
  }
276
297
  attachImage(value) {
@@ -289,9 +310,6 @@ export class McpResponse {
289
310
  return this.#listWebMcpTools;
290
311
  }
291
312
  async #handleSnapshot(context) {
292
- if (this.#includePages) {
293
- await context.createPagesSnapshot();
294
- }
295
313
  if (!this.#snapshotParams) {
296
314
  return undefined;
297
315
  }
@@ -307,9 +325,7 @@ export class McpResponse {
307
325
  const result = await context.saveFile(new TextEncoder().encode(formatter.toString()), this.#snapshotParams.filePath, '.txt');
308
326
  return result.filename;
309
327
  }
310
- else {
311
- return formatter;
312
- }
328
+ return formatter;
313
329
  }
314
330
  async #handleAttachedNetworkRequest(context) {
315
331
  if (!this.#attachedNetworkRequestId) {
@@ -326,7 +342,7 @@ export class McpResponse {
326
342
  requestFilePath: this.#attachedNetworkRequestOptions?.requestFilePath,
327
343
  responseFilePath: this.#attachedNetworkRequestOptions?.responseFilePath,
328
344
  saveFile: (data, filename, extension) => context.saveFile(data, filename, extension),
329
- redactNetworkHeaders: this.#redactNetworkHeaders,
345
+ redactNetworkHeaders: this.#config.resolved.redactNetworkHeaders,
330
346
  });
331
347
  }
332
348
  async #handleAttachedConsoleMessage() {
@@ -346,7 +362,7 @@ export class McpResponse {
346
362
  devTools: this.#page.devtoolsUniverse,
347
363
  });
348
364
  }
349
- else if (message instanceof DevTools.AggregatedIssue) {
365
+ if (message instanceof DevTools.AggregatedIssue) {
350
366
  const formatter = new IssueFormatter(message, {
351
367
  id: consoleMessageStableId,
352
368
  requestIdResolver: this.#page.resolveCdpRequestId.bind(this.#page),
@@ -357,20 +373,18 @@ export class McpResponse {
357
373
  }
358
374
  return formatter;
359
375
  }
360
- else {
361
- return undefined;
362
- }
376
+ return undefined;
363
377
  }
364
- async #handleThirdPartyDevelopeTools() {
365
- if (this.#args.categoryExperimentalThirdParty &&
378
+ async #handleThirdPartyDeveloperTools() {
379
+ if (this.#config.resolved.categoryExperimentalThirdParty &&
366
380
  this.#listThirdPartyDeveloperTools &&
367
381
  this.#page) {
368
- return await this.#page.getToolGroups();
382
+ return await this.#page.discoverThirdPartyDeveloperTools();
369
383
  }
370
384
  return undefined;
371
385
  }
372
386
  async #handleWebMCP() {
373
- if (this.#args.categoryExperimentalWebmcp &&
387
+ if (this.#config.resolved.categoryExperimentalWebmcp &&
374
388
  this.#listWebMcpTools &&
375
389
  this.#page) {
376
390
  return this.#page.getWebMcpTools();
@@ -440,8 +454,7 @@ export class McpResponse {
440
454
  if (this.#networkRequestsOptions.resourceTypes?.length) {
441
455
  const normalizedTypes = new Set(this.#networkRequestsOptions.resourceTypes);
442
456
  requests = requests.filter(request => {
443
- const type = request.resourceType();
444
- return normalizedTypes.has(type);
457
+ return normalizedTypes.has(getFilterableResourceType(request));
445
458
  });
446
459
  }
447
460
  return await Promise.all(requests.map(request => NetworkFormatter.from(request, {
@@ -450,7 +463,7 @@ export class McpResponse {
450
463
  this.#networkRequestsOptions?.networkRequestIdInDevToolsUI,
451
464
  fetchData: false,
452
465
  saveFile: (data, filename, extension) => context.saveFile(data, filename, extension),
453
- redactNetworkHeaders: this.#redactNetworkHeaders,
466
+ redactNetworkHeaders: this.#config.resolved.redactNetworkHeaders,
454
467
  })));
455
468
  }
456
469
  async #handleComments() {
@@ -459,7 +472,8 @@ export class McpResponse {
459
472
  return undefined;
460
473
  }
461
474
  const page = this.#page;
462
- return await CommentFormatter.from(comments, {
475
+ const initialSnapshot = page?.textSnapshot;
476
+ const formatter = await CommentFormatter.from(comments, {
463
477
  resolveBackendNodeId: page
464
478
  ? (id) => page.resolveBackendNodeId(id)
465
479
  : undefined,
@@ -467,26 +481,44 @@ export class McpResponse {
467
481
  ? (id) => page.resolveCdpRequestId(id)
468
482
  : undefined,
469
483
  });
484
+ let commentsSnapshotRegenerated;
485
+ if (page?.textSnapshot && page.textSnapshot !== initialSnapshot) {
486
+ commentsSnapshotRegenerated = page.textSnapshot.verbose
487
+ ? 'verbose'
488
+ : 'standard';
489
+ }
490
+ return { formatter, commentsSnapshotRegenerated };
470
491
  }
471
492
  async handle(context, dataFormat = 'default') {
472
- const [snapshot, detailedNetworkRequest, detailedConsoleMessage, thirdPartyDeveloperTools, webmcpTools, consoleMessages, networkRequests, comments,] = await Promise.all([
493
+ if (this.#includePages || this.#attachedWaitForResult?.openedPages) {
494
+ await context.createPagesSnapshot();
495
+ }
496
+ if (this.#includePages && (!this.#page || this.#page.isClosed())) {
497
+ try {
498
+ this.#page = context.getSelectedMcpPage();
499
+ }
500
+ catch {
501
+ this.#page = undefined;
502
+ }
503
+ }
504
+ const [snapshot, detailedNetworkRequest, detailedConsoleMessage, thirdPartyDeveloperTools, webmcpTools, consoleMessages, networkRequests, commentsResult,] = await Promise.all([
473
505
  this.#handleSnapshot(context),
474
506
  this.#handleAttachedNetworkRequest(context),
475
507
  this.#handleAttachedConsoleMessage(),
476
- this.#handleThirdPartyDevelopeTools(),
508
+ this.#handleThirdPartyDeveloperTools(),
477
509
  this.#handleWebMCP(),
478
510
  this.#handleConsoleList(context),
479
511
  this.#handleNetworkRequestList(context),
480
512
  this.#handleComments(),
481
513
  ]);
482
514
  if (this.#includeExtensionServiceWorkers) {
483
- await context.createExtensionServiceWorkersSnapshot();
515
+ context.createWorkersSnapshot();
484
516
  }
485
517
  let extensions;
486
518
  if (this.#listExtensions) {
487
519
  extensions = await context.listExtensions();
488
520
  }
489
- return this.format(context, {
521
+ return await this.format(context, {
490
522
  detailedConsoleMessage,
491
523
  consoleMessages,
492
524
  snapshot,
@@ -498,7 +530,8 @@ export class McpResponse {
498
530
  lighthouseResult: this.#attachedLighthouseResult,
499
531
  thirdPartyDeveloperTools,
500
532
  webmcpTools,
501
- comments,
533
+ comments: commentsResult?.formatter,
534
+ commentsSnapshotRegenerated: commentsResult?.commentsSnapshotRegenerated,
502
535
  errorMessage: this.#error?.message,
503
536
  }, dataFormat);
504
537
  }
@@ -537,7 +570,7 @@ export class McpResponse {
537
570
  const response = [];
538
571
  if (this.#reconnectNotice) {
539
572
  structuredContent.reconnected = true;
540
- response.push(`Note: the browser was restarted or reconnected since the last call. Page ids have changed. Call ${listPages(this.#args).name} to see open pages.`);
573
+ response.push(`Note: the browser was restarted or reconnected since the last call. Page ids have changed. Call ${listPages(this.#config.resolved).name} to see open pages.`);
541
574
  }
542
575
  if (this.#textResponseLines.length) {
543
576
  structuredContent.message = this.#textResponseLines.join('\n');
@@ -549,10 +582,28 @@ export class McpResponse {
549
582
  structuredContent.navigatedToUrl =
550
583
  this.#attachedWaitForResult.navigatedToUrl;
551
584
  }
585
+ if (this.#attachedWaitForResult.openedPages) {
586
+ const openedPages = this.#attachedWaitForResult.openedPages;
587
+ const openedMcpPages = context
588
+ .getPages()
589
+ .filter(mcpPage => openedPages.has(mcpPage.target));
590
+ if (openedMcpPages.length) {
591
+ const targetInfos = await context.getTargetInfos();
592
+ response.push('## Opened pages');
593
+ const structuredPages = [];
594
+ for (const mcpPage of openedMcpPages) {
595
+ const page = formatPage(mcpPage, context, targetInfos.get(mcpPage.targetId));
596
+ response.push(page.text);
597
+ structuredPages.push(page.structured);
598
+ }
599
+ structuredContent.openedPages = structuredPages;
600
+ }
601
+ }
552
602
  }
553
- const networkConditions = this.#page?.networkConditions;
554
- if (networkConditions) {
555
- const timeout = this.#page.pptrPage.getDefaultNavigationTimeout();
603
+ const page = this.#page;
604
+ const networkConditions = page?.networkConditions;
605
+ if (page && networkConditions) {
606
+ const timeout = page.pptrPage.getDefaultNavigationTimeout();
556
607
  response.push(`Emulating network conditions: ${networkConditions}`);
557
608
  response.push(`Default navigation timeout set to ${timeout} ms`);
558
609
  structuredContent.networkConditions = networkConditions;
@@ -583,6 +634,21 @@ export class McpResponse {
583
634
  response.push(`Emulating color scheme: ${colorScheme}`);
584
635
  structuredContent.colorScheme = colorScheme;
585
636
  }
637
+ const forcedColors = this.#page?.forcedColors;
638
+ if (forcedColors) {
639
+ response.push(`Emulating forced-colors: ${forcedColors}`);
640
+ structuredContent.forcedColors = forcedColors;
641
+ }
642
+ const prefersContrast = this.#page?.prefersContrast;
643
+ if (prefersContrast) {
644
+ response.push(`Emulating prefers-contrast: ${prefersContrast}`);
645
+ structuredContent.prefersContrast = prefersContrast;
646
+ }
647
+ const prefersReducedMotion = this.#page?.prefersReducedMotion;
648
+ if (prefersReducedMotion) {
649
+ response.push(`Emulating prefers-reduced-motion: ${prefersReducedMotion}`);
650
+ structuredContent.prefersReducedMotion = prefersReducedMotion;
651
+ }
586
652
  const dialog = this.#page?.getDialog();
587
653
  if (dialog) {
588
654
  const defaultValueIfNeeded = dialog.type() === 'prompt'
@@ -590,7 +656,7 @@ export class McpResponse {
590
656
  : '';
591
657
  response.push(`# Open dialog
592
658
  ${dialog.type()}: ${dialog.message()}${defaultValueIfNeeded}.
593
- Call ${handleDialog(this.#args).name} to handle it before continuing.`);
659
+ Call ${handleDialog(this.#config.resolved).name} to handle it before continuing.`);
594
660
  structuredContent.dialog = {
595
661
  type: dialog.type(),
596
662
  message: dialog.message(),
@@ -600,7 +666,7 @@ Call ${handleDialog(this.#args).name} to handle it before continuing.`);
600
666
  if (this.#includePages) {
601
667
  const allPages = context.getPages();
602
668
  const { regularPages, extensionPages } = allPages.reduce((acc, mcpPage) => {
603
- if (mcpPage.pptrPage.url().startsWith('chrome-extension://')) {
669
+ if (mcpPage.url().startsWith('chrome-extension://')) {
604
670
  acc.extensionPages.push(mcpPage);
605
671
  }
606
672
  else {
@@ -619,6 +685,10 @@ Call ${handleDialog(this.#args).name} to handle it before continuing.`);
619
685
  }
620
686
  response.push(`Note: the previously selected page ${selectionFallback.wasClosed ? 'was closed' : 'is no longer listed'}.${selectedPageId !== undefined ? ` Page ${selectedPageId} is now selected.` : ''}`);
621
687
  }
688
+ const targetInfos = regularPages.length ||
689
+ (this.#includeExtensionPages && extensionPages.length)
690
+ ? await context.getTargetInfos()
691
+ : new Map();
622
692
  if (regularPages.length) {
623
693
  const parts = [`## Pages`];
624
694
  const structuredPages = [];
@@ -627,12 +697,9 @@ Call ${handleDialog(this.#args).name} to handle it before continuing.`);
627
697
  const contextLabel = isolatedContextName
628
698
  ? ` isolatedContext=${isolatedContextName}`
629
699
  : '';
630
- const title = await fetchPageTitle(mcpPage.pptrPage);
631
- const pageLabel = title
632
- ? `${truncateTitle(title)} (${mcpPage.pptrPage.url()})`
633
- : mcpPage.pptrPage.url();
634
- parts.push(`${mcpPage.id}: ${pageLabel}${context.isPageSelected(mcpPage) ? ' [selected]' : ''}${contextLabel}`);
635
- structuredPages.push(createStructuredPage(mcpPage, context, title));
700
+ const page = formatPage(mcpPage, context, targetInfos.get(mcpPage.targetId));
701
+ parts.push(`${page.text}${context.isPageSelected(mcpPage) ? ' [selected]' : ''}${contextLabel}`);
702
+ structuredPages.push(page.structured);
636
703
  }
637
704
  response.push(...parts);
638
705
  structuredContent.pages = structuredPages;
@@ -646,27 +713,25 @@ Call ${handleDialog(this.#args).name} to handle it before continuing.`);
646
713
  const contextLabel = isolatedContextName
647
714
  ? ` isolatedContext=${isolatedContextName}`
648
715
  : '';
649
- const title = await fetchPageTitle(mcpPage.pptrPage);
650
- const pageLabel = title
651
- ? `${truncateTitle(title)} (${mcpPage.pptrPage.url()})`
652
- : mcpPage.pptrPage.url();
653
- response.push(`${mcpPage.id}: ${pageLabel}${context.isPageSelected(mcpPage) ? ' [selected]' : ''}${contextLabel}`);
654
- structuredExtensionPages.push(createStructuredPage(mcpPage, context, title));
716
+ const page = formatPage(mcpPage, context, targetInfos.get(mcpPage.targetId));
717
+ response.push(`${page.text}${context.isPageSelected(mcpPage) ? ' [selected]' : ''}${contextLabel}`);
718
+ structuredExtensionPages.push(page.structured);
655
719
  }
656
720
  structuredContent.extensionPages = structuredExtensionPages;
657
721
  }
658
722
  }
659
723
  }
660
724
  if (this.#includeExtensionServiceWorkers) {
661
- if (context.getExtensionServiceWorkers().length) {
725
+ const extensionServiceWorkers = context
726
+ .getWorkers()
727
+ .filter(worker => worker.type === 'service_worker');
728
+ if (extensionServiceWorkers.length) {
662
729
  response.push(`## Extension Service Workers`);
663
730
  }
664
- for (const extensionServiceWorker of context.getExtensionServiceWorkers()) {
731
+ for (const extensionServiceWorker of extensionServiceWorkers) {
665
732
  response.push(`${extensionServiceWorker.id}: ${extensionServiceWorker.url}`);
666
733
  }
667
- structuredContent.extensionServiceWorkers = context
668
- .getExtensionServiceWorkers()
669
- .map(extensionServiceWorker => {
734
+ structuredContent.extensionServiceWorkers = extensionServiceWorkers.map(extensionServiceWorker => {
670
735
  return {
671
736
  id: extensionServiceWorker.id,
672
737
  url: extensionServiceWorker.url,
@@ -698,26 +763,70 @@ Call ${handleDialog(this.#args).name} to handle it before continuing.`);
698
763
  const insightOutput = getInsightOutput(data.traceInsight.trace, data.traceInsight.insightSetId, data.traceInsight.insightName, this.#deviceScope);
699
764
  if ('error' in insightOutput) {
700
765
  response.push(insightOutput.error);
766
+ structuredContent.error = insightOutput.error;
701
767
  }
702
768
  else {
703
769
  response.push(insightOutput.output);
770
+ structuredContent.traceInsight = insightOutput.output;
704
771
  }
705
772
  }
706
773
  if (data.lighthouseResult) {
707
774
  structuredContent.lighthouseResult = data.lighthouseResult;
708
- const { summary, reports } = data.lighthouseResult;
709
- response.push('## Lighthouse Audit Results');
775
+ const { summary, failedAudits, reports } = data.lighthouseResult;
776
+ response.push('## Lighthouse audit results');
710
777
  response.push(`Mode: ${summary.mode}`);
711
778
  response.push(`Device: ${summary.device}`);
712
779
  response.push(`URL: ${summary.url}`);
713
- response.push('### Category Scores');
780
+ response.push('### Category scores');
714
781
  for (const score of summary.scores) {
715
- response.push(`- ${score.title}: ${(score.score ?? 0) * 100} (${score.id})`);
782
+ // Lighthouse uses a null score for categories that could not be
783
+ // scored and renders scores as Math.round(score * 100).
784
+ const formattedScore = score.score === null ? 'n/a' : Math.round(score.score * 100);
785
+ response.push(`- ${score.title}: ${formattedScore} (${score.id})`);
716
786
  }
717
- response.push('### Audit Summary');
787
+ response.push('### Audit summary');
718
788
  response.push(`Passed: ${summary.audits.passed}`);
719
789
  response.push(`Failed: ${summary.audits.failed}`);
720
- response.push(`Total Timing: ${summary.timing.total}ms`);
790
+ response.push(`Total timing: ${summary.timing.total}ms`);
791
+ if (failedAudits.length) {
792
+ response.push('### Failed audits');
793
+ for (const audit of failedAudits) {
794
+ const categories = audit.categories.length
795
+ ? ` [${audit.categories.join(', ')}]`
796
+ : '';
797
+ const displayValue = audit.displayValue
798
+ ? ` (${audit.displayValue})`
799
+ : '';
800
+ response.push(`- ${audit.id}${categories}: ${audit.title}${displayValue} (score: ${audit.score})`);
801
+ if (audit.description) {
802
+ response.push(` ${collapseWhitespace(audit.description)}`);
803
+ }
804
+ if (audit.totalNodes) {
805
+ const shown = audit.totalNodes > audit.nodes.length
806
+ ? `, showing ${audit.nodes.length}`
807
+ : '';
808
+ response.push(` Nodes (${audit.totalNodes}${shown}):`);
809
+ }
810
+ for (const node of audit.nodes) {
811
+ // Values are JSON-encoded so that quotes or spaces within them
812
+ // cannot be confused with the `key=value` delimiters.
813
+ const parts = [];
814
+ if (node.selector) {
815
+ parts.push(`selector=${JSON.stringify(node.selector)}`);
816
+ }
817
+ if (node.nodeLabel) {
818
+ parts.push(`label=${JSON.stringify(collapseWhitespace(node.nodeLabel))}`);
819
+ }
820
+ if (node.snippet) {
821
+ parts.push(`snippet=${JSON.stringify(collapseWhitespace(node.snippet))}`);
822
+ }
823
+ response.push(` - ${parts.join(' ')}`);
824
+ if (node.explanation) {
825
+ response.push(` ${collapseWhitespace(node.explanation)}`);
826
+ }
827
+ }
828
+ }
829
+ }
721
830
  response.push('### Reports');
722
831
  for (const report of reports) {
723
832
  response.push(`- ${report}`);
@@ -738,6 +847,7 @@ Call ${handleDialog(this.#args).name} to handle it before continuing.`);
738
847
  }
739
848
  if (this.#heapSnapshotOptions?.include) {
740
849
  response.push('## Heap Snapshot Data');
850
+ const formatOptions = this.#heapSnapshotOptions.formatOptions ?? {};
741
851
  const stats = this.#heapSnapshotOptions.stats;
742
852
  const staticData = this.#heapSnapshotOptions.staticData;
743
853
  if (stats) {
@@ -753,7 +863,7 @@ Call ${handleDialog(this.#args).name} to handle it before continuing.`);
753
863
  const nativeContextSizes = this.#heapSnapshotOptions.nativeContextSizes;
754
864
  if (nativeContextSizes) {
755
865
  response.push('### Native Contexts');
756
- response.push(HeapSnapshotFormatter.formatNativeContextSizes(nativeContextSizes));
866
+ response.push(HeapSnapshotFormatter.formatNativeContextSizes(nativeContextSizes, formatOptions));
757
867
  structuredContent.heapSnapshot = structuredContent.heapSnapshot || {};
758
868
  structuredContent.heapSnapshot.nativeContextSizes = nativeContextSizes;
759
869
  }
@@ -767,8 +877,7 @@ Call ${handleDialog(this.#args).name} to handle it before continuing.`);
767
877
  }
768
878
  const aggregateData = this.#heapSnapshotOptions.aggregateData;
769
879
  if (aggregateData) {
770
- const sortedEntries = HeapSnapshotFormatter.sort(aggregateData.aggregates);
771
- const paginationData = this.#dataWithPagination(sortedEntries, this.#heapSnapshotOptions.pagination);
880
+ const paginationData = this.#dataWithPagination(aggregateData.aggregates, this.#heapSnapshotOptions.pagination);
772
881
  response.push(`Objects: ${aggregateData.objectCount}`);
773
882
  response.push(`Total shallow size: ${formatBytesToKb(aggregateData.totalSelfSize)}`);
774
883
  structuredContent.heapSnapshot = structuredContent.heapSnapshot || {};
@@ -778,12 +887,13 @@ Call ${handleDialog(this.#args).name} to handle it before continuing.`);
778
887
  };
779
888
  structuredContent.pagination = paginationData.pagination;
780
889
  response.push(...paginationData.info);
781
- const paginatedRecord = Object.fromEntries(paginationData.items);
782
- const formatter = new HeapSnapshotFormatter(paginatedRecord);
783
- structuredContent.heapSnapshotData = formatter.toJSON();
890
+ structuredContent.heapSnapshotAggregates = paginationData.items;
784
891
  response.push(compactEncode
785
- ? compactEncode(structuredContent.heapSnapshotData)
786
- : formatter.toString());
892
+ ? compactEncode(paginationData.items.map(aggregate => ({
893
+ ...aggregate,
894
+ className: formatName(aggregate.className, formatOptions),
895
+ })))
896
+ : HeapSnapshotFormatter.formatAggregates(paginationData.items, formatOptions));
787
897
  }
788
898
  const nodes = this.#heapSnapshotOptions.nodes;
789
899
  if (nodes) {
@@ -800,7 +910,7 @@ Call ${handleDialog(this.#args).name} to handle it before continuing.`);
800
910
  }
801
911
  }
802
912
  const paginationData = this.#dataWithPagination(items, this.#heapSnapshotOptions.pagination);
803
- response.push(HeapSnapshotFormatter.formatNodes(paginationData.items));
913
+ response.push(HeapSnapshotFormatter.formatNodes(paginationData.items, formatOptions));
804
914
  structuredContent.pagination = paginationData.pagination;
805
915
  response.push(...paginationData.info);
806
916
  structuredContent.heapSnapshotNodes = paginationData.items;
@@ -813,7 +923,7 @@ Call ${handleDialog(this.#args).name} to handle it before continuing.`);
813
923
  response.push('No retaining paths found.');
814
924
  }
815
925
  else {
816
- response.push(HeapSnapshotFormatter.formatRetainingPaths(paths));
926
+ response.push(HeapSnapshotFormatter.formatRetainingPaths(paths, formatOptions));
817
927
  }
818
928
  const reached = Object.entries(limitsReached)
819
929
  .filter(([, hit]) => hit)
@@ -831,25 +941,47 @@ Call ${handleDialog(this.#args).name} to handle it before continuing.`);
831
941
  response.push('No dominators found.');
832
942
  }
833
943
  else {
834
- response.push(HeapSnapshotFormatter.formatDominators(dominators));
944
+ response.push(HeapSnapshotFormatter.formatDominators(dominators, formatOptions));
835
945
  }
836
946
  structuredContent.heapSnapshotDominators = dominators;
837
947
  }
838
- const classDiffs = this.#heapSnapshotOptions.classDiffs;
839
- if (classDiffs) {
948
+ const diff = this.#heapSnapshotOptions.diff;
949
+ if (diff) {
840
950
  response.push('### Heap Snapshot Diff');
951
+ response.push(HeapSnapshotFormatter.formatDiffTotals(diff.totals));
952
+ structuredContent.heapSnapshot = structuredContent.heapSnapshot || {};
953
+ structuredContent.heapSnapshot.classDiffStats = diff.totals;
954
+ const paginationData = this.#dataWithPagination(diff.classDiffs, this.#heapSnapshotOptions.pagination);
955
+ structuredContent.pagination = paginationData.pagination;
956
+ response.push(...paginationData.info);
841
957
  response.push(compactEncode
842
- ? compactEncode(classDiffs)
843
- : HeapSnapshotFormatter.formatDiffSummary(classDiffs));
844
- structuredContent.heapSnapshotClassDiffs = classDiffs;
958
+ ? compactEncode(paginationData.items.map(diff => ({
959
+ ...diff,
960
+ className: formatName(diff.className, formatOptions),
961
+ })))
962
+ : HeapSnapshotFormatter.formatDiffSummary(paginationData.items, formatOptions));
963
+ structuredContent.heapSnapshotClassDiffs = paginationData.items;
845
964
  }
846
965
  const detailedClassDiff = this.#heapSnapshotOptions.detailedClassDiff;
847
966
  if (detailedClassDiff) {
848
967
  response.push('### Heap Snapshot Detailed Diff');
968
+ const { classDiff, objects } = detailedClassDiff;
969
+ const paginationData = this.#dataWithPagination(objects, this.#heapSnapshotOptions.pagination);
970
+ structuredContent.pagination = paginationData.pagination;
849
971
  response.push(compactEncode
850
- ? compactEncode(detailedClassDiff)
851
- : HeapSnapshotFormatter.formatDiffDetails(detailedClassDiff));
852
- structuredContent.heapSnapshotDetailedClassDiff = detailedClassDiff;
972
+ ? compactEncode({
973
+ ...classDiff,
974
+ className: formatName(classDiff.className, formatOptions),
975
+ })
976
+ : HeapSnapshotFormatter.formatDetailedClassDiffHeader(classDiff, formatOptions));
977
+ response.push(...paginationData.info);
978
+ response.push(compactEncode
979
+ ? compactEncode(paginationData.items)
980
+ : HeapSnapshotFormatter.formatDetailedClassDiffObjects(paginationData.items));
981
+ structuredContent.heapSnapshotDetailedClassDiff = {
982
+ classDiff,
983
+ objects: paginationData.items,
984
+ };
853
985
  }
854
986
  const duplicateStrings = this.#heapSnapshotOptions.duplicateStrings;
855
987
  if (duplicateStrings) {
@@ -857,18 +989,47 @@ Call ${handleDialog(this.#args).name} to handle it before continuing.`);
857
989
  const paginationData = this.#dataWithPagination(duplicateStrings, this.#heapSnapshotOptions.pagination);
858
990
  structuredContent.pagination = paginationData.pagination;
859
991
  response.push(...paginationData.info);
860
- const formatted = HeapSnapshotFormatter.formatDuplicateStrings(paginationData.items);
992
+ const formatted = HeapSnapshotFormatter.formatDuplicateStrings(paginationData.items, formatOptions);
861
993
  response.push(formatted);
862
994
  structuredContent.heapSnapshotDuplicateStrings = paginationData.items;
863
995
  }
864
996
  const objectInfo = this.#heapSnapshotOptions.objectInfo;
865
997
  if (objectInfo) {
866
998
  response.push('### Object Details');
867
- response.push(compactEncode
868
- ? compactEncode(objectInfo)
869
- : HeapSnapshotFormatter.formatObjectInfo(objectInfo));
999
+ if (compactEncode) {
1000
+ response.push(compactEncode({
1001
+ ...objectInfo,
1002
+ name: formatName(objectInfo.name, formatOptions),
1003
+ }));
1004
+ }
1005
+ else {
1006
+ response.push(HeapSnapshotFormatter.formatObjectInfo(objectInfo, formatOptions));
1007
+ }
870
1008
  structuredContent.heapSnapshotObjectDetails = objectInfo;
871
1009
  }
1010
+ const contextAnalysis = this.#heapSnapshotOptions.contextAnalysis;
1011
+ if (contextAnalysis) {
1012
+ const contextAnalysisOptions = this.#heapSnapshotOptions.contextAnalysisOptions;
1013
+ const rankedContexts = collectRankedContexts(contextAnalysis, {
1014
+ retainedSize: contextAnalysisOptions?.retainedSize,
1015
+ scopeInfoNodeId: contextAnalysisOptions?.scopeInfoNodeId,
1016
+ });
1017
+ const paginationData = this.#dataWithPagination(rankedContexts, {
1018
+ pageIdx: contextAnalysisOptions?.pageIdx ?? 0,
1019
+ pageSize: contextAnalysisOptions?.pageSize,
1020
+ });
1021
+ const report = {
1022
+ contexts: paginationData.items,
1023
+ scriptsWithoutScopes: contextAnalysis.scriptsWithoutScopes,
1024
+ };
1025
+ response.push('### Context Analysis');
1026
+ structuredContent.pagination = paginationData.pagination;
1027
+ response.push(...paginationData.info);
1028
+ response.push(compactEncode
1029
+ ? compactEncode(report)
1030
+ : HeapSnapshotFormatter.formatContextAnalysis(report, formatOptions));
1031
+ structuredContent.heapSnapshotContextAnalysis = report;
1032
+ }
872
1033
  }
873
1034
  if (data.detailedNetworkRequest) {
874
1035
  response.push(data.detailedNetworkRequest.toStringDetailed());
@@ -897,18 +1058,23 @@ Call ${handleDialog(this.#args).name} to handle it before continuing.`);
897
1058
  }
898
1059
  }
899
1060
  const thirdPartyDeveloperTools = data.thirdPartyDeveloperTools;
900
- if (thirdPartyDeveloperTools?.length) {
1061
+ if (this.#listThirdPartyDeveloperTools && thirdPartyDeveloperTools) {
901
1062
  structuredContent.thirdPartyDeveloperTools = thirdPartyDeveloperTools;
902
1063
  response.push('## Third-party developer tools');
903
- for (const toolGroup of thirdPartyDeveloperTools) {
904
- response.push(`${toolGroup.name}: ${toolGroup.description}`);
905
- response.push('Available tools:');
906
- const toolDefinitionsMessage = toolGroup.tools
907
- .map(tool => {
908
- return `name="${tool.name}", description="${tool.description}", inputSchema=${JSON.stringify(tool.inputSchema)}`;
909
- })
910
- .join('\n');
911
- response.push(toolDefinitionsMessage);
1064
+ if (thirdPartyDeveloperTools.length === 0) {
1065
+ response.push('No third-party developer tools available.');
1066
+ }
1067
+ else {
1068
+ for (const toolGroup of thirdPartyDeveloperTools) {
1069
+ response.push(`${toolGroup.name}: ${toolGroup.description}`);
1070
+ response.push('Available tools:');
1071
+ const toolDefinitionsMessage = toolGroup.tools
1072
+ .map(tool => {
1073
+ return `name="${tool.name}", description="${tool.description}", inputSchema=${JSON.stringify(tool.inputSchema)}`;
1074
+ })
1075
+ .join('\n');
1076
+ response.push(toolDefinitionsMessage);
1077
+ }
912
1078
  }
913
1079
  }
914
1080
  if (this.#listWebMcpTools && data.webmcpTools) {
@@ -976,6 +1142,11 @@ Call ${handleDialog(this.#args).name} to handle it before continuing.`);
976
1142
  const commentsJson = data.comments.toJSON();
977
1143
  structuredContent.comments = commentsJson;
978
1144
  response.push(compactEncode ? compactEncode(commentsJson) : data.comments.toString());
1145
+ if (data.commentsSnapshotRegenerated) {
1146
+ response.push(`Note: DevTools comments regenerated the ${data.commentsSnapshotRegenerated} text snapshot.`);
1147
+ structuredContent.commentsSnapshotRegenerated =
1148
+ data.commentsSnapshotRegenerated;
1149
+ }
979
1150
  }
980
1151
  if (this.#cssStylesData) {
981
1152
  const resolveUid = (backendNodeId) => this.#page?.textSnapshot?.resolveCdpElementId(backendNodeId);
@@ -1030,7 +1201,8 @@ Call ${handleDialog(this.#args).name} to handle it before continuing.`);
1030
1201
  response.push('Invalid page number provided. Showing first page.');
1031
1202
  }
1032
1203
  const { startIndex, endIndex, currentPage, totalPages } = paginationResult;
1033
- response.push(`Showing ${startIndex + 1}-${endIndex} of ${data.length} (Page ${currentPage + 1} of ${totalPages}).`);
1204
+ const displayStartIndex = data.length === 0 ? 0 : startIndex + 1;
1205
+ response.push(`Showing ${displayStartIndex}-${endIndex} of ${data.length} (Page ${currentPage + 1} of ${totalPages}).`);
1034
1206
  if (pagination) {
1035
1207
  if (paginationResult.hasNextPage) {
1036
1208
  response.push(`Next page: ${currentPage + 1}`);
@@ -1058,23 +1230,26 @@ Call ${handleDialog(this.#args).name} to handle it before continuing.`);
1058
1230
  }
1059
1231
  }
1060
1232
  function truncateTitle(title, maxLength = 50) {
1061
- if (title.length <= maxLength) {
1062
- return title;
1063
- }
1064
- return title.slice(0, maxLength - 3) + '...';
1233
+ return truncateText(title, maxLength, { includeEllipsisInLength: true });
1065
1234
  }
1066
- async function fetchPageTitle(page) {
1067
- return Promise.race([
1068
- page.title().catch(() => ''),
1069
- new Promise(resolve => setTimeout(() => resolve(''), 1000)),
1070
- ]);
1235
+ const collapseWhitespace = (value) => {
1236
+ return value.replace(/\s+/g, ' ').trim();
1237
+ };
1238
+ function formatPage(mcpPage, context, targetInfo) {
1239
+ const title = mcpPage.getTitle(targetInfo);
1240
+ const url = mcpPage.url();
1241
+ const pageLabel = title ? `${truncateTitle(title)} (${url})` : url;
1242
+ return {
1243
+ text: `${mcpPage.id}: ${pageLabel}`,
1244
+ structured: createStructuredPage(mcpPage, context, title),
1245
+ };
1071
1246
  }
1072
1247
  function createStructuredPage(mcpPage, context, rawTitle) {
1073
1248
  const isolatedContextName = mcpPage.isolatedContextName;
1074
1249
  const title = truncateTitle(rawTitle);
1075
1250
  const entry = {
1076
1251
  id: mcpPage.id,
1077
- url: mcpPage.pptrPage.url(),
1252
+ url: mcpPage.url(),
1078
1253
  title,
1079
1254
  selected: context.isPageSelected(mcpPage),
1080
1255
  };