@ejazullah/browser-mcp 0.0.56

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 (66) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +860 -0
  3. package/cli.js +19 -0
  4. package/index.d.ts +23 -0
  5. package/index.js +1061 -0
  6. package/lib/auth.js +82 -0
  7. package/lib/browserContextFactory.js +205 -0
  8. package/lib/browserServerBackend.js +125 -0
  9. package/lib/config.js +266 -0
  10. package/lib/context.js +232 -0
  11. package/lib/databaseLogger.js +264 -0
  12. package/lib/extension/cdpRelay.js +346 -0
  13. package/lib/extension/extensionContextFactory.js +56 -0
  14. package/lib/extension/main.js +26 -0
  15. package/lib/fileUtils.js +32 -0
  16. package/lib/httpServer.js +39 -0
  17. package/lib/index.js +39 -0
  18. package/lib/javascript.js +49 -0
  19. package/lib/log.js +21 -0
  20. package/lib/loop/loop.js +69 -0
  21. package/lib/loop/loopClaude.js +152 -0
  22. package/lib/loop/loopOpenAI.js +143 -0
  23. package/lib/loop/main.js +60 -0
  24. package/lib/loopTools/context.js +66 -0
  25. package/lib/loopTools/main.js +49 -0
  26. package/lib/loopTools/perform.js +32 -0
  27. package/lib/loopTools/snapshot.js +29 -0
  28. package/lib/loopTools/tool.js +18 -0
  29. package/lib/manualPromise.js +111 -0
  30. package/lib/mcp/inProcessTransport.js +72 -0
  31. package/lib/mcp/server.js +93 -0
  32. package/lib/mcp/transport.js +217 -0
  33. package/lib/mongoDBLogger.js +252 -0
  34. package/lib/package.js +20 -0
  35. package/lib/program.js +113 -0
  36. package/lib/response.js +172 -0
  37. package/lib/sessionLog.js +156 -0
  38. package/lib/tab.js +266 -0
  39. package/lib/tools/cdp.js +169 -0
  40. package/lib/tools/common.js +55 -0
  41. package/lib/tools/console.js +33 -0
  42. package/lib/tools/dialogs.js +47 -0
  43. package/lib/tools/evaluate.js +53 -0
  44. package/lib/tools/extraction.js +217 -0
  45. package/lib/tools/files.js +44 -0
  46. package/lib/tools/forms.js +180 -0
  47. package/lib/tools/getext.js +99 -0
  48. package/lib/tools/install.js +53 -0
  49. package/lib/tools/interactions.js +191 -0
  50. package/lib/tools/keyboard.js +86 -0
  51. package/lib/tools/mouse.js +99 -0
  52. package/lib/tools/navigate.js +70 -0
  53. package/lib/tools/network.js +41 -0
  54. package/lib/tools/pdf.js +40 -0
  55. package/lib/tools/screenshot.js +75 -0
  56. package/lib/tools/selectors.js +233 -0
  57. package/lib/tools/snapshot.js +169 -0
  58. package/lib/tools/states.js +147 -0
  59. package/lib/tools/tabs.js +87 -0
  60. package/lib/tools/tool.js +33 -0
  61. package/lib/tools/utils.js +74 -0
  62. package/lib/tools/wait.js +56 -0
  63. package/lib/tools.js +64 -0
  64. package/lib/utils.js +26 -0
  65. package/openapi.json +683 -0
  66. package/package.json +92 -0
package/lib/auth.js ADDED
@@ -0,0 +1,82 @@
1
+ /**
2
+ * External API Key Authentication
3
+ *
4
+ * Validates API keys against the external auth provider:
5
+ * POST https://system-mangment-app.vercel.app/api/validate
6
+ * Headers: { "X-API-KEY": "<key>" }
7
+ */
8
+ const VALIDATE_URL = process.env.VALIDATE_URL || 'https://nexviahub.vercel.app/functions/v1/api-keys';
9
+ const CACHE_TTL_MS = 2 * 60 * 1000; // 2 minutes
10
+ const validationCache = new Map();
11
+ // ─── Core Validator ──────────────────────────────────────────────────────────
12
+ /**
13
+ * Validate an API key against the external auth provider.
14
+ * Results are cached for 5 minutes to reduce external API calls.
15
+ */
16
+ export async function validateApiKey(apiKey) {
17
+ const cached = validationCache.get(apiKey);
18
+ if (cached && Date.now() < cached.expiresAt)
19
+ return cached.valid;
20
+ let valid = false;
21
+ try {
22
+ const response = await fetch(VALIDATE_URL, {
23
+ method: 'POST',
24
+ headers: { 'X-API-KEY': apiKey },
25
+ body: JSON.stringify({ "action": "authorize" })
26
+ });
27
+ valid = response.ok;
28
+ }
29
+ catch {
30
+ valid = false;
31
+ }
32
+ validationCache.set(apiKey, { valid, expiresAt: Date.now() + CACHE_TTL_MS });
33
+ return valid;
34
+ }
35
+ // ─── HTTP Middleware ──────────────────────────────────────────────────────────
36
+ /**
37
+ * Authenticate an incoming HTTP request.
38
+ * Reads the X-API-KEY header and validates it against the external provider.
39
+ * Returns false if authenticated (request may proceed).
40
+ * Returns true if authentication failed (error response already sent).
41
+ */
42
+ export async function authenticateRequest(req, res) {
43
+ const apiKey = req.headers['x-api-key'];
44
+ if (!apiKey) {
45
+ res.setHeader('WWW-Authenticate', 'ApiKey realm="mcp-playwright"');
46
+ sendJsonResponse(res, 401, {
47
+ error: 'unauthorized',
48
+ error_description: 'Authentication required. Provide your API key via the X-API-KEY header.',
49
+ });
50
+ return true;
51
+ }
52
+ const valid = await validateApiKey(apiKey);
53
+ if (!valid) {
54
+ sendJsonResponse(res, 401, {
55
+ error: 'invalid_api_key',
56
+ error_description: 'The provided API key is invalid or has been revoked.',
57
+ });
58
+ return true;
59
+ }
60
+ return false; // authenticated
61
+ }
62
+ // ─── Utilities ───────────────────────────────────────────────────────────────
63
+ function sendJsonResponse(res, status, body) {
64
+ res.setHeader('Content-Type', 'application/json');
65
+ res.statusCode = status;
66
+ res.end(JSON.stringify(body));
67
+ }
68
+ export function defaultAuthConfig() {
69
+ return { enabled: true };
70
+ }
71
+ export function buildAuthConfig(_options) {
72
+ return { enabled: true };
73
+ }
74
+ export class AuthManager {
75
+ constructor(_config) { }
76
+ get enabled() {
77
+ return true;
78
+ }
79
+ async authenticateRequest(req, res) {
80
+ return authenticateRequest(req, res);
81
+ }
82
+ }
@@ -0,0 +1,205 @@
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 net from 'net';
18
+ import path from 'path';
19
+ import * as playwright from 'playwright';
20
+ // @ts-ignore
21
+ import { registryDirectory } from 'playwright-core/lib/server/registry/index';
22
+ import { logUnhandledError, testDebug } from './log.js';
23
+ import { createHash } from './utils.js';
24
+ import { outputFile } from './config.js';
25
+ export function contextFactory(config) {
26
+ if (config.browser.remoteEndpoint)
27
+ return new RemoteContextFactory(config);
28
+ if (config.browser.cdpEndpoint)
29
+ return new CdpContextFactory(config);
30
+ if (config.browser.isolated)
31
+ return new IsolatedContextFactory(config);
32
+ return new PersistentContextFactory(config);
33
+ }
34
+ class BaseContextFactory {
35
+ name;
36
+ description;
37
+ config;
38
+ _browserPromise;
39
+ _tracesDir;
40
+ constructor(name, description, config) {
41
+ this.name = name;
42
+ this.description = description;
43
+ this.config = config;
44
+ }
45
+ async _obtainBrowser() {
46
+ if (this._browserPromise)
47
+ return this._browserPromise;
48
+ testDebug(`obtain browser (${this.name})`);
49
+ this._browserPromise = this._doObtainBrowser();
50
+ void this._browserPromise.then(browser => {
51
+ browser.on('disconnected', () => {
52
+ this._browserPromise = undefined;
53
+ });
54
+ }).catch(() => {
55
+ this._browserPromise = undefined;
56
+ });
57
+ return this._browserPromise;
58
+ }
59
+ async _doObtainBrowser() {
60
+ throw new Error('Not implemented');
61
+ }
62
+ async createContext(clientInfo) {
63
+ if (this.config.saveTrace)
64
+ this._tracesDir = await outputFile(this.config, clientInfo.rootPath, `traces-${Date.now()}`);
65
+ testDebug(`create browser context (${this.name})`);
66
+ const browser = await this._obtainBrowser();
67
+ const browserContext = await this._doCreateContext(browser);
68
+ return { browserContext, close: () => this._closeBrowserContext(browserContext, browser) };
69
+ }
70
+ async _doCreateContext(browser) {
71
+ throw new Error('Not implemented');
72
+ }
73
+ async _closeBrowserContext(browserContext, browser) {
74
+ testDebug(`close browser context (${this.name})`);
75
+ if (browser.contexts().length === 1)
76
+ this._browserPromise = undefined;
77
+ await browserContext.close().catch(logUnhandledError);
78
+ if (browser.contexts().length === 0) {
79
+ testDebug(`close browser (${this.name})`);
80
+ await browser.close().catch(logUnhandledError);
81
+ }
82
+ }
83
+ }
84
+ class IsolatedContextFactory extends BaseContextFactory {
85
+ constructor(config) {
86
+ super('isolated', 'Create a new isolated browser context', config);
87
+ }
88
+ async _doObtainBrowser() {
89
+ await injectCdpPort(this.config.browser);
90
+ const browserType = playwright[this.config.browser.browserName];
91
+ return browserType.launch({
92
+ tracesDir: this._tracesDir,
93
+ ...this.config.browser.launchOptions,
94
+ handleSIGINT: false,
95
+ handleSIGTERM: false,
96
+ }).catch(error => {
97
+ if (error.message.includes('Executable doesn\'t exist'))
98
+ throw new Error(`Browser specified in your config is not installed. Either install it (likely) or change the config.`);
99
+ throw error;
100
+ });
101
+ }
102
+ async _doCreateContext(browser) {
103
+ return browser.newContext(this.config.browser.contextOptions);
104
+ }
105
+ }
106
+ class CdpContextFactory extends BaseContextFactory {
107
+ constructor(config) {
108
+ super('cdp', 'Connect to a browser over CDP', config);
109
+ }
110
+ async _doObtainBrowser() {
111
+ return playwright.chromium.connectOverCDP(this.config.browser.cdpEndpoint);
112
+ }
113
+ async _doCreateContext(browser) {
114
+ return this.config.browser.isolated ? await browser.newContext() : browser.contexts()[0];
115
+ }
116
+ }
117
+ class RemoteContextFactory extends BaseContextFactory {
118
+ constructor(config) {
119
+ super('remote', 'Connect to a browser using a remote endpoint', config);
120
+ }
121
+ async _doObtainBrowser() {
122
+ const url = new URL(this.config.browser.remoteEndpoint);
123
+ url.searchParams.set('browser', this.config.browser.browserName);
124
+ if (this.config.browser.launchOptions)
125
+ url.searchParams.set('launch-options', JSON.stringify(this.config.browser.launchOptions));
126
+ return playwright[this.config.browser.browserName].connect(String(url));
127
+ }
128
+ async _doCreateContext(browser) {
129
+ return browser.newContext();
130
+ }
131
+ }
132
+ class PersistentContextFactory {
133
+ config;
134
+ name = 'persistent';
135
+ description = 'Create a new persistent browser context';
136
+ _userDataDirs = new Set();
137
+ constructor(config) {
138
+ this.config = config;
139
+ }
140
+ async createContext(clientInfo) {
141
+ await injectCdpPort(this.config.browser);
142
+ testDebug('create browser context (persistent)');
143
+ const userDataDir = this.config.browser.userDataDir ?? await this._createUserDataDir(clientInfo.rootPath);
144
+ let tracesDir;
145
+ if (this.config.saveTrace)
146
+ tracesDir = await outputFile(this.config, clientInfo.rootPath, `traces-${Date.now()}`);
147
+ this._userDataDirs.add(userDataDir);
148
+ testDebug('lock user data dir', userDataDir);
149
+ const browserType = playwright[this.config.browser.browserName];
150
+ for (let i = 0; i < 5; i++) {
151
+ try {
152
+ const browserContext = await browserType.launchPersistentContext(userDataDir, {
153
+ tracesDir,
154
+ ...this.config.browser.launchOptions,
155
+ ...this.config.browser.contextOptions,
156
+ handleSIGINT: false,
157
+ handleSIGTERM: false,
158
+ });
159
+ const close = () => this._closeBrowserContext(browserContext, userDataDir);
160
+ return { browserContext, close };
161
+ }
162
+ catch (error) {
163
+ if (error.message.includes('Executable doesn\'t exist'))
164
+ throw new Error(`Browser specified in your config is not installed. Either install it (likely) or change the config.`);
165
+ if (error.message.includes('ProcessSingleton') || error.message.includes('Invalid URL')) {
166
+ // User data directory is already in use, try again.
167
+ await new Promise(resolve => setTimeout(resolve, 1000));
168
+ continue;
169
+ }
170
+ throw error;
171
+ }
172
+ }
173
+ throw new Error(`Browser is already in use for ${userDataDir}, use --isolated to run multiple instances of the same browser`);
174
+ }
175
+ async _closeBrowserContext(browserContext, userDataDir) {
176
+ testDebug('close browser context (persistent)');
177
+ testDebug('release user data dir', userDataDir);
178
+ await browserContext.close().catch(() => { });
179
+ this._userDataDirs.delete(userDataDir);
180
+ testDebug('close browser context complete (persistent)');
181
+ }
182
+ async _createUserDataDir(rootPath) {
183
+ const dir = process.env.PWMCP_PROFILES_DIR_FOR_TEST ?? registryDirectory;
184
+ const browserToken = this.config.browser.launchOptions?.channel ?? this.config.browser?.browserName;
185
+ // Hesitant putting hundreds of files into the user's workspace, so using it for hashing instead.
186
+ const rootPathToken = rootPath ? `-${createHash(rootPath)}` : '';
187
+ const result = path.join(dir, `mcp-${browserToken}${rootPathToken}`);
188
+ await fs.promises.mkdir(result, { recursive: true });
189
+ return result;
190
+ }
191
+ }
192
+ async function injectCdpPort(browserConfig) {
193
+ if (browserConfig.browserName === 'chromium')
194
+ browserConfig.launchOptions.cdpPort = await findFreePort();
195
+ }
196
+ async function findFreePort() {
197
+ return new Promise((resolve, reject) => {
198
+ const server = net.createServer();
199
+ server.listen(0, () => {
200
+ const { port } = server.address();
201
+ server.close(() => resolve(port));
202
+ });
203
+ server.on('error', reject);
204
+ });
205
+ }
@@ -0,0 +1,125 @@
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 { fileURLToPath } from 'url';
17
+ import { z } from 'zod';
18
+ import { Context } from './context.js';
19
+ import { logUnhandledError } from './log.js';
20
+ import { Response } from './response.js';
21
+ import { SessionLog } from './sessionLog.js';
22
+ import { filteredTools } from './tools.js';
23
+ import { packageJSON } from './package.js';
24
+ import { defineTool } from './tools/tool.js';
25
+ export class BrowserServerBackend {
26
+ name = 'Playwright';
27
+ version = packageJSON.version;
28
+ _tools;
29
+ _context;
30
+ _sessionLog;
31
+ _config;
32
+ _browserContextFactory;
33
+ constructor(config, factories) {
34
+ this._config = config;
35
+ this._browserContextFactory = factories[0];
36
+ this._tools = filteredTools(config);
37
+ if (factories.length > 1)
38
+ this._tools.push(this._defineContextSwitchTool(factories));
39
+ }
40
+ async initialize(server) {
41
+ const capabilities = server.getClientCapabilities();
42
+ let rootPath;
43
+ if (capabilities.roots && (server.getClientVersion()?.name === 'Visual Studio Code' ||
44
+ server.getClientVersion()?.name === 'Visual Studio Code - Insiders')) {
45
+ const { roots } = await server.listRoots();
46
+ const firstRootUri = roots[0]?.uri;
47
+ const url = firstRootUri ? new URL(firstRootUri) : undefined;
48
+ rootPath = url ? fileURLToPath(url) : undefined;
49
+ }
50
+ this._sessionLog = this._config.saveSession ? await SessionLog.create(this._config, rootPath) : undefined;
51
+ this._context = new Context({
52
+ tools: this._tools,
53
+ config: this._config,
54
+ browserContextFactory: this._browserContextFactory,
55
+ sessionLog: this._sessionLog,
56
+ clientInfo: { ...server.getClientVersion(), rootPath },
57
+ });
58
+ }
59
+ tools() {
60
+ return this._tools.map(tool => tool.schema);
61
+ }
62
+ async callTool(schema, parsedArguments) {
63
+ const context = this._context;
64
+ const response = new Response(context, schema.name, parsedArguments);
65
+ const tool = this._tools.find(tool => tool.schema.name === schema.name);
66
+ context.setRunningTool(true);
67
+ try {
68
+ await tool.handle(context, parsedArguments, response);
69
+ await response.finish();
70
+ this._sessionLog?.logResponse(response);
71
+ }
72
+ catch (error) {
73
+ response.addError(String(error));
74
+ }
75
+ finally {
76
+ context.setRunningTool(false);
77
+ }
78
+ return response.serialize();
79
+ }
80
+ serverClosed() {
81
+ try {
82
+ void this._context?.dispose().catch(logUnhandledError);
83
+ }
84
+ catch {
85
+ }
86
+ }
87
+ _defineContextSwitchTool(factories) {
88
+ const self = this;
89
+ return defineTool({
90
+ capability: 'core',
91
+ schema: {
92
+ name: 'browser_connect',
93
+ title: 'Connect to a browser context',
94
+ description: [
95
+ 'Connect to a browser using one of the available methods:',
96
+ ...factories.map(factory => `- "${factory.name}": ${factory.description}`),
97
+ ].join('\n'),
98
+ inputSchema: z.object({
99
+ method: z.enum(factories.map(factory => factory.name)).default(factories[0].name).describe('The method to use to connect to the browser'),
100
+ }),
101
+ type: 'readOnly',
102
+ },
103
+ async handle(context, params, response) {
104
+ const factory = factories.find(factory => factory.name === params.method);
105
+ if (!factory) {
106
+ response.addError('Unknown connection method: ' + params.method);
107
+ return;
108
+ }
109
+ await self._setContextFactory(factory);
110
+ response.addResult('Successfully changed connection method.');
111
+ }
112
+ });
113
+ }
114
+ async _setContextFactory(newFactory) {
115
+ if (this._context) {
116
+ const options = {
117
+ ...this._context.options,
118
+ browserContextFactory: newFactory,
119
+ };
120
+ await this._context.dispose();
121
+ this._context = new Context(options);
122
+ }
123
+ this._browserContextFactory = newFactory;
124
+ }
125
+ }
package/lib/config.js ADDED
@@ -0,0 +1,266 @@
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';
20
+ import { sanitizeForFilePath } from './utils.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
+ };
82
+ // --no-sandbox was passed, disable the sandbox
83
+ if (cliOptions.sandbox === false)
84
+ launchOptions.chromiumSandbox = false;
85
+ if (cliOptions.proxyServer) {
86
+ launchOptions.proxy = {
87
+ server: cliOptions.proxyServer
88
+ };
89
+ if (cliOptions.proxyBypass)
90
+ launchOptions.proxy.bypass = cliOptions.proxyBypass;
91
+ }
92
+ if (cliOptions.device && cliOptions.cdpEndpoint)
93
+ throw new Error('Device emulation is not supported with cdpEndpoint.');
94
+ // Context options
95
+ const contextOptions = cliOptions.device ? devices[cliOptions.device] : {};
96
+ if (cliOptions.storageState)
97
+ contextOptions.storageState = cliOptions.storageState;
98
+ if (cliOptions.userAgent)
99
+ contextOptions.userAgent = cliOptions.userAgent;
100
+ if (cliOptions.viewportSize) {
101
+ try {
102
+ const [width, height] = cliOptions.viewportSize.split(',').map(n => +n);
103
+ if (isNaN(width) || isNaN(height))
104
+ throw new Error('bad values');
105
+ contextOptions.viewport = { width, height };
106
+ }
107
+ catch (e) {
108
+ throw new Error('Invalid viewport size format: use "width,height", for example --viewport-size="800,600"');
109
+ }
110
+ }
111
+ if (cliOptions.ignoreHttpsErrors)
112
+ contextOptions.ignoreHTTPSErrors = true;
113
+ if (cliOptions.blockServiceWorkers)
114
+ contextOptions.serviceWorkers = 'block';
115
+ const result = {
116
+ browser: {
117
+ browserName,
118
+ isolated: cliOptions.isolated,
119
+ userDataDir: cliOptions.userDataDir,
120
+ launchOptions,
121
+ contextOptions,
122
+ cdpEndpoint: cliOptions.cdpEndpoint,
123
+ },
124
+ server: {
125
+ port: cliOptions.port,
126
+ host: cliOptions.host,
127
+ },
128
+ capabilities: cliOptions.caps,
129
+ network: {
130
+ allowedOrigins: cliOptions.allowedOrigins,
131
+ blockedOrigins: cliOptions.blockedOrigins,
132
+ },
133
+ saveSession: cliOptions.saveSession,
134
+ saveTrace: cliOptions.saveTrace,
135
+ outputDir: cliOptions.outputDir,
136
+ imageResponses: cliOptions.imageResponses,
137
+ mongodb: {
138
+ url: cliOptions.mongodbUrl,
139
+ dbName: cliOptions.mongodbDb,
140
+ collectionName: cliOptions.mongodbCollection,
141
+ },
142
+ auth: {
143
+ enabled: cliOptions.auth,
144
+ jwtSecret: cliOptions.jwtSecret,
145
+ tokenExpiry: cliOptions.tokenExpiry,
146
+ apiKeys: cliOptions.apiKeys,
147
+ oauthClients: cliOptions.oauthClients,
148
+ },
149
+ };
150
+ return result;
151
+ }
152
+ function configFromEnv() {
153
+ const options = {};
154
+ options.allowedOrigins = semicolonSeparatedList(process.env.PLAYWRIGHT_MCP_ALLOWED_ORIGINS);
155
+ options.blockedOrigins = semicolonSeparatedList(process.env.PLAYWRIGHT_MCP_BLOCKED_ORIGINS);
156
+ options.blockServiceWorkers = envToBoolean(process.env.PLAYWRIGHT_MCP_BLOCK_SERVICE_WORKERS);
157
+ options.browser = envToString(process.env.PLAYWRIGHT_MCP_BROWSER);
158
+ options.caps = commaSeparatedList(process.env.PLAYWRIGHT_MCP_CAPS);
159
+ options.cdpEndpoint = envToString(process.env.PLAYWRIGHT_MCP_CDP_ENDPOINT);
160
+ options.config = envToString(process.env.PLAYWRIGHT_MCP_CONFIG);
161
+ options.device = envToString(process.env.PLAYWRIGHT_MCP_DEVICE);
162
+ options.executablePath = envToString(process.env.PLAYWRIGHT_MCP_EXECUTABLE_PATH);
163
+ options.headless = envToBoolean(process.env.PLAYWRIGHT_MCP_HEADLESS);
164
+ options.host = envToString(process.env.PLAYWRIGHT_MCP_HOST);
165
+ options.ignoreHttpsErrors = envToBoolean(process.env.PLAYWRIGHT_MCP_IGNORE_HTTPS_ERRORS);
166
+ options.isolated = envToBoolean(process.env.PLAYWRIGHT_MCP_ISOLATED);
167
+ if (process.env.PLAYWRIGHT_MCP_IMAGE_RESPONSES === 'omit')
168
+ options.imageResponses = 'omit';
169
+ options.sandbox = envToBoolean(process.env.PLAYWRIGHT_MCP_SANDBOX);
170
+ options.outputDir = envToString(process.env.PLAYWRIGHT_MCP_OUTPUT_DIR);
171
+ options.port = envToNumber(process.env.PLAYWRIGHT_MCP_PORT);
172
+ options.proxyBypass = envToString(process.env.PLAYWRIGHT_MCP_PROXY_BYPASS);
173
+ options.proxyServer = envToString(process.env.PLAYWRIGHT_MCP_PROXY_SERVER);
174
+ options.saveTrace = envToBoolean(process.env.PLAYWRIGHT_MCP_SAVE_TRACE);
175
+ options.storageState = envToString(process.env.PLAYWRIGHT_MCP_STORAGE_STATE);
176
+ options.userAgent = envToString(process.env.PLAYWRIGHT_MCP_USER_AGENT);
177
+ options.userDataDir = envToString(process.env.PLAYWRIGHT_MCP_USER_DATA_DIR);
178
+ options.viewportSize = envToString(process.env.PLAYWRIGHT_MCP_VIEWPORT_SIZE);
179
+ options.mongodbUrl = envToString(process.env.MONGODB_URL);
180
+ options.mongodbDb = envToString(process.env.MONGODB_DB_NAME);
181
+ options.mongodbCollection = envToString(process.env.MONGODB_COLLECTION);
182
+ options.auth = envToBoolean(process.env.MCP_AUTH_ENABLED);
183
+ options.jwtSecret = envToString(process.env.MCP_JWT_SECRET);
184
+ options.tokenExpiry = envToString(process.env.MCP_TOKEN_EXPIRY);
185
+ options.apiKeys = envToString(process.env.MCP_API_KEYS);
186
+ options.oauthClients = envToString(process.env.MCP_OAUTH_CLIENTS);
187
+ return configFromCLIOptions(options);
188
+ }
189
+ async function loadConfig(configFile) {
190
+ if (!configFile)
191
+ return {};
192
+ try {
193
+ return JSON.parse(await fs.promises.readFile(configFile, 'utf8'));
194
+ }
195
+ catch (error) {
196
+ throw new Error(`Failed to load config file: ${configFile}, ${error}`);
197
+ }
198
+ }
199
+ export async function outputFile(config, rootPath, name) {
200
+ const outputDir = config.outputDir
201
+ ?? (rootPath ? path.join(rootPath, '.playwright-mcp') : undefined)
202
+ ?? path.join(os.tmpdir(), 'playwright-mcp-output', sanitizeForFilePath(new Date().toISOString()));
203
+ await fs.promises.mkdir(outputDir, { recursive: true });
204
+ const fileName = sanitizeForFilePath(name);
205
+ return path.join(outputDir, fileName);
206
+ }
207
+ function pickDefined(obj) {
208
+ return Object.fromEntries(Object.entries(obj ?? {}).filter(([_, v]) => v !== undefined));
209
+ }
210
+ function mergeConfig(base, overrides) {
211
+ const browser = {
212
+ ...pickDefined(base.browser),
213
+ ...pickDefined(overrides.browser),
214
+ browserName: overrides.browser?.browserName ?? base.browser?.browserName ?? 'chromium',
215
+ isolated: overrides.browser?.isolated ?? base.browser?.isolated ?? false,
216
+ launchOptions: {
217
+ ...pickDefined(base.browser?.launchOptions),
218
+ ...pickDefined(overrides.browser?.launchOptions),
219
+ ...{ assistantMode: true },
220
+ },
221
+ contextOptions: {
222
+ ...pickDefined(base.browser?.contextOptions),
223
+ ...pickDefined(overrides.browser?.contextOptions),
224
+ },
225
+ };
226
+ if (browser.browserName !== 'chromium' && browser.launchOptions)
227
+ delete browser.launchOptions.channel;
228
+ return {
229
+ ...pickDefined(base),
230
+ ...pickDefined(overrides),
231
+ browser,
232
+ network: {
233
+ ...pickDefined(base.network),
234
+ ...pickDefined(overrides.network),
235
+ },
236
+ server: {
237
+ ...pickDefined(base.server),
238
+ ...pickDefined(overrides.server),
239
+ },
240
+ };
241
+ }
242
+ export function semicolonSeparatedList(value) {
243
+ if (!value)
244
+ return undefined;
245
+ return value.split(';').map(v => v.trim());
246
+ }
247
+ export function commaSeparatedList(value) {
248
+ if (!value)
249
+ return undefined;
250
+ return value.split(',').map(v => v.trim());
251
+ }
252
+ function envToNumber(value) {
253
+ if (!value)
254
+ return undefined;
255
+ return +value;
256
+ }
257
+ function envToBoolean(value) {
258
+ if (value === 'true' || value === '1')
259
+ return true;
260
+ if (value === 'false' || value === '0')
261
+ return false;
262
+ return undefined;
263
+ }
264
+ function envToString(value) {
265
+ return value ? value.trim() : undefined;
266
+ }