mcp-browser-dev-tools 0.0.1 → 0.0.2

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.
@@ -325,6 +325,122 @@ export function buildPageContextExpression(
325
325
  };
326
326
  }
327
327
 
328
+ function parseDocumentCookies() {
329
+ const COOKIE_LIMIT = 100;
330
+ const NAME_LIMIT = 120;
331
+ const VALUE_LIMIT = 300;
332
+ const cookieText =
333
+ typeof document.cookie === "string" ? document.cookie.trim() : "";
334
+
335
+ if (!cookieText) {
336
+ return {
337
+ totalEntries: 0,
338
+ returnedEntries: 0,
339
+ truncated: false,
340
+ entries: [],
341
+ source: "document.cookie",
342
+ };
343
+ }
344
+
345
+ const rawEntries = cookieText
346
+ .split(";")
347
+ .map((entry) => entry.trim())
348
+ .filter(Boolean);
349
+ const entries = rawEntries.slice(0, COOKIE_LIMIT).map((entry) => {
350
+ const separatorIndex = entry.indexOf("=");
351
+ const name =
352
+ separatorIndex === -1 ? entry : entry.slice(0, separatorIndex);
353
+ const value =
354
+ separatorIndex === -1 ? "" : entry.slice(separatorIndex + 1);
355
+ return {
356
+ name: clipText(name, NAME_LIMIT),
357
+ value: clipText(value, VALUE_LIMIT),
358
+ };
359
+ });
360
+
361
+ return {
362
+ totalEntries: rawEntries.length,
363
+ returnedEntries: entries.length,
364
+ truncated: rawEntries.length > COOKIE_LIMIT,
365
+ entries,
366
+ source: "document.cookie",
367
+ };
368
+ }
369
+
370
+ function snapshotStorage(storage, type) {
371
+ const STORAGE_LIMIT = 100;
372
+ const KEY_LIMIT = 200;
373
+ const VALUE_LIMIT = 300;
374
+
375
+ try {
376
+ const totalEntries = storage.length;
377
+ const entries = [];
378
+ const limit = Math.min(totalEntries, STORAGE_LIMIT);
379
+
380
+ for (let index = 0; index < limit; index += 1) {
381
+ const key = storage.key(index);
382
+ if (key === null) {
383
+ continue;
384
+ }
385
+
386
+ entries.push({
387
+ key: clipText(key, KEY_LIMIT),
388
+ value: clipText(storage.getItem(key), VALUE_LIMIT),
389
+ });
390
+ }
391
+
392
+ return {
393
+ type,
394
+ totalEntries,
395
+ returnedEntries: entries.length,
396
+ truncated: totalEntries > STORAGE_LIMIT,
397
+ entries,
398
+ };
399
+ } catch (error) {
400
+ return {
401
+ type,
402
+ totalEntries: 0,
403
+ returnedEntries: 0,
404
+ truncated: false,
405
+ entries: [],
406
+ error: error instanceof Error ? error.message : String(error),
407
+ };
408
+ }
409
+ }
410
+
411
+ function summarizeStorage(storage, type) {
412
+ const SAMPLE_LIMIT = 20;
413
+ const KEY_LIMIT = 80;
414
+
415
+ try {
416
+ const totalEntries = storage.length;
417
+ const sampleKeys = [];
418
+ const limit = Math.min(totalEntries, SAMPLE_LIMIT);
419
+
420
+ for (let index = 0; index < limit; index += 1) {
421
+ const key = storage.key(index);
422
+ if (key !== null) {
423
+ sampleKeys.push(clipText(key, KEY_LIMIT));
424
+ }
425
+ }
426
+
427
+ return {
428
+ type,
429
+ totalEntries,
430
+ sampleKeys,
431
+ truncated: totalEntries > SAMPLE_LIMIT,
432
+ };
433
+ } catch (error) {
434
+ return {
435
+ type,
436
+ totalEntries: 0,
437
+ sampleKeys: [],
438
+ truncated: false,
439
+ error: error instanceof Error ? error.message : String(error),
440
+ };
441
+ }
442
+ }
443
+
328
444
  function resolveLocator(rawLocator) {
329
445
  const locator = typeof rawLocator === "string" ? rawLocator.trim() : "";
330
446
  if (!locator) {
@@ -722,6 +838,107 @@ export function buildPageContextExpression(
722
838
  entries,
723
839
  };
724
840
  }
841
+ case "cookie_snapshot":
842
+ return {
843
+ browserFamily: payload.browserFamily,
844
+ cookies: parseDocumentCookies(),
845
+ };
846
+ case "storage_snapshot":
847
+ return {
848
+ browserFamily: payload.browserFamily,
849
+ storage: {
850
+ localStorage: snapshotStorage(localStorage, "localStorage"),
851
+ sessionStorage: snapshotStorage(sessionStorage, "sessionStorage"),
852
+ },
853
+ };
854
+ case "debug_report": {
855
+ const cookies = parseDocumentCookies();
856
+ return {
857
+ browserFamily: payload.browserFamily,
858
+ page: describePage(),
859
+ cookies: {
860
+ totalEntries: cookies.totalEntries,
861
+ returnedEntries: cookies.returnedEntries,
862
+ truncated: cookies.truncated,
863
+ sampleNames: cookies.entries.map((entry) => entry.name),
864
+ },
865
+ storage: {
866
+ localStorage: summarizeStorage(localStorage, "localStorage"),
867
+ sessionStorage: summarizeStorage(sessionStorage, "sessionStorage"),
868
+ },
869
+ };
870
+ }
871
+ case "restore_snapshot": {
872
+ const snapshot = payload.snapshot ?? {};
873
+ const clearStorage = payload.clearStorage === true;
874
+ const snapshotUrl = snapshot.page?.url ?? null;
875
+ const snapshotOrigin = snapshotUrl ? new URL(snapshotUrl).origin : null;
876
+ const currentOrigin = location.origin;
877
+
878
+ if (snapshotOrigin && snapshotOrigin !== currentOrigin) {
879
+ throw new Error(
880
+ "Snapshot origin " +
881
+ snapshotOrigin +
882
+ " does not match current origin " +
883
+ currentOrigin,
884
+ );
885
+ }
886
+
887
+ const restoreEntries = (storage, entries) => {
888
+ const safeEntries = Array.isArray(entries) ? entries.slice(0, 100) : [];
889
+ if (clearStorage) {
890
+ storage.clear();
891
+ }
892
+
893
+ for (const entry of safeEntries) {
894
+ if (!entry || typeof entry.key !== "string") {
895
+ continue;
896
+ }
897
+
898
+ storage.setItem(entry.key, typeof entry.value === "string" ? entry.value : "");
899
+ }
900
+
901
+ return safeEntries.length;
902
+ };
903
+
904
+ const restoreCookies = (entries) => {
905
+ const safeEntries = Array.isArray(entries) ? entries.slice(0, 100) : [];
906
+ for (const entry of safeEntries) {
907
+ if (!entry || typeof entry.name !== "string") {
908
+ continue;
909
+ }
910
+
911
+ const encodedName = encodeURIComponent(entry.name);
912
+ const encodedValue = encodeURIComponent(
913
+ typeof entry.value === "string" ? entry.value : "",
914
+ );
915
+ document.cookie =
916
+ encodedName + "=" + encodedValue + "; path=/; SameSite=Lax";
917
+ }
918
+
919
+ return safeEntries.length;
920
+ };
921
+
922
+ return {
923
+ browserFamily: payload.browserFamily,
924
+ restoredAt: new Date().toISOString(),
925
+ clearStorage,
926
+ snapshotOrigin: snapshotOrigin ?? currentOrigin,
927
+ currentOrigin,
928
+ restored: {
929
+ cookies: restoreCookies(snapshot.cookies?.entries),
930
+ localStorage: restoreEntries(
931
+ localStorage,
932
+ snapshot.storage?.localStorage?.entries,
933
+ ),
934
+ sessionStorage: restoreEntries(
935
+ sessionStorage,
936
+ snapshot.storage?.sessionStorage?.entries,
937
+ ),
938
+ },
939
+ page: describePage(),
940
+ };
941
+ }
725
942
  default:
726
943
  throw new Error(\`Unsupported page action: \${payload.action}\`);
727
944
  }
@@ -0,0 +1,290 @@
1
+ import { spawn } from "node:child_process";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import process from "node:process";
5
+ import { fileURLToPath } from "node:url";
6
+
7
+ import { DEFAULT_CDP_BASE_URL } from "./config.mjs";
8
+
9
+ const RELAY_READY_PREFIX = "relay listening on ";
10
+ const WSL_LOCALHOST_PREFIX = "\\\\wsl.localhost\\";
11
+
12
+ function isWslRuntime({
13
+ platform = process.platform,
14
+ release = os.release(),
15
+ env = process.env,
16
+ } = {}) {
17
+ return (
18
+ platform === "linux" &&
19
+ (release.toLowerCase().includes("microsoft") || Boolean(env.WSL_INTEROP))
20
+ );
21
+ }
22
+
23
+ function toWslUncPath(filePath, distroName) {
24
+ if (!distroName) {
25
+ throw new Error("WSL_DISTRO_NAME is required to launch the Windows relay");
26
+ }
27
+
28
+ const resolvedPath = path.resolve(filePath);
29
+ const windowsPath = resolvedPath.replace(/\//g, "\\");
30
+ return `${WSL_LOCALHOST_PREFIX}${distroName}${windowsPath}`;
31
+ }
32
+
33
+ function parseRelayListeningLine(line) {
34
+ const normalized = typeof line === "string" ? line.trim() : "";
35
+ if (!normalized.startsWith(RELAY_READY_PREFIX)) {
36
+ return null;
37
+ }
38
+
39
+ const [binding, target] = normalized
40
+ .slice(RELAY_READY_PREFIX.length)
41
+ .split(" -> ", 2);
42
+ if (!binding || !target) {
43
+ return null;
44
+ }
45
+
46
+ const separatorIndex = binding.lastIndexOf(":");
47
+ if (separatorIndex <= 0) {
48
+ return null;
49
+ }
50
+
51
+ return {
52
+ listenHost: binding.slice(0, separatorIndex),
53
+ listenPort: Number.parseInt(binding.slice(separatorIndex + 1), 10),
54
+ target,
55
+ };
56
+ }
57
+
58
+ function collectLinesFromStream(stream, onLine) {
59
+ if (!stream) {
60
+ return () => {};
61
+ }
62
+
63
+ let buffer = "";
64
+ const handleData = (chunk) => {
65
+ buffer += String(chunk);
66
+ for (;;) {
67
+ const newlineIndex = buffer.indexOf("\n");
68
+ if (newlineIndex === -1) {
69
+ break;
70
+ }
71
+
72
+ const line = buffer.slice(0, newlineIndex);
73
+ buffer = buffer.slice(newlineIndex + 1);
74
+ onLine(line.replace(/\r$/, ""));
75
+ }
76
+ };
77
+
78
+ stream.on("data", handleData);
79
+ return () => {
80
+ stream.off("data", handleData);
81
+ };
82
+ }
83
+
84
+ function normalizeRelayPort(value, fallback, optionName) {
85
+ if (value === undefined || value === null || value === "") {
86
+ return fallback;
87
+ }
88
+
89
+ const parsed =
90
+ typeof value === "number" ? value : Number.parseInt(String(value), 10);
91
+ if (!Number.isInteger(parsed) || parsed < 1 || parsed > 65535) {
92
+ throw new Error(`${optionName} must be an integer between 1 and 65535`);
93
+ }
94
+
95
+ return parsed;
96
+ }
97
+
98
+ function powershellRelayCommand({
99
+ cliScriptPath,
100
+ listenPort,
101
+ targetPort,
102
+ nodeCommand = "node",
103
+ }) {
104
+ const quotedNodeCommand = nodeCommand.replace(/'/g, "''");
105
+ const quotedScriptPath = cliScriptPath.replace(/'/g, "''");
106
+ return [
107
+ "$ErrorActionPreference = 'Stop'",
108
+ `& '${quotedNodeCommand}' '${quotedScriptPath}' relay --wsl --listen-port ${listenPort} --target-port ${targetPort}`,
109
+ ].join("; ");
110
+ }
111
+
112
+ function defaultCliScriptPath() {
113
+ return fileURLToPath(new URL("./cli.mjs", import.meta.url));
114
+ }
115
+
116
+ function defaultCdpTargetPort(config) {
117
+ return Number.parseInt(
118
+ new URL(config.cdpBaseUrl ?? DEFAULT_CDP_BASE_URL).port || "9222",
119
+ 10,
120
+ );
121
+ }
122
+
123
+ export async function bootstrapWslRelay(
124
+ {
125
+ config,
126
+ relayListenPort,
127
+ relayTargetPort,
128
+ startupTimeoutMs = 10_000,
129
+ env = process.env,
130
+ },
131
+ {
132
+ platform = process.platform,
133
+ release = os.release(),
134
+ cliScriptPath = defaultCliScriptPath(),
135
+ spawnProcess = spawn,
136
+ errorOutput = process.stderr,
137
+ } = {},
138
+ ) {
139
+ if (!isWslRuntime({ platform, release, env })) {
140
+ throw new Error("--bootstrap-wsl-relay is only supported inside WSL");
141
+ }
142
+
143
+ if (config.browserFamily === "firefox") {
144
+ throw new Error(
145
+ "--bootstrap-wsl-relay requires a CDP-backed browser family (chromium, edge, or auto)",
146
+ );
147
+ }
148
+
149
+ const targetPort = normalizeRelayPort(
150
+ relayTargetPort,
151
+ defaultCdpTargetPort(config),
152
+ "--target-port",
153
+ );
154
+ const listenPort = normalizeRelayPort(
155
+ relayListenPort,
156
+ targetPort,
157
+ "--bridge-port",
158
+ );
159
+ const relayCliPath = toWslUncPath(cliScriptPath, env.WSL_DISTRO_NAME);
160
+ const relayProcess = spawnProcess(
161
+ "powershell.exe",
162
+ [
163
+ "-NoLogo",
164
+ "-NoProfile",
165
+ "-NonInteractive",
166
+ "-Command",
167
+ powershellRelayCommand({
168
+ cliScriptPath: relayCliPath,
169
+ listenPort,
170
+ targetPort,
171
+ nodeCommand:
172
+ typeof env.MCP_BROWSER_WINDOWS_NODE === "string" &&
173
+ env.MCP_BROWSER_WINDOWS_NODE.trim()
174
+ ? env.MCP_BROWSER_WINDOWS_NODE.trim()
175
+ : "node",
176
+ }),
177
+ ],
178
+ {
179
+ stdio: ["ignore", "pipe", "pipe"],
180
+ },
181
+ );
182
+
183
+ const stderrLines = [];
184
+
185
+ try {
186
+ const relayInfo = await new Promise((resolve, reject) => {
187
+ let settled = false;
188
+ const timer = setTimeout(() => {
189
+ settle(() => {
190
+ reject(
191
+ new Error(
192
+ `Timed out starting the Windows WSL relay after ${startupTimeoutMs}ms`,
193
+ ),
194
+ );
195
+ });
196
+ }, startupTimeoutMs);
197
+ timer.unref?.();
198
+
199
+ const settle = (callback) => {
200
+ if (settled) {
201
+ return;
202
+ }
203
+
204
+ settled = true;
205
+ clearTimeout(timer);
206
+ stopStdout();
207
+ stopStderr();
208
+ relayProcess.off("error", handleError);
209
+ relayProcess.off("exit", handleExit);
210
+ callback();
211
+ };
212
+
213
+ const handleError = (error) => {
214
+ settle(() => reject(error));
215
+ };
216
+
217
+ const handleExit = (code, signal) => {
218
+ const stderrText =
219
+ stderrLines.length > 0 ? `\n${stderrLines.join("\n")}` : "";
220
+ settle(() => {
221
+ reject(
222
+ new Error(
223
+ `Windows WSL relay exited before startup completed (code=${code}, signal=${signal})${stderrText}`,
224
+ ),
225
+ );
226
+ });
227
+ };
228
+
229
+ const stopStdout = collectLinesFromStream(relayProcess.stdout, (line) => {
230
+ const relayInfo = parseRelayListeningLine(line);
231
+ if (relayInfo) {
232
+ settle(() => resolve(relayInfo));
233
+ }
234
+ });
235
+ const stopStderr = collectLinesFromStream(relayProcess.stderr, (line) => {
236
+ stderrLines.push(line);
237
+ });
238
+
239
+ relayProcess.on("error", handleError);
240
+ relayProcess.on("exit", handleExit);
241
+ });
242
+
243
+ const relayBaseUrl = `http://${relayInfo.listenHost}:${relayInfo.listenPort}`;
244
+ relayProcess.stderr?.on("data", (chunk) => {
245
+ errorOutput.write(String(chunk));
246
+ });
247
+
248
+ return {
249
+ env: {
250
+ ...env,
251
+ MCP_BROWSER_ALLOW_REMOTE_ENDPOINTS: "1",
252
+ CDP_BASE_URL: relayBaseUrl,
253
+ },
254
+ bridge: {
255
+ listenHost: relayInfo.listenHost,
256
+ listenPort: relayInfo.listenPort,
257
+ targetPort,
258
+ cdpBaseUrl: relayBaseUrl,
259
+ processId: relayProcess.pid ?? null,
260
+ },
261
+ async close() {
262
+ if (relayProcess.exitCode !== null || relayProcess.killed) {
263
+ return;
264
+ }
265
+
266
+ relayProcess.kill();
267
+ await new Promise((resolve) => {
268
+ relayProcess.once("exit", () => resolve());
269
+ const timer = setTimeout(resolve, 1_000);
270
+ timer.unref?.();
271
+ });
272
+ },
273
+ };
274
+ } catch (error) {
275
+ relayProcess.kill();
276
+ await new Promise((resolve) => {
277
+ relayProcess.once("exit", () => resolve());
278
+ const timer = setTimeout(resolve, 250);
279
+ timer.unref?.();
280
+ });
281
+ throw error;
282
+ }
283
+ }
284
+
285
+ export const _internal = {
286
+ isWslRuntime,
287
+ parseRelayListeningLine,
288
+ powershellRelayCommand,
289
+ toWslUncPath,
290
+ };
@@ -1,3 +1,5 @@
1
+ import { PACKAGE_NAME, PACKAGE_VERSION } from "./package-info.mjs";
2
+
1
3
  const CONSOLE_EVENT_KINDS = new Set(["console", "log", "exception"]);
2
4
 
3
5
  function normalizeLimit(limit, fallback = 50) {
@@ -88,3 +90,84 @@ export function summarizeNetworkRequests(events = [], limit = 50) {
88
90
 
89
91
  return Array.from(requests.values()).slice(-safeLimit);
90
92
  }
93
+
94
+ function asHarDateTime(value, fallback) {
95
+ if (typeof value === "string") {
96
+ const parsed = Date.parse(value);
97
+ if (!Number.isNaN(parsed)) {
98
+ return new Date(parsed).toISOString();
99
+ }
100
+ }
101
+
102
+ return fallback;
103
+ }
104
+
105
+ export function exportHarLikeSummary(events = [], options = {}) {
106
+ const safeLimit = normalizeLimit(options.limit, 50);
107
+ const exportedAt = new Date().toISOString();
108
+ const page = options.page ?? null;
109
+ const pageId = page ? "page-1" : null;
110
+ const requests = summarizeNetworkRequests(events, safeLimit);
111
+
112
+ return {
113
+ log: {
114
+ version: "1.2",
115
+ creator: {
116
+ name: PACKAGE_NAME,
117
+ version: PACKAGE_VERSION,
118
+ },
119
+ pages: page
120
+ ? [
121
+ {
122
+ startedDateTime: exportedAt,
123
+ id: pageId,
124
+ title: page.title ?? page.url ?? "Attached Page",
125
+ pageTimings: {},
126
+ },
127
+ ]
128
+ : [],
129
+ entries: requests.map((request) => ({
130
+ pageref: pageId,
131
+ startedDateTime: asHarDateTime(request.startedAt, exportedAt),
132
+ time: typeof request.duration === "number" ? request.duration : -1,
133
+ request: {
134
+ method: request.method ?? "GET",
135
+ url: request.url ?? "",
136
+ httpVersion: "unknown",
137
+ headers: [],
138
+ queryString: [],
139
+ headersSize: -1,
140
+ bodySize: request.encodedBodySize ?? -1,
141
+ },
142
+ response: {
143
+ status: request.status ?? 0,
144
+ statusText: request.statusText ?? "",
145
+ httpVersion: "unknown",
146
+ headers: [],
147
+ content: {
148
+ size: request.decodedBodySize ?? -1,
149
+ mimeType: request.mimeType ?? "application/octet-stream",
150
+ },
151
+ redirectURL: "",
152
+ headersSize: -1,
153
+ bodySize: request.encodedBodySize ?? -1,
154
+ _transferSize: request.transferSize ?? -1,
155
+ },
156
+ cache: {},
157
+ timings: {
158
+ send: -1,
159
+ wait: typeof request.duration === "number" ? request.duration : -1,
160
+ receive: -1,
161
+ },
162
+ _requestId: request.requestId,
163
+ _resourceType: request.resourceType ?? null,
164
+ _initiatorType: request.initiatorType ?? null,
165
+ _source: request.source ?? null,
166
+ _finished: request.finished,
167
+ _failed: request.failed,
168
+ _canceled: request.canceled,
169
+ _errorText: request.errorText ?? null,
170
+ })),
171
+ },
172
+ };
173
+ }
package/src/tcp-relay.mjs CHANGED
@@ -3,6 +3,8 @@ import os from "node:os";
3
3
  import process from "node:process";
4
4
 
5
5
  import { isLoopbackHost, isTruthyFlag } from "./config.mjs";
6
+ import { createLogger } from "./logger.mjs";
7
+ import { PACKAGE_NAME } from "./package-info.mjs";
6
8
 
7
9
  export const DEFAULT_RELAY_LISTEN_HOST = "127.0.0.1";
8
10
  export const DEFAULT_RELAY_LISTEN_PORT = 9223;
@@ -129,6 +131,10 @@ export async function startTcpRelay({
129
131
  targetHost,
130
132
  targetPort,
131
133
  errorOutput = process.stderr,
134
+ logger = createLogger({
135
+ output: errorOutput,
136
+ name: PACKAGE_NAME,
137
+ }),
132
138
  } = {}) {
133
139
  const openSockets = new Set();
134
140
 
@@ -154,7 +160,7 @@ export async function startTcpRelay({
154
160
  });
155
161
 
156
162
  upstreamSocket.on("error", (error) => {
157
- errorOutput.write(`[relay] target connection failed: ${error.message}\n`);
163
+ logger.error(`relay target connection failed: ${error.message}`);
158
164
  clientSocket.destroy();
159
165
  });
160
166