chrome-devtools-mcp 1.10.1 → 1.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +72 -20
- package/build/src/BrowserManager.js +155 -27
- package/build/src/McpContext.js +598 -200
- package/build/src/McpPage.js +513 -131
- package/build/src/McpResponse.js +291 -116
- package/build/src/McpWorker.js +66 -0
- package/build/src/SlimMcpResponse.js +5 -1
- package/build/src/TextSnapshot.js +40 -20
- package/build/src/ToolHandler.js +306 -147
- package/build/src/bin/chrome-devtools-mcp-main.js +13 -10
- package/build/src/bin/chrome-devtools-mcp.js +1 -1
- package/build/src/bin/chrome-devtools.js +34 -44
- package/build/src/collectors/PageCollector.js +13 -9
- package/build/src/collectors/ServiceWorkerCollector.js +20 -13
- package/build/src/collectors/constants.js +7 -0
- package/build/src/config/ConfigLocator.js +70 -0
- package/build/src/config/ConfigParser.js +159 -0
- package/build/src/config/ConfigWatcher.js +94 -0
- package/build/src/config/ServerConfig.js +251 -0
- package/build/src/config/browser-options.js +15 -17
- package/build/src/config/category-options.js +15 -30
- package/build/src/config/cli-commands.js +165 -5
- package/build/src/config/cli-options.js +441 -58
- package/build/src/config/mcp-options.js +212 -264
- package/build/src/config/puppeteer-options.js +67 -0
- package/build/src/config/tool-options.js +60 -0
- package/build/src/daemon/client.js +84 -44
- package/build/src/daemon/daemon.js +59 -45
- package/build/src/daemon/utils.js +46 -12
- package/build/src/devtools/DevToolsCommentBridge.js +71 -11
- package/build/src/devtools/DevtoolsUtils.js +52 -15
- package/build/src/devtools/McpHostBindingAdapter.js +0 -1
- package/build/src/formatters/CommentFormatter.js +4 -13
- package/build/src/formatters/ConsoleFormatter.js +29 -2
- package/build/src/formatters/CssFormatter.js +3 -2
- package/build/src/formatters/HeapSnapshotFormatter.js +111 -57
- package/build/src/formatters/IssueFormatter.js +33 -32
- package/build/src/formatters/NetworkFormatter.js +62 -22
- package/build/src/formatters/RemoteObjectFormatter.js +231 -0
- package/build/src/formatters/SnapshotFormatter.js +44 -7
- package/build/src/index.js +285 -88
- package/build/src/processors/ChunkedTraceParser.js +11 -11
- package/build/src/processors/HeapSnapshotManager.js +455 -156
- package/build/src/processors/PerformanceTrace.js +9 -9
- package/build/src/telemetry/ClearcutLogger.js +1 -1
- package/build/src/telemetry/transformation.js +7 -11
- package/build/src/telemetry/watchdog/main.js +1 -1
- package/build/src/third_party/THIRD_PARTY_NOTICES +399 -689
- package/build/src/third_party/bundled-packages.json +7 -8
- package/build/src/third_party/cli.js +9239 -0
- package/build/src/third_party/devtools-formatter-worker.js +4299 -2517
- package/build/src/third_party/devtools-heap-snapshot-worker.js +1298 -22
- package/build/src/third_party/index.js +132003 -146852
- package/build/src/third_party/issue-descriptions/cookieWarnMetadataGrantRead.md +0 -1
- package/build/src/third_party/issue-descriptions/cookieWarnMetadataGrantReadOptOut.md +5 -0
- package/build/src/third_party/issue-descriptions/cookieWarnMetadataGrantSet.md +0 -1
- package/build/src/third_party/issue-descriptions/cookieWarnMetadataGrantSetOptOut.md +5 -0
- package/build/src/third_party/issue-descriptions/deprecation.md +1 -1
- package/build/src/third_party/issue-descriptions/genericGeolocationPromptWithoutUserGesture.md +5 -0
- package/build/src/third_party/issue-descriptions/sriValidationFailedIntegrityMismatch.md +2 -0
- package/build/src/third_party/lighthouse-devtools-mcp-bundle.js +54576 -52174
- package/build/src/tools/ToolDefinition.js +102 -12
- package/build/src/tools/comments.js +62 -4
- package/build/src/tools/console.js +6 -4
- package/build/src/tools/css.js +5 -2
- package/build/src/tools/emulation.js +22 -8
- package/build/src/tools/extensions.js +5 -0
- package/build/src/tools/input.js +29 -9
- package/build/src/tools/lighthouse.js +136 -12
- package/build/src/tools/memory.js +166 -59
- package/build/src/tools/network.js +5 -4
- package/build/src/tools/pages.js +52 -7
- package/build/src/tools/performance.js +28 -7
- package/build/src/tools/pwa.js +7 -0
- package/build/src/tools/screencast.js +74 -33
- package/build/src/tools/screenshot.js +52 -21
- package/build/src/tools/script.js +125 -40
- package/build/src/tools/slim/tools.js +27 -13
- package/build/src/tools/snapshot.js +13 -3
- package/build/src/tools/thirdPartyDeveloper.js +9 -5
- package/build/src/tools/tools.js +35 -22
- package/build/src/tools/webmcp.js +11 -6
- package/build/src/types.js +11 -0
- package/build/src/utils/TaskRunner.js +136 -0
- package/build/src/utils/WaitForHelper.js +15 -2
- package/build/src/utils/bytes.js +2 -12
- package/build/src/utils/check-for-updates.js +2 -2
- package/build/src/utils/disclaimers.js +27 -0
- package/build/src/utils/errorHandling.js +20 -0
- package/build/src/utils/keyboard.js +14 -2
- package/build/src/utils/logger.js +84 -5
- package/build/src/utils/resourceType.js +27 -0
- package/build/src/utils/text.js +44 -0
- package/build/src/utils/timeout.js +14 -0
- package/build/src/utils/url.js +140 -3
- package/build/src/version.js +1 -1
- package/package.json +16 -11
- package/skills/a11y-debugging/SKILL.md +7 -12
- package/skills/chrome-devtools/SKILL.md +2 -2
- package/skills/chrome-devtools-cli/SKILL.md +18 -15
- package/skills/cookie-debugging/SKILL.md +8 -5
- package/skills/debug-optimize-lcp/SKILL.md +1 -1
- package/skills/troubleshooting/SKILL.md +5 -6
package/build/src/McpContext.js
CHANGED
|
@@ -3,95 +3,369 @@
|
|
|
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
|
-
import { HeapSnapshotManager } from './processors/HeapSnapshotManager.js';
|
|
12
64
|
import { McpPage } from './McpPage.js';
|
|
13
65
|
import { ServiceWorkerConsoleCollector } from './collectors/ServiceWorkerCollector.js';
|
|
14
|
-
import { Locator, } from './third_party/index.js';
|
|
15
|
-
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';
|
|
69
|
+
import { McpWorker } from './McpWorker.js';
|
|
16
70
|
import { getTempFilePath, resolveCanonicalPath } from './utils/files.js';
|
|
71
|
+
import { escapeForLog } from './utils/logger.js';
|
|
17
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
|
+
];
|
|
18
106
|
// Page ids are handed out from a process-wide counter so they stay unique
|
|
19
107
|
// across all contexts, in particular across browser reconnects. An id issued
|
|
20
108
|
// before a reconnect then fails to resolve instead of hitting an unrelated
|
|
21
109
|
// page of the reconnected browser.
|
|
22
110
|
let nextPageId = 1;
|
|
23
111
|
export class McpContext {
|
|
24
|
-
browser;
|
|
25
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;
|
|
26
120
|
// Maps LLM-provided isolatedContext name → Puppeteer BrowserContext.
|
|
27
121
|
#isolatedContexts = new Map();
|
|
28
122
|
// Auto-generated name counter for when no name is provided.
|
|
29
123
|
#nextIsolatedContextId = 1;
|
|
30
|
-
#
|
|
124
|
+
// Cached McpWorker per target, reused across snapshots (mirrors #mcpPages) so
|
|
125
|
+
// referential identity holds and workers can carry per-worker state later.
|
|
126
|
+
#workers = new Map();
|
|
31
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();
|
|
32
141
|
#selectedPage;
|
|
33
142
|
#selectedPageFallback;
|
|
143
|
+
#selectedPageFallbackRead = false;
|
|
34
144
|
#serviceWorkerConsoleCollector;
|
|
35
|
-
#isRunningTrace = false;
|
|
36
|
-
#screenRecorderData = null;
|
|
37
145
|
#reconnectNotice = false;
|
|
38
|
-
#extensionPages = new WeakMap();
|
|
39
|
-
#extensionServiceWorkerMap = new WeakMap();
|
|
40
|
-
#nextExtensionServiceWorkerId = 1;
|
|
41
146
|
#traceResults = [];
|
|
42
147
|
#locatorClass;
|
|
148
|
+
#config;
|
|
43
149
|
#options;
|
|
44
|
-
#heapSnapshotManager
|
|
150
|
+
#heapSnapshotManager;
|
|
45
151
|
#roots = undefined;
|
|
46
|
-
|
|
47
|
-
constructor(browser, logger, options, locatorClass) {
|
|
152
|
+
constructor(logger, options, locatorClass) {
|
|
48
153
|
overrideDevToolsGlobals({
|
|
49
154
|
loadResource: (url) => {
|
|
50
155
|
return this.loadResource(url);
|
|
51
156
|
},
|
|
52
157
|
});
|
|
53
|
-
this.browser = browser;
|
|
54
158
|
this.logger = logger;
|
|
55
159
|
this.#locatorClass = locatorClass;
|
|
160
|
+
this.#taskRunner = options.taskRunner;
|
|
161
|
+
this.taskQueue = options.taskRunner.createQueue();
|
|
162
|
+
this.#config = options.config;
|
|
56
163
|
this.#options = options;
|
|
57
|
-
this.#
|
|
58
|
-
this.#reconnectNotice = options.reconnected ?? false;
|
|
59
|
-
this.#serviceWorkerConsoleCollector = new ServiceWorkerConsoleCollector(this.browser);
|
|
164
|
+
this.#heapSnapshotManager = options.heapSnapshotManager;
|
|
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
|
-
|
|
74
|
-
|
|
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);
|
|
75
344
|
}
|
|
76
345
|
this.#mcpPages.clear();
|
|
346
|
+
this.#workers.clear();
|
|
77
347
|
// Isolated contexts are intentionally not closed here.
|
|
78
348
|
// Either the entire browser will be closed or we disconnect
|
|
79
349
|
// without destroying browser state.
|
|
80
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();
|
|
81
362
|
}
|
|
82
|
-
#onTargetCreated =
|
|
363
|
+
#onTargetCreated = (target) => {
|
|
83
364
|
try {
|
|
84
|
-
|
|
85
|
-
if (!isAllowedUrl(url, {
|
|
86
|
-
categoryExtensions: this.#options.categoryExtensions,
|
|
87
|
-
})) {
|
|
365
|
+
if (!this.#isPageTarget(target)) {
|
|
88
366
|
return;
|
|
89
367
|
}
|
|
90
|
-
|
|
91
|
-
if (!page) {
|
|
92
|
-
return;
|
|
93
|
-
}
|
|
94
|
-
void this.#createMcpPage(page);
|
|
368
|
+
this.#createMcpPage(target);
|
|
95
369
|
}
|
|
96
370
|
catch (err) {
|
|
97
371
|
this.logger?.('Error handling targetcreated', err);
|
|
@@ -99,36 +373,28 @@ export class McpContext {
|
|
|
99
373
|
};
|
|
100
374
|
#onTargetDestroyed = (target) => {
|
|
101
375
|
try {
|
|
102
|
-
|
|
103
|
-
for (const page of this.#mcpPages.keys()) {
|
|
104
|
-
if (page.target() === target) {
|
|
105
|
-
foundPage = page;
|
|
106
|
-
break;
|
|
107
|
-
}
|
|
108
|
-
}
|
|
109
|
-
if (!foundPage) {
|
|
110
|
-
return;
|
|
111
|
-
}
|
|
112
|
-
const mcpPage = this.#mcpPages.get(foundPage);
|
|
376
|
+
const mcpPage = this.#mcpPages.get(target);
|
|
113
377
|
if (mcpPage) {
|
|
114
|
-
mcpPage
|
|
115
|
-
this.#mcpPages.delete(
|
|
378
|
+
this.#disposeMcpPage(mcpPage);
|
|
379
|
+
this.#mcpPages.delete(target);
|
|
116
380
|
}
|
|
381
|
+
this.#workers.delete(target);
|
|
117
382
|
}
|
|
118
383
|
catch (err) {
|
|
119
384
|
this.logger?.('Error handling targetdestroyed', err);
|
|
120
385
|
}
|
|
121
386
|
};
|
|
122
|
-
static
|
|
387
|
+
static create(logger, opts,
|
|
123
388
|
/* Let tests use unbundled Locator class to avoid overly strict checks within puppeteer that fail when mixing bundled and unbundled class instances */
|
|
124
389
|
locatorClass = Locator) {
|
|
125
|
-
|
|
126
|
-
await context.#init();
|
|
127
|
-
return context;
|
|
390
|
+
return new McpContext(logger, opts, locatorClass);
|
|
128
391
|
}
|
|
129
392
|
static resetPageIdsForTesting() {
|
|
130
393
|
nextPageId = 1;
|
|
131
394
|
}
|
|
395
|
+
static resetWorkerIdsForTesting() {
|
|
396
|
+
McpWorker.resetIdsForTesting();
|
|
397
|
+
}
|
|
132
398
|
roots() {
|
|
133
399
|
return [
|
|
134
400
|
...(this.#roots ?? []),
|
|
@@ -151,13 +417,14 @@ export class McpContext {
|
|
|
151
417
|
}
|
|
152
418
|
catch (err) {
|
|
153
419
|
const errMsg = err instanceof Error ? err.message : String(err);
|
|
154
|
-
console.error(`[MCP Context] Error resolving real path for ${filePath}: ${errMsg}`);
|
|
155
|
-
throw new Error(`Access denied: Cannot resolve base path for ${filePath}.`);
|
|
420
|
+
console.error(`[MCP Context] Error resolving real path for ${escapeForLog(filePath)}: ${escapeForLog(errMsg)}`);
|
|
421
|
+
throw new Error(`Access denied: Cannot resolve base path for ${escapeForLog(filePath)}.`);
|
|
156
422
|
}
|
|
157
423
|
// If the client never negotiated roots and the operator has explicitly
|
|
158
424
|
// opted into unrestricted access via --allow-unrestricted-paths, restore
|
|
159
425
|
// the previous permissive behavior and skip validation.
|
|
160
|
-
if (this.#roots === undefined &&
|
|
426
|
+
if (this.#roots === undefined &&
|
|
427
|
+
this.#config.resolved.allowUnrestrictedPaths) {
|
|
161
428
|
// Canonical path might not exist yet so we fallback to
|
|
162
429
|
// path.resolve(filePath). Consumers should not follow symlinks.
|
|
163
430
|
return canonicalPath || path.resolve(filePath);
|
|
@@ -178,8 +445,13 @@ export class McpContext {
|
|
|
178
445
|
const result = resolvedRoots[i];
|
|
179
446
|
if (result.status === 'fulfilled') {
|
|
180
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;
|
|
181
453
|
if (canonicalPath === canonicalRoot ||
|
|
182
|
-
canonicalPath.startsWith(
|
|
454
|
+
canonicalPath.startsWith(rootPrefix)) {
|
|
183
455
|
allowed = true;
|
|
184
456
|
break;
|
|
185
457
|
}
|
|
@@ -187,12 +459,12 @@ export class McpContext {
|
|
|
187
459
|
else {
|
|
188
460
|
const rootErr = result.reason;
|
|
189
461
|
const errMsg = rootErr instanceof Error ? rootErr.message : String(rootErr);
|
|
190
|
-
console.warn(`[MCP Context] Could not resolve configured root ${root.uri}: ${errMsg}`);
|
|
462
|
+
console.warn(`[MCP Context] Could not resolve configured root ${escapeForLog(root.uri)}: ${escapeForLog(errMsg)}`);
|
|
191
463
|
// Skip this root if it cannot be resolved.
|
|
192
464
|
}
|
|
193
465
|
}
|
|
194
466
|
if (!allowed) {
|
|
195
|
-
throw new Error(`Access denied: path ${filePath} (canonical: ${canonicalPath}) is not within any of the configured workspace roots.`);
|
|
467
|
+
throw new Error(`Access denied: path ${escapeForLog(filePath)} (canonical: ${escapeForLog(canonicalPath)}) is not within any of the configured workspace roots.`);
|
|
196
468
|
}
|
|
197
469
|
return canonicalPath || path.resolve(filePath);
|
|
198
470
|
}
|
|
@@ -215,61 +487,89 @@ export class McpContext {
|
|
|
215
487
|
else {
|
|
216
488
|
page = await this.browser.newPage({ background });
|
|
217
489
|
}
|
|
218
|
-
const mcpPage =
|
|
219
|
-
await
|
|
490
|
+
const mcpPage = this.#createMcpPage(page.target());
|
|
491
|
+
await mcpPage.init({ emulateFocus: true });
|
|
220
492
|
this.selectPage(mcpPage);
|
|
493
|
+
await this.createPagesSnapshot();
|
|
221
494
|
return mcpPage;
|
|
222
495
|
}
|
|
223
496
|
async closePage(pageId) {
|
|
497
|
+
const page = this.getPageById(pageId);
|
|
224
498
|
if (this.#mcpPages.size === 1) {
|
|
225
499
|
throw new Error(CLOSE_PAGE_ERROR);
|
|
226
500
|
}
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
page.dispose();
|
|
230
|
-
this.#mcpPages.delete(page.pptrPage);
|
|
231
|
-
}
|
|
232
|
-
await page.pptrPage.close({ runBeforeUnload: false });
|
|
233
|
-
}
|
|
234
|
-
get #hasNetworkBlockOrAllowlist() {
|
|
235
|
-
return !!(this.#options.allowlist || this.#options.blocklist);
|
|
501
|
+
this.#mcpPages.delete(page.target);
|
|
502
|
+
await page.close();
|
|
236
503
|
}
|
|
237
|
-
installPWA(options) {
|
|
238
|
-
|
|
504
|
+
async installPWA(options) {
|
|
505
|
+
try {
|
|
506
|
+
return await this.browser.installPWA(options);
|
|
507
|
+
}
|
|
508
|
+
catch (error) {
|
|
509
|
+
if (error instanceof Error &&
|
|
510
|
+
error.message.includes("Couldn't fetch install info")) {
|
|
511
|
+
return await this.browser.installPWA(options);
|
|
512
|
+
}
|
|
513
|
+
throw error;
|
|
514
|
+
}
|
|
239
515
|
}
|
|
240
516
|
uninstallPWA(options) {
|
|
241
517
|
return this.browser.uninstallPWA(options);
|
|
242
518
|
}
|
|
243
|
-
launchPWA(options) {
|
|
244
|
-
|
|
519
|
+
async launchPWA(options) {
|
|
520
|
+
const page = await this.browser.launchPWA(options);
|
|
521
|
+
if (!page.url() || page.url() === 'about:blank') {
|
|
522
|
+
await page
|
|
523
|
+
.waitForNavigation({
|
|
524
|
+
timeout: this.#options.navigationTimeout ?? 10_000,
|
|
525
|
+
})
|
|
526
|
+
.catch(() => {
|
|
527
|
+
// Ignore timeout if navigation already completed or failed.
|
|
528
|
+
});
|
|
529
|
+
}
|
|
530
|
+
return page;
|
|
245
531
|
}
|
|
246
532
|
getPWAState(options) {
|
|
247
533
|
return this.browser.getPWAState(options);
|
|
248
534
|
}
|
|
249
|
-
setIsRunningPerformanceTrace(x) {
|
|
250
|
-
this.#isRunningTrace = x;
|
|
251
|
-
}
|
|
252
535
|
isRunningPerformanceTrace() {
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
this.#screenRecorderData = data;
|
|
536
|
+
for (const mcpPage of this.#allMcpPages()) {
|
|
537
|
+
if (mcpPage.isRunningPerformanceTrace()) {
|
|
538
|
+
return true;
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
return false;
|
|
260
542
|
}
|
|
261
543
|
isCruxEnabled() {
|
|
262
|
-
return this.#
|
|
544
|
+
return this.#config.resolved.performanceCrux;
|
|
263
545
|
}
|
|
264
546
|
getPages() {
|
|
265
547
|
return Array.from(this.#mcpPages.values());
|
|
266
548
|
}
|
|
549
|
+
/**
|
|
550
|
+
* Fetches current target info for all targets from the browser, keyed by
|
|
551
|
+
* target id. Unlike Puppeteer's cached target info, this reflects title
|
|
552
|
+
* changes, which Chrome does not report via `Target.targetInfoChanged`.
|
|
553
|
+
* Returns an empty map if the browser cannot be queried.
|
|
554
|
+
*/
|
|
555
|
+
async getTargetInfos() {
|
|
556
|
+
try {
|
|
557
|
+
// @ts-expect-error use existing browser connection (internal Puppeteer API).
|
|
558
|
+
const connection = this.browser._connection;
|
|
559
|
+
const { targetInfos } = await connection.send('Target.getTargets');
|
|
560
|
+
return new Map(targetInfos.map(info => [info.targetId, info]));
|
|
561
|
+
}
|
|
562
|
+
catch (err) {
|
|
563
|
+
this.logger?.('Failed to fetch target infos', err);
|
|
564
|
+
return new Map();
|
|
565
|
+
}
|
|
566
|
+
}
|
|
267
567
|
getSelectedMcpPage() {
|
|
268
568
|
const page = this.#selectedPage;
|
|
269
569
|
if (!page) {
|
|
270
570
|
throw new Error('No page selected');
|
|
271
571
|
}
|
|
272
|
-
if (page.
|
|
572
|
+
if (page.isClosed()) {
|
|
273
573
|
throw new Error('The selected page has been closed. Call list_pages to see open pages.');
|
|
274
574
|
}
|
|
275
575
|
return page;
|
|
@@ -284,8 +584,8 @@ export class McpContext {
|
|
|
284
584
|
return undefined;
|
|
285
585
|
}
|
|
286
586
|
}
|
|
287
|
-
if (targetPage
|
|
288
|
-
return targetPage.
|
|
587
|
+
if (targetPage && !targetPage.isClosed()) {
|
|
588
|
+
return targetPage.url();
|
|
289
589
|
}
|
|
290
590
|
return undefined;
|
|
291
591
|
}
|
|
@@ -310,9 +610,9 @@ export class McpContext {
|
|
|
310
610
|
}
|
|
311
611
|
}
|
|
312
612
|
/**
|
|
313
|
-
* Returns true once
|
|
314
|
-
*
|
|
315
|
-
*
|
|
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.
|
|
316
616
|
*/
|
|
317
617
|
consumeReconnectNotice() {
|
|
318
618
|
const notice = this.#reconnectNotice;
|
|
@@ -326,47 +626,87 @@ export class McpContext {
|
|
|
326
626
|
}
|
|
327
627
|
return page;
|
|
328
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
|
+
}
|
|
329
649
|
isPageSelected(page) {
|
|
330
650
|
return this.#selectedPage === page;
|
|
331
651
|
}
|
|
332
652
|
selectPage(newPage) {
|
|
653
|
+
this.#selectedPageFallback = undefined;
|
|
654
|
+
this.#selectedPageFallbackRead = false;
|
|
655
|
+
this.#selectPage(newPage);
|
|
656
|
+
}
|
|
657
|
+
#selectPage(newPage) {
|
|
658
|
+
if (this.#selectedPage &&
|
|
659
|
+
this.#selectedPage !== newPage &&
|
|
660
|
+
!this.#mcpPages.has(this.#selectedPage.target)) {
|
|
661
|
+
this.#disposeMcpPage(this.#selectedPage);
|
|
662
|
+
}
|
|
333
663
|
this.#selectedPage = newPage;
|
|
334
664
|
newPage.updateTimeouts();
|
|
335
665
|
}
|
|
336
666
|
/**
|
|
337
667
|
* Returns details about the last page snapshot automatically replacing the
|
|
338
668
|
* selection because the selected page disappeared from the page list, or
|
|
339
|
-
* `undefined` if the snapshot left the selection intact.
|
|
340
|
-
* 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.
|
|
341
672
|
*/
|
|
342
673
|
getSelectedPageFallback() {
|
|
674
|
+
this.#selectedPageFallbackRead = true;
|
|
343
675
|
return this.#selectedPageFallback;
|
|
344
676
|
}
|
|
345
677
|
/**
|
|
346
|
-
* Creates a snapshot of the
|
|
678
|
+
* Creates a snapshot of the tracked workers. Today this is limited to
|
|
679
|
+
* extension service workers; the McpWorker abstraction lets dedicated and
|
|
680
|
+
* shared workers join the same snapshot later without changing consumers.
|
|
347
681
|
*/
|
|
348
|
-
|
|
349
|
-
const
|
|
350
|
-
const serviceWorkers = allTargets.filter(target => {
|
|
682
|
+
createWorkersSnapshot() {
|
|
683
|
+
const serviceWorkers = this.browser.targets().filter(target => {
|
|
351
684
|
return (target.type() === 'service_worker' &&
|
|
352
685
|
target.url().includes('chrome-extension://'));
|
|
353
686
|
});
|
|
354
|
-
for (
|
|
355
|
-
|
|
356
|
-
|
|
687
|
+
// Reuse the existing McpWorker for a target; only mint one (and an id) for
|
|
688
|
+
// targets seen for the first time.
|
|
689
|
+
for (const target of serviceWorkers) {
|
|
690
|
+
if (!this.#workers.has(target)) {
|
|
691
|
+
this.#workers.set(target, McpWorker.create('service_worker', target));
|
|
357
692
|
}
|
|
358
693
|
}
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
}
|
|
365
|
-
}
|
|
366
|
-
return this.#
|
|
694
|
+
// Prune workers whose target is gone (mirrors #mcpPages pruning).
|
|
695
|
+
const currentTargets = new Set(serviceWorkers);
|
|
696
|
+
for (const target of this.#workers.keys()) {
|
|
697
|
+
if (!currentTargets.has(target)) {
|
|
698
|
+
this.#workers.delete(target);
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
return Array.from(this.#workers.values());
|
|
367
702
|
}
|
|
368
|
-
getServiceWorkerConsoleData(
|
|
369
|
-
|
|
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) ?? [];
|
|
370
710
|
}
|
|
371
711
|
#getBrowserContextToNameMap() {
|
|
372
712
|
// Build a reverse lookup from BrowserContext instance → name.
|
|
@@ -387,92 +727,123 @@ export class McpContext {
|
|
|
387
727
|
}
|
|
388
728
|
return contextToName;
|
|
389
729
|
}
|
|
390
|
-
|
|
391
|
-
let mcpPage = this.#mcpPages.get(
|
|
730
|
+
#createMcpPage(target) {
|
|
731
|
+
let mcpPage = this.#mcpPages.get(target) ??
|
|
732
|
+
(this.#selectedPage?.target === target ? this.#selectedPage : undefined);
|
|
392
733
|
if (!mcpPage) {
|
|
393
|
-
mcpPage = new McpPage(
|
|
734
|
+
mcpPage = new McpPage(target, nextPageId++, {
|
|
735
|
+
config: this.#config,
|
|
394
736
|
locatorClass: this.#locatorClass,
|
|
395
|
-
|
|
396
|
-
isolatedContextName: this.#getBrowserContextToNameMap().get(page.browserContext()),
|
|
737
|
+
isolatedContextName: this.#getBrowserContextToNameMap().get(target.browserContext()),
|
|
397
738
|
navigationTimeout: this.#options.navigationTimeout,
|
|
398
|
-
sourceMaps: this.#options.sourceMaps,
|
|
399
|
-
onNotification: this.#options.onNotification,
|
|
400
739
|
});
|
|
401
|
-
this.#mcpPages.set(page, mcpPage);
|
|
402
|
-
await mcpPage.init();
|
|
403
740
|
}
|
|
741
|
+
this.#mcpPages.set(target, mcpPage);
|
|
404
742
|
return mcpPage;
|
|
405
743
|
}
|
|
406
744
|
async createPagesSnapshot() {
|
|
407
|
-
const
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
pages[0]) {
|
|
424
|
-
// Record the automatic change so the response can surface it. Skipped on
|
|
425
|
-
// first connect, when there was no prior selection to replace.
|
|
426
|
-
if (this.#selectedPage) {
|
|
427
|
-
this.#selectedPageFallback = {
|
|
428
|
-
wasClosed: this.#selectedPage.pptrPage.isClosed(),
|
|
429
|
-
};
|
|
430
|
-
}
|
|
431
|
-
this.selectPage(pages[0]);
|
|
432
|
-
}
|
|
433
|
-
return pages.map(p => p.pptrPage);
|
|
434
|
-
}
|
|
435
|
-
async #fetchBrowserPages() {
|
|
436
|
-
const allPages = (await this.browser.pages(this.#options.experimentalIncludeAllPages)).filter(page => {
|
|
437
|
-
if (!this.#options.experimentalDevToolsDebugging &&
|
|
438
|
-
page.url().startsWith('devtools://')) {
|
|
439
|
-
return false;
|
|
440
|
-
}
|
|
441
|
-
return isAllowedUrl(page.url(), {
|
|
442
|
-
categoryExtensions: this.#options.categoryExtensions,
|
|
443
|
-
});
|
|
444
|
-
});
|
|
445
|
-
if (this.#options.categoryExtensions) {
|
|
446
|
-
const allTargets = this.browser.targets();
|
|
447
|
-
const extensionTargets = allTargets.filter(target => {
|
|
448
|
-
return (target.url().startsWith('chrome-extension://') &&
|
|
449
|
-
target.type() === 'page');
|
|
450
|
-
});
|
|
451
|
-
await Promise.allSettled(extensionTargets.map(async (target) => {
|
|
452
|
-
try {
|
|
453
|
-
let page = await target.page();
|
|
454
|
-
if (!page) {
|
|
455
|
-
page = await target.asPage();
|
|
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);
|
|
456
761
|
}
|
|
457
|
-
this.#
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
762
|
+
this.#mcpPages.delete(target);
|
|
763
|
+
}
|
|
764
|
+
}
|
|
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;
|
|
774
|
+
}
|
|
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
|
+
};
|
|
462
785
|
}
|
|
786
|
+
this.#selectPage(pages[0]);
|
|
463
787
|
}
|
|
464
|
-
|
|
465
|
-
this.
|
|
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 };
|
|
466
795
|
}
|
|
467
|
-
}
|
|
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;
|
|
802
|
+
}
|
|
803
|
+
catch (e_1) {
|
|
804
|
+
env_1.error = e_1;
|
|
805
|
+
env_1.hasError = true;
|
|
806
|
+
}
|
|
807
|
+
finally {
|
|
808
|
+
__disposeResources(env_1);
|
|
468
809
|
}
|
|
469
|
-
return allPages;
|
|
470
810
|
}
|
|
471
|
-
|
|
472
|
-
|
|
811
|
+
#isPageTarget(target) {
|
|
812
|
+
const existingMcpPage = this.#mcpPages.get(target) ??
|
|
813
|
+
(this.#selectedPage?.target === target ? this.#selectedPage : undefined);
|
|
814
|
+
const url = existingMcpPage ? existingMcpPage.url() : target.url();
|
|
815
|
+
if (!this.#config.resolved.experimentalDevtools &&
|
|
816
|
+
url.startsWith('devtools://')) {
|
|
817
|
+
return false;
|
|
818
|
+
}
|
|
819
|
+
if (!isAllowedUrl(url, {
|
|
820
|
+
categoryExtensions: this.#config.resolved.categoryExtensions,
|
|
821
|
+
})) {
|
|
822
|
+
return false;
|
|
823
|
+
}
|
|
824
|
+
const type = target.type();
|
|
825
|
+
if (type === 'page') {
|
|
826
|
+
return true;
|
|
827
|
+
}
|
|
828
|
+
if (this.#config.resolved.experimentalIncludeAllPages &&
|
|
829
|
+
(type === 'background_page' || type === 'webview')) {
|
|
830
|
+
return true;
|
|
831
|
+
}
|
|
832
|
+
if (this.#config.resolved.experimentalDevtools &&
|
|
833
|
+
type === 'other' &&
|
|
834
|
+
url.startsWith('devtools://')) {
|
|
835
|
+
return true;
|
|
836
|
+
}
|
|
837
|
+
return false;
|
|
473
838
|
}
|
|
474
|
-
|
|
475
|
-
return this
|
|
839
|
+
#fetchPageTargets() {
|
|
840
|
+
return this.browser.targets().filter(target => this.#isPageTarget(target));
|
|
841
|
+
}
|
|
842
|
+
getWorkers() {
|
|
843
|
+
return Array.from(this.#workers.values());
|
|
844
|
+
}
|
|
845
|
+
getWorkerById(id) {
|
|
846
|
+
return this.#workers.values().find(worker => worker.id === id);
|
|
476
847
|
}
|
|
477
848
|
async #writeFile(filepath, data) {
|
|
478
849
|
const resolved = await this.validatePath(filepath);
|
|
@@ -493,7 +864,9 @@ export class McpContext {
|
|
|
493
864
|
});
|
|
494
865
|
}
|
|
495
866
|
catch (err) {
|
|
496
|
-
throw new Error(`Could not write ${filepath}`, {
|
|
867
|
+
throw new Error(`Could not write ${escapeForLog(filepath)}`, {
|
|
868
|
+
cause: err,
|
|
869
|
+
});
|
|
497
870
|
}
|
|
498
871
|
}
|
|
499
872
|
async saveTemporaryFile(data, filename) {
|
|
@@ -573,11 +946,11 @@ export class McpContext {
|
|
|
573
946
|
async getHeapSnapshotObjectDetails(filePath, nodeId) {
|
|
574
947
|
return await this.#heapSnapshotManager.getObjectInfo(filePath, nodeId);
|
|
575
948
|
}
|
|
576
|
-
async
|
|
577
|
-
return this.#heapSnapshotManager.
|
|
949
|
+
async analyzeHeapSnapshotContexts(filePath) {
|
|
950
|
+
return await this.#heapSnapshotManager.analyzeContexts(filePath);
|
|
578
951
|
}
|
|
579
|
-
|
|
580
|
-
return this.#heapSnapshotManager.
|
|
952
|
+
async closeHeapSnapshot(filePath) {
|
|
953
|
+
return await this.#heapSnapshotManager.disposeSnapshot(filePath);
|
|
581
954
|
}
|
|
582
955
|
async getHeapSnapshotRetainingPaths(filePath, nodeId, maxDepth, maxNodes, maxSiblings) {
|
|
583
956
|
return await this.#heapSnapshotManager.getRetainingPaths(filePath, nodeId, maxDepth, maxNodes, maxSiblings);
|
|
@@ -586,10 +959,11 @@ export class McpContext {
|
|
|
586
959
|
return await this.#heapSnapshotManager.getDominatorsOf(filePath, nodeId);
|
|
587
960
|
}
|
|
588
961
|
#validateUrlNotBlocked(url) {
|
|
589
|
-
|
|
962
|
+
const blocklist = this.#config.resolved.blockedUrlPattern;
|
|
963
|
+
if (!blocklist) {
|
|
590
964
|
return;
|
|
591
965
|
}
|
|
592
|
-
for (const block of
|
|
966
|
+
for (const block of blocklist) {
|
|
593
967
|
const pattern = new URLPattern(block);
|
|
594
968
|
if (pattern.test(url)) {
|
|
595
969
|
throw new Error(`Blocked by blocklist: ${url}`);
|
|
@@ -597,10 +971,11 @@ export class McpContext {
|
|
|
597
971
|
}
|
|
598
972
|
}
|
|
599
973
|
#validateUrlAllowed(url) {
|
|
600
|
-
|
|
974
|
+
const allowlist = this.#config.resolved.allowedUrlPattern;
|
|
975
|
+
if (!allowlist) {
|
|
601
976
|
return;
|
|
602
977
|
}
|
|
603
|
-
for (const allow of
|
|
978
|
+
for (const allow of allowlist) {
|
|
604
979
|
const pattern = new URLPattern(allow);
|
|
605
980
|
if (pattern.test(url)) {
|
|
606
981
|
return;
|
|
@@ -608,18 +983,41 @@ export class McpContext {
|
|
|
608
983
|
}
|
|
609
984
|
throw new Error(`Not allowed by allowlist: ${url}`);
|
|
610
985
|
}
|
|
986
|
+
async #loadNetworkResource(url) {
|
|
987
|
+
const redirectStatuses = new Set([301, 302, 303, 307, 308]);
|
|
988
|
+
const maxRedirects = 20;
|
|
989
|
+
let currentUrl = url;
|
|
990
|
+
for (let redirectCount = 0;; redirectCount++) {
|
|
991
|
+
this.#validateUrlNotBlocked(currentUrl);
|
|
992
|
+
this.#validateUrlAllowed(currentUrl);
|
|
993
|
+
const response = await fetch(currentUrl, { redirect: 'manual' });
|
|
994
|
+
if (!redirectStatuses.has(response.status)) {
|
|
995
|
+
if (!response.ok) {
|
|
996
|
+
throw new Error(`Failed to load resource: ${currentUrl}`);
|
|
997
|
+
}
|
|
998
|
+
return await response.text();
|
|
999
|
+
}
|
|
1000
|
+
const location = response.headers.get('location');
|
|
1001
|
+
if (!location) {
|
|
1002
|
+
throw new Error(`Failed to load resource: ${currentUrl}`);
|
|
1003
|
+
}
|
|
1004
|
+
if (redirectCount >= maxRedirects) {
|
|
1005
|
+
throw new Error(`Too many redirects loading resource: ${url}`);
|
|
1006
|
+
}
|
|
1007
|
+
await response.body?.cancel();
|
|
1008
|
+
currentUrl = new URL(location, currentUrl);
|
|
1009
|
+
if (currentUrl.protocol !== 'https:' && currentUrl.protocol !== 'http:') {
|
|
1010
|
+
throw new Error(`Unsupported protocol for: ${currentUrl}`);
|
|
1011
|
+
}
|
|
1012
|
+
}
|
|
1013
|
+
}
|
|
611
1014
|
async loadResource(path) {
|
|
612
1015
|
const url = new URL(path);
|
|
613
1016
|
this.#validateUrlNotBlocked(url);
|
|
614
1017
|
switch (url.protocol) {
|
|
615
1018
|
case 'https:':
|
|
616
1019
|
case 'http:': {
|
|
617
|
-
this.#
|
|
618
|
-
const response = await fetch(url);
|
|
619
|
-
if (!response.ok) {
|
|
620
|
-
throw new Error(`Failed to load resource: ${url}`);
|
|
621
|
-
}
|
|
622
|
-
return response.text();
|
|
1020
|
+
return await this.#loadNetworkResource(url);
|
|
623
1021
|
}
|
|
624
1022
|
case 'file:': {
|
|
625
1023
|
const resolved = await this.validatePath(fileURLToPath(url));
|