@wordbricks/playwright-mcp 0.1.3

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 (95) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +624 -0
  3. package/cli-wrapper.js +47 -0
  4. package/cli.js +18 -0
  5. package/config.d.ts +119 -0
  6. package/index.d.ts +23 -0
  7. package/index.js +19 -0
  8. package/lib/browserContextFactory.js +289 -0
  9. package/lib/browserServerBackend.js +82 -0
  10. package/lib/config.js +246 -0
  11. package/lib/context.js +236 -0
  12. package/lib/extension/cdpRelay.js +346 -0
  13. package/lib/extension/extensionContextFactory.js +56 -0
  14. package/lib/frameworkPatterns.js +35 -0
  15. package/lib/hooks/core.js +144 -0
  16. package/lib/hooks/eventConsumer.js +39 -0
  17. package/lib/hooks/events.js +42 -0
  18. package/lib/hooks/formatToolCallEvent.js +16 -0
  19. package/lib/hooks/frameworkStateHook.js +182 -0
  20. package/lib/hooks/grouping.js +72 -0
  21. package/lib/hooks/jsonLdDetectionHook.js +175 -0
  22. package/lib/hooks/networkFilters.js +74 -0
  23. package/lib/hooks/networkSetup.js +56 -0
  24. package/lib/hooks/networkTrackingHook.js +55 -0
  25. package/lib/hooks/pageHeightHook.js +75 -0
  26. package/lib/hooks/registry.js +39 -0
  27. package/lib/hooks/requireTabHook.js +26 -0
  28. package/lib/hooks/schema.js +75 -0
  29. package/lib/hooks/waitHook.js +33 -0
  30. package/lib/index.js +39 -0
  31. package/lib/loop/loop.js +69 -0
  32. package/lib/loop/loopClaude.js +152 -0
  33. package/lib/loop/loopOpenAI.js +141 -0
  34. package/lib/loop/main.js +60 -0
  35. package/lib/loopTools/context.js +66 -0
  36. package/lib/loopTools/main.js +51 -0
  37. package/lib/loopTools/perform.js +32 -0
  38. package/lib/loopTools/snapshot.js +29 -0
  39. package/lib/loopTools/tool.js +18 -0
  40. package/lib/mcp/inProcessTransport.js +72 -0
  41. package/lib/mcp/proxyBackend.js +115 -0
  42. package/lib/mcp/server.js +86 -0
  43. package/lib/mcp/tool.js +29 -0
  44. package/lib/mcp/transport.js +181 -0
  45. package/lib/playwrightTransformer.js +497 -0
  46. package/lib/program.js +111 -0
  47. package/lib/response.js +186 -0
  48. package/lib/sessionLog.js +121 -0
  49. package/lib/tab.js +249 -0
  50. package/lib/tools/common.js +55 -0
  51. package/lib/tools/console.js +33 -0
  52. package/lib/tools/dialogs.js +47 -0
  53. package/lib/tools/evaluate.js +53 -0
  54. package/lib/tools/extractFrameworkState.js +214 -0
  55. package/lib/tools/files.js +44 -0
  56. package/lib/tools/getSnapshot.js +37 -0
  57. package/lib/tools/getVisibleHtml.js +52 -0
  58. package/lib/tools/install.js +53 -0
  59. package/lib/tools/keyboard.js +78 -0
  60. package/lib/tools/mouse.js +99 -0
  61. package/lib/tools/navigate.js +70 -0
  62. package/lib/tools/network.js +123 -0
  63. package/lib/tools/networkDetail.js +231 -0
  64. package/lib/tools/networkSearch/bodySearch.js +141 -0
  65. package/lib/tools/networkSearch/grouping.js +28 -0
  66. package/lib/tools/networkSearch/helpers.js +32 -0
  67. package/lib/tools/networkSearch/searchHtml.js +65 -0
  68. package/lib/tools/networkSearch/types.js +1 -0
  69. package/lib/tools/networkSearch/urlSearch.js +82 -0
  70. package/lib/tools/networkSearch.js +168 -0
  71. package/lib/tools/pdf.js +40 -0
  72. package/lib/tools/repl.js +402 -0
  73. package/lib/tools/screenshot.js +79 -0
  74. package/lib/tools/scroll.js +126 -0
  75. package/lib/tools/snapshot.js +139 -0
  76. package/lib/tools/tabs.js +87 -0
  77. package/lib/tools/tool.js +33 -0
  78. package/lib/tools/utils.js +74 -0
  79. package/lib/tools/wait.js +55 -0
  80. package/lib/tools.js +67 -0
  81. package/lib/utils/codegen.js +49 -0
  82. package/lib/utils/extensionPath.js +6 -0
  83. package/lib/utils/fileUtils.js +36 -0
  84. package/lib/utils/graphql.js +258 -0
  85. package/lib/utils/guid.js +22 -0
  86. package/lib/utils/httpServer.js +39 -0
  87. package/lib/utils/log.js +21 -0
  88. package/lib/utils/manualPromise.js +111 -0
  89. package/lib/utils/networkFormat.js +12 -0
  90. package/lib/utils/package.js +20 -0
  91. package/lib/utils/result.js +2 -0
  92. package/lib/utils/sanitizeHtml.js +98 -0
  93. package/lib/utils/truncate.js +103 -0
  94. package/lib/utils/withTimeout.js +7 -0
  95. package/package.json +100 -0
package/config.d.ts ADDED
@@ -0,0 +1,119 @@
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
+
17
+ import type * as playwright from 'playwright';
18
+
19
+ export type ToolCapability = 'core' | 'core-tabs' | 'core-install' | 'vision' | 'pdf';
20
+
21
+ export type Config = {
22
+ /**
23
+ * The browser to use.
24
+ */
25
+ browser?: {
26
+ /**
27
+ * The type of browser to use.
28
+ */
29
+ browserName?: 'chromium' | 'firefox' | 'webkit';
30
+
31
+ /**
32
+ * Keep the browser profile in memory, do not save it to disk.
33
+ */
34
+ isolated?: boolean;
35
+
36
+ /**
37
+ * Path to a user data directory for browser profile persistence.
38
+ * Temporary directory is created by default.
39
+ */
40
+ userDataDir?: string;
41
+
42
+ /**
43
+ * Launch options passed to
44
+ * @see https://playwright.dev/docs/api/class-browsertype#browser-type-launch-persistent-context
45
+ *
46
+ * This is useful for settings options like `channel`, `headless`, `executablePath`, etc.
47
+ */
48
+ launchOptions?: playwright.LaunchOptions;
49
+
50
+ /**
51
+ * Context options for the browser context.
52
+ *
53
+ * This is useful for settings options like `viewport`.
54
+ */
55
+ contextOptions?: playwright.BrowserContextOptions;
56
+
57
+ /**
58
+ * Chrome DevTools Protocol endpoint to connect to an existing browser instance in case of Chromium family browsers.
59
+ */
60
+ cdpEndpoint?: string;
61
+
62
+ /**
63
+ * Remote endpoint to connect to an existing Playwright server.
64
+ */
65
+ remoteEndpoint?: string;
66
+ },
67
+
68
+ server?: {
69
+ /**
70
+ * The port to listen on for SSE or MCP transport.
71
+ */
72
+ port?: number;
73
+
74
+ /**
75
+ * The host to bind the server to. Default is localhost. Use 0.0.0.0 to bind to all interfaces.
76
+ */
77
+ host?: string;
78
+ },
79
+
80
+ /**
81
+ * List of enabled tool capabilities. Possible values:
82
+ * - 'core': Core browser automation features.
83
+ * - 'pdf': PDF generation and manipulation.
84
+ * - 'vision': Coordinate-based interactions.
85
+ */
86
+ capabilities?: ToolCapability[];
87
+
88
+ /**
89
+ * Whether to save the Playwright session into the output directory.
90
+ */
91
+ saveSession?: boolean;
92
+
93
+ /**
94
+ * Whether to save the Playwright trace of the session into the output directory.
95
+ */
96
+ saveTrace?: boolean;
97
+
98
+ /**
99
+ * The directory to save output files.
100
+ */
101
+ outputDir?: string;
102
+
103
+ network?: {
104
+ /**
105
+ * List of origins to allow the browser to request. Default is to allow all. Origins matching both `allowedOrigins` and `blockedOrigins` will be blocked.
106
+ */
107
+ allowedOrigins?: string[];
108
+
109
+ /**
110
+ * List of origins to block the browser to request. Origins matching both `allowedOrigins` and `blockedOrigins` will be blocked.
111
+ */
112
+ blockedOrigins?: string[];
113
+ };
114
+
115
+ /**
116
+ * Whether to send image responses to the client. Can be "allow", "omit", or "auto". Defaults to "auto", which sends images if the client can display them.
117
+ */
118
+ imageResponses?: 'allow' | 'omit';
119
+ };
package/index.d.ts ADDED
@@ -0,0 +1,23 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Copyright (c) Microsoft Corporation.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+
18
+ import type { Server } from '@modelcontextprotocol/sdk/server/index.js';
19
+ import type { Config } from './config.js';
20
+ import type { BrowserContext } from 'playwright';
21
+
22
+ export declare function createConnection(config?: Config, contextGetter?: () => Promise<BrowserContext>): Promise<Server>;
23
+ export {};
package/index.js ADDED
@@ -0,0 +1,19 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Copyright (c) Microsoft Corporation.
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+
18
+ import { createConnection } from './lib/index.js';
19
+ export { createConnection };
@@ -0,0 +1,289 @@
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
+ 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
+ import { extensionPath } from './utils/extensionPath.js';
29
+ const TIMEOUT_STR = '30m';
30
+ export function contextFactory(config) {
31
+ if (config.browser.remoteEndpoint)
32
+ return new RemoteContextFactory(config);
33
+ if (config.browser.cdpEndpoint)
34
+ return new CdpContextFactory(config);
35
+ if (config.browser.isolated)
36
+ return new IsolatedContextFactory(config);
37
+ return new PersistentContextFactory(config);
38
+ }
39
+ class BaseContextFactory {
40
+ name;
41
+ _autoCloseTimer;
42
+ description;
43
+ config;
44
+ _browserPromise;
45
+ constructor(name, description, config) {
46
+ this.name = name;
47
+ this.description = description;
48
+ this.config = config;
49
+ }
50
+ async _obtainBrowser(clientInfo) {
51
+ if (this._browserPromise)
52
+ return this._browserPromise;
53
+ testDebug(`obtain browser (${this.name})`);
54
+ this._browserPromise = this._doObtainBrowser(clientInfo);
55
+ void this._browserPromise.then(browser => {
56
+ browser.on('disconnected', () => {
57
+ this._browserPromise = undefined;
58
+ this._clearAutoCloseTimer();
59
+ });
60
+ // Start auto-close timer
61
+ this._startAutoCloseTimer(browser);
62
+ }).catch(() => {
63
+ this._browserPromise = undefined;
64
+ this._clearAutoCloseTimer();
65
+ });
66
+ return this._browserPromise;
67
+ }
68
+ _startAutoCloseTimer(browser) {
69
+ this._clearAutoCloseTimer();
70
+ testDebug(`schedule auto-close in ${TIMEOUT_STR} (${this.name})`);
71
+ this._autoCloseTimer = setTimeout(async () => {
72
+ testDebug(`auto-closing browser after ${TIMEOUT_STR} (${this.name})`);
73
+ try {
74
+ await browser.close();
75
+ this._browserPromise = undefined;
76
+ testDebug(`auto-close complete (${this.name})`);
77
+ }
78
+ catch (error) {
79
+ testDebug(`error during auto-close: ${error}`);
80
+ }
81
+ }, ms(TIMEOUT_STR));
82
+ }
83
+ _clearAutoCloseTimer() {
84
+ if (this._autoCloseTimer) {
85
+ testDebug(`cancel auto-close timer (${this.name})`);
86
+ clearTimeout(this._autoCloseTimer);
87
+ this._autoCloseTimer = undefined;
88
+ }
89
+ }
90
+ async _doObtainBrowser(clientInfo) {
91
+ throw new Error('Not implemented');
92
+ }
93
+ async createContext(clientInfo) {
94
+ testDebug(`create browser context (${this.name})`);
95
+ const browser = await this._obtainBrowser(clientInfo);
96
+ const browserContext = await this._doCreateContext(browser);
97
+ return { browserContext, close: () => this._closeBrowserContext(browserContext, browser) };
98
+ }
99
+ async _doCreateContext(browser) {
100
+ throw new Error('Not implemented');
101
+ }
102
+ async _closeBrowserContext(browserContext, browser) {
103
+ testDebug(`close browser context (${this.name})`);
104
+ if (browser.contexts().length === 1) {
105
+ this._browserPromise = undefined;
106
+ this._clearAutoCloseTimer();
107
+ }
108
+ await browserContext.close().catch(logUnhandledError);
109
+ if (browser.contexts().length === 0) {
110
+ testDebug(`close browser (${this.name})`);
111
+ this._clearAutoCloseTimer();
112
+ await browser.close().catch(logUnhandledError);
113
+ }
114
+ }
115
+ }
116
+ class IsolatedContextFactory extends BaseContextFactory {
117
+ constructor(config) {
118
+ super('isolated', 'Create a new isolated browser context', config);
119
+ }
120
+ async _doObtainBrowser(clientInfo) {
121
+ await injectCdpPort(this.config.browser);
122
+ const browserType = playwright[this.config.browser.browserName];
123
+ const extensionArgs = [
124
+ `--disable-extensions-except=${extensionPath}`,
125
+ `--load-extension=${extensionPath}`,
126
+ ];
127
+ const args = [...(this.config.browser.launchOptions?.args || []), ...extensionArgs];
128
+ return browserType.launch({
129
+ tracesDir: await startTraceServer(this.config, clientInfo.rootPath),
130
+ ...this.config.browser.launchOptions,
131
+ handleSIGINT: false,
132
+ handleSIGTERM: false,
133
+ args,
134
+ }).catch(error => {
135
+ if (error.message.includes('Executable doesn\'t exist'))
136
+ throw new Error(`Browser specified in your config is not installed. Either install it (likely) or change the config.`);
137
+ throw error;
138
+ });
139
+ }
140
+ async _doCreateContext(browser) {
141
+ return browser.newContext(this.config.browser.contextOptions);
142
+ }
143
+ }
144
+ class CdpContextFactory extends BaseContextFactory {
145
+ constructor(config) {
146
+ super('cdp', 'Connect to a browser over CDP', config);
147
+ }
148
+ async _doObtainBrowser() {
149
+ return playwright.chromium.connectOverCDP(this.config.browser.cdpEndpoint);
150
+ }
151
+ async _doCreateContext(browser) {
152
+ return this.config.browser.isolated ? await browser.newContext() : browser.contexts()[0];
153
+ }
154
+ }
155
+ class RemoteContextFactory extends BaseContextFactory {
156
+ constructor(config) {
157
+ super('remote', 'Connect to a browser using a remote endpoint', config);
158
+ }
159
+ async _doObtainBrowser() {
160
+ const url = new URL(this.config.browser.remoteEndpoint);
161
+ url.searchParams.set('browser', this.config.browser.browserName);
162
+ if (this.config.browser.launchOptions)
163
+ url.searchParams.set('launch-options', JSON.stringify(this.config.browser.launchOptions));
164
+ return playwright[this.config.browser.browserName].connect(String(url));
165
+ }
166
+ async _doCreateContext(browser) {
167
+ return browser.newContext();
168
+ }
169
+ }
170
+ class PersistentContextFactory {
171
+ config;
172
+ name = 'persistent';
173
+ description = 'Create a new persistent browser context';
174
+ _userDataDirs = new Set();
175
+ _autoCloseTimer;
176
+ constructor(config) {
177
+ this.config = config;
178
+ }
179
+ async createContext(clientInfo) {
180
+ await injectCdpPort(this.config.browser);
181
+ testDebug('create browser context (persistent)');
182
+ const userDataDir = this.config.browser.userDataDir ?? await this._createUserDataDir(clientInfo.rootPath);
183
+ const tracesDir = await startTraceServer(this.config, clientInfo.rootPath);
184
+ this._userDataDirs.add(userDataDir);
185
+ testDebug('lock user data dir', userDataDir);
186
+ const browserType = playwright[this.config.browser.browserName];
187
+ for (let i = 0; i < 5; i++) {
188
+ try {
189
+ const extensionArgs = [
190
+ `--disable-extensions-except=${extensionPath}`,
191
+ `--load-extension=${extensionPath}`,
192
+ ];
193
+ const args = [...(this.config.browser.launchOptions?.args || []), ...extensionArgs];
194
+ const browserContext = await browserType.launchPersistentContext(userDataDir, {
195
+ tracesDir,
196
+ ...this.config.browser.launchOptions,
197
+ ...this.config.browser.contextOptions,
198
+ handleSIGINT: false,
199
+ handleSIGTERM: false,
200
+ args,
201
+ });
202
+ // Start auto-close timer
203
+ this._startAutoCloseTimer(browserContext);
204
+ const close = () => this._closeBrowserContext(browserContext, userDataDir);
205
+ return { browserContext, close };
206
+ }
207
+ catch (error) {
208
+ if (error.message.includes('Executable doesn\'t exist'))
209
+ throw new Error(`Browser specified in your config is not installed. Either install it (likely) or change the config.`);
210
+ if (error.message.includes('ProcessSingleton') || error.message.includes('Invalid URL')) {
211
+ // User data directory is already in use, try again.
212
+ await new Promise(resolve => setTimeout(resolve, 1000));
213
+ continue;
214
+ }
215
+ throw error;
216
+ }
217
+ }
218
+ throw new Error(`Browser is already in use for ${userDataDir}, use --isolated to run multiple instances of the same browser`);
219
+ }
220
+ _startAutoCloseTimer(browserContext) {
221
+ this._clearAutoCloseTimer();
222
+ testDebug(`schedule auto-close in ${TIMEOUT_STR} (persistent)`);
223
+ this._autoCloseTimer = setTimeout(async () => {
224
+ testDebug(`auto-closing browser after ${TIMEOUT_STR} (persistent)`);
225
+ try {
226
+ await browserContext.close();
227
+ testDebug(`auto-close complete (persistent)`);
228
+ }
229
+ catch (error) {
230
+ testDebug(`error during auto-close: ${error}`);
231
+ }
232
+ }, ms(TIMEOUT_STR));
233
+ }
234
+ _clearAutoCloseTimer() {
235
+ if (this._autoCloseTimer) {
236
+ testDebug(`cancel auto-close timer (persistent)`);
237
+ clearTimeout(this._autoCloseTimer);
238
+ this._autoCloseTimer = undefined;
239
+ }
240
+ }
241
+ async _closeBrowserContext(browserContext, userDataDir) {
242
+ testDebug('close browser context (persistent)');
243
+ testDebug('release user data dir', userDataDir);
244
+ this._clearAutoCloseTimer();
245
+ await browserContext.close().catch(() => { });
246
+ this._userDataDirs.delete(userDataDir);
247
+ testDebug('close browser context complete (persistent)');
248
+ }
249
+ async _createUserDataDir(rootPath) {
250
+ const dir = process.env.PWMCP_PROFILES_DIR_FOR_TEST ?? registryDirectory;
251
+ const browserToken = this.config.browser.launchOptions?.channel ?? this.config.browser?.browserName;
252
+ // Hesitant putting hundreds of files into the user's workspace, so using it for hashing instead.
253
+ const rootPathToken = rootPath ? `-${createHash(rootPath)}` : '';
254
+ const result = path.join(dir, `mcp-${browserToken}${rootPathToken}`);
255
+ await fs.promises.mkdir(result, { recursive: true });
256
+ return result;
257
+ }
258
+ }
259
+ async function injectCdpPort(browserConfig) {
260
+ const isBunRuntime = 'bun' in process.versions;
261
+ if (isBunRuntime)
262
+ return;
263
+ if (browserConfig.browserName !== 'chromium')
264
+ return;
265
+ const launchOptions = browserConfig.launchOptions || {};
266
+ launchOptions.cdpPort = await findFreePort();
267
+ browserConfig.launchOptions = launchOptions;
268
+ }
269
+ async function findFreePort() {
270
+ return new Promise((resolve, reject) => {
271
+ const server = net.createServer();
272
+ server.listen(0, () => {
273
+ const { port } = server.address();
274
+ server.close(() => resolve(port));
275
+ });
276
+ server.on('error', reject);
277
+ });
278
+ }
279
+ async function startTraceServer(config, rootPath) {
280
+ if (!config.saveTrace)
281
+ return undefined;
282
+ const tracesDir = await outputFile(config, rootPath, `traces-${Date.now()}`);
283
+ const server = await startTraceViewerServer();
284
+ const urlPrefix = server.urlPrefix('human-readable');
285
+ const url = urlPrefix + '/trace/index.html?trace=' + tracesDir + '/trace.json';
286
+ // eslint-disable-next-line no-console
287
+ console.error('\nTrace viewer listening on ' + url);
288
+ return tracesDir;
289
+ }
@@ -0,0 +1,82 @@
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
+ }
55
+ async listTools() {
56
+ return this._tools.map(tool => toMcpTool(tool.schema));
57
+ }
58
+ async callTool(name, rawArguments) {
59
+ const context = this._context;
60
+ const tool = context.tools.find(tool => tool.schema.name === name);
61
+ if (!tool)
62
+ throw new Error(`Tool "${name}" not found`);
63
+ const parsedArguments = tool.schema.inputSchema.parse(rawArguments || {});
64
+ const response = new Response(context, name, parsedArguments);
65
+ context.setRunningTool(true);
66
+ try {
67
+ await tool.handle(context, parsedArguments, response);
68
+ await response.finish();
69
+ this._sessionLog?.logResponse(response);
70
+ }
71
+ catch (error) {
72
+ response.addError(String(error));
73
+ }
74
+ finally {
75
+ context.setRunningTool(false);
76
+ }
77
+ return response.serialize();
78
+ }
79
+ serverClosed() {
80
+ void this._context?.dispose().catch(logUnhandledError);
81
+ }
82
+ }