@wordbricks/playwright-mcp 0.1.25 → 0.1.26

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/lib/browserContextFactory.js +399 -0
  2. package/lib/browserServerBackend.js +86 -0
  3. package/lib/config.js +300 -0
  4. package/lib/context.js +311 -0
  5. package/lib/extension/cdpRelay.js +352 -0
  6. package/lib/extension/extensionContextFactory.js +56 -0
  7. package/lib/frameworkPatterns.js +35 -0
  8. package/lib/hooks/antiBotDetectionHook.js +178 -0
  9. package/lib/hooks/core.js +145 -0
  10. package/lib/hooks/eventConsumer.js +52 -0
  11. package/lib/hooks/events.js +42 -0
  12. package/lib/hooks/formatToolCallEvent.js +12 -0
  13. package/lib/hooks/frameworkStateHook.js +182 -0
  14. package/lib/hooks/grouping.js +72 -0
  15. package/lib/hooks/jsonLdDetectionHook.js +182 -0
  16. package/lib/hooks/networkFilters.js +82 -0
  17. package/lib/hooks/networkSetup.js +61 -0
  18. package/lib/hooks/networkTrackingHook.js +67 -0
  19. package/lib/hooks/pageHeightHook.js +75 -0
  20. package/lib/hooks/registry.js +41 -0
  21. package/lib/hooks/requireTabHook.js +26 -0
  22. package/lib/hooks/schema.js +89 -0
  23. package/lib/hooks/waitHook.js +33 -0
  24. package/lib/index.js +41 -0
  25. package/lib/mcp/inProcessTransport.js +71 -0
  26. package/lib/mcp/proxyBackend.js +130 -0
  27. package/lib/mcp/server.js +91 -0
  28. package/lib/mcp/tool.js +44 -0
  29. package/lib/mcp/transport.js +188 -0
  30. package/lib/playwrightTransformer.js +520 -0
  31. package/lib/program.js +112 -0
  32. package/lib/response.js +192 -0
  33. package/lib/sessionLog.js +123 -0
  34. package/lib/tab.js +251 -0
  35. package/lib/tools/common.js +55 -0
  36. package/lib/tools/console.js +33 -0
  37. package/lib/tools/dialogs.js +50 -0
  38. package/lib/tools/evaluate.js +62 -0
  39. package/lib/tools/extractFrameworkState.js +225 -0
  40. package/lib/tools/files.js +48 -0
  41. package/lib/tools/form.js +66 -0
  42. package/lib/tools/getSnapshot.js +36 -0
  43. package/lib/tools/getVisibleHtml.js +68 -0
  44. package/lib/tools/install.js +51 -0
  45. package/lib/tools/keyboard.js +83 -0
  46. package/lib/tools/mouse.js +97 -0
  47. package/lib/tools/navigate.js +66 -0
  48. package/lib/tools/network.js +121 -0
  49. package/lib/tools/networkDetail.js +238 -0
  50. package/lib/tools/networkSearch/bodySearch.js +161 -0
  51. package/lib/tools/networkSearch/grouping.js +37 -0
  52. package/lib/tools/networkSearch/helpers.js +32 -0
  53. package/lib/tools/networkSearch/searchHtml.js +76 -0
  54. package/lib/tools/networkSearch/types.js +1 -0
  55. package/lib/tools/networkSearch/urlSearch.js +124 -0
  56. package/lib/tools/networkSearch.js +278 -0
  57. package/lib/tools/pdf.js +41 -0
  58. package/lib/tools/repl.js +414 -0
  59. package/lib/tools/screenshot.js +103 -0
  60. package/lib/tools/scroll.js +131 -0
  61. package/lib/tools/snapshot.js +161 -0
  62. package/lib/tools/tabs.js +62 -0
  63. package/lib/tools/tool.js +35 -0
  64. package/lib/tools/utils.js +78 -0
  65. package/lib/tools/wait.js +60 -0
  66. package/lib/tools.js +68 -0
  67. package/lib/utils/adBlockFilter.js +90 -0
  68. package/lib/utils/codegen.js +55 -0
  69. package/lib/utils/extensionPath.js +10 -0
  70. package/lib/utils/fileUtils.js +40 -0
  71. package/lib/utils/graphql.js +269 -0
  72. package/lib/utils/guid.js +22 -0
  73. package/lib/utils/httpServer.js +39 -0
  74. package/lib/utils/log.js +21 -0
  75. package/lib/utils/manualPromise.js +111 -0
  76. package/lib/utils/networkFormat.js +14 -0
  77. package/lib/utils/package.js +20 -0
  78. package/lib/utils/result.js +2 -0
  79. package/lib/utils/sanitizeHtml.js +130 -0
  80. package/lib/utils/truncate.js +103 -0
  81. package/lib/utils/withTimeout.js +7 -0
  82. package/package.json +11 -1
package/lib/config.js ADDED
@@ -0,0 +1,300 @@
1
+ /**
2
+ * Copyright (c) Microsoft Corporation.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ import fs from "fs";
17
+ import os from "os";
18
+ import path from "path";
19
+ import { devices } from "playwright-core";
20
+ import { sanitizeForFilePath } from "./utils/fileUtils.js";
21
+ const defaultConfig = {
22
+ browser: {
23
+ browserName: "chromium",
24
+ launchOptions: {
25
+ channel: "chrome",
26
+ headless: os.platform() === "linux" && !process.env.DISPLAY,
27
+ chromiumSandbox: true,
28
+ },
29
+ contextOptions: {
30
+ viewport: null,
31
+ },
32
+ },
33
+ network: {
34
+ allowedOrigins: undefined,
35
+ blockedOrigins: undefined,
36
+ },
37
+ server: {},
38
+ saveTrace: false,
39
+ };
40
+ export async function resolveConfig(config) {
41
+ return mergeConfig(defaultConfig, config);
42
+ }
43
+ export async function resolveCLIConfig(cliOptions) {
44
+ const configInFile = await loadConfig(cliOptions.config);
45
+ const envOverrides = configFromEnv();
46
+ const cliOverrides = configFromCLIOptions(cliOptions);
47
+ let result = defaultConfig;
48
+ result = mergeConfig(result, configInFile);
49
+ result = mergeConfig(result, envOverrides);
50
+ result = mergeConfig(result, cliOverrides);
51
+ return result;
52
+ }
53
+ export function configFromCLIOptions(cliOptions) {
54
+ let browserName;
55
+ let channel;
56
+ switch (cliOptions.browser) {
57
+ case "chrome":
58
+ case "chrome-beta":
59
+ case "chrome-canary":
60
+ case "chrome-dev":
61
+ case "chromium":
62
+ case "msedge":
63
+ case "msedge-beta":
64
+ case "msedge-canary":
65
+ case "msedge-dev":
66
+ browserName = "chromium";
67
+ channel = cliOptions.browser;
68
+ break;
69
+ case "firefox":
70
+ browserName = "firefox";
71
+ break;
72
+ case "webkit":
73
+ browserName = "webkit";
74
+ break;
75
+ }
76
+ // Launch options
77
+ const launchOptions = {
78
+ channel,
79
+ executablePath: cliOptions.executablePath,
80
+ headless: cliOptions.headless,
81
+ // Ignore default automation flag to reduce bot detection
82
+ ignoreDefaultArgs: ["--enable-automation"],
83
+ };
84
+ // --no-sandbox was passed, disable the sandbox
85
+ if (cliOptions.sandbox === false)
86
+ launchOptions.chromiumSandbox = false;
87
+ // Add default Chrome args to avoid automation detection and suppress popups
88
+ launchOptions.args = launchOptions.args || [];
89
+ launchOptions.args.push("--disable-infobars",
90
+ // Password & credential popups
91
+ "--disable-save-password-bubble", "--password-store=basic", "--use-mock-keychain",
92
+ // Crash restore popup
93
+ "--hide-crash-restore-bubble",
94
+ // First run & default browser
95
+ "--no-first-run", "--no-default-browser-check",
96
+ // Disable various Chrome features (Translate, PasswordManager, Autofill, Sync)
97
+ "--disable-features=Translate,PasswordManager,PasswordManagerEnabled,PasswordManagerOnboarding,AutofillServerCommunication,CredentialManagerOnboarding", "--disable-sync",
98
+ // Disable password manager via experimental options
99
+ "--enable-features=DisablePasswordManager");
100
+ // --app was passed, add app mode argument
101
+ if (cliOptions.app) {
102
+ launchOptions.args = launchOptions.args || [];
103
+ launchOptions.args.push(`--app=${cliOptions.app}`);
104
+ }
105
+ // --window-position was passed, add window position argument
106
+ if (cliOptions.windowPosition) {
107
+ try {
108
+ const [x, y] = cliOptions.windowPosition.split(",").map((n) => +n);
109
+ if (isNaN(x) || isNaN(y))
110
+ throw new Error("bad values");
111
+ launchOptions.args = launchOptions.args || [];
112
+ launchOptions.args.push(`--window-position=${x},${y}`);
113
+ }
114
+ catch (e) {
115
+ throw new Error('Invalid window position format: use "x,y", for example --window-position="100,200"');
116
+ }
117
+ }
118
+ // --window-size was passed, add window size argument
119
+ if (cliOptions.windowSize) {
120
+ try {
121
+ const [width, height] = cliOptions.windowSize.split(",").map((n) => +n);
122
+ if (isNaN(width) || isNaN(height))
123
+ throw new Error("bad values");
124
+ launchOptions.args = launchOptions.args || [];
125
+ launchOptions.args.push(`--window-size=${width},${height}`);
126
+ }
127
+ catch (e) {
128
+ throw new Error('Invalid window size format: use "width,height", for example --window-size="1280,720"');
129
+ }
130
+ }
131
+ if (cliOptions.proxyServer) {
132
+ launchOptions.proxy = {
133
+ server: cliOptions.proxyServer,
134
+ };
135
+ if (cliOptions.proxyBypass)
136
+ launchOptions.proxy.bypass = cliOptions.proxyBypass;
137
+ }
138
+ if (cliOptions.device && cliOptions.cdpEndpoint)
139
+ throw new Error("Device emulation is not supported with cdpEndpoint.");
140
+ // Context options
141
+ const contextOptions = cliOptions.device
142
+ ? devices[cliOptions.device]
143
+ : {};
144
+ if (cliOptions.storageState)
145
+ contextOptions.storageState = cliOptions.storageState;
146
+ if (cliOptions.userAgent)
147
+ contextOptions.userAgent = cliOptions.userAgent;
148
+ if (cliOptions.viewportSize) {
149
+ try {
150
+ const [width, height] = cliOptions.viewportSize.split(",").map((n) => +n);
151
+ if (isNaN(width) || isNaN(height))
152
+ throw new Error("bad values");
153
+ contextOptions.viewport = { width, height };
154
+ }
155
+ catch (e) {
156
+ throw new Error('Invalid viewport size format: use "width,height", for example --viewport-size="800,600"');
157
+ }
158
+ }
159
+ if (cliOptions.ignoreHttpsErrors)
160
+ contextOptions.ignoreHTTPSErrors = true;
161
+ if (cliOptions.blockServiceWorkers)
162
+ contextOptions.serviceWorkers = "block";
163
+ const result = {
164
+ browser: {
165
+ browserName,
166
+ isolated: cliOptions.isolated,
167
+ userDataDir: cliOptions.userDataDir,
168
+ launchOptions,
169
+ contextOptions,
170
+ cdpEndpoint: cliOptions.cdpEndpoint,
171
+ initScript: cliOptions.initScript,
172
+ app: cliOptions.app,
173
+ },
174
+ server: {
175
+ port: cliOptions.port,
176
+ host: cliOptions.host,
177
+ },
178
+ capabilities: cliOptions.caps,
179
+ network: {
180
+ allowedOrigins: cliOptions.allowedOrigins,
181
+ blockedOrigins: cliOptions.blockedOrigins,
182
+ },
183
+ saveSession: cliOptions.saveSession,
184
+ saveTrace: cliOptions.saveTrace,
185
+ outputDir: cliOptions.outputDir,
186
+ imageResponses: cliOptions.imageResponses,
187
+ };
188
+ return result;
189
+ }
190
+ function configFromEnv() {
191
+ const options = {};
192
+ options.allowedOrigins = semicolonSeparatedList(process.env.PLAYWRIGHT_MCP_ALLOWED_ORIGINS);
193
+ options.app = envToString(process.env.PLAYWRIGHT_MCP_APP);
194
+ options.blockedOrigins = semicolonSeparatedList(process.env.PLAYWRIGHT_MCP_BLOCKED_ORIGINS);
195
+ options.blockServiceWorkers = envToBoolean(process.env.PLAYWRIGHT_MCP_BLOCK_SERVICE_WORKERS);
196
+ options.browser = envToString(process.env.PLAYWRIGHT_MCP_BROWSER);
197
+ options.caps = commaSeparatedList(process.env.PLAYWRIGHT_MCP_CAPS);
198
+ options.cdpEndpoint = envToString(process.env.PLAYWRIGHT_MCP_CDP_ENDPOINT);
199
+ options.config = envToString(process.env.PLAYWRIGHT_MCP_CONFIG);
200
+ options.device = envToString(process.env.PLAYWRIGHT_MCP_DEVICE);
201
+ options.executablePath = envToString(process.env.PLAYWRIGHT_MCP_EXECUTABLE_PATH);
202
+ options.headless = envToBoolean(process.env.PLAYWRIGHT_MCP_HEADLESS);
203
+ options.host = envToString(process.env.PLAYWRIGHT_MCP_HOST);
204
+ options.ignoreHttpsErrors = envToBoolean(process.env.PLAYWRIGHT_MCP_IGNORE_HTTPS_ERRORS);
205
+ options.initScript = envToString(process.env.PLAYWRIGHT_MCP_INIT_SCRIPT);
206
+ options.isolated = envToBoolean(process.env.PLAYWRIGHT_MCP_ISOLATED);
207
+ if (process.env.PLAYWRIGHT_MCP_IMAGE_RESPONSES === "omit")
208
+ options.imageResponses = "omit";
209
+ options.sandbox = envToBoolean(process.env.PLAYWRIGHT_MCP_SANDBOX);
210
+ options.outputDir = envToString(process.env.PLAYWRIGHT_MCP_OUTPUT_DIR);
211
+ options.port = envToNumber(process.env.PLAYWRIGHT_MCP_PORT);
212
+ options.proxyBypass = envToString(process.env.PLAYWRIGHT_MCP_PROXY_BYPASS);
213
+ options.proxyServer = envToString(process.env.PLAYWRIGHT_MCP_PROXY_SERVER);
214
+ options.saveTrace = envToBoolean(process.env.PLAYWRIGHT_MCP_SAVE_TRACE);
215
+ options.storageState = envToString(process.env.PLAYWRIGHT_MCP_STORAGE_STATE);
216
+ options.userAgent = envToString(process.env.PLAYWRIGHT_MCP_USER_AGENT);
217
+ options.userDataDir = envToString(process.env.PLAYWRIGHT_MCP_USER_DATA_DIR);
218
+ options.viewportSize = envToString(process.env.PLAYWRIGHT_MCP_VIEWPORT_SIZE);
219
+ options.windowPosition = envToString(process.env.PLAYWRIGHT_MCP_WINDOW_POSITION);
220
+ options.windowSize = envToString(process.env.PLAYWRIGHT_MCP_WINDOW_SIZE);
221
+ return configFromCLIOptions(options);
222
+ }
223
+ async function loadConfig(configFile) {
224
+ if (!configFile)
225
+ return {};
226
+ try {
227
+ return JSON.parse(await fs.promises.readFile(configFile, "utf8"));
228
+ }
229
+ catch (error) {
230
+ throw new Error(`Failed to load config file: ${configFile}, ${error}`);
231
+ }
232
+ }
233
+ export async function outputFile(config, rootPath, name) {
234
+ const outputDir = config.outputDir ??
235
+ (rootPath ? path.join(rootPath, ".playwright-mcp") : undefined) ??
236
+ path.join(os.tmpdir(), "playwright-mcp-output", sanitizeForFilePath(new Date().toISOString()));
237
+ await fs.promises.mkdir(outputDir, { recursive: true });
238
+ const fileName = sanitizeForFilePath(name);
239
+ return path.join(outputDir, fileName);
240
+ }
241
+ function pickDefined(obj) {
242
+ return Object.fromEntries(Object.entries(obj ?? {}).filter(([_, v]) => v !== undefined));
243
+ }
244
+ function mergeConfig(base, overrides) {
245
+ const browser = {
246
+ ...pickDefined(base.browser),
247
+ ...pickDefined(overrides.browser),
248
+ browserName: overrides.browser?.browserName ?? base.browser?.browserName ?? "chromium",
249
+ isolated: overrides.browser?.isolated ?? base.browser?.isolated ?? false,
250
+ launchOptions: {
251
+ ...pickDefined(base.browser?.launchOptions),
252
+ ...pickDefined(overrides.browser?.launchOptions),
253
+ ...{ assistantMode: true },
254
+ },
255
+ contextOptions: {
256
+ ...pickDefined(base.browser?.contextOptions),
257
+ ...pickDefined(overrides.browser?.contextOptions),
258
+ },
259
+ };
260
+ if (browser.browserName !== "chromium" && browser.launchOptions)
261
+ delete browser.launchOptions.channel;
262
+ return {
263
+ ...pickDefined(base),
264
+ ...pickDefined(overrides),
265
+ browser,
266
+ network: {
267
+ ...pickDefined(base.network),
268
+ ...pickDefined(overrides.network),
269
+ },
270
+ server: {
271
+ ...pickDefined(base.server),
272
+ ...pickDefined(overrides.server),
273
+ },
274
+ };
275
+ }
276
+ export function semicolonSeparatedList(value) {
277
+ if (!value)
278
+ return undefined;
279
+ return value.split(";").map((v) => v.trim());
280
+ }
281
+ export function commaSeparatedList(value) {
282
+ if (!value)
283
+ return undefined;
284
+ return value.split(",").map((v) => v.trim());
285
+ }
286
+ function envToNumber(value) {
287
+ if (!value)
288
+ return undefined;
289
+ return +value;
290
+ }
291
+ function envToBoolean(value) {
292
+ if (value === "true" || value === "1")
293
+ return true;
294
+ if (value === "false" || value === "0")
295
+ return false;
296
+ return undefined;
297
+ }
298
+ function envToString(value) {
299
+ return value ? value.trim() : undefined;
300
+ }
package/lib/context.js ADDED
@@ -0,0 +1,311 @@
1
+ /**
2
+ * Copyright (c) Microsoft Corporation.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ import debug from "debug";
17
+ import { outputFile } from "./config.js";
18
+ import { applyHooksToTools, hookRegistryMap } from "./hooks/core.js";
19
+ import { createEventStore, setEventStore } from "./hooks/events.js";
20
+ import { setupNetworkTracking } from "./hooks/networkSetup.js";
21
+ import { buildHookRegistry } from "./hooks/registry.js";
22
+ import { Tab } from "./tab.js";
23
+ import { shouldBlockRequest } from "./utils/adBlockFilter.js";
24
+ import * as codegen from "./utils/codegen.js";
25
+ import { logUnhandledError } from "./utils/log.js";
26
+ const testDebug = debug("pw:mcp:test");
27
+ const protocolPattern = /^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//;
28
+ const defaultPortForProtocol = (protocol) => {
29
+ if (protocol === "http:")
30
+ return "80";
31
+ if (protocol === "https:")
32
+ return "443";
33
+ return "";
34
+ };
35
+ const matchesOriginHost = (requestUrl, candidate) => {
36
+ const normalized = candidate.trim();
37
+ if (!normalized)
38
+ return false;
39
+ const hasProtocol = protocolPattern.test(normalized);
40
+ const parsed = (() => {
41
+ try {
42
+ return new URL(hasProtocol ? normalized : `http://${normalized}`);
43
+ }
44
+ catch {
45
+ return undefined;
46
+ }
47
+ })();
48
+ if (!parsed)
49
+ return false;
50
+ const candidateHost = parsed.hostname.toLowerCase().replace(/\.+$/, "");
51
+ if (!candidateHost)
52
+ return false;
53
+ const requestHost = requestUrl.hostname.toLowerCase();
54
+ if (requestHost !== candidateHost &&
55
+ !requestHost.endsWith(`.${candidateHost}`))
56
+ return false;
57
+ if (hasProtocol && parsed.protocol !== requestUrl.protocol)
58
+ return false;
59
+ if (parsed.port === "")
60
+ return true;
61
+ const candidatePort = parsed.port || defaultPortForProtocol(parsed.protocol);
62
+ if (!candidatePort)
63
+ return false;
64
+ const requestPort = requestUrl.port || defaultPortForProtocol(requestUrl.protocol);
65
+ return requestPort === candidatePort;
66
+ };
67
+ export class Context {
68
+ tools;
69
+ config;
70
+ sessionLog;
71
+ options;
72
+ _browserContextPromise;
73
+ _browserContextFactory;
74
+ _tabs = [];
75
+ _currentTab;
76
+ _clientInfo;
77
+ static _allContexts = new Set();
78
+ _closeBrowserContextPromise;
79
+ _isRunningTool = false;
80
+ _abortController = new AbortController();
81
+ constructor(options) {
82
+ // Set up hook registry and event store first
83
+ hookRegistryMap.set(this, buildHookRegistry());
84
+ setEventStore(this, createEventStore());
85
+ // Apply hooks to tools
86
+ this.tools = applyHooksToTools(options.tools, this);
87
+ this.config = options.config;
88
+ this.sessionLog = options.sessionLog;
89
+ this.options = options;
90
+ this._browserContextFactory = options.browserContextFactory;
91
+ this._clientInfo = options.clientInfo;
92
+ testDebug("create context");
93
+ Context._allContexts.add(this);
94
+ }
95
+ static async disposeAll() {
96
+ await Promise.all([...Context._allContexts].map((context) => context.dispose()));
97
+ }
98
+ tabs() {
99
+ return this._tabs;
100
+ }
101
+ currentTab() {
102
+ return this._currentTab;
103
+ }
104
+ currentTabOrDie() {
105
+ if (!this._currentTab)
106
+ throw new Error('No open pages available. Use the "browser_navigate" tool to navigate to a page first.');
107
+ return this._currentTab;
108
+ }
109
+ async newTab() {
110
+ const { browserContext } = await this._ensureBrowserContext();
111
+ const page = await browserContext.newPage();
112
+ this._currentTab = this._tabs.find((t) => t.page === page);
113
+ return this._currentTab;
114
+ }
115
+ async selectTab(index) {
116
+ const tab = this._tabs[index];
117
+ if (!tab)
118
+ throw new Error(`Tab ${index} not found`);
119
+ await tab.page.bringToFront();
120
+ this._currentTab = tab;
121
+ return tab;
122
+ }
123
+ async ensureTab() {
124
+ const { browserContext } = await this._ensureBrowserContext();
125
+ if (!this._currentTab)
126
+ await browserContext.newPage();
127
+ return this._currentTab;
128
+ }
129
+ async closeTab(index) {
130
+ const tab = index === undefined ? this._currentTab : this._tabs[index];
131
+ if (!tab)
132
+ throw new Error(`Tab ${index} not found`);
133
+ const url = tab.page.url();
134
+ await tab.page.close();
135
+ return url;
136
+ }
137
+ async outputFile(name) {
138
+ return outputFile(this.config, this._clientInfo.rootPath, name);
139
+ }
140
+ _onPageCreated(page) {
141
+ const tab = new Tab(this, page, (tab) => this._onPageClosed(tab));
142
+ this._tabs.push(tab);
143
+ if (!this._currentTab)
144
+ this._currentTab = tab;
145
+ // Set up network tracking via hooks system
146
+ setupNetworkTracking(this, page);
147
+ }
148
+ _onPageClosed(tab) {
149
+ const index = this._tabs.indexOf(tab);
150
+ if (index === -1)
151
+ return;
152
+ this._tabs.splice(index, 1);
153
+ if (this._currentTab === tab)
154
+ this._currentTab = this._tabs[Math.min(index, this._tabs.length - 1)];
155
+ if (!this._tabs.length)
156
+ void this.closeBrowserContext();
157
+ }
158
+ async closeBrowserContext() {
159
+ if (!this._closeBrowserContextPromise)
160
+ this._closeBrowserContextPromise =
161
+ this._closeBrowserContextImpl().catch(logUnhandledError);
162
+ await this._closeBrowserContextPromise;
163
+ this._closeBrowserContextPromise = undefined;
164
+ }
165
+ isRunningTool() {
166
+ return this._isRunningTool;
167
+ }
168
+ setRunningTool(isRunningTool) {
169
+ this._isRunningTool = isRunningTool;
170
+ }
171
+ async _closeBrowserContextImpl() {
172
+ if (!this._browserContextPromise)
173
+ return;
174
+ testDebug("close context");
175
+ const promise = this._browserContextPromise;
176
+ this._browserContextPromise = undefined;
177
+ await promise.then(async ({ browserContext, close }) => {
178
+ if (this.config.saveTrace)
179
+ await browserContext.tracing.stop();
180
+ await close();
181
+ });
182
+ }
183
+ async dispose() {
184
+ this._abortController.abort("MCP context disposed");
185
+ await this.closeBrowserContext();
186
+ Context._allContexts.delete(this);
187
+ }
188
+ async _setupRequestInterception(context) {
189
+ await context.route("**", (route) => {
190
+ const request = route.request();
191
+ const url = request.url();
192
+ const resourceType = request.resourceType();
193
+ let urlObj;
194
+ try {
195
+ urlObj = new URL(url);
196
+ }
197
+ catch {
198
+ void route.continue();
199
+ return;
200
+ }
201
+ const domain = urlObj.hostname;
202
+ if (shouldBlockRequest(url, domain, resourceType)) {
203
+ void route.abort("blockedbyclient");
204
+ return;
205
+ }
206
+ if (this.config.network?.allowedOrigins?.length) {
207
+ const isAllowed = this.config.network.allowedOrigins.some((allowed) => matchesOriginHost(urlObj, allowed));
208
+ if (!isAllowed) {
209
+ void route.abort("blockedbyclient");
210
+ return;
211
+ }
212
+ }
213
+ if (this.config.network?.blockedOrigins?.length) {
214
+ const isBlocked = this.config.network.blockedOrigins.some((blocked) => matchesOriginHost(urlObj, blocked));
215
+ if (isBlocked) {
216
+ void route.abort("blockedbyclient");
217
+ return;
218
+ }
219
+ }
220
+ void route.continue();
221
+ });
222
+ }
223
+ _ensureBrowserContext() {
224
+ if (!this._browserContextPromise) {
225
+ this._browserContextPromise = this._setupBrowserContext();
226
+ this._browserContextPromise.catch(() => {
227
+ this._browserContextPromise = undefined;
228
+ });
229
+ }
230
+ return this._browserContextPromise;
231
+ }
232
+ async _setupBrowserContext() {
233
+ if (this._closeBrowserContextPromise)
234
+ throw new Error("Another browser context is being closed.");
235
+ // TODO: move to the browser context factory to make it based on isolation mode.
236
+ const result = await this._browserContextFactory.createContext(this._clientInfo, this._abortController.signal);
237
+ const { browserContext } = result;
238
+ await this._setupRequestInterception(browserContext);
239
+ if (this.sessionLog)
240
+ await InputRecorder.create(this, browserContext);
241
+ for (const page of browserContext.pages())
242
+ this._onPageCreated(page);
243
+ browserContext.on("page", (page) => this._onPageCreated(page));
244
+ if (this.config.saveTrace) {
245
+ await browserContext.tracing.start({
246
+ name: "trace",
247
+ screenshots: false,
248
+ snapshots: true,
249
+ sources: false,
250
+ });
251
+ }
252
+ return result;
253
+ }
254
+ lookupSecret(secretName) {
255
+ // if (!this.config.secrets?.[secretName])
256
+ return { value: secretName, code: codegen.quote(secretName) };
257
+ // return {
258
+ // value: this.config.secrets[secretName]!,
259
+ // code: `process.env['${secretName}']`,
260
+ // };
261
+ }
262
+ }
263
+ export class InputRecorder {
264
+ _context;
265
+ _browserContext;
266
+ constructor(context, browserContext) {
267
+ this._context = context;
268
+ this._browserContext = browserContext;
269
+ }
270
+ static async create(context, browserContext) {
271
+ const recorder = new InputRecorder(context, browserContext);
272
+ await recorder._initialize();
273
+ return recorder;
274
+ }
275
+ async _initialize() {
276
+ const sessionLog = this._context.sessionLog;
277
+ await this._browserContext._enableRecorder({
278
+ mode: "recording",
279
+ recorderMode: "api",
280
+ }, {
281
+ actionAdded: (page, data, code) => {
282
+ if (this._context.isRunningTool())
283
+ return;
284
+ const tab = Tab.forPage(page);
285
+ if (tab)
286
+ sessionLog.logUserAction(data.action, tab, code, false);
287
+ },
288
+ actionUpdated: (page, data, code) => {
289
+ if (this._context.isRunningTool())
290
+ return;
291
+ const tab = Tab.forPage(page);
292
+ if (tab)
293
+ sessionLog.logUserAction(data.action, tab, code, true);
294
+ },
295
+ signalAdded: (page, data) => {
296
+ if (this._context.isRunningTool())
297
+ return;
298
+ if (data.signal.name !== "navigation")
299
+ return;
300
+ const tab = Tab.forPage(page);
301
+ const navigateAction = {
302
+ name: "navigate",
303
+ url: data.signal.url,
304
+ signals: [],
305
+ };
306
+ if (tab)
307
+ sessionLog.logUserAction(navigateAction, tab, `await page.goto('${data.signal.url}');`, false);
308
+ },
309
+ });
310
+ }
311
+ }