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

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/index.mjs CHANGED
@@ -1,5 +1,8 @@
1
1
  export { createBrowserDevToolsApp } from "./app.mjs";
2
- export { createBrowserAdapter } from "./browser-adapter.mjs";
2
+ export {
3
+ createBrowserAdapter,
4
+ MultiBrowserAdapter,
5
+ } from "./browser-adapter.mjs";
3
6
  export {
4
7
  buildBrowserLaunchArgs,
5
8
  detectInstalledBrowsers,
@@ -29,3 +32,12 @@ export {
29
32
  PACKAGE_NAME,
30
33
  PACKAGE_VERSION,
31
34
  } from "./package-info.mjs";
35
+ export {
36
+ DEFAULT_RELAY_LISTEN_HOST,
37
+ DEFAULT_RELAY_LISTEN_PORT,
38
+ DEFAULT_RELAY_TARGET_HOST,
39
+ DEFAULT_RELAY_TARGET_PORT,
40
+ getWindowsWslHostCandidates,
41
+ resolveRelayOptions,
42
+ startTcpRelay,
43
+ } from "./tcp-relay.mjs";
@@ -1,7 +1,104 @@
1
1
  export const MAX_MESSAGE_BYTES = 1024 * 1024;
2
2
 
3
- export function encodeMessage(message) {
3
+ function findHeaderEnd(buffer) {
4
+ const crlfHeaderEnd = buffer.indexOf("\r\n\r\n");
5
+ if (crlfHeaderEnd !== -1) {
6
+ return {
7
+ headerEnd: crlfHeaderEnd,
8
+ separatorLength: 4,
9
+ };
10
+ }
11
+
12
+ const lfHeaderEnd = buffer.indexOf("\n\n");
13
+ if (lfHeaderEnd !== -1) {
14
+ return {
15
+ headerEnd: lfHeaderEnd,
16
+ separatorLength: 2,
17
+ };
18
+ }
19
+
20
+ return null;
21
+ }
22
+
23
+ function findJsonMessage(buffer) {
24
+ const text = buffer.toString("utf8");
25
+ let start = 0;
26
+ while (start < text.length && /\s/.test(text[start])) {
27
+ start += 1;
28
+ }
29
+
30
+ if (start >= text.length) {
31
+ return null;
32
+ }
33
+
34
+ const firstChar = text[start];
35
+ if (firstChar !== "{" && firstChar !== "[") {
36
+ return null;
37
+ }
38
+
39
+ let depth = 0;
40
+ let inString = false;
41
+ let escaping = false;
42
+ for (let index = start; index < text.length; index += 1) {
43
+ const char = text[index];
44
+
45
+ if (inString) {
46
+ if (escaping) {
47
+ escaping = false;
48
+ continue;
49
+ }
50
+
51
+ if (char === "\\") {
52
+ escaping = true;
53
+ continue;
54
+ }
55
+
56
+ if (char === '"') {
57
+ inString = false;
58
+ }
59
+
60
+ continue;
61
+ }
62
+
63
+ if (char === '"') {
64
+ inString = true;
65
+ continue;
66
+ }
67
+
68
+ if (char === "{" || char === "[") {
69
+ depth += 1;
70
+ continue;
71
+ }
72
+
73
+ if (char === "}" || char === "]") {
74
+ depth -= 1;
75
+ if (depth < 0) {
76
+ throw new Error("Malformed JSON message");
77
+ }
78
+
79
+ if (depth === 0) {
80
+ let end = index + 1;
81
+ while (end < text.length && /\s/.test(text[end])) {
82
+ end += 1;
83
+ }
84
+
85
+ return {
86
+ consumedBytes: Buffer.byteLength(text.slice(0, end), "utf8"),
87
+ jsonText: text.slice(start, index + 1),
88
+ };
89
+ }
90
+ }
91
+ }
92
+
93
+ return null;
94
+ }
95
+
96
+ export function encodeMessage(message, transportMode = "content-length") {
4
97
  const payload = Buffer.from(JSON.stringify(message), "utf8");
98
+ if (transportMode === "json") {
99
+ return Buffer.concat([payload, Buffer.from("\n", "utf8")]);
100
+ }
101
+
5
102
  return Buffer.concat([
6
103
  Buffer.from(`Content-Length: ${payload.length}\r\n\r\n`, "utf8"),
7
104
  payload,
@@ -11,6 +108,7 @@ export function encodeMessage(message) {
11
108
  export class MessageBuffer {
12
109
  constructor() {
13
110
  this.buffer = Buffer.alloc(0);
111
+ this.transportMode = null;
14
112
  }
15
113
 
16
114
  push(chunk) {
@@ -24,33 +122,44 @@ export class MessageBuffer {
24
122
 
25
123
  const messages = [];
26
124
  while (true) {
27
- const headerEnd = this.buffer.indexOf("\r\n\r\n");
28
- if (headerEnd === -1) {
29
- return messages;
30
- }
125
+ const headerMatch = findHeaderEnd(this.buffer);
126
+ if (headerMatch) {
127
+ const { headerEnd, separatorLength } = headerMatch;
128
+ const header = this.buffer.slice(0, headerEnd).toString("utf8");
129
+ const match = header.match(/content-length:\s*(\d+)/i);
130
+ if (!match) {
131
+ this.buffer = Buffer.alloc(0);
132
+ throw new Error("Missing Content-Length header");
133
+ }
31
134
 
32
- const header = this.buffer.slice(0, headerEnd).toString("utf8");
33
- const match = header.match(/content-length:\s*(\d+)/i);
34
- if (!match) {
35
- this.buffer = Buffer.alloc(0);
36
- throw new Error("Missing Content-Length header");
37
- }
135
+ const bodyLength = Number.parseInt(match[1], 10);
136
+ if (bodyLength > MAX_MESSAGE_BYTES) {
137
+ this.buffer = Buffer.alloc(0);
138
+ throw new Error("Message exceeded maximum size");
139
+ }
140
+
141
+ const bodyStart = headerEnd + separatorLength;
142
+ const bodyEnd = bodyStart + bodyLength;
143
+ if (this.buffer.length < bodyEnd) {
144
+ return messages;
145
+ }
38
146
 
39
- const bodyLength = Number.parseInt(match[1], 10);
40
- if (bodyLength > MAX_MESSAGE_BYTES) {
41
- this.buffer = Buffer.alloc(0);
42
- throw new Error("Message exceeded maximum size");
147
+ const body = this.buffer.slice(bodyStart, bodyEnd).toString("utf8");
148
+ this.buffer = this.buffer.slice(bodyEnd);
149
+ this.transportMode ??= "content-length";
150
+ messages.push(JSON.parse(body));
151
+ continue;
43
152
  }
44
153
 
45
- const bodyStart = headerEnd + 4;
46
- const bodyEnd = bodyStart + bodyLength;
47
- if (this.buffer.length < bodyEnd) {
154
+ const jsonMatch = findJsonMessage(this.buffer);
155
+ if (!jsonMatch) {
48
156
  return messages;
49
157
  }
50
158
 
51
- const body = this.buffer.slice(bodyStart, bodyEnd).toString("utf8");
52
- this.buffer = this.buffer.slice(bodyEnd);
53
- messages.push(JSON.parse(body));
159
+ const { consumedBytes, jsonText } = jsonMatch;
160
+ this.buffer = this.buffer.slice(consumedBytes);
161
+ this.transportMode ??= "json";
162
+ messages.push(JSON.parse(jsonText));
54
163
  }
55
164
  }
56
165
  }
@@ -3,6 +3,16 @@ import { PACKAGE_NAME, PACKAGE_VERSION } from "./package-info.mjs";
3
3
 
4
4
  const SERVER_NAME = PACKAGE_NAME;
5
5
  const SERVER_VERSION = PACKAGE_VERSION;
6
+ const DEBUG_STDIO_ENABLED = process.env.MCP_BROWSER_DEBUG_STDIO === "1";
7
+
8
+ function formatChunkPreview(chunk, limit = 160) {
9
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
10
+ return buffer
11
+ .subarray(0, limit)
12
+ .toString("utf8")
13
+ .replace(/\r/g, "\\r")
14
+ .replace(/\n/g, "\\n");
15
+ }
6
16
 
7
17
  function success(id, result) {
8
18
  return {
@@ -102,6 +112,18 @@ function validateValue(path, value, schema) {
102
112
  if (schema.minimum !== undefined && value < schema.minimum) {
103
113
  throw new Error(`${path} must be >= ${schema.minimum}`);
104
114
  }
115
+
116
+ return;
117
+ }
118
+
119
+ if (schema.type === "number") {
120
+ if (typeof value !== "number" || Number.isNaN(value)) {
121
+ throw new Error(`${path} must be a number`);
122
+ }
123
+
124
+ if (schema.minimum !== undefined && value < schema.minimum) {
125
+ throw new Error(`${path} must be >= ${schema.minimum}`);
126
+ }
105
127
  }
106
128
  }
107
129
 
@@ -129,6 +151,28 @@ function sessionWithLimitSchema(description) {
129
151
  };
130
152
  }
131
153
 
154
+ function sessionSchema(properties, required, description) {
155
+ return {
156
+ type: "object",
157
+ properties: {
158
+ sessionId: {
159
+ type: "string",
160
+ },
161
+ ...properties,
162
+ },
163
+ required: ["sessionId", ...required],
164
+ additionalProperties: false,
165
+ description,
166
+ };
167
+ }
168
+
169
+ function waitUntilProperty() {
170
+ return {
171
+ type: "string",
172
+ enum: ["none", "interactive", "complete"],
173
+ };
174
+ }
175
+
132
176
  export class McpBrowserDevToolsServer {
133
177
  constructor({
134
178
  config,
@@ -157,7 +201,11 @@ export class McpBrowserDevToolsServer {
157
201
  "Report whether the configured browser endpoint is reachable and how many active sessions are attached.",
158
202
  inputSchema: emptyObjectSchema(),
159
203
  },
160
- handler: async () => this.browserAdapter.getBrowserStatus(),
204
+ handler: async () => ({
205
+ serverName: SERVER_NAME,
206
+ serverVersion: SERVER_VERSION,
207
+ ...(await this.browserAdapter.getBrowserStatus()),
208
+ }),
161
209
  },
162
210
  ],
163
211
  [
@@ -233,6 +281,278 @@ export class McpBrowserDevToolsServer {
233
281
  this.browserAdapter.detachSession(args.sessionId),
234
282
  },
235
283
  ],
284
+ [
285
+ "get_page_state",
286
+ {
287
+ definition: {
288
+ name: "get_page_state",
289
+ description:
290
+ "Return the current URL, title, ready state, viewport, and scroll positions for an attached page.",
291
+ inputSchema: sessionSchema({}, []),
292
+ },
293
+ handler: async (args) =>
294
+ this.browserAdapter.getPageState(args.sessionId),
295
+ },
296
+ ],
297
+ [
298
+ "navigate",
299
+ {
300
+ definition: {
301
+ name: "navigate",
302
+ description:
303
+ "Navigate an attached tab to a URL and optionally wait for interactive or complete load state.",
304
+ inputSchema: sessionSchema(
305
+ {
306
+ url: {
307
+ type: "string",
308
+ },
309
+ waitUntil: waitUntilProperty(),
310
+ },
311
+ ["url"],
312
+ ),
313
+ },
314
+ handler: async (args) =>
315
+ this.browserAdapter.navigate(args.sessionId, args.url, {
316
+ waitUntil: args.waitUntil,
317
+ }),
318
+ },
319
+ ],
320
+ [
321
+ "reload",
322
+ {
323
+ definition: {
324
+ name: "reload",
325
+ description:
326
+ "Reload the attached tab and optionally ignore cache while waiting for interactive or complete load state.",
327
+ inputSchema: sessionSchema(
328
+ {
329
+ ignoreCache: {
330
+ type: "boolean",
331
+ },
332
+ waitUntil: waitUntilProperty(),
333
+ },
334
+ [],
335
+ ),
336
+ },
337
+ handler: async (args) =>
338
+ this.browserAdapter.reload(args.sessionId, {
339
+ ignoreCache: args.ignoreCache,
340
+ waitUntil: args.waitUntil,
341
+ }),
342
+ },
343
+ ],
344
+ [
345
+ "click",
346
+ {
347
+ definition: {
348
+ name: "click",
349
+ description:
350
+ "Click a single element located by CSS, text=..., role=..., or name=... syntax.",
351
+ inputSchema: sessionSchema(
352
+ {
353
+ selector: {
354
+ type: "string",
355
+ },
356
+ },
357
+ ["selector"],
358
+ ),
359
+ },
360
+ handler: async (args) =>
361
+ this.browserAdapter.click(args.sessionId, args.selector),
362
+ },
363
+ ],
364
+ [
365
+ "hover",
366
+ {
367
+ definition: {
368
+ name: "hover",
369
+ description:
370
+ "Hover a single element located by CSS, text=..., role=..., or name=... syntax.",
371
+ inputSchema: sessionSchema(
372
+ {
373
+ selector: {
374
+ type: "string",
375
+ },
376
+ },
377
+ ["selector"],
378
+ ),
379
+ },
380
+ handler: async (args) =>
381
+ this.browserAdapter.hover(args.sessionId, args.selector),
382
+ },
383
+ ],
384
+ [
385
+ "type",
386
+ {
387
+ definition: {
388
+ name: "type",
389
+ description:
390
+ "Type text into an input, textarea, or contenteditable element.",
391
+ inputSchema: sessionSchema(
392
+ {
393
+ selector: {
394
+ type: "string",
395
+ },
396
+ text: {
397
+ type: "string",
398
+ },
399
+ clear: {
400
+ type: "boolean",
401
+ },
402
+ },
403
+ ["selector", "text"],
404
+ ),
405
+ },
406
+ handler: async (args) =>
407
+ this.browserAdapter.type(args.sessionId, args.selector, args.text, {
408
+ clear: args.clear,
409
+ }),
410
+ },
411
+ ],
412
+ [
413
+ "select",
414
+ {
415
+ definition: {
416
+ name: "select",
417
+ description:
418
+ "Select an option from a <select> by value or visible label.",
419
+ inputSchema: sessionSchema(
420
+ {
421
+ selector: {
422
+ type: "string",
423
+ },
424
+ value: {
425
+ type: "string",
426
+ },
427
+ label: {
428
+ type: "string",
429
+ },
430
+ },
431
+ ["selector"],
432
+ ),
433
+ },
434
+ handler: async (args) => {
435
+ if (!args.value && !args.label) {
436
+ throw new Error("select requires either value or label");
437
+ }
438
+
439
+ return this.browserAdapter.select(args.sessionId, args.selector, {
440
+ value: args.value,
441
+ label: args.label,
442
+ });
443
+ },
444
+ },
445
+ ],
446
+ [
447
+ "press_key",
448
+ {
449
+ definition: {
450
+ name: "press_key",
451
+ description:
452
+ "Dispatch a key press against the focused element or an optionally targeted element.",
453
+ inputSchema: sessionSchema(
454
+ {
455
+ key: {
456
+ type: "string",
457
+ },
458
+ selector: {
459
+ type: "string",
460
+ },
461
+ },
462
+ ["key"],
463
+ ),
464
+ },
465
+ handler: async (args) =>
466
+ this.browserAdapter.pressKey(
467
+ args.sessionId,
468
+ args.key,
469
+ args.selector,
470
+ ),
471
+ },
472
+ ],
473
+ [
474
+ "scroll",
475
+ {
476
+ definition: {
477
+ name: "scroll",
478
+ description:
479
+ "Scroll the page by deltas or scroll a specific element into view.",
480
+ inputSchema: sessionSchema(
481
+ {
482
+ selector: {
483
+ type: "string",
484
+ },
485
+ deltaX: {
486
+ type: "integer",
487
+ },
488
+ deltaY: {
489
+ type: "integer",
490
+ },
491
+ block: {
492
+ type: "string",
493
+ enum: ["start", "center", "end", "nearest"],
494
+ },
495
+ },
496
+ [],
497
+ ),
498
+ },
499
+ handler: async (args) => {
500
+ if (
501
+ !args.selector &&
502
+ args.deltaX === undefined &&
503
+ args.deltaY === undefined
504
+ ) {
505
+ throw new Error(
506
+ "scroll requires either selector or deltaX/deltaY values",
507
+ );
508
+ }
509
+
510
+ return this.browserAdapter.scroll(args.sessionId, {
511
+ selector: args.selector,
512
+ deltaX: args.deltaX,
513
+ deltaY: args.deltaY,
514
+ block: args.block,
515
+ });
516
+ },
517
+ },
518
+ ],
519
+ [
520
+ "set_viewport",
521
+ {
522
+ definition: {
523
+ name: "set_viewport",
524
+ description:
525
+ "Override the page viewport to a specific width and height for responsive debugging.",
526
+ inputSchema: sessionSchema(
527
+ {
528
+ width: {
529
+ type: "integer",
530
+ minimum: 1,
531
+ },
532
+ height: {
533
+ type: "integer",
534
+ minimum: 1,
535
+ },
536
+ deviceScaleFactor: {
537
+ type: "number",
538
+ minimum: 0.1,
539
+ },
540
+ mobile: {
541
+ type: "boolean",
542
+ },
543
+ },
544
+ ["width", "height"],
545
+ ),
546
+ },
547
+ handler: async (args) =>
548
+ this.browserAdapter.setViewport(args.sessionId, {
549
+ width: args.width,
550
+ height: args.height,
551
+ deviceScaleFactor: args.deviceScaleFactor,
552
+ mobile: args.mobile,
553
+ }),
554
+ },
555
+ ],
236
556
  [
237
557
  "get_console_messages",
238
558
  {
@@ -298,7 +618,7 @@ export class McpBrowserDevToolsServer {
298
618
  definition: {
299
619
  name: "inspect_element",
300
620
  description:
301
- "Inspect a single DOM element with a CSS selector and return normalized element details.",
621
+ "Inspect a single DOM element located by CSS, text=..., role=..., or name=... syntax and return normalized element details.",
302
622
  inputSchema: {
303
623
  type: "object",
304
624
  properties: {
@@ -322,7 +642,8 @@ export class McpBrowserDevToolsServer {
322
642
  {
323
643
  definition: {
324
644
  name: "take_screenshot",
325
- description: "Capture a screenshot from an attached page.",
645
+ description:
646
+ "Capture a screenshot from an attached page or a single element when selector is provided.",
326
647
  inputSchema: {
327
648
  type: "object",
328
649
  properties: {
@@ -333,6 +654,9 @@ export class McpBrowserDevToolsServer {
333
654
  type: "string",
334
655
  enum: screenshotFormatsFor(this.config.browserFamily),
335
656
  },
657
+ selector: {
658
+ type: "string",
659
+ },
336
660
  },
337
661
  required: ["sessionId"],
338
662
  additionalProperties: false,
@@ -342,6 +666,9 @@ export class McpBrowserDevToolsServer {
342
666
  this.browserAdapter.takeScreenshot(
343
667
  args.sessionId,
344
668
  args.format ?? "png",
669
+ {
670
+ selector: args.selector,
671
+ },
345
672
  ),
346
673
  },
347
674
  ],
@@ -417,7 +744,16 @@ export class McpBrowserDevToolsServer {
417
744
  }
418
745
 
419
746
  start() {
747
+ let sawInput = false;
748
+
420
749
  this.input.on("data", (chunk) => {
750
+ sawInput = true;
751
+ if (DEBUG_STDIO_ENABLED) {
752
+ this.log(
753
+ `stdin chunk bytes=${chunk.length} preview="${formatChunkPreview(chunk)}"`,
754
+ );
755
+ }
756
+
421
757
  let messages;
422
758
  try {
423
759
  messages = this.messageBuffer.push(chunk);
@@ -431,6 +767,20 @@ export class McpBrowserDevToolsServer {
431
767
  }
432
768
  });
433
769
 
770
+ if (DEBUG_STDIO_ENABLED) {
771
+ this.input.on("end", () => {
772
+ this.log(`stdin ended after_input=${sawInput}`);
773
+ });
774
+
775
+ this.input.on("close", () => {
776
+ this.log(`stdin closed after_input=${sawInput}`);
777
+ });
778
+ }
779
+
780
+ if (typeof this.input.resume === "function") {
781
+ this.input.resume();
782
+ }
783
+
434
784
  this.log(
435
785
  `listening on stdio for MCP messages; browser=${this.config.browserFamily}`,
436
786
  );
@@ -446,7 +796,12 @@ export class McpBrowserDevToolsServer {
446
796
  return;
447
797
  }
448
798
 
449
- this.output.write(encodeMessage(response));
799
+ this.output.write(
800
+ encodeMessage(
801
+ response,
802
+ this.messageBuffer.transportMode ?? "content-length",
803
+ ),
804
+ );
450
805
  }
451
806
 
452
807
  async handleRequest(message) {
@@ -469,7 +824,7 @@ export class McpBrowserDevToolsServer {
469
824
  version: SERVER_VERSION,
470
825
  },
471
826
  instructions:
472
- "Use the browser tools to inspect tabs, console output, network activity, DOM structure, and specific elements across Chromium CDP or Firefox BiDi.",
827
+ "Use the browser tools to inspect tabs, console output, network activity, DOM structure, element state, screenshots, and page interactions across Chromium CDP or Firefox BiDi.",
473
828
  });
474
829
  case "notifications/initialized":
475
830
  return null;