mcp-browser-dev-tools 0.0.2-beta.0 → 0.0.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.
@@ -0,0 +1,575 @@
1
+ import { execFile, spawn } from "node:child_process";
2
+ import { mkdir, mkdtemp, readFile } from "node:fs/promises";
3
+ import os from "node:os";
4
+ import process from "node:process";
5
+ import path from "node:path";
6
+ import { promisify } from "node:util";
7
+
8
+ import {
9
+ buildBrowserLaunchArgs,
10
+ findBrowserExecutable,
11
+ } from "./browser-launcher.mjs";
12
+ import { isLoopbackHost } from "./config.mjs";
13
+ import { collectDoctorReport } from "./doctor.mjs";
14
+
15
+ const FIREFOX_BIDI_SERVER_FILENAME = "WebDriverBiDiServer.json";
16
+ const execFileAsync = promisify(execFile);
17
+
18
+ function detectRuntimePlatform(env = process.env) {
19
+ const release = os.release().toLowerCase();
20
+ if (
21
+ process.platform === "linux" &&
22
+ (release.includes("microsoft") || env.WSL_INTEROP)
23
+ ) {
24
+ return "wsl";
25
+ }
26
+
27
+ return process.platform;
28
+ }
29
+
30
+ function sleep(ms) {
31
+ return new Promise((resolve) => {
32
+ setTimeout(resolve, ms);
33
+ });
34
+ }
35
+
36
+ function isHttpLikeUrl(value) {
37
+ try {
38
+ const url = new URL(value);
39
+ return url.protocol === "http:" || url.protocol === "https:";
40
+ } catch {
41
+ return false;
42
+ }
43
+ }
44
+
45
+ function normalizeFirefoxDoctorHost(value) {
46
+ const host = typeof value === "string" ? value.trim() : "";
47
+ if (!host || host === "0.0.0.0" || host === "::" || host === "[::]") {
48
+ return "127.0.0.1";
49
+ }
50
+
51
+ return host;
52
+ }
53
+
54
+ function normalizeFirefoxDoctorPath(value) {
55
+ if (typeof value !== "string") {
56
+ return "/";
57
+ }
58
+
59
+ const trimmed = value.trim();
60
+ if (!trimmed) {
61
+ return "/";
62
+ }
63
+
64
+ return trimmed.startsWith("/") ? trimmed : `/${trimmed}`;
65
+ }
66
+
67
+ function normalizeStringValue(value) {
68
+ if (typeof value !== "string") {
69
+ return null;
70
+ }
71
+
72
+ const trimmed = value.trim();
73
+ return trimmed ? trimmed : null;
74
+ }
75
+
76
+ const MANAGED_UNSAFE_LAUNCH_ARG_PREFIXES = [
77
+ "--remote-debugging-address",
78
+ "--remote-debugging-port",
79
+ "--remote-debugging-pipe",
80
+ "--user-data-dir",
81
+ "--profile",
82
+ "-profile",
83
+ "-new-instance",
84
+ ];
85
+
86
+ function normalizeIntegerValue(value, optionName, { minimum = 1 } = {}) {
87
+ if (value === undefined || value === null || value === "") {
88
+ return null;
89
+ }
90
+
91
+ const parsed =
92
+ typeof value === "number" ? value : Number.parseInt(String(value), 10);
93
+ if (!Number.isInteger(parsed) || parsed < minimum) {
94
+ throw new Error(`${optionName} must be an integer >= ${minimum}`);
95
+ }
96
+
97
+ return String(parsed);
98
+ }
99
+
100
+ function normalizeUnsafeLaunchArgs(unsafeArgs) {
101
+ if (unsafeArgs === undefined || unsafeArgs === null) {
102
+ return [];
103
+ }
104
+
105
+ if (!Array.isArray(unsafeArgs)) {
106
+ throw new Error("unsafeArgs must be an array of strings");
107
+ }
108
+
109
+ return unsafeArgs.map((value, index) => {
110
+ if (typeof value !== "string") {
111
+ throw new Error(`unsafeArgs[${index}] must be a string`);
112
+ }
113
+
114
+ const normalized = value.trim();
115
+ if (!normalized) {
116
+ throw new Error(`unsafeArgs[${index}] must not be empty`);
117
+ }
118
+
119
+ if (!normalized.startsWith("-")) {
120
+ throw new Error(
121
+ `unsafeArgs[${index}] must be a browser flag starting with "-"`,
122
+ );
123
+ }
124
+
125
+ const lowered = normalized.toLowerCase();
126
+ if (
127
+ MANAGED_UNSAFE_LAUNCH_ARG_PREFIXES.some(
128
+ (prefix) => lowered === prefix || lowered.startsWith(`${prefix}=`),
129
+ )
130
+ ) {
131
+ throw new Error(
132
+ `unsafeArgs[${index}] conflicts with broker-managed launch options`,
133
+ );
134
+ }
135
+
136
+ return normalized;
137
+ });
138
+ }
139
+
140
+ function resolveDefaultPort(config, family) {
141
+ if (family === "firefox") {
142
+ return new URL(config.firefoxBidiWsUrl).port || "9222";
143
+ }
144
+
145
+ return new URL(config.cdpBaseUrl).port || "9222";
146
+ }
147
+
148
+ function resolveDefaultAddress(config) {
149
+ const host = new URL(config.cdpBaseUrl).hostname;
150
+ return host || "127.0.0.1";
151
+ }
152
+
153
+ function browserProcessMatchers(family) {
154
+ if (family === "edge") {
155
+ return [
156
+ "msedge",
157
+ "msedge.exe",
158
+ "microsoft edge",
159
+ "microsoft-edge",
160
+ "microsoft-edge-stable",
161
+ ];
162
+ }
163
+
164
+ if (family === "firefox") {
165
+ return ["firefox", "firefox.exe"];
166
+ }
167
+
168
+ return [
169
+ "chrome",
170
+ "chrome.exe",
171
+ "google chrome",
172
+ "google-chrome",
173
+ "google-chrome-stable",
174
+ "chromium",
175
+ "chromium.exe",
176
+ "chromium-browser",
177
+ ];
178
+ }
179
+
180
+ function normalizeProcessEntry(value) {
181
+ if (typeof value !== "string") {
182
+ return null;
183
+ }
184
+
185
+ const trimmed = value.trim().replace(/^"+|"+$/g, "");
186
+ if (!trimmed) {
187
+ return null;
188
+ }
189
+
190
+ const lowered = trimmed.toLowerCase();
191
+ const basename = lowered.split(/[\\/]/).pop();
192
+ return basename || lowered;
193
+ }
194
+
195
+ function parsePsProcessList(stdout) {
196
+ return String(stdout)
197
+ .split(/\r?\n/)
198
+ .map((line) => normalizeProcessEntry(line))
199
+ .filter(Boolean);
200
+ }
201
+
202
+ function parseTasklistProcessList(stdout) {
203
+ return String(stdout)
204
+ .split(/\r?\n/)
205
+ .map((line) => {
206
+ const match = line.match(/^"([^"]+)"/);
207
+ if (!match) {
208
+ return null;
209
+ }
210
+
211
+ return normalizeProcessEntry(match[1]);
212
+ })
213
+ .filter(Boolean);
214
+ }
215
+
216
+ async function collectRunningProcesses(
217
+ platform,
218
+ { execFileFn = execFileAsync } = {},
219
+ ) {
220
+ const sources = [];
221
+ const entries = [];
222
+ const errors = [];
223
+
224
+ const runSource = async (source, command, args, parser) => {
225
+ try {
226
+ const { stdout } = await execFileFn(command, args, {
227
+ windowsHide: true,
228
+ maxBuffer: 2 * 1024 * 1024,
229
+ });
230
+ sources.push(source);
231
+ entries.push(...parser(stdout));
232
+ } catch (error) {
233
+ errors.push(`${source}: ${error?.message ?? String(error)}`);
234
+ }
235
+ };
236
+
237
+ if (platform === "win32") {
238
+ await runSource(
239
+ "tasklist",
240
+ "tasklist.exe",
241
+ ["/fo", "csv", "/nh"],
242
+ parseTasklistProcessList,
243
+ );
244
+ } else {
245
+ await runSource("ps", "ps", ["-A", "-o", "comm="], parsePsProcessList);
246
+ if (platform === "wsl") {
247
+ await runSource(
248
+ "tasklist",
249
+ "tasklist.exe",
250
+ ["/fo", "csv", "/nh"],
251
+ parseTasklistProcessList,
252
+ );
253
+ }
254
+ }
255
+
256
+ return {
257
+ checked: sources.length > 0,
258
+ sources,
259
+ entries: [...new Set(entries)],
260
+ error: errors.length > 0 ? errors.join("; ") : null,
261
+ };
262
+ }
263
+
264
+ async function detectRunningBrowserProcess(
265
+ family,
266
+ { env = process.env, execFileFn = execFileAsync } = {},
267
+ ) {
268
+ const platform = detectRuntimePlatform(env);
269
+ const processList = await collectRunningProcesses(platform, { execFileFn });
270
+ const matchers = browserProcessMatchers(family);
271
+ const matches = processList.entries.filter((entry) =>
272
+ matchers.includes(entry),
273
+ );
274
+
275
+ return {
276
+ checked: processList.checked,
277
+ detected: matches.length > 0,
278
+ matches,
279
+ sources: processList.sources,
280
+ error: processList.error,
281
+ };
282
+ }
283
+
284
+ async function maybeCreateAutomaticUserDataDir(
285
+ family,
286
+ normalizedUserDataDir,
287
+ {
288
+ env = process.env,
289
+ execFileFn = execFileAsync,
290
+ mkdtempFn = mkdtemp,
291
+ tmpdirFn = os.tmpdir,
292
+ } = {},
293
+ ) {
294
+ const existingBrowserProcess = await detectRunningBrowserProcess(family, {
295
+ env,
296
+ execFileFn,
297
+ });
298
+
299
+ if (
300
+ (family === "chromium" || family === "edge") &&
301
+ !normalizedUserDataDir &&
302
+ existingBrowserProcess.detected
303
+ ) {
304
+ return {
305
+ userDataDir: await mkdtempFn(
306
+ path.join(tmpdirFn(), `mcp-browser-dev-tools-${family}-`),
307
+ ),
308
+ profileStrategy: "temporary",
309
+ existingBrowserProcess,
310
+ };
311
+ }
312
+
313
+ return {
314
+ userDataDir: normalizedUserDataDir,
315
+ profileStrategy: normalizedUserDataDir ? "provided" : "default",
316
+ existingBrowserProcess,
317
+ };
318
+ }
319
+
320
+ export function supportedLaunchFamilies(configuredFamily) {
321
+ if (configuredFamily === "auto") {
322
+ return ["chromium", "edge", "firefox"];
323
+ }
324
+
325
+ if (configuredFamily === "firefox") {
326
+ return ["firefox"];
327
+ }
328
+
329
+ return ["chromium", "edge"];
330
+ }
331
+
332
+ export function resolveLaunchFamily(configuredFamily, requestedFamily) {
333
+ const allowedFamilies = supportedLaunchFamilies(configuredFamily);
334
+ if (!requestedFamily) {
335
+ if (configuredFamily === "auto") {
336
+ throw new Error(
337
+ "browserFamily is required when multiple browser families are configured",
338
+ );
339
+ }
340
+
341
+ return configuredFamily;
342
+ }
343
+
344
+ if (!allowedFamilies.includes(requestedFamily)) {
345
+ throw new Error(
346
+ `browserFamily must be one of: ${allowedFamilies.join(", ")}`,
347
+ );
348
+ }
349
+
350
+ return requestedFamily;
351
+ }
352
+
353
+ export function parseFirefoxBidiServerInfo(contents) {
354
+ const parsed = JSON.parse(contents);
355
+ if (!parsed || typeof parsed !== "object") {
356
+ return null;
357
+ }
358
+
359
+ const directUrl =
360
+ parsed.webSocketUrl ??
361
+ parsed.websocketUrl ??
362
+ parsed.wsUrl ??
363
+ parsed.ws_url ??
364
+ null;
365
+ if (typeof directUrl === "string" && directUrl.trim()) {
366
+ return directUrl.trim().replace(/\/+$/, "");
367
+ }
368
+
369
+ const port =
370
+ parsed.ws_port ?? parsed.port ?? parsed.remoteDebuggingPort ?? null;
371
+ if (!Number.isInteger(port) && !/^\d+$/.test(String(port ?? "").trim())) {
372
+ return null;
373
+ }
374
+
375
+ const host = normalizeFirefoxDoctorHost(
376
+ parsed.ws_host ?? parsed.host ?? parsed.hostname ?? "127.0.0.1",
377
+ );
378
+ const protocol =
379
+ parsed.protocol === "https" || parsed.protocol === "wss" ? "wss:" : "ws:";
380
+ const endpoint = new URL(`${protocol}//${host}`);
381
+ endpoint.port = String(port);
382
+ endpoint.pathname = normalizeFirefoxDoctorPath(
383
+ parsed.path ?? parsed.ws_path ?? "/",
384
+ );
385
+ return endpoint.toString().replace(/\/+$/, "");
386
+ }
387
+
388
+ export async function resolveFirefoxDoctorEndpoint(
389
+ { userDataDir, fallbackPort },
390
+ { readFileFn = readFile } = {},
391
+ ) {
392
+ if (!userDataDir) {
393
+ return `ws://127.0.0.1:${fallbackPort}`;
394
+ }
395
+
396
+ try {
397
+ const serverInfo = await readFileFn(
398
+ path.join(userDataDir, FIREFOX_BIDI_SERVER_FILENAME),
399
+ "utf8",
400
+ );
401
+ return (
402
+ parseFirefoxBidiServerInfo(serverInfo) ?? `ws://127.0.0.1:${fallbackPort}`
403
+ );
404
+ } catch (error) {
405
+ if (error?.code === "ENOENT") {
406
+ return `ws://127.0.0.1:${fallbackPort}`;
407
+ }
408
+
409
+ return `ws://127.0.0.1:${fallbackPort}`;
410
+ }
411
+ }
412
+
413
+ export async function launchBrowser(
414
+ {
415
+ config,
416
+ browserFamily,
417
+ url = "about:blank",
418
+ port,
419
+ address,
420
+ userDataDir,
421
+ unsafeArgs,
422
+ waitMs = 5_000,
423
+ skipDoctor = false,
424
+ env = process.env,
425
+ },
426
+ {
427
+ spawnProcess = spawn,
428
+ mkdirFn = mkdir,
429
+ mkdtempFn = mkdtemp,
430
+ execFileFn = execFileAsync,
431
+ tmpdirFn = os.tmpdir,
432
+ findBrowserExecutableFn = findBrowserExecutable,
433
+ collectDoctorReportFn = collectDoctorReport,
434
+ resolveFirefoxDoctorEndpointFn = resolveFirefoxDoctorEndpoint,
435
+ sleepFn = sleep,
436
+ } = {},
437
+ ) {
438
+ const family = resolveLaunchFamily(config.browserFamily, browserFamily);
439
+ const targetUrl = normalizeStringValue(url) ?? "about:blank";
440
+ const resolvedPort =
441
+ normalizeIntegerValue(port, "port", { minimum: 1 }) ??
442
+ resolveDefaultPort(config, family);
443
+ const normalizedUnsafeArgs = normalizeUnsafeLaunchArgs(unsafeArgs);
444
+ const requestedAddress =
445
+ family === "firefox" ? null : normalizeStringValue(address);
446
+
447
+ if (normalizedUnsafeArgs.length > 0 && !config.enableUnsafeLaunchArgs) {
448
+ throw new Error(
449
+ "unsafeArgs requires MCP_BROWSER_ENABLE_UNSAFE_LAUNCH_ARGS=1",
450
+ );
451
+ }
452
+
453
+ if (
454
+ requestedAddress &&
455
+ !isLoopbackHost(requestedAddress) &&
456
+ !config.allowRemoteEndpoints
457
+ ) {
458
+ throw new Error(
459
+ "--address must be loopback unless MCP_BROWSER_ALLOW_REMOTE_ENDPOINTS=1",
460
+ );
461
+ }
462
+
463
+ const executable = await findBrowserExecutableFn(family, env);
464
+ if (!executable) {
465
+ throw new Error(`No local ${family} browser executable found`);
466
+ }
467
+
468
+ const providedUserDataDir = normalizeStringValue(userDataDir) ?? undefined;
469
+ const {
470
+ userDataDir: normalizedUserDataDir,
471
+ profileStrategy,
472
+ existingBrowserProcess,
473
+ } = await maybeCreateAutomaticUserDataDir(family, providedUserDataDir, {
474
+ env,
475
+ execFileFn,
476
+ mkdtempFn,
477
+ tmpdirFn,
478
+ });
479
+ if (family === "firefox" && normalizedUserDataDir) {
480
+ await mkdirFn(normalizedUserDataDir, { recursive: true });
481
+ }
482
+
483
+ const launchAddress = family === "firefox" ? null : requestedAddress;
484
+ const endpointAddress =
485
+ family === "firefox"
486
+ ? null
487
+ : (requestedAddress ?? resolveDefaultAddress(config));
488
+ const args = buildBrowserLaunchArgs({
489
+ family,
490
+ url: targetUrl,
491
+ remoteDebuggingPort: resolvedPort,
492
+ remoteDebuggingAddress: launchAddress ?? undefined,
493
+ userDataDir: normalizedUserDataDir,
494
+ unsafeArgs: normalizedUnsafeArgs,
495
+ });
496
+
497
+ const child = spawnProcess(executable, args, {
498
+ detached: true,
499
+ stdio: "ignore",
500
+ });
501
+ child.unref?.();
502
+
503
+ const launchedAt = new Date().toISOString();
504
+ const result = {
505
+ browserFamily: family,
506
+ url: targetUrl,
507
+ executable,
508
+ args,
509
+ pid: child.pid ?? null,
510
+ launchedAt,
511
+ endpoint:
512
+ family === "firefox"
513
+ ? `ws://127.0.0.1:${resolvedPort}`
514
+ : `http://${endpointAddress}:${resolvedPort}`,
515
+ userDataDir: normalizedUserDataDir ?? null,
516
+ unsafeArgs: normalizedUnsafeArgs,
517
+ profileStrategy,
518
+ existingBrowserProcess,
519
+ doctorReport: null,
520
+ };
521
+
522
+ if (skipDoctor) {
523
+ return result;
524
+ }
525
+
526
+ const timeoutMs =
527
+ Number.parseInt(
528
+ normalizeIntegerValue(waitMs, "waitMs", { minimum: 0 }) ?? "5000",
529
+ 10,
530
+ ) || 0;
531
+ const startedAt = Date.now();
532
+ const doctorEnv = {
533
+ ...env,
534
+ MCP_BROWSER_FAMILY: family,
535
+ };
536
+
537
+ if (family === "firefox") {
538
+ doctorEnv.FIREFOX_BIDI_WS_URL = await resolveFirefoxDoctorEndpointFn({
539
+ userDataDir: normalizedUserDataDir,
540
+ fallbackPort: resolvedPort,
541
+ });
542
+ } else {
543
+ doctorEnv.CDP_BASE_URL = result.endpoint;
544
+ }
545
+
546
+ let report = await collectDoctorReportFn({
547
+ env: doctorEnv,
548
+ url: isHttpLikeUrl(targetUrl) ? targetUrl : null,
549
+ });
550
+
551
+ while (
552
+ !report.browserStatus.available &&
553
+ Date.now() - startedAt < timeoutMs
554
+ ) {
555
+ await sleepFn(250);
556
+ if (family === "firefox") {
557
+ doctorEnv.FIREFOX_BIDI_WS_URL = await resolveFirefoxDoctorEndpointFn({
558
+ userDataDir: normalizedUserDataDir,
559
+ fallbackPort: resolvedPort,
560
+ });
561
+ }
562
+
563
+ report = await collectDoctorReportFn({
564
+ env: doctorEnv,
565
+ url: isHttpLikeUrl(targetUrl) ? targetUrl : null,
566
+ });
567
+ }
568
+
569
+ result.endpoint =
570
+ family === "firefox"
571
+ ? doctorEnv.FIREFOX_BIDI_WS_URL
572
+ : doctorEnv.CDP_BASE_URL;
573
+ result.doctorReport = report;
574
+ return result;
575
+ }
@@ -174,6 +174,7 @@ export function buildBrowserLaunchArgs({
174
174
  remoteDebuggingPort,
175
175
  remoteDebuggingAddress,
176
176
  userDataDir,
177
+ unsafeArgs = [],
177
178
  }) {
178
179
  if (!url) {
179
180
  throw new Error("A target URL is required");
@@ -187,6 +188,7 @@ export function buildBrowserLaunchArgs({
187
188
  if (remoteDebuggingPort) {
188
189
  args.push(`--remote-debugging-port=${remoteDebuggingPort}`);
189
190
  }
191
+ args.push(...unsafeArgs);
190
192
  args.push(url);
191
193
  return args;
192
194
  }
@@ -200,6 +202,7 @@ export function buildBrowserLaunchArgs({
200
202
  if (userDataDir) {
201
203
  args.push(`--user-data-dir=${userDataDir}`);
202
204
  }
205
+ args.push(...unsafeArgs);
203
206
  args.push(url);
204
207
  return args;
205
208
  }