chrome-devtools-mcp 1.5.0 → 1.6.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 (51) hide show
  1. package/README.md +15 -0
  2. package/build/src/HeapSnapshotManager.js +23 -13
  3. package/build/src/McpContext.js +174 -365
  4. package/build/src/McpPage.js +242 -31
  5. package/build/src/McpResponse.js +113 -67
  6. package/build/src/PageCollector.js +48 -122
  7. package/build/src/TextSnapshot.js +20 -2
  8. package/build/src/ToolHandler.js +13 -3
  9. package/build/src/WaitForHelper.js +18 -8
  10. package/build/src/bin/chrome-devtools-cli-options.js +25 -1
  11. package/build/src/bin/chrome-devtools-mcp-cli-options.js +15 -6
  12. package/build/src/bin/chrome-devtools-mcp-main.js +2 -2
  13. package/build/src/browser.js +1 -1
  14. package/build/src/daemon/client.js +33 -3
  15. package/build/src/daemon/daemon.js +2 -1
  16. package/build/src/daemon/utils.js +1 -1
  17. package/build/src/devtools/DevtoolsUtils.js +2 -63
  18. package/build/src/{issue-descriptions.js → devtools/issueDescriptions.js} +2 -2
  19. package/build/src/formatters/IssueFormatter.js +2 -2
  20. package/build/src/index.js +12 -3
  21. package/build/src/telemetry/ClearcutLogger.js +1 -1
  22. package/build/src/telemetry/WatchdogClient.js +1 -1
  23. package/build/src/telemetry/metricsRegistry.js +2 -9
  24. package/build/src/telemetry/persistence.js +1 -1
  25. package/build/src/telemetry/transformation.js +20 -0
  26. package/build/src/telemetry/watchdog/ClearcutSender.js +1 -1
  27. package/build/src/telemetry/watchdog/main.js +1 -1
  28. package/build/src/third_party/THIRD_PARTY_NOTICES +13 -249
  29. package/build/src/third_party/bundled-packages.json +2 -3
  30. package/build/src/third_party/index.js +1527 -1514
  31. package/build/src/third_party/lighthouse-devtools-mcp-bundle.js +3082 -6343
  32. package/build/src/tools/emulation.js +2 -2
  33. package/build/src/tools/extensions.js +1 -1
  34. package/build/src/tools/input.js +17 -8
  35. package/build/src/tools/lighthouse.js +1 -1
  36. package/build/src/tools/memory.js +16 -2
  37. package/build/src/tools/network.js +4 -4
  38. package/build/src/tools/pages.js +21 -89
  39. package/build/src/tools/performance.js +2 -2
  40. package/build/src/tools/script.js +3 -0
  41. package/build/src/tools/snapshot.js +2 -2
  42. package/build/src/tools/thirdPartyDeveloper.js +1 -1
  43. package/build/src/tools/webmcp.js +1 -1
  44. package/build/src/trace-processing/parse.js +1 -1
  45. package/build/src/{logger.js → utils/logger.js} +1 -1
  46. package/build/src/{polyfill.js → utils/polyfill.js} +1 -1
  47. package/build/src/version.js +1 -1
  48. package/package.json +9 -5
  49. package/skills/memory-leak-debugging/SKILL.md +22 -14
  50. package/build/src/utils/types.js +0 -7
  51. /package/build/src/{Mutex.js → utils/Mutex.js} +0 -0
@@ -8,18 +8,19 @@ import fsPromises from 'node:fs/promises';
8
8
  import os from 'node:os';
9
9
  import path from 'node:path';
10
10
  import { fileURLToPath, pathToFileURL } from 'node:url';
11
- import { overrideDevToolsGlobals, UniverseManager, } from './devtools/DevtoolsUtils.js';
11
+ import { overrideDevToolsGlobals } from './devtools/DevtoolsUtils.js';
12
12
  import { HeapSnapshotManager } from './HeapSnapshotManager.js';
13
13
  import { McpPage } from './McpPage.js';
14
- import { NetworkCollector, ConsoleCollector, } from './PageCollector.js';
15
14
  import { ServiceWorkerConsoleCollector } from './ServiceWorkerCollector.js';
16
- import { Locator, PredefinedNetworkConditions, } from './third_party/index.js';
15
+ import { Locator, } from './third_party/index.js';
17
16
  import { listPages } from './tools/pages.js';
18
17
  import { CLOSE_PAGE_ERROR } from './tools/ToolDefinition.js';
19
18
  import { getTempFilePath, resolveCanonicalPath } from './utils/files.js';
20
- import { getNetworkMultiplierFromString } from './WaitForHelper.js';
21
- const DEFAULT_TIMEOUT = 5_000;
22
- const NAVIGATION_TIMEOUT = 10_000;
19
+ // Page ids are handed out from a process-wide counter so they stay unique
20
+ // across all contexts, in particular across browser reconnects. An id issued
21
+ // before a reconnect then fails to resolve instead of hitting an unrelated
22
+ // page of the reconnected browser.
23
+ let nextPageId = 1;
23
24
  export class McpContext {
24
25
  browser;
25
26
  logger;
@@ -27,17 +28,14 @@ export class McpContext {
27
28
  #isolatedContexts = new Map();
28
29
  // Auto-generated name counter for when no name is provided.
29
30
  #nextIsolatedContextId = 1;
30
- #pages = [];
31
31
  #extensionServiceWorkers = [];
32
32
  #mcpPages = new Map();
33
33
  #selectedPage;
34
- #networkCollector;
35
- #consoleCollector;
36
- #devtoolsUniverseManager;
34
+ #selectedPageFallback;
37
35
  #serviceWorkerConsoleCollector;
38
36
  #isRunningTrace = false;
39
37
  #screenRecorderData = null;
40
- #nextPageId = 1;
38
+ #reconnectNotice = false;
41
39
  #extensionPages = new WeakMap();
42
40
  #extensionServiceWorkerMap = new WeakMap();
43
41
  #nextExtensionServiceWorkerId = 1;
@@ -46,6 +44,7 @@ export class McpContext {
46
44
  #options;
47
45
  #heapSnapshotManager = new HeapSnapshotManager();
48
46
  #roots = undefined;
47
+ #allowUnrestrictedPaths;
49
48
  constructor(browser, logger, options, locatorClass) {
50
49
  overrideDevToolsGlobals({
51
50
  loadResource: (url) => {
@@ -56,35 +55,20 @@ export class McpContext {
56
55
  this.logger = logger;
57
56
  this.#locatorClass = locatorClass;
58
57
  this.#options = options;
59
- this.#networkCollector = new NetworkCollector(this.browser);
60
- this.#consoleCollector = new ConsoleCollector(this.browser, collect => {
61
- return {
62
- console: event => {
63
- collect(event);
64
- },
65
- uncaughtError: event => {
66
- collect(event);
67
- },
68
- devtoolsAggregatedIssue: event => {
69
- collect(event);
70
- },
71
- };
72
- });
58
+ this.#allowUnrestrictedPaths = options.allowUnrestrictedPaths ?? false;
59
+ this.#reconnectNotice = options.reconnected ?? false;
73
60
  this.#serviceWorkerConsoleCollector = new ServiceWorkerConsoleCollector(this.browser);
74
- this.#devtoolsUniverseManager = new UniverseManager(this.browser);
75
61
  }
76
62
  async #init() {
77
- const pages = await this.createPagesSnapshot();
63
+ await this.createPagesSnapshot();
78
64
  const workers = await this.createExtensionServiceWorkersSnapshot();
79
- await this.#networkCollector.init(pages);
80
- await this.#consoleCollector.init(pages);
81
- await this.#devtoolsUniverseManager.init(pages);
82
65
  await this.#serviceWorkerConsoleCollector.init(workers);
66
+ this.browser.on('targetcreated', this.#onTargetCreated);
67
+ this.browser.on('targetdestroyed', this.#onTargetDestroyed);
83
68
  }
84
69
  dispose() {
85
- this.#networkCollector.dispose();
86
- this.#consoleCollector.dispose();
87
- this.#devtoolsUniverseManager.dispose();
70
+ this.browser.off('targetcreated', this.#onTargetCreated);
71
+ this.browser.off('targetdestroyed', this.#onTargetDestroyed);
88
72
  this.#serviceWorkerConsoleCollector.dispose();
89
73
  for (const mcpPage of this.#mcpPages.values()) {
90
74
  mcpPage.dispose();
@@ -95,6 +79,40 @@ export class McpContext {
95
79
  // without destroying browser state.
96
80
  this.#isolatedContexts.clear();
97
81
  }
82
+ #onTargetCreated = async (target) => {
83
+ try {
84
+ const page = await target.page();
85
+ if (!page) {
86
+ return;
87
+ }
88
+ void this.#createMcpPage(page);
89
+ }
90
+ catch (err) {
91
+ this.logger?.('Error handling targetcreated', err);
92
+ }
93
+ };
94
+ #onTargetDestroyed = (target) => {
95
+ try {
96
+ let foundPage;
97
+ for (const page of this.#mcpPages.keys()) {
98
+ if (page.target() === target) {
99
+ foundPage = page;
100
+ break;
101
+ }
102
+ }
103
+ if (!foundPage) {
104
+ return;
105
+ }
106
+ const mcpPage = this.#mcpPages.get(foundPage);
107
+ if (mcpPage) {
108
+ mcpPage.dispose();
109
+ this.#mcpPages.delete(foundPage);
110
+ }
111
+ }
112
+ catch (err) {
113
+ this.logger?.('Error handling targetdestroyed', err);
114
+ }
115
+ };
98
116
  static async from(browser, logger, opts,
99
117
  /* Let tests use unbundled Locator class to avoid overly strict checks within puppeteer that fail when mixing bundled and unbundled class instances */
100
118
  locatorClass = Locator) {
@@ -102,12 +120,12 @@ export class McpContext {
102
120
  await context.#init();
103
121
  return context;
104
122
  }
123
+ static resetPageIdsForTesting() {
124
+ nextPageId = 1;
125
+ }
105
126
  roots() {
106
- if (this.#roots === undefined) {
107
- return undefined;
108
- }
109
127
  return [
110
- ...this.#roots,
128
+ ...(this.#roots ?? []),
111
129
  {
112
130
  uri: pathToFileURL(os.tmpdir()).href,
113
131
  name: 'temp',
@@ -121,10 +139,17 @@ export class McpContext {
121
139
  if (filePath === undefined) {
122
140
  return;
123
141
  }
124
- const roots = this.roots();
125
- if (roots === undefined) {
142
+ // If the client never negotiated roots and the operator has explicitly
143
+ // opted into unrestricted access via --allow-unrestricted-paths, restore
144
+ // the previous permissive behavior and skip validation.
145
+ if (this.#roots === undefined && this.#allowUnrestrictedPaths) {
126
146
  return;
127
147
  }
148
+ // roots() always returns at least the temp directory, even if the
149
+ // connecting client never negotiated the optional `roots` capability.
150
+ // Path validation must not be skipped just because no workspace roots
151
+ // were configured.
152
+ const roots = this.roots();
128
153
  let canonicalPath;
129
154
  try {
130
155
  canonicalPath = await resolveCanonicalPath(filePath);
@@ -135,18 +160,24 @@ export class McpContext {
135
160
  throw new Error(`Access denied: Cannot resolve base path for ${filePath}.`);
136
161
  }
137
162
  let allowed = false;
138
- for (const root of roots) {
139
- try {
140
- const rootPathUri = root.uri;
141
- const rootPath = path.resolve(fileURLToPath(rootPathUri));
142
- const canonicalRoot = await fsPromises.realpath(rootPath);
163
+ const resolvedRoots = await Promise.allSettled(roots.map(async (root) => {
164
+ const rootPathUri = root.uri;
165
+ const rootPath = path.resolve(fileURLToPath(rootPathUri));
166
+ return await fsPromises.realpath(rootPath);
167
+ }));
168
+ for (let i = 0; i < roots.length; i++) {
169
+ const root = roots[i];
170
+ const result = resolvedRoots[i];
171
+ if (result.status === 'fulfilled') {
172
+ const canonicalRoot = result.value;
143
173
  if (canonicalPath === canonicalRoot ||
144
174
  canonicalPath.startsWith(canonicalRoot + path.sep)) {
145
175
  allowed = true;
146
176
  break;
147
177
  }
148
178
  }
149
- catch (rootErr) {
179
+ else {
180
+ const rootErr = result.reason;
150
181
  const errMsg = rootErr instanceof Error ? rootErr.message : String(rootErr);
151
182
  console.warn(`[MCP Context] Could not resolve configured root ${root.uri}: ${errMsg}`);
152
183
  // Skip this root if it cannot be resolved.
@@ -163,36 +194,6 @@ export class McpContext {
163
194
  await this.validatePath(outputPath);
164
195
  return outputPath;
165
196
  }
166
- resolveCdpRequestId(page, cdpRequestId) {
167
- if (!cdpRequestId) {
168
- this.logger?.('no network request');
169
- return;
170
- }
171
- const request = this.#networkCollector.find(page.pptrPage, request => {
172
- // @ts-expect-error id is internal.
173
- return request.id === cdpRequestId;
174
- });
175
- if (!request) {
176
- this.logger?.('no network request for ' + cdpRequestId);
177
- return;
178
- }
179
- return this.#networkCollector.getIdForResource(request);
180
- }
181
- getNetworkRequests(page, includePreservedRequests) {
182
- return this.#networkCollector.getData(page.pptrPage, includePreservedRequests);
183
- }
184
- getConsoleData(page, includePreservedMessages) {
185
- return this.#consoleCollector.getData(page.pptrPage, includePreservedMessages);
186
- }
187
- getDevToolsUniverse(page) {
188
- return this.#devtoolsUniverseManager.get(page.pptrPage);
189
- }
190
- getConsoleMessageStableId(message) {
191
- return this.#consoleCollector.getIdForResource(message);
192
- }
193
- getConsoleMessageById(page, id) {
194
- return this.#consoleCollector.getById(page.pptrPage, id);
195
- }
196
197
  async newPage(background, isolatedContextName) {
197
198
  let page;
198
199
  if (isolatedContextName !== undefined) {
@@ -206,14 +207,13 @@ export class McpContext {
206
207
  else {
207
208
  page = await this.browser.newPage({ background });
208
209
  }
210
+ const mcpPage = await this.#createMcpPage(page);
209
211
  await this.createPagesSnapshot();
210
- this.selectPage(this.#getMcpPage(page));
211
- this.#networkCollector.addPage(page);
212
- this.#consoleCollector.addPage(page);
213
- return this.#getMcpPage(page);
212
+ this.selectPage(mcpPage);
213
+ return mcpPage;
214
214
  }
215
215
  async closePage(pageId) {
216
- if (this.#pages.length === 1) {
216
+ if (this.#mcpPages.size === 1) {
217
217
  throw new Error(CLOSE_PAGE_ERROR);
218
218
  }
219
219
  const page = this.getPageById(pageId);
@@ -223,118 +223,9 @@ export class McpContext {
223
223
  }
224
224
  await page.pptrPage.close({ runBeforeUnload: false });
225
225
  }
226
- getNetworkRequestById(page, reqid) {
227
- return this.#networkCollector.getById(page.pptrPage, reqid);
228
- }
229
- async restoreEmulation(page) {
230
- const currentSetting = page.emulationSettings;
231
- await this.emulate(currentSetting, page.pptrPage);
232
- }
233
226
  get #hasNetworkBlockOrAllowlist() {
234
227
  return !!(this.#options.allowList || this.#options.blocklist);
235
228
  }
236
- async emulate(options, targetPage) {
237
- const page = targetPage ?? this.getSelectedPptrPage();
238
- const mcpPage = this.#getMcpPage(page);
239
- const newSettings = { ...mcpPage.emulationSettings };
240
- // Skip network emulation if blocklist/allowlist is configured, as it conflicts with blocking rules in Puppeteer.
241
- if (this.#hasNetworkBlockOrAllowlist) {
242
- if (options.networkConditions !== undefined) {
243
- throw new Error('Network throttling is not supported when network blocking (allowlist/blocklist) is configured.');
244
- }
245
- }
246
- else if (!options.networkConditions) {
247
- await page.emulateNetworkConditions(null);
248
- delete newSettings.networkConditions;
249
- }
250
- else if (options.networkConditions === 'Offline') {
251
- await page.emulateNetworkConditions({
252
- offline: true,
253
- download: 0,
254
- upload: 0,
255
- latency: 0,
256
- });
257
- newSettings.networkConditions = 'Offline';
258
- }
259
- else if (options.networkConditions in PredefinedNetworkConditions) {
260
- const networkCondition = PredefinedNetworkConditions[options.networkConditions];
261
- await page.emulateNetworkConditions(networkCondition);
262
- newSettings.networkConditions = options.networkConditions;
263
- }
264
- const secondarySession = this.getDevToolsUniverse(mcpPage)?.session;
265
- if (!options.cpuThrottlingRate) {
266
- await page.emulateCPUThrottling(1);
267
- if (secondarySession) {
268
- await secondarySession.send('Emulation.setCPUThrottlingRate', {
269
- rate: 1,
270
- });
271
- }
272
- delete newSettings.cpuThrottlingRate;
273
- }
274
- else {
275
- await page.emulateCPUThrottling(options.cpuThrottlingRate);
276
- if (secondarySession) {
277
- await secondarySession.send('Emulation.setCPUThrottlingRate', {
278
- rate: options.cpuThrottlingRate,
279
- });
280
- }
281
- newSettings.cpuThrottlingRate = options.cpuThrottlingRate;
282
- }
283
- if (!options.geolocation) {
284
- await page.setGeolocation({ latitude: 0, longitude: 0 });
285
- delete newSettings.geolocation;
286
- }
287
- else {
288
- await page.setGeolocation(options.geolocation);
289
- newSettings.geolocation = options.geolocation;
290
- }
291
- if (!options.userAgent) {
292
- await page.setUserAgent({ userAgent: undefined });
293
- delete newSettings.userAgent;
294
- }
295
- else {
296
- await page.setUserAgent({ userAgent: options.userAgent });
297
- newSettings.userAgent = options.userAgent;
298
- }
299
- if (!options.colorScheme || options.colorScheme === 'auto') {
300
- await page.emulateMediaFeatures([
301
- { name: 'prefers-color-scheme', value: '' },
302
- ]);
303
- delete newSettings.colorScheme;
304
- }
305
- else {
306
- await page.emulateMediaFeatures([
307
- { name: 'prefers-color-scheme', value: options.colorScheme },
308
- ]);
309
- newSettings.colorScheme = options.colorScheme;
310
- }
311
- if (!options.viewport) {
312
- delete newSettings.viewport;
313
- }
314
- else {
315
- const defaults = {
316
- deviceScaleFactor: 1,
317
- isMobile: false,
318
- hasTouch: false,
319
- isLandscape: false,
320
- };
321
- newSettings.viewport = { ...defaults, ...options.viewport };
322
- }
323
- if (options.extraHttpHeaders !== undefined) {
324
- await page.setExtraHTTPHeaders(options.extraHttpHeaders);
325
- newSettings.extraHttpHeaders = options.extraHttpHeaders;
326
- if (Object.keys(options.extraHttpHeaders).length === 0) {
327
- delete newSettings.extraHttpHeaders;
328
- }
329
- }
330
- mcpPage.emulationSettings = Object.keys(newSettings).length
331
- ? newSettings
332
- : {};
333
- this.#updateSelectedPageTimeouts();
334
- // This should happen after updating the page timeouts.
335
- // Setting the viewport can trigger a reload which we don't want to timeout.
336
- await page.setViewport(newSettings.viewport ?? null);
337
- }
338
229
  setIsRunningPerformanceTrace(x) {
339
230
  this.#isRunningTrace = x;
340
231
  }
@@ -350,7 +241,10 @@ export class McpContext {
350
241
  isCruxEnabled() {
351
242
  return this.#options.performanceCrux;
352
243
  }
353
- getSelectedPptrPage() {
244
+ getPages() {
245
+ return Array.from(this.#mcpPages.values());
246
+ }
247
+ getSelectedMcpPage() {
354
248
  const page = this.#selectedPage;
355
249
  if (!page) {
356
250
  throw new Error('No page selected');
@@ -358,11 +252,17 @@ export class McpContext {
358
252
  if (page.pptrPage.isClosed()) {
359
253
  throw new Error(`The selected page has been closed. Call ${listPages().name} to see open pages.`);
360
254
  }
361
- return page.pptrPage;
255
+ return page;
362
256
  }
363
- getSelectedMcpPage() {
364
- const page = this.getSelectedPptrPage();
365
- return this.#getMcpPage(page);
257
+ /**
258
+ * Returns true once if this context was created by reconnecting after the
259
+ * previous browser connection was lost, so the next response can surface a
260
+ * note. Cleared on first call.
261
+ */
262
+ consumeReconnectNotice() {
263
+ const notice = this.#reconnectNotice;
264
+ this.#reconnectNotice = false;
265
+ return notice;
366
266
  }
367
267
  getPageById(pageId) {
368
268
  const page = this.#mcpPages.values().find(mcpPage => mcpPage.id === pageId);
@@ -371,55 +271,27 @@ export class McpContext {
371
271
  }
372
272
  return page;
373
273
  }
374
- getPageId(page) {
375
- return this.#mcpPages.get(page)?.id;
376
- }
377
- #getMcpPage(page) {
378
- const mcpPage = this.#mcpPages.get(page);
379
- if (!mcpPage) {
380
- throw new Error('No McpPage found for the given page.');
381
- }
382
- return mcpPage;
383
- }
384
- #getSelectedMcpPage() {
385
- return this.#getMcpPage(this.getSelectedPptrPage());
386
- }
387
274
  isPageSelected(page) {
388
- return this.#selectedPage?.pptrPage === page;
275
+ return this.#selectedPage === page;
389
276
  }
390
277
  selectPage(newPage) {
391
278
  this.#selectedPage = newPage;
392
- this.#updateSelectedPageTimeouts();
393
- }
394
- #updateSelectedPageTimeouts() {
395
- const page = this.#getSelectedMcpPage();
396
- // For waiters 5sec timeout should be sufficient.
397
- // Increased in case we throttle the CPU
398
- const cpuMultiplier = page.cpuThrottlingRate;
399
- page.pptrPage.setDefaultTimeout(DEFAULT_TIMEOUT * cpuMultiplier);
400
- // 10sec should be enough for the load event to be emitted during
401
- // navigations.
402
- // Increased in case we throttle the network requests or the CPU
403
- const networkMultiplier = getNetworkMultiplierFromString(page.networkConditions);
404
- page.pptrPage.setDefaultNavigationTimeout(NAVIGATION_TIMEOUT * networkMultiplier * cpuMultiplier);
405
- }
406
- // Linear scan over per-page snapshots. The page count is small (typically
407
- // 2-10) so a reverse index isn't worthwhile given the uid-reuse lifecycle
408
- // complexity it would introduce.
409
- getAXNodeByUid(uid) {
410
- for (const mcpPage of this.#mcpPages.values()) {
411
- const node = mcpPage.textSnapshot?.idToNode.get(uid);
412
- if (node) {
413
- return node;
414
- }
415
- }
416
- return undefined;
279
+ newPage.updateTimeouts();
280
+ }
281
+ /**
282
+ * Returns details about the last page snapshot automatically replacing the
283
+ * selection because the selected page disappeared from the page list, or
284
+ * `undefined` if the snapshot left the selection intact. Recomputed on every
285
+ * createPagesSnapshot() call.
286
+ */
287
+ getSelectedPageFallback() {
288
+ return this.#selectedPageFallback;
417
289
  }
418
290
  /**
419
291
  * Creates a snapshot of the extension service workers.
420
292
  */
421
293
  async createExtensionServiceWorkersSnapshot() {
422
- const allTargets = await this.browser.targets();
294
+ const allTargets = this.browser.targets();
423
295
  const serviceWorkers = allTargets.filter(target => {
424
296
  return (target.type() === 'service_worker' &&
425
297
  target.url().includes('chrome-extension://'));
@@ -441,74 +313,13 @@ export class McpContext {
441
313
  getServiceWorkerConsoleData(extensionId) {
442
314
  return this.#serviceWorkerConsoleCollector.getData(extensionId);
443
315
  }
444
- async createPagesSnapshot() {
445
- const { pages: allPages, isolatedContextNames } = await this.#getAllPages();
446
- for (const page of allPages) {
447
- let mcpPage = this.#mcpPages.get(page);
448
- if (!mcpPage) {
449
- mcpPage = new McpPage(page, this.#nextPageId++);
450
- this.#mcpPages.set(page, mcpPage);
451
- // We emulate a focused page for all pages to support multi-agent workflows.
452
- void page.emulateFocusedPage(true).catch(error => {
453
- this.logger?.('Error turning on focused page emulation', error);
454
- });
455
- }
456
- mcpPage.isolatedContextName = isolatedContextNames.get(page);
457
- }
458
- // Prune orphaned #mcpPages entries (pages that no longer exist).
459
- const currentPages = new Set(allPages);
460
- for (const [page, mcpPage] of this.#mcpPages) {
461
- if (!currentPages.has(page)) {
462
- mcpPage.dispose();
463
- this.#mcpPages.delete(page);
464
- }
465
- }
466
- this.#pages = allPages.filter(page => {
467
- return (this.#options.experimentalDevToolsDebugging ||
468
- !page.url().startsWith('devtools://'));
469
- });
470
- if ((!this.#selectedPage ||
471
- this.#pages.indexOf(this.#selectedPage.pptrPage) === -1) &&
472
- this.#pages[0]) {
473
- this.selectPage(this.#getMcpPage(this.#pages[0]));
474
- }
475
- await this.detectOpenDevToolsWindows();
476
- return this.#pages;
477
- }
478
- async #getAllPages() {
479
- const defaultCtx = this.browser.defaultBrowserContext();
480
- const allPages = await this.browser.pages(this.#options.experimentalIncludeAllPages);
481
- const allTargets = this.browser.targets();
482
- const extensionTargets = allTargets.filter(target => {
483
- return (target.url().startsWith('chrome-extension://') &&
484
- target.type() === 'page');
485
- });
486
- for (const target of extensionTargets) {
487
- // Right now target.page() returns null for popup and side panel pages.
488
- let page = await target.page();
489
- if (!page) {
490
- // We need to cache pages instances for targets because target.asPage()
491
- // returns a new page instance every time.
492
- page = this.#extensionPages.get(target) ?? null;
493
- if (!page) {
494
- try {
495
- page = await target.asPage();
496
- this.#extensionPages.set(target, page);
497
- }
498
- catch (e) {
499
- this.logger?.('Failed to get page for extension target', e);
500
- }
501
- }
502
- }
503
- if (page && !allPages.includes(page)) {
504
- allPages.push(page);
505
- }
506
- }
316
+ #getBrowserContextToNameMap() {
507
317
  // Build a reverse lookup from BrowserContext instance → name.
508
318
  const contextToName = new Map();
509
319
  for (const [name, ctx] of this.#isolatedContexts) {
510
320
  contextToName.set(ctx, name);
511
321
  }
322
+ const defaultCtx = this.browser.defaultBrowserContext();
512
323
  // Auto-discover BrowserContexts not in our mapping (e.g., externally
513
324
  // created incognito contexts) and assign generated names.
514
325
  const knownContexts = new Set(this.#isolatedContexts.values());
@@ -519,40 +330,76 @@ export class McpContext {
519
330
  contextToName.set(ctx, name);
520
331
  }
521
332
  }
522
- // Map each page to its isolated context name (if any).
523
- const isolatedContextNames = new Map();
524
- for (const page of allPages) {
525
- const ctx = page.browserContext();
526
- const name = contextToName.get(ctx);
527
- if (name) {
528
- isolatedContextNames.set(page, name);
529
- }
333
+ return contextToName;
334
+ }
335
+ async #createMcpPage(page) {
336
+ let mcpPage = this.#mcpPages.get(page);
337
+ if (!mcpPage) {
338
+ mcpPage = new McpPage(page, nextPageId++, {
339
+ locatorClass: this.#locatorClass,
340
+ hasNetworkBlockOrAllowlist: this.#hasNetworkBlockOrAllowlist,
341
+ isolatedContextName: this.#getBrowserContextToNameMap().get(page.browserContext()),
342
+ });
343
+ this.#mcpPages.set(page, mcpPage);
344
+ await mcpPage.init();
530
345
  }
531
- return { pages: allPages, isolatedContextNames };
346
+ return mcpPage;
532
347
  }
533
- async detectOpenDevToolsWindows() {
534
- this.logger?.('Detecting open DevTools windows');
535
- const { pages } = await this.#getAllPages();
536
- await Promise.all(pages.map(async (page) => {
537
- const mcpPage = this.#mcpPages.get(page);
538
- if (!mcpPage) {
539
- return;
348
+ async createPagesSnapshot() {
349
+ const allPages = await this.#fetchBrowserPages();
350
+ await Promise.allSettled(allPages.map(page => this.#createMcpPage(page)));
351
+ // Prune orphaned #mcpPages entries (pages that no longer exist).
352
+ const currentPages = new Set(allPages);
353
+ for (const [page, mcpPage] of this.#mcpPages) {
354
+ if (!currentPages.has(page)) {
355
+ mcpPage.dispose();
356
+ this.#mcpPages.delete(page);
357
+ }
358
+ }
359
+ const pages = Array.from(this.#mcpPages.values());
360
+ // Only fall back when the selected page is actually gone. Gating on
361
+ // `isClosed()` instead of `pages` membership avoids silently swapping a
362
+ // live page that is momentarily missing from the snapshot.
363
+ this.#selectedPageFallback = undefined;
364
+ if ((!this.#selectedPage || this.#selectedPage.pptrPage.isClosed()) &&
365
+ pages[0]) {
366
+ // Record the automatic change so the response can surface it. Skipped on
367
+ // first connect, when there was no prior selection to replace.
368
+ if (this.#selectedPage) {
369
+ this.#selectedPageFallback = {
370
+ wasClosed: this.#selectedPage.pptrPage.isClosed(),
371
+ };
540
372
  }
541
- // Prior to Chrome 144.0.7559.59, the command fails,
542
- // Some Electron apps still use older version
543
- // Fall back to not exposing DevTools at all.
373
+ this.selectPage(pages[0]);
374
+ }
375
+ return pages.map(p => p.pptrPage);
376
+ }
377
+ async #fetchBrowserPages() {
378
+ const allPages = (await this.browser.pages(this.#options.experimentalIncludeAllPages)).filter(page => {
379
+ return (this.#options.experimentalDevToolsDebugging ||
380
+ !page.url().startsWith('devtools://'));
381
+ });
382
+ const allTargets = this.browser.targets();
383
+ const extensionTargets = allTargets.filter(target => {
384
+ return (target.url().startsWith('chrome-extension://') &&
385
+ target.type() === 'page');
386
+ });
387
+ await Promise.allSettled(extensionTargets.map(async (target) => {
544
388
  try {
545
- if (await page.hasDevTools()) {
546
- mcpPage.devToolsPage = await page.openDevTools();
389
+ let page = await target.page();
390
+ if (!page) {
391
+ page = await target.asPage();
547
392
  }
548
- else {
549
- mcpPage.devToolsPage = undefined;
393
+ this.#extensionPages.set(target, page);
394
+ if (page && !allPages.includes(page)) {
395
+ allPages.push(page);
550
396
  }
551
397
  }
552
- catch {
553
- mcpPage.devToolsPage = undefined;
398
+ catch (e) {
399
+ this.logger?.('Failed to get page for extension target', e);
554
400
  }
555
401
  }));
402
+ return allPages;
556
403
  }
557
404
  getExtensionServiceWorkers() {
558
405
  return this.#extensionServiceWorkers;
@@ -560,12 +407,6 @@ export class McpContext {
560
407
  getExtensionServiceWorkerId(extensionServiceWorker) {
561
408
  return this.#extensionServiceWorkerMap.get(extensionServiceWorker.target);
562
409
  }
563
- getPages() {
564
- return this.#pages;
565
- }
566
- getIsolatedContextName(page) {
567
- return this.#mcpPages.get(page)?.isolatedContextName;
568
- }
569
410
  async saveTemporaryFile(data, filename) {
570
411
  const filepath = await getTempFilePath(filename);
571
412
  await this.validatePath(filepath);
@@ -597,38 +438,6 @@ export class McpContext {
597
438
  recordedTraces() {
598
439
  return this.#traceResults;
599
440
  }
600
- getNetworkRequestStableId(request) {
601
- return this.#networkCollector.getIdForResource(request);
602
- }
603
- waitForTextOnPage(text, timeout, targetPage) {
604
- const page = targetPage ?? this.getSelectedPptrPage();
605
- const frames = page.frames();
606
- let locator = this.#locatorClass.race(frames.flatMap(frame => text.flatMap(value => [
607
- frame.locator(`aria/${value}`),
608
- frame.locator(`text/${value}`),
609
- ])));
610
- if (timeout) {
611
- locator = locator.setTimeout(timeout);
612
- }
613
- return locator.wait();
614
- }
615
- /**
616
- * We need to ignore favicon request as they make our test flaky
617
- */
618
- async setUpNetworkCollectorForTesting() {
619
- this.#networkCollector = new NetworkCollector(this.browser, collect => {
620
- return {
621
- request: req => {
622
- if (req.url().includes('favicon.ico')) {
623
- return;
624
- }
625
- collect(req);
626
- },
627
- };
628
- });
629
- const { pages } = await this.#getAllPages();
630
- await this.#networkCollector.init(pages);
631
- }
632
441
  async installExtension(extensionPath) {
633
442
  const id = await this.browser.installExtension(extensionPath);
634
443
  return id;
@@ -642,7 +451,7 @@ export class McpContext {
642
451
  if (!extension) {
643
452
  throw new Error(`Extension with ID ${id} not found.`);
644
453
  }
645
- const page = this.getSelectedPptrPage();
454
+ const page = this.getSelectedMcpPage().pptrPage;
646
455
  await extension.triggerAction(page);
647
456
  }
648
457
  listExtensions() {
@@ -652,8 +461,8 @@ export class McpContext {
652
461
  const pptrExtensions = await this.browser.extensions();
653
462
  return pptrExtensions.get(id);
654
463
  }
655
- async getHeapSnapshotAggregates(filePath) {
656
- return await this.#heapSnapshotManager.getAggregates(filePath);
464
+ async getHeapSnapshotAggregates(filePath, filterName) {
465
+ return await this.#heapSnapshotManager.getAggregates(filePath, filterName);
657
466
  }
658
467
  async getHeapSnapshotDuplicateStrings(filePath) {
659
468
  return await this.#heapSnapshotManager.getDuplicateStrings(filePath);
@@ -664,8 +473,8 @@ export class McpContext {
664
473
  async getHeapSnapshotStaticData(filePath) {
665
474
  return await this.#heapSnapshotManager.getStaticData(filePath);
666
475
  }
667
- async getHeapSnapshotNodesById(filePath, id) {
668
- return await this.#heapSnapshotManager.getNodesById(filePath, id);
476
+ async getHeapSnapshotNodesById(filePath, id, filterName) {
477
+ return await this.#heapSnapshotManager.getNodesById(filePath, id, filterName);
669
478
  }
670
479
  async getHeapSnapshotRetainers(filePath, nodeId) {
671
480
  return await this.#heapSnapshotManager.getRetainers(filePath, nodeId);