chrome-devtools-mcp 1.7.0 → 1.9.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 (74) hide show
  1. package/README.md +20 -874
  2. package/build/src/McpContext.js +98 -45
  3. package/build/src/McpPage.js +10 -4
  4. package/build/src/McpResponse.js +22 -4
  5. package/build/src/ToolHandler.js +81 -57
  6. package/build/src/bin/chrome-devtools-mcp-main.js +4 -4
  7. package/build/src/bin/chrome-devtools.js +29 -30
  8. package/build/src/browser.js +8 -17
  9. package/build/src/{PageCollector.js → collectors/PageCollector.js} +7 -7
  10. package/build/src/{ServiceWorkerCollector.js → collectors/ServiceWorkerCollector.js} +1 -1
  11. package/build/src/config/browser-options.js +123 -0
  12. package/build/src/config/category-options.js +80 -0
  13. package/build/src/{bin/chrome-devtools-cli-options.js → config/cli-options.js} +380 -25
  14. package/build/src/{bin/chrome-devtools-mcp-cli-options.js → config/mcp-options.js} +113 -148
  15. package/build/src/daemon/client.js +11 -2
  16. package/build/src/daemon/daemon.js +2 -2
  17. package/build/src/daemon/utils.js +6 -0
  18. package/build/src/devtools/DevtoolsUtils.js +29 -35
  19. package/build/src/formatters/ConsoleFormatter.js +43 -10
  20. package/build/src/formatters/HeapSnapshotFormatter.js +10 -2
  21. package/build/src/formatters/IssueFormatter.js +1 -1
  22. package/build/src/formatters/NetworkFormatter.js +12 -9
  23. package/build/src/index.js +185 -91
  24. package/build/src/{HeapSnapshotManager.js → processors/HeapSnapshotManager.js} +21 -5
  25. package/build/src/{trace-processing/parse.js → processors/PerformanceTrace.js} +1 -1
  26. package/build/src/telemetry/ClearcutLogger.js +18 -5
  27. package/build/src/telemetry/flagUtils.js +4 -3
  28. package/build/src/telemetry/types.js +4 -0
  29. package/build/src/third_party/THIRD_PARTY_NOTICES +8 -65
  30. package/build/src/third_party/bundled-packages.json +4 -4
  31. package/build/src/third_party/devtools-formatter-worker.js +22 -0
  32. package/build/src/third_party/devtools-heap-snapshot-worker.js +296 -42
  33. package/build/src/third_party/index.js +38728 -37176
  34. package/build/src/third_party/issue-descriptions/connectionAllowlistEmbeddingRequirementNotSatisfied.md +26 -0
  35. package/build/src/third_party/issue-descriptions/connectionAllowlistIFrameAttributeLoosensEmbeddingRequirement.md +19 -0
  36. package/build/src/third_party/issue-descriptions/connectionAllowlistInvalidAllowConnectionAllowlistFrom.md +21 -0
  37. package/build/src/third_party/issue-descriptions/federatedAuthRequestAccountsBlockedByConnectionAllowlist.md +1 -0
  38. package/build/src/third_party/issue-descriptions/federatedAuthRequestConfigBlockedByConnectionAllowlist.md +1 -0
  39. package/build/src/third_party/issue-descriptions/federatedAuthRequestIdTokenBlockedByConnectionAllowlist.md +1 -0
  40. package/build/src/third_party/issue-descriptions/federatedAuthRequestWellKnownBlockedByConnectionAllowlist.md +1 -0
  41. package/build/src/tools/ToolDefinition.js +15 -0
  42. package/build/src/tools/categories.js +2 -5
  43. package/build/src/tools/console.js +9 -3
  44. package/build/src/tools/emulation.js +2 -2
  45. package/build/src/tools/extensions.js +7 -5
  46. package/build/src/tools/input.js +26 -16
  47. package/build/src/tools/lighthouse.js +3 -1
  48. package/build/src/tools/memory.js +112 -16
  49. package/build/src/tools/network.js +7 -4
  50. package/build/src/tools/pages.js +34 -23
  51. package/build/src/tools/performance.js +16 -25
  52. package/build/src/tools/pwa.js +128 -0
  53. package/build/src/tools/screencast.js +7 -4
  54. package/build/src/tools/screenshot.js +42 -9
  55. package/build/src/tools/script.js +29 -8
  56. package/build/src/tools/slim/tools.js +43 -35
  57. package/build/src/tools/snapshot.js +5 -3
  58. package/build/src/tools/thirdPartyDeveloper.js +2 -2
  59. package/build/src/tools/tools.js +2 -0
  60. package/build/src/tools/webmcp.js +2 -2
  61. package/build/src/{WaitForHelper.js → utils/WaitForHelper.js} +74 -38
  62. package/build/src/utils/bytes.js +105 -0
  63. package/build/src/utils/logger.js +25 -11
  64. package/build/src/utils/url.js +73 -0
  65. package/build/src/version.js +1 -1
  66. package/package.json +21 -13
  67. package/skills/a11y-debugging/SKILL.md +2 -0
  68. package/skills/chrome-devtools/SKILL.md +5 -4
  69. package/skills/chrome-devtools-cli/SKILL.md +103 -64
  70. package/skills/cookie-debugging/SKILL.md +149 -0
  71. package/skills/debug-optimize-lcp/SKILL.md +9 -9
  72. package/skills/memory-leak-debugging/SKILL.md +6 -2
  73. package/skills/troubleshooting/SKILL.md +1 -0
  74. package/build/src/utils/string.js +0 -37
@@ -8,13 +8,14 @@ import os from 'node:os';
8
8
  import path from 'node:path';
9
9
  import { fileURLToPath, pathToFileURL } from 'node:url';
10
10
  import { overrideDevToolsGlobals } from './devtools/DevtoolsUtils.js';
11
- import { HeapSnapshotManager } from './HeapSnapshotManager.js';
11
+ import { HeapSnapshotManager } from './processors/HeapSnapshotManager.js';
12
12
  import { McpPage } from './McpPage.js';
13
- import { ServiceWorkerConsoleCollector } from './ServiceWorkerCollector.js';
13
+ import { ServiceWorkerConsoleCollector } from './collectors/ServiceWorkerCollector.js';
14
14
  import { Locator, } from './third_party/index.js';
15
15
  import { listPages } from './tools/pages.js';
16
16
  import { CLOSE_PAGE_ERROR } from './tools/ToolDefinition.js';
17
17
  import { getTempFilePath, resolveCanonicalPath } from './utils/files.js';
18
+ import { isAllowedUrl } from './utils/url.js';
18
19
  // Page ids are handed out from a process-wide counter so they stay unique
19
20
  // across all contexts, in particular across browser reconnects. An id issued
20
21
  // before a reconnect then fails to resolve instead of hitting an unrelated
@@ -81,6 +82,12 @@ export class McpContext {
81
82
  }
82
83
  #onTargetCreated = async (target) => {
83
84
  try {
85
+ const url = target.url();
86
+ if (!isAllowedUrl(url, {
87
+ categoryExtensions: this.#options.categoryExtensions,
88
+ })) {
89
+ return;
90
+ }
84
91
  const page = await target.page();
85
92
  if (!page) {
86
93
  return;
@@ -137,28 +144,30 @@ export class McpContext {
137
144
  }
138
145
  async validatePath(filePath) {
139
146
  if (filePath === undefined) {
140
- return;
147
+ return undefined;
148
+ }
149
+ let canonicalPath;
150
+ try {
151
+ canonicalPath = await resolveCanonicalPath(filePath);
152
+ }
153
+ catch (err) {
154
+ const errMsg = err instanceof Error ? err.message : String(err);
155
+ console.error(`[MCP Context] Error resolving real path for ${filePath}: ${errMsg}`);
156
+ throw new Error(`Access denied: Cannot resolve base path for ${filePath}.`);
141
157
  }
142
158
  // If the client never negotiated roots and the operator has explicitly
143
159
  // opted into unrestricted access via --allow-unrestricted-paths, restore
144
160
  // the previous permissive behavior and skip validation.
145
161
  if (this.#roots === undefined && this.#allowUnrestrictedPaths) {
146
- return;
162
+ // Canonical path might not exist yet so we fallback to
163
+ // path.resolve(filePath). Consumers should not follow symlinks.
164
+ return canonicalPath || path.resolve(filePath);
147
165
  }
148
166
  // roots() always returns at least the temp directory, even if the
149
167
  // connecting client never negotiated the optional `roots` capability.
150
168
  // Path validation must not be skipped just because no workspace roots
151
169
  // were configured.
152
170
  const roots = this.roots();
153
- let canonicalPath;
154
- try {
155
- canonicalPath = await resolveCanonicalPath(filePath);
156
- }
157
- catch (err) {
158
- const errMsg = err instanceof Error ? err.message : String(err);
159
- console.error(`[MCP Context] Error resolving real path for ${filePath}: ${errMsg}`);
160
- throw new Error(`Access denied: Cannot resolve base path for ${filePath}.`);
161
- }
162
171
  let allowed = false;
163
172
  const resolvedRoots = await Promise.allSettled(roots.map(async (root) => {
164
173
  const rootPathUri = root.uri;
@@ -186,12 +195,12 @@ export class McpContext {
186
195
  if (!allowed) {
187
196
  throw new Error(`Access denied: path ${filePath} (canonical: ${canonicalPath}) is not within any of the configured workspace roots.`);
188
197
  }
198
+ return canonicalPath || path.resolve(filePath);
189
199
  }
190
200
  async ensureExtension(filePath, extension) {
191
- const resolvedPath = path.resolve(filePath);
192
- const currentExtension = path.extname(resolvedPath);
193
- const outputPath = `${resolvedPath.slice(0, resolvedPath.length - currentExtension.length)}${extension}`;
194
- await this.validatePath(outputPath);
201
+ const resolved = await this.validatePath(filePath);
202
+ const currentExtension = path.extname(resolved);
203
+ const outputPath = `${resolved.slice(0, resolved.length - currentExtension.length)}${extension}`;
195
204
  return outputPath;
196
205
  }
197
206
  async newPage(background, isolatedContextName) {
@@ -202,7 +211,7 @@ export class McpContext {
202
211
  ctx = await this.browser.createBrowserContext();
203
212
  this.#isolatedContexts.set(isolatedContextName, ctx);
204
213
  }
205
- page = await ctx.newPage();
214
+ page = await ctx.newPage({ background });
206
215
  }
207
216
  else {
208
217
  page = await this.browser.newPage({ background });
@@ -226,6 +235,18 @@ export class McpContext {
226
235
  get #hasNetworkBlockOrAllowlist() {
227
236
  return !!(this.#options.allowList || this.#options.blocklist);
228
237
  }
238
+ installPWA(options) {
239
+ return this.browser.installPWA(options);
240
+ }
241
+ uninstallPWA(options) {
242
+ return this.browser.uninstallPWA(options);
243
+ }
244
+ launchPWA(options) {
245
+ return this.browser.launchPWA(options);
246
+ }
247
+ getPWAState(options) {
248
+ return this.browser.getPWAState(options);
249
+ }
229
250
  setIsRunningPerformanceTrace(x) {
230
251
  this.#isRunningTrace = x;
231
252
  }
@@ -254,6 +275,21 @@ export class McpContext {
254
275
  }
255
276
  return page;
256
277
  }
278
+ getSelectedMcpPageUrl(page) {
279
+ let targetPage = page;
280
+ if (!targetPage) {
281
+ try {
282
+ targetPage = this.getSelectedMcpPage();
283
+ }
284
+ catch {
285
+ return undefined;
286
+ }
287
+ }
288
+ if (targetPage?.pptrPage?.isClosed() === false) {
289
+ return targetPage.pptrPage.url();
290
+ }
291
+ return undefined;
292
+ }
257
293
  async getDevToolsData(page) {
258
294
  const targetPage = page ?? this.#selectedPage;
259
295
  if (!targetPage) {
@@ -359,6 +395,8 @@ export class McpContext {
359
395
  locatorClass: this.#locatorClass,
360
396
  hasNetworkBlockOrAllowlist: this.#hasNetworkBlockOrAllowlist,
361
397
  isolatedContextName: this.#getBrowserContextToNameMap().get(page.browserContext()),
398
+ navigationTimeout: this.#options.navigationTimeout,
399
+ sourceMaps: this.#options.sourceMaps,
362
400
  });
363
401
  this.#mcpPages.set(page, mcpPage);
364
402
  await mcpPage.init();
@@ -396,29 +434,38 @@ export class McpContext {
396
434
  }
397
435
  async #fetchBrowserPages() {
398
436
  const allPages = (await this.browser.pages(this.#options.experimentalIncludeAllPages)).filter(page => {
399
- return (this.#options.experimentalDevToolsDebugging ||
400
- !page.url().startsWith('devtools://'));
401
- });
402
- const allTargets = this.browser.targets();
403
- const extensionTargets = allTargets.filter(target => {
404
- return (target.url().startsWith('chrome-extension://') &&
405
- target.type() === 'page');
437
+ if (!this.#options.experimentalDevToolsDebugging &&
438
+ page.url().startsWith('devtools://')) {
439
+ return false;
440
+ }
441
+ return isAllowedUrl(page.url(), {
442
+ categoryExtensions: this.#options.categoryExtensions,
443
+ });
406
444
  });
407
- await Promise.allSettled(extensionTargets.map(async (target) => {
408
- try {
409
- let page = await target.page();
410
- if (!page) {
411
- page = await target.asPage();
445
+ if (this.#options.categoryExtensions) {
446
+ const allTargets = this.browser.targets();
447
+ const extensionTargets = allTargets.filter(target => {
448
+ return (target.url().startsWith('chrome-extension://') &&
449
+ target.type() === 'page');
450
+ });
451
+ await Promise.allSettled(extensionTargets.map(async (target) => {
452
+ try {
453
+ let page = await target.page();
454
+ if (!page) {
455
+ page = await target.asPage();
456
+ }
457
+ this.#extensionPages.set(target, page);
458
+ if (page &&
459
+ isAllowedUrl(page.url(), { categoryExtensions: true }) &&
460
+ !allPages.includes(page)) {
461
+ allPages.push(page);
462
+ }
412
463
  }
413
- this.#extensionPages.set(target, page);
414
- if (page && !allPages.includes(page)) {
415
- allPages.push(page);
464
+ catch (e) {
465
+ this.logger?.('Failed to get page for extension target', e);
416
466
  }
417
- }
418
- catch (e) {
419
- this.logger?.('Failed to get page for extension target', e);
420
- }
421
- }));
467
+ }));
468
+ }
422
469
  return allPages;
423
470
  }
424
471
  getExtensionServiceWorkers() {
@@ -428,16 +475,16 @@ export class McpContext {
428
475
  return this.#extensionServiceWorkerMap.get(extensionServiceWorker.target);
429
476
  }
430
477
  async #writeFile(filepath, data) {
431
- await this.validatePath(filepath);
478
+ const resolved = await this.validatePath(filepath);
432
479
  try {
433
- await fs.mkdir(path.dirname(filepath), { recursive: true });
480
+ await fs.mkdir(path.dirname(resolved), { recursive: true });
434
481
  // Open the file with flags to:
435
482
  // - O_WRONLY: Write-only
436
483
  // - O_CREAT: Create if it doesn't exist
437
484
  // - O_TRUNC: Truncate to zero length if it exists
438
485
  // - O_NOFOLLOW: DO NOT follow symlinks.
439
486
  // - 0o600: Permissions: read/write for owner, no permissions for others.
440
- await fs.writeFile(filepath, data, {
487
+ await fs.writeFile(resolved, data, {
441
488
  flag: fs.constants.O_WRONLY |
442
489
  fs.constants.O_CREAT |
443
490
  fs.constants.O_TRUNC |
@@ -502,6 +549,9 @@ export class McpContext {
502
549
  async getHeapSnapshotDuplicateStrings(filePath) {
503
550
  return await this.#heapSnapshotManager.getDuplicateStrings(filePath);
504
551
  }
552
+ async queryHeapSnapshotObjects(filePath, options) {
553
+ return await this.#heapSnapshotManager.queryObjects(filePath, options);
554
+ }
505
555
  async getHeapSnapshotStats(filePath) {
506
556
  return await this.#heapSnapshotManager.getStats(filePath);
507
557
  }
@@ -511,6 +561,9 @@ export class McpContext {
511
561
  async getHeapSnapshotNativeContextSizes(filePath) {
512
562
  return await this.#heapSnapshotManager.getNativeContextSizes(filePath);
513
563
  }
564
+ async getHeapSnapshotRetainedByContextSummary(filePath) {
565
+ return await this.#heapSnapshotManager.getRetainedByContextSummary(filePath);
566
+ }
514
567
  async getHeapSnapshotNodesById(filePath, id, filterName, objectId) {
515
568
  return await this.#heapSnapshotManager.getNodesById(filePath, id, filterName, objectId);
516
569
  }
@@ -569,15 +622,15 @@ export class McpContext {
569
622
  return response.text();
570
623
  }
571
624
  case 'file:': {
572
- await this.validatePath(fileURLToPath(url));
573
- return await fs.readFile(url, 'utf-8');
625
+ const resolved = await this.validatePath(fileURLToPath(url));
626
+ return await fs.readFile(resolved, 'utf-8');
574
627
  }
575
628
  default:
576
629
  throw new Error(`Unsupported protocol for: ${url}`);
577
630
  }
578
631
  }
579
- async getHeapSnapshotEdges(filePath, nodeId) {
580
- return await this.#heapSnapshotManager.getEdges(filePath, nodeId);
632
+ async getHeapSnapshotEdges(filePath, nodeId, options) {
633
+ return await this.#heapSnapshotManager.getEdges(filePath, nodeId, options);
581
634
  }
582
635
  async getHeapSnapshotClassDiffs(baseFilePath, currentFilePath) {
583
636
  return await this.#heapSnapshotManager.getClassDiffs(baseFilePath, currentFilePath);
@@ -102,14 +102,14 @@ export function replaceHtmlElementsWithUids(schema) {
102
102
  }
103
103
  }
104
104
  import { createTargetUniverse, } from './devtools/DevtoolsUtils.js';
105
- import { ConsoleCollector, NetworkCollector, } from './PageCollector.js';
105
+ import { ConsoleCollector, NetworkCollector, } from './collectors/PageCollector.js';
106
106
  import { TextSnapshot } from './TextSnapshot.js';
107
107
  import { PredefinedNetworkConditions, } from './third_party/index.js';
108
108
  import { takeSnapshot } from './tools/snapshot.js';
109
109
  const DEFAULT_TIMEOUT = 5_000;
110
110
  const NAVIGATION_TIMEOUT = 10_000;
111
111
  import { logger } from './utils/logger.js';
112
- import { getNetworkMultiplierFromString, WaitForHelper, } from './WaitForHelper.js';
112
+ import { getNetworkMultiplierFromString, WaitForHelper, } from './utils/WaitForHelper.js';
113
113
  /**
114
114
  * Per-page state wrapper. Consolidates dialog, snapshot, emulation,
115
115
  * and metadata that were previously scattered across Maps in McpContext.
@@ -138,9 +138,13 @@ export class McpPage {
138
138
  consoleCollector;
139
139
  #hasNetworkBlockOrAllowlist;
140
140
  #locatorClass;
141
+ #navigationTimeout;
142
+ #sourceMaps;
141
143
  constructor(page, id, options) {
142
144
  this.#hasNetworkBlockOrAllowlist = options.hasNetworkBlockOrAllowlist;
143
145
  this.#locatorClass = options.locatorClass;
146
+ this.#navigationTimeout = options.navigationTimeout ?? NAVIGATION_TIMEOUT;
147
+ this.#sourceMaps = options.sourceMaps ?? true;
144
148
  this.pptrPage = page;
145
149
  this.id = id;
146
150
  this.isolatedContextName = options.isolatedContextName;
@@ -181,7 +185,9 @@ export class McpPage {
181
185
  }
182
186
  try {
183
187
  const session = await this.pptrPage.createCDPSession();
184
- this.#devtoolsUniverse = await createTargetUniverse(session);
188
+ this.#devtoolsUniverse = await createTargetUniverse(session, {
189
+ sourceMaps: this.#sourceMaps,
190
+ });
185
191
  }
186
192
  catch (e) {
187
193
  logger?.('Failed to initialize DevTools universe', e);
@@ -707,7 +713,7 @@ export class McpPage {
707
713
  // navigations.
708
714
  // Increased in case we throttle the network requests or the CPU
709
715
  const networkMultiplier = getNetworkMultiplierFromString(this.networkConditions);
710
- this.pptrPage.setDefaultNavigationTimeout(NAVIGATION_TIMEOUT * networkMultiplier * cpuMultiplier);
716
+ this.pptrPage.setDefaultNavigationTimeout(this.#navigationTimeout * networkMultiplier * cpuMultiplier);
711
717
  }
712
718
  waitForTextOnPage(text, timeout) {
713
719
  const frames = this.pptrPage.frames();
@@ -8,11 +8,11 @@ import { HeapSnapshotFormatter, isEdgeLike, isNodeLike, } from './formatters/Hea
8
8
  import { IssueFormatter } from './formatters/IssueFormatter.js';
9
9
  import { NetworkFormatter } from './formatters/NetworkFormatter.js';
10
10
  import { SnapshotFormatter } from './formatters/SnapshotFormatter.js';
11
- import { UncaughtError } from './PageCollector.js';
11
+ import { UncaughtError } from './collectors/PageCollector.js';
12
12
  import { TextSnapshot } from './TextSnapshot.js';
13
13
  import { DevTools, getToonEncode, getGcfEncode } from './third_party/index.js';
14
14
  import { handleDialog, listPages } from './tools/pages.js';
15
- import { getInsightOutput, getTraceSummary } from './trace-processing/parse.js';
15
+ import { getInsightOutput, getTraceSummary, } from './processors/PerformanceTrace.js';
16
16
  import { stableIdSymbol } from './utils/id.js';
17
17
  import { paginate } from './utils/pagination.js';
18
18
  const { formatBytesToKb } = DevTools.I18n.ByteUtilities;
@@ -122,6 +122,7 @@ export class McpResponse {
122
122
  : undefined,
123
123
  types: options?.types,
124
124
  includePreservedMessages: options?.includePreservedMessages,
125
+ includeStackTraces: options?.includeStackTraces,
125
126
  serviceWorkerId: options?.serviceWorkerId,
126
127
  };
127
128
  }
@@ -195,13 +196,14 @@ export class McpResponse {
195
196
  pagination: options,
196
197
  };
197
198
  }
198
- setHeapSnapshotStats(stats, staticData, nativeContextSizes) {
199
+ setHeapSnapshotStats(stats, staticData, nativeContextSizes, retainedByContextSummary) {
199
200
  this.#heapSnapshotOptions = {
200
201
  ...this.#heapSnapshotOptions,
201
202
  include: true,
202
203
  stats,
203
204
  staticData,
204
205
  nativeContextSizes,
206
+ retainedByContextSummary,
205
207
  };
206
208
  }
207
209
  setHeapSnapshotNodes(nodes, options) {
@@ -394,6 +396,7 @@ export class McpResponse {
394
396
  return await ConsoleFormatter.from(consoleMessage, {
395
397
  id: consoleMessageStableId,
396
398
  fetchDetailedData: false,
399
+ fetchStackTrace: this.#consoleDataOptions?.includeStackTraces,
397
400
  devTools: page ? page.devtoolsUniverse : undefined,
398
401
  });
399
402
  }
@@ -649,7 +652,11 @@ Call ${handleDialog.name} to handle it before continuing.`);
649
652
  for (const [insightName, model] of Object.entries(insightSet.model)) {
650
653
  structuredContent.traceInsights.push({
651
654
  insightName,
652
- insightKey: model.insightKey,
655
+ insightKey: typeof model === 'object' &&
656
+ model !== null &&
657
+ 'insightKey' in model
658
+ ? model.insightKey
659
+ : undefined,
653
660
  });
654
661
  }
655
662
  }
@@ -717,6 +724,14 @@ Call ${handleDialog.name} to handle it before continuing.`);
717
724
  structuredContent.heapSnapshot = structuredContent.heapSnapshot || {};
718
725
  structuredContent.heapSnapshot.nativeContextSizes = nativeContextSizes;
719
726
  }
727
+ const retainedByContextSummary = this.#heapSnapshotOptions.retainedByContextSummary;
728
+ if (retainedByContextSummary) {
729
+ response.push('### Retained by Context Summary');
730
+ response.push(HeapSnapshotFormatter.formatRetainedByContextSummary(retainedByContextSummary));
731
+ structuredContent.heapSnapshot = structuredContent.heapSnapshot || {};
732
+ structuredContent.heapSnapshot.retainedByContextSummary =
733
+ retainedByContextSummary;
734
+ }
720
735
  const aggregateData = this.#heapSnapshotOptions.aggregateData;
721
736
  if (aggregateData) {
722
737
  const sortedEntries = HeapSnapshotFormatter.sort(aggregateData.aggregates);
@@ -916,6 +931,9 @@ Call ${handleDialog.name} to handle it before continuing.`);
916
931
  else {
917
932
  response.push(...paginationData.items.map(item => item.toString()));
918
933
  }
934
+ if (structuredContent.consoleMessages.some(message => 'stackTrace' in message)) {
935
+ response.push('Note: stack trace line and column numbers use 1-based indexing');
936
+ }
919
937
  }
920
938
  else {
921
939
  response.push('<no console messages found>');
@@ -6,63 +6,35 @@
6
6
  import { McpResponse } from './McpResponse.js';
7
7
  import { SlimMcpResponse } from './SlimMcpResponse.js';
8
8
  import { ClearcutLogger } from './telemetry/ClearcutLogger.js';
9
- import { bucketizeLatency, buildContext } from './telemetry/transformation.js';
10
9
  import { zod } from './third_party/index.js';
11
- import { labels, OFF_BY_DEFAULT_CATEGORIES } from './tools/categories.js';
10
+ import { labels } from './tools/categories.js';
11
+ import { categoryToFlagName } from './config/category-options.js';
12
12
  import { pageIdSchema } from './tools/ToolDefinition.js';
13
13
  import { logger } from './utils/logger.js';
14
- export function buildFlag(category) {
15
- return `category${category.charAt(0).toUpperCase() + category.slice(1)}`;
16
- }
14
+ import { fileURLToPath, pathToFileURL } from 'node:url';
15
+ import { isLocalhost } from './utils/url.js';
17
16
  function buildDisabledMessage(toolName, flag, categoryLabel) {
18
17
  const reason = categoryLabel
19
18
  ? `is in category ${categoryLabel} which`
20
- : `requires experimental feature ${flag} and`;
19
+ : `requires ${flag.startsWith('--experimental') ? 'experimental feature' : 'flag'} ${flag} and`;
21
20
  return `Tool ${toolName} ${reason} is currently disabled. Enable it by running chrome-devtools start ${flag}=true. For more information check the README.`;
22
21
  }
23
- function getCategoryStatus(category, serverArgs) {
24
- const categoryFlag = buildFlag(category);
25
- const flagValue = serverArgs[categoryFlag];
26
- const isDisabled = OFF_BY_DEFAULT_CATEGORIES.includes(category)
27
- ? !flagValue
28
- : flagValue === false;
29
- if (isDisabled) {
30
- return {
31
- categoryFlag,
32
- disabled: true,
33
- };
34
- }
35
- return {
36
- disabled: false,
37
- };
38
- }
39
- function getConditionStatus(condition, serverArgs) {
40
- if (condition && !serverArgs[condition]) {
41
- return { conditionFlag: condition, disabled: true };
42
- }
43
- return { disabled: false };
44
- }
45
22
  function getToolStatusInfo(tool, serverArgs) {
46
23
  const category = tool.annotations.category;
47
- const categoryCheck = getCategoryStatus(category, serverArgs);
48
- if (category && categoryCheck.disabled) {
49
- if (!categoryCheck.categoryFlag) {
50
- throw new Error('when the category is disabled there should always be a flag set');
24
+ if (category) {
25
+ const flag = categoryToFlagName(category);
26
+ if (!serverArgs[flag]) {
27
+ return {
28
+ disabled: true,
29
+ reason: buildDisabledMessage(tool.name, `--${flag}`, labels[category]),
30
+ };
51
31
  }
52
- return {
53
- disabled: true,
54
- reason: buildDisabledMessage(tool.name, `--${categoryCheck.categoryFlag}`, labels[category]),
55
- };
56
32
  }
57
33
  for (const condition of tool.annotations.conditions || []) {
58
- const conditionCheck = getConditionStatus(condition, serverArgs);
59
- if (conditionCheck.disabled) {
60
- if (!conditionCheck.conditionFlag) {
61
- throw new Error('when the condition is disabled there should always be a flag set');
62
- }
34
+ if (!serverArgs[condition]) {
63
35
  return {
64
36
  disabled: true,
65
- reason: buildDisabledMessage(tool.name, `--${conditionCheck.conditionFlag}`),
37
+ reason: buildDisabledMessage(tool.name, `--${condition}`),
66
38
  };
67
39
  }
68
40
  }
@@ -82,6 +54,66 @@ function buildUnknownArgumentsMessage(toolName, unknownArgumentNames, expectedAr
82
54
  const correction = unknownArgumentNames.length === 1 ? 'Remove it' : 'Remove them';
83
55
  return `Unknown ${unknownLabel} for tool "${toolName}": ${formatArgumentNames(unknownArgumentNames)}. ${expectedArguments} ${correction} and retry.`;
84
56
  }
57
+ async function validateAndResolvePathOrUrl(filePathOrUrl, context) {
58
+ try {
59
+ const url = new URL(filePathOrUrl);
60
+ if (url.protocol === 'file:') {
61
+ return pathToFileURL(await context.validatePath(fileURLToPath(url))).href;
62
+ }
63
+ else if (['http:', 'https:', 'ws:', 'wss:'].includes(url.protocol)) {
64
+ return filePathOrUrl;
65
+ }
66
+ }
67
+ catch {
68
+ // Suppress parsing errors for regular file paths.
69
+ }
70
+ return await context.validatePath(filePathOrUrl);
71
+ }
72
+ function isLocalBrowser(context) {
73
+ if (context.browser.process()) {
74
+ return true;
75
+ }
76
+ const wsEndpoint = context.browser.wsEndpoint();
77
+ if (wsEndpoint && isLocalhost(wsEndpoint)) {
78
+ return true;
79
+ }
80
+ return false;
81
+ }
82
+ function shouldValidateFile(option, isLocal) {
83
+ if (option === true) {
84
+ return true;
85
+ }
86
+ if (typeof option === 'object' && option !== null) {
87
+ if (isLocal) {
88
+ return Boolean(option.local);
89
+ }
90
+ return Boolean(option.remote);
91
+ }
92
+ return false;
93
+ }
94
+ async function validateToolFiles(tool, params, context) {
95
+ const isLocal = isLocalBrowser(context);
96
+ for (const [key, option] of Object.entries(tool.verifyFilesSchema)) {
97
+ if (shouldValidateFile(option, isLocal)) {
98
+ const val = params[key];
99
+ if (typeof val === 'string') {
100
+ params[key] = await validateAndResolvePathOrUrl(val, context);
101
+ }
102
+ else if (Array.isArray(val)) {
103
+ const updated = [];
104
+ for (const item of val) {
105
+ if (typeof item === 'string') {
106
+ updated.push(await validateAndResolvePathOrUrl(item, context));
107
+ }
108
+ else {
109
+ throw new Error('Unexpected non-string value as a file path or URL');
110
+ }
111
+ }
112
+ params[key] = updated;
113
+ }
114
+ }
115
+ }
116
+ }
85
117
  export class ToolHandler {
86
118
  tool;
87
119
  serverArgs;
@@ -102,7 +134,7 @@ export class ToolHandler {
102
134
  this.inputSchema =
103
135
  'pageScoped' in tool &&
104
136
  tool.pageScoped &&
105
- serverArgs.experimentalPageIdRouting &&
137
+ serverArgs.pageIdRouting &&
106
138
  !serverArgs.slim
107
139
  ? { ...pageIdSchema, ...tool.schema }
108
140
  : tool.schema;
@@ -153,16 +185,11 @@ export class ToolHandler {
153
185
  }
154
186
  let page;
155
187
  try {
156
- if (this.tool.verifyFilesSchema) {
157
- for (const key of this.tool.verifyFilesSchema) {
158
- const filePath = params[key];
159
- await context.validatePath(filePath);
160
- }
161
- }
188
+ await validateToolFiles(this.tool, params, context);
162
189
  if (isPageScopedTool(this.tool)) {
163
190
  const pageId = typeof params.pageId === 'number' ? params.pageId : undefined;
164
191
  page =
165
- this.serverArgs.experimentalPageIdRouting &&
192
+ this.serverArgs.pageIdRouting &&
166
193
  pageId !== undefined &&
167
194
  !this.serverArgs.slim
168
195
  ? context.getPageById(pageId)
@@ -186,10 +213,7 @@ export class ToolHandler {
186
213
  response.setError(err);
187
214
  }
188
215
  devToolsData = await context.getDevToolsData(page);
189
- const targetPage = page ?? context.getSelectedMcpPage();
190
- if (targetPage?.pptrPage?.isClosed() === false) {
191
- pageUrl = targetPage.pptrPage.url();
192
- }
216
+ pageUrl = context.getSelectedMcpPageUrl(page);
193
217
  // Resolve data format: --experimentalDataFormat takes precedence, fall back to legacy --experimentalToonFormat
194
218
  let dataFormat = 'default';
195
219
  if (this.serverArgs.experimentalDataFormat) {
@@ -228,14 +252,14 @@ export class ToolHandler {
228
252
  };
229
253
  }
230
254
  finally {
231
- const context = buildContext(devToolsData, pageUrl);
232
255
  void ClearcutLogger.get()?.logToolInvocation({
233
256
  toolName: this.tool.name,
234
257
  params,
235
258
  schema: this.inputSchema,
236
259
  success,
237
- latencyMs: bucketizeLatency(Date.now() - startTime),
238
- context,
260
+ latencyMs: Date.now() - startTime,
261
+ devToolsData,
262
+ pageUrl,
239
263
  });
240
264
  guard[Symbol.dispose]();
241
265
  }
@@ -6,14 +6,14 @@
6
6
  import '../utils/polyfill.js';
7
7
  import process from 'node:process';
8
8
  import { closeBrowser } from '../browser.js';
9
- import { createMcpServer, logDisclaimers } from '../index.js';
9
+ import { McpServer, logDisclaimers } 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
14
  import { logger, saveLogsToFile } from '../utils/logger.js';
15
15
  import { VERSION } from '../version.js';
16
- import { cliOptions, parseArguments } from './chrome-devtools-mcp-cli-options.js';
16
+ import { mcpOptions, parseArguments } from '../config/mcp-options.js';
17
17
  await checkForUpdates('Run `npm install chrome-devtools-mcp@latest` to update.');
18
18
  export const args = parseArguments(VERSION);
19
19
  const logFile = args.logFile ? saveLogsToFile(args.logFile) : undefined;
@@ -60,7 +60,7 @@ process.on('SIGHUP', () => {
60
60
  void shutdown('SIGHUP');
61
61
  });
62
62
  logger?.(`Starting Chrome DevTools MCP Server v${VERSION}`);
63
- const { server } = await createMcpServer(args, {
63
+ const server = await McpServer.from(args, {
64
64
  logFile,
65
65
  });
66
66
  const transport = new StdioServerTransport();
@@ -68,5 +68,5 @@ await server.connect(transport);
68
68
  logger?.('Chrome DevTools MCP Server connected');
69
69
  logDisclaimers(args);
70
70
  void ClearcutLogger.get()?.logDailyActiveIfNeeded();
71
- void ClearcutLogger.get()?.logServerStart(computeFlagUsage(args, cliOptions));
71
+ void ClearcutLogger.get()?.logServerStart(computeFlagUsage(args, mcpOptions));
72
72
  //# sourceMappingURL=chrome-devtools-mcp-main.js.map