@ejazullah/browser-mcp 0.0.56

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +860 -0
  3. package/cli.js +19 -0
  4. package/index.d.ts +23 -0
  5. package/index.js +1061 -0
  6. package/lib/auth.js +82 -0
  7. package/lib/browserContextFactory.js +205 -0
  8. package/lib/browserServerBackend.js +125 -0
  9. package/lib/config.js +266 -0
  10. package/lib/context.js +232 -0
  11. package/lib/databaseLogger.js +264 -0
  12. package/lib/extension/cdpRelay.js +346 -0
  13. package/lib/extension/extensionContextFactory.js +56 -0
  14. package/lib/extension/main.js +26 -0
  15. package/lib/fileUtils.js +32 -0
  16. package/lib/httpServer.js +39 -0
  17. package/lib/index.js +39 -0
  18. package/lib/javascript.js +49 -0
  19. package/lib/log.js +21 -0
  20. package/lib/loop/loop.js +69 -0
  21. package/lib/loop/loopClaude.js +152 -0
  22. package/lib/loop/loopOpenAI.js +143 -0
  23. package/lib/loop/main.js +60 -0
  24. package/lib/loopTools/context.js +66 -0
  25. package/lib/loopTools/main.js +49 -0
  26. package/lib/loopTools/perform.js +32 -0
  27. package/lib/loopTools/snapshot.js +29 -0
  28. package/lib/loopTools/tool.js +18 -0
  29. package/lib/manualPromise.js +111 -0
  30. package/lib/mcp/inProcessTransport.js +72 -0
  31. package/lib/mcp/server.js +93 -0
  32. package/lib/mcp/transport.js +217 -0
  33. package/lib/mongoDBLogger.js +252 -0
  34. package/lib/package.js +20 -0
  35. package/lib/program.js +113 -0
  36. package/lib/response.js +172 -0
  37. package/lib/sessionLog.js +156 -0
  38. package/lib/tab.js +266 -0
  39. package/lib/tools/cdp.js +169 -0
  40. package/lib/tools/common.js +55 -0
  41. package/lib/tools/console.js +33 -0
  42. package/lib/tools/dialogs.js +47 -0
  43. package/lib/tools/evaluate.js +53 -0
  44. package/lib/tools/extraction.js +217 -0
  45. package/lib/tools/files.js +44 -0
  46. package/lib/tools/forms.js +180 -0
  47. package/lib/tools/getext.js +99 -0
  48. package/lib/tools/install.js +53 -0
  49. package/lib/tools/interactions.js +191 -0
  50. package/lib/tools/keyboard.js +86 -0
  51. package/lib/tools/mouse.js +99 -0
  52. package/lib/tools/navigate.js +70 -0
  53. package/lib/tools/network.js +41 -0
  54. package/lib/tools/pdf.js +40 -0
  55. package/lib/tools/screenshot.js +75 -0
  56. package/lib/tools/selectors.js +233 -0
  57. package/lib/tools/snapshot.js +169 -0
  58. package/lib/tools/states.js +147 -0
  59. package/lib/tools/tabs.js +87 -0
  60. package/lib/tools/tool.js +33 -0
  61. package/lib/tools/utils.js +74 -0
  62. package/lib/tools/wait.js +56 -0
  63. package/lib/tools.js +64 -0
  64. package/lib/utils.js +26 -0
  65. package/openapi.json +683 -0
  66. package/package.json +92 -0
@@ -0,0 +1,346 @@
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
+ * WebSocket server that bridges Playwright MCP and Chrome Extension
18
+ *
19
+ * Endpoints:
20
+ * - /cdp/guid - Full CDP interface for Playwright MCP
21
+ * - /extension/guid - Extension connection for chrome.debugger forwarding
22
+ */
23
+ import { spawn } from 'child_process';
24
+ import debug from 'debug';
25
+ import { WebSocket, WebSocketServer } from 'ws';
26
+ import { httpAddressToString } from '../httpServer.js';
27
+ import { logUnhandledError } from '../log.js';
28
+ import { ManualPromise } from '../manualPromise.js';
29
+ // @ts-ignore
30
+ const { registry } = await import('playwright-core/lib/server/registry/index');
31
+ const debugLogger = debug('pw:mcp:relay');
32
+ export class CDPRelayServer {
33
+ _wsHost;
34
+ _browserChannel;
35
+ _userDataDir;
36
+ _cdpPath;
37
+ _extensionPath;
38
+ _wss;
39
+ _playwrightConnection = null;
40
+ _extensionConnection = null;
41
+ _connectedTabInfo;
42
+ _nextSessionId = 1;
43
+ _extensionConnectionPromise;
44
+ constructor(server, browserChannel, userDataDir) {
45
+ this._wsHost = httpAddressToString(server.address()).replace(/^http/, 'ws');
46
+ this._browserChannel = browserChannel;
47
+ this._userDataDir = userDataDir;
48
+ const uuid = crypto.randomUUID();
49
+ this._cdpPath = `/cdp/${uuid}`;
50
+ this._extensionPath = `/extension/${uuid}`;
51
+ this._resetExtensionConnection();
52
+ this._wss = new WebSocketServer({ server });
53
+ this._wss.on('connection', this._onConnection.bind(this));
54
+ }
55
+ cdpEndpoint() {
56
+ return `${this._wsHost}${this._cdpPath}`;
57
+ }
58
+ extensionEndpoint() {
59
+ return `${this._wsHost}${this._extensionPath}`;
60
+ }
61
+ async ensureExtensionConnectionForMCPContext(clientInfo, abortSignal) {
62
+ debugLogger('Ensuring extension connection for MCP context');
63
+ if (this._extensionConnection)
64
+ return;
65
+ this._connectBrowser(clientInfo);
66
+ debugLogger('Waiting for incoming extension connection');
67
+ await Promise.race([
68
+ this._extensionConnectionPromise,
69
+ new Promise((_, reject) => abortSignal.addEventListener('abort', reject))
70
+ ]);
71
+ debugLogger('Extension connection established');
72
+ }
73
+ _connectBrowser(clientInfo) {
74
+ const mcpRelayEndpoint = `${this._wsHost}${this._extensionPath}`;
75
+ // Need to specify "key" in the manifest.json to make the id stable when loading from file.
76
+ const url = new URL('chrome-extension://jakfalbnbhgkpmoaakfflhflbfpkailf/connect.html');
77
+ url.searchParams.set('mcpRelayUrl', mcpRelayEndpoint);
78
+ url.searchParams.set('client', JSON.stringify(clientInfo));
79
+ const href = url.toString();
80
+ const executableInfo = registry.findExecutable(this._browserChannel);
81
+ if (!executableInfo)
82
+ throw new Error(`Unsupported channel: "${this._browserChannel}"`);
83
+ const executablePath = executableInfo.executablePath();
84
+ if (!executablePath)
85
+ throw new Error(`"${this._browserChannel}" executable not found. Make sure it is installed at a standard location.`);
86
+ const args = [];
87
+ if (this._userDataDir)
88
+ args.push(`--user-data-dir=${this._userDataDir}`);
89
+ args.push(href);
90
+ spawn(executablePath, args, {
91
+ windowsHide: true,
92
+ detached: true,
93
+ shell: false,
94
+ stdio: 'ignore',
95
+ });
96
+ }
97
+ stop() {
98
+ this.closeConnections('Server stopped');
99
+ this._wss.close();
100
+ }
101
+ closeConnections(reason) {
102
+ this._closePlaywrightConnection(reason);
103
+ this._closeExtensionConnection(reason);
104
+ }
105
+ _onConnection(ws, request) {
106
+ const url = new URL(`http://localhost${request.url}`);
107
+ debugLogger(`New connection to ${url.pathname}`);
108
+ if (url.pathname === this._cdpPath) {
109
+ this._handlePlaywrightConnection(ws);
110
+ }
111
+ else if (url.pathname === this._extensionPath) {
112
+ this._handleExtensionConnection(ws);
113
+ }
114
+ else {
115
+ debugLogger(`Invalid path: ${url.pathname}`);
116
+ ws.close(4004, 'Invalid path');
117
+ }
118
+ }
119
+ _handlePlaywrightConnection(ws) {
120
+ if (this._playwrightConnection) {
121
+ debugLogger('Rejecting second Playwright connection');
122
+ ws.close(1000, 'Another CDP client already connected');
123
+ return;
124
+ }
125
+ this._playwrightConnection = ws;
126
+ ws.on('message', async (data) => {
127
+ try {
128
+ const message = JSON.parse(data.toString());
129
+ await this._handlePlaywrightMessage(message);
130
+ }
131
+ catch (error) {
132
+ debugLogger(`Error while handling Playwright message\n${data.toString()}\n`, error);
133
+ }
134
+ });
135
+ ws.on('close', () => {
136
+ if (this._playwrightConnection !== ws)
137
+ return;
138
+ this._playwrightConnection = null;
139
+ this._closeExtensionConnection('Playwright client disconnected');
140
+ debugLogger('Playwright WebSocket closed');
141
+ });
142
+ ws.on('error', error => {
143
+ debugLogger('Playwright WebSocket error:', error);
144
+ });
145
+ debugLogger('Playwright MCP connected');
146
+ }
147
+ _closeExtensionConnection(reason) {
148
+ this._extensionConnection?.close(reason);
149
+ this._extensionConnectionPromise.reject(new Error(reason));
150
+ this._resetExtensionConnection();
151
+ }
152
+ _resetExtensionConnection() {
153
+ this._connectedTabInfo = undefined;
154
+ this._extensionConnection = null;
155
+ this._extensionConnectionPromise = new ManualPromise();
156
+ void this._extensionConnectionPromise.catch(logUnhandledError);
157
+ }
158
+ _closePlaywrightConnection(reason) {
159
+ if (this._playwrightConnection?.readyState === WebSocket.OPEN)
160
+ this._playwrightConnection.close(1000, reason);
161
+ this._playwrightConnection = null;
162
+ }
163
+ _handleExtensionConnection(ws) {
164
+ if (this._extensionConnection) {
165
+ ws.close(1000, 'Another extension connection already established');
166
+ return;
167
+ }
168
+ this._extensionConnection = new ExtensionConnection(ws);
169
+ this._extensionConnection.onclose = (c, reason) => {
170
+ debugLogger('Extension WebSocket closed:', reason, c === this._extensionConnection);
171
+ if (this._extensionConnection !== c)
172
+ return;
173
+ this._resetExtensionConnection();
174
+ this._closePlaywrightConnection(`Extension disconnected: ${reason}`);
175
+ };
176
+ this._extensionConnection.onmessage = this._handleExtensionMessage.bind(this);
177
+ this._extensionConnectionPromise.resolve();
178
+ }
179
+ _handleExtensionMessage(method, params) {
180
+ switch (method) {
181
+ case 'forwardCDPEvent':
182
+ const sessionId = params.sessionId || this._connectedTabInfo?.sessionId;
183
+ this._sendToPlaywright({
184
+ sessionId,
185
+ method: params.method,
186
+ params: params.params
187
+ });
188
+ break;
189
+ case 'detachedFromTab':
190
+ debugLogger('← Debugger detached from tab:', params);
191
+ this._connectedTabInfo = undefined;
192
+ break;
193
+ }
194
+ }
195
+ async _handlePlaywrightMessage(message) {
196
+ debugLogger('← Playwright:', `${message.method} (id=${message.id})`);
197
+ const { id, sessionId, method, params } = message;
198
+ try {
199
+ const result = await this._handleCDPCommand(method, params, sessionId);
200
+ this._sendToPlaywright({ id, sessionId, result });
201
+ }
202
+ catch (e) {
203
+ debugLogger('Error in the extension:', e);
204
+ this._sendToPlaywright({
205
+ id,
206
+ sessionId,
207
+ error: { message: e.message }
208
+ });
209
+ }
210
+ }
211
+ async _handleCDPCommand(method, params, sessionId) {
212
+ switch (method) {
213
+ case 'Browser.getVersion': {
214
+ return {
215
+ protocolVersion: '1.3',
216
+ product: 'Chrome/Extension-Bridge',
217
+ userAgent: 'CDP-Bridge-Server/1.0.0',
218
+ };
219
+ }
220
+ case 'Browser.setDownloadBehavior': {
221
+ return {};
222
+ }
223
+ case 'Target.setAutoAttach': {
224
+ // Forward child session handling.
225
+ if (sessionId)
226
+ break;
227
+ // Simulate auto-attach behavior with real target info
228
+ const { targetInfo } = await this._extensionConnection.send('attachToTab');
229
+ this._connectedTabInfo = {
230
+ targetInfo,
231
+ sessionId: `pw-tab-${this._nextSessionId++}`,
232
+ };
233
+ debugLogger('Simulating auto-attach');
234
+ this._sendToPlaywright({
235
+ method: 'Target.attachedToTarget',
236
+ params: {
237
+ sessionId: this._connectedTabInfo.sessionId,
238
+ targetInfo: {
239
+ ...this._connectedTabInfo.targetInfo,
240
+ attached: true,
241
+ },
242
+ waitingForDebugger: false
243
+ }
244
+ });
245
+ return {};
246
+ }
247
+ case 'Target.getTargetInfo': {
248
+ return this._connectedTabInfo?.targetInfo;
249
+ }
250
+ }
251
+ return await this._forwardToExtension(method, params, sessionId);
252
+ }
253
+ async _forwardToExtension(method, params, sessionId) {
254
+ if (!this._extensionConnection)
255
+ throw new Error('Extension not connected');
256
+ // Top level sessionId is only passed between the relay and the client.
257
+ if (this._connectedTabInfo?.sessionId === sessionId)
258
+ sessionId = undefined;
259
+ return await this._extensionConnection.send('forwardCDPCommand', { sessionId, method, params });
260
+ }
261
+ _sendToPlaywright(message) {
262
+ debugLogger('→ Playwright:', `${message.method ?? `response(id=${message.id})`}`);
263
+ this._playwrightConnection?.send(JSON.stringify(message));
264
+ }
265
+ }
266
+ class ExtensionConnection {
267
+ _ws;
268
+ _callbacks = new Map();
269
+ _lastId = 0;
270
+ onmessage;
271
+ onclose;
272
+ constructor(ws) {
273
+ this._ws = ws;
274
+ this._ws.on('message', this._onMessage.bind(this));
275
+ this._ws.on('close', this._onClose.bind(this));
276
+ this._ws.on('error', this._onError.bind(this));
277
+ }
278
+ async send(method, params, sessionId) {
279
+ if (this._ws.readyState !== WebSocket.OPEN)
280
+ throw new Error(`Unexpected WebSocket state: ${this._ws.readyState}`);
281
+ const id = ++this._lastId;
282
+ this._ws.send(JSON.stringify({ id, method, params, sessionId }));
283
+ const error = new Error(`Protocol error: ${method}`);
284
+ return new Promise((resolve, reject) => {
285
+ this._callbacks.set(id, { resolve, reject, error });
286
+ });
287
+ }
288
+ close(message) {
289
+ debugLogger('closing extension connection:', message);
290
+ if (this._ws.readyState === WebSocket.OPEN)
291
+ this._ws.close(1000, message);
292
+ }
293
+ _onMessage(event) {
294
+ const eventData = event.toString();
295
+ let parsedJson;
296
+ try {
297
+ parsedJson = JSON.parse(eventData);
298
+ }
299
+ catch (e) {
300
+ debugLogger(`<closing ws> Closing websocket due to malformed JSON. eventData=${eventData} e=${e?.message}`);
301
+ this._ws.close();
302
+ return;
303
+ }
304
+ try {
305
+ this._handleParsedMessage(parsedJson);
306
+ }
307
+ catch (e) {
308
+ debugLogger(`<closing ws> Closing websocket due to failed onmessage callback. eventData=${eventData} e=${e?.message}`);
309
+ this._ws.close();
310
+ }
311
+ }
312
+ _handleParsedMessage(object) {
313
+ if (object.id && this._callbacks.has(object.id)) {
314
+ const callback = this._callbacks.get(object.id);
315
+ this._callbacks.delete(object.id);
316
+ if (object.error) {
317
+ const error = callback.error;
318
+ error.message = object.error;
319
+ callback.reject(error);
320
+ }
321
+ else {
322
+ callback.resolve(object.result);
323
+ }
324
+ }
325
+ else if (object.id) {
326
+ debugLogger('← Extension: unexpected response', object);
327
+ }
328
+ else {
329
+ this.onmessage?.(object.method, object.params);
330
+ }
331
+ }
332
+ _onClose(event) {
333
+ debugLogger(`<ws closed> code=${event.code} reason=${event.reason}`);
334
+ this._dispose();
335
+ this.onclose?.(this, event.reason);
336
+ }
337
+ _onError(event) {
338
+ debugLogger(`<ws error> message=${event.message} type=${event.type} target=${event.target}`);
339
+ this._dispose();
340
+ }
341
+ _dispose() {
342
+ for (const callback of this._callbacks.values())
343
+ callback.reject(new Error('WebSocket closed'));
344
+ this._callbacks.clear();
345
+ }
346
+ }
@@ -0,0 +1,56 @@
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 * as playwright from 'playwright';
18
+ import { startHttpServer } from '../httpServer.js';
19
+ import { CDPRelayServer } from './cdpRelay.js';
20
+ const debugLogger = debug('pw:mcp:relay');
21
+ export class ExtensionContextFactory {
22
+ name = 'extension';
23
+ description = 'Connect to a browser using the Playwright MCP extension';
24
+ _browserChannel;
25
+ _userDataDir;
26
+ constructor(browserChannel, userDataDir) {
27
+ this._browserChannel = browserChannel;
28
+ this._userDataDir = userDataDir;
29
+ }
30
+ async createContext(clientInfo, abortSignal) {
31
+ const browser = await this._obtainBrowser(clientInfo, abortSignal);
32
+ return {
33
+ browserContext: browser.contexts()[0],
34
+ close: async () => {
35
+ debugLogger('close() called for browser context');
36
+ await browser.close();
37
+ }
38
+ };
39
+ }
40
+ async _obtainBrowser(clientInfo, abortSignal) {
41
+ const relay = await this._startRelay(abortSignal);
42
+ await relay.ensureExtensionConnectionForMCPContext(clientInfo, abortSignal);
43
+ return await playwright.chromium.connectOverCDP(relay.cdpEndpoint());
44
+ }
45
+ async _startRelay(abortSignal) {
46
+ const httpServer = await startHttpServer({});
47
+ if (abortSignal.aborted) {
48
+ httpServer.close();
49
+ throw new Error(abortSignal.reason);
50
+ }
51
+ const cdpRelayServer = new CDPRelayServer(httpServer, this._browserChannel, this._userDataDir);
52
+ abortSignal.addEventListener('abort', () => cdpRelayServer.stop());
53
+ debugLogger(`CDP relay server started, extension endpoint: ${cdpRelayServer.extensionEndpoint()}.`);
54
+ return cdpRelayServer;
55
+ }
56
+ }
@@ -0,0 +1,26 @@
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 { ExtensionContextFactory } from './extensionContextFactory.js';
17
+ import { BrowserServerBackend } from '../browserServerBackend.js';
18
+ import * as mcpTransport from '../mcp/transport.js';
19
+ export async function runWithExtension(config) {
20
+ const contextFactory = new ExtensionContextFactory(config.browser.launchOptions.channel || 'chrome', config.browser.userDataDir);
21
+ const serverBackendFactory = () => new BrowserServerBackend(config, [contextFactory]);
22
+ await mcpTransport.start(serverBackendFactory, config.server);
23
+ }
24
+ export function createExtensionContextFactory(config) {
25
+ return new ExtensionContextFactory(config.browser.launchOptions.channel || 'chrome', config.browser.userDataDir);
26
+ }
@@ -0,0 +1,32 @@
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 os from 'node:os';
17
+ import path from 'node:path';
18
+ export function cacheDir() {
19
+ let cacheDirectory;
20
+ if (process.platform === 'linux')
21
+ cacheDirectory = process.env.XDG_CACHE_HOME || path.join(os.homedir(), '.cache');
22
+ else if (process.platform === 'darwin')
23
+ cacheDirectory = path.join(os.homedir(), 'Library', 'Caches');
24
+ else if (process.platform === 'win32')
25
+ cacheDirectory = process.env.LOCALAPPDATA || path.join(os.homedir(), 'AppData', 'Local');
26
+ else
27
+ throw new Error('Unsupported platform: ' + process.platform);
28
+ return path.join(cacheDirectory, 'ms-playwright');
29
+ }
30
+ export async function userDataDir(browserConfig) {
31
+ return path.join(cacheDir(), 'ms-playwright', `mcp-${browserConfig.launchOptions?.channel ?? browserConfig?.browserName}-profile`);
32
+ }
@@ -0,0 +1,39 @@
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 assert from 'assert';
17
+ import http from 'http';
18
+ export async function startHttpServer(config) {
19
+ const { host, port } = config;
20
+ const httpServer = http.createServer();
21
+ await new Promise((resolve, reject) => {
22
+ httpServer.on('error', reject);
23
+ httpServer.listen(port, host, () => {
24
+ resolve();
25
+ httpServer.removeListener('error', reject);
26
+ });
27
+ });
28
+ return httpServer;
29
+ }
30
+ export function httpAddressToString(address) {
31
+ assert(address, 'Could not bind server socket');
32
+ if (typeof address === 'string')
33
+ return address;
34
+ const resolvedPort = address.port;
35
+ let resolvedHost = address.family === 'IPv4' ? address.address : `[${address.address}]`;
36
+ if (resolvedHost === '0.0.0.0' || resolvedHost === '[::]')
37
+ resolvedHost = 'localhost';
38
+ return `http://${resolvedHost}:${resolvedPort}`;
39
+ }
package/lib/index.js ADDED
@@ -0,0 +1,39 @@
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 { BrowserServerBackend } from './browserServerBackend.js';
17
+ import { resolveConfig } from './config.js';
18
+ import { contextFactory } from './browserContextFactory.js';
19
+ import * as mcpServer from './mcp/server.js';
20
+ export async function createConnection(userConfig = {}, contextGetter) {
21
+ const config = await resolveConfig(userConfig);
22
+ const factory = contextGetter ? new SimpleBrowserContextFactory(contextGetter) : contextFactory(config);
23
+ return mcpServer.createServer(new BrowserServerBackend(config, [factory]), false);
24
+ }
25
+ class SimpleBrowserContextFactory {
26
+ name = 'custom';
27
+ description = 'Connect to a browser using a custom context getter';
28
+ _contextGetter;
29
+ constructor(contextGetter) {
30
+ this._contextGetter = contextGetter;
31
+ }
32
+ async createContext() {
33
+ const browserContext = await this._contextGetter();
34
+ return {
35
+ browserContext,
36
+ close: () => browserContext.close()
37
+ };
38
+ }
39
+ }
@@ -0,0 +1,49 @@
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
+ // adapted from:
17
+ // - https://github.com/microsoft/playwright/blob/76ee48dc9d4034536e3ec5b2c7ce8be3b79418a8/packages/playwright-core/src/utils/isomorphic/stringUtils.ts
18
+ // - https://github.com/microsoft/playwright/blob/76ee48dc9d4034536e3ec5b2c7ce8be3b79418a8/packages/playwright-core/src/server/codegen/javascript.ts
19
+ // NOTE: this function should not be used to escape any selectors.
20
+ export function escapeWithQuotes(text, char = '\'') {
21
+ const stringified = JSON.stringify(text);
22
+ const escapedText = stringified.substring(1, stringified.length - 1).replace(/\\"/g, '"');
23
+ if (char === '\'')
24
+ return char + escapedText.replace(/[']/g, '\\\'') + char;
25
+ if (char === '"')
26
+ return char + escapedText.replace(/["]/g, '\\"') + char;
27
+ if (char === '`')
28
+ return char + escapedText.replace(/[`]/g, '`') + char;
29
+ throw new Error('Invalid escape char');
30
+ }
31
+ export function quote(text) {
32
+ return escapeWithQuotes(text, '\'');
33
+ }
34
+ export function formatObject(value, indent = ' ') {
35
+ if (typeof value === 'string')
36
+ return quote(value);
37
+ if (Array.isArray(value))
38
+ return `[${value.map(o => formatObject(o)).join(', ')}]`;
39
+ if (typeof value === 'object') {
40
+ const keys = Object.keys(value).filter(key => value[key] !== undefined).sort();
41
+ if (!keys.length)
42
+ return '{}';
43
+ const tokens = [];
44
+ for (const key of keys)
45
+ tokens.push(`${key}: ${formatObject(value[key])}`);
46
+ return `{\n${indent}${tokens.join(`,\n${indent}`)}\n}`;
47
+ }
48
+ return String(value);
49
+ }
package/lib/log.js ADDED
@@ -0,0 +1,21 @@
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
+ const errorsDebug = debug('pw:mcp:errors');
18
+ export function logUnhandledError(error) {
19
+ errorsDebug(error);
20
+ }
21
+ export const testDebug = debug('pw:mcp:test');
@@ -0,0 +1,69 @@
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
+ export async function runTask(delegate, client, task, oneShot = false) {
18
+ const { tools } = await client.listTools();
19
+ const taskContent = oneShot ? `Perform following task: ${task}.` : `Perform following task: ${task}. Once the task is complete, call the "done" tool.`;
20
+ const conversation = delegate.createConversation(taskContent, tools, oneShot);
21
+ for (let iteration = 0; iteration < 5; ++iteration) {
22
+ debug('history')('Making API call for iteration', iteration);
23
+ const toolCalls = await delegate.makeApiCall(conversation);
24
+ if (toolCalls.length === 0)
25
+ throw new Error('Call the "done" tool when the task is complete.');
26
+ const toolResults = [];
27
+ for (const toolCall of toolCalls) {
28
+ const doneResult = delegate.checkDoneToolCall(toolCall);
29
+ if (doneResult !== null)
30
+ return conversation.messages;
31
+ const { name, arguments: args, id } = toolCall;
32
+ try {
33
+ debug('tool')(name, args);
34
+ const response = await client.callTool({
35
+ name,
36
+ arguments: args,
37
+ });
38
+ const responseContent = (response.content || []);
39
+ debug('tool')(responseContent);
40
+ const text = responseContent.filter(part => part.type === 'text').map(part => part.text).join('\n');
41
+ toolResults.push({
42
+ toolCallId: id,
43
+ content: text,
44
+ });
45
+ }
46
+ catch (error) {
47
+ debug('tool')(error);
48
+ toolResults.push({
49
+ toolCallId: id,
50
+ content: `Error while executing tool "${name}": ${error instanceof Error ? error.message : String(error)}\n\nPlease try to recover and complete the task.`,
51
+ isError: true,
52
+ });
53
+ // Skip remaining tool calls for this iteration
54
+ for (const remainingToolCall of toolCalls.slice(toolCalls.indexOf(toolCall) + 1)) {
55
+ toolResults.push({
56
+ toolCallId: remainingToolCall.id,
57
+ content: `This tool call is skipped due to previous error.`,
58
+ isError: true,
59
+ });
60
+ }
61
+ break;
62
+ }
63
+ }
64
+ delegate.addToolResults(conversation, toolResults);
65
+ if (oneShot)
66
+ return conversation.messages;
67
+ }
68
+ throw new Error('Failed to perform step, max attempts reached');
69
+ }