@playwright/mcp 0.0.36 → 0.0.37-alpha-2025-09-09

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 (61) hide show
  1. package/README.md +82 -47
  2. package/cli.js +7 -1
  3. package/config.d.ts +24 -0
  4. package/index.d.ts +1 -1
  5. package/index.js +2 -2
  6. package/package.json +14 -40
  7. package/lib/browserContextFactory.js +0 -211
  8. package/lib/browserServerBackend.js +0 -77
  9. package/lib/config.js +0 -246
  10. package/lib/context.js +0 -226
  11. package/lib/extension/cdpRelay.js +0 -358
  12. package/lib/extension/extensionContextFactory.js +0 -56
  13. package/lib/extension/protocol.js +0 -18
  14. package/lib/index.js +0 -40
  15. package/lib/loop/loop.js +0 -69
  16. package/lib/loop/loopClaude.js +0 -152
  17. package/lib/loop/loopOpenAI.js +0 -141
  18. package/lib/loop/main.js +0 -60
  19. package/lib/loopTools/context.js +0 -67
  20. package/lib/loopTools/main.js +0 -54
  21. package/lib/loopTools/perform.js +0 -32
  22. package/lib/loopTools/snapshot.js +0 -29
  23. package/lib/loopTools/tool.js +0 -18
  24. package/lib/mcp/http.js +0 -135
  25. package/lib/mcp/inProcessTransport.js +0 -72
  26. package/lib/mcp/manualPromise.js +0 -111
  27. package/lib/mcp/mdb.js +0 -198
  28. package/lib/mcp/proxyBackend.js +0 -104
  29. package/lib/mcp/server.js +0 -123
  30. package/lib/mcp/tool.js +0 -32
  31. package/lib/program.js +0 -132
  32. package/lib/response.js +0 -165
  33. package/lib/sessionLog.js +0 -121
  34. package/lib/tab.js +0 -249
  35. package/lib/tools/common.js +0 -55
  36. package/lib/tools/console.js +0 -33
  37. package/lib/tools/dialogs.js +0 -47
  38. package/lib/tools/evaluate.js +0 -53
  39. package/lib/tools/files.js +0 -44
  40. package/lib/tools/form.js +0 -57
  41. package/lib/tools/install.js +0 -53
  42. package/lib/tools/keyboard.js +0 -78
  43. package/lib/tools/mouse.js +0 -99
  44. package/lib/tools/navigate.js +0 -54
  45. package/lib/tools/network.js +0 -41
  46. package/lib/tools/pdf.js +0 -40
  47. package/lib/tools/screenshot.js +0 -79
  48. package/lib/tools/snapshot.js +0 -139
  49. package/lib/tools/tabs.js +0 -59
  50. package/lib/tools/tool.js +0 -33
  51. package/lib/tools/utils.js +0 -74
  52. package/lib/tools/verify.js +0 -137
  53. package/lib/tools/wait.js +0 -55
  54. package/lib/tools.js +0 -54
  55. package/lib/utils/codegen.js +0 -49
  56. package/lib/utils/fileUtils.js +0 -36
  57. package/lib/utils/guid.js +0 -22
  58. package/lib/utils/log.js +0 -21
  59. package/lib/utils/package.js +0 -20
  60. package/lib/vscode/host.js +0 -128
  61. package/lib/vscode/main.js +0 -62
package/lib/config.js DELETED
@@ -1,246 +0,0 @@
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/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
- };
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
- };
138
- return result;
139
- }
140
- function configFromEnv() {
141
- const options = {};
142
- options.allowedOrigins = semicolonSeparatedList(process.env.PLAYWRIGHT_MCP_ALLOWED_ORIGINS);
143
- options.blockedOrigins = semicolonSeparatedList(process.env.PLAYWRIGHT_MCP_BLOCKED_ORIGINS);
144
- options.blockServiceWorkers = envToBoolean(process.env.PLAYWRIGHT_MCP_BLOCK_SERVICE_WORKERS);
145
- options.browser = envToString(process.env.PLAYWRIGHT_MCP_BROWSER);
146
- options.caps = commaSeparatedList(process.env.PLAYWRIGHT_MCP_CAPS);
147
- options.cdpEndpoint = envToString(process.env.PLAYWRIGHT_MCP_CDP_ENDPOINT);
148
- options.config = envToString(process.env.PLAYWRIGHT_MCP_CONFIG);
149
- options.device = envToString(process.env.PLAYWRIGHT_MCP_DEVICE);
150
- options.executablePath = envToString(process.env.PLAYWRIGHT_MCP_EXECUTABLE_PATH);
151
- options.headless = envToBoolean(process.env.PLAYWRIGHT_MCP_HEADLESS);
152
- options.host = envToString(process.env.PLAYWRIGHT_MCP_HOST);
153
- options.ignoreHttpsErrors = envToBoolean(process.env.PLAYWRIGHT_MCP_IGNORE_HTTPS_ERRORS);
154
- options.isolated = envToBoolean(process.env.PLAYWRIGHT_MCP_ISOLATED);
155
- if (process.env.PLAYWRIGHT_MCP_IMAGE_RESPONSES === 'omit')
156
- options.imageResponses = 'omit';
157
- options.sandbox = envToBoolean(process.env.PLAYWRIGHT_MCP_SANDBOX);
158
- options.outputDir = envToString(process.env.PLAYWRIGHT_MCP_OUTPUT_DIR);
159
- options.port = envToNumber(process.env.PLAYWRIGHT_MCP_PORT);
160
- options.proxyBypass = envToString(process.env.PLAYWRIGHT_MCP_PROXY_BYPASS);
161
- options.proxyServer = envToString(process.env.PLAYWRIGHT_MCP_PROXY_SERVER);
162
- options.saveTrace = envToBoolean(process.env.PLAYWRIGHT_MCP_SAVE_TRACE);
163
- options.storageState = envToString(process.env.PLAYWRIGHT_MCP_STORAGE_STATE);
164
- options.userAgent = envToString(process.env.PLAYWRIGHT_MCP_USER_AGENT);
165
- options.userDataDir = envToString(process.env.PLAYWRIGHT_MCP_USER_DATA_DIR);
166
- options.viewportSize = envToString(process.env.PLAYWRIGHT_MCP_VIEWPORT_SIZE);
167
- return configFromCLIOptions(options);
168
- }
169
- async function loadConfig(configFile) {
170
- if (!configFile)
171
- return {};
172
- try {
173
- return JSON.parse(await fs.promises.readFile(configFile, 'utf8'));
174
- }
175
- catch (error) {
176
- throw new Error(`Failed to load config file: ${configFile}, ${error}`);
177
- }
178
- }
179
- export async function outputFile(config, rootPath, name) {
180
- const outputDir = config.outputDir
181
- ?? (rootPath ? path.join(rootPath, '.playwright-mcp') : undefined)
182
- ?? path.join(os.tmpdir(), 'playwright-mcp-output', sanitizeForFilePath(new Date().toISOString()));
183
- await fs.promises.mkdir(outputDir, { recursive: true });
184
- const fileName = sanitizeForFilePath(name);
185
- return path.join(outputDir, fileName);
186
- }
187
- function pickDefined(obj) {
188
- return Object.fromEntries(Object.entries(obj ?? {}).filter(([_, v]) => v !== undefined));
189
- }
190
- function mergeConfig(base, overrides) {
191
- const browser = {
192
- ...pickDefined(base.browser),
193
- ...pickDefined(overrides.browser),
194
- browserName: overrides.browser?.browserName ?? base.browser?.browserName ?? 'chromium',
195
- isolated: overrides.browser?.isolated ?? base.browser?.isolated ?? false,
196
- launchOptions: {
197
- ...pickDefined(base.browser?.launchOptions),
198
- ...pickDefined(overrides.browser?.launchOptions),
199
- ...{ assistantMode: true },
200
- },
201
- contextOptions: {
202
- ...pickDefined(base.browser?.contextOptions),
203
- ...pickDefined(overrides.browser?.contextOptions),
204
- },
205
- };
206
- if (browser.browserName !== 'chromium' && browser.launchOptions)
207
- delete browser.launchOptions.channel;
208
- return {
209
- ...pickDefined(base),
210
- ...pickDefined(overrides),
211
- browser,
212
- network: {
213
- ...pickDefined(base.network),
214
- ...pickDefined(overrides.network),
215
- },
216
- server: {
217
- ...pickDefined(base.server),
218
- ...pickDefined(overrides.server),
219
- },
220
- };
221
- }
222
- export function semicolonSeparatedList(value) {
223
- if (!value)
224
- return undefined;
225
- return value.split(';').map(v => v.trim());
226
- }
227
- export function commaSeparatedList(value) {
228
- if (!value)
229
- return undefined;
230
- return value.split(',').map(v => v.trim());
231
- }
232
- function envToNumber(value) {
233
- if (!value)
234
- return undefined;
235
- return +value;
236
- }
237
- function envToBoolean(value) {
238
- if (value === 'true' || value === '1')
239
- return true;
240
- if (value === 'false' || value === '0')
241
- return false;
242
- return undefined;
243
- }
244
- function envToString(value) {
245
- return value ? value.trim() : undefined;
246
- }
package/lib/context.js DELETED
@@ -1,226 +0,0 @@
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 { logUnhandledError } from './utils/log.js';
18
- import { Tab } from './tab.js';
19
- import { outputFile } from './config.js';
20
- const testDebug = debug('pw:mcp:test');
21
- export class Context {
22
- tools;
23
- config;
24
- sessionLog;
25
- options;
26
- _browserContextPromise;
27
- _browserContextFactory;
28
- _tabs = [];
29
- _currentTab;
30
- _clientInfo;
31
- static _allContexts = new Set();
32
- _closeBrowserContextPromise;
33
- _runningToolName;
34
- _abortController = new AbortController();
35
- constructor(options) {
36
- this.tools = options.tools;
37
- this.config = options.config;
38
- this.sessionLog = options.sessionLog;
39
- this.options = options;
40
- this._browserContextFactory = options.browserContextFactory;
41
- this._clientInfo = options.clientInfo;
42
- testDebug('create context');
43
- Context._allContexts.add(this);
44
- }
45
- static async disposeAll() {
46
- await Promise.all([...Context._allContexts].map(context => context.dispose()));
47
- }
48
- tabs() {
49
- return this._tabs;
50
- }
51
- currentTab() {
52
- return this._currentTab;
53
- }
54
- currentTabOrDie() {
55
- if (!this._currentTab)
56
- throw new Error('No open pages available. Use the "browser_navigate" tool to navigate to a page first.');
57
- return this._currentTab;
58
- }
59
- async newTab() {
60
- const { browserContext } = await this._ensureBrowserContext();
61
- const page = await browserContext.newPage();
62
- this._currentTab = this._tabs.find(t => t.page === page);
63
- return this._currentTab;
64
- }
65
- async selectTab(index) {
66
- const tab = this._tabs[index];
67
- if (!tab)
68
- throw new Error(`Tab ${index} not found`);
69
- await tab.page.bringToFront();
70
- this._currentTab = tab;
71
- return tab;
72
- }
73
- async ensureTab() {
74
- const { browserContext } = await this._ensureBrowserContext();
75
- if (!this._currentTab)
76
- await browserContext.newPage();
77
- return this._currentTab;
78
- }
79
- async closeTab(index) {
80
- const tab = index === undefined ? this._currentTab : this._tabs[index];
81
- if (!tab)
82
- throw new Error(`Tab ${index} not found`);
83
- const url = tab.page.url();
84
- await tab.page.close();
85
- return url;
86
- }
87
- async outputFile(name) {
88
- return outputFile(this.config, this._clientInfo.rootPath, name);
89
- }
90
- _onPageCreated(page) {
91
- const tab = new Tab(this, page, tab => this._onPageClosed(tab));
92
- this._tabs.push(tab);
93
- if (!this._currentTab)
94
- this._currentTab = tab;
95
- }
96
- _onPageClosed(tab) {
97
- const index = this._tabs.indexOf(tab);
98
- if (index === -1)
99
- return;
100
- this._tabs.splice(index, 1);
101
- if (this._currentTab === tab)
102
- this._currentTab = this._tabs[Math.min(index, this._tabs.length - 1)];
103
- if (!this._tabs.length)
104
- void this.closeBrowserContext();
105
- }
106
- async closeBrowserContext() {
107
- if (!this._closeBrowserContextPromise)
108
- this._closeBrowserContextPromise = this._closeBrowserContextImpl().catch(logUnhandledError);
109
- await this._closeBrowserContextPromise;
110
- this._closeBrowserContextPromise = undefined;
111
- }
112
- isRunningTool() {
113
- return this._runningToolName !== undefined;
114
- }
115
- setRunningTool(name) {
116
- this._runningToolName = name;
117
- }
118
- async _closeBrowserContextImpl() {
119
- if (!this._browserContextPromise)
120
- return;
121
- testDebug('close context');
122
- const promise = this._browserContextPromise;
123
- this._browserContextPromise = undefined;
124
- await promise.then(async ({ browserContext, close }) => {
125
- if (this.config.saveTrace)
126
- await browserContext.tracing.stop();
127
- await close();
128
- });
129
- }
130
- async dispose() {
131
- this._abortController.abort('MCP context disposed');
132
- await this.closeBrowserContext();
133
- Context._allContexts.delete(this);
134
- }
135
- async _setupRequestInterception(context) {
136
- if (this.config.network?.allowedOrigins?.length) {
137
- await context.route('**', route => route.abort('blockedbyclient'));
138
- for (const origin of this.config.network.allowedOrigins)
139
- await context.route(`*://${origin}/**`, route => route.continue());
140
- }
141
- if (this.config.network?.blockedOrigins?.length) {
142
- for (const origin of this.config.network.blockedOrigins)
143
- await context.route(`*://${origin}/**`, route => route.abort('blockedbyclient'));
144
- }
145
- }
146
- _ensureBrowserContext() {
147
- if (!this._browserContextPromise) {
148
- this._browserContextPromise = this._setupBrowserContext();
149
- this._browserContextPromise.catch(() => {
150
- this._browserContextPromise = undefined;
151
- });
152
- }
153
- return this._browserContextPromise;
154
- }
155
- async _setupBrowserContext() {
156
- if (this._closeBrowserContextPromise)
157
- throw new Error('Another browser context is being closed.');
158
- // TODO: move to the browser context factory to make it based on isolation mode.
159
- const result = await this._browserContextFactory.createContext(this._clientInfo, this._abortController.signal, this._runningToolName);
160
- const { browserContext } = result;
161
- await this._setupRequestInterception(browserContext);
162
- if (this.sessionLog)
163
- await InputRecorder.create(this, browserContext);
164
- for (const page of browserContext.pages())
165
- this._onPageCreated(page);
166
- browserContext.on('page', page => this._onPageCreated(page));
167
- if (this.config.saveTrace) {
168
- await browserContext.tracing.start({
169
- name: 'trace',
170
- screenshots: false,
171
- snapshots: true,
172
- sources: false,
173
- });
174
- }
175
- return result;
176
- }
177
- }
178
- export class InputRecorder {
179
- _context;
180
- _browserContext;
181
- constructor(context, browserContext) {
182
- this._context = context;
183
- this._browserContext = browserContext;
184
- }
185
- static async create(context, browserContext) {
186
- const recorder = new InputRecorder(context, browserContext);
187
- await recorder._initialize();
188
- return recorder;
189
- }
190
- async _initialize() {
191
- const sessionLog = this._context.sessionLog;
192
- await this._browserContext._enableRecorder({
193
- mode: 'recording',
194
- recorderMode: 'api',
195
- }, {
196
- actionAdded: (page, data, code) => {
197
- if (this._context.isRunningTool())
198
- return;
199
- const tab = Tab.forPage(page);
200
- if (tab)
201
- sessionLog.logUserAction(data.action, tab, code, false);
202
- },
203
- actionUpdated: (page, data, code) => {
204
- if (this._context.isRunningTool())
205
- return;
206
- const tab = Tab.forPage(page);
207
- if (tab)
208
- sessionLog.logUserAction(data.action, tab, code, true);
209
- },
210
- signalAdded: (page, data) => {
211
- if (this._context.isRunningTool())
212
- return;
213
- if (data.signal.name !== 'navigation')
214
- return;
215
- const tab = Tab.forPage(page);
216
- const navigateAction = {
217
- name: 'navigate',
218
- url: data.signal.url,
219
- signals: [],
220
- };
221
- if (tab)
222
- sessionLog.logUserAction(navigateAction, tab, `await page.goto('${data.signal.url}');`, false);
223
- },
224
- });
225
- }
226
- }