@wordbricks/playwright-mcp 0.1.25 → 0.1.27

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 +616 -0
  2. package/lib/browserServerBackend.js +86 -0
  3. package/lib/config.js +302 -0
  4. package/lib/context.js +320 -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
@@ -0,0 +1,86 @@
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 { toMcpTool } from "./mcp/tool.js";
19
+ import { Response } from "./response.js";
20
+ import { SessionLog } from "./sessionLog.js";
21
+ import { filteredTools } from "./tools.js";
22
+ import { logUnhandledError } from "./utils/log.js";
23
+ import { packageJSON } from "./utils/package.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
47
+ ? await SessionLog.create(this._config, rootPath)
48
+ : undefined;
49
+ this._context = new Context({
50
+ tools: this._tools,
51
+ config: this._config,
52
+ browserContextFactory: this._browserContextFactory,
53
+ sessionLog: this._sessionLog,
54
+ clientInfo: { ...server.getClientVersion(), rootPath },
55
+ });
56
+ if (this._config.browser.app)
57
+ await this._context.ensureTab();
58
+ }
59
+ async listTools() {
60
+ return this._tools.map((tool) => toMcpTool(tool.schema));
61
+ }
62
+ async callTool(name, rawArguments) {
63
+ const context = this._context;
64
+ const tool = context.tools.find((tool) => tool.schema.name === name);
65
+ if (!tool)
66
+ throw new Error(`Tool "${name}" not found`);
67
+ const parsedArguments = tool.schema.inputSchema.parse(rawArguments || {});
68
+ const response = new Response(context, name, parsedArguments);
69
+ context.setRunningTool(true);
70
+ try {
71
+ await tool.handle(context, parsedArguments, response);
72
+ await response.finish();
73
+ this._sessionLog?.logResponse(response);
74
+ }
75
+ catch (error) {
76
+ response.addError(String(error));
77
+ }
78
+ finally {
79
+ context.setRunningTool(false);
80
+ }
81
+ return response.serialize();
82
+ }
83
+ serverClosed() {
84
+ void this._context?.dispose().catch(logUnhandledError);
85
+ }
86
+ }
package/lib/config.js ADDED
@@ -0,0 +1,302 @@
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 Cast/Media Router and local network discovery
97
+ "--media-router=0", "--disable-cast", "--disable-cast-streaming-hw-encoding",
98
+ // Disable various Chrome features (Translate, PasswordManager, Autofill, Sync, MediaRouter, Cast)
99
+ "--disable-features=Translate,PasswordManager,PasswordManagerEnabled,PasswordManagerOnboarding,AutofillServerCommunication,CredentialManagerOnboarding,MediaRouter,GlobalMediaControls,CastMediaRouteProvider,DialMediaRouteProvider,CastAllowAllIPs,EnableCastDiscovery,LocalNetworkAccessChecks", "--disable-sync",
100
+ // Disable password manager via experimental options
101
+ "--enable-features=DisablePasswordManager");
102
+ // --app was passed, add app mode argument
103
+ if (cliOptions.app) {
104
+ launchOptions.args = launchOptions.args || [];
105
+ launchOptions.args.push(`--app=${cliOptions.app}`);
106
+ }
107
+ // --window-position was passed, add window position argument
108
+ if (cliOptions.windowPosition) {
109
+ try {
110
+ const [x, y] = cliOptions.windowPosition.split(",").map((n) => +n);
111
+ if (isNaN(x) || isNaN(y))
112
+ throw new Error("bad values");
113
+ launchOptions.args = launchOptions.args || [];
114
+ launchOptions.args.push(`--window-position=${x},${y}`);
115
+ }
116
+ catch (e) {
117
+ throw new Error('Invalid window position format: use "x,y", for example --window-position="100,200"');
118
+ }
119
+ }
120
+ // --window-size was passed, add window size argument
121
+ if (cliOptions.windowSize) {
122
+ try {
123
+ const [width, height] = cliOptions.windowSize.split(",").map((n) => +n);
124
+ if (isNaN(width) || isNaN(height))
125
+ throw new Error("bad values");
126
+ launchOptions.args = launchOptions.args || [];
127
+ launchOptions.args.push(`--window-size=${width},${height}`);
128
+ }
129
+ catch (e) {
130
+ throw new Error('Invalid window size format: use "width,height", for example --window-size="1280,720"');
131
+ }
132
+ }
133
+ if (cliOptions.proxyServer) {
134
+ launchOptions.proxy = {
135
+ server: cliOptions.proxyServer,
136
+ };
137
+ if (cliOptions.proxyBypass)
138
+ launchOptions.proxy.bypass = cliOptions.proxyBypass;
139
+ }
140
+ if (cliOptions.device && cliOptions.cdpEndpoint)
141
+ throw new Error("Device emulation is not supported with cdpEndpoint.");
142
+ // Context options
143
+ const contextOptions = cliOptions.device
144
+ ? devices[cliOptions.device]
145
+ : {};
146
+ if (cliOptions.storageState)
147
+ contextOptions.storageState = cliOptions.storageState;
148
+ if (cliOptions.userAgent)
149
+ contextOptions.userAgent = cliOptions.userAgent;
150
+ if (cliOptions.viewportSize) {
151
+ try {
152
+ const [width, height] = cliOptions.viewportSize.split(",").map((n) => +n);
153
+ if (isNaN(width) || isNaN(height))
154
+ throw new Error("bad values");
155
+ contextOptions.viewport = { width, height };
156
+ }
157
+ catch (e) {
158
+ throw new Error('Invalid viewport size format: use "width,height", for example --viewport-size="800,600"');
159
+ }
160
+ }
161
+ if (cliOptions.ignoreHttpsErrors)
162
+ contextOptions.ignoreHTTPSErrors = true;
163
+ if (cliOptions.blockServiceWorkers)
164
+ contextOptions.serviceWorkers = "block";
165
+ const result = {
166
+ browser: {
167
+ browserName,
168
+ isolated: cliOptions.isolated,
169
+ userDataDir: cliOptions.userDataDir,
170
+ launchOptions,
171
+ contextOptions,
172
+ cdpEndpoint: cliOptions.cdpEndpoint,
173
+ initScript: cliOptions.initScript,
174
+ app: cliOptions.app,
175
+ },
176
+ server: {
177
+ port: cliOptions.port,
178
+ host: cliOptions.host,
179
+ },
180
+ capabilities: cliOptions.caps,
181
+ network: {
182
+ allowedOrigins: cliOptions.allowedOrigins,
183
+ blockedOrigins: cliOptions.blockedOrigins,
184
+ },
185
+ saveSession: cliOptions.saveSession,
186
+ saveTrace: cliOptions.saveTrace,
187
+ outputDir: cliOptions.outputDir,
188
+ imageResponses: cliOptions.imageResponses,
189
+ };
190
+ return result;
191
+ }
192
+ function configFromEnv() {
193
+ const options = {};
194
+ options.allowedOrigins = semicolonSeparatedList(process.env.PLAYWRIGHT_MCP_ALLOWED_ORIGINS);
195
+ options.app = envToString(process.env.PLAYWRIGHT_MCP_APP);
196
+ options.blockedOrigins = semicolonSeparatedList(process.env.PLAYWRIGHT_MCP_BLOCKED_ORIGINS);
197
+ options.blockServiceWorkers = envToBoolean(process.env.PLAYWRIGHT_MCP_BLOCK_SERVICE_WORKERS);
198
+ options.browser = envToString(process.env.PLAYWRIGHT_MCP_BROWSER);
199
+ options.caps = commaSeparatedList(process.env.PLAYWRIGHT_MCP_CAPS);
200
+ options.cdpEndpoint = envToString(process.env.PLAYWRIGHT_MCP_CDP_ENDPOINT);
201
+ options.config = envToString(process.env.PLAYWRIGHT_MCP_CONFIG);
202
+ options.device = envToString(process.env.PLAYWRIGHT_MCP_DEVICE);
203
+ options.executablePath = envToString(process.env.PLAYWRIGHT_MCP_EXECUTABLE_PATH);
204
+ options.headless = envToBoolean(process.env.PLAYWRIGHT_MCP_HEADLESS);
205
+ options.host = envToString(process.env.PLAYWRIGHT_MCP_HOST);
206
+ options.ignoreHttpsErrors = envToBoolean(process.env.PLAYWRIGHT_MCP_IGNORE_HTTPS_ERRORS);
207
+ options.initScript = envToString(process.env.PLAYWRIGHT_MCP_INIT_SCRIPT);
208
+ options.isolated = envToBoolean(process.env.PLAYWRIGHT_MCP_ISOLATED);
209
+ if (process.env.PLAYWRIGHT_MCP_IMAGE_RESPONSES === "omit")
210
+ options.imageResponses = "omit";
211
+ options.sandbox = envToBoolean(process.env.PLAYWRIGHT_MCP_SANDBOX);
212
+ options.outputDir = envToString(process.env.PLAYWRIGHT_MCP_OUTPUT_DIR);
213
+ options.port = envToNumber(process.env.PLAYWRIGHT_MCP_PORT);
214
+ options.proxyBypass = envToString(process.env.PLAYWRIGHT_MCP_PROXY_BYPASS);
215
+ options.proxyServer = envToString(process.env.PLAYWRIGHT_MCP_PROXY_SERVER);
216
+ options.saveTrace = envToBoolean(process.env.PLAYWRIGHT_MCP_SAVE_TRACE);
217
+ options.storageState = envToString(process.env.PLAYWRIGHT_MCP_STORAGE_STATE);
218
+ options.userAgent = envToString(process.env.PLAYWRIGHT_MCP_USER_AGENT);
219
+ options.userDataDir = envToString(process.env.PLAYWRIGHT_MCP_USER_DATA_DIR);
220
+ options.viewportSize = envToString(process.env.PLAYWRIGHT_MCP_VIEWPORT_SIZE);
221
+ options.windowPosition = envToString(process.env.PLAYWRIGHT_MCP_WINDOW_POSITION);
222
+ options.windowSize = envToString(process.env.PLAYWRIGHT_MCP_WINDOW_SIZE);
223
+ return configFromCLIOptions(options);
224
+ }
225
+ async function loadConfig(configFile) {
226
+ if (!configFile)
227
+ return {};
228
+ try {
229
+ return JSON.parse(await fs.promises.readFile(configFile, "utf8"));
230
+ }
231
+ catch (error) {
232
+ throw new Error(`Failed to load config file: ${configFile}, ${error}`);
233
+ }
234
+ }
235
+ export async function outputFile(config, rootPath, name) {
236
+ const outputDir = config.outputDir ??
237
+ (rootPath ? path.join(rootPath, ".playwright-mcp") : undefined) ??
238
+ path.join(os.tmpdir(), "playwright-mcp-output", sanitizeForFilePath(new Date().toISOString()));
239
+ await fs.promises.mkdir(outputDir, { recursive: true });
240
+ const fileName = sanitizeForFilePath(name);
241
+ return path.join(outputDir, fileName);
242
+ }
243
+ function pickDefined(obj) {
244
+ return Object.fromEntries(Object.entries(obj ?? {}).filter(([_, v]) => v !== undefined));
245
+ }
246
+ function mergeConfig(base, overrides) {
247
+ const browser = {
248
+ ...pickDefined(base.browser),
249
+ ...pickDefined(overrides.browser),
250
+ browserName: overrides.browser?.browserName ?? base.browser?.browserName ?? "chromium",
251
+ isolated: overrides.browser?.isolated ?? base.browser?.isolated ?? false,
252
+ launchOptions: {
253
+ ...pickDefined(base.browser?.launchOptions),
254
+ ...pickDefined(overrides.browser?.launchOptions),
255
+ ...{ assistantMode: true },
256
+ },
257
+ contextOptions: {
258
+ ...pickDefined(base.browser?.contextOptions),
259
+ ...pickDefined(overrides.browser?.contextOptions),
260
+ },
261
+ };
262
+ if (browser.browserName !== "chromium" && browser.launchOptions)
263
+ delete browser.launchOptions.channel;
264
+ return {
265
+ ...pickDefined(base),
266
+ ...pickDefined(overrides),
267
+ browser,
268
+ network: {
269
+ ...pickDefined(base.network),
270
+ ...pickDefined(overrides.network),
271
+ },
272
+ server: {
273
+ ...pickDefined(base.server),
274
+ ...pickDefined(overrides.server),
275
+ },
276
+ };
277
+ }
278
+ export function semicolonSeparatedList(value) {
279
+ if (!value)
280
+ return undefined;
281
+ return value.split(";").map((v) => v.trim());
282
+ }
283
+ export function commaSeparatedList(value) {
284
+ if (!value)
285
+ return undefined;
286
+ return value.split(",").map((v) => v.trim());
287
+ }
288
+ function envToNumber(value) {
289
+ if (!value)
290
+ return undefined;
291
+ return +value;
292
+ }
293
+ function envToBoolean(value) {
294
+ if (value === "true" || value === "1")
295
+ return true;
296
+ if (value === "false" || value === "0")
297
+ return false;
298
+ return undefined;
299
+ }
300
+ function envToString(value) {
301
+ return value ? value.trim() : undefined;
302
+ }