mcp-browser-dev-tools 0.0.1-beta.7 → 0.0.1-beta.8

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mcp-browser-dev-tools",
3
- "version": "0.0.1-beta.7",
3
+ "version": "0.0.1-beta.8",
4
4
  "description": "Local MCP server for Chromium DevTools Protocol and Firefox WebDriver BiDi",
5
5
  "author": "Hinaser <rindo.hinase@gmail.com>",
6
6
  "type": "module",
package/src/cli.mjs CHANGED
@@ -1,6 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import { spawn } from "node:child_process";
3
- import { mkdir } from "node:fs/promises";
3
+ import { mkdir, readFile } from "node:fs/promises";
4
+ import path from "node:path";
4
5
  import process from "node:process";
5
6
  import { pathToFileURL } from "node:url";
6
7
 
@@ -94,6 +95,8 @@ function sleep(ms) {
94
95
  });
95
96
  }
96
97
 
98
+ const FIREFOX_BIDI_SERVER_FILENAME = "WebDriverBiDiServer.json";
99
+
97
100
  function isHttpLikeUrl(value) {
98
101
  try {
99
102
  const url = new URL(value);
@@ -103,6 +106,90 @@ function isHttpLikeUrl(value) {
103
106
  }
104
107
  }
105
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"
158
+ ? "https:"
159
+ : "http:";
160
+ const endpoint = new URL(`${protocol}//${host}`);
161
+ endpoint.port = String(port);
162
+ endpoint.pathname = normalizeFirefoxDoctorPath(
163
+ parsed.path ?? parsed.ws_path ?? "/",
164
+ );
165
+ return endpoint.toString().replace(/\/+$/, "");
166
+ }
167
+
168
+ export async function resolveFirefoxDoctorEndpoint({
169
+ userDataDir,
170
+ fallbackPort,
171
+ }) {
172
+ if (!userDataDir) {
173
+ return `ws://127.0.0.1:${fallbackPort}`;
174
+ }
175
+
176
+ try {
177
+ const serverInfo = await readFile(
178
+ path.join(userDataDir, FIREFOX_BIDI_SERVER_FILENAME),
179
+ "utf8",
180
+ );
181
+ return (
182
+ parseFirefoxBidiServerInfo(serverInfo) ?? `ws://127.0.0.1:${fallbackPort}`
183
+ );
184
+ } catch (error) {
185
+ if (error?.code === "ENOENT") {
186
+ return `ws://127.0.0.1:${fallbackPort}`;
187
+ }
188
+
189
+ return `ws://127.0.0.1:${fallbackPort}`;
190
+ }
191
+ }
192
+
106
193
  async function runServe() {
107
194
  const app = createBrowserDevToolsApp();
108
195
  app.installSignalHandlers();
@@ -200,7 +287,10 @@ async function runOpen(positional, options) {
200
287
  };
201
288
 
202
289
  if (family === "firefox") {
203
- doctorEnv.FIREFOX_BIDI_WS_URL = `ws://127.0.0.1:${resolvedPort}`;
290
+ doctorEnv.FIREFOX_BIDI_WS_URL = await resolveFirefoxDoctorEndpoint({
291
+ userDataDir,
292
+ fallbackPort: resolvedPort,
293
+ });
204
294
  } else {
205
295
  const address = requestedAddress || "127.0.0.1";
206
296
  doctorEnv.CDP_BASE_URL = `http://${address}:${resolvedPort}`;
@@ -216,6 +306,12 @@ async function runOpen(positional, options) {
216
306
  Date.now() - startedAt < timeoutMs
217
307
  ) {
218
308
  await sleep(250);
309
+ if (family === "firefox") {
310
+ doctorEnv.FIREFOX_BIDI_WS_URL = await resolveFirefoxDoctorEndpoint({
311
+ userDataDir,
312
+ fallbackPort: resolvedPort,
313
+ });
314
+ }
219
315
  report = await collectDoctorReport({
220
316
  env: doctorEnv,
221
317
  url: isHttpLikeUrl(url) ? url : null,
@@ -251,6 +251,14 @@ function isRootPathname(pathname) {
251
251
  return pathname === "" || pathname === "/";
252
252
  }
253
253
 
254
+ function isAbortError(error) {
255
+ return (
256
+ error?.name === "AbortError" ||
257
+ error?.name === "TimeoutError" ||
258
+ error?.code === "ABORT_ERR"
259
+ );
260
+ }
261
+
254
262
  function toHttpEndpointUrl(endpointUrl) {
255
263
  const url = new URL(endpointUrl);
256
264
  if (url.protocol === "ws:") {
@@ -342,6 +350,7 @@ export class FirefoxBidiSessionManager {
342
350
  this.websocketFactory =
343
351
  options.websocketFactory ?? ((url) => new WebSocket(url));
344
352
  this.fetchImpl = options.fetchImpl ?? fetch;
353
+ this.connectionTimeoutMs = options.connectionTimeoutMs ?? 2_000;
345
354
  this.pending = new Map();
346
355
  this.nextMessageId = 1;
347
356
  this.websocket = null;
@@ -380,14 +389,35 @@ export class FirefoxBidiSessionManager {
380
389
 
381
390
  await new Promise((resolve, reject) => {
382
391
  let settled = false;
392
+ const timer = setTimeout(() => {
393
+ if (settled) {
394
+ return;
395
+ }
396
+
397
+ settled = true;
398
+ this.websocket?.close?.();
399
+ reject(
400
+ new Error(
401
+ `Timed out connecting to Firefox BiDi at ${endpoint.webSocketUrl}`,
402
+ ),
403
+ );
404
+ }, this.connectionTimeoutMs);
405
+ timer.unref?.();
406
+
407
+ const settle = (callback) => {
408
+ if (settled) {
409
+ return;
410
+ }
411
+
412
+ settled = true;
413
+ clearTimeout(timer);
414
+ callback();
415
+ };
383
416
 
384
417
  this.websocket.addEventListener(
385
418
  "open",
386
419
  () => {
387
- if (!settled) {
388
- settled = true;
389
- resolve();
390
- }
420
+ settle(resolve);
391
421
  },
392
422
  { once: true },
393
423
  );
@@ -395,12 +425,11 @@ export class FirefoxBidiSessionManager {
395
425
  this.websocket.addEventListener(
396
426
  "error",
397
427
  () => {
398
- if (!settled) {
399
- settled = true;
428
+ settle(() => {
400
429
  reject(
401
430
  new Error(`Failed to connect to ${this.config.firefoxBidiWsUrl}`),
402
431
  );
403
- }
432
+ });
404
433
  },
405
434
  { once: true },
406
435
  );
@@ -415,12 +444,11 @@ export class FirefoxBidiSessionManager {
415
444
  this.browserSessionId = null;
416
445
  this.capabilities = null;
417
446
  this.sessions.clear();
418
- if (!settled) {
419
- settled = true;
447
+ settle(() => {
420
448
  reject(
421
449
  new Error("Firefox BiDi connection closed before it connected"),
422
450
  );
423
- }
451
+ });
424
452
  });
425
453
  });
426
454
 
@@ -461,19 +489,34 @@ export class FirefoxBidiSessionManager {
461
489
 
462
490
  async createWebDriverSession(endpointUrl) {
463
491
  const sessionUrl = joinUrlPath(toHttpEndpointUrl(endpointUrl), "/session");
464
- const response = await this.fetchImpl(sessionUrl, {
465
- method: "POST",
466
- headers: {
467
- "content-type": "application/json",
468
- },
469
- body: JSON.stringify({
470
- capabilities: {
471
- alwaysMatch: {
472
- webSocketUrl: true,
473
- },
492
+ let response;
493
+ try {
494
+ response = await this.fetchImpl(sessionUrl, {
495
+ method: "POST",
496
+ headers: {
497
+ "content-type": "application/json",
474
498
  },
475
- }),
476
- });
499
+ body: JSON.stringify({
500
+ capabilities: {
501
+ alwaysMatch: {
502
+ webSocketUrl: true,
503
+ },
504
+ },
505
+ }),
506
+ signal: AbortSignal.timeout(this.connectionTimeoutMs),
507
+ });
508
+ } catch (error) {
509
+ if (isAbortError(error)) {
510
+ throw new Error(
511
+ `Timed out creating Firefox WebDriver session at ${sessionUrl}`,
512
+ {
513
+ cause: error,
514
+ },
515
+ );
516
+ }
517
+
518
+ throw error;
519
+ }
477
520
 
478
521
  if (!response.ok) {
479
522
  throw new Error(