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
@@ -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, } 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,15 @@ 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
+ #disposed = false;
147
+ #closed = false;
127
148
  // Snapshot
128
149
  textSnapshot = null;
129
150
  uniqueBackendNodeIdToMcpId = new Map();
@@ -136,48 +157,141 @@ export class McpPage {
136
157
  // Dialog
137
158
  #dialog;
138
159
  #dialogHandler;
139
- thirdPartyDeveloperTools = [];
140
- networkCollector;
141
- consoleCollector;
160
+ // Screencast
161
+ #screenRecorder = null;
162
+ eventBasedThirdPartyTools = [];
163
+ #networkCollector;
164
+ #consoleCollector;
142
165
  #hasNetworkBlockOrAllowlist;
143
166
  #locatorClass;
144
167
  #navigationTimeout;
145
168
  #sourceMaps;
146
169
  #commentBridge;
147
170
  #onNotification;
148
- constructor(page, id, options) {
171
+ constructor(target, id, options) {
149
172
  this.#hasNetworkBlockOrAllowlist = options.hasNetworkBlockOrAllowlist;
150
173
  this.#locatorClass = options.locatorClass;
151
174
  this.#navigationTimeout = options.navigationTimeout ?? NAVIGATION_TIMEOUT;
152
175
  this.#sourceMaps = options.sourceMaps ?? true;
153
176
  this.#onNotification = options.onNotification;
154
- this.pptrPage = page;
177
+ this.target = target;
155
178
  this.id = id;
156
179
  this.isolatedContextName = options.isolatedContextName;
157
180
  this.#dialogHandler = (dialog) => {
158
181
  this.#dialog = dialog;
159
182
  };
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
- });
183
+ }
184
+ get pptrPage() {
185
+ if (!this.#pptrPage) {
186
+ throw new Error(`McpPage (id=${this.id}) is not initialized. Call init() first.`);
187
+ }
188
+ return this.#pptrPage;
189
+ }
190
+ get networkCollector() {
191
+ if (!this.#networkCollector) {
192
+ throw new Error(`McpPage (id=${this.id}) is not initialized. Call init() first.`);
193
+ }
194
+ return this.#networkCollector;
195
+ }
196
+ set networkCollector(collector) {
197
+ this.#networkCollector = collector;
198
+ }
199
+ get consoleCollector() {
200
+ if (!this.#consoleCollector) {
201
+ throw new Error(`McpPage (id=${this.id}) is not initialized. Call init() first.`);
202
+ }
203
+ return this.#consoleCollector;
204
+ }
205
+ url() {
206
+ return this.#pptrPage?.url() ?? this.target.url();
207
+ }
208
+ get targetId() {
209
+ // @ts-expect-error internal types
210
+ const info = this.target._getTargetInfo();
211
+ return info.targetId;
212
+ }
213
+ /**
214
+ * Returns the page title or an empty string if the target only has Chrome's
215
+ * URL-based placeholder title.
216
+ *
217
+ * Puppeteer's cached target info is only refreshed by
218
+ * `Target.targetInfoChanged`, which Chrome emits on navigation commit (before
219
+ * the document title is known) but not on title changes. Callers should pass
220
+ * fresh target info (e.g., from `Target.getTargets`) when available.
221
+ */
222
+ getTitle(freshTargetInfo) {
223
+ // @ts-expect-error internal types
224
+ const cachedInfo = this.target._getTargetInfo();
225
+ const info = freshTargetInfo ?? cachedInfo;
226
+ return isPlaceholderTitle(info.title, info.url) ? '' : info.title;
227
+ }
228
+ isClosed() {
229
+ if (this.#closed) {
230
+ return true;
231
+ }
232
+ if (this.#pptrPage) {
233
+ return this.#pptrPage.isClosed();
234
+ }
235
+ return this.#disposed;
236
+ }
237
+ async close() {
238
+ this.#closed = true;
239
+ const page = this.#pptrPage ??
240
+ (await this.target.page()) ??
241
+ (await this.target.asPage());
242
+ this.dispose();
243
+ await page?.close({ runBeforeUnload: false });
175
244
  }
176
245
  async init() {
246
+ if (this.#disposed) {
247
+ throw new Error(`McpPage (id=${this.id}) has already been disposed.`);
248
+ }
249
+ if (this.#initPromise) {
250
+ return await this.#initPromise;
251
+ }
252
+ this.#initPromise = this.#doInit();
253
+ try {
254
+ await this.#initPromise;
255
+ }
256
+ catch (err) {
257
+ this.#initPromise = undefined;
258
+ throw err;
259
+ }
260
+ }
261
+ async #doInit() {
262
+ if (!this.#pptrPage) {
263
+ const page = (await this.target.page()) ?? (await this.target.asPage());
264
+ if (!page) {
265
+ throw new Error(`Failed to initialize Puppeteer Page for target ${this.target.url()}`);
266
+ }
267
+ if (this.#disposed) {
268
+ return;
269
+ }
270
+ this.#pptrPage = page;
271
+ page.on('dialog', this.#dialogHandler);
272
+ this.#networkCollector = new NetworkCollector(page);
273
+ this.#consoleCollector = new ConsoleCollector(page, collect => {
274
+ return {
275
+ console: event => {
276
+ collect(event);
277
+ },
278
+ uncaughtError: event => {
279
+ collect(event);
280
+ },
281
+ devtoolsAggregatedIssue: event => {
282
+ collect(event);
283
+ },
284
+ };
285
+ });
286
+ }
287
+ this.updateTimeouts();
177
288
  await Promise.allSettled([
178
289
  this.#initDevToolsUniverseNoThrow(),
179
290
  this.#initFocusEmulationNoThrow(),
180
291
  ]);
292
+ if (this.#disposed) {
293
+ this.dispose();
294
+ }
181
295
  }
182
296
  async #initFocusEmulationNoThrow() {
183
297
  // We emulate a focused page for all pages to support multi-agent workflows.
@@ -208,13 +322,41 @@ export class McpPage {
208
322
  clearDialog() {
209
323
  this.#dialog = undefined;
210
324
  }
325
+ getScreenRecorder() {
326
+ return this.#screenRecorder;
327
+ }
328
+ setScreenRecorder(data) {
329
+ this.#screenRecorder = data;
330
+ }
211
331
  throwIfDialogOpen() {
212
332
  if (this.#dialog && !this.#dialog.handled) {
213
333
  throw new Error(`A dialog is open (${this.#dialog.type()}: ${this.#dialog.message()}).`);
214
334
  }
215
335
  }
336
+ #getDebuggingWebMcpToolGroups() {
337
+ const webmcpTools = this.pptrPage.webmcp
338
+ .tools()
339
+ .filter(isDebuggingWebMcpTool);
340
+ if (webmcpTools.length === 0) {
341
+ return [];
342
+ }
343
+ return [
344
+ {
345
+ name: 'WebMCP Tools',
346
+ description: 'Tools exposed via WebMCP',
347
+ tools: webmcpTools.map(tool => ({
348
+ name: tool.name,
349
+ description: tool.description,
350
+ inputSchema: structuredClone(tool.inputSchema ?? {}),
351
+ })),
352
+ },
353
+ ];
354
+ }
216
355
  getThirdPartyDeveloperTools() {
217
- return this.thirdPartyDeveloperTools;
356
+ return [
357
+ ...this.#getDebuggingWebMcpToolGroups(),
358
+ ...this.eventBasedThirdPartyTools,
359
+ ];
218
360
  }
219
361
  async getToolGroups() {
220
362
  const env_1 = { stack: [], error: void 0, hasError: false };
@@ -223,13 +365,14 @@ export class McpPage {
223
365
  const windowHandle = __addDisposableResource(env_1, await this.pptrPage.evaluateHandle(() => window), false);
224
366
  // @ts-expect-error internal API
225
367
  const client = this.pptrPage._client();
226
- const { listeners } = await client.send('DOMDebugger.getEventListeners', {
368
+ const { listeners = [] } = await client.send('DOMDebugger.getEventListeners', {
227
369
  objectId: windowHandle.remoteObject().objectId,
228
370
  });
229
371
  if (listeners.find(l => l.type === 'devtoolstooldiscovery') === undefined) {
230
- return [];
372
+ this.eventBasedThirdPartyTools = [];
373
+ return this.getThirdPartyDeveloperTools();
231
374
  }
232
- const toolGroups = await this.pptrPage.evaluate(() => {
375
+ const eventToolGroups = await this.pptrPage.evaluate(() => {
233
376
  if (window.__dtmcp) {
234
377
  window.__dtmcp.toolGroups = [];
235
378
  }
@@ -297,13 +440,13 @@ export class McpPage {
297
440
  }
298
441
  });
299
442
  });
300
- for (const group of toolGroups) {
443
+ for (const group of eventToolGroups) {
301
444
  for (const tool of group.tools ?? []) {
302
445
  replaceHtmlElementsWithUids(tool.inputSchema);
303
446
  }
304
447
  }
305
- this.thirdPartyDeveloperTools = toolGroups;
306
- return toolGroups;
448
+ this.eventBasedThirdPartyTools = eventToolGroups;
449
+ return this.getThirdPartyDeveloperTools();
307
450
  }
308
451
  catch (e_1) {
309
452
  env_1.error = e_1;
@@ -314,7 +457,9 @@ export class McpPage {
314
457
  }
315
458
  }
316
459
  getWebMcpTools() {
317
- return this.pptrPage.webmcp.tools();
460
+ return this.pptrPage.webmcp
461
+ .tools()
462
+ .filter(tool => !isDebuggingWebMcpTool(tool));
318
463
  }
319
464
  resolveCdpRequestId(cdpRequestId) {
320
465
  if (!cdpRequestId) {
@@ -345,14 +490,18 @@ export class McpPage {
345
490
  get commentBridge() {
346
491
  return this.#commentBridge;
347
492
  }
493
+ /**
494
+ * Returns the comment bridge attached to the DevTools page, or undefined if
495
+ * the DevTools page does not support DevTools comments.
496
+ */
348
497
  async ensureDevToolsCommentBridge(devtoolsPage) {
349
498
  if (!this.#commentBridge) {
350
499
  this.#commentBridge = new DevToolsCommentBridge({
351
500
  onNotification: this.#onNotification,
352
501
  });
353
502
  }
354
- await this.#commentBridge.attach(devtoolsPage);
355
- return this.#commentBridge;
503
+ const attached = await this.#commentBridge.attach(devtoolsPage);
504
+ return attached ? this.#commentBridge : undefined;
356
505
  }
357
506
  async getDevToolsPage() {
358
507
  try {
@@ -400,6 +549,15 @@ export class McpPage {
400
549
  get colorScheme() {
401
550
  return this.emulationSettings.colorScheme ?? null;
402
551
  }
552
+ get forcedColors() {
553
+ return this.emulationSettings.forcedColors ?? null;
554
+ }
555
+ get prefersContrast() {
556
+ return this.emulationSettings.prefersContrast ?? null;
557
+ }
558
+ get prefersReducedMotion() {
559
+ return this.emulationSettings.prefersReducedMotion ?? null;
560
+ }
403
561
  // Public for testability: tests spy on this method to verify throttle multipliers.
404
562
  createWaitForHelper(cpuMultiplier, networkMultiplier) {
405
563
  return new WaitForHelper(this.pptrPage, cpuMultiplier, networkMultiplier);
@@ -409,11 +567,12 @@ export class McpPage {
409
567
  return helper.waitForEventsAfterAction(action, options);
410
568
  }
411
569
  dispose() {
570
+ this.#disposed = true;
412
571
  this.#commentBridge?.dispose();
413
572
  this.#commentBridge = undefined;
414
- this.pptrPage.off('dialog', this.#dialogHandler);
415
- this.networkCollector.dispose();
416
- this.consoleCollector.dispose();
573
+ this.#pptrPage?.off('dialog', this.#dialogHandler);
574
+ this.#networkCollector?.dispose();
575
+ this.#consoleCollector?.dispose();
417
576
  const devtoolsUniverse = this.#devtoolsUniverse;
418
577
  this.#devtoolsUniverse = undefined;
419
578
  devtoolsUniverse?.universe.dispose();
@@ -422,6 +581,23 @@ export class McpPage {
422
581
  });
423
582
  }
424
583
  async executeThirdPartyDeveloperTool(toolName, params, response) {
584
+ const webmcpTool = this.pptrPage.webmcp
585
+ .tools()
586
+ .find(t => t.name === toolName && isDebuggingWebMcpTool(t));
587
+ if (webmcpTool) {
588
+ const { status, output, errorText, exception } = await webmcpTool.execute(params);
589
+ if (status !== 'Completed') {
590
+ const error = exception?.description ?? exception?.value ?? errorText;
591
+ throw new Error(error ? String(error) : `Tool execution failed: ${status}`);
592
+ }
593
+ if (output !== undefined) {
594
+ response.appendResponseLine(JSON.stringify(output, null, 2));
595
+ }
596
+ else {
597
+ response.appendResponseLine('Tool returned no result.');
598
+ }
599
+ return;
600
+ }
425
601
  // Creates array of ElementHandles from the UIDs in the params.
426
602
  // We do not replace the uids with the ElementsHandles yet, because
427
603
  // the `evaluate` function only turns them into DOM elements if they
@@ -449,80 +625,111 @@ export class McpPage {
449
625
  throw new Error('No tools found on the page');
450
626
  }
451
627
  const toolResult = await window.__dtmcp.executeTool(name, args);
628
+ const stashedElements = [];
452
629
  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);
630
+ stashedElements.push(el);
460
631
  return {
461
- stashedId: `stashed-${window.__dtmcp.stashedElements.length - 1}`,
632
+ stashedId: `stashed-${stashedElements.length - 1}`,
462
633
  };
463
634
  };
464
- const ancestors = [];
635
+ const ancestors = new Set();
465
636
  // Recursively walks the tool result:
466
637
  // - Replaces DOM elements with an ID and stashes the DOM element on the window object
467
638
  // - Replaces non-plain objects with a string representation of the object
468
639
  // - Replaces circular references with the string '<Circular reference>'
469
640
  // - Replaces functions with the string '<Function object>'
470
- const processToolResult = (data, parentEl) => {
641
+ // - Replaces symbols and bigints with their string representation
642
+ const processToolResult = (data) => {
471
643
  // 1. Handle DOM Elements
472
644
  if (data instanceof Element) {
473
645
  return stashDOMElement(data);
474
646
  }
475
647
  // 2. Handle Arrays
476
648
  if (Array.isArray(data)) {
477
- return data.map((item) => processToolResult(item, parentEl));
649
+ if (ancestors.has(data)) {
650
+ return '<Circular reference>';
651
+ }
652
+ ancestors.add(data);
653
+ try {
654
+ return data.map((item) => processToolResult(item));
655
+ }
656
+ finally {
657
+ ancestors.delete(data);
658
+ }
478
659
  }
479
660
  // 3. Handle Objects
480
661
  if (data !== null && typeof data === 'object') {
481
- while (ancestors.length > 0 && ancestors.at(-1) !== parentEl) {
482
- ancestors.pop();
662
+ const proto = Object.getPrototypeOf(data);
663
+ // If not a plain object, return a string representation of the object
664
+ if (proto !== null && proto !== Object.prototype) {
665
+ return `<${data.constructor?.name || 'Object'} instance>`;
483
666
  }
484
- if (ancestors.includes(data)) {
667
+ if (ancestors.has(data)) {
485
668
  return '<Circular reference>';
486
669
  }
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>`;
670
+ ancestors.add(data);
671
+ try {
672
+ const processedObj = {};
673
+ for (const [key, value] of Object.entries(data)) {
674
+ processedObj[key] = processToolResult(value);
675
+ }
676
+ return processedObj;
491
677
  }
492
- const processedObj = {};
493
- for (const [key, value] of Object.entries(data)) {
494
- processedObj[key] = processToolResult(value, data);
678
+ finally {
679
+ ancestors.delete(data);
495
680
  }
496
- return processedObj;
497
681
  }
498
682
  // 4. Handle Functions
499
683
  if (typeof data === 'function') {
500
684
  return '<Function object>';
501
685
  }
502
- // 5. Return primitives (strings, numbers, booleans) as-is
686
+ // 5. Handle Symbols and BigInts (not JSON/CDP-by-value serializable)
687
+ if (typeof data === 'symbol') {
688
+ return data.toString();
689
+ }
690
+ if (typeof data === 'bigint') {
691
+ return `${data.toString()}n`;
692
+ }
693
+ // 6. Return primitives (strings, numbers, booleans, undefined, null) as-is
503
694
  return data;
504
695
  };
696
+ const processed = processToolResult(toolResult);
697
+ const serialized = processed !== undefined ? JSON.stringify(processed) : undefined;
698
+ if (stashedElements.length > 0) {
699
+ window.__dtmcp.stashedElements = stashedElements;
700
+ }
505
701
  return {
506
- result: processToolResult(toolResult),
507
- stashed: window.__dtmcp?.stashedElements?.length ?? 0,
702
+ result: serialized,
703
+ stashed: stashedElements.length,
508
704
  };
509
705
  }, toolName, params, ...handles);
510
706
  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`);
707
+ if (result.stashed > 0) {
708
+ try {
709
+ for (let i = 0; i < result.stashed; i++) {
710
+ const elementHandle = await this.pptrPage.evaluateHandle(index => {
711
+ const el = window.__dtmcp?.stashedElements?.[index];
712
+ if (!el) {
713
+ throw new Error(`Stashed element at index ${index} not found`);
714
+ }
715
+ return el;
716
+ }, i);
717
+ elementHandles.push(elementHandle);
516
718
  }
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
719
  }
525
- });
720
+ finally {
721
+ try {
722
+ await this.pptrPage.evaluate(() => {
723
+ if (window.__dtmcp) {
724
+ window.__dtmcp.stashedElements = undefined;
725
+ }
726
+ });
727
+ }
728
+ catch (error) {
729
+ logger?.('Failed to clean up stashed elements', error);
730
+ }
731
+ }
732
+ }
526
733
  if (elementHandles.length) {
527
734
  const env_2 = { stack: [], error: void 0, hasError: false };
528
735
  try {
@@ -565,7 +772,7 @@ export class McpPage {
565
772
  typeof node.stashedId === 'string' &&
566
773
  node.stashedId.startsWith('stashed-') &&
567
774
  Object.keys(node).length === 1) {
568
- const index = parseInt(node.stashedId.split('-')[1]);
775
+ const index = parseInt(node.stashedId.split('-')[1], 10);
569
776
  return { uid: cdpElementIds[index] };
570
777
  }
571
778
  const resultObj = {};
@@ -576,8 +783,14 @@ export class McpPage {
576
783
  }
577
784
  return node;
578
785
  };
579
- const resultWithUids = recursivelyReplaceStashedElements(result.result);
580
- response.appendResponseLine(JSON.stringify(resultWithUids, null, 2));
786
+ if (result.result !== undefined) {
787
+ const parsedResult = JSON.parse(result.result);
788
+ const resultWithUids = recursivelyReplaceStashedElements(parsedResult);
789
+ response.appendResponseLine(JSON.stringify(resultWithUids, null, 2));
790
+ }
791
+ else {
792
+ response.appendResponseLine('Tool returned no result.');
793
+ }
581
794
  }
582
795
  async getElementByUid(uid) {
583
796
  if (!this.textSnapshot) {
@@ -587,7 +800,7 @@ export class McpPage {
587
800
  if (!node) {
588
801
  throw new Error(`Element uid "${uid}" not found on page ${this.id}.`);
589
802
  }
590
- return this.#resolveElementHandle(node, uid);
803
+ return await this.#resolveElementHandle(node, uid);
591
804
  }
592
805
  async #resolveElementHandle(node, uid) {
593
806
  const message = `Element with uid ${uid} no longer exists on the page.`;
@@ -608,18 +821,24 @@ export class McpPage {
608
821
  return this.textSnapshot?.idToNode.get(uid);
609
822
  }
610
823
  async resolveBackendNodeId(backendNodeId) {
611
- if (!this.textSnapshot) {
612
- this.textSnapshot = await TextSnapshot.create(this);
824
+ let id = this.textSnapshot?.resolveCdpElementId(backendNodeId);
825
+ if (id) {
826
+ return id;
613
827
  }
614
- let id = this.textSnapshot.resolveCdpElementId(backendNodeId);
615
- if (!id) {
616
- this.textSnapshot = await TextSnapshot.create(this);
828
+ this.textSnapshot = await TextSnapshot.create(this, {
829
+ verbose: this.textSnapshot?.verbose ?? false,
830
+ });
831
+ id = this.textSnapshot.resolveCdpElementId(backendNodeId);
832
+ if (!id && !this.textSnapshot.verbose) {
833
+ this.textSnapshot = await TextSnapshot.create(this, {
834
+ verbose: true,
835
+ });
617
836
  id = this.textSnapshot.resolveCdpElementId(backendNodeId);
618
837
  }
619
838
  return id;
620
839
  }
621
840
  async resolveUidToBackendNodeId(uid) {
622
- const target = this.pptrPage.target();
841
+ const target = this.target;
623
842
  const targetId = Boolean(target) &&
624
843
  '_targetId' in target &&
625
844
  typeof target._targetId === 'string'
@@ -686,7 +905,9 @@ export class McpPage {
686
905
  logger?.('No DevTools page detected');
687
906
  return {};
688
907
  }
908
+ await this.ensureDevToolsCommentBridge(devtoolsPage);
689
909
  const { cdpRequestId, cdpBackendNodeId } = await devtoolsPage.evaluate(async () => {
910
+ window.universe?.cd4aBridge?.setAgentAttached(true);
690
911
  // @ts-expect-error no types
691
912
  const UI = await import('/bundled/ui/legacy/legacy.js');
692
913
  // @ts-expect-error no types
@@ -709,6 +930,20 @@ export class McpPage {
709
930
  const currentSetting = this.emulationSettings;
710
931
  await this.emulate(currentSetting);
711
932
  }
933
+ async #emulateMediaFeatures(settings) {
934
+ // `page.emulateMediaFeatures` replaces all previously emulated media
935
+ // features, so every supported feature is sent on each call. An empty
936
+ // value disables the override for that feature.
937
+ await this.pptrPage.emulateMediaFeatures([
938
+ { name: 'prefers-color-scheme', value: settings.colorScheme ?? '' },
939
+ { name: 'forced-colors', value: settings.forcedColors ?? '' },
940
+ { name: 'prefers-contrast', value: settings.prefersContrast ?? '' },
941
+ {
942
+ name: 'prefers-reduced-motion',
943
+ value: settings.prefersReducedMotion ?? '',
944
+ },
945
+ ]);
946
+ }
712
947
  async emulate(options) {
713
948
  const page = this.pptrPage;
714
949
  const newSettings = { ...this.emulationSettings };
@@ -772,17 +1007,31 @@ export class McpPage {
772
1007
  newSettings.userAgent = options.userAgent;
773
1008
  }
774
1009
  if (!options.colorScheme || options.colorScheme === 'auto') {
775
- await page.emulateMediaFeatures([
776
- { name: 'prefers-color-scheme', value: '' },
777
- ]);
778
1010
  delete newSettings.colorScheme;
779
1011
  }
780
1012
  else {
781
- await page.emulateMediaFeatures([
782
- { name: 'prefers-color-scheme', value: options.colorScheme },
783
- ]);
784
1013
  newSettings.colorScheme = options.colorScheme;
785
1014
  }
1015
+ if (!options.forcedColors || options.forcedColors === 'auto') {
1016
+ delete newSettings.forcedColors;
1017
+ }
1018
+ else {
1019
+ newSettings.forcedColors = options.forcedColors;
1020
+ }
1021
+ if (!options.prefersContrast || options.prefersContrast === 'auto') {
1022
+ delete newSettings.prefersContrast;
1023
+ }
1024
+ else {
1025
+ newSettings.prefersContrast = options.prefersContrast;
1026
+ }
1027
+ if (!options.prefersReducedMotion ||
1028
+ options.prefersReducedMotion === 'auto') {
1029
+ delete newSettings.prefersReducedMotion;
1030
+ }
1031
+ else {
1032
+ newSettings.prefersReducedMotion = options.prefersReducedMotion;
1033
+ }
1034
+ await this.#emulateMediaFeatures(newSettings);
786
1035
  if (!options.viewport) {
787
1036
  delete newSettings.viewport;
788
1037
  }
@@ -809,6 +1058,9 @@ export class McpPage {
809
1058
  await page.setViewport(newSettings.viewport ?? null);
810
1059
  }
811
1060
  updateTimeouts() {
1061
+ if (!this.#pptrPage) {
1062
+ return;
1063
+ }
812
1064
  // For waiters 5sec timeout should be sufficient.
813
1065
  // Increased in case we throttle the CPU
814
1066
  const cpuMultiplier = this.cpuThrottlingRate;