mcp-browser-dev-tools 0.0.1-beta.2 → 0.0.1-beta.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.
@@ -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,
@@ -233,6 +277,278 @@ export class McpBrowserDevToolsServer {
233
277
  this.browserAdapter.detachSession(args.sessionId),
234
278
  },
235
279
  ],
280
+ [
281
+ "get_page_state",
282
+ {
283
+ definition: {
284
+ name: "get_page_state",
285
+ description:
286
+ "Return the current URL, title, ready state, viewport, and scroll positions for an attached page.",
287
+ inputSchema: sessionSchema({}, []),
288
+ },
289
+ handler: async (args) =>
290
+ this.browserAdapter.getPageState(args.sessionId),
291
+ },
292
+ ],
293
+ [
294
+ "navigate",
295
+ {
296
+ definition: {
297
+ name: "navigate",
298
+ description:
299
+ "Navigate an attached tab to a URL and optionally wait for interactive or complete load state.",
300
+ inputSchema: sessionSchema(
301
+ {
302
+ url: {
303
+ type: "string",
304
+ },
305
+ waitUntil: waitUntilProperty(),
306
+ },
307
+ ["url"],
308
+ ),
309
+ },
310
+ handler: async (args) =>
311
+ this.browserAdapter.navigate(args.sessionId, args.url, {
312
+ waitUntil: args.waitUntil,
313
+ }),
314
+ },
315
+ ],
316
+ [
317
+ "reload",
318
+ {
319
+ definition: {
320
+ name: "reload",
321
+ description:
322
+ "Reload the attached tab and optionally ignore cache while waiting for interactive or complete load state.",
323
+ inputSchema: sessionSchema(
324
+ {
325
+ ignoreCache: {
326
+ type: "boolean",
327
+ },
328
+ waitUntil: waitUntilProperty(),
329
+ },
330
+ [],
331
+ ),
332
+ },
333
+ handler: async (args) =>
334
+ this.browserAdapter.reload(args.sessionId, {
335
+ ignoreCache: args.ignoreCache,
336
+ waitUntil: args.waitUntil,
337
+ }),
338
+ },
339
+ ],
340
+ [
341
+ "click",
342
+ {
343
+ definition: {
344
+ name: "click",
345
+ description:
346
+ "Click a single element located by CSS, text=..., role=..., or name=... syntax.",
347
+ inputSchema: sessionSchema(
348
+ {
349
+ selector: {
350
+ type: "string",
351
+ },
352
+ },
353
+ ["selector"],
354
+ ),
355
+ },
356
+ handler: async (args) =>
357
+ this.browserAdapter.click(args.sessionId, args.selector),
358
+ },
359
+ ],
360
+ [
361
+ "hover",
362
+ {
363
+ definition: {
364
+ name: "hover",
365
+ description:
366
+ "Hover a single element located by CSS, text=..., role=..., or name=... syntax.",
367
+ inputSchema: sessionSchema(
368
+ {
369
+ selector: {
370
+ type: "string",
371
+ },
372
+ },
373
+ ["selector"],
374
+ ),
375
+ },
376
+ handler: async (args) =>
377
+ this.browserAdapter.hover(args.sessionId, args.selector),
378
+ },
379
+ ],
380
+ [
381
+ "type",
382
+ {
383
+ definition: {
384
+ name: "type",
385
+ description:
386
+ "Type text into an input, textarea, or contenteditable element.",
387
+ inputSchema: sessionSchema(
388
+ {
389
+ selector: {
390
+ type: "string",
391
+ },
392
+ text: {
393
+ type: "string",
394
+ },
395
+ clear: {
396
+ type: "boolean",
397
+ },
398
+ },
399
+ ["selector", "text"],
400
+ ),
401
+ },
402
+ handler: async (args) =>
403
+ this.browserAdapter.type(args.sessionId, args.selector, args.text, {
404
+ clear: args.clear,
405
+ }),
406
+ },
407
+ ],
408
+ [
409
+ "select",
410
+ {
411
+ definition: {
412
+ name: "select",
413
+ description:
414
+ "Select an option from a <select> by value or visible label.",
415
+ inputSchema: sessionSchema(
416
+ {
417
+ selector: {
418
+ type: "string",
419
+ },
420
+ value: {
421
+ type: "string",
422
+ },
423
+ label: {
424
+ type: "string",
425
+ },
426
+ },
427
+ ["selector"],
428
+ ),
429
+ },
430
+ handler: async (args) => {
431
+ if (!args.value && !args.label) {
432
+ throw new Error("select requires either value or label");
433
+ }
434
+
435
+ return this.browserAdapter.select(args.sessionId, args.selector, {
436
+ value: args.value,
437
+ label: args.label,
438
+ });
439
+ },
440
+ },
441
+ ],
442
+ [
443
+ "press_key",
444
+ {
445
+ definition: {
446
+ name: "press_key",
447
+ description:
448
+ "Dispatch a key press against the focused element or an optionally targeted element.",
449
+ inputSchema: sessionSchema(
450
+ {
451
+ key: {
452
+ type: "string",
453
+ },
454
+ selector: {
455
+ type: "string",
456
+ },
457
+ },
458
+ ["key"],
459
+ ),
460
+ },
461
+ handler: async (args) =>
462
+ this.browserAdapter.pressKey(
463
+ args.sessionId,
464
+ args.key,
465
+ args.selector,
466
+ ),
467
+ },
468
+ ],
469
+ [
470
+ "scroll",
471
+ {
472
+ definition: {
473
+ name: "scroll",
474
+ description:
475
+ "Scroll the page by deltas or scroll a specific element into view.",
476
+ inputSchema: sessionSchema(
477
+ {
478
+ selector: {
479
+ type: "string",
480
+ },
481
+ deltaX: {
482
+ type: "integer",
483
+ },
484
+ deltaY: {
485
+ type: "integer",
486
+ },
487
+ block: {
488
+ type: "string",
489
+ enum: ["start", "center", "end", "nearest"],
490
+ },
491
+ },
492
+ [],
493
+ ),
494
+ },
495
+ handler: async (args) => {
496
+ if (
497
+ !args.selector &&
498
+ args.deltaX === undefined &&
499
+ args.deltaY === undefined
500
+ ) {
501
+ throw new Error(
502
+ "scroll requires either selector or deltaX/deltaY values",
503
+ );
504
+ }
505
+
506
+ return this.browserAdapter.scroll(args.sessionId, {
507
+ selector: args.selector,
508
+ deltaX: args.deltaX,
509
+ deltaY: args.deltaY,
510
+ block: args.block,
511
+ });
512
+ },
513
+ },
514
+ ],
515
+ [
516
+ "set_viewport",
517
+ {
518
+ definition: {
519
+ name: "set_viewport",
520
+ description:
521
+ "Override the page viewport to a specific width and height for responsive debugging.",
522
+ inputSchema: sessionSchema(
523
+ {
524
+ width: {
525
+ type: "integer",
526
+ minimum: 1,
527
+ },
528
+ height: {
529
+ type: "integer",
530
+ minimum: 1,
531
+ },
532
+ deviceScaleFactor: {
533
+ type: "number",
534
+ minimum: 0.1,
535
+ },
536
+ mobile: {
537
+ type: "boolean",
538
+ },
539
+ },
540
+ ["width", "height"],
541
+ ),
542
+ },
543
+ handler: async (args) =>
544
+ this.browserAdapter.setViewport(args.sessionId, {
545
+ width: args.width,
546
+ height: args.height,
547
+ deviceScaleFactor: args.deviceScaleFactor,
548
+ mobile: args.mobile,
549
+ }),
550
+ },
551
+ ],
236
552
  [
237
553
  "get_console_messages",
238
554
  {
@@ -298,7 +614,7 @@ export class McpBrowserDevToolsServer {
298
614
  definition: {
299
615
  name: "inspect_element",
300
616
  description:
301
- "Inspect a single DOM element with a CSS selector and return normalized element details.",
617
+ "Inspect a single DOM element located by CSS, text=..., role=..., or name=... syntax and return normalized element details.",
302
618
  inputSchema: {
303
619
  type: "object",
304
620
  properties: {
@@ -322,7 +638,8 @@ export class McpBrowserDevToolsServer {
322
638
  {
323
639
  definition: {
324
640
  name: "take_screenshot",
325
- description: "Capture a screenshot from an attached page.",
641
+ description:
642
+ "Capture a screenshot from an attached page or a single element when selector is provided.",
326
643
  inputSchema: {
327
644
  type: "object",
328
645
  properties: {
@@ -333,6 +650,9 @@ export class McpBrowserDevToolsServer {
333
650
  type: "string",
334
651
  enum: screenshotFormatsFor(this.config.browserFamily),
335
652
  },
653
+ selector: {
654
+ type: "string",
655
+ },
336
656
  },
337
657
  required: ["sessionId"],
338
658
  additionalProperties: false,
@@ -342,6 +662,9 @@ export class McpBrowserDevToolsServer {
342
662
  this.browserAdapter.takeScreenshot(
343
663
  args.sessionId,
344
664
  args.format ?? "png",
665
+ {
666
+ selector: args.selector,
667
+ },
345
668
  ),
346
669
  },
347
670
  ],
@@ -417,7 +740,16 @@ export class McpBrowserDevToolsServer {
417
740
  }
418
741
 
419
742
  start() {
743
+ let sawInput = false;
744
+
420
745
  this.input.on("data", (chunk) => {
746
+ sawInput = true;
747
+ if (DEBUG_STDIO_ENABLED) {
748
+ this.log(
749
+ `stdin chunk bytes=${chunk.length} preview="${formatChunkPreview(chunk)}"`,
750
+ );
751
+ }
752
+
421
753
  let messages;
422
754
  try {
423
755
  messages = this.messageBuffer.push(chunk);
@@ -431,6 +763,20 @@ export class McpBrowserDevToolsServer {
431
763
  }
432
764
  });
433
765
 
766
+ if (DEBUG_STDIO_ENABLED) {
767
+ this.input.on("end", () => {
768
+ this.log(`stdin ended after_input=${sawInput}`);
769
+ });
770
+
771
+ this.input.on("close", () => {
772
+ this.log(`stdin closed after_input=${sawInput}`);
773
+ });
774
+ }
775
+
776
+ if (typeof this.input.resume === "function") {
777
+ this.input.resume();
778
+ }
779
+
434
780
  this.log(
435
781
  `listening on stdio for MCP messages; browser=${this.config.browserFamily}`,
436
782
  );
@@ -446,7 +792,12 @@ export class McpBrowserDevToolsServer {
446
792
  return;
447
793
  }
448
794
 
449
- this.output.write(encodeMessage(response));
795
+ this.output.write(
796
+ encodeMessage(
797
+ response,
798
+ this.messageBuffer.transportMode ?? "content-length",
799
+ ),
800
+ );
450
801
  }
451
802
 
452
803
  async handleRequest(message) {
@@ -469,7 +820,7 @@ export class McpBrowserDevToolsServer {
469
820
  version: SERVER_VERSION,
470
821
  },
471
822
  instructions:
472
- "Use the browser tools to inspect tabs, console output, network activity, DOM structure, and specific elements across Chromium CDP or Firefox BiDi.",
823
+ "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
824
  });
474
825
  case "notifications/initialized":
475
826
  return null;