chrome-devtools-mcp 1.10.1 → 1.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/build/src/BrowserManager.js +132 -13
  2. package/build/src/McpContext.js +188 -138
  3. package/build/src/McpPage.js +348 -96
  4. package/build/src/McpResponse.js +234 -76
  5. package/build/src/McpWorker.js +66 -0
  6. package/build/src/SlimMcpResponse.js +5 -1
  7. package/build/src/TextSnapshot.js +3 -2
  8. package/build/src/ToolHandler.js +80 -42
  9. package/build/src/bin/chrome-devtools-mcp-main.js +8 -7
  10. package/build/src/bin/chrome-devtools-mcp.js +1 -1
  11. package/build/src/bin/chrome-devtools.js +31 -41
  12. package/build/src/collectors/ServiceWorkerCollector.js +18 -11
  13. package/build/src/config/ConfigLocator.js +70 -0
  14. package/build/src/config/ConfigParser.js +264 -0
  15. package/build/src/config/ConfigWatcher.js +93 -0
  16. package/build/src/config/browser-options.js +2 -13
  17. package/build/src/config/category-options.js +15 -30
  18. package/build/src/config/cli-commands.js +165 -5
  19. package/build/src/config/cli-options.js +410 -43
  20. package/build/src/config/mcp-options.js +156 -234
  21. package/build/src/config/puppeteer-options.js +65 -0
  22. package/build/src/config/tool-options.js +60 -0
  23. package/build/src/daemon/client.js +81 -41
  24. package/build/src/daemon/daemon.js +55 -45
  25. package/build/src/daemon/utils.js +44 -11
  26. package/build/src/devtools/DevToolsCommentBridge.js +43 -6
  27. package/build/src/devtools/DevtoolsUtils.js +3 -3
  28. package/build/src/devtools/McpHostBindingAdapter.js +0 -1
  29. package/build/src/formatters/CommentFormatter.js +4 -13
  30. package/build/src/formatters/ConsoleFormatter.js +1 -1
  31. package/build/src/formatters/CssFormatter.js +3 -2
  32. package/build/src/formatters/HeapSnapshotFormatter.js +104 -46
  33. package/build/src/formatters/IssueFormatter.js +33 -32
  34. package/build/src/formatters/NetworkFormatter.js +12 -11
  35. package/build/src/formatters/SnapshotFormatter.js +31 -4
  36. package/build/src/index.js +54 -9
  37. package/build/src/processors/ChunkedTraceParser.js +11 -11
  38. package/build/src/processors/HeapSnapshotManager.js +121 -84
  39. package/build/src/processors/PerformanceTrace.js +9 -9
  40. package/build/src/telemetry/ClearcutLogger.js +1 -1
  41. package/build/src/telemetry/transformation.js +7 -11
  42. package/build/src/telemetry/watchdog/main.js +1 -1
  43. package/build/src/third_party/THIRD_PARTY_NOTICES +10 -397
  44. package/build/src/third_party/bundled-packages.json +7 -8
  45. package/build/src/third_party/devtools-formatter-worker.js +1193 -62
  46. package/build/src/third_party/devtools-heap-snapshot-worker.js +1126 -21
  47. package/build/src/third_party/index.js +8087 -19419
  48. package/build/src/third_party/issue-descriptions/cookieWarnMetadataGrantRead.md +0 -1
  49. package/build/src/third_party/issue-descriptions/cookieWarnMetadataGrantReadOptOut.md +5 -0
  50. package/build/src/third_party/issue-descriptions/cookieWarnMetadataGrantSet.md +0 -1
  51. package/build/src/third_party/issue-descriptions/cookieWarnMetadataGrantSetOptOut.md +5 -0
  52. package/build/src/third_party/issue-descriptions/deprecation.md +1 -1
  53. package/build/src/third_party/issue-descriptions/genericGeolocationPromptWithoutUserGesture.md +5 -0
  54. package/build/src/third_party/issue-descriptions/sriValidationFailedIntegrityMismatch.md +2 -0
  55. package/build/src/third_party/lighthouse-devtools-mcp-bundle.js +3 -3
  56. package/build/src/tools/ToolDefinition.js +16 -4
  57. package/build/src/tools/comments.js +20 -1
  58. package/build/src/tools/css.js +4 -2
  59. package/build/src/tools/emulation.js +17 -4
  60. package/build/src/tools/input.js +8 -3
  61. package/build/src/tools/lighthouse.js +112 -4
  62. package/build/src/tools/memory.js +129 -28
  63. package/build/src/tools/pages.js +5 -2
  64. package/build/src/tools/performance.js +21 -3
  65. package/build/src/tools/screencast.js +71 -32
  66. package/build/src/tools/screenshot.js +29 -14
  67. package/build/src/tools/script.js +90 -37
  68. package/build/src/tools/slim/tools.js +6 -8
  69. package/build/src/tools/thirdPartyDeveloper.js +6 -4
  70. package/build/src/tools/tools.js +35 -22
  71. package/build/src/tools/webmcp.js +9 -6
  72. package/build/src/types.js +11 -0
  73. package/build/src/utils/WaitForHelper.js +14 -1
  74. package/build/src/utils/check-for-updates.js +1 -1
  75. package/build/src/utils/errorHandling.js +20 -0
  76. package/build/src/utils/logger.js +15 -5
  77. package/build/src/utils/text.js +15 -0
  78. package/build/src/utils/url.js +99 -3
  79. package/build/src/version.js +1 -1
  80. package/package.json +14 -10
  81. package/skills/a11y-debugging/SKILL.md +4 -4
  82. package/skills/chrome-devtools/SKILL.md +2 -2
  83. package/skills/chrome-devtools-cli/SKILL.md +18 -15
  84. package/skills/cookie-debugging/SKILL.md +8 -5
  85. package/skills/debug-optimize-lcp/SKILL.md +1 -1
  86. package/skills/troubleshooting/SKILL.md +5 -6
@@ -295,7 +295,7 @@ function formatAsyncFragment(fragment, formatter) {
295
295
  }
296
296
  const separatorLineLength = 40;
297
297
  const prefix = `--- ${fragment.description || 'async'} `;
298
- const separator = prefix + '-'.repeat(separatorLineLength - prefix.length);
298
+ const separator = prefix + '-'.repeat(Math.max(0, separatorLineLength - prefix.length));
299
299
  return [separator, ...formattedFrames];
300
300
  }
301
301
  function formatFrame(frame) {
@@ -133,8 +133,9 @@ function createContainerQueryAncestor(containerQuery, containerDetails) {
133
133
  };
134
134
  }
135
135
  /**
136
- * Collects enclosing ancestor rules (@media, @container, @supports, @layer,
137
- * @scope, @starting-style, @navigation, and CSS nesting) for a style rule.
136
+ * Collects enclosing ancestor rules (`@media`, `@container`, `@supports`,
137
+ * `@layer`, `@scope`, `@starting-style`, `@navigation`, and CSS nesting) for a
138
+ * style rule.
138
139
  */
139
140
  function collectAncestorRules(rule, containerDetails) {
140
141
  if (!rule.ruleTypes || rule.ruleTypes.length === 0) {
@@ -4,8 +4,50 @@
4
4
  * SPDX-License-Identifier: Apache-2.0
5
5
  */
6
6
  import { DevTools } from '../third_party/index.js';
7
- import { stableIdSymbol } from '../utils/id.js';
8
7
  const { formatBytesToKb } = DevTools.I18n.ByteUtilities;
8
+ export const MAX_NAME_LENGTH = 100;
9
+ /**
10
+ * Renders a name for single-line output: the name is truncated to
11
+ * `maxNameLength` and line breaks are always escaped.
12
+ */
13
+ export function formatName(name, options) {
14
+ return truncateValue(name, options.maxNameLength)
15
+ .replaceAll('\r', '\\r')
16
+ .replaceAll('\n', '\\n');
17
+ }
18
+ /**
19
+ * Truncates `value` to `maxLength`, appending an ellipsis if it was cut off.
20
+ */
21
+ function truncateValue(value, maxLength = MAX_NAME_LENGTH) {
22
+ if (value.length <= maxLength) {
23
+ return value;
24
+ }
25
+ return value.slice(0, maxLength) + '...';
26
+ }
27
+ /**
28
+ * Flattens the analysis into the contexts matching `options`, ranked descending
29
+ * by their dead-field retained-size score across all scopes.
30
+ */
31
+ export function collectRankedContexts(analysis, options = {}) {
32
+ const { min = 0, max } = options.retainedSize ?? {};
33
+ const contexts = [];
34
+ for (const scope of analysis.scopes) {
35
+ if (options.scopeInfoNodeId !== undefined &&
36
+ scope.scopeInfoNodeId !== options.scopeInfoNodeId) {
37
+ continue;
38
+ }
39
+ for (const context of scope.contexts) {
40
+ const score = context.deadFieldsRetainedSizeSum;
41
+ if (score < min || (max !== undefined && score > max)) {
42
+ continue;
43
+ }
44
+ contexts.push({ scope, context });
45
+ }
46
+ }
47
+ contexts.sort((left, right) => right.context.deadFieldsRetainedSizeSum -
48
+ left.context.deadFieldsRetainedSizeSum);
49
+ return contexts;
50
+ }
9
51
  export function isNodeLike(item) {
10
52
  return (typeof item === 'object' && item !== null && 'id' in item && 'name' in item);
11
53
  }
@@ -21,11 +63,7 @@ export function isEdgeLike(item) {
21
63
  'name' in item.node);
22
64
  }
23
65
  export class HeapSnapshotFormatter {
24
- #aggregates;
25
- constructor(aggregates) {
26
- this.#aggregates = aggregates;
27
- }
28
- static formatNodes(items) {
66
+ static formatNodes(items, options) {
29
67
  const lines = [];
30
68
  if (items.length > 0) {
31
69
  const firstItem = items[0];
@@ -38,19 +76,19 @@ export class HeapSnapshotFormatter {
38
76
  }
39
77
  for (const item of items) {
40
78
  if (isNodeLike(item)) {
41
- lines.push(`${item.id},${item.name},${item.type},${item.distance},${formatBytesToKb(item.selfSize)},${formatBytesToKb(item.retainedSize)}`);
79
+ lines.push(`${item.id},${formatName(item.name, options)},${item.type},${item.distance},${formatBytesToKb(item.selfSize)},${formatBytesToKb(item.retainedSize)}`);
42
80
  }
43
81
  else if (isEdgeLike(item)) {
44
- lines.push(`${item.name},${item.type},${item.node.id},${item.node.name},${formatBytesToKb(item.node.selfSize)},${formatBytesToKb(item.node.retainedSize)}`);
82
+ lines.push(`${formatName(item.name, options)},${item.type},${item.node.id},${formatName(item.node.name, options)},${formatBytesToKb(item.node.selfSize)},${formatBytesToKb(item.node.retainedSize)}`);
45
83
  }
46
84
  }
47
85
  return lines.join('\n');
48
86
  }
49
- static formatRetainingPaths(retainingPaths) {
87
+ static formatRetainingPaths(retainingPaths, options) {
50
88
  const lines = [];
51
89
  function formatEdge(edge, depth) {
52
90
  const indent = ' '.repeat(depth);
53
- lines.push(`${indent}<- @${edge.nodeId} ${edge.nodeName} via ${edge.edgeType} ${edge.edgeName} (distance: ${edge.distance})`);
91
+ lines.push(`${indent}<- @${edge.nodeId} ${formatName(edge.nodeName, options)} via ${edge.edgeType} ${formatName(edge.edgeName, options)} (distance: ${edge.distance})`);
54
92
  for (const child of edge.children) {
55
93
  formatEdge(child, depth + 1);
56
94
  }
@@ -60,30 +98,31 @@ export class HeapSnapshotFormatter {
60
98
  }
61
99
  return lines.join('\n');
62
100
  }
63
- static formatDominators(dominators) {
101
+ static formatDominators(dominators, options) {
64
102
  const lines = [];
65
103
  lines.push('nodeId,nodeName,selfSize,retainedSize');
66
104
  for (const node of dominators) {
67
- lines.push(`${node.nodeId},${node.nodeName},${formatBytesToKb(node.selfSize)},${formatBytesToKb(node.retainedSize)}`);
105
+ lines.push(`${node.nodeId},${formatName(node.nodeName, options)},${formatBytesToKb(node.selfSize)},${formatBytesToKb(node.retainedSize)}`);
68
106
  }
69
107
  return lines.join('\n');
70
108
  }
71
- static formatDuplicateStrings(groups) {
109
+ static formatDuplicateStrings(groups, options) {
72
110
  const lines = [];
73
111
  lines.push('value,count,totalSelfSize,totalRetainedSize,truncated,nodeIds');
74
112
  for (const group of groups) {
75
113
  const nodeIds = group.nodes.map(n => `@${n.id}`).join(' ');
76
114
  const truncated = group.truncated ?? false;
77
- lines.push(`${JSON.stringify(group.value)},${group.count},${formatBytesToKb(group.totalSelfSize)},${formatBytesToKb(group.totalRetainedSize)},${truncated},${nodeIds}`);
115
+ const displayValue = truncateValue(group.value, options.maxNameLength);
116
+ lines.push(`${JSON.stringify(displayValue)},${group.count},${formatBytesToKb(group.totalSelfSize)},${formatBytesToKb(group.totalRetainedSize)},${truncated},${nodeIds}`);
78
117
  }
79
118
  return lines.join('\n');
80
119
  }
81
- static formatNativeContextSizes(sizes) {
120
+ static formatNativeContextSizes(sizes, options) {
82
121
  const lines = [];
83
122
  lines.push('nodeId,nodeName,selfSize,retainedSize,attributedSize');
84
123
  const sortedContexts = [...sizes.nativeContexts].sort((a, b) => b.attributedSize - a.attributedSize);
85
124
  for (const nc of sortedContexts) {
86
- lines.push(`${nc.nodeId},${nc.nodeName},${formatBytesToKb(nc.selfSize)},${formatBytesToKb(nc.retainedSize)},${formatBytesToKb(nc.attributedSize)}`);
125
+ lines.push(`${nc.nodeId},${formatName(nc.nodeName, options)},${formatBytesToKb(nc.selfSize)},${formatBytesToKb(nc.retainedSize)},${formatBytesToKb(nc.attributedSize)}`);
87
126
  }
88
127
  lines.push(`Shared Size: ${formatBytesToKb(sizes.sharedSize)}`);
89
128
  lines.push(`Unattributed Size: ${formatBytesToKb(sizes.noAttributionSize)}`);
@@ -97,45 +136,28 @@ export class HeapSnapshotFormatter {
97
136
  lines.push(`Total size: ${formatBytesToKb(summary.totalSize)}`);
98
137
  return lines.join('\n');
99
138
  }
100
- #getSortedAggregates() {
101
- return Object.values(this.#aggregates).sort((a, b) => b.maxRet - a.maxRet);
102
- }
103
- toString() {
104
- const sorted = this.#getSortedAggregates();
139
+ static formatAggregates(aggregates, options) {
105
140
  const lines = [];
106
- lines.push('id,name,count,selfSize,retainedSize');
107
- for (const info of sorted) {
108
- const id = info[stableIdSymbol] ?? '';
109
- lines.push(`${id},${info.name},${info.count},${formatBytesToKb(info.self)},${formatBytesToKb(info.maxRet)}`);
141
+ lines.push('id,className,count,selfSize,retainedSize');
142
+ for (const info of aggregates) {
143
+ lines.push(`${info.id},${formatName(info.className, options)},${info.count},${formatBytesToKb(info.selfSize)},${formatBytesToKb(info.retainedSize)}`);
110
144
  }
111
145
  return lines.join('\n');
112
146
  }
113
- toJSON() {
114
- const sorted = this.#getSortedAggregates();
115
- return sorted.map(info => ({
116
- id: info[stableIdSymbol],
117
- className: info.name,
118
- count: info.count,
119
- selfSize: formatBytesToKb(info.self),
120
- retainedSize: formatBytesToKb(info.maxRet),
121
- }));
122
- }
123
- static sort(aggregates) {
124
- return Object.entries(aggregates).sort((a, b) => b[1].maxRet - a[1].maxRet);
125
- }
126
- static formatDiffSummary(diffs) {
147
+ static formatDiffSummary(diffs, options) {
127
148
  const lines = [];
128
149
  lines.push('index,className,addedCount,removedCount,countDelta,addedSize,removedSize,sizeDelta');
129
- let index = 0;
130
150
  for (const diff of diffs) {
131
- lines.push(`${index},${diff.className},${diff.addedCount},${diff.removedCount},${diff.countDelta},${formatBytesToKb(diff.addedSize)},${formatBytesToKb(diff.removedSize)},${formatBytesToKb(diff.sizeDelta)}`);
132
- index++;
151
+ lines.push(`${diff.index},${formatName(diff.className, options)},${diff.addedCount},${diff.removedCount},${diff.countDelta},${formatBytesToKb(diff.addedSize)},${formatBytesToKb(diff.removedSize)},${formatBytesToKb(diff.sizeDelta)}`);
133
152
  }
134
153
  return lines.join('\n');
135
154
  }
136
- static formatDiffDetails(diff) {
155
+ static formatDiffTotals(totals) {
156
+ return `Total: # new: ${totals.addedCount}, # deleted: ${totals.removedCount}, # delta: ${formatSignedCount(totals.countDelta)}, alloc size: ${formatSignedSize(totals.addedSize)}, freed size: ${formatSignedSize(totals.removedSize)}, size delta: ${formatSignedSize(totals.sizeDelta)}`;
157
+ }
158
+ static formatDiffDetails(diff, options) {
137
159
  const lines = [];
138
- lines.push(`${diff.className}: # new: ${diff.addedCount}, # deleted: ${diff.removedCount}, # delta: ${formatSignedCount(diff.countDelta)}, alloc size: ${formatSignedSize(diff.addedSize)}, freed size: ${formatSignedSize(diff.removedSize)}, size delta: ${formatSignedSize(diff.sizeDelta)}`);
160
+ lines.push(`${formatName(diff.className, options)}: # new: ${diff.addedCount}, # deleted: ${diff.removedCount}, # delta: ${formatSignedCount(diff.countDelta)}, alloc size: ${formatSignedSize(diff.addedSize)}, freed size: ${formatSignedSize(diff.removedSize)}, size delta: ${formatSignedSize(diff.sizeDelta)}`);
139
161
  const addedIds = diff.addedIds;
140
162
  const addedSelfSizes = diff.addedSelfSizes;
141
163
  const deletedIds = diff.deletedIds;
@@ -149,10 +171,10 @@ export class HeapSnapshotFormatter {
149
171
  }
150
172
  return lines.join('\n');
151
173
  }
152
- static formatObjectInfo(info) {
174
+ static formatObjectInfo(info, options) {
153
175
  const lines = [
154
176
  `id: @${info.id}`,
155
- `name: ${info.name}`,
177
+ `name: ${formatName(info.name, options)}`,
156
178
  `type: ${info.type}`,
157
179
  `detachedness: ${formatDOMLinkState(info.detachedness)}`,
158
180
  `selfSize: ${formatBytesToKb(info.selfSize)}`,
@@ -163,6 +185,42 @@ export class HeapSnapshotFormatter {
163
185
  ];
164
186
  return lines.join('\n');
165
187
  }
188
+ static formatContextAnalysis(report, options) {
189
+ const lines = [];
190
+ if (report.contexts.length === 0) {
191
+ lines.push('No live contexts with dead fields were found.');
192
+ }
193
+ for (const { scope, context } of report.contexts) {
194
+ if (lines.length > 0) {
195
+ lines.push('');
196
+ }
197
+ lines.push(`#### Context @${context.contextNodeId} in \`${formatScopeName(scope, options)}\` — ${formatBytesToKb(context.deadFieldsRetainedSizeSum)}`, `Script @${scope.scriptNodeId}, ScopeInfo @${scope.scopeInfoNodeId}, offsets ${scope.scopeStart}-${scope.scopeEnd}, ${formatCount(scope.contextFieldCount, 'context field')}`);
198
+ for (const field of context.deadFields) {
199
+ lines.push(`- \`${formatName(field.name, options)}\` (${formatName(field.valueName, options)} @${field.valueNodeId}) — ${formatBytesToKb(field.retainedSize)}`);
200
+ }
201
+ }
202
+ if (report.scriptsWithoutScopes.length > 0) {
203
+ lines.push('', 'Scripts without scope metadata could not be analyzed:');
204
+ for (const script of report.scriptsWithoutScopes) {
205
+ const scriptName = script.scriptName
206
+ ? formatName(script.scriptName, options)
207
+ : `script @${script.scriptNodeId}`;
208
+ lines.push(`- \`${scriptName}\` (@${script.scriptNodeId}) — ${formatCount(script.contextCount, 'context')}`);
209
+ }
210
+ }
211
+ return lines.join('\n');
212
+ }
213
+ }
214
+ function formatCount(count, singular) {
215
+ return `${count} ${singular}${count === 1 ? '' : 's'}`;
216
+ }
217
+ function formatScopeName(scope, options) {
218
+ const scriptName = scope.scriptName
219
+ ? formatName(scope.scriptName, options)
220
+ : `script @${scope.scriptNodeId}`;
221
+ return scope.scopeName
222
+ ? `${formatName(scope.scopeName, options)} (${scriptName})`
223
+ : scriptName;
166
224
  }
167
225
  function formatDOMLinkState(state) {
168
226
  switch (state) {
@@ -6,6 +6,8 @@
6
6
  import { ISSUE_UTILS } from '../devtools/issueDescriptions.js';
7
7
  import { DevTools } from '../third_party/index.js';
8
8
  import { logger } from '../utils/logger.js';
9
+ import { substitutePlaceholders } from '../utils/text.js';
10
+ const parsedDescriptionCache = new WeakMap();
9
11
  export class IssueFormatter {
10
12
  #issue;
11
13
  #options;
@@ -85,7 +87,7 @@ export class IssueFormatter {
85
87
  delete data.frameId;
86
88
  affectedResources.push({
87
89
  uid,
88
- data: data,
90
+ data,
89
91
  request,
90
92
  });
91
93
  }
@@ -94,53 +96,52 @@ export class IssueFormatter {
94
96
  isValid() {
95
97
  return this.#getTitle() !== undefined;
96
98
  }
97
- // Helper to extract title
98
- #getTitle() {
99
+ #getParsedDescription() {
100
+ const cached = parsedDescriptionCache.get(this.#issue);
101
+ if (cached) {
102
+ return cached;
103
+ }
99
104
  const markdownDescription = this.#issue.getDescription();
100
105
  const filename = markdownDescription?.file;
101
106
  if (!filename) {
102
107
  logger?.(`no description found for issue:` + this.#issue.code());
103
- return undefined;
108
+ const empty = {};
109
+ parsedDescriptionCache.set(this.#issue, empty);
110
+ return empty;
104
111
  }
105
- // We already have the description logic in #getDescription, but title extraction is separate
106
- // We can reuse the logic or cache it.
107
- // Ideally we should process markdown once.
108
112
  const rawMarkdown = ISSUE_UTILS.getIssueDescription(filename);
109
113
  if (!rawMarkdown) {
110
114
  logger?.(`no markdown ${filename} found for issue:` + this.#issue.code());
111
- return undefined;
115
+ const empty = {};
116
+ parsedDescriptionCache.set(this.#issue, empty);
117
+ return empty;
112
118
  }
113
119
  try {
114
- const processedMarkdown = DevTools.MarkdownIssueDescription.substitutePlaceholders(rawMarkdown, markdownDescription?.substitutions);
115
- const markdownAst = DevTools.Marked.Marked.lexer(processedMarkdown);
116
- const title = DevTools.MarkdownIssueDescription.findTitleFromMarkdownAst(markdownAst);
117
- if (!title) {
118
- logger?.('cannot read issue title from ' + filename);
119
- return undefined;
120
- }
121
- return title;
120
+ const description = DevTools.MarkdownIssueDescription.createIssueDescriptionFromRawMarkdown(rawMarkdown, {
121
+ file: filename,
122
+ links: markdownDescription?.links || [],
123
+ substitutions: markdownDescription?.substitutions,
124
+ });
125
+ const parsed = {
126
+ title: description.title,
127
+ description: substitutePlaceholders(rawMarkdown, markdownDescription?.substitutions),
128
+ };
129
+ parsedDescriptionCache.set(this.#issue, parsed);
130
+ return parsed;
122
131
  }
123
132
  catch {
124
133
  logger?.('error parsing markdown for issue ' + this.#issue.code());
125
- return undefined;
134
+ const empty = {};
135
+ parsedDescriptionCache.set(this.#issue, empty);
136
+ return empty;
126
137
  }
127
138
  }
139
+ // Helper to extract title
140
+ #getTitle() {
141
+ return this.#getParsedDescription().title;
142
+ }
128
143
  #getDescription() {
129
- const markdownDescription = this.#issue.getDescription();
130
- const filename = markdownDescription?.file;
131
- if (!filename) {
132
- return undefined;
133
- }
134
- const rawMarkdown = ISSUE_UTILS.getIssueDescription(filename);
135
- if (!rawMarkdown) {
136
- return undefined;
137
- }
138
- try {
139
- return DevTools.MarkdownIssueDescription.substitutePlaceholders(rawMarkdown, markdownDescription?.substitutions);
140
- }
141
- catch {
142
- return undefined;
143
- }
144
+ return this.#getParsedDescription().description;
144
145
  }
145
146
  }
146
147
  function convertIssueConciseToString(issue) {
@@ -49,13 +49,11 @@ export class NetworkFormatter {
49
49
  this.#requestBody = requestBodyNotAvailableMessage;
50
50
  }
51
51
  }
52
+ else if (data) {
53
+ this.#requestBody = getSizeLimitedString(data, BODY_CONTEXT_SIZE_LIMIT);
54
+ }
52
55
  else {
53
- if (data) {
54
- this.#requestBody = getSizeLimitedString(data, BODY_CONTEXT_SIZE_LIMIT);
55
- }
56
- else {
57
- this.#requestBody = requestBodyNotAvailableMessage;
58
- }
56
+ this.#requestBody = requestBodyNotAvailableMessage;
59
57
  }
60
58
  }
61
59
  // Load Response Body
@@ -63,18 +61,21 @@ export class NetworkFormatter {
63
61
  if (response) {
64
62
  const responseBodyNotAvailableMessage = '<Response body not available anymore>';
65
63
  if (this.#options.responseFilePath) {
64
+ let buffer;
66
65
  try {
67
- const buffer = await response.buffer();
66
+ buffer = await response.buffer();
67
+ }
68
+ catch {
69
+ // Response body is not available anymore
70
+ }
71
+ if (buffer) {
68
72
  if (!this.#options.saveFile) {
69
73
  throw new Error('Unable to save the response body to a file: no saveFile callback was configured.');
70
74
  }
71
75
  const result = await this.#options.saveFile(buffer, this.#options.responseFilePath, '.network-response');
72
76
  this.#responseBodyFilePath = result.filename;
73
77
  }
74
- catch {
75
- // Flatten error handling for buffer() failure and save failure
76
- }
77
- if (!this.#responseBodyFilePath) {
78
+ else {
78
79
  this.#responseBody = responseBodyNotAvailableMessage;
79
80
  }
80
81
  }
@@ -34,11 +34,28 @@ Get a verbose snapshot to include all elements if you are interested in the sele
34
34
  : '') +
35
35
  '\n';
36
36
  chunks.push(line);
37
- for (const child of node.children) {
38
- chunks.push(this.#formatNode(child, depth + 1));
37
+ if (!this.#hasRedundantTextChildren(node)) {
38
+ for (const child of node.children) {
39
+ chunks.push(this.#formatNode(child, depth + 1));
40
+ }
39
41
  }
40
42
  return chunks.join('');
41
43
  }
44
+ #hasRedundantTextChildren(node) {
45
+ if (this.#snapshot.verbose || !node.name || node.children.length === 0) {
46
+ return false;
47
+ }
48
+ let text = '';
49
+ for (const child of node.children) {
50
+ if (child.role !== 'StaticText' ||
51
+ child.children.length !== 0 ||
52
+ child.id === this.#snapshot.selectedElementUid) {
53
+ return false;
54
+ }
55
+ text += child.name ?? '';
56
+ }
57
+ return stripWhitespace(text) === stripWhitespace(node.name);
58
+ }
42
59
  #nodeToJSON(node) {
43
60
  const rawAttrs = this.#getAttributesMap(node);
44
61
  const children = node.children.map(child => this.#nodeToJSON(child));
@@ -50,7 +67,8 @@ Get a verbose snapshot to include all elements if you are interested in the sele
50
67
  }
51
68
  #getAttributes(serializedAXNodeRoot) {
52
69
  const attributes = [`uid=${serializedAXNodeRoot.id}`];
53
- if (serializedAXNodeRoot.role) {
70
+ if (serializedAXNodeRoot.role &&
71
+ serializedAXNodeRoot.role !== 'StaticText') {
54
72
  attributes.push(serializedAXNodeRoot.role === 'none'
55
73
  ? 'ignored'
56
74
  : serializedAXNodeRoot.role);
@@ -60,15 +78,21 @@ Get a verbose snapshot to include all elements if you are interested in the sele
60
78
  }
61
79
  const simpleAttrs = this.#getAttributesMap(serializedAXNodeRoot,
62
80
  /* excludeSpecial */ true);
81
+ const isOption = serializedAXNodeRoot.role === 'option';
63
82
  for (const attr of Object.keys(serializedAXNodeRoot).sort()) {
64
83
  if (excludedAttributes.has(attr)) {
65
84
  continue;
66
85
  }
67
86
  const mapped = booleanPropertyMap[attr];
68
- if (mapped && simpleAttrs[mapped]) {
87
+ if (mapped &&
88
+ simpleAttrs[mapped] &&
89
+ !(isOption && mapped === 'selectable')) {
69
90
  attributes.push(mapped);
70
91
  }
71
92
  const val = simpleAttrs[attr];
93
+ if (isOption && attr === 'value' && val === serializedAXNodeRoot.name) {
94
+ continue;
95
+ }
72
96
  if (val === true) {
73
97
  attributes.push(attr);
74
98
  }
@@ -132,4 +156,7 @@ const excludedAttributes = new Set([
132
156
  'backendNodeId',
133
157
  'loaderId',
134
158
  ]);
159
+ function stripWhitespace(text) {
160
+ return text.replace(/\s+/g, '');
161
+ }
135
162
  //# sourceMappingURL=SnapshotFormatter.js.map
@@ -8,10 +8,12 @@ import { pathToFileURL } from 'node:url';
8
8
  import { BrowserManager } from './BrowserManager.js';
9
9
  import { loadIssueDescriptions } from './devtools/issueDescriptions.js';
10
10
  import { McpContext } from './McpContext.js';
11
+ import { HeapSnapshotManager } from './processors/HeapSnapshotManager.js';
11
12
  import { ClearcutLogger } from './telemetry/ClearcutLogger.js';
12
13
  import { FilePersistence } from './telemetry/persistence.js';
13
14
  import { McpServer as SdkMcpServer, Mutex, puppeteer, } from './third_party/index.js';
14
15
  import { ToolHandler } from './ToolHandler.js';
16
+ import { isAvailableInMode, } from './tools/ToolDefinition.js';
15
17
  import { createTools } from './tools/tools.js';
16
18
  import { logger } from './utils/logger.js';
17
19
  import { VERSION } from './version.js';
@@ -30,6 +32,7 @@ export class McpServer {
30
32
  #serverArgs;
31
33
  #browserManager;
32
34
  #context;
35
+ #heapSnapshotManager = new HeapSnapshotManager();
33
36
  /**
34
37
  * Client roots stay valid across browser reconnects and only the client can
35
38
  * invalidate them through a `roots/list_changed` notification. CLI-configured
@@ -37,6 +40,7 @@ export class McpServer {
37
40
  */
38
41
  #lastClientRoots;
39
42
  #toolMutex = new Mutex();
43
+ #tools = new Map();
40
44
  constructor(serverArgs, options) {
41
45
  this.#serverArgs = serverArgs;
42
46
  this.#browserManager = options.browserManager;
@@ -54,7 +58,11 @@ export class McpServer {
54
58
  name: 'chrome_devtools',
55
59
  title: 'Chrome DevTools MCP server',
56
60
  version: VERSION,
57
- }, { capabilities: { logging: {} } });
61
+ }, {
62
+ capabilities: { logging: {}, tools: { listChanged: true } },
63
+ // Enabling or updating many tools at once sends a single notification.
64
+ debouncedNotificationMethods: ['notifications/tools/list_changed'],
65
+ });
58
66
  this.server.server.setRequestHandler('logging/setLevel', () => {
59
67
  return {};
60
68
  });
@@ -72,7 +80,7 @@ export class McpServer {
72
80
  else if (!this.#serverArgs.allowUnrestrictedPaths &&
73
81
  (this.#serverArgs.filesystemRoot ?? []).length === 0) {
74
82
  console.warn('[chrome-devtools-mcp] The connecting client did not negotiate the MCP roots ' +
75
- 'capability. File-writing tools will be restricted to the OS temp directory. ' +
83
+ 'capability. Tools that read or write local files will be restricted to the OS temp directory. ' +
76
84
  'To restore the previous unrestricted behavior, start the server with ' +
77
85
  '--allow-unrestricted-paths.');
78
86
  }
@@ -81,6 +89,35 @@ export class McpServer {
81
89
  async connect(transport) {
82
90
  return await this.server.connect(transport);
83
91
  }
92
+ async callTool(name, args = {}) {
93
+ const toolHandler = this.#tools.get(name)?.handler;
94
+ if (!toolHandler) {
95
+ return {
96
+ content: [
97
+ {
98
+ type: 'text',
99
+ text: `Tool ${name} not found`,
100
+ },
101
+ ],
102
+ isError: true,
103
+ };
104
+ }
105
+ const parseResult = await toolHandler.registeredInputSchema.safeParseAsync(args);
106
+ if (!parseResult.success) {
107
+ return {
108
+ content: [
109
+ {
110
+ type: 'text',
111
+ text: `Input validation error: Invalid arguments for tool ${name}: ${parseResult.error.issues
112
+ .map(issue => `${issue.path.length > 0 ? `${issue.path.join('.')}: ` : ''}${issue.message}`)
113
+ .join(', ')}`,
114
+ },
115
+ ],
116
+ isError: true,
117
+ };
118
+ }
119
+ return await toolHandler.handle(parseResult.data);
120
+ }
84
121
  /**
85
122
  * Closes the MCP connection and disposes internal context/listeners.
86
123
  */
@@ -94,6 +131,7 @@ export class McpServer {
94
131
  finally {
95
132
  this.#context = undefined;
96
133
  }
134
+ this.#heapSnapshotManager.dispose();
97
135
  await Promise.allSettled([
98
136
  this.#browserManager.close(),
99
137
  this.server.close(),
@@ -113,9 +151,11 @@ export class McpServer {
113
151
  return server;
114
152
  }
115
153
  async #init() {
116
- const tools = createTools(this.#serverArgs);
117
- for (const tool of tools) {
118
- this.#registerTool(tool);
154
+ for (const tool of createTools(this.#serverArgs)) {
155
+ // Slim and regular tools may share names, only register the current mode.
156
+ if (isAvailableInMode(tool, this.#serverArgs)) {
157
+ this.#registerTool(tool);
158
+ }
119
159
  }
120
160
  await loadIssueDescriptions();
121
161
  }
@@ -167,6 +207,7 @@ export class McpServer {
167
207
  // Surfaces a one-time note in the next response after a reconnect.
168
208
  reconnected: this.#context !== undefined,
169
209
  categoryExtensions: this.#serverArgs.categoryExtensions,
210
+ heapSnapshotManager: this.#heapSnapshotManager,
170
211
  onNotification: (message) => {
171
212
  void this.server
172
213
  .sendLoggingMessage({
@@ -192,16 +233,20 @@ export class McpServer {
192
233
  }
193
234
  return this.#context;
194
235
  }
236
+ #createToolHandler(tool) {
237
+ return new ToolHandler(tool, this.#serverArgs, () => this.#getContext(), this.#toolMutex, () => this.#browserManager.abandonPendingAttempt());
238
+ }
195
239
  #registerTool(tool) {
196
- const toolHandler = new ToolHandler(tool, this.#serverArgs, () => this.#getContext(), this.#toolMutex);
240
+ const handler = this.#createToolHandler(tool);
197
241
  const registeredTool = this.server.registerTool(tool.name, {
198
242
  description: tool.description,
199
- inputSchema: toolHandler.registeredInputSchema,
243
+ inputSchema: handler.registeredInputSchema,
200
244
  annotations: tool.annotations,
201
- }, toolHandler.handle);
202
- if (toolHandler.disabled) {
245
+ }, handler.handle);
246
+ if (handler.disabled) {
203
247
  registeredTool.disable();
204
248
  }
249
+ this.#tools.set(tool.name, { handler, registeredTool });
205
250
  }
206
251
  }
207
252
  /**