chrome-devtools-mcp 1.11.0 → 1.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +72 -20
- package/build/src/BrowserManager.js +27 -18
- package/build/src/McpContext.js +435 -87
- package/build/src/McpPage.js +189 -59
- package/build/src/McpResponse.js +61 -44
- package/build/src/TextSnapshot.js +37 -18
- package/build/src/ToolHandler.js +256 -135
- package/build/src/bin/chrome-devtools-mcp-main.js +6 -4
- package/build/src/bin/chrome-devtools.js +4 -4
- package/build/src/collectors/PageCollector.js +13 -9
- package/build/src/collectors/ServiceWorkerCollector.js +2 -2
- package/build/src/collectors/constants.js +7 -0
- package/build/src/config/ConfigParser.js +44 -149
- package/build/src/config/ConfigWatcher.js +3 -2
- package/build/src/config/ServerConfig.js +251 -0
- package/build/src/config/browser-options.js +13 -4
- package/build/src/config/cli-options.js +35 -19
- package/build/src/config/mcp-options.js +61 -35
- package/build/src/config/puppeteer-options.js +4 -2
- package/build/src/daemon/client.js +3 -3
- package/build/src/daemon/daemon.js +7 -3
- package/build/src/daemon/utils.js +2 -1
- package/build/src/devtools/DevToolsCommentBridge.js +28 -5
- package/build/src/devtools/DevtoolsUtils.js +49 -12
- package/build/src/formatters/ConsoleFormatter.js +28 -1
- package/build/src/formatters/HeapSnapshotFormatter.js +14 -18
- package/build/src/formatters/NetworkFormatter.js +54 -15
- package/build/src/formatters/RemoteObjectFormatter.js +231 -0
- package/build/src/formatters/SnapshotFormatter.js +13 -3
- package/build/src/index.js +256 -104
- package/build/src/processors/HeapSnapshotManager.js +390 -128
- package/build/src/third_party/THIRD_PARTY_NOTICES +542 -445
- package/build/src/third_party/bundled-packages.json +2 -2
- package/build/src/third_party/cli.js +9239 -0
- package/build/src/third_party/devtools-formatter-worker.js +3089 -2438
- package/build/src/third_party/devtools-heap-snapshot-worker.js +172 -1
- package/build/src/third_party/index.js +52247 -55764
- package/build/src/third_party/lighthouse-devtools-mcp-bundle.js +54576 -52174
- package/build/src/tools/ToolDefinition.js +90 -12
- package/build/src/tools/comments.js +42 -3
- package/build/src/tools/console.js +6 -4
- package/build/src/tools/css.js +1 -0
- package/build/src/tools/emulation.js +5 -4
- package/build/src/tools/extensions.js +5 -0
- package/build/src/tools/input.js +21 -6
- package/build/src/tools/lighthouse.js +24 -8
- package/build/src/tools/memory.js +59 -53
- package/build/src/tools/network.js +5 -4
- package/build/src/tools/pages.js +48 -6
- package/build/src/tools/performance.js +7 -4
- package/build/src/tools/pwa.js +7 -0
- package/build/src/tools/screencast.js +3 -1
- package/build/src/tools/screenshot.js +23 -7
- package/build/src/tools/script.js +38 -6
- package/build/src/tools/slim/tools.js +21 -5
- package/build/src/tools/snapshot.js +13 -3
- package/build/src/tools/thirdPartyDeveloper.js +3 -1
- package/build/src/tools/webmcp.js +2 -0
- package/build/src/utils/TaskRunner.js +136 -0
- package/build/src/utils/WaitForHelper.js +1 -1
- package/build/src/utils/bytes.js +2 -12
- package/build/src/utils/check-for-updates.js +1 -1
- package/build/src/utils/disclaimers.js +27 -0
- package/build/src/utils/keyboard.js +14 -2
- package/build/src/utils/logger.js +69 -0
- package/build/src/utils/resourceType.js +27 -0
- package/build/src/utils/text.js +29 -0
- package/build/src/utils/timeout.js +14 -0
- package/build/src/utils/url.js +41 -0
- package/build/src/version.js +1 -1
- package/package.json +5 -4
- package/skills/a11y-debugging/SKILL.md +3 -8
package/build/src/McpContext.js
CHANGED
|
@@ -3,27 +3,120 @@
|
|
|
3
3
|
* Copyright 2025 Google LLC
|
|
4
4
|
* SPDX-License-Identifier: Apache-2.0
|
|
5
5
|
*/
|
|
6
|
+
var __addDisposableResource = (this && this.__addDisposableResource) || function (env, value, async) {
|
|
7
|
+
if (value !== null && value !== void 0) {
|
|
8
|
+
if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected.");
|
|
9
|
+
var dispose, inner;
|
|
10
|
+
if (async) {
|
|
11
|
+
if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined.");
|
|
12
|
+
dispose = value[Symbol.asyncDispose];
|
|
13
|
+
}
|
|
14
|
+
if (dispose === void 0) {
|
|
15
|
+
if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");
|
|
16
|
+
dispose = value[Symbol.dispose];
|
|
17
|
+
if (async) inner = dispose;
|
|
18
|
+
}
|
|
19
|
+
if (typeof dispose !== "function") throw new TypeError("Object not disposable.");
|
|
20
|
+
if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } };
|
|
21
|
+
env.stack.push({ value: value, dispose: dispose, async: async });
|
|
22
|
+
}
|
|
23
|
+
else if (async) {
|
|
24
|
+
env.stack.push({ async: true });
|
|
25
|
+
}
|
|
26
|
+
return value;
|
|
27
|
+
};
|
|
28
|
+
var __disposeResources = (this && this.__disposeResources) || (function (SuppressedError) {
|
|
29
|
+
return function (env) {
|
|
30
|
+
function fail(e) {
|
|
31
|
+
env.error = env.hasError ? new SuppressedError(e, env.error, "An error was suppressed during disposal.") : e;
|
|
32
|
+
env.hasError = true;
|
|
33
|
+
}
|
|
34
|
+
var r, s = 0;
|
|
35
|
+
function next() {
|
|
36
|
+
while (r = env.stack.pop()) {
|
|
37
|
+
try {
|
|
38
|
+
if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next);
|
|
39
|
+
if (r.dispose) {
|
|
40
|
+
var result = r.dispose.call(r.value);
|
|
41
|
+
if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); });
|
|
42
|
+
}
|
|
43
|
+
else s |= 1;
|
|
44
|
+
}
|
|
45
|
+
catch (e) {
|
|
46
|
+
fail(e);
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve();
|
|
50
|
+
if (env.hasError) throw env.error;
|
|
51
|
+
}
|
|
52
|
+
return next();
|
|
53
|
+
};
|
|
54
|
+
})(typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
|
|
55
|
+
var e = new Error(message);
|
|
56
|
+
return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
|
|
57
|
+
});
|
|
6
58
|
import fs from 'node:fs/promises';
|
|
7
59
|
import os from 'node:os';
|
|
8
60
|
import path from 'node:path';
|
|
9
61
|
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
62
|
+
import { isDeepStrictEqual } from 'node:util';
|
|
10
63
|
import { overrideDevToolsGlobals } from './devtools/DevtoolsUtils.js';
|
|
11
64
|
import { McpPage } from './McpPage.js';
|
|
12
65
|
import { ServiceWorkerConsoleCollector } from './collectors/ServiceWorkerCollector.js';
|
|
13
|
-
import { Locator, } from './third_party/index.js';
|
|
14
|
-
import {
|
|
66
|
+
import { Locator, Mutex, } from './third_party/index.js';
|
|
67
|
+
import { ToolCategory } from './tools/categories.js';
|
|
68
|
+
import { CLOSE_PAGE_ERROR, isCapabilityEnabled, } from './tools/ToolDefinition.js';
|
|
15
69
|
import { McpWorker } from './McpWorker.js';
|
|
16
70
|
import { getTempFilePath, resolveCanonicalPath } from './utils/files.js';
|
|
17
71
|
import { escapeForLog } from './utils/logger.js';
|
|
18
72
|
import { isAllowedUrl } from './utils/url.js';
|
|
73
|
+
function hasOptionChanged(gate, previousArgs, nextArgs) {
|
|
74
|
+
return gate.options.some(option => !isDeepStrictEqual(nextArgs[option], previousArgs[option]));
|
|
75
|
+
}
|
|
76
|
+
const FEATURE_CONTROLLERS = [
|
|
77
|
+
{
|
|
78
|
+
gate: { options: ['blockedUrlPattern', 'allowedUrlPattern'] },
|
|
79
|
+
onChange: context => context.syncNetworkRestrictions(),
|
|
80
|
+
},
|
|
81
|
+
{
|
|
82
|
+
gate: { options: ['sourceMaps'] },
|
|
83
|
+
onChange: context => context.syncSourceMaps(),
|
|
84
|
+
},
|
|
85
|
+
{
|
|
86
|
+
gate: { options: ['experimentalIncludeAllPages'] },
|
|
87
|
+
onChange: context => context.createPagesSnapshot(),
|
|
88
|
+
},
|
|
89
|
+
{
|
|
90
|
+
gate: { category: ToolCategory.DEBUGGING },
|
|
91
|
+
onDisable: context => context.releaseScreencasts(),
|
|
92
|
+
},
|
|
93
|
+
{
|
|
94
|
+
gate: { category: ToolCategory.MEMORY, conditions: ['memoryDebugging'] },
|
|
95
|
+
onDisable: context => context.releaseHeapSnapshots(),
|
|
96
|
+
},
|
|
97
|
+
{
|
|
98
|
+
gate: { category: ToolCategory.PERFORMANCE },
|
|
99
|
+
onDisable: context => context.releasePerformanceTrace(),
|
|
100
|
+
},
|
|
101
|
+
{
|
|
102
|
+
gate: { category: ToolCategory.DEBUGGING, conditions: ['devtoolsComments'] },
|
|
103
|
+
onDisable: context => context.releaseDevToolsComments(),
|
|
104
|
+
},
|
|
105
|
+
];
|
|
19
106
|
// Page ids are handed out from a process-wide counter so they stay unique
|
|
20
107
|
// across all contexts, in particular across browser reconnects. An id issued
|
|
21
108
|
// before a reconnect then fails to resolve instead of hitting an unrelated
|
|
22
109
|
// page of the reconnected browser.
|
|
23
110
|
let nextPageId = 1;
|
|
24
111
|
export class McpContext {
|
|
25
|
-
browser;
|
|
26
112
|
logger;
|
|
113
|
+
#browser;
|
|
114
|
+
// Initialization of #browser, settles once its browser-dependent state is
|
|
115
|
+
// ready.
|
|
116
|
+
#browserReady;
|
|
117
|
+
// Whether a browser connection was established before, so that switching to
|
|
118
|
+
// a new browser surfaces a reconnect notice.
|
|
119
|
+
#hasConnected = false;
|
|
27
120
|
// Maps LLM-provided isolatedContext name → Puppeteer BrowserContext.
|
|
28
121
|
#isolatedContexts = new Map();
|
|
29
122
|
// Auto-generated name counter for when no name is provided.
|
|
@@ -32,53 +125,240 @@ export class McpContext {
|
|
|
32
125
|
// referential identity holds and workers can carry per-worker state later.
|
|
33
126
|
#workers = new Map();
|
|
34
127
|
#mcpPages = new Map();
|
|
128
|
+
/**
|
|
129
|
+
* Queue for the browser-wide state (page list, selected page, trace
|
|
130
|
+
* state). Every page queue is a child of it, so a task on it waits for
|
|
131
|
+
* every page task and blocks later page tasks.
|
|
132
|
+
*/
|
|
133
|
+
taskQueue;
|
|
134
|
+
#taskRunner;
|
|
135
|
+
#pageTaskQueues = new Map();
|
|
136
|
+
/**
|
|
137
|
+
* Serializes `createPagesSnapshot()`. Two tasks on different page queues
|
|
138
|
+
* can call it at the same time.
|
|
139
|
+
*/
|
|
140
|
+
#pagesSnapshotMutex = new Mutex();
|
|
35
141
|
#selectedPage;
|
|
36
142
|
#selectedPageFallback;
|
|
143
|
+
#selectedPageFallbackRead = false;
|
|
37
144
|
#serviceWorkerConsoleCollector;
|
|
38
|
-
#isRunningTrace = false;
|
|
39
145
|
#reconnectNotice = false;
|
|
40
146
|
#traceResults = [];
|
|
41
147
|
#locatorClass;
|
|
148
|
+
#config;
|
|
42
149
|
#options;
|
|
43
150
|
#heapSnapshotManager;
|
|
44
151
|
#roots = undefined;
|
|
45
|
-
|
|
46
|
-
constructor(browser, logger, options, locatorClass) {
|
|
152
|
+
constructor(logger, options, locatorClass) {
|
|
47
153
|
overrideDevToolsGlobals({
|
|
48
154
|
loadResource: (url) => {
|
|
49
155
|
return this.loadResource(url);
|
|
50
156
|
},
|
|
51
157
|
});
|
|
52
|
-
this.browser = browser;
|
|
53
158
|
this.logger = logger;
|
|
54
159
|
this.#locatorClass = locatorClass;
|
|
160
|
+
this.#taskRunner = options.taskRunner;
|
|
161
|
+
this.taskQueue = options.taskRunner.createQueue();
|
|
162
|
+
this.#config = options.config;
|
|
55
163
|
this.#options = options;
|
|
56
164
|
this.#heapSnapshotManager = options.heapSnapshotManager;
|
|
57
|
-
this.#allowUnrestrictedPaths = options.allowUnrestrictedPaths ?? false;
|
|
58
|
-
this.#reconnectNotice = options.reconnected ?? false;
|
|
59
|
-
this.#serviceWorkerConsoleCollector = new ServiceWorkerConsoleCollector(this.browser);
|
|
60
165
|
}
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
166
|
+
/**
|
|
167
|
+
* The browser of the current connection. Throws if no browser connection was
|
|
168
|
+
* established yet, see {@link McpContext.ensureBrowser}.
|
|
169
|
+
*/
|
|
170
|
+
get browser() {
|
|
171
|
+
if (!this.#browser) {
|
|
172
|
+
throw new Error('Not connected to a browser.');
|
|
173
|
+
}
|
|
174
|
+
return this.#browser;
|
|
67
175
|
}
|
|
68
|
-
|
|
69
|
-
this.
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
176
|
+
#allMcpPages() {
|
|
177
|
+
const pages = new Set(this.#mcpPages.values());
|
|
178
|
+
if (this.#selectedPage) {
|
|
179
|
+
pages.add(this.#selectedPage);
|
|
180
|
+
}
|
|
181
|
+
return pages;
|
|
182
|
+
}
|
|
183
|
+
/**
|
|
184
|
+
* Synchronizes browser/page state and releases state of capabilities that
|
|
185
|
+
* transitioned from enabled to disabled after a config reload.
|
|
186
|
+
*/
|
|
187
|
+
async onConfigChanged(previousArgs) {
|
|
188
|
+
const nextArgs = this.#config.resolved;
|
|
189
|
+
for (const controller of FEATURE_CONTROLLERS) {
|
|
190
|
+
if ('onChange' in controller) {
|
|
191
|
+
if (hasOptionChanged(controller.gate, previousArgs, nextArgs)) {
|
|
192
|
+
await controller.onChange(this);
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
else if (isCapabilityEnabled(controller.gate, previousArgs) &&
|
|
196
|
+
!isCapabilityEnabled(controller.gate, nextArgs)) {
|
|
197
|
+
await controller.onDisable(this);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
/**
|
|
202
|
+
* Applies updated URL allowlist/blocklist rules to the connected browser and
|
|
203
|
+
* clears incompatible page network throttling state.
|
|
204
|
+
*/
|
|
205
|
+
async syncNetworkRestrictions() {
|
|
206
|
+
const { blockedUrlPattern, allowedUrlPattern } = this.#config.resolved;
|
|
207
|
+
if (blockedUrlPattern || allowedUrlPattern) {
|
|
208
|
+
for (const mcpPage of this.#allMcpPages()) {
|
|
209
|
+
await mcpPage.clearNetworkConditions();
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
if (this.#browser) {
|
|
213
|
+
await this.#browser.restrictNetwork({
|
|
214
|
+
blocklist: blockedUrlPattern,
|
|
215
|
+
allowlist: allowedUrlPattern,
|
|
216
|
+
});
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
/**
|
|
220
|
+
* Synchronizes the DevTools source maps setting across all pages.
|
|
221
|
+
*/
|
|
222
|
+
syncSourceMaps() {
|
|
223
|
+
for (const mcpPage of this.#allMcpPages()) {
|
|
224
|
+
mcpPage.syncSourceMaps();
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
/**
|
|
228
|
+
* Stops and saves active screencast recordings across all pages when
|
|
229
|
+
* screencast tools are disabled.
|
|
230
|
+
*/
|
|
231
|
+
async releaseScreencasts() {
|
|
232
|
+
for (const mcpPage of this.#allMcpPages()) {
|
|
233
|
+
const screenRecorderData = mcpPage.getScreenRecorder();
|
|
234
|
+
if (!screenRecorderData) {
|
|
235
|
+
continue;
|
|
236
|
+
}
|
|
237
|
+
const { recorder, filePath } = screenRecorderData;
|
|
238
|
+
mcpPage.setScreenRecorder(null);
|
|
239
|
+
try {
|
|
240
|
+
await recorder.stop();
|
|
241
|
+
this.logger?.(`The screencast recording was stopped and saved to ${filePath} because screencast tools were disabled.`);
|
|
242
|
+
}
|
|
243
|
+
catch (err) {
|
|
244
|
+
this.logger?.('Failed to stop the screencast recording', err);
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
/**
|
|
249
|
+
* Closes all loaded heap snapshots when memory tools are disabled.
|
|
250
|
+
*/
|
|
251
|
+
releaseHeapSnapshots() {
|
|
252
|
+
if (this.#heapSnapshotManager.hasSnapshots()) {
|
|
253
|
+
this.#heapSnapshotManager.dispose();
|
|
254
|
+
this.logger?.('Loaded heap snapshots were closed because memory tools were disabled.');
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
/**
|
|
258
|
+
* Discards recorded performance traces and stops any running trace when
|
|
259
|
+
* performance tools are disabled.
|
|
260
|
+
*/
|
|
261
|
+
async releasePerformanceTrace() {
|
|
262
|
+
this.#traceResults = [];
|
|
263
|
+
for (const mcpPage of this.#allMcpPages()) {
|
|
264
|
+
if (!mcpPage.isRunningPerformanceTrace()) {
|
|
265
|
+
continue;
|
|
266
|
+
}
|
|
267
|
+
mcpPage.setIsRunningPerformanceTrace(false);
|
|
268
|
+
try {
|
|
269
|
+
await mcpPage.pptrPage.tracing.stop();
|
|
270
|
+
}
|
|
271
|
+
catch (err) {
|
|
272
|
+
this.logger?.('Failed to stop the performance trace', err);
|
|
273
|
+
}
|
|
274
|
+
this.logger?.('The running performance trace was discarded because performance tools were disabled.');
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
/**
|
|
278
|
+
* Disposes DevTools comment bridges across all pages when DevTools comment
|
|
279
|
+
* tools are disabled.
|
|
280
|
+
*/
|
|
281
|
+
releaseDevToolsComments() {
|
|
282
|
+
for (const mcpPage of this.#allMcpPages()) {
|
|
283
|
+
mcpPage.disposeCommentBridge();
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
/**
|
|
287
|
+
* Returns the browser, establishing the connection if needed. If the browser
|
|
288
|
+
* changed since the last call (e.g. after a reconnect), all
|
|
289
|
+
* browser-dependent state is rebuilt for the new browser.
|
|
290
|
+
*/
|
|
291
|
+
async ensureBrowser() {
|
|
292
|
+
const browser = await this.#options.getBrowser();
|
|
293
|
+
if (browser === this.#browser && this.#browserReady) {
|
|
294
|
+
// Joins a still pending initialization instead of handing out
|
|
295
|
+
// half-initialized state.
|
|
296
|
+
await this.#browserReady;
|
|
297
|
+
return browser;
|
|
298
|
+
}
|
|
299
|
+
this.#resetBrowserState();
|
|
300
|
+
this.#browser = browser;
|
|
301
|
+
const ready = this.#initBrowserState(browser);
|
|
302
|
+
this.#browserReady = ready;
|
|
303
|
+
try {
|
|
304
|
+
await ready;
|
|
305
|
+
return browser;
|
|
306
|
+
}
|
|
307
|
+
catch (err) {
|
|
308
|
+
// Leave no half-initialized state behind, the next call starts over. If
|
|
309
|
+
// a later call already installed another browser, its state is left
|
|
310
|
+
// intact.
|
|
311
|
+
if (this.#browserReady === ready) {
|
|
312
|
+
this.#resetBrowserState();
|
|
313
|
+
}
|
|
314
|
+
throw err;
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
async #initBrowserState(browser) {
|
|
318
|
+
const collector = new ServiceWorkerConsoleCollector(browser);
|
|
319
|
+
this.#serviceWorkerConsoleCollector = collector;
|
|
320
|
+
// All listeners are registered synchronously, before the first await. If
|
|
321
|
+
// this call hangs and is abandoned by the tool-call timeout, a later call
|
|
322
|
+
// that installs a different browser removes them in #resetBrowserState().
|
|
323
|
+
browser.on('targetcreated', this.#onTargetCreated);
|
|
324
|
+
browser.on('targetdestroyed', this.#onTargetDestroyed);
|
|
325
|
+
await Promise.all([
|
|
326
|
+
collector.init(this.createWorkersSnapshot()),
|
|
327
|
+
this.createPagesSnapshot(),
|
|
328
|
+
]);
|
|
329
|
+
// The state now belongs to the browser of a later call, leave it intact.
|
|
330
|
+
if (this.#browser !== browser) {
|
|
331
|
+
throw new Error('Browser was replaced while initializing.');
|
|
332
|
+
}
|
|
333
|
+
if (this.#hasConnected) {
|
|
334
|
+
this.#reconnectNotice = true;
|
|
335
|
+
}
|
|
336
|
+
this.#hasConnected = true;
|
|
337
|
+
}
|
|
338
|
+
#resetBrowserState() {
|
|
339
|
+
this.#browser?.off('targetcreated', this.#onTargetCreated);
|
|
340
|
+
this.#browser?.off('targetdestroyed', this.#onTargetDestroyed);
|
|
341
|
+
this.#serviceWorkerConsoleCollector?.dispose();
|
|
342
|
+
for (const mcpPage of this.#allMcpPages()) {
|
|
343
|
+
this.#disposeMcpPage(mcpPage);
|
|
74
344
|
}
|
|
75
|
-
this.#selectedPage?.dispose();
|
|
76
345
|
this.#mcpPages.clear();
|
|
77
346
|
this.#workers.clear();
|
|
78
347
|
// Isolated contexts are intentionally not closed here.
|
|
79
348
|
// Either the entire browser will be closed or we disconnect
|
|
80
349
|
// without destroying browser state.
|
|
81
350
|
this.#isolatedContexts.clear();
|
|
351
|
+
this.#nextIsolatedContextId = 1;
|
|
352
|
+
this.#selectedPage = undefined;
|
|
353
|
+
this.#selectedPageFallback = undefined;
|
|
354
|
+
this.#selectedPageFallbackRead = false;
|
|
355
|
+
this.#traceResults = [];
|
|
356
|
+
this.#serviceWorkerConsoleCollector = undefined;
|
|
357
|
+
this.#browser = undefined;
|
|
358
|
+
this.#browserReady = undefined;
|
|
359
|
+
}
|
|
360
|
+
dispose() {
|
|
361
|
+
this.#resetBrowserState();
|
|
82
362
|
}
|
|
83
363
|
#onTargetCreated = (target) => {
|
|
84
364
|
try {
|
|
@@ -95,7 +375,7 @@ export class McpContext {
|
|
|
95
375
|
try {
|
|
96
376
|
const mcpPage = this.#mcpPages.get(target);
|
|
97
377
|
if (mcpPage) {
|
|
98
|
-
mcpPage
|
|
378
|
+
this.#disposeMcpPage(mcpPage);
|
|
99
379
|
this.#mcpPages.delete(target);
|
|
100
380
|
}
|
|
101
381
|
this.#workers.delete(target);
|
|
@@ -104,12 +384,10 @@ export class McpContext {
|
|
|
104
384
|
this.logger?.('Error handling targetdestroyed', err);
|
|
105
385
|
}
|
|
106
386
|
};
|
|
107
|
-
static
|
|
387
|
+
static create(logger, opts,
|
|
108
388
|
/* Let tests use unbundled Locator class to avoid overly strict checks within puppeteer that fail when mixing bundled and unbundled class instances */
|
|
109
389
|
locatorClass = Locator) {
|
|
110
|
-
|
|
111
|
-
await context.#init();
|
|
112
|
-
return context;
|
|
390
|
+
return new McpContext(logger, opts, locatorClass);
|
|
113
391
|
}
|
|
114
392
|
static resetPageIdsForTesting() {
|
|
115
393
|
nextPageId = 1;
|
|
@@ -145,7 +423,8 @@ export class McpContext {
|
|
|
145
423
|
// If the client never negotiated roots and the operator has explicitly
|
|
146
424
|
// opted into unrestricted access via --allow-unrestricted-paths, restore
|
|
147
425
|
// the previous permissive behavior and skip validation.
|
|
148
|
-
if (this.#roots === undefined &&
|
|
426
|
+
if (this.#roots === undefined &&
|
|
427
|
+
this.#config.resolved.allowUnrestrictedPaths) {
|
|
149
428
|
// Canonical path might not exist yet so we fallback to
|
|
150
429
|
// path.resolve(filePath). Consumers should not follow symlinks.
|
|
151
430
|
return canonicalPath || path.resolve(filePath);
|
|
@@ -166,8 +445,13 @@ export class McpContext {
|
|
|
166
445
|
const result = resolvedRoots[i];
|
|
167
446
|
if (result.status === 'fulfilled') {
|
|
168
447
|
const canonicalRoot = result.value;
|
|
448
|
+
// A filesystem root such as `/` or `C:\` already ends with the
|
|
449
|
+
// separator; appending another one would match no path below it.
|
|
450
|
+
const rootPrefix = canonicalRoot.endsWith(path.sep)
|
|
451
|
+
? canonicalRoot
|
|
452
|
+
: canonicalRoot + path.sep;
|
|
169
453
|
if (canonicalPath === canonicalRoot ||
|
|
170
|
-
canonicalPath.startsWith(
|
|
454
|
+
canonicalPath.startsWith(rootPrefix)) {
|
|
171
455
|
allowed = true;
|
|
172
456
|
break;
|
|
173
457
|
}
|
|
@@ -204,7 +488,7 @@ export class McpContext {
|
|
|
204
488
|
page = await this.browser.newPage({ background });
|
|
205
489
|
}
|
|
206
490
|
const mcpPage = this.#createMcpPage(page.target());
|
|
207
|
-
await mcpPage.init();
|
|
491
|
+
await mcpPage.init({ emulateFocus: true });
|
|
208
492
|
this.selectPage(mcpPage);
|
|
209
493
|
await this.createPagesSnapshot();
|
|
210
494
|
return mcpPage;
|
|
@@ -217,9 +501,6 @@ export class McpContext {
|
|
|
217
501
|
this.#mcpPages.delete(page.target);
|
|
218
502
|
await page.close();
|
|
219
503
|
}
|
|
220
|
-
get #hasNetworkBlockOrAllowlist() {
|
|
221
|
-
return !!(this.#options.allowlist || this.#options.blocklist);
|
|
222
|
-
}
|
|
223
504
|
async installPWA(options) {
|
|
224
505
|
try {
|
|
225
506
|
return await this.browser.installPWA(options);
|
|
@@ -251,14 +532,16 @@ export class McpContext {
|
|
|
251
532
|
getPWAState(options) {
|
|
252
533
|
return this.browser.getPWAState(options);
|
|
253
534
|
}
|
|
254
|
-
setIsRunningPerformanceTrace(x) {
|
|
255
|
-
this.#isRunningTrace = x;
|
|
256
|
-
}
|
|
257
535
|
isRunningPerformanceTrace() {
|
|
258
|
-
|
|
536
|
+
for (const mcpPage of this.#allMcpPages()) {
|
|
537
|
+
if (mcpPage.isRunningPerformanceTrace()) {
|
|
538
|
+
return true;
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
return false;
|
|
259
542
|
}
|
|
260
543
|
isCruxEnabled() {
|
|
261
|
-
return this.#
|
|
544
|
+
return this.#config.resolved.performanceCrux;
|
|
262
545
|
}
|
|
263
546
|
getPages() {
|
|
264
547
|
return Array.from(this.#mcpPages.values());
|
|
@@ -327,9 +610,9 @@ export class McpContext {
|
|
|
327
610
|
}
|
|
328
611
|
}
|
|
329
612
|
/**
|
|
330
|
-
* Returns true once
|
|
331
|
-
*
|
|
332
|
-
*
|
|
613
|
+
* Returns true once after the browser connection was re-established with a
|
|
614
|
+
* new browser, so the next response can surface a note. Cleared on first
|
|
615
|
+
* call.
|
|
333
616
|
*/
|
|
334
617
|
consumeReconnectNotice() {
|
|
335
618
|
const notice = this.#reconnectNotice;
|
|
@@ -343,14 +626,39 @@ export class McpContext {
|
|
|
343
626
|
}
|
|
344
627
|
return page;
|
|
345
628
|
}
|
|
629
|
+
/**
|
|
630
|
+
* The queue for tasks on page `pageId`. The queue exists before the page
|
|
631
|
+
* does, so a tool call can enter it before the browser connects. It is a
|
|
632
|
+
* child of {@link taskQueue}.
|
|
633
|
+
*/
|
|
634
|
+
pageTaskQueue(pageId) {
|
|
635
|
+
let queue = this.#pageTaskQueues.get(pageId);
|
|
636
|
+
if (!queue) {
|
|
637
|
+
queue = this.#taskRunner.createQueue(this.taskQueue);
|
|
638
|
+
this.#pageTaskQueues.set(pageId, queue);
|
|
639
|
+
}
|
|
640
|
+
return queue;
|
|
641
|
+
}
|
|
642
|
+
#disposeMcpPage(mcpPage) {
|
|
643
|
+
mcpPage.dispose();
|
|
644
|
+
this.#pageTaskQueues
|
|
645
|
+
.get(mcpPage.id)
|
|
646
|
+
?.dispose(new Error(`Page ${mcpPage.id} is closed.`));
|
|
647
|
+
this.#pageTaskQueues.delete(mcpPage.id);
|
|
648
|
+
}
|
|
346
649
|
isPageSelected(page) {
|
|
347
650
|
return this.#selectedPage === page;
|
|
348
651
|
}
|
|
349
652
|
selectPage(newPage) {
|
|
653
|
+
this.#selectedPageFallback = undefined;
|
|
654
|
+
this.#selectedPageFallbackRead = false;
|
|
655
|
+
this.#selectPage(newPage);
|
|
656
|
+
}
|
|
657
|
+
#selectPage(newPage) {
|
|
350
658
|
if (this.#selectedPage &&
|
|
351
659
|
this.#selectedPage !== newPage &&
|
|
352
660
|
!this.#mcpPages.has(this.#selectedPage.target)) {
|
|
353
|
-
this.#selectedPage
|
|
661
|
+
this.#disposeMcpPage(this.#selectedPage);
|
|
354
662
|
}
|
|
355
663
|
this.#selectedPage = newPage;
|
|
356
664
|
newPage.updateTimeouts();
|
|
@@ -358,10 +666,12 @@ export class McpContext {
|
|
|
358
666
|
/**
|
|
359
667
|
* Returns details about the last page snapshot automatically replacing the
|
|
360
668
|
* selection because the selected page disappeared from the page list, or
|
|
361
|
-
* `undefined` if the snapshot left the selection intact.
|
|
362
|
-
* createPagesSnapshot() call
|
|
669
|
+
* `undefined` if the snapshot left the selection intact. Cleared on the next
|
|
670
|
+
* createPagesSnapshot() call after it has been read, or when selectPage() is
|
|
671
|
+
* called explicitly.
|
|
363
672
|
*/
|
|
364
673
|
getSelectedPageFallback() {
|
|
674
|
+
this.#selectedPageFallbackRead = true;
|
|
365
675
|
return this.#selectedPageFallback;
|
|
366
676
|
}
|
|
367
677
|
/**
|
|
@@ -390,8 +700,13 @@ export class McpContext {
|
|
|
390
700
|
}
|
|
391
701
|
return Array.from(this.#workers.values());
|
|
392
702
|
}
|
|
393
|
-
getServiceWorkerConsoleData(
|
|
394
|
-
|
|
703
|
+
getServiceWorkerConsoleData(serviceWorkerId) {
|
|
704
|
+
const worker = this.getWorkerById(serviceWorkerId);
|
|
705
|
+
if (worker?.type !== 'service_worker') {
|
|
706
|
+
throw new Error('Service worker not found.');
|
|
707
|
+
}
|
|
708
|
+
const extensionId = new URL(worker.url).hostname;
|
|
709
|
+
return this.#serviceWorkerConsoleCollector?.getData(extensionId) ?? [];
|
|
395
710
|
}
|
|
396
711
|
#getBrowserContextToNameMap() {
|
|
397
712
|
// Build a reverse lookup from BrowserContext instance → name.
|
|
@@ -417,61 +732,92 @@ export class McpContext {
|
|
|
417
732
|
(this.#selectedPage?.target === target ? this.#selectedPage : undefined);
|
|
418
733
|
if (!mcpPage) {
|
|
419
734
|
mcpPage = new McpPage(target, nextPageId++, {
|
|
735
|
+
config: this.#config,
|
|
420
736
|
locatorClass: this.#locatorClass,
|
|
421
|
-
hasNetworkBlockOrAllowlist: this.#hasNetworkBlockOrAllowlist,
|
|
422
737
|
isolatedContextName: this.#getBrowserContextToNameMap().get(target.browserContext()),
|
|
423
738
|
navigationTimeout: this.#options.navigationTimeout,
|
|
424
|
-
sourceMaps: this.#options.sourceMaps,
|
|
425
|
-
onNotification: this.#options.onNotification,
|
|
426
739
|
});
|
|
427
740
|
}
|
|
428
741
|
this.#mcpPages.set(target, mcpPage);
|
|
429
742
|
return mcpPage;
|
|
430
743
|
}
|
|
431
744
|
async createPagesSnapshot() {
|
|
432
|
-
const
|
|
433
|
-
|
|
434
|
-
this.#
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
745
|
+
const env_1 = { stack: [], error: void 0, hasError: false };
|
|
746
|
+
try {
|
|
747
|
+
if (!this.#browser) {
|
|
748
|
+
return [];
|
|
749
|
+
}
|
|
750
|
+
const guard = __addDisposableResource(env_1, await this.#pagesSnapshotMutex.acquire(), false);
|
|
751
|
+
const allTargets = this.#fetchPageTargets();
|
|
752
|
+
for (const target of allTargets) {
|
|
753
|
+
this.#createMcpPage(target);
|
|
754
|
+
}
|
|
755
|
+
// Prune orphaned #mcpPages entries (targets that no longer exist).
|
|
756
|
+
const currentTargets = new Set(allTargets);
|
|
757
|
+
for (const [target, mcpPage] of this.#mcpPages) {
|
|
758
|
+
if (!currentTargets.has(target)) {
|
|
759
|
+
if (mcpPage !== this.#selectedPage || mcpPage.isClosed()) {
|
|
760
|
+
this.#disposeMcpPage(mcpPage);
|
|
761
|
+
}
|
|
762
|
+
this.#mcpPages.delete(target);
|
|
442
763
|
}
|
|
443
|
-
this.#mcpPages.delete(target);
|
|
444
764
|
}
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
if (this.#selectedPage) {
|
|
455
|
-
this.#selectedPageFallback = {
|
|
456
|
-
wasClosed: this.#selectedPage.isClosed(),
|
|
457
|
-
};
|
|
765
|
+
const pages = Array.from(this.#mcpPages.values());
|
|
766
|
+
// Only fall back when the selected page is actually gone or no longer
|
|
767
|
+
// counts as a page, e.g. a background page after
|
|
768
|
+
// experimentalIncludeAllPages was turned off. Gating on `isClosed()`
|
|
769
|
+
// instead of `pages` membership avoids silently swapping a live page that
|
|
770
|
+
// is momentarily missing from the snapshot.
|
|
771
|
+
if (this.#selectedPageFallbackRead) {
|
|
772
|
+
this.#selectedPageFallback = undefined;
|
|
773
|
+
this.#selectedPageFallbackRead = false;
|
|
458
774
|
}
|
|
459
|
-
this
|
|
775
|
+
if (!this.#selectedPage ||
|
|
776
|
+
this.#selectedPage.isClosed() ||
|
|
777
|
+
!this.#isPageTarget(this.#selectedPage.target)) {
|
|
778
|
+
if (pages[0]) {
|
|
779
|
+
// Record the automatic change so the response can surface it. Skipped on
|
|
780
|
+
// first connect, when there was no prior selection to replace.
|
|
781
|
+
if (this.#selectedPage) {
|
|
782
|
+
this.#selectedPageFallback = {
|
|
783
|
+
wasClosed: this.#selectedPage.isClosed(),
|
|
784
|
+
};
|
|
785
|
+
}
|
|
786
|
+
this.#selectPage(pages[0]);
|
|
787
|
+
}
|
|
788
|
+
else if (this.#selectedPage) {
|
|
789
|
+
const wasClosed = Boolean(this.#selectedPage.isClosed());
|
|
790
|
+
if (!wasClosed) {
|
|
791
|
+
this.#disposeMcpPage(this.#selectedPage);
|
|
792
|
+
}
|
|
793
|
+
this.#selectedPage = undefined;
|
|
794
|
+
this.#selectedPageFallback = { wasClosed };
|
|
795
|
+
}
|
|
796
|
+
}
|
|
797
|
+
if (this.#selectedPage && !this.#selectedPage.isClosed()) {
|
|
798
|
+
// Automatic page snapshots must preserve real focus on untouched tabs.
|
|
799
|
+
await this.#selectedPage.init({ emulateFocus: false });
|
|
800
|
+
}
|
|
801
|
+
return pages;
|
|
460
802
|
}
|
|
461
|
-
|
|
462
|
-
|
|
803
|
+
catch (e_1) {
|
|
804
|
+
env_1.error = e_1;
|
|
805
|
+
env_1.hasError = true;
|
|
806
|
+
}
|
|
807
|
+
finally {
|
|
808
|
+
__disposeResources(env_1);
|
|
463
809
|
}
|
|
464
|
-
return pages;
|
|
465
810
|
}
|
|
466
811
|
#isPageTarget(target) {
|
|
467
|
-
const existingMcpPage = this.#mcpPages.get(target)
|
|
812
|
+
const existingMcpPage = this.#mcpPages.get(target) ??
|
|
813
|
+
(this.#selectedPage?.target === target ? this.#selectedPage : undefined);
|
|
468
814
|
const url = existingMcpPage ? existingMcpPage.url() : target.url();
|
|
469
|
-
if (!this.#
|
|
815
|
+
if (!this.#config.resolved.experimentalDevtools &&
|
|
470
816
|
url.startsWith('devtools://')) {
|
|
471
817
|
return false;
|
|
472
818
|
}
|
|
473
819
|
if (!isAllowedUrl(url, {
|
|
474
|
-
categoryExtensions: this.#
|
|
820
|
+
categoryExtensions: this.#config.resolved.categoryExtensions,
|
|
475
821
|
})) {
|
|
476
822
|
return false;
|
|
477
823
|
}
|
|
@@ -479,11 +825,11 @@ export class McpContext {
|
|
|
479
825
|
if (type === 'page') {
|
|
480
826
|
return true;
|
|
481
827
|
}
|
|
482
|
-
if (this.#
|
|
828
|
+
if (this.#config.resolved.experimentalIncludeAllPages &&
|
|
483
829
|
(type === 'background_page' || type === 'webview')) {
|
|
484
830
|
return true;
|
|
485
831
|
}
|
|
486
|
-
if (this.#
|
|
832
|
+
if (this.#config.resolved.experimentalDevtools &&
|
|
487
833
|
type === 'other' &&
|
|
488
834
|
url.startsWith('devtools://')) {
|
|
489
835
|
return true;
|
|
@@ -613,10 +959,11 @@ export class McpContext {
|
|
|
613
959
|
return await this.#heapSnapshotManager.getDominatorsOf(filePath, nodeId);
|
|
614
960
|
}
|
|
615
961
|
#validateUrlNotBlocked(url) {
|
|
616
|
-
|
|
962
|
+
const blocklist = this.#config.resolved.blockedUrlPattern;
|
|
963
|
+
if (!blocklist) {
|
|
617
964
|
return;
|
|
618
965
|
}
|
|
619
|
-
for (const block of
|
|
966
|
+
for (const block of blocklist) {
|
|
620
967
|
const pattern = new URLPattern(block);
|
|
621
968
|
if (pattern.test(url)) {
|
|
622
969
|
throw new Error(`Blocked by blocklist: ${url}`);
|
|
@@ -624,10 +971,11 @@ export class McpContext {
|
|
|
624
971
|
}
|
|
625
972
|
}
|
|
626
973
|
#validateUrlAllowed(url) {
|
|
627
|
-
|
|
974
|
+
const allowlist = this.#config.resolved.allowedUrlPattern;
|
|
975
|
+
if (!allowlist) {
|
|
628
976
|
return;
|
|
629
977
|
}
|
|
630
|
-
for (const allow of
|
|
978
|
+
for (const allow of allowlist) {
|
|
631
979
|
const pattern = new URLPattern(allow);
|
|
632
980
|
if (pattern.test(url)) {
|
|
633
981
|
return;
|