@wordbricks/playwright-mcp 0.1.20 → 0.1.23
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/cli-wrapper.js +15 -14
- package/cli.js +1 -1
- package/config.d.ts +11 -6
- package/index.d.ts +7 -5
- package/index.js +1 -1
- package/package.json +34 -57
- package/LICENSE +0 -202
- package/lib/browserContextFactory.js +0 -326
- package/lib/browserServerBackend.js +0 -84
- package/lib/config.js +0 -286
- package/lib/context.js +0 -309
- package/lib/extension/cdpRelay.js +0 -346
- package/lib/extension/extensionContextFactory.js +0 -56
- package/lib/frameworkPatterns.js +0 -35
- package/lib/hooks/antiBotDetectionHook.js +0 -171
- package/lib/hooks/core.js +0 -144
- package/lib/hooks/eventConsumer.js +0 -52
- package/lib/hooks/events.js +0 -42
- package/lib/hooks/formatToolCallEvent.js +0 -16
- package/lib/hooks/frameworkStateHook.js +0 -182
- package/lib/hooks/grouping.js +0 -72
- package/lib/hooks/jsonLdDetectionHook.js +0 -175
- package/lib/hooks/networkFilters.js +0 -82
- package/lib/hooks/networkSetup.js +0 -59
- package/lib/hooks/networkTrackingHook.js +0 -67
- package/lib/hooks/pageHeightHook.js +0 -75
- package/lib/hooks/registry.js +0 -42
- package/lib/hooks/requireTabHook.js +0 -26
- package/lib/hooks/schema.js +0 -89
- package/lib/hooks/waitHook.js +0 -33
- package/lib/index.js +0 -39
- package/lib/mcp/inProcessTransport.js +0 -72
- package/lib/mcp/proxyBackend.js +0 -115
- package/lib/mcp/server.js +0 -86
- package/lib/mcp/tool.js +0 -38
- package/lib/mcp/transport.js +0 -181
- package/lib/playwrightTransformer.js +0 -497
- package/lib/program.js +0 -110
- package/lib/response.js +0 -186
- package/lib/sessionLog.js +0 -121
- package/lib/tab.js +0 -249
- package/lib/tools/common.js +0 -55
- package/lib/tools/console.js +0 -33
- package/lib/tools/dialogs.js +0 -47
- package/lib/tools/evaluate.js +0 -53
- package/lib/tools/extractFrameworkState.js +0 -214
- package/lib/tools/files.js +0 -45
- package/lib/tools/form.js +0 -57
- package/lib/tools/getSnapshot.js +0 -37
- package/lib/tools/getVisibleHtml.js +0 -52
- package/lib/tools/install.js +0 -51
- package/lib/tools/keyboard.js +0 -78
- package/lib/tools/mouse.js +0 -99
- package/lib/tools/navigate.js +0 -70
- package/lib/tools/network.js +0 -123
- package/lib/tools/networkDetail.js +0 -229
- package/lib/tools/networkSearch/bodySearch.js +0 -147
- package/lib/tools/networkSearch/grouping.js +0 -28
- package/lib/tools/networkSearch/helpers.js +0 -32
- package/lib/tools/networkSearch/searchHtml.js +0 -67
- package/lib/tools/networkSearch/types.js +0 -1
- package/lib/tools/networkSearch/urlSearch.js +0 -82
- package/lib/tools/networkSearch.js +0 -268
- package/lib/tools/pdf.js +0 -40
- package/lib/tools/repl.js +0 -402
- package/lib/tools/screenshot.js +0 -79
- package/lib/tools/scroll.js +0 -126
- package/lib/tools/snapshot.js +0 -144
- package/lib/tools/tabs.js +0 -59
- package/lib/tools/tool.js +0 -33
- package/lib/tools/utils.js +0 -74
- package/lib/tools/wait.js +0 -55
- package/lib/tools.js +0 -67
- package/lib/utils/adBlockFilter.js +0 -87
- package/lib/utils/codegen.js +0 -51
- package/lib/utils/extensionPath.js +0 -10
- package/lib/utils/fileUtils.js +0 -36
- package/lib/utils/graphql.js +0 -258
- package/lib/utils/guid.js +0 -22
- package/lib/utils/httpServer.js +0 -39
- package/lib/utils/log.js +0 -21
- package/lib/utils/manualPromise.js +0 -111
- package/lib/utils/networkFormat.js +0 -12
- package/lib/utils/package.js +0 -20
- package/lib/utils/result.js +0 -2
- package/lib/utils/sanitizeHtml.js +0 -98
- package/lib/utils/truncate.js +0 -103
- package/lib/utils/withTimeout.js +0 -7
- package/src/index.ts +0 -50
|
@@ -1,326 +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 net from 'net';
|
|
18
|
-
import path from 'path';
|
|
19
|
-
import * as playwright from 'playwright-core';
|
|
20
|
-
import ms from 'ms';
|
|
21
|
-
// @ts-ignore
|
|
22
|
-
import { registryDirectory } from 'playwright-core/lib/server/registry/index';
|
|
23
|
-
// @ts-ignore
|
|
24
|
-
import { startTraceViewerServer } from 'playwright-core/lib/server';
|
|
25
|
-
import { logUnhandledError, testDebug } from './utils/log.js';
|
|
26
|
-
import { createHash } from './utils/guid.js';
|
|
27
|
-
import { outputFile } from './config.js';
|
|
28
|
-
const TIMEOUT_STR = '30m';
|
|
29
|
-
async function applyInitScript(browserContext, config) {
|
|
30
|
-
if (config.browser.initScript) {
|
|
31
|
-
const scriptContent = await fs.promises.readFile(config.browser.initScript, 'utf8');
|
|
32
|
-
await browserContext.addInitScript(scriptContent);
|
|
33
|
-
}
|
|
34
|
-
}
|
|
35
|
-
async function hidePlaywrightMarkers(browserContext) {
|
|
36
|
-
await browserContext.addInitScript(() => {
|
|
37
|
-
// Delete the property if it exists
|
|
38
|
-
delete window.__pwInitScripts;
|
|
39
|
-
// Redefine `Object.getOwnPropertyNames`
|
|
40
|
-
const originalGetOwnPropertyNames = Object.getOwnPropertyNames;
|
|
41
|
-
Object.getOwnPropertyNames = (obj) => {
|
|
42
|
-
const props = originalGetOwnPropertyNames(obj);
|
|
43
|
-
return props.filter((prop) => prop !== '__pwInitScripts');
|
|
44
|
-
};
|
|
45
|
-
// Use a Proxy to handle access to `window`
|
|
46
|
-
const windowHandler = {
|
|
47
|
-
get(target, prop) {
|
|
48
|
-
if (prop === '__pwInitScripts')
|
|
49
|
-
return undefined; // Hide the property
|
|
50
|
-
return Reflect.get(target, prop);
|
|
51
|
-
},
|
|
52
|
-
has(target, prop) {
|
|
53
|
-
if (prop === '__pwInitScripts')
|
|
54
|
-
return false; // Prevent detection via "in" operator
|
|
55
|
-
return Reflect.has(target, prop);
|
|
56
|
-
},
|
|
57
|
-
};
|
|
58
|
-
const proxiedWindow = new Proxy(window, windowHandler);
|
|
59
|
-
Object.defineProperty(globalThis, 'window', {
|
|
60
|
-
value: proxiedWindow,
|
|
61
|
-
configurable: false,
|
|
62
|
-
writable: false,
|
|
63
|
-
});
|
|
64
|
-
});
|
|
65
|
-
}
|
|
66
|
-
export function contextFactory(config) {
|
|
67
|
-
if (config.browser.remoteEndpoint)
|
|
68
|
-
return new RemoteContextFactory(config);
|
|
69
|
-
if (config.browser.cdpEndpoint)
|
|
70
|
-
return new CdpContextFactory(config);
|
|
71
|
-
if (config.browser.isolated)
|
|
72
|
-
return new IsolatedContextFactory(config);
|
|
73
|
-
return new PersistentContextFactory(config);
|
|
74
|
-
}
|
|
75
|
-
class BaseContextFactory {
|
|
76
|
-
name;
|
|
77
|
-
_autoCloseTimer;
|
|
78
|
-
description;
|
|
79
|
-
config;
|
|
80
|
-
_browserPromise;
|
|
81
|
-
constructor(name, description, config) {
|
|
82
|
-
this.name = name;
|
|
83
|
-
this.description = description;
|
|
84
|
-
this.config = config;
|
|
85
|
-
}
|
|
86
|
-
async _obtainBrowser(clientInfo) {
|
|
87
|
-
if (this._browserPromise)
|
|
88
|
-
return this._browserPromise;
|
|
89
|
-
testDebug(`obtain browser (${this.name})`);
|
|
90
|
-
this._browserPromise = this._doObtainBrowser(clientInfo);
|
|
91
|
-
void this._browserPromise.then(browser => {
|
|
92
|
-
browser.on('disconnected', () => {
|
|
93
|
-
this._browserPromise = undefined;
|
|
94
|
-
this._clearAutoCloseTimer();
|
|
95
|
-
});
|
|
96
|
-
// Start auto-close timer
|
|
97
|
-
this._startAutoCloseTimer(browser);
|
|
98
|
-
}).catch(() => {
|
|
99
|
-
this._browserPromise = undefined;
|
|
100
|
-
this._clearAutoCloseTimer();
|
|
101
|
-
});
|
|
102
|
-
return this._browserPromise;
|
|
103
|
-
}
|
|
104
|
-
_startAutoCloseTimer(browser) {
|
|
105
|
-
this._clearAutoCloseTimer();
|
|
106
|
-
testDebug(`schedule auto-close in ${TIMEOUT_STR} (${this.name})`);
|
|
107
|
-
this._autoCloseTimer = setTimeout(async () => {
|
|
108
|
-
testDebug(`auto-closing browser after ${TIMEOUT_STR} (${this.name})`);
|
|
109
|
-
try {
|
|
110
|
-
await browser.close();
|
|
111
|
-
this._browserPromise = undefined;
|
|
112
|
-
testDebug(`auto-close complete (${this.name})`);
|
|
113
|
-
}
|
|
114
|
-
catch (error) {
|
|
115
|
-
testDebug(`error during auto-close: ${error}`);
|
|
116
|
-
}
|
|
117
|
-
}, ms(TIMEOUT_STR));
|
|
118
|
-
}
|
|
119
|
-
_clearAutoCloseTimer() {
|
|
120
|
-
if (this._autoCloseTimer) {
|
|
121
|
-
testDebug(`cancel auto-close timer (${this.name})`);
|
|
122
|
-
clearTimeout(this._autoCloseTimer);
|
|
123
|
-
this._autoCloseTimer = undefined;
|
|
124
|
-
}
|
|
125
|
-
}
|
|
126
|
-
async _doObtainBrowser(clientInfo) {
|
|
127
|
-
throw new Error('Not implemented');
|
|
128
|
-
}
|
|
129
|
-
async createContext(clientInfo) {
|
|
130
|
-
testDebug(`create browser context (${this.name})`);
|
|
131
|
-
const browser = await this._obtainBrowser(clientInfo);
|
|
132
|
-
const browserContext = await this._doCreateContext(browser);
|
|
133
|
-
return { browserContext, close: () => this._closeBrowserContext(browserContext, browser) };
|
|
134
|
-
}
|
|
135
|
-
async _doCreateContext(browser) {
|
|
136
|
-
throw new Error('Not implemented');
|
|
137
|
-
}
|
|
138
|
-
async _closeBrowserContext(browserContext, browser) {
|
|
139
|
-
testDebug(`close browser context (${this.name})`);
|
|
140
|
-
if (browser.contexts().length === 1) {
|
|
141
|
-
this._browserPromise = undefined;
|
|
142
|
-
this._clearAutoCloseTimer();
|
|
143
|
-
}
|
|
144
|
-
await browserContext.close().catch(logUnhandledError);
|
|
145
|
-
if (browser.contexts().length === 0) {
|
|
146
|
-
testDebug(`close browser (${this.name})`);
|
|
147
|
-
this._clearAutoCloseTimer();
|
|
148
|
-
await browser.close().catch(logUnhandledError);
|
|
149
|
-
}
|
|
150
|
-
}
|
|
151
|
-
}
|
|
152
|
-
class IsolatedContextFactory extends BaseContextFactory {
|
|
153
|
-
constructor(config) {
|
|
154
|
-
super('isolated', 'Create a new isolated browser context', config);
|
|
155
|
-
}
|
|
156
|
-
async _doObtainBrowser(clientInfo) {
|
|
157
|
-
await injectCdpPort(this.config.browser);
|
|
158
|
-
const browserType = playwright[this.config.browser.browserName];
|
|
159
|
-
return browserType.launch({
|
|
160
|
-
tracesDir: await startTraceServer(this.config, clientInfo.rootPath),
|
|
161
|
-
...this.config.browser.launchOptions,
|
|
162
|
-
handleSIGINT: false,
|
|
163
|
-
handleSIGTERM: false,
|
|
164
|
-
args: this.config.browser.launchOptions?.args || [],
|
|
165
|
-
}).catch(error => {
|
|
166
|
-
if (error.message.includes('Executable doesn\'t exist'))
|
|
167
|
-
throw new Error(`Browser specified in your config is not installed. Either install it (likely) or change the config.`);
|
|
168
|
-
throw error;
|
|
169
|
-
});
|
|
170
|
-
}
|
|
171
|
-
async _doCreateContext(browser) {
|
|
172
|
-
const browserContext = await browser.newContext(this.config.browser.contextOptions);
|
|
173
|
-
await applyInitScript(browserContext, this.config);
|
|
174
|
-
await hidePlaywrightMarkers(browserContext);
|
|
175
|
-
return browserContext;
|
|
176
|
-
}
|
|
177
|
-
}
|
|
178
|
-
class CdpContextFactory extends BaseContextFactory {
|
|
179
|
-
constructor(config) {
|
|
180
|
-
super('cdp', 'Connect to a browser over CDP', config);
|
|
181
|
-
}
|
|
182
|
-
async _doObtainBrowser() {
|
|
183
|
-
return playwright.chromium.connectOverCDP(this.config.browser.cdpEndpoint);
|
|
184
|
-
}
|
|
185
|
-
async _doCreateContext(browser) {
|
|
186
|
-
const browserContext = this.config.browser.isolated ? await browser.newContext() : browser.contexts()[0];
|
|
187
|
-
await applyInitScript(browserContext, this.config);
|
|
188
|
-
await hidePlaywrightMarkers(browserContext);
|
|
189
|
-
return browserContext;
|
|
190
|
-
}
|
|
191
|
-
}
|
|
192
|
-
class RemoteContextFactory extends BaseContextFactory {
|
|
193
|
-
constructor(config) {
|
|
194
|
-
super('remote', 'Connect to a browser using a remote endpoint', config);
|
|
195
|
-
}
|
|
196
|
-
async _doObtainBrowser() {
|
|
197
|
-
const url = new URL(this.config.browser.remoteEndpoint);
|
|
198
|
-
url.searchParams.set('browser', this.config.browser.browserName);
|
|
199
|
-
if (this.config.browser.launchOptions)
|
|
200
|
-
url.searchParams.set('launch-options', JSON.stringify(this.config.browser.launchOptions));
|
|
201
|
-
return playwright[this.config.browser.browserName].connect(String(url));
|
|
202
|
-
}
|
|
203
|
-
async _doCreateContext(browser) {
|
|
204
|
-
const browserContext = await browser.newContext();
|
|
205
|
-
await applyInitScript(browserContext, this.config);
|
|
206
|
-
await hidePlaywrightMarkers(browserContext);
|
|
207
|
-
return browserContext;
|
|
208
|
-
}
|
|
209
|
-
}
|
|
210
|
-
class PersistentContextFactory {
|
|
211
|
-
config;
|
|
212
|
-
name = 'persistent';
|
|
213
|
-
description = 'Create a new persistent browser context';
|
|
214
|
-
_userDataDirs = new Set();
|
|
215
|
-
_autoCloseTimer;
|
|
216
|
-
constructor(config) {
|
|
217
|
-
this.config = config;
|
|
218
|
-
}
|
|
219
|
-
async createContext(clientInfo) {
|
|
220
|
-
await injectCdpPort(this.config.browser);
|
|
221
|
-
testDebug('create browser context (persistent)');
|
|
222
|
-
const userDataDir = this.config.browser.userDataDir ?? await this._createUserDataDir(clientInfo.rootPath);
|
|
223
|
-
const tracesDir = await startTraceServer(this.config, clientInfo.rootPath);
|
|
224
|
-
this._userDataDirs.add(userDataDir);
|
|
225
|
-
testDebug('lock user data dir', userDataDir);
|
|
226
|
-
const browserType = playwright[this.config.browser.browserName];
|
|
227
|
-
for (let i = 0; i < 5; i++) {
|
|
228
|
-
try {
|
|
229
|
-
const browserContext = await browserType.launchPersistentContext(userDataDir, {
|
|
230
|
-
tracesDir,
|
|
231
|
-
...this.config.browser.launchOptions,
|
|
232
|
-
...this.config.browser.contextOptions,
|
|
233
|
-
handleSIGINT: false,
|
|
234
|
-
handleSIGTERM: false,
|
|
235
|
-
args: this.config.browser.launchOptions?.args || [],
|
|
236
|
-
});
|
|
237
|
-
await applyInitScript(browserContext, this.config);
|
|
238
|
-
await hidePlaywrightMarkers(browserContext);
|
|
239
|
-
// Start auto-close timer
|
|
240
|
-
this._startAutoCloseTimer(browserContext);
|
|
241
|
-
const close = () => this._closeBrowserContext(browserContext, userDataDir);
|
|
242
|
-
return { browserContext, close };
|
|
243
|
-
}
|
|
244
|
-
catch (error) {
|
|
245
|
-
if (error.message.includes('Executable doesn\'t exist'))
|
|
246
|
-
throw new Error(`Browser specified in your config is not installed. Either install it (likely) or change the config.`);
|
|
247
|
-
if (error.message.includes('ProcessSingleton') || error.message.includes('Invalid URL')) {
|
|
248
|
-
// User data directory is already in use, try again.
|
|
249
|
-
await new Promise(resolve => setTimeout(resolve, 1000));
|
|
250
|
-
continue;
|
|
251
|
-
}
|
|
252
|
-
throw error;
|
|
253
|
-
}
|
|
254
|
-
}
|
|
255
|
-
throw new Error(`Browser is already in use for ${userDataDir}, use --isolated to run multiple instances of the same browser`);
|
|
256
|
-
}
|
|
257
|
-
_startAutoCloseTimer(browserContext) {
|
|
258
|
-
this._clearAutoCloseTimer();
|
|
259
|
-
testDebug(`schedule auto-close in ${TIMEOUT_STR} (persistent)`);
|
|
260
|
-
this._autoCloseTimer = setTimeout(async () => {
|
|
261
|
-
testDebug(`auto-closing browser after ${TIMEOUT_STR} (persistent)`);
|
|
262
|
-
try {
|
|
263
|
-
await browserContext.close();
|
|
264
|
-
testDebug(`auto-close complete (persistent)`);
|
|
265
|
-
}
|
|
266
|
-
catch (error) {
|
|
267
|
-
testDebug(`error during auto-close: ${error}`);
|
|
268
|
-
}
|
|
269
|
-
}, ms(TIMEOUT_STR));
|
|
270
|
-
}
|
|
271
|
-
_clearAutoCloseTimer() {
|
|
272
|
-
if (this._autoCloseTimer) {
|
|
273
|
-
testDebug(`cancel auto-close timer (persistent)`);
|
|
274
|
-
clearTimeout(this._autoCloseTimer);
|
|
275
|
-
this._autoCloseTimer = undefined;
|
|
276
|
-
}
|
|
277
|
-
}
|
|
278
|
-
async _closeBrowserContext(browserContext, userDataDir) {
|
|
279
|
-
testDebug('close browser context (persistent)');
|
|
280
|
-
testDebug('release user data dir', userDataDir);
|
|
281
|
-
this._clearAutoCloseTimer();
|
|
282
|
-
await browserContext.close().catch(() => { });
|
|
283
|
-
this._userDataDirs.delete(userDataDir);
|
|
284
|
-
testDebug('close browser context complete (persistent)');
|
|
285
|
-
}
|
|
286
|
-
async _createUserDataDir(rootPath) {
|
|
287
|
-
const dir = process.env.PWMCP_PROFILES_DIR_FOR_TEST ?? registryDirectory;
|
|
288
|
-
const browserToken = this.config.browser.launchOptions?.channel ?? this.config.browser?.browserName;
|
|
289
|
-
// Hesitant putting hundreds of files into the user's workspace, so using it for hashing instead.
|
|
290
|
-
const rootPathToken = rootPath ? `-${createHash(rootPath)}` : '';
|
|
291
|
-
const result = path.join(dir, `mcp-${browserToken}${rootPathToken}`);
|
|
292
|
-
await fs.promises.mkdir(result, { recursive: true });
|
|
293
|
-
return result;
|
|
294
|
-
}
|
|
295
|
-
}
|
|
296
|
-
async function injectCdpPort(browserConfig) {
|
|
297
|
-
const isBunRuntime = 'bun' in process.versions;
|
|
298
|
-
if (isBunRuntime)
|
|
299
|
-
return;
|
|
300
|
-
if (browserConfig.browserName !== 'chromium')
|
|
301
|
-
return;
|
|
302
|
-
const launchOptions = browserConfig.launchOptions || {};
|
|
303
|
-
launchOptions.cdpPort = await findFreePort();
|
|
304
|
-
browserConfig.launchOptions = launchOptions;
|
|
305
|
-
}
|
|
306
|
-
async function findFreePort() {
|
|
307
|
-
return new Promise((resolve, reject) => {
|
|
308
|
-
const server = net.createServer();
|
|
309
|
-
server.listen(0, () => {
|
|
310
|
-
const { port } = server.address();
|
|
311
|
-
server.close(() => resolve(port));
|
|
312
|
-
});
|
|
313
|
-
server.on('error', reject);
|
|
314
|
-
});
|
|
315
|
-
}
|
|
316
|
-
async function startTraceServer(config, rootPath) {
|
|
317
|
-
if (!config.saveTrace)
|
|
318
|
-
return undefined;
|
|
319
|
-
const tracesDir = await outputFile(config, rootPath, `traces-${Date.now()}`);
|
|
320
|
-
const server = await startTraceViewerServer();
|
|
321
|
-
const urlPrefix = server.urlPrefix('human-readable');
|
|
322
|
-
const url = urlPrefix + '/trace/index.html?trace=' + tracesDir + '/trace.json';
|
|
323
|
-
// eslint-disable-next-line no-console
|
|
324
|
-
console.error('\nTrace viewer listening on ' + url);
|
|
325
|
-
return tracesDir;
|
|
326
|
-
}
|
|
@@ -1,84 +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 { fileURLToPath } from 'url';
|
|
17
|
-
import { Context } from './context.js';
|
|
18
|
-
import { logUnhandledError } from './utils/log.js';
|
|
19
|
-
import { Response } from './response.js';
|
|
20
|
-
import { SessionLog } from './sessionLog.js';
|
|
21
|
-
import { filteredTools } from './tools.js';
|
|
22
|
-
import { packageJSON } from './utils/package.js';
|
|
23
|
-
import { toMcpTool } from './mcp/tool.js';
|
|
24
|
-
export class BrowserServerBackend {
|
|
25
|
-
name = 'Playwright';
|
|
26
|
-
version = packageJSON.version;
|
|
27
|
-
_tools;
|
|
28
|
-
_context;
|
|
29
|
-
_sessionLog;
|
|
30
|
-
_config;
|
|
31
|
-
_browserContextFactory;
|
|
32
|
-
constructor(config, factory) {
|
|
33
|
-
this._config = config;
|
|
34
|
-
this._browserContextFactory = factory;
|
|
35
|
-
this._tools = filteredTools(config);
|
|
36
|
-
}
|
|
37
|
-
async initialize(server) {
|
|
38
|
-
const capabilities = server.getClientCapabilities();
|
|
39
|
-
let rootPath;
|
|
40
|
-
if (capabilities?.roots) {
|
|
41
|
-
const { roots } = await server.listRoots();
|
|
42
|
-
const firstRootUri = roots[0]?.uri;
|
|
43
|
-
const url = firstRootUri ? new URL(firstRootUri) : undefined;
|
|
44
|
-
rootPath = url ? fileURLToPath(url) : undefined;
|
|
45
|
-
}
|
|
46
|
-
this._sessionLog = this._config.saveSession ? await SessionLog.create(this._config, rootPath) : undefined;
|
|
47
|
-
this._context = new Context({
|
|
48
|
-
tools: this._tools,
|
|
49
|
-
config: this._config,
|
|
50
|
-
browserContextFactory: this._browserContextFactory,
|
|
51
|
-
sessionLog: this._sessionLog,
|
|
52
|
-
clientInfo: { ...server.getClientVersion(), rootPath },
|
|
53
|
-
});
|
|
54
|
-
if (this._config.browser.app)
|
|
55
|
-
await this._context.ensureTab();
|
|
56
|
-
}
|
|
57
|
-
async listTools() {
|
|
58
|
-
return this._tools.map(tool => toMcpTool(tool.schema));
|
|
59
|
-
}
|
|
60
|
-
async callTool(name, rawArguments) {
|
|
61
|
-
const context = this._context;
|
|
62
|
-
const tool = context.tools.find(tool => tool.schema.name === name);
|
|
63
|
-
if (!tool)
|
|
64
|
-
throw new Error(`Tool "${name}" not found`);
|
|
65
|
-
const parsedArguments = tool.schema.inputSchema.parse(rawArguments || {});
|
|
66
|
-
const response = new Response(context, name, parsedArguments);
|
|
67
|
-
context.setRunningTool(true);
|
|
68
|
-
try {
|
|
69
|
-
await tool.handle(context, parsedArguments, response);
|
|
70
|
-
await response.finish();
|
|
71
|
-
this._sessionLog?.logResponse(response);
|
|
72
|
-
}
|
|
73
|
-
catch (error) {
|
|
74
|
-
response.addError(String(error));
|
|
75
|
-
}
|
|
76
|
-
finally {
|
|
77
|
-
context.setRunningTool(false);
|
|
78
|
-
}
|
|
79
|
-
return response.serialize();
|
|
80
|
-
}
|
|
81
|
-
serverClosed() {
|
|
82
|
-
void this._context?.dispose().catch(logUnhandledError);
|
|
83
|
-
}
|
|
84
|
-
}
|
package/lib/config.js
DELETED
|
@@ -1,286 +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-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
|
-
};
|
|
82
|
-
// --no-sandbox was passed, disable the sandbox
|
|
83
|
-
if (cliOptions.sandbox === false)
|
|
84
|
-
launchOptions.chromiumSandbox = false;
|
|
85
|
-
// Add default Chrome args to avoid automation detection
|
|
86
|
-
launchOptions.args = launchOptions.args || [];
|
|
87
|
-
launchOptions.args.push('--disable-infobars');
|
|
88
|
-
// --app was passed, add app mode argument
|
|
89
|
-
if (cliOptions.app) {
|
|
90
|
-
launchOptions.args = launchOptions.args || [];
|
|
91
|
-
launchOptions.args.push(`--app=${cliOptions.app}`);
|
|
92
|
-
}
|
|
93
|
-
// --window-position was passed, add window position argument
|
|
94
|
-
if (cliOptions.windowPosition) {
|
|
95
|
-
try {
|
|
96
|
-
const [x, y] = cliOptions.windowPosition.split(',').map(n => +n);
|
|
97
|
-
if (isNaN(x) || isNaN(y))
|
|
98
|
-
throw new Error('bad values');
|
|
99
|
-
launchOptions.args = launchOptions.args || [];
|
|
100
|
-
launchOptions.args.push(`--window-position=${x},${y}`);
|
|
101
|
-
}
|
|
102
|
-
catch (e) {
|
|
103
|
-
throw new Error('Invalid window position format: use "x,y", for example --window-position="100,200"');
|
|
104
|
-
}
|
|
105
|
-
}
|
|
106
|
-
// --window-size was passed, add window size argument
|
|
107
|
-
if (cliOptions.windowSize) {
|
|
108
|
-
try {
|
|
109
|
-
const [width, height] = cliOptions.windowSize.split(',').map(n => +n);
|
|
110
|
-
if (isNaN(width) || isNaN(height))
|
|
111
|
-
throw new Error('bad values');
|
|
112
|
-
launchOptions.args = launchOptions.args || [];
|
|
113
|
-
launchOptions.args.push(`--window-size=${width},${height}`);
|
|
114
|
-
}
|
|
115
|
-
catch (e) {
|
|
116
|
-
throw new Error('Invalid window size format: use "width,height", for example --window-size="1280,720"');
|
|
117
|
-
}
|
|
118
|
-
}
|
|
119
|
-
if (cliOptions.proxyServer) {
|
|
120
|
-
launchOptions.proxy = {
|
|
121
|
-
server: cliOptions.proxyServer
|
|
122
|
-
};
|
|
123
|
-
if (cliOptions.proxyBypass)
|
|
124
|
-
launchOptions.proxy.bypass = cliOptions.proxyBypass;
|
|
125
|
-
}
|
|
126
|
-
if (cliOptions.device && cliOptions.cdpEndpoint)
|
|
127
|
-
throw new Error('Device emulation is not supported with cdpEndpoint.');
|
|
128
|
-
// Context options
|
|
129
|
-
const contextOptions = cliOptions.device ? devices[cliOptions.device] : {};
|
|
130
|
-
if (cliOptions.storageState)
|
|
131
|
-
contextOptions.storageState = cliOptions.storageState;
|
|
132
|
-
if (cliOptions.userAgent)
|
|
133
|
-
contextOptions.userAgent = cliOptions.userAgent;
|
|
134
|
-
if (cliOptions.viewportSize) {
|
|
135
|
-
try {
|
|
136
|
-
const [width, height] = cliOptions.viewportSize.split(',').map(n => +n);
|
|
137
|
-
if (isNaN(width) || isNaN(height))
|
|
138
|
-
throw new Error('bad values');
|
|
139
|
-
contextOptions.viewport = { width, height };
|
|
140
|
-
}
|
|
141
|
-
catch (e) {
|
|
142
|
-
throw new Error('Invalid viewport size format: use "width,height", for example --viewport-size="800,600"');
|
|
143
|
-
}
|
|
144
|
-
}
|
|
145
|
-
if (cliOptions.ignoreHttpsErrors)
|
|
146
|
-
contextOptions.ignoreHTTPSErrors = true;
|
|
147
|
-
if (cliOptions.blockServiceWorkers)
|
|
148
|
-
contextOptions.serviceWorkers = 'block';
|
|
149
|
-
const result = {
|
|
150
|
-
browser: {
|
|
151
|
-
browserName,
|
|
152
|
-
isolated: cliOptions.isolated,
|
|
153
|
-
userDataDir: cliOptions.userDataDir,
|
|
154
|
-
launchOptions,
|
|
155
|
-
contextOptions,
|
|
156
|
-
cdpEndpoint: cliOptions.cdpEndpoint,
|
|
157
|
-
initScript: cliOptions.initScript,
|
|
158
|
-
app: cliOptions.app,
|
|
159
|
-
},
|
|
160
|
-
server: {
|
|
161
|
-
port: cliOptions.port,
|
|
162
|
-
host: cliOptions.host,
|
|
163
|
-
},
|
|
164
|
-
capabilities: cliOptions.caps,
|
|
165
|
-
network: {
|
|
166
|
-
allowedOrigins: cliOptions.allowedOrigins,
|
|
167
|
-
blockedOrigins: cliOptions.blockedOrigins,
|
|
168
|
-
},
|
|
169
|
-
saveSession: cliOptions.saveSession,
|
|
170
|
-
saveTrace: cliOptions.saveTrace,
|
|
171
|
-
outputDir: cliOptions.outputDir,
|
|
172
|
-
imageResponses: cliOptions.imageResponses,
|
|
173
|
-
};
|
|
174
|
-
return result;
|
|
175
|
-
}
|
|
176
|
-
function configFromEnv() {
|
|
177
|
-
const options = {};
|
|
178
|
-
options.allowedOrigins = semicolonSeparatedList(process.env.PLAYWRIGHT_MCP_ALLOWED_ORIGINS);
|
|
179
|
-
options.app = envToString(process.env.PLAYWRIGHT_MCP_APP);
|
|
180
|
-
options.blockedOrigins = semicolonSeparatedList(process.env.PLAYWRIGHT_MCP_BLOCKED_ORIGINS);
|
|
181
|
-
options.blockServiceWorkers = envToBoolean(process.env.PLAYWRIGHT_MCP_BLOCK_SERVICE_WORKERS);
|
|
182
|
-
options.browser = envToString(process.env.PLAYWRIGHT_MCP_BROWSER);
|
|
183
|
-
options.caps = commaSeparatedList(process.env.PLAYWRIGHT_MCP_CAPS);
|
|
184
|
-
options.cdpEndpoint = envToString(process.env.PLAYWRIGHT_MCP_CDP_ENDPOINT);
|
|
185
|
-
options.config = envToString(process.env.PLAYWRIGHT_MCP_CONFIG);
|
|
186
|
-
options.device = envToString(process.env.PLAYWRIGHT_MCP_DEVICE);
|
|
187
|
-
options.executablePath = envToString(process.env.PLAYWRIGHT_MCP_EXECUTABLE_PATH);
|
|
188
|
-
options.headless = envToBoolean(process.env.PLAYWRIGHT_MCP_HEADLESS);
|
|
189
|
-
options.host = envToString(process.env.PLAYWRIGHT_MCP_HOST);
|
|
190
|
-
options.ignoreHttpsErrors = envToBoolean(process.env.PLAYWRIGHT_MCP_IGNORE_HTTPS_ERRORS);
|
|
191
|
-
options.initScript = envToString(process.env.PLAYWRIGHT_MCP_INIT_SCRIPT);
|
|
192
|
-
options.isolated = envToBoolean(process.env.PLAYWRIGHT_MCP_ISOLATED);
|
|
193
|
-
if (process.env.PLAYWRIGHT_MCP_IMAGE_RESPONSES === 'omit')
|
|
194
|
-
options.imageResponses = 'omit';
|
|
195
|
-
options.sandbox = envToBoolean(process.env.PLAYWRIGHT_MCP_SANDBOX);
|
|
196
|
-
options.outputDir = envToString(process.env.PLAYWRIGHT_MCP_OUTPUT_DIR);
|
|
197
|
-
options.port = envToNumber(process.env.PLAYWRIGHT_MCP_PORT);
|
|
198
|
-
options.proxyBypass = envToString(process.env.PLAYWRIGHT_MCP_PROXY_BYPASS);
|
|
199
|
-
options.proxyServer = envToString(process.env.PLAYWRIGHT_MCP_PROXY_SERVER);
|
|
200
|
-
options.saveTrace = envToBoolean(process.env.PLAYWRIGHT_MCP_SAVE_TRACE);
|
|
201
|
-
options.storageState = envToString(process.env.PLAYWRIGHT_MCP_STORAGE_STATE);
|
|
202
|
-
options.userAgent = envToString(process.env.PLAYWRIGHT_MCP_USER_AGENT);
|
|
203
|
-
options.userDataDir = envToString(process.env.PLAYWRIGHT_MCP_USER_DATA_DIR);
|
|
204
|
-
options.viewportSize = envToString(process.env.PLAYWRIGHT_MCP_VIEWPORT_SIZE);
|
|
205
|
-
options.windowPosition = envToString(process.env.PLAYWRIGHT_MCP_WINDOW_POSITION);
|
|
206
|
-
options.windowSize = envToString(process.env.PLAYWRIGHT_MCP_WINDOW_SIZE);
|
|
207
|
-
return configFromCLIOptions(options);
|
|
208
|
-
}
|
|
209
|
-
async function loadConfig(configFile) {
|
|
210
|
-
if (!configFile)
|
|
211
|
-
return {};
|
|
212
|
-
try {
|
|
213
|
-
return JSON.parse(await fs.promises.readFile(configFile, 'utf8'));
|
|
214
|
-
}
|
|
215
|
-
catch (error) {
|
|
216
|
-
throw new Error(`Failed to load config file: ${configFile}, ${error}`);
|
|
217
|
-
}
|
|
218
|
-
}
|
|
219
|
-
export async function outputFile(config, rootPath, name) {
|
|
220
|
-
const outputDir = config.outputDir
|
|
221
|
-
?? (rootPath ? path.join(rootPath, '.playwright-mcp') : undefined)
|
|
222
|
-
?? path.join(os.tmpdir(), 'playwright-mcp-output', sanitizeForFilePath(new Date().toISOString()));
|
|
223
|
-
await fs.promises.mkdir(outputDir, { recursive: true });
|
|
224
|
-
const fileName = sanitizeForFilePath(name);
|
|
225
|
-
return path.join(outputDir, fileName);
|
|
226
|
-
}
|
|
227
|
-
function pickDefined(obj) {
|
|
228
|
-
return Object.fromEntries(Object.entries(obj ?? {}).filter(([_, v]) => v !== undefined));
|
|
229
|
-
}
|
|
230
|
-
function mergeConfig(base, overrides) {
|
|
231
|
-
const browser = {
|
|
232
|
-
...pickDefined(base.browser),
|
|
233
|
-
...pickDefined(overrides.browser),
|
|
234
|
-
browserName: overrides.browser?.browserName ?? base.browser?.browserName ?? 'chromium',
|
|
235
|
-
isolated: overrides.browser?.isolated ?? base.browser?.isolated ?? false,
|
|
236
|
-
launchOptions: {
|
|
237
|
-
...pickDefined(base.browser?.launchOptions),
|
|
238
|
-
...pickDefined(overrides.browser?.launchOptions),
|
|
239
|
-
...{ assistantMode: true },
|
|
240
|
-
},
|
|
241
|
-
contextOptions: {
|
|
242
|
-
...pickDefined(base.browser?.contextOptions),
|
|
243
|
-
...pickDefined(overrides.browser?.contextOptions),
|
|
244
|
-
},
|
|
245
|
-
};
|
|
246
|
-
if (browser.browserName !== 'chromium' && browser.launchOptions)
|
|
247
|
-
delete browser.launchOptions.channel;
|
|
248
|
-
return {
|
|
249
|
-
...pickDefined(base),
|
|
250
|
-
...pickDefined(overrides),
|
|
251
|
-
browser,
|
|
252
|
-
network: {
|
|
253
|
-
...pickDefined(base.network),
|
|
254
|
-
...pickDefined(overrides.network),
|
|
255
|
-
},
|
|
256
|
-
server: {
|
|
257
|
-
...pickDefined(base.server),
|
|
258
|
-
...pickDefined(overrides.server),
|
|
259
|
-
},
|
|
260
|
-
};
|
|
261
|
-
}
|
|
262
|
-
export function semicolonSeparatedList(value) {
|
|
263
|
-
if (!value)
|
|
264
|
-
return undefined;
|
|
265
|
-
return value.split(';').map(v => v.trim());
|
|
266
|
-
}
|
|
267
|
-
export function commaSeparatedList(value) {
|
|
268
|
-
if (!value)
|
|
269
|
-
return undefined;
|
|
270
|
-
return value.split(',').map(v => v.trim());
|
|
271
|
-
}
|
|
272
|
-
function envToNumber(value) {
|
|
273
|
-
if (!value)
|
|
274
|
-
return undefined;
|
|
275
|
-
return +value;
|
|
276
|
-
}
|
|
277
|
-
function envToBoolean(value) {
|
|
278
|
-
if (value === 'true' || value === '1')
|
|
279
|
-
return true;
|
|
280
|
-
if (value === 'false' || value === '0')
|
|
281
|
-
return false;
|
|
282
|
-
return undefined;
|
|
283
|
-
}
|
|
284
|
-
function envToString(value) {
|
|
285
|
-
return value ? value.trim() : undefined;
|
|
286
|
-
}
|