chrome-devtools-mcp 1.4.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.
- package/README.md +20 -3
- package/build/src/HeapSnapshotManager.js +83 -16
- package/build/src/McpContext.js +218 -367
- package/build/src/McpPage.js +242 -31
- package/build/src/McpResponse.js +165 -60
- package/build/src/PageCollector.js +48 -122
- package/build/src/TextSnapshot.js +20 -2
- package/build/src/ToolHandler.js +13 -3
- package/build/src/WaitForHelper.js +18 -8
- package/build/src/bin/chrome-devtools-cli-options.js +76 -4
- package/build/src/bin/chrome-devtools-mcp-cli-options.js +15 -6
- package/build/src/bin/chrome-devtools-mcp-main.js +2 -2
- package/build/src/bin/chrome-devtools.js +25 -1
- package/build/src/browser.js +1 -1
- package/build/src/daemon/client.js +33 -3
- package/build/src/daemon/daemon.js +3 -2
- package/build/src/daemon/utils.js +1 -1
- package/build/src/devtools/DevtoolsUtils.js +2 -63
- package/build/src/{issue-descriptions.js → devtools/issueDescriptions.js} +8 -6
- package/build/src/formatters/HeapSnapshotFormatter.js +43 -0
- package/build/src/formatters/IssueFormatter.js +2 -2
- package/build/src/index.js +14 -5
- package/build/src/telemetry/ClearcutLogger.js +1 -1
- package/build/src/telemetry/WatchdogClient.js +1 -1
- package/build/src/telemetry/metricsRegistry.js +2 -9
- package/build/src/telemetry/persistence.js +1 -1
- package/build/src/telemetry/transformation.js +20 -0
- package/build/src/telemetry/watchdog/ClearcutSender.js +1 -1
- package/build/src/telemetry/watchdog/main.js +1 -1
- package/build/src/third_party/THIRD_PARTY_NOTICES +13 -279
- package/build/src/third_party/bundled-packages.json +3 -5
- package/build/src/third_party/devtools-heap-snapshot-worker.js +81 -0
- package/build/src/third_party/index.js +2418 -2197
- package/build/src/third_party/lighthouse-devtools-mcp-bundle.js +3082 -6343
- package/build/src/tools/emulation.js +2 -2
- package/build/src/tools/extensions.js +1 -1
- package/build/src/tools/input.js +17 -8
- package/build/src/tools/lighthouse.js +1 -1
- package/build/src/tools/memory.js +76 -6
- package/build/src/tools/network.js +4 -4
- package/build/src/tools/pages.js +21 -89
- package/build/src/tools/performance.js +2 -2
- package/build/src/tools/screencast.js +1 -2
- package/build/src/tools/script.js +6 -10
- package/build/src/tools/snapshot.js +2 -2
- package/build/src/tools/thirdPartyDeveloper.js +7 -7
- package/build/src/tools/webmcp.js +1 -1
- package/build/src/trace-processing/parse.js +1 -1
- package/build/src/utils/files.js +0 -4
- package/build/src/{logger.js → utils/logger.js} +1 -1
- package/build/src/{polyfill.js → utils/polyfill.js} +1 -1
- package/build/src/version.js +1 -1
- package/package.json +17 -5
- package/skills/memory-leak-debugging/SKILL.md +22 -14
- package/build/src/utils/types.js +0 -7
- /package/build/src/{Mutex.js → utils/Mutex.js} +0 -0
package/build/src/McpContext.js
CHANGED
|
@@ -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
|
|
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,
|
|
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
|
-
import {
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
18
|
+
import { getTempFilePath, resolveCanonicalPath } from './utils/files.js';
|
|
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
|
-
#
|
|
35
|
-
#consoleCollector;
|
|
36
|
-
#devtoolsUniverseManager;
|
|
34
|
+
#selectedPageFallback;
|
|
37
35
|
#serviceWorkerConsoleCollector;
|
|
38
36
|
#isRunningTrace = false;
|
|
39
37
|
#screenRecorderData = null;
|
|
40
|
-
#
|
|
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.#
|
|
60
|
-
this.#
|
|
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
|
-
|
|
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
|
|
86
|
-
this
|
|
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
|
-
|
|
125
|
-
|
|
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
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
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
|
-
|
|
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.
|
|
@@ -156,35 +187,12 @@ export class McpContext {
|
|
|
156
187
|
throw new Error(`Access denied: path ${filePath} (canonical: ${canonicalPath}) is not within any of the configured workspace roots.`);
|
|
157
188
|
}
|
|
158
189
|
}
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
// @ts-expect-error id is internal.
|
|
166
|
-
return request.id === cdpRequestId;
|
|
167
|
-
});
|
|
168
|
-
if (!request) {
|
|
169
|
-
this.logger?.('no network request for ' + cdpRequestId);
|
|
170
|
-
return;
|
|
171
|
-
}
|
|
172
|
-
return this.#networkCollector.getIdForResource(request);
|
|
173
|
-
}
|
|
174
|
-
getNetworkRequests(page, includePreservedRequests) {
|
|
175
|
-
return this.#networkCollector.getData(page.pptrPage, includePreservedRequests);
|
|
176
|
-
}
|
|
177
|
-
getConsoleData(page, includePreservedMessages) {
|
|
178
|
-
return this.#consoleCollector.getData(page.pptrPage, includePreservedMessages);
|
|
179
|
-
}
|
|
180
|
-
getDevToolsUniverse(page) {
|
|
181
|
-
return this.#devtoolsUniverseManager.get(page.pptrPage);
|
|
182
|
-
}
|
|
183
|
-
getConsoleMessageStableId(message) {
|
|
184
|
-
return this.#consoleCollector.getIdForResource(message);
|
|
185
|
-
}
|
|
186
|
-
getConsoleMessageById(page, id) {
|
|
187
|
-
return this.#consoleCollector.getById(page.pptrPage, id);
|
|
190
|
+
async ensureExtension(filePath, extension) {
|
|
191
|
+
const resolvedPath = path.resolve(filePath);
|
|
192
|
+
const currentExtension = path.extname(resolvedPath);
|
|
193
|
+
const outputPath = `${resolvedPath.slice(0, resolvedPath.length - currentExtension.length)}${extension}`;
|
|
194
|
+
await this.validatePath(outputPath);
|
|
195
|
+
return outputPath;
|
|
188
196
|
}
|
|
189
197
|
async newPage(background, isolatedContextName) {
|
|
190
198
|
let page;
|
|
@@ -199,14 +207,13 @@ export class McpContext {
|
|
|
199
207
|
else {
|
|
200
208
|
page = await this.browser.newPage({ background });
|
|
201
209
|
}
|
|
210
|
+
const mcpPage = await this.#createMcpPage(page);
|
|
202
211
|
await this.createPagesSnapshot();
|
|
203
|
-
this.selectPage(
|
|
204
|
-
|
|
205
|
-
this.#consoleCollector.addPage(page);
|
|
206
|
-
return this.#getMcpPage(page);
|
|
212
|
+
this.selectPage(mcpPage);
|
|
213
|
+
return mcpPage;
|
|
207
214
|
}
|
|
208
215
|
async closePage(pageId) {
|
|
209
|
-
if (this.#
|
|
216
|
+
if (this.#mcpPages.size === 1) {
|
|
210
217
|
throw new Error(CLOSE_PAGE_ERROR);
|
|
211
218
|
}
|
|
212
219
|
const page = this.getPageById(pageId);
|
|
@@ -216,114 +223,8 @@ export class McpContext {
|
|
|
216
223
|
}
|
|
217
224
|
await page.pptrPage.close({ runBeforeUnload: false });
|
|
218
225
|
}
|
|
219
|
-
|
|
220
|
-
return this.#
|
|
221
|
-
}
|
|
222
|
-
async restoreEmulation(page) {
|
|
223
|
-
const currentSetting = page.emulationSettings;
|
|
224
|
-
await this.emulate(currentSetting, page.pptrPage);
|
|
225
|
-
}
|
|
226
|
-
async emulate(options, targetPage) {
|
|
227
|
-
const page = targetPage ?? this.getSelectedPptrPage();
|
|
228
|
-
const mcpPage = this.#getMcpPage(page);
|
|
229
|
-
const newSettings = { ...mcpPage.emulationSettings };
|
|
230
|
-
// Skip network emulation if blocklist/allowlist is configured, as it conflicts with blocking rules in Puppeteer.
|
|
231
|
-
if (this.#options.hasNetworkBlockOrAllowlist) {
|
|
232
|
-
if (options.networkConditions !== undefined) {
|
|
233
|
-
throw new Error('Network throttling is not supported when network blocking (allowlist/blocklist) is configured.');
|
|
234
|
-
}
|
|
235
|
-
}
|
|
236
|
-
else if (!options.networkConditions) {
|
|
237
|
-
await page.emulateNetworkConditions(null);
|
|
238
|
-
delete newSettings.networkConditions;
|
|
239
|
-
}
|
|
240
|
-
else if (options.networkConditions === 'Offline') {
|
|
241
|
-
await page.emulateNetworkConditions({
|
|
242
|
-
offline: true,
|
|
243
|
-
download: 0,
|
|
244
|
-
upload: 0,
|
|
245
|
-
latency: 0,
|
|
246
|
-
});
|
|
247
|
-
newSettings.networkConditions = 'Offline';
|
|
248
|
-
}
|
|
249
|
-
else if (options.networkConditions in PredefinedNetworkConditions) {
|
|
250
|
-
const networkCondition = PredefinedNetworkConditions[options.networkConditions];
|
|
251
|
-
await page.emulateNetworkConditions(networkCondition);
|
|
252
|
-
newSettings.networkConditions = options.networkConditions;
|
|
253
|
-
}
|
|
254
|
-
const secondarySession = this.getDevToolsUniverse(mcpPage)?.session;
|
|
255
|
-
if (!options.cpuThrottlingRate) {
|
|
256
|
-
await page.emulateCPUThrottling(1);
|
|
257
|
-
if (secondarySession) {
|
|
258
|
-
await secondarySession.send('Emulation.setCPUThrottlingRate', {
|
|
259
|
-
rate: 1,
|
|
260
|
-
});
|
|
261
|
-
}
|
|
262
|
-
delete newSettings.cpuThrottlingRate;
|
|
263
|
-
}
|
|
264
|
-
else {
|
|
265
|
-
await page.emulateCPUThrottling(options.cpuThrottlingRate);
|
|
266
|
-
if (secondarySession) {
|
|
267
|
-
await secondarySession.send('Emulation.setCPUThrottlingRate', {
|
|
268
|
-
rate: options.cpuThrottlingRate,
|
|
269
|
-
});
|
|
270
|
-
}
|
|
271
|
-
newSettings.cpuThrottlingRate = options.cpuThrottlingRate;
|
|
272
|
-
}
|
|
273
|
-
if (!options.geolocation) {
|
|
274
|
-
await page.setGeolocation({ latitude: 0, longitude: 0 });
|
|
275
|
-
delete newSettings.geolocation;
|
|
276
|
-
}
|
|
277
|
-
else {
|
|
278
|
-
await page.setGeolocation(options.geolocation);
|
|
279
|
-
newSettings.geolocation = options.geolocation;
|
|
280
|
-
}
|
|
281
|
-
if (!options.userAgent) {
|
|
282
|
-
await page.setUserAgent({ userAgent: undefined });
|
|
283
|
-
delete newSettings.userAgent;
|
|
284
|
-
}
|
|
285
|
-
else {
|
|
286
|
-
await page.setUserAgent({ userAgent: options.userAgent });
|
|
287
|
-
newSettings.userAgent = options.userAgent;
|
|
288
|
-
}
|
|
289
|
-
if (!options.colorScheme || options.colorScheme === 'auto') {
|
|
290
|
-
await page.emulateMediaFeatures([
|
|
291
|
-
{ name: 'prefers-color-scheme', value: '' },
|
|
292
|
-
]);
|
|
293
|
-
delete newSettings.colorScheme;
|
|
294
|
-
}
|
|
295
|
-
else {
|
|
296
|
-
await page.emulateMediaFeatures([
|
|
297
|
-
{ name: 'prefers-color-scheme', value: options.colorScheme },
|
|
298
|
-
]);
|
|
299
|
-
newSettings.colorScheme = options.colorScheme;
|
|
300
|
-
}
|
|
301
|
-
if (!options.viewport) {
|
|
302
|
-
delete newSettings.viewport;
|
|
303
|
-
}
|
|
304
|
-
else {
|
|
305
|
-
const defaults = {
|
|
306
|
-
deviceScaleFactor: 1,
|
|
307
|
-
isMobile: false,
|
|
308
|
-
hasTouch: false,
|
|
309
|
-
isLandscape: false,
|
|
310
|
-
};
|
|
311
|
-
newSettings.viewport = { ...defaults, ...options.viewport };
|
|
312
|
-
}
|
|
313
|
-
if (options.extraHttpHeaders !== undefined) {
|
|
314
|
-
await page.setExtraHTTPHeaders(options.extraHttpHeaders);
|
|
315
|
-
newSettings.extraHttpHeaders = options.extraHttpHeaders;
|
|
316
|
-
if (Object.keys(options.extraHttpHeaders).length === 0) {
|
|
317
|
-
delete newSettings.extraHttpHeaders;
|
|
318
|
-
}
|
|
319
|
-
}
|
|
320
|
-
mcpPage.emulationSettings = Object.keys(newSettings).length
|
|
321
|
-
? newSettings
|
|
322
|
-
: {};
|
|
323
|
-
this.#updateSelectedPageTimeouts();
|
|
324
|
-
// This should happen after updating the page timeouts.
|
|
325
|
-
// Setting the viewport can trigger a reload which we don't want to timeout.
|
|
326
|
-
await page.setViewport(newSettings.viewport ?? null);
|
|
226
|
+
get #hasNetworkBlockOrAllowlist() {
|
|
227
|
+
return !!(this.#options.allowList || this.#options.blocklist);
|
|
327
228
|
}
|
|
328
229
|
setIsRunningPerformanceTrace(x) {
|
|
329
230
|
this.#isRunningTrace = x;
|
|
@@ -340,7 +241,10 @@ export class McpContext {
|
|
|
340
241
|
isCruxEnabled() {
|
|
341
242
|
return this.#options.performanceCrux;
|
|
342
243
|
}
|
|
343
|
-
|
|
244
|
+
getPages() {
|
|
245
|
+
return Array.from(this.#mcpPages.values());
|
|
246
|
+
}
|
|
247
|
+
getSelectedMcpPage() {
|
|
344
248
|
const page = this.#selectedPage;
|
|
345
249
|
if (!page) {
|
|
346
250
|
throw new Error('No page selected');
|
|
@@ -348,11 +252,17 @@ export class McpContext {
|
|
|
348
252
|
if (page.pptrPage.isClosed()) {
|
|
349
253
|
throw new Error(`The selected page has been closed. Call ${listPages().name} to see open pages.`);
|
|
350
254
|
}
|
|
351
|
-
return page
|
|
255
|
+
return page;
|
|
352
256
|
}
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
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;
|
|
356
266
|
}
|
|
357
267
|
getPageById(pageId) {
|
|
358
268
|
const page = this.#mcpPages.values().find(mcpPage => mcpPage.id === pageId);
|
|
@@ -361,55 +271,27 @@ export class McpContext {
|
|
|
361
271
|
}
|
|
362
272
|
return page;
|
|
363
273
|
}
|
|
364
|
-
getPageId(page) {
|
|
365
|
-
return this.#mcpPages.get(page)?.id;
|
|
366
|
-
}
|
|
367
|
-
#getMcpPage(page) {
|
|
368
|
-
const mcpPage = this.#mcpPages.get(page);
|
|
369
|
-
if (!mcpPage) {
|
|
370
|
-
throw new Error('No McpPage found for the given page.');
|
|
371
|
-
}
|
|
372
|
-
return mcpPage;
|
|
373
|
-
}
|
|
374
|
-
#getSelectedMcpPage() {
|
|
375
|
-
return this.#getMcpPage(this.getSelectedPptrPage());
|
|
376
|
-
}
|
|
377
274
|
isPageSelected(page) {
|
|
378
|
-
return this.#selectedPage
|
|
275
|
+
return this.#selectedPage === page;
|
|
379
276
|
}
|
|
380
277
|
selectPage(newPage) {
|
|
381
278
|
this.#selectedPage = newPage;
|
|
382
|
-
|
|
383
|
-
}
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
// Increased in case we throttle the network requests or the CPU
|
|
393
|
-
const networkMultiplier = getNetworkMultiplierFromString(page.networkConditions);
|
|
394
|
-
page.pptrPage.setDefaultNavigationTimeout(NAVIGATION_TIMEOUT * networkMultiplier * cpuMultiplier);
|
|
395
|
-
}
|
|
396
|
-
// Linear scan over per-page snapshots. The page count is small (typically
|
|
397
|
-
// 2-10) so a reverse index isn't worthwhile given the uid-reuse lifecycle
|
|
398
|
-
// complexity it would introduce.
|
|
399
|
-
getAXNodeByUid(uid) {
|
|
400
|
-
for (const mcpPage of this.#mcpPages.values()) {
|
|
401
|
-
const node = mcpPage.textSnapshot?.idToNode.get(uid);
|
|
402
|
-
if (node) {
|
|
403
|
-
return node;
|
|
404
|
-
}
|
|
405
|
-
}
|
|
406
|
-
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;
|
|
407
289
|
}
|
|
408
290
|
/**
|
|
409
291
|
* Creates a snapshot of the extension service workers.
|
|
410
292
|
*/
|
|
411
293
|
async createExtensionServiceWorkersSnapshot() {
|
|
412
|
-
const allTargets =
|
|
294
|
+
const allTargets = this.browser.targets();
|
|
413
295
|
const serviceWorkers = allTargets.filter(target => {
|
|
414
296
|
return (target.type() === 'service_worker' &&
|
|
415
297
|
target.url().includes('chrome-extension://'));
|
|
@@ -431,74 +313,13 @@ export class McpContext {
|
|
|
431
313
|
getServiceWorkerConsoleData(extensionId) {
|
|
432
314
|
return this.#serviceWorkerConsoleCollector.getData(extensionId);
|
|
433
315
|
}
|
|
434
|
-
|
|
435
|
-
const { pages: allPages, isolatedContextNames } = await this.#getAllPages();
|
|
436
|
-
for (const page of allPages) {
|
|
437
|
-
let mcpPage = this.#mcpPages.get(page);
|
|
438
|
-
if (!mcpPage) {
|
|
439
|
-
mcpPage = new McpPage(page, this.#nextPageId++);
|
|
440
|
-
this.#mcpPages.set(page, mcpPage);
|
|
441
|
-
// We emulate a focused page for all pages to support multi-agent workflows.
|
|
442
|
-
void page.emulateFocusedPage(true).catch(error => {
|
|
443
|
-
this.logger?.('Error turning on focused page emulation', error);
|
|
444
|
-
});
|
|
445
|
-
}
|
|
446
|
-
mcpPage.isolatedContextName = isolatedContextNames.get(page);
|
|
447
|
-
}
|
|
448
|
-
// Prune orphaned #mcpPages entries (pages that no longer exist).
|
|
449
|
-
const currentPages = new Set(allPages);
|
|
450
|
-
for (const [page, mcpPage] of this.#mcpPages) {
|
|
451
|
-
if (!currentPages.has(page)) {
|
|
452
|
-
mcpPage.dispose();
|
|
453
|
-
this.#mcpPages.delete(page);
|
|
454
|
-
}
|
|
455
|
-
}
|
|
456
|
-
this.#pages = allPages.filter(page => {
|
|
457
|
-
return (this.#options.experimentalDevToolsDebugging ||
|
|
458
|
-
!page.url().startsWith('devtools://'));
|
|
459
|
-
});
|
|
460
|
-
if ((!this.#selectedPage ||
|
|
461
|
-
this.#pages.indexOf(this.#selectedPage.pptrPage) === -1) &&
|
|
462
|
-
this.#pages[0]) {
|
|
463
|
-
this.selectPage(this.#getMcpPage(this.#pages[0]));
|
|
464
|
-
}
|
|
465
|
-
await this.detectOpenDevToolsWindows();
|
|
466
|
-
return this.#pages;
|
|
467
|
-
}
|
|
468
|
-
async #getAllPages() {
|
|
469
|
-
const defaultCtx = this.browser.defaultBrowserContext();
|
|
470
|
-
const allPages = await this.browser.pages(this.#options.experimentalIncludeAllPages);
|
|
471
|
-
const allTargets = this.browser.targets();
|
|
472
|
-
const extensionTargets = allTargets.filter(target => {
|
|
473
|
-
return (target.url().startsWith('chrome-extension://') &&
|
|
474
|
-
target.type() === 'page');
|
|
475
|
-
});
|
|
476
|
-
for (const target of extensionTargets) {
|
|
477
|
-
// Right now target.page() returns null for popup and side panel pages.
|
|
478
|
-
let page = await target.page();
|
|
479
|
-
if (!page) {
|
|
480
|
-
// We need to cache pages instances for targets because target.asPage()
|
|
481
|
-
// returns a new page instance every time.
|
|
482
|
-
page = this.#extensionPages.get(target) ?? null;
|
|
483
|
-
if (!page) {
|
|
484
|
-
try {
|
|
485
|
-
page = await target.asPage();
|
|
486
|
-
this.#extensionPages.set(target, page);
|
|
487
|
-
}
|
|
488
|
-
catch (e) {
|
|
489
|
-
this.logger?.('Failed to get page for extension target', e);
|
|
490
|
-
}
|
|
491
|
-
}
|
|
492
|
-
}
|
|
493
|
-
if (page && !allPages.includes(page)) {
|
|
494
|
-
allPages.push(page);
|
|
495
|
-
}
|
|
496
|
-
}
|
|
316
|
+
#getBrowserContextToNameMap() {
|
|
497
317
|
// Build a reverse lookup from BrowserContext instance → name.
|
|
498
318
|
const contextToName = new Map();
|
|
499
319
|
for (const [name, ctx] of this.#isolatedContexts) {
|
|
500
320
|
contextToName.set(ctx, name);
|
|
501
321
|
}
|
|
322
|
+
const defaultCtx = this.browser.defaultBrowserContext();
|
|
502
323
|
// Auto-discover BrowserContexts not in our mapping (e.g., externally
|
|
503
324
|
// created incognito contexts) and assign generated names.
|
|
504
325
|
const knownContexts = new Set(this.#isolatedContexts.values());
|
|
@@ -509,40 +330,76 @@ export class McpContext {
|
|
|
509
330
|
contextToName.set(ctx, name);
|
|
510
331
|
}
|
|
511
332
|
}
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
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();
|
|
520
345
|
}
|
|
521
|
-
return
|
|
346
|
+
return mcpPage;
|
|
522
347
|
}
|
|
523
|
-
async
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
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
|
+
};
|
|
530
372
|
}
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
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) => {
|
|
534
388
|
try {
|
|
535
|
-
|
|
536
|
-
|
|
389
|
+
let page = await target.page();
|
|
390
|
+
if (!page) {
|
|
391
|
+
page = await target.asPage();
|
|
537
392
|
}
|
|
538
|
-
|
|
539
|
-
|
|
393
|
+
this.#extensionPages.set(target, page);
|
|
394
|
+
if (page && !allPages.includes(page)) {
|
|
395
|
+
allPages.push(page);
|
|
540
396
|
}
|
|
541
397
|
}
|
|
542
|
-
catch {
|
|
543
|
-
|
|
398
|
+
catch (e) {
|
|
399
|
+
this.logger?.('Failed to get page for extension target', e);
|
|
544
400
|
}
|
|
545
401
|
}));
|
|
402
|
+
return allPages;
|
|
546
403
|
}
|
|
547
404
|
getExtensionServiceWorkers() {
|
|
548
405
|
return this.#extensionServiceWorkers;
|
|
@@ -550,12 +407,6 @@ export class McpContext {
|
|
|
550
407
|
getExtensionServiceWorkerId(extensionServiceWorker) {
|
|
551
408
|
return this.#extensionServiceWorkerMap.get(extensionServiceWorker.target);
|
|
552
409
|
}
|
|
553
|
-
getPages() {
|
|
554
|
-
return this.#pages;
|
|
555
|
-
}
|
|
556
|
-
getIsolatedContextName(page) {
|
|
557
|
-
return this.#mcpPages.get(page)?.isolatedContextName;
|
|
558
|
-
}
|
|
559
410
|
async saveTemporaryFile(data, filename) {
|
|
560
411
|
const filepath = await getTempFilePath(filename);
|
|
561
412
|
await this.validatePath(filepath);
|
|
@@ -568,9 +419,8 @@ export class McpContext {
|
|
|
568
419
|
return { filepath };
|
|
569
420
|
}
|
|
570
421
|
async saveFile(data, clientProvidedFilePath, extension) {
|
|
571
|
-
await this.
|
|
422
|
+
const filePath = await this.ensureExtension(clientProvidedFilePath, extension);
|
|
572
423
|
try {
|
|
573
|
-
const filePath = ensureExtension(path.resolve(clientProvidedFilePath), extension);
|
|
574
424
|
await fs.mkdir(path.dirname(filePath), { recursive: true });
|
|
575
425
|
await fs.writeFile(filePath, data);
|
|
576
426
|
return { filename: filePath };
|
|
@@ -588,38 +438,6 @@ export class McpContext {
|
|
|
588
438
|
recordedTraces() {
|
|
589
439
|
return this.#traceResults;
|
|
590
440
|
}
|
|
591
|
-
getNetworkRequestStableId(request) {
|
|
592
|
-
return this.#networkCollector.getIdForResource(request);
|
|
593
|
-
}
|
|
594
|
-
waitForTextOnPage(text, timeout, targetPage) {
|
|
595
|
-
const page = targetPage ?? this.getSelectedPptrPage();
|
|
596
|
-
const frames = page.frames();
|
|
597
|
-
let locator = this.#locatorClass.race(frames.flatMap(frame => text.flatMap(value => [
|
|
598
|
-
frame.locator(`aria/${value}`),
|
|
599
|
-
frame.locator(`text/${value}`),
|
|
600
|
-
])));
|
|
601
|
-
if (timeout) {
|
|
602
|
-
locator = locator.setTimeout(timeout);
|
|
603
|
-
}
|
|
604
|
-
return locator.wait();
|
|
605
|
-
}
|
|
606
|
-
/**
|
|
607
|
-
* We need to ignore favicon request as they make our test flaky
|
|
608
|
-
*/
|
|
609
|
-
async setUpNetworkCollectorForTesting() {
|
|
610
|
-
this.#networkCollector = new NetworkCollector(this.browser, collect => {
|
|
611
|
-
return {
|
|
612
|
-
request: req => {
|
|
613
|
-
if (req.url().includes('favicon.ico')) {
|
|
614
|
-
return;
|
|
615
|
-
}
|
|
616
|
-
collect(req);
|
|
617
|
-
},
|
|
618
|
-
};
|
|
619
|
-
});
|
|
620
|
-
const { pages } = await this.#getAllPages();
|
|
621
|
-
await this.#networkCollector.init(pages);
|
|
622
|
-
}
|
|
623
441
|
async installExtension(extensionPath) {
|
|
624
442
|
const id = await this.browser.installExtension(extensionPath);
|
|
625
443
|
return id;
|
|
@@ -633,7 +451,7 @@ export class McpContext {
|
|
|
633
451
|
if (!extension) {
|
|
634
452
|
throw new Error(`Extension with ID ${id} not found.`);
|
|
635
453
|
}
|
|
636
|
-
const page = this.
|
|
454
|
+
const page = this.getSelectedMcpPage().pptrPage;
|
|
637
455
|
await extension.triggerAction(page);
|
|
638
456
|
}
|
|
639
457
|
listExtensions() {
|
|
@@ -643,8 +461,11 @@ export class McpContext {
|
|
|
643
461
|
const pptrExtensions = await this.browser.extensions();
|
|
644
462
|
return pptrExtensions.get(id);
|
|
645
463
|
}
|
|
646
|
-
async getHeapSnapshotAggregates(filePath) {
|
|
647
|
-
return await this.#heapSnapshotManager.getAggregates(filePath);
|
|
464
|
+
async getHeapSnapshotAggregates(filePath, filterName) {
|
|
465
|
+
return await this.#heapSnapshotManager.getAggregates(filePath, filterName);
|
|
466
|
+
}
|
|
467
|
+
async getHeapSnapshotDuplicateStrings(filePath) {
|
|
468
|
+
return await this.#heapSnapshotManager.getDuplicateStrings(filePath);
|
|
648
469
|
}
|
|
649
470
|
async getHeapSnapshotStats(filePath) {
|
|
650
471
|
return await this.#heapSnapshotManager.getStats(filePath);
|
|
@@ -652,8 +473,8 @@ export class McpContext {
|
|
|
652
473
|
async getHeapSnapshotStaticData(filePath) {
|
|
653
474
|
return await this.#heapSnapshotManager.getStaticData(filePath);
|
|
654
475
|
}
|
|
655
|
-
async getHeapSnapshotNodesById(filePath, id) {
|
|
656
|
-
return await this.#heapSnapshotManager.getNodesById(filePath, id);
|
|
476
|
+
async getHeapSnapshotNodesById(filePath, id, filterName) {
|
|
477
|
+
return await this.#heapSnapshotManager.getNodesById(filePath, id, filterName);
|
|
657
478
|
}
|
|
658
479
|
async getHeapSnapshotRetainers(filePath, nodeId) {
|
|
659
480
|
return await this.#heapSnapshotManager.getRetainers(filePath, nodeId);
|
|
@@ -670,12 +491,36 @@ export class McpContext {
|
|
|
670
491
|
async getHeapSnapshotDominators(filePath, nodeId) {
|
|
671
492
|
return await this.#heapSnapshotManager.getDominatorsOf(filePath, nodeId);
|
|
672
493
|
}
|
|
494
|
+
#validateUrlNotBlocked(url) {
|
|
495
|
+
if (!this.#options.blocklist) {
|
|
496
|
+
return;
|
|
497
|
+
}
|
|
498
|
+
for (const block of this.#options.blocklist) {
|
|
499
|
+
const pattern = new URLPattern(block);
|
|
500
|
+
if (pattern.test(url)) {
|
|
501
|
+
throw new Error(`Blocked by blocklist: ${url}`);
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
#validateUrlAllowed(url) {
|
|
506
|
+
if (!this.#options.allowList) {
|
|
507
|
+
return;
|
|
508
|
+
}
|
|
509
|
+
for (const allow of this.#options.allowList) {
|
|
510
|
+
const pattern = new URLPattern(allow);
|
|
511
|
+
if (pattern.test(url)) {
|
|
512
|
+
return;
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
throw new Error(`Not allowed by allowlist: ${url}`);
|
|
516
|
+
}
|
|
673
517
|
async loadResource(path) {
|
|
674
518
|
const url = new URL(path);
|
|
519
|
+
this.#validateUrlNotBlocked(url);
|
|
675
520
|
switch (url.protocol) {
|
|
676
521
|
case 'https:':
|
|
677
522
|
case 'http:': {
|
|
678
|
-
|
|
523
|
+
this.#validateUrlAllowed(url);
|
|
679
524
|
const response = await fetch(url);
|
|
680
525
|
if (!response.ok) {
|
|
681
526
|
throw new Error(`Failed to load resource: ${url}`);
|
|
@@ -693,5 +538,11 @@ export class McpContext {
|
|
|
693
538
|
async getHeapSnapshotEdges(filePath, nodeId) {
|
|
694
539
|
return await this.#heapSnapshotManager.getEdges(filePath, nodeId);
|
|
695
540
|
}
|
|
541
|
+
async getHeapSnapshotClassDiffs(baseFilePath, currentFilePath) {
|
|
542
|
+
return await this.#heapSnapshotManager.getClassDiffs(baseFilePath, currentFilePath);
|
|
543
|
+
}
|
|
544
|
+
async getHeapSnapshotDetailedClassDiff(baseFilePath, currentFilePath, classIndex) {
|
|
545
|
+
return await this.#heapSnapshotManager.getDetailedClassDiff(baseFilePath, currentFilePath, classIndex);
|
|
546
|
+
}
|
|
696
547
|
}
|
|
697
548
|
//# sourceMappingURL=McpContext.js.map
|