@darbotlabs/darbot-browser-mcp 0.1.0

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.
@@ -0,0 +1,275 @@
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
+ * Bridge Server - Standalone WebSocket server that bridges Darbot Browser MCP and Browser Extension
18
+ *
19
+ * Endpoints:
20
+ * - /cdp - Full CDP interface for Darbot Browser MCP
21
+ * - /extension - Extension connection for chrome.debugger forwarding
22
+ */
23
+ /* eslint-disable no-console */
24
+ import { WebSocket, WebSocketServer } from 'ws';
25
+ import http from 'node:http';
26
+ import { EventEmitter } from 'node:events';
27
+ import debug from 'debug';
28
+ import { httpAddressToString } from './transport.js';
29
+ const debugLogger = debug('pw:mcp:relay');
30
+ const CDP_PATH = '/cdp';
31
+ const EXTENSION_PATH = '/extension';
32
+ export class CDPRelayServer extends EventEmitter {
33
+ _wss;
34
+ _playwrightSocket = null;
35
+ _extensionSocket = null;
36
+ _connectionInfo;
37
+ constructor(server) {
38
+ super();
39
+ this._wss = new WebSocketServer({ server });
40
+ this._wss.on('connection', this._onConnection.bind(this));
41
+ }
42
+ stop() {
43
+ this._playwrightSocket?.close();
44
+ this._extensionSocket?.close();
45
+ }
46
+ _onConnection(ws, request) {
47
+ const url = new URL(`http://localhost${request.url}`);
48
+ debugLogger(`New connection to ${url.pathname}`);
49
+ if (url.pathname === CDP_PATH) {
50
+ this._handlePlaywrightConnection(ws);
51
+ }
52
+ else if (url.pathname === EXTENSION_PATH) {
53
+ this._handleExtensionConnection(ws);
54
+ }
55
+ else {
56
+ debugLogger(`Invalid path: ${url.pathname}`);
57
+ ws.close(4004, 'Invalid path');
58
+ }
59
+ }
60
+ /**
61
+ * Handle Darbot Browser MCP connection - provides full CDP interface
62
+ */
63
+ _handlePlaywrightConnection(ws) {
64
+ if (this._playwrightSocket?.readyState === WebSocket.OPEN) {
65
+ debugLogger('Closing previous Playwright connection');
66
+ this._playwrightSocket.close(1000, 'New connection established');
67
+ }
68
+ this._playwrightSocket = ws;
69
+ debugLogger('Darbot Browser MCP connected');
70
+ ws.on('message', data => {
71
+ try {
72
+ const message = JSON.parse(data.toString());
73
+ this._handlePlaywrightMessage(message);
74
+ }
75
+ catch (error) {
76
+ debugLogger('Error parsing Playwright message:', error);
77
+ }
78
+ });
79
+ ws.on('close', () => {
80
+ if (this._playwrightSocket === ws)
81
+ this._playwrightSocket = null;
82
+ debugLogger('Darbot Browser MCP disconnected');
83
+ });
84
+ ws.on('error', error => {
85
+ debugLogger('Playwright WebSocket error:', error);
86
+ });
87
+ }
88
+ /**
89
+ * Handle Extension connection - forwards to browser debugger
90
+ */
91
+ _handleExtensionConnection(ws) {
92
+ if (this._extensionSocket?.readyState === WebSocket.OPEN) {
93
+ debugLogger('Closing previous extension connection');
94
+ this._extensionSocket.close(1000, 'New connection established');
95
+ }
96
+ this._extensionSocket = ws;
97
+ debugLogger('Extension connected');
98
+ ws.on('message', data => {
99
+ try {
100
+ const message = JSON.parse(data.toString());
101
+ this._handleExtensionMessage(message);
102
+ }
103
+ catch (error) {
104
+ debugLogger('Error parsing extension message:', error);
105
+ }
106
+ });
107
+ ws.on('close', () => {
108
+ if (this._extensionSocket === ws)
109
+ this._extensionSocket = null;
110
+ debugLogger('Extension disconnected');
111
+ });
112
+ ws.on('error', error => {
113
+ debugLogger('Extension WebSocket error:', error);
114
+ });
115
+ }
116
+ /**
117
+ * Handle messages from Darbot Browser MCP
118
+ */
119
+ _handlePlaywrightMessage(message) {
120
+ debugLogger('← Playwright:', message.method || `response(${message.id})`);
121
+ // Handle Browser domain methods locally
122
+ if (message.method?.startsWith('Browser.')) {
123
+ this._handleBrowserDomainMethod(message);
124
+ return;
125
+ }
126
+ // Handle Target domain methods
127
+ if (message.method?.startsWith('Target.')) {
128
+ this._handleTargetDomainMethod(message);
129
+ return;
130
+ }
131
+ // Forward other commands to extension
132
+ if (message.method)
133
+ this._forwardToExtension(message);
134
+ }
135
+ /**
136
+ * Handle messages from Extension
137
+ */
138
+ _handleExtensionMessage(message) {
139
+ // Handle connection info from extension
140
+ if (message.type === 'connection_info') {
141
+ debugLogger('← Extension connected to tab:', message);
142
+ this._connectionInfo = {
143
+ targetInfo: message.targetInfo,
144
+ // Page sessionId that should be used by this connection.
145
+ sessionId: message.sessionId
146
+ };
147
+ return;
148
+ }
149
+ // CDP event from extension
150
+ debugLogger(`← Extension message: ${message.method ?? (message.id && `response(id=${message.id})`) ?? 'unknown'}`);
151
+ this._sendToPlaywright(message);
152
+ }
153
+ /**
154
+ * Handle Browser domain methods locally
155
+ */
156
+ _handleBrowserDomainMethod(message) {
157
+ switch (message.method) {
158
+ case 'Browser.getVersion':
159
+ this._sendToPlaywright({
160
+ id: message.id,
161
+ result: {
162
+ protocolVersion: '1.3',
163
+ product: 'Browser/Extension-Bridge',
164
+ userAgent: 'CDP-Bridge-Server/1.0.0',
165
+ }
166
+ });
167
+ break;
168
+ case 'Browser.setDownloadBehavior':
169
+ this._sendToPlaywright({
170
+ id: message.id,
171
+ result: {}
172
+ });
173
+ break;
174
+ default:
175
+ // Forward unknown Browser methods to extension
176
+ this._forwardToExtension(message);
177
+ }
178
+ }
179
+ /**
180
+ * Handle Target domain methods
181
+ */
182
+ _handleTargetDomainMethod(message) {
183
+ switch (message.method) {
184
+ case 'Target.setAutoAttach':
185
+ // Simulate auto-attach behavior with real target info
186
+ if (this._connectionInfo && !message.sessionId) {
187
+ debugLogger('Simulating auto-attach for target:', JSON.stringify(message));
188
+ this._sendToPlaywright({
189
+ method: 'Target.attachedToTarget',
190
+ params: {
191
+ sessionId: this._connectionInfo.sessionId,
192
+ targetInfo: {
193
+ ...this._connectionInfo.targetInfo,
194
+ attached: true,
195
+ },
196
+ waitingForDebugger: false
197
+ }
198
+ });
199
+ this._sendToPlaywright({
200
+ id: message.id,
201
+ result: {}
202
+ });
203
+ }
204
+ else {
205
+ this._forwardToExtension(message);
206
+ }
207
+ break;
208
+ case 'Target.getTargets':
209
+ const targetInfos = [];
210
+ if (this._connectionInfo) {
211
+ targetInfos.push({
212
+ ...this._connectionInfo.targetInfo,
213
+ attached: true,
214
+ });
215
+ }
216
+ this._sendToPlaywright({
217
+ id: message.id,
218
+ result: { targetInfos }
219
+ });
220
+ break;
221
+ default:
222
+ this._forwardToExtension(message);
223
+ }
224
+ }
225
+ /**
226
+ * Forward message to extension
227
+ */
228
+ _forwardToExtension(message) {
229
+ if (this._extensionSocket?.readyState === WebSocket.OPEN) {
230
+ debugLogger('→ Extension:', message.method || `command(${message.id})`);
231
+ this._extensionSocket.send(JSON.stringify(message));
232
+ }
233
+ else {
234
+ debugLogger('Extension not connected, cannot forward message');
235
+ if (message.id) {
236
+ this._sendToPlaywright({
237
+ id: message.id,
238
+ error: { message: 'Extension not connected' }
239
+ });
240
+ }
241
+ }
242
+ }
243
+ /**
244
+ * Forward message to Playwright
245
+ */
246
+ _sendToPlaywright(message) {
247
+ if (this._playwrightSocket?.readyState === WebSocket.OPEN) {
248
+ debugLogger('→ Playwright:', JSON.stringify(message));
249
+ this._playwrightSocket.send(JSON.stringify(message));
250
+ }
251
+ }
252
+ }
253
+ export async function startCDPRelayServer(httpServer) {
254
+ const wsAddress = httpAddressToString(httpServer.address()).replace(/^http/, 'ws');
255
+ const cdpRelayServer = new CDPRelayServer(httpServer);
256
+ process.on('exit', () => cdpRelayServer.stop());
257
+ debugLogger(`CDP relay server started on ${wsAddress}${EXTENSION_PATH} - Connect to it using the browser extension.`);
258
+ const cdpEndpoint = `${wsAddress}${CDP_PATH}`;
259
+ return cdpEndpoint;
260
+ }
261
+ // CLI usage
262
+ if (import.meta.url === `file://${process.argv[1]}`) {
263
+ const port = parseInt(process.argv[2], 10) || 9223;
264
+ const httpServer = http.createServer();
265
+ await new Promise(resolve => httpServer.listen(port, resolve));
266
+ const server = new CDPRelayServer(httpServer);
267
+ console.error(`CDP Bridge Server listening on ws://localhost:${port}`);
268
+ console.error(`- Darbot Browser MCP: ws://localhost:${port}${CDP_PATH}`);
269
+ console.error(`- Extension: ws://localhost:${port}${EXTENSION_PATH}`);
270
+ process.on('SIGINT', () => {
271
+ debugLogger('\nShutting down bridge server...');
272
+ server.stop();
273
+ process.exit(0);
274
+ });
275
+ }
package/lib/config.js ADDED
@@ -0,0 +1,204 @@
1
+ /**
2
+ * Copyright (c) Microsoft Corporation.
3
+ *
4
+ * Licensed under the Apache License, Version 2.0 (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ *
8
+ * http://www.apache.org/licenses/LICENSE-2.0
9
+ *
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ import fs from 'fs';
17
+ import os from 'os';
18
+ import path from 'path';
19
+ import { devices } from 'playwright';
20
+ import { sanitizeForFilePath } from './tools/utils.js';
21
+ const defaultConfig = {
22
+ browser: {
23
+ browserName: 'chromium',
24
+ launchOptions: {
25
+ channel: 'msedge',
26
+ headless: os.platform() === 'linux' && !process.env.DISPLAY,
27
+ chromiumSandbox: true,
28
+ args: [
29
+ '--disable-popup-blocking',
30
+ '--allow-popups',
31
+ `--disable-extensions-except=${process.env.EXTENSION_PATH || '/default/path/to/extension'}`, // Use EXTENSION_PATH environment variable or fallback to default
32
+ `--load-extension=${process.env.EXTENSION_PATH || '/default/path/to/extension'}`, // Use EXTENSION_PATH environment variable or fallback to default
33
+ ],
34
+ },
35
+ contextOptions: {
36
+ viewport: null,
37
+ },
38
+ },
39
+ network: {
40
+ allowedOrigins: undefined,
41
+ blockedOrigins: undefined,
42
+ },
43
+ server: {},
44
+ outputDir: path.join(os.tmpdir(), 'darbot-browser-mcp-output', sanitizeForFilePath(new Date().toISOString())),
45
+ };
46
+ export async function resolveConfig(config) {
47
+ return mergeConfig(defaultConfig, config);
48
+ }
49
+ export async function resolveCLIConfig(cliOptions) {
50
+ const configInFile = await loadConfig(cliOptions.config);
51
+ const cliOverrides = await configFromCLIOptions(cliOptions);
52
+ const result = mergeConfig(mergeConfig(defaultConfig, configInFile), cliOverrides);
53
+ // Derive artifact output directory from config.outputDir
54
+ if (result.saveTrace)
55
+ result.browser.launchOptions.tracesDir = path.join(result.outputDir, 'traces');
56
+ return result;
57
+ }
58
+ export function validateConfig(config) {
59
+ if (config.extension) {
60
+ if (config.browser?.browserName !== 'chromium')
61
+ throw new Error('Extension mode is only supported for Chromium browsers.');
62
+ }
63
+ }
64
+ export async function configFromCLIOptions(cliOptions) {
65
+ let browserName;
66
+ let channel;
67
+ switch (cliOptions.browser) {
68
+ case 'chrome':
69
+ case 'chrome-beta':
70
+ case 'chrome-canary':
71
+ case 'chrome-dev':
72
+ case 'chromium':
73
+ case 'msedge':
74
+ case 'msedge-beta':
75
+ case 'msedge-canary':
76
+ case 'msedge-dev':
77
+ browserName = 'chromium';
78
+ channel = cliOptions.browser;
79
+ break;
80
+ case 'firefox':
81
+ browserName = 'firefox';
82
+ break;
83
+ case 'webkit':
84
+ browserName = 'webkit';
85
+ break;
86
+ }
87
+ // Launch options
88
+ const launchOptions = {
89
+ channel,
90
+ executablePath: cliOptions.executablePath,
91
+ headless: cliOptions.headless,
92
+ };
93
+ // --no-sandbox was passed, disable the sandbox
94
+ if (!cliOptions.sandbox)
95
+ launchOptions.chromiumSandbox = false;
96
+ if (cliOptions.proxyServer) {
97
+ launchOptions.proxy = {
98
+ server: cliOptions.proxyServer
99
+ };
100
+ if (cliOptions.proxyBypass)
101
+ launchOptions.proxy.bypass = cliOptions.proxyBypass;
102
+ }
103
+ if (cliOptions.device && cliOptions.cdpEndpoint)
104
+ throw new Error('Device emulation is not supported with cdpEndpoint.');
105
+ if (cliOptions.device && cliOptions.extension)
106
+ throw new Error('Device emulation is not supported with extension mode.');
107
+ // Context options
108
+ const contextOptions = cliOptions.device ? devices[cliOptions.device] : {};
109
+ if (cliOptions.storageState)
110
+ contextOptions.storageState = cliOptions.storageState;
111
+ if (cliOptions.userAgent)
112
+ contextOptions.userAgent = cliOptions.userAgent;
113
+ if (cliOptions.viewportSize) {
114
+ try {
115
+ const [width, height] = cliOptions.viewportSize.split(',').map(n => +n);
116
+ if (isNaN(width) || isNaN(height))
117
+ throw new Error('bad values');
118
+ contextOptions.viewport = { width, height };
119
+ }
120
+ catch (e) {
121
+ throw new Error('Invalid viewport size format: use "width,height", for example --viewport-size="800,600"');
122
+ }
123
+ }
124
+ if (cliOptions.ignoreHttpsErrors)
125
+ contextOptions.ignoreHTTPSErrors = true;
126
+ if (cliOptions.blockServiceWorkers)
127
+ contextOptions.serviceWorkers = 'block';
128
+ const result = {
129
+ browser: {
130
+ browserAgent: cliOptions.browserAgent ?? process.env.PW_BROWSER_AGENT,
131
+ browserName,
132
+ isolated: cliOptions.isolated,
133
+ userDataDir: cliOptions.userDataDir,
134
+ launchOptions,
135
+ contextOptions,
136
+ cdpEndpoint: cliOptions.cdpEndpoint,
137
+ },
138
+ server: {
139
+ port: cliOptions.port,
140
+ host: cliOptions.host,
141
+ },
142
+ capabilities: cliOptions.caps?.split(',').map((c) => c.trim()),
143
+ vision: !!cliOptions.vision,
144
+ extension: !!cliOptions.extension,
145
+ network: {
146
+ allowedOrigins: cliOptions.allowedOrigins,
147
+ blockedOrigins: cliOptions.blockedOrigins,
148
+ },
149
+ saveTrace: cliOptions.saveTrace,
150
+ outputDir: cliOptions.outputDir,
151
+ imageResponses: cliOptions.imageResponses,
152
+ };
153
+ return result;
154
+ }
155
+ async function loadConfig(configFile) {
156
+ if (!configFile)
157
+ return {};
158
+ try {
159
+ return JSON.parse(await fs.promises.readFile(configFile, 'utf8'));
160
+ }
161
+ catch (error) {
162
+ throw new Error(`Failed to load config file: ${configFile}, ${error}`);
163
+ }
164
+ }
165
+ export async function outputFile(config, name) {
166
+ await fs.promises.mkdir(config.outputDir, { recursive: true });
167
+ const fileName = sanitizeForFilePath(name);
168
+ return path.join(config.outputDir, fileName);
169
+ }
170
+ function pickDefined(obj) {
171
+ return Object.fromEntries(Object.entries(obj ?? {}).filter(([_, v]) => v !== undefined));
172
+ }
173
+ function mergeConfig(base, overrides) {
174
+ const browser = {
175
+ ...pickDefined(base.browser),
176
+ ...pickDefined(overrides.browser),
177
+ browserName: overrides.browser?.browserName ?? base.browser?.browserName ?? 'chromium',
178
+ isolated: overrides.browser?.isolated ?? base.browser?.isolated ?? false,
179
+ launchOptions: {
180
+ ...pickDefined(base.browser?.launchOptions),
181
+ ...pickDefined(overrides.browser?.launchOptions),
182
+ ...{ assistantMode: true },
183
+ },
184
+ contextOptions: {
185
+ ...pickDefined(base.browser?.contextOptions),
186
+ ...pickDefined(overrides.browser?.contextOptions),
187
+ },
188
+ };
189
+ if (browser.browserName !== 'chromium' && browser.launchOptions)
190
+ delete browser.launchOptions.channel;
191
+ return {
192
+ ...pickDefined(base),
193
+ ...pickDefined(overrides),
194
+ browser,
195
+ network: {
196
+ ...pickDefined(base.network),
197
+ ...pickDefined(overrides.network),
198
+ },
199
+ server: {
200
+ ...pickDefined(base.server),
201
+ ...pickDefined(overrides.server),
202
+ },
203
+ };
204
+ }
@@ -0,0 +1,84 @@
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 { Server as McpServer } from '@modelcontextprotocol/sdk/server/index.js';
17
+ import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js';
18
+ import { zodToJsonSchema } from 'zod-to-json-schema';
19
+ import { Context } from './context.js';
20
+ import { snapshotTools, visionTools } from './tools.js';
21
+ import { packageJSON } from './package.js';
22
+ import { validateConfig } from './config.js';
23
+ export function createConnection(config, browserContextFactory) {
24
+ const allTools = config.vision ? visionTools : snapshotTools;
25
+ const tools = allTools.filter(tool => !config.capabilities || tool.capability === 'core' || config.capabilities.includes(tool.capability));
26
+ validateConfig(config);
27
+ const context = new Context(tools, config, browserContextFactory);
28
+ const server = new McpServer({ name: 'Browser', version: packageJSON.version }, {
29
+ capabilities: {
30
+ tools: {},
31
+ }
32
+ });
33
+ server.setRequestHandler(ListToolsRequestSchema, async () => {
34
+ return {
35
+ tools: tools.map(tool => ({
36
+ name: tool.schema.name,
37
+ description: tool.schema.description,
38
+ inputSchema: zodToJsonSchema(tool.schema.inputSchema),
39
+ annotations: {
40
+ title: tool.schema.title,
41
+ readOnlyHint: tool.schema.type === 'readOnly',
42
+ destructiveHint: tool.schema.type === 'destructive',
43
+ openWorldHint: true,
44
+ },
45
+ })),
46
+ };
47
+ });
48
+ server.setRequestHandler(CallToolRequestSchema, async (request) => {
49
+ const errorResult = (...messages) => ({
50
+ content: [{ type: 'text', text: messages.join('\n') }],
51
+ isError: true,
52
+ });
53
+ const tool = tools.find(tool => tool.schema.name === request.params.name);
54
+ if (!tool)
55
+ return errorResult(`Tool "${request.params.name}" not found`);
56
+ const modalStates = context.modalStates().map(state => state.type);
57
+ if (tool.clearsModalState && !modalStates.includes(tool.clearsModalState))
58
+ return errorResult(`The tool "${request.params.name}" can only be used when there is related modal state present.`, ...context.modalStatesMarkdown());
59
+ if (!tool.clearsModalState && modalStates.length)
60
+ return errorResult(`Tool "${request.params.name}" does not handle the modal state.`, ...context.modalStatesMarkdown());
61
+ try {
62
+ return await context.run(tool, request.params.arguments);
63
+ }
64
+ catch (error) {
65
+ return errorResult(String(error));
66
+ }
67
+ });
68
+ return new Connection(server, context);
69
+ }
70
+ export class Connection {
71
+ server;
72
+ context;
73
+ constructor(server, context) {
74
+ this.server = server;
75
+ this.context = context;
76
+ this.server.oninitialized = () => {
77
+ this.context.clientVersion = this.server.getClientVersion();
78
+ };
79
+ }
80
+ async close() {
81
+ await this.server.close();
82
+ await this.context.close();
83
+ }
84
+ }