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
@@ -55,6 +55,13 @@ var __disposeResources = (this && this.__disposeResources) || (function (Suppres
55
55
  var e = new Error(message);
56
56
  return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
57
57
  });
58
+ import { DevToolsCommentBridge } from './devtools/DevToolsCommentBridge.js';
59
+ import { createTargetUniverse, } from './devtools/DevtoolsUtils.js';
60
+ import { ConsoleCollector, NetworkCollector, } from './collectors/PageCollector.js';
61
+ import { TextSnapshot } from './TextSnapshot.js';
62
+ import { PredefinedNetworkConditions, DevTools, lighthouseNavigation, lighthouseSnapshot, } from './third_party/index.js';
63
+ import { logger } from './utils/logger.js';
64
+ import { getNetworkMultiplierFromString, WaitForHelper, } from './utils/WaitForHelper.js';
58
65
  export function replaceHtmlElementsWithUids(schema) {
59
66
  if (typeof schema === 'boolean') {
60
67
  return;
@@ -101,15 +108,25 @@ export function replaceHtmlElementsWithUids(schema) {
101
108
  }
102
109
  }
103
110
  }
104
- import { DevToolsCommentBridge } from './devtools/DevToolsCommentBridge.js';
105
- import { createTargetUniverse, } from './devtools/DevtoolsUtils.js';
106
- import { ConsoleCollector, NetworkCollector, } from './collectors/PageCollector.js';
107
- import { TextSnapshot } from './TextSnapshot.js';
108
- import { PredefinedNetworkConditions, DevTools, } from './third_party/index.js';
111
+ function isDebuggingWebMcpTool(tool) {
112
+ return Boolean(tool.annotations &&
113
+ 'debugging' in tool.annotations &&
114
+ tool.annotations.debugging === true);
115
+ }
109
116
  const DEFAULT_TIMEOUT = 5_000;
110
117
  const NAVIGATION_TIMEOUT = 10_000;
111
- import { logger } from './utils/logger.js';
112
- import { getNetworkMultiplierFromString, WaitForHelper, } from './utils/WaitForHelper.js';
118
+ /**
119
+ * Chrome reports a URL-derived placeholder as the target title until the
120
+ * document provides one. The placeholder omits the `http://` / `https://`
121
+ * scheme and the trailing slash of a bare hostname.
122
+ */
123
+ function isPlaceholderTitle(title, url) {
124
+ if (title === url) {
125
+ return true;
126
+ }
127
+ const withoutScheme = url.replace(/^https?:\/\//, '');
128
+ return title === withoutScheme || title === withoutScheme.replace(/\/$/, '');
129
+ }
113
130
  function isBackendNodeId(id) {
114
131
  return typeof id === 'number';
115
132
  }
@@ -119,11 +136,16 @@ function isBackendNodeId(id) {
119
136
  *
120
137
  * Internal class consumed only by McpContext. Fields are public for direct
121
138
  * read/write access. The dialog field is private because it requires an
122
- * event listener lifecycle managed by the constructor/dispose pair.
139
+ * event listener lifecycle managed by the init/dispose pair.
123
140
  */
124
141
  export class McpPage {
125
- pptrPage;
142
+ target;
126
143
  id;
144
+ #pptrPage;
145
+ #initPromise;
146
+ #focusEmulationRequested = false;
147
+ #disposed = false;
148
+ #closed = false;
127
149
  // Snapshot
128
150
  textSnapshot = null;
129
151
  uniqueBackendNodeIdToMcpId = new Map();
@@ -136,52 +158,151 @@ export class McpPage {
136
158
  // Dialog
137
159
  #dialog;
138
160
  #dialogHandler;
139
- thirdPartyDeveloperTools = [];
140
- networkCollector;
141
- consoleCollector;
142
- #hasNetworkBlockOrAllowlist;
161
+ // Screencast
162
+ #screenRecorder = null;
163
+ // Performance trace
164
+ #isRunningPerformanceTrace = false;
165
+ #networkCollector;
166
+ #consoleCollector;
143
167
  #locatorClass;
144
168
  #navigationTimeout;
145
- #sourceMaps;
169
+ #config;
146
170
  #commentBridge;
147
- #onNotification;
148
- constructor(page, id, options) {
149
- this.#hasNetworkBlockOrAllowlist = options.hasNetworkBlockOrAllowlist;
171
+ constructor(target, id, options) {
172
+ this.#config = options.config;
150
173
  this.#locatorClass = options.locatorClass;
151
174
  this.#navigationTimeout = options.navigationTimeout ?? NAVIGATION_TIMEOUT;
152
- this.#sourceMaps = options.sourceMaps ?? true;
153
- this.#onNotification = options.onNotification;
154
- this.pptrPage = page;
175
+ this.target = target;
155
176
  this.id = id;
156
177
  this.isolatedContextName = options.isolatedContextName;
157
178
  this.#dialogHandler = (dialog) => {
158
179
  this.#dialog = dialog;
159
180
  };
160
- page.on('dialog', this.#dialogHandler);
161
- this.networkCollector = new NetworkCollector(page);
162
- this.consoleCollector = new ConsoleCollector(page, collect => {
163
- return {
164
- console: event => {
165
- collect(event);
166
- },
167
- uncaughtError: event => {
168
- collect(event);
169
- },
170
- devtoolsAggregatedIssue: event => {
171
- collect(event);
172
- },
173
- };
174
- });
175
181
  }
176
- async init() {
177
- await Promise.allSettled([
178
- this.#initDevToolsUniverseNoThrow(),
179
- this.#initFocusEmulationNoThrow(),
180
- ]);
182
+ get #hasNetworkBlockOrAllowlist() {
183
+ return Boolean(this.#config.resolved.allowedUrlPattern ||
184
+ this.#config.resolved.blockedUrlPattern);
185
+ }
186
+ get pptrPage() {
187
+ if (!this.#pptrPage) {
188
+ throw new Error(`McpPage (id=${this.id}) is not initialized. Call init() first.`);
189
+ }
190
+ return this.#pptrPage;
191
+ }
192
+ get networkCollector() {
193
+ if (!this.#networkCollector) {
194
+ throw new Error(`McpPage (id=${this.id}) is not initialized. Call init() first.`);
195
+ }
196
+ return this.#networkCollector;
197
+ }
198
+ set networkCollector(collector) {
199
+ this.#networkCollector = collector;
200
+ }
201
+ get consoleCollector() {
202
+ if (!this.#consoleCollector) {
203
+ throw new Error(`McpPage (id=${this.id}) is not initialized. Call init() first.`);
204
+ }
205
+ return this.#consoleCollector;
206
+ }
207
+ url() {
208
+ return this.#pptrPage?.url() ?? this.target.url();
209
+ }
210
+ get targetId() {
211
+ // @ts-expect-error internal types
212
+ const info = this.target._getTargetInfo();
213
+ return info.targetId;
214
+ }
215
+ /**
216
+ * Returns the page title or an empty string if the target only has Chrome's
217
+ * URL-based placeholder title.
218
+ *
219
+ * Puppeteer's cached target info is only refreshed by
220
+ * `Target.targetInfoChanged`, which Chrome emits on navigation commit (before
221
+ * the document title is known) but not on title changes. Callers should pass
222
+ * fresh target info (e.g., from `Target.getTargets`) when available.
223
+ */
224
+ getTitle(freshTargetInfo) {
225
+ // @ts-expect-error internal types
226
+ const cachedInfo = this.target._getTargetInfo();
227
+ const info = freshTargetInfo ?? cachedInfo;
228
+ return isPlaceholderTitle(info.title, info.url) ? '' : info.title;
229
+ }
230
+ isClosed() {
231
+ if (this.#closed) {
232
+ return true;
233
+ }
234
+ if (this.#pptrPage) {
235
+ return this.#pptrPage.isClosed();
236
+ }
237
+ return this.#disposed;
238
+ }
239
+ async close() {
240
+ this.#closed = true;
241
+ const page = this.#pptrPage ??
242
+ (await this.target.page()) ??
243
+ (await this.target.asPage());
244
+ this.dispose();
245
+ await page?.close({ runBeforeUnload: false });
181
246
  }
182
- async #initFocusEmulationNoThrow() {
183
- // We emulate a focused page for all pages to support multi-agent workflows.
247
+ async init(options) {
248
+ if (this.#disposed) {
249
+ throw new Error(`McpPage (id=${this.id}) has already been disposed.`);
250
+ }
251
+ if (!this.#initPromise) {
252
+ this.#initPromise = this.#doInit().catch(err => {
253
+ this.#initPromise = undefined;
254
+ throw err;
255
+ });
256
+ }
257
+ await this.#initPromise;
258
+ // Discovery skips focus emulation, but a later page tool still needs it.
259
+ if (options?.emulateFocus !== false &&
260
+ !this.#disposed &&
261
+ !this.#focusEmulationRequested) {
262
+ // Prevent duplicate requests while pending and after success.
263
+ this.#focusEmulationRequested = true;
264
+ this.#initFocusEmulationNoThrow();
265
+ }
266
+ }
267
+ async #doInit() {
268
+ if (!this.#pptrPage) {
269
+ const page = (await this.target.page()) ?? (await this.target.asPage());
270
+ if (!page) {
271
+ throw new Error(`Failed to initialize Puppeteer Page for target ${this.target.url()}`);
272
+ }
273
+ if (this.#disposed) {
274
+ return;
275
+ }
276
+ this.#pptrPage = page;
277
+ page.on('dialog', this.#dialogHandler);
278
+ this.#networkCollector = new NetworkCollector(page, {
279
+ maxNavigationSaved: this.#config.resolved.maxNavigationSaved,
280
+ });
281
+ this.#consoleCollector = new ConsoleCollector(page, collect => {
282
+ return {
283
+ console: event => {
284
+ collect(event);
285
+ },
286
+ uncaughtError: event => {
287
+ collect(event);
288
+ },
289
+ devtoolsAggregatedIssue: event => {
290
+ collect(event);
291
+ },
292
+ };
293
+ }, { maxNavigationSaved: this.#config.resolved.maxNavigationSaved });
294
+ }
295
+ this.updateTimeouts();
296
+ await this.#initDevToolsUniverseNoThrow();
297
+ if (this.#disposed) {
298
+ this.dispose();
299
+ }
300
+ }
301
+ #initFocusEmulationNoThrow() {
302
+ // Background pages need emulated focus for multi-agent workflows.
184
303
  void this.pptrPage.emulateFocusedPage(true).catch(error => {
304
+ // Allow the next page operation to retry a transient failure.
305
+ this.#focusEmulationRequested = false;
185
306
  logger?.('Error turning on focused page emulation', error);
186
307
  });
187
308
  }
@@ -192,44 +313,88 @@ export class McpPage {
192
313
  try {
193
314
  const session = await this.pptrPage.createCDPSession();
194
315
  this.#devtoolsUniverse = await createTargetUniverse(session, {
195
- sourceMaps: this.#sourceMaps,
316
+ sourceMaps: this.#config.resolved.sourceMaps,
196
317
  });
197
318
  }
198
319
  catch (e) {
199
320
  logger?.('Failed to initialize DevTools universe', e);
200
321
  }
201
322
  }
323
+ syncSourceMaps() {
324
+ if (!this.#devtoolsUniverse) {
325
+ return;
326
+ }
327
+ const sourceMaps = this.#config.resolved.sourceMaps;
328
+ this.#devtoolsUniverse.universe.settings
329
+ .resolve(DevTools.SDKSettings.jsSourceMapsEnabledSettingDescriptor)
330
+ .set(sourceMaps);
331
+ this.#devtoolsUniverse.universe.settings
332
+ .resolve(DevTools.SDKSettings.cssSourceMapsEnabledSettingDescriptor)
333
+ .set(sourceMaps);
334
+ }
202
335
  get devtoolsUniverse() {
203
336
  return this.#devtoolsUniverse;
204
337
  }
205
338
  getDialog() {
339
+ if (this.#dialog?.handled) {
340
+ this.#dialog = undefined;
341
+ }
206
342
  return this.#dialog;
207
343
  }
208
344
  clearDialog() {
209
345
  this.#dialog = undefined;
210
346
  }
347
+ getScreenRecorder() {
348
+ return this.#screenRecorder;
349
+ }
350
+ setScreenRecorder(data) {
351
+ this.#screenRecorder = data;
352
+ }
353
+ isRunningPerformanceTrace() {
354
+ return this.#isRunningPerformanceTrace;
355
+ }
356
+ setIsRunningPerformanceTrace(x) {
357
+ this.#isRunningPerformanceTrace = x;
358
+ }
211
359
  throwIfDialogOpen() {
212
- if (this.#dialog && !this.#dialog.handled) {
213
- throw new Error(`A dialog is open (${this.#dialog.type()}: ${this.#dialog.message()}).`);
360
+ const dialog = this.getDialog();
361
+ if (dialog) {
362
+ throw new Error(`A dialog is open (${dialog.type()}: ${dialog.message()}).`);
214
363
  }
215
364
  }
216
- getThirdPartyDeveloperTools() {
217
- return this.thirdPartyDeveloperTools;
365
+ #getDebuggingWebMcpToolGroups() {
366
+ const webmcpTools = this.pptrPage.webmcp
367
+ .tools()
368
+ .filter(isDebuggingWebMcpTool);
369
+ if (webmcpTools.length === 0) {
370
+ return [];
371
+ }
372
+ return [
373
+ {
374
+ name: 'WebMCP Tools',
375
+ description: 'Tools exposed via WebMCP',
376
+ tools: webmcpTools.map(tool => ({
377
+ name: tool.name,
378
+ description: tool.description,
379
+ inputSchema: structuredClone(tool.inputSchema ?? {}),
380
+ })),
381
+ },
382
+ ];
218
383
  }
219
- async getToolGroups() {
384
+ async discoverThirdPartyDeveloperTools() {
220
385
  const env_1 = { stack: [], error: void 0, hasError: false };
221
386
  try {
222
387
  // Check if there is a `devtoolstooldiscovery` event listener
223
388
  const windowHandle = __addDisposableResource(env_1, await this.pptrPage.evaluateHandle(() => window), false);
224
389
  // @ts-expect-error internal API
225
390
  const client = this.pptrPage._client();
226
- const { listeners } = await client.send('DOMDebugger.getEventListeners', {
391
+ const { listeners = [] } = await client.send('DOMDebugger.getEventListeners', {
227
392
  objectId: windowHandle.remoteObject().objectId,
228
393
  });
229
394
  if (listeners.find(l => l.type === 'devtoolstooldiscovery') === undefined) {
230
- return [];
395
+ return this.#getDebuggingWebMcpToolGroups();
231
396
  }
232
- const toolGroups = await this.pptrPage.evaluate(() => {
397
+ const eventToolGroups = await this.pptrPage.evaluate(() => {
233
398
  if (window.__dtmcp) {
234
399
  window.__dtmcp.toolGroups = [];
235
400
  }
@@ -297,13 +462,12 @@ export class McpPage {
297
462
  }
298
463
  });
299
464
  });
300
- for (const group of toolGroups) {
465
+ for (const group of eventToolGroups) {
301
466
  for (const tool of group.tools ?? []) {
302
467
  replaceHtmlElementsWithUids(tool.inputSchema);
303
468
  }
304
469
  }
305
- this.thirdPartyDeveloperTools = toolGroups;
306
- return toolGroups;
470
+ return [...this.#getDebuggingWebMcpToolGroups(), ...eventToolGroups];
307
471
  }
308
472
  catch (e_1) {
309
473
  env_1.error = e_1;
@@ -314,7 +478,9 @@ export class McpPage {
314
478
  }
315
479
  }
316
480
  getWebMcpTools() {
317
- return this.pptrPage.webmcp.tools();
481
+ return this.pptrPage.webmcp
482
+ .tools()
483
+ .filter(tool => !isDebuggingWebMcpTool(tool));
318
484
  }
319
485
  resolveCdpRequestId(cdpRequestId) {
320
486
  if (!cdpRequestId) {
@@ -345,14 +511,20 @@ export class McpPage {
345
511
  get commentBridge() {
346
512
  return this.#commentBridge;
347
513
  }
514
+ disposeCommentBridge() {
515
+ this.#commentBridge?.dispose();
516
+ this.#commentBridge = undefined;
517
+ }
518
+ /**
519
+ * Returns the comment bridge attached to the DevTools page, or undefined if
520
+ * the DevTools page does not support DevTools comments.
521
+ */
348
522
  async ensureDevToolsCommentBridge(devtoolsPage) {
349
523
  if (!this.#commentBridge) {
350
- this.#commentBridge = new DevToolsCommentBridge({
351
- onNotification: this.#onNotification,
352
- });
524
+ this.#commentBridge = new DevToolsCommentBridge();
353
525
  }
354
- await this.#commentBridge.attach(devtoolsPage);
355
- return this.#commentBridge;
526
+ const attached = await this.#commentBridge.attach(devtoolsPage);
527
+ return attached ? this.#commentBridge : undefined;
356
528
  }
357
529
  async getDevToolsPage() {
358
530
  try {
@@ -370,7 +542,9 @@ export class McpPage {
370
542
  }
371
543
  async openDevTools() {
372
544
  const devtoolsPage = await this.pptrPage.openDevTools();
373
- await this.ensureDevToolsCommentBridge(devtoolsPage);
545
+ if (this.#config.resolved.devtoolsComments) {
546
+ await this.ensureDevToolsCommentBridge(devtoolsPage);
547
+ }
374
548
  return devtoolsPage;
375
549
  }
376
550
  getConsoleData(includePreservedMessages) {
@@ -400,6 +574,15 @@ export class McpPage {
400
574
  get colorScheme() {
401
575
  return this.emulationSettings.colorScheme ?? null;
402
576
  }
577
+ get forcedColors() {
578
+ return this.emulationSettings.forcedColors ?? null;
579
+ }
580
+ get prefersContrast() {
581
+ return this.emulationSettings.prefersContrast ?? null;
582
+ }
583
+ get prefersReducedMotion() {
584
+ return this.emulationSettings.prefersReducedMotion ?? null;
585
+ }
403
586
  // Public for testability: tests spy on this method to verify throttle multipliers.
404
587
  createWaitForHelper(cpuMultiplier, networkMultiplier) {
405
588
  return new WaitForHelper(this.pptrPage, cpuMultiplier, networkMultiplier);
@@ -409,11 +592,19 @@ export class McpPage {
409
592
  return helper.waitForEventsAfterAction(action, options);
410
593
  }
411
594
  dispose() {
412
- this.#commentBridge?.dispose();
413
- this.#commentBridge = undefined;
414
- this.pptrPage.off('dialog', this.#dialogHandler);
415
- this.networkCollector.dispose();
416
- this.consoleCollector.dispose();
595
+ this.#disposed = true;
596
+ this.#isRunningPerformanceTrace = false;
597
+ this.disposeCommentBridge();
598
+ if (this.#screenRecorder) {
599
+ const { recorder } = this.#screenRecorder;
600
+ this.#screenRecorder = null;
601
+ void recorder.stop().catch(e => {
602
+ logger?.('Failed to stop screencast recording on dispose', e);
603
+ });
604
+ }
605
+ this.#pptrPage?.off('dialog', this.#dialogHandler);
606
+ this.#networkCollector?.dispose();
607
+ this.#consoleCollector?.dispose();
417
608
  const devtoolsUniverse = this.#devtoolsUniverse;
418
609
  this.#devtoolsUniverse = undefined;
419
610
  devtoolsUniverse?.universe.dispose();
@@ -422,6 +613,23 @@ export class McpPage {
422
613
  });
423
614
  }
424
615
  async executeThirdPartyDeveloperTool(toolName, params, response) {
616
+ const webmcpTool = this.pptrPage.webmcp
617
+ .tools()
618
+ .find(t => t.name === toolName && isDebuggingWebMcpTool(t));
619
+ if (webmcpTool) {
620
+ const { status, output, errorText, exception } = await webmcpTool.execute(params);
621
+ if (status !== 'Completed') {
622
+ const error = exception?.description ?? exception?.value ?? errorText;
623
+ throw new Error(error ? String(error) : `Tool execution failed: ${status}`);
624
+ }
625
+ if (output !== undefined) {
626
+ response.appendResponseLine(JSON.stringify(output, null, 2));
627
+ }
628
+ else {
629
+ response.appendResponseLine('Tool returned no result.');
630
+ }
631
+ return;
632
+ }
425
633
  // Creates array of ElementHandles from the UIDs in the params.
426
634
  // We do not replace the uids with the ElementsHandles yet, because
427
635
  // the `evaluate` function only turns them into DOM elements if they
@@ -449,80 +657,111 @@ export class McpPage {
449
657
  throw new Error('No tools found on the page');
450
658
  }
451
659
  const toolResult = await window.__dtmcp.executeTool(name, args);
660
+ const stashedElements = [];
452
661
  const stashDOMElement = (el) => {
453
- if (!window.__dtmcp) {
454
- window.__dtmcp = {};
455
- }
456
- if (window.__dtmcp.stashedElements === undefined) {
457
- window.__dtmcp.stashedElements = [];
458
- }
459
- window.__dtmcp.stashedElements.push(el);
662
+ stashedElements.push(el);
460
663
  return {
461
- stashedId: `stashed-${window.__dtmcp.stashedElements.length - 1}`,
664
+ stashedId: `stashed-${stashedElements.length - 1}`,
462
665
  };
463
666
  };
464
- const ancestors = [];
667
+ const ancestors = new Set();
465
668
  // Recursively walks the tool result:
466
669
  // - Replaces DOM elements with an ID and stashes the DOM element on the window object
467
670
  // - Replaces non-plain objects with a string representation of the object
468
671
  // - Replaces circular references with the string '<Circular reference>'
469
672
  // - Replaces functions with the string '<Function object>'
470
- const processToolResult = (data, parentEl) => {
673
+ // - Replaces symbols and bigints with their string representation
674
+ const processToolResult = (data) => {
471
675
  // 1. Handle DOM Elements
472
676
  if (data instanceof Element) {
473
677
  return stashDOMElement(data);
474
678
  }
475
679
  // 2. Handle Arrays
476
680
  if (Array.isArray(data)) {
477
- return data.map((item) => processToolResult(item, parentEl));
681
+ if (ancestors.has(data)) {
682
+ return '<Circular reference>';
683
+ }
684
+ ancestors.add(data);
685
+ try {
686
+ return data.map((item) => processToolResult(item));
687
+ }
688
+ finally {
689
+ ancestors.delete(data);
690
+ }
478
691
  }
479
692
  // 3. Handle Objects
480
693
  if (data !== null && typeof data === 'object') {
481
- while (ancestors.length > 0 && ancestors.at(-1) !== parentEl) {
482
- ancestors.pop();
694
+ const proto = Object.getPrototypeOf(data);
695
+ // If not a plain object, return a string representation of the object
696
+ if (proto !== null && proto !== Object.prototype) {
697
+ return `<${data.constructor?.name || 'Object'} instance>`;
483
698
  }
484
- if (ancestors.includes(data)) {
699
+ if (ancestors.has(data)) {
485
700
  return '<Circular reference>';
486
701
  }
487
- ancestors.push(data);
488
- // If not a plain object, return a string representation of the object
489
- if (Object.getPrototypeOf(data) !== Object.prototype) {
490
- return `<${data.constructor.name} instance>`;
702
+ ancestors.add(data);
703
+ try {
704
+ const processedObj = {};
705
+ for (const [key, value] of Object.entries(data)) {
706
+ processedObj[key] = processToolResult(value);
707
+ }
708
+ return processedObj;
491
709
  }
492
- const processedObj = {};
493
- for (const [key, value] of Object.entries(data)) {
494
- processedObj[key] = processToolResult(value, data);
710
+ finally {
711
+ ancestors.delete(data);
495
712
  }
496
- return processedObj;
497
713
  }
498
714
  // 4. Handle Functions
499
715
  if (typeof data === 'function') {
500
716
  return '<Function object>';
501
717
  }
502
- // 5. Return primitives (strings, numbers, booleans) as-is
718
+ // 5. Handle Symbols and BigInts (not JSON/CDP-by-value serializable)
719
+ if (typeof data === 'symbol') {
720
+ return data.toString();
721
+ }
722
+ if (typeof data === 'bigint') {
723
+ return `${data.toString()}n`;
724
+ }
725
+ // 6. Return primitives (strings, numbers, booleans, undefined, null) as-is
503
726
  return data;
504
727
  };
728
+ const processed = processToolResult(toolResult);
729
+ const serialized = processed !== undefined ? JSON.stringify(processed) : undefined;
730
+ if (stashedElements.length > 0) {
731
+ window.__dtmcp.stashedElements = stashedElements;
732
+ }
505
733
  return {
506
- result: processToolResult(toolResult),
507
- stashed: window.__dtmcp?.stashedElements?.length ?? 0,
734
+ result: serialized,
735
+ stashed: stashedElements.length,
508
736
  };
509
737
  }, toolName, params, ...handles);
510
738
  const elementHandles = [];
511
- for (let i = 0; i < (result.stashed ?? 0); i++) {
512
- const elementHandle = await this.pptrPage.evaluateHandle(index => {
513
- const el = window.__dtmcp?.stashedElements?.[index];
514
- if (!el) {
515
- throw new Error(`Stashed element at index ${index} not found`);
739
+ if (result.stashed > 0) {
740
+ try {
741
+ for (let i = 0; i < result.stashed; i++) {
742
+ const elementHandle = await this.pptrPage.evaluateHandle(index => {
743
+ const el = window.__dtmcp?.stashedElements?.[index];
744
+ if (!el) {
745
+ throw new Error(`Stashed element at index ${index} not found`);
746
+ }
747
+ return el;
748
+ }, i);
749
+ elementHandles.push(elementHandle);
516
750
  }
517
- return el;
518
- }, i);
519
- elementHandles.push(elementHandle);
520
- }
521
- await this.pptrPage.evaluate(() => {
522
- if (window.__dtmcp) {
523
- window.__dtmcp.stashedElements = undefined;
524
751
  }
525
- });
752
+ finally {
753
+ try {
754
+ await this.pptrPage.evaluate(() => {
755
+ if (window.__dtmcp) {
756
+ window.__dtmcp.stashedElements = undefined;
757
+ }
758
+ });
759
+ }
760
+ catch (error) {
761
+ logger?.('Failed to clean up stashed elements', error);
762
+ }
763
+ }
764
+ }
526
765
  if (elementHandles.length) {
527
766
  const env_2 = { stack: [], error: void 0, hasError: false };
528
767
  try {
@@ -565,7 +804,7 @@ export class McpPage {
565
804
  typeof node.stashedId === 'string' &&
566
805
  node.stashedId.startsWith('stashed-') &&
567
806
  Object.keys(node).length === 1) {
568
- const index = parseInt(node.stashedId.split('-')[1]);
807
+ const index = parseInt(node.stashedId.split('-')[1], 10);
569
808
  return { uid: cdpElementIds[index] };
570
809
  }
571
810
  const resultObj = {};
@@ -576,8 +815,14 @@ export class McpPage {
576
815
  }
577
816
  return node;
578
817
  };
579
- const resultWithUids = recursivelyReplaceStashedElements(result.result);
580
- response.appendResponseLine(JSON.stringify(resultWithUids, null, 2));
818
+ if (result.result !== undefined) {
819
+ const parsedResult = JSON.parse(result.result);
820
+ const resultWithUids = recursivelyReplaceStashedElements(parsedResult);
821
+ response.appendResponseLine(JSON.stringify(resultWithUids, null, 2));
822
+ }
823
+ else {
824
+ response.appendResponseLine('Tool returned no result.');
825
+ }
581
826
  }
582
827
  async getElementByUid(uid) {
583
828
  if (!this.textSnapshot) {
@@ -587,7 +832,7 @@ export class McpPage {
587
832
  if (!node) {
588
833
  throw new Error(`Element uid "${uid}" not found on page ${this.id}.`);
589
834
  }
590
- return this.#resolveElementHandle(node, uid);
835
+ return await this.#resolveElementHandle(node, uid);
591
836
  }
592
837
  async #resolveElementHandle(node, uid) {
593
838
  const message = `Element with uid ${uid} no longer exists on the page.`;
@@ -608,18 +853,24 @@ export class McpPage {
608
853
  return this.textSnapshot?.idToNode.get(uid);
609
854
  }
610
855
  async resolveBackendNodeId(backendNodeId) {
611
- if (!this.textSnapshot) {
612
- this.textSnapshot = await TextSnapshot.create(this);
856
+ let id = this.textSnapshot?.resolveCdpElementId(backendNodeId);
857
+ if (id) {
858
+ return id;
613
859
  }
614
- let id = this.textSnapshot.resolveCdpElementId(backendNodeId);
615
- if (!id) {
616
- this.textSnapshot = await TextSnapshot.create(this);
860
+ this.textSnapshot = await TextSnapshot.create(this, {
861
+ verbose: this.textSnapshot?.verbose ?? false,
862
+ });
863
+ id = this.textSnapshot.resolveCdpElementId(backendNodeId);
864
+ if (!id && !this.textSnapshot.verbose) {
865
+ this.textSnapshot = await TextSnapshot.create(this, {
866
+ verbose: true,
867
+ });
617
868
  id = this.textSnapshot.resolveCdpElementId(backendNodeId);
618
869
  }
619
870
  return id;
620
871
  }
621
872
  async resolveUidToBackendNodeId(uid) {
622
- const target = this.pptrPage.target();
873
+ const target = this.target;
623
874
  const targetId = Boolean(target) &&
624
875
  '_targetId' in target &&
625
876
  typeof target._targetId === 'string'
@@ -686,6 +937,9 @@ export class McpPage {
686
937
  logger?.('No DevTools page detected');
687
938
  return {};
688
939
  }
940
+ if (this.#config.resolved.devtoolsComments) {
941
+ await this.ensureDevToolsCommentBridge(devtoolsPage);
942
+ }
689
943
  const { cdpRequestId, cdpBackendNodeId } = await devtoolsPage.evaluate(async () => {
690
944
  // @ts-expect-error no types
691
945
  const UI = await import('/bundled/ui/legacy/legacy.js');
@@ -707,8 +961,35 @@ export class McpPage {
707
961
  }
708
962
  async restoreEmulation() {
709
963
  const currentSetting = this.emulationSettings;
964
+ const { viewport } = currentSetting;
965
+ if (viewport) {
966
+ // Lighthouse's CDP session replaces the device metrics override and
967
+ // clears it on detach, and Chrome ignores an override identical to the
968
+ // last one this session sent. A different width first makes the real
969
+ // call take effect without a reload (`isMobile` and `hasTouch` stay the
970
+ // same). This also runs after snapshot audits and fires a resize event,
971
+ // so do not remove it as redundant.
972
+ await this.pptrPage.setViewport({
973
+ ...viewport,
974
+ width: Math.max(1, viewport.width - 1),
975
+ });
976
+ }
710
977
  await this.emulate(currentSetting);
711
978
  }
979
+ async #emulateMediaFeatures(settings) {
980
+ // `page.emulateMediaFeatures` replaces all previously emulated media
981
+ // features, so every supported feature is sent on each call. An empty
982
+ // value disables the override for that feature.
983
+ await this.pptrPage.emulateMediaFeatures([
984
+ { name: 'prefers-color-scheme', value: settings.colorScheme ?? '' },
985
+ { name: 'forced-colors', value: settings.forcedColors ?? '' },
986
+ { name: 'prefers-contrast', value: settings.prefersContrast ?? '' },
987
+ {
988
+ name: 'prefers-reduced-motion',
989
+ value: settings.prefersReducedMotion ?? '',
990
+ },
991
+ ]);
992
+ }
712
993
  async emulate(options) {
713
994
  const page = this.pptrPage;
714
995
  const newSettings = { ...this.emulationSettings };
@@ -756,7 +1037,7 @@ export class McpPage {
756
1037
  newSettings.cpuThrottlingRate = options.cpuThrottlingRate;
757
1038
  }
758
1039
  if (!options.geolocation) {
759
- await page.setGeolocation({ latitude: 0, longitude: 0 });
1040
+ await page.setGeolocation(null);
760
1041
  delete newSettings.geolocation;
761
1042
  }
762
1043
  else {
@@ -772,17 +1053,31 @@ export class McpPage {
772
1053
  newSettings.userAgent = options.userAgent;
773
1054
  }
774
1055
  if (!options.colorScheme || options.colorScheme === 'auto') {
775
- await page.emulateMediaFeatures([
776
- { name: 'prefers-color-scheme', value: '' },
777
- ]);
778
1056
  delete newSettings.colorScheme;
779
1057
  }
780
1058
  else {
781
- await page.emulateMediaFeatures([
782
- { name: 'prefers-color-scheme', value: options.colorScheme },
783
- ]);
784
1059
  newSettings.colorScheme = options.colorScheme;
785
1060
  }
1061
+ if (!options.forcedColors || options.forcedColors === 'auto') {
1062
+ delete newSettings.forcedColors;
1063
+ }
1064
+ else {
1065
+ newSettings.forcedColors = options.forcedColors;
1066
+ }
1067
+ if (!options.prefersContrast || options.prefersContrast === 'auto') {
1068
+ delete newSettings.prefersContrast;
1069
+ }
1070
+ else {
1071
+ newSettings.prefersContrast = options.prefersContrast;
1072
+ }
1073
+ if (!options.prefersReducedMotion ||
1074
+ options.prefersReducedMotion === 'auto') {
1075
+ delete newSettings.prefersReducedMotion;
1076
+ }
1077
+ else {
1078
+ newSettings.prefersReducedMotion = options.prefersReducedMotion;
1079
+ }
1080
+ await this.#emulateMediaFeatures(newSettings);
786
1081
  if (!options.viewport) {
787
1082
  delete newSettings.viewport;
788
1083
  }
@@ -802,13 +1097,39 @@ export class McpPage {
802
1097
  delete newSettings.extraHttpHeaders;
803
1098
  }
804
1099
  }
1100
+ const previousViewport = this.emulationSettings.viewport;
805
1101
  this.emulationSettings = Object.keys(newSettings).length ? newSettings : {};
806
1102
  this.updateTimeouts();
807
1103
  // This should happen after updating the page timeouts.
808
1104
  // Setting the viewport can trigger a reload which we don't want to timeout.
809
- await page.setViewport(newSettings.viewport ?? null);
1105
+ try {
1106
+ await page.setViewport(newSettings.viewport ?? null);
1107
+ }
1108
+ catch (error) {
1109
+ if (previousViewport) {
1110
+ newSettings.viewport = previousViewport;
1111
+ }
1112
+ else {
1113
+ delete newSettings.viewport;
1114
+ }
1115
+ this.emulationSettings = Object.keys(newSettings).length
1116
+ ? newSettings
1117
+ : {};
1118
+ throw error;
1119
+ }
1120
+ }
1121
+ async clearNetworkConditions() {
1122
+ if (!this.emulationSettings.networkConditions) {
1123
+ return;
1124
+ }
1125
+ await this.#pptrPage?.emulateNetworkConditions(null);
1126
+ delete this.emulationSettings.networkConditions;
1127
+ this.updateTimeouts();
810
1128
  }
811
1129
  updateTimeouts() {
1130
+ if (!this.#pptrPage) {
1131
+ return;
1132
+ }
812
1133
  // For waiters 5sec timeout should be sufficient.
813
1134
  // Increased in case we throttle the CPU
814
1135
  const cpuMultiplier = this.cpuThrottlingRate;
@@ -819,23 +1140,84 @@ export class McpPage {
819
1140
  const networkMultiplier = getNetworkMultiplierFromString(this.networkConditions);
820
1141
  this.pptrPage.setDefaultNavigationTimeout(this.#navigationTimeout * networkMultiplier * cpuMultiplier);
821
1142
  }
822
- waitForTextOnPage(text, timeout) {
823
- const frames = this.pptrPage.frames();
824
- let locator = this.#locatorClass.race(frames.flatMap(frame => text.flatMap(value => [
825
- frame.locator(`aria/${value}`),
826
- frame.locator(`text/${value}`),
827
- ])));
1143
+ waitForTextOnPage(text, options = {}) {
1144
+ const { timeout, visible } = options;
1145
+ const page = this.pptrPage;
1146
+ const initialFrames = page.frames();
1147
+ const observedFrames = new Set(initialFrames);
1148
+ const controller = new AbortController();
1149
+ const locatorForFrames = (frames) => this.#locatorClass.race(frames.flatMap(frame => text.flatMap(value => {
1150
+ const locators = [
1151
+ frame.locator(`aria/${value}`),
1152
+ frame.locator(`text/${value}`),
1153
+ ];
1154
+ return visible
1155
+ ? locators.map(locator => locator.setVisibility('visible'))
1156
+ : locators;
1157
+ })));
1158
+ let initialLocator = locatorForFrames(initialFrames);
828
1159
  if (timeout) {
829
- locator = locator.setTimeout(timeout);
1160
+ initialLocator = initialLocator.setTimeout(timeout);
830
1161
  }
831
- return locator.wait();
1162
+ return new Promise((resolve, reject) => {
1163
+ let settled = false;
1164
+ const cleanup = () => {
1165
+ if (settled) {
1166
+ return false;
1167
+ }
1168
+ settled = true;
1169
+ page.off('frameattached', onFrameAttached);
1170
+ controller.abort();
1171
+ return true;
1172
+ };
1173
+ const finish = (element) => {
1174
+ if (cleanup()) {
1175
+ resolve(element);
1176
+ }
1177
+ };
1178
+ const fail = (error) => {
1179
+ if (cleanup()) {
1180
+ reject(error);
1181
+ }
1182
+ };
1183
+ const onFrameAttached = (frame) => {
1184
+ if (observedFrames.has(frame)) {
1185
+ return;
1186
+ }
1187
+ observedFrames.add(frame);
1188
+ // The initial locator race does not include frames added later.
1189
+ // Watch each new frame until the initial race resolves or times out.
1190
+ // A timeout of 0 disables the frame timer; controller.abort() stops it.
1191
+ void locatorForFrames([frame])
1192
+ .setTimeout(0)
1193
+ .wait({ signal: controller.signal })
1194
+ .then(finish, error => {
1195
+ if (controller.signal.aborted) {
1196
+ return;
1197
+ }
1198
+ logger?.('Failed to wait for text in an attached frame', error);
1199
+ });
1200
+ };
1201
+ page.on('frameattached', onFrameAttached);
1202
+ void initialLocator.wait({ signal: controller.signal }).then(finish, fail);
1203
+ });
1204
+ }
1205
+ lighthouseNavigation(flags) {
1206
+ return lighthouseNavigation(this.pptrPage, this.pptrPage.url(), {
1207
+ flags,
1208
+ });
1209
+ }
1210
+ lighthouseSnapshot(flags) {
1211
+ return lighthouseSnapshot(this.pptrPage, {
1212
+ flags,
1213
+ });
832
1214
  }
833
1215
  /**
834
1216
  * We need to ignore favicon request as they make our test flaky
835
1217
  */
836
1218
  async setUpNetworkCollectorForTesting() {
837
1219
  this.networkCollector.dispose();
838
- this.networkCollector = new NetworkCollector(this.pptrPage, undefined, collect => {
1220
+ this.networkCollector = new NetworkCollector(this.pptrPage, { maxNavigationSaved: this.#config.resolved.maxNavigationSaved }, collect => {
839
1221
  return {
840
1222
  request: req => {
841
1223
  if (req.url().includes('favicon.ico')) {