mcp-browser-dev-tools 0.0.1-beta.6 → 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.6",
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;
@@ -349,6 +358,7 @@ export class FirefoxBidiSessionManager {
349
358
  this.capabilities = null;
350
359
  this.connectPromise = null;
351
360
  this.resolvedWebSocketUrl = null;
361
+ this.deleteSessionUrl = null;
352
362
  }
353
363
 
354
364
  async ensureConnected() {
@@ -374,18 +384,40 @@ export class FirefoxBidiSessionManager {
374
384
  async openConnection() {
375
385
  const endpoint = await this.resolveConnectionEndpoint();
376
386
  this.resolvedWebSocketUrl = endpoint.webSocketUrl;
387
+ this.deleteSessionUrl = endpoint.deleteSessionUrl ?? null;
377
388
  this.websocket = this.websocketFactory(endpoint.webSocketUrl);
378
389
 
379
390
  await new Promise((resolve, reject) => {
380
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
+ };
381
416
 
382
417
  this.websocket.addEventListener(
383
418
  "open",
384
419
  () => {
385
- if (!settled) {
386
- settled = true;
387
- resolve();
388
- }
420
+ settle(resolve);
389
421
  },
390
422
  { once: true },
391
423
  );
@@ -393,12 +425,11 @@ export class FirefoxBidiSessionManager {
393
425
  this.websocket.addEventListener(
394
426
  "error",
395
427
  () => {
396
- if (!settled) {
397
- settled = true;
428
+ settle(() => {
398
429
  reject(
399
430
  new Error(`Failed to connect to ${this.config.firefoxBidiWsUrl}`),
400
431
  );
401
- }
432
+ });
402
433
  },
403
434
  { once: true },
404
435
  );
@@ -413,12 +444,11 @@ export class FirefoxBidiSessionManager {
413
444
  this.browserSessionId = null;
414
445
  this.capabilities = null;
415
446
  this.sessions.clear();
416
- if (!settled) {
417
- settled = true;
447
+ settle(() => {
418
448
  reject(
419
449
  new Error("Firefox BiDi connection closed before it connected"),
420
450
  );
421
- }
451
+ });
422
452
  });
423
453
  });
424
454
 
@@ -453,24 +483,40 @@ export class FirefoxBidiSessionManager {
453
483
  requiresSessionNew: true,
454
484
  sessionId: null,
455
485
  capabilities: null,
486
+ deleteSessionUrl: null,
456
487
  };
457
488
  }
458
489
 
459
490
  async createWebDriverSession(endpointUrl) {
460
491
  const sessionUrl = joinUrlPath(toHttpEndpointUrl(endpointUrl), "/session");
461
- const response = await this.fetchImpl(sessionUrl, {
462
- method: "POST",
463
- headers: {
464
- "content-type": "application/json",
465
- },
466
- body: JSON.stringify({
467
- capabilities: {
468
- alwaysMatch: {
469
- webSocketUrl: true,
470
- },
492
+ let response;
493
+ try {
494
+ response = await this.fetchImpl(sessionUrl, {
495
+ method: "POST",
496
+ headers: {
497
+ "content-type": "application/json",
471
498
  },
472
- }),
473
- });
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
+ }
474
520
 
475
521
  if (!response.ok) {
476
522
  throw new Error(
@@ -495,9 +541,49 @@ export class FirefoxBidiSessionManager {
495
541
  requiresSessionNew: false,
496
542
  sessionId,
497
543
  capabilities,
544
+ deleteSessionUrl: joinUrlPath(sessionUrl, sessionId).toString(),
498
545
  };
499
546
  }
500
547
 
548
+ async waitForWebSocketClose(websocket, timeoutMs = 250) {
549
+ if (!websocket || websocket.readyState === WebSocket.CLOSED) {
550
+ return;
551
+ }
552
+
553
+ await new Promise((resolve) => {
554
+ let settled = false;
555
+ const done = () => {
556
+ if (settled) {
557
+ return;
558
+ }
559
+ settled = true;
560
+ resolve();
561
+ };
562
+
563
+ websocket.addEventListener("close", done, { once: true });
564
+ const timer = setTimeout(done, timeoutMs);
565
+ timer.unref?.();
566
+ });
567
+ }
568
+
569
+ async closeBrowserSession() {
570
+ if (!this.browserSessionId) {
571
+ return;
572
+ }
573
+
574
+ if (this.deleteSessionUrl) {
575
+ await this.fetchImpl(this.deleteSessionUrl, {
576
+ method: "DELETE",
577
+ signal: AbortSignal.timeout(2_000),
578
+ }).catch(() => {});
579
+ return;
580
+ }
581
+
582
+ if (this.websocket?.readyState === WebSocket.OPEN) {
583
+ await this.send("session.end", {}).catch(() => {});
584
+ }
585
+ }
586
+
501
587
  rejectPending(error) {
502
588
  for (const pending of this.pending.values()) {
503
589
  pending.reject(error);
@@ -1019,10 +1105,20 @@ export class FirefoxBidiSessionManager {
1019
1105
  ),
1020
1106
  );
1021
1107
 
1022
- if (this.websocket && this.websocket.readyState < WebSocket.CLOSING) {
1023
- this.websocket.close();
1108
+ const websocket = this.websocket;
1109
+
1110
+ await this.closeBrowserSession();
1111
+
1112
+ if (websocket && websocket.readyState < WebSocket.CLOSING) {
1113
+ websocket.close();
1114
+ await this.waitForWebSocketClose(websocket);
1024
1115
  }
1025
1116
 
1026
1117
  this.sessions.clear();
1118
+ this.websocket = null;
1119
+ this.browserSessionId = null;
1120
+ this.capabilities = null;
1121
+ this.resolvedWebSocketUrl = null;
1122
+ this.deleteSessionUrl = null;
1027
1123
  }
1028
1124
  }