mcp-browser-dev-tools 0.0.1-beta.1 → 0.0.1-beta.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/cli.mjs CHANGED
@@ -1,5 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import { spawn } from "node:child_process";
3
+ import { mkdir, readFile } from "node:fs/promises";
4
+ import path from "node:path";
3
5
  import process from "node:process";
4
6
  import { pathToFileURL } from "node:url";
5
7
 
@@ -11,6 +13,7 @@ import {
11
13
  import { isLoopbackHost, loadConfig } from "./config.mjs";
12
14
  import { collectDoctorReport, renderDoctorReport } from "./doctor.mjs";
13
15
  import { PACKAGE_NAME, PACKAGE_VERSION } from "./package-info.mjs";
16
+ import { resolveRelayOptions, startTcpRelay } from "./tcp-relay.mjs";
14
17
 
15
18
  export function parseCliArgs(argv) {
16
19
  const args = [...argv];
@@ -55,6 +58,7 @@ function printUsage() {
55
58
  " serve Run the MCP broker over stdio",
56
59
  " doctor [--url URL] Check browser endpoint and optional page reachability",
57
60
  " open <url> Launch a local browser with remote debugging enabled",
61
+ " relay Forward TCP traffic across a local machine boundary",
58
62
  " version Print the package version",
59
63
  " help Print usage information",
60
64
  "",
@@ -63,10 +67,19 @@ function printUsage() {
63
67
  " --version Print the package version",
64
68
  "",
65
69
  "Open options:",
66
- " --family <name> chromium or firefox",
70
+ " --family <name> chromium, edge, or firefox",
67
71
  " --port <port> remote debugging port",
68
72
  " --address <host> remote debugging address for Chromium",
69
- " --user-data-dir <p> optional browser profile directory",
73
+ " --user-data-dir <p> optional Chromium user data dir or Firefox profile dir",
74
+ " --wait-ms <ms> wait for the debug endpoint and print doctor output",
75
+ " --no-doctor skip the post-launch doctor check",
76
+ "",
77
+ "Relay options:",
78
+ " --listen-host <host> relay bind host (defaults to 127.0.0.1)",
79
+ " --listen-port <port> relay bind port (defaults to 9223)",
80
+ " --target-host <host> relay target host (defaults to 127.0.0.1)",
81
+ " --target-port <port> relay target port (defaults to 9222)",
82
+ " --wsl on Windows, bind to the WSL virtual interface",
70
83
  "",
71
84
  ].join("\n"),
72
85
  );
@@ -76,6 +89,105 @@ function printVersion() {
76
89
  process.stdout.write(`${PACKAGE_VERSION}\n`);
77
90
  }
78
91
 
92
+ function sleep(ms) {
93
+ return new Promise((resolve) => {
94
+ setTimeout(resolve, ms);
95
+ });
96
+ }
97
+
98
+ const FIREFOX_BIDI_SERVER_FILENAME = "WebDriverBiDiServer.json";
99
+
100
+ function isHttpLikeUrl(value) {
101
+ try {
102
+ const url = new URL(value);
103
+ return url.protocol === "http:" || url.protocol === "https:";
104
+ } catch {
105
+ return false;
106
+ }
107
+ }
108
+
109
+ function normalizeFirefoxDoctorHost(value) {
110
+ const host = typeof value === "string" ? value.trim() : "";
111
+ if (!host || host === "0.0.0.0" || host === "::" || host === "[::]") {
112
+ return "127.0.0.1";
113
+ }
114
+
115
+ return host;
116
+ }
117
+
118
+ function normalizeFirefoxDoctorPath(value) {
119
+ if (typeof value !== "string") {
120
+ return "/";
121
+ }
122
+
123
+ const trimmed = value.trim();
124
+ if (!trimmed) {
125
+ return "/";
126
+ }
127
+
128
+ return trimmed.startsWith("/") ? trimmed : `/${trimmed}`;
129
+ }
130
+
131
+ export function parseFirefoxBidiServerInfo(contents) {
132
+ const parsed = JSON.parse(contents);
133
+ if (!parsed || typeof parsed !== "object") {
134
+ return null;
135
+ }
136
+
137
+ const directUrl =
138
+ parsed.webSocketUrl ??
139
+ parsed.websocketUrl ??
140
+ parsed.wsUrl ??
141
+ parsed.ws_url ??
142
+ null;
143
+ if (typeof directUrl === "string" && directUrl.trim()) {
144
+ return directUrl.trim().replace(/\/+$/, "");
145
+ }
146
+
147
+ const port =
148
+ parsed.ws_port ?? parsed.port ?? parsed.remoteDebuggingPort ?? null;
149
+ if (!Number.isInteger(port) && !/^\d+$/.test(String(port ?? "").trim())) {
150
+ return null;
151
+ }
152
+
153
+ const host = normalizeFirefoxDoctorHost(
154
+ parsed.ws_host ?? parsed.host ?? parsed.hostname ?? "127.0.0.1",
155
+ );
156
+ const protocol =
157
+ parsed.protocol === "https" || parsed.protocol === "wss" ? "wss:" : "ws:";
158
+ const endpoint = new URL(`${protocol}//${host}`);
159
+ endpoint.port = String(port);
160
+ endpoint.pathname = normalizeFirefoxDoctorPath(
161
+ parsed.path ?? parsed.ws_path ?? "/",
162
+ );
163
+ return endpoint.toString().replace(/\/+$/, "");
164
+ }
165
+
166
+ export async function resolveFirefoxDoctorEndpoint({
167
+ userDataDir,
168
+ fallbackPort,
169
+ }) {
170
+ if (!userDataDir) {
171
+ return `ws://127.0.0.1:${fallbackPort}`;
172
+ }
173
+
174
+ try {
175
+ const serverInfo = await readFile(
176
+ path.join(userDataDir, FIREFOX_BIDI_SERVER_FILENAME),
177
+ "utf8",
178
+ );
179
+ return (
180
+ parseFirefoxBidiServerInfo(serverInfo) ?? `ws://127.0.0.1:${fallbackPort}`
181
+ );
182
+ } catch (error) {
183
+ if (error?.code === "ENOENT") {
184
+ return `ws://127.0.0.1:${fallbackPort}`;
185
+ }
186
+
187
+ return `ws://127.0.0.1:${fallbackPort}`;
188
+ }
189
+ }
190
+
79
191
  async function runServe() {
80
192
  const app = createBrowserDevToolsApp();
81
193
  app.installSignalHandlers();
@@ -105,7 +217,8 @@ async function runOpen(positional, options) {
105
217
  const family =
106
218
  typeof options.family === "string" ? options.family : config.browserFamily;
107
219
  const requestedAddress =
108
- family === "chromium" && typeof options.address === "string"
220
+ (family === "chromium" || family === "edge") &&
221
+ typeof options.address === "string"
109
222
  ? options.address.trim()
110
223
  : null;
111
224
 
@@ -128,17 +241,23 @@ async function runOpen(positional, options) {
128
241
  family === "firefox"
129
242
  ? new URL(config.firefoxBidiWsUrl).port || "9222"
130
243
  : new URL(config.cdpBaseUrl).port || "9222";
244
+ const resolvedPort =
245
+ typeof options.port === "string" ? options.port : defaultPort;
246
+ const userDataDir =
247
+ typeof options["user-data-dir"] === "string"
248
+ ? options["user-data-dir"]
249
+ : undefined;
250
+
251
+ if (family === "firefox" && userDataDir) {
252
+ await mkdir(userDataDir, { recursive: true });
253
+ }
131
254
 
132
255
  const args = buildBrowserLaunchArgs({
133
256
  family,
134
257
  url,
135
- remoteDebuggingPort:
136
- typeof options.port === "string" ? options.port : defaultPort,
258
+ remoteDebuggingPort: resolvedPort,
137
259
  remoteDebuggingAddress: requestedAddress || undefined,
138
- userDataDir:
139
- family === "chromium" && typeof options["user-data-dir"] === "string"
140
- ? options["user-data-dir"]
141
- : undefined,
260
+ userDataDir,
142
261
  });
143
262
 
144
263
  const child = spawn(executable, args, {
@@ -150,6 +269,87 @@ async function runOpen(positional, options) {
150
269
  process.stdout.write(
151
270
  `launched ${family} browser: ${executable} ${args.join(" ")}\n`,
152
271
  );
272
+
273
+ if (options["no-doctor"] === true) {
274
+ return;
275
+ }
276
+
277
+ const waitMs =
278
+ typeof options["wait-ms"] === "string"
279
+ ? Number.parseInt(options["wait-ms"], 10)
280
+ : 5000;
281
+ const timeoutMs = Number.isInteger(waitMs) && waitMs >= 0 ? waitMs : 5000;
282
+ const startedAt = Date.now();
283
+ const doctorEnv = {
284
+ ...process.env,
285
+ MCP_BROWSER_FAMILY: family,
286
+ };
287
+
288
+ if (family === "firefox") {
289
+ doctorEnv.FIREFOX_BIDI_WS_URL = await resolveFirefoxDoctorEndpoint({
290
+ userDataDir,
291
+ fallbackPort: resolvedPort,
292
+ });
293
+ } else {
294
+ const address = requestedAddress || "127.0.0.1";
295
+ doctorEnv.CDP_BASE_URL = `http://${address}:${resolvedPort}`;
296
+ }
297
+
298
+ let report = await collectDoctorReport({
299
+ env: doctorEnv,
300
+ url: isHttpLikeUrl(url) ? url : null,
301
+ });
302
+
303
+ while (
304
+ !report.browserStatus.available &&
305
+ Date.now() - startedAt < timeoutMs
306
+ ) {
307
+ await sleep(250);
308
+ if (family === "firefox") {
309
+ doctorEnv.FIREFOX_BIDI_WS_URL = await resolveFirefoxDoctorEndpoint({
310
+ userDataDir,
311
+ fallbackPort: resolvedPort,
312
+ });
313
+ }
314
+ report = await collectDoctorReport({
315
+ env: doctorEnv,
316
+ url: isHttpLikeUrl(url) ? url : null,
317
+ });
318
+ }
319
+
320
+ process.stdout.write(`${renderDoctorReport(report)}\n`);
321
+
322
+ if (!report.browserStatus.available) {
323
+ process.exitCode = 1;
324
+ }
325
+ }
326
+
327
+ async function runRelay(options) {
328
+ const relayOptions = resolveRelayOptions(options);
329
+ const relay = await startTcpRelay(relayOptions);
330
+
331
+ const close = async (signal) => {
332
+ process.stderr.write(`[relay] shutting down after ${signal}\n`);
333
+ await relay.close();
334
+ };
335
+
336
+ process.on("SIGINT", () => {
337
+ void close("SIGINT").finally(() => process.exit(0));
338
+ });
339
+
340
+ process.on("SIGTERM", () => {
341
+ void close("SIGTERM").finally(() => process.exit(0));
342
+ });
343
+
344
+ process.stdout.write(
345
+ `relay listening on ${relayOptions.listenHost}:${relayOptions.listenPort} -> ${relayOptions.targetHost}:${relayOptions.targetPort}\n`,
346
+ );
347
+
348
+ if (relayOptions.useWslBridge) {
349
+ process.stdout.write(
350
+ `for WSL use: CDP_BASE_URL=http://${relayOptions.listenHost}:${relayOptions.listenPort}\n`,
351
+ );
352
+ }
153
353
  }
154
354
 
155
355
  export async function runCli(argv = process.argv.slice(2)) {
@@ -175,6 +375,9 @@ export async function runCli(argv = process.argv.slice(2)) {
175
375
  case "open":
176
376
  await runOpen(positional, options);
177
377
  return;
378
+ case "relay":
379
+ await runRelay(options);
380
+ return;
178
381
  case "version":
179
382
  case "-v":
180
383
  printVersion();
package/src/config.mjs CHANGED
@@ -3,6 +3,7 @@ export const DEFAULT_FIREFOX_BIDI_WS_URL = "ws://127.0.0.1:9222";
3
3
  export const DEFAULT_EVENT_BUFFER_SIZE = 200;
4
4
  export const DEFAULT_PROTOCOL_VERSION = "2024-11-05";
5
5
  export const DEFAULT_BROWSER_FAMILY = "chromium";
6
+ export const CDP_BROWSER_FAMILIES = ["chromium", "edge"];
6
7
 
7
8
  export function isLoopbackHost(value) {
8
9
  return ["127.0.0.1", "localhost", "::1", "[::1]"].includes(value);
@@ -46,7 +47,12 @@ export function isLoopbackOrigin(value) {
46
47
 
47
48
  export function parseBrowserFamily(value) {
48
49
  const normalized = value?.trim().toLowerCase();
49
- if (normalized === "firefox" || normalized === "chromium") {
50
+ if (
51
+ normalized === "firefox" ||
52
+ normalized === "chromium" ||
53
+ normalized === "edge" ||
54
+ normalized === "auto"
55
+ ) {
50
56
  return normalized;
51
57
  }
52
58
 
@@ -58,15 +64,24 @@ export function loadConfig(env = process.env) {
58
64
  const allowRemoteEndpoints = allowsRemoteEndpoints(env);
59
65
  const cdpBaseUrl = normalizeBaseUrl(env.CDP_BASE_URL);
60
66
  const firefoxBidiWsUrl = normalizeWebSocketUrl(env.FIREFOX_BIDI_WS_URL);
61
- const selectedEndpoint =
62
- browserFamily === "firefox" ? firefoxBidiWsUrl : cdpBaseUrl;
67
+ const endpointsToValidate =
68
+ browserFamily === "firefox"
69
+ ? [["FIREFOX_BIDI_WS_URL", firefoxBidiWsUrl]]
70
+ : browserFamily === "auto"
71
+ ? [
72
+ ["CDP_BASE_URL", cdpBaseUrl],
73
+ ["FIREFOX_BIDI_WS_URL", firefoxBidiWsUrl],
74
+ ]
75
+ : [["CDP_BASE_URL", cdpBaseUrl]];
63
76
 
64
- if (!allowRemoteEndpoints && !isLoopbackOrigin(selectedEndpoint)) {
65
- throw new Error(
66
- `${
67
- browserFamily === "firefox" ? "FIREFOX_BIDI_WS_URL" : "CDP_BASE_URL"
68
- } must point to a loopback host unless MCP_BROWSER_ALLOW_REMOTE_ENDPOINTS=1`,
69
- );
77
+ if (!allowRemoteEndpoints) {
78
+ for (const [name, endpoint] of endpointsToValidate) {
79
+ if (!isLoopbackOrigin(endpoint)) {
80
+ throw new Error(
81
+ `${name} must point to a loopback host unless MCP_BROWSER_ALLOW_REMOTE_ENDPOINTS=1`,
82
+ );
83
+ }
84
+ }
70
85
  }
71
86
 
72
87
  return {
package/src/doctor.mjs CHANGED
@@ -4,6 +4,21 @@ import { createBrowserAdapter } from "./browser-adapter.mjs";
4
4
  import { loadConfig } from "./config.mjs";
5
5
  import { detectInstalledBrowsers } from "./browser-launcher.mjs";
6
6
 
7
+ function reportEndpoints(config) {
8
+ if (config.browserFamily === "firefox") {
9
+ return config.firefoxBidiWsUrl;
10
+ }
11
+
12
+ if (config.browserFamily === "auto") {
13
+ return {
14
+ chromium: config.cdpBaseUrl,
15
+ firefox: config.firefoxBidiWsUrl,
16
+ };
17
+ }
18
+
19
+ return config.cdpBaseUrl;
20
+ }
21
+
7
22
  async function probeUrl(url) {
8
23
  try {
9
24
  const response = await fetch(url);
@@ -37,10 +52,7 @@ export async function collectDoctorReport({
37
52
  platform: process.platform,
38
53
  release: os.release(),
39
54
  browserFamily: config.browserFamily,
40
- endpoint:
41
- config.browserFamily === "firefox"
42
- ? config.firefoxBidiWsUrl
43
- : config.cdpBaseUrl,
55
+ endpoint: reportEndpoints(config),
44
56
  display: {
45
57
  DISPLAY: env.DISPLAY || null,
46
58
  WAYLAND_DISPLAY: env.WAYLAND_DISPLAY || null,
@@ -56,14 +68,22 @@ export async function collectDoctorReport({
56
68
  }
57
69
 
58
70
  export function renderDoctorReport(report) {
71
+ const endpointLines =
72
+ typeof report.endpoint === "string"
73
+ ? [`browser endpoint: ${report.endpoint}`]
74
+ : Object.entries(report.endpoint).map(
75
+ ([browserFamily, endpoint]) =>
76
+ `${browserFamily} endpoint: ${endpoint}`,
77
+ );
59
78
  const lines = [
60
79
  `platform: ${report.platform}`,
61
80
  `release: ${report.release}`,
62
81
  `browser family: ${report.browserFamily}`,
63
- `browser endpoint: ${report.endpoint}`,
82
+ ...endpointLines,
64
83
  `DISPLAY: ${report.display.DISPLAY ?? "-"}`,
65
84
  `WAYLAND_DISPLAY: ${report.display.WAYLAND_DISPLAY ?? "-"}`,
66
85
  `chromium executable: ${report.installedBrowsers.chromium ?? "not found"}`,
86
+ `edge executable: ${report.installedBrowsers.edge ?? "not found"}`,
67
87
  `firefox executable: ${report.installedBrowsers.firefox ?? "not found"}`,
68
88
  `adapter available: ${report.browserStatus.available}`,
69
89
  ];