mcp-browser-dev-tools 0.5.1 → 0.5.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.
package/README.md CHANGED
@@ -47,6 +47,8 @@ Your agent gets 46 browser tools over MCP: open or attach to tabs, click, type,
47
47
  - **Right where you work.** It attaches to the browser you already use, with its logins, tabs, and extensions, and speaks to Chrome, Edge, and Firefox with the same tools.
48
48
  - **A debugger at hand.** Console messages with stack traces, network requests and HAR export, cookies and storage, and a one-call debug report.
49
49
 
50
+ Against Playwright MCP and Chrome DevTools MCP, on the same tasks with six models, it took the fewest turns and the least time with every model, while Playwright MCP cost less with five of the six: see the [comparison](https://hinaser.github.io/mcp-browser-dev-tools/).
51
+
50
52
  ## One Call, Start To Finish
51
53
 
52
54
  A `run_steps` call that dismisses a cookie banner if one is showing, fills in and submits a form, waits for either the success or the error message, and reads it:
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mcp-browser-dev-tools",
3
- "version": "0.5.1",
3
+ "version": "0.5.2",
4
4
  "description": "Browser MCP server for AI agents: batch actions, waits, and checks into one call on Chrome, Edge, or Firefox (CDP and WebDriver BiDi)",
5
5
  "author": "Hinaser <rindo.hinase@gmail.com>",
6
6
  "license": "MIT",
@@ -42,6 +42,7 @@
42
42
  "src/package-info.mjs",
43
43
  "src/serve-bootstrap.mjs",
44
44
  "src/session-events.mjs",
45
+ "src/session-ids.mjs",
45
46
  "src/server.mjs",
46
47
  "src/tcp-relay.mjs",
47
48
  "src/top-level-await.mjs",
@@ -1,4 +1,5 @@
1
1
  import { mkdtemp, rm, writeFile } from "node:fs/promises";
2
+ import { newSessionId } from "./session-ids.mjs";
2
3
  import { tmpdir } from "node:os";
3
4
  import path from "node:path";
4
5
 
@@ -480,7 +481,7 @@ function videoGapWarnings(state) {
480
481
 
481
482
  export class CdpSession {
482
483
  constructor(target, options = {}) {
483
- this.id = crypto.randomUUID();
484
+ this.id = newSessionId();
484
485
  this.config = options.config ?? { browserFamily: "chromium" };
485
486
  this.target = target;
486
487
  this.eventBufferSize = options.eventBufferSize ?? 200;
@@ -4,6 +4,7 @@ import {
4
4
  InFlightRequests,
5
5
  summarizeNetworkRequests,
6
6
  } from "./session-events.mjs";
7
+ import { newSessionId } from "./session-ids.mjs";
7
8
  import { DEFAULT_FIREFOX_BIDI_WS_URL } from "./config.mjs";
8
9
  import {
9
10
  answerDialog,
@@ -440,7 +441,7 @@ function joinUrlPath(baseUrl, pathname) {
440
441
 
441
442
  class FirefoxBidiTabSession {
442
443
  constructor(target, options = {}) {
443
- this.id = crypto.randomUUID();
444
+ this.id = newSessionId();
444
445
  this.target = target;
445
446
  this.eventBufferSize = options.eventBufferSize ?? 200;
446
447
  this.connectedAt = new Date().toISOString();
@@ -76,8 +76,10 @@ const STATUS_PROBE_ATTEMPTS = 3;
76
76
  const LAUNCH_GRACE_MS = 30_000;
77
77
 
78
78
  // The definition clients see: additionalProperties: false tells a model
79
- // nothing it acts on, so it is left out of what every turn pays for. Calls
80
- // are still validated against the full schema.
79
+ // nothing it acts on, so it is left out of what every turn pays for, and
80
+ // sessionId is not required, since a call without it uses the default
81
+ // session (see defaultSessionId). Calls are still validated against the full
82
+ // schema once the default is filled in.
81
83
  function advertisedDefinition(definition) {
82
84
  const strip = (value) => {
83
85
  if (Array.isArray(value)) {
@@ -94,7 +96,16 @@ function advertisedDefinition(definition) {
94
96
  .map(([key, item]) => [key, strip(item)]),
95
97
  );
96
98
  };
97
- return strip(definition);
99
+ const advertised = strip(definition);
100
+ const required = advertised.inputSchema?.required;
101
+ if (required?.includes("sessionId")) {
102
+ const rest = required.filter((name) => name !== "sessionId");
103
+ advertised.inputSchema = { ...advertised.inputSchema, required: rest };
104
+ if (rest.length === 0) {
105
+ delete advertised.inputSchema.required;
106
+ }
107
+ }
108
+ return advertised;
98
109
  }
99
110
 
100
111
  function sleep(ms) {
@@ -301,7 +312,11 @@ export class McpBrowserDevToolsServer {
301
312
  runTabsTool(this.tabRunner, stepTools, this.config.browserFamily),
302
313
  );
303
314
  if (hidden.size > 0) {
304
- tools.push(moreToolsTool(hidden, advertisedDefinition));
315
+ tools.push(
316
+ moreToolsTool(hidden, advertisedDefinition, (schema, args) =>
317
+ this.withDefaultSession(schema, args),
318
+ ),
319
+ );
305
320
  }
306
321
 
307
322
  return new Map(tools);
@@ -389,7 +404,7 @@ export class McpBrowserDevToolsServer {
389
404
  name: SERVER_NAME,
390
405
  version: SERVER_VERSION,
391
406
  },
392
- instructions: `Browser tools for Chromium (CDP) and Firefox (BiDi). Start with attach_tab, by the tab's url or a targetId from list_tabs or new_tab: it returns the sessionId other tools take and the page's snapshot, one line per visible heading and control (iframes too) with a ref such as e12 or f1e3. get_snapshot reads the page again, far cheaper than a screenshot. To act, prefer run_steps: send the actions you already know, such as every field of a form, in one call: {"sessionId":"<id>","steps":[{"tool":"type","arguments":{"selector":"ref=e3","text":"Ada"}},{"tool":"click","arguments":{"selector":"ref=e4"}}]}. Actions return what changed once the page settles (controls, new text such as a toast, URL, console errors, a new page's snapshot); that is usually the check, so add wait_for only for something later. Read several pages at once with run_tabs and read_text. Locators: ref=e12, until the page navigates; CSS, the first match; text=Foo and name=Foo, the first visible element whose text, or accessible name, equals, else contains, Foo (a label finds its control); role=button[name="Save"], by role and accessible name; a >> b, b inside a; has-text=Foo filters: tr >> has-text=Ada >> text=Delete. Case-sensitive; only refs reach into iframes. more_tools lists and calls the other tools (drag, cookies, request mocking, HAR, performance); they also work as run_steps steps.`,
407
+ instructions: `Start with attach_tab, by the tab's url or a targetId from list_tabs or new_tab: it returns the page's snapshot, one line per visible heading and control with a ref such as e12 (f1e3 inside an iframe, which only refs reach). Tools then act on the tab attached last unless given another sessionId. To act, prefer run_steps: send the actions you already know, such as every field of a form, in one call: {"steps":[{"tool":"type","arguments":{"selector":"ref=e3","text":"Ada"}},{"tool":"click","arguments":{"selector":"ref=e4"}}]}. Actions return what changed once the page settles, which is usually the check; add wait_for only for something later. Read several pages at once with run_tabs. Locators, case-sensitive: ref=e12 until the page navigates; CSS; text=Foo and name=Foo, the first visible element whose text or accessible name equals, else contains, Foo (a label finds its control); role=button[name="Save"]; a >> b for b inside a, and has-text=Foo to filter: tr >> has-text=Ada >> text=Delete. more_tools lists and calls the other tools (drag, cookies, request mocking, HAR, performance).`,
393
408
  });
394
409
  case "notifications/initialized":
395
410
  return null;
@@ -414,6 +429,43 @@ export class McpBrowserDevToolsServer {
414
429
  }
415
430
  }
416
431
 
432
+ // A tool that needs a session and got none uses the tab attached last,
433
+ // while it is still attached, else the only attached tab. Leaving the id
434
+ // out saves the model writing it into every call.
435
+ withDefaultSession(schema, args) {
436
+ // Arguments that are not an object are left for validation to reject.
437
+ if (
438
+ !args ||
439
+ typeof args !== "object" ||
440
+ Array.isArray(args) ||
441
+ args.sessionId !== undefined ||
442
+ !schema?.required?.includes("sessionId")
443
+ ) {
444
+ return args;
445
+ }
446
+ return { ...args, sessionId: this.defaultSessionId() };
447
+ }
448
+
449
+ defaultSessionId() {
450
+ const sessions = this.browserAdapter.listSessions();
451
+ if (
452
+ this.lastAttachedSessionId &&
453
+ sessions.some(
454
+ (session) => session.sessionId === this.lastAttachedSessionId,
455
+ )
456
+ ) {
457
+ return this.lastAttachedSessionId;
458
+ }
459
+ if (sessions.length === 1) {
460
+ return sessions[0].sessionId;
461
+ }
462
+ throw new Error(
463
+ sessions.length === 0
464
+ ? "No tab is attached: call attach_tab first"
465
+ : `${sessions.length} tabs are attached and the one attached last is gone; pass the sessionId of one: ${sessions.map((session) => session.sessionId).join(", ")}`,
466
+ );
467
+ }
468
+
417
469
  async callTool(params = {}) {
418
470
  const startedAt = Date.now();
419
471
  let response = null;
@@ -432,7 +484,10 @@ export class McpBrowserDevToolsServer {
432
484
  );
433
485
  }
434
486
 
435
- const args = params.arguments ?? {};
487
+ const args = this.withDefaultSession(
488
+ tool.definition.inputSchema,
489
+ params.arguments ?? {},
490
+ );
436
491
  validateValue("arguments", args, tool.definition.inputSchema);
437
492
  tool.validate?.(args);
438
493
  const result = await tool.handler(args);
@@ -0,0 +1,26 @@
1
+ // Session ids go into nearly every tool call an agent writes, and the tokens
2
+ // a model writes cost the most, so they are short: "s" and seven base-36
3
+ // characters, unique within the process. A stale id from an earlier process
4
+ // is very unlikely to name a live session.
5
+ const ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz";
6
+ const LENGTH = 7;
7
+ const issued = new Set();
8
+
9
+ export function newSessionId() {
10
+ for (;;) {
11
+ let id = "s";
12
+ while (id.length <= LENGTH) {
13
+ for (const byte of crypto.getRandomValues(new Uint8Array(LENGTH))) {
14
+ // 252 is the largest multiple of 36 below 256, so every character
15
+ // is equally likely.
16
+ if (byte < 252 && id.length <= LENGTH) {
17
+ id += ALPHABET[byte % 36];
18
+ }
19
+ }
20
+ }
21
+ if (!issued.has(id)) {
22
+ issued.add(id);
23
+ return id;
24
+ }
25
+ }
26
+ }
@@ -234,6 +234,7 @@ async function attachTab(server, { targetId, url }) {
234
234
  const session = await server.browserAdapter.attachToTarget(
235
235
  targetId ?? (await tabForUrl(server, url)),
236
236
  );
237
+ server.lastAttachedSessionId = session.sessionId;
237
238
  const settled = await settleAfterAttach(server, session.sessionId);
238
239
  try {
239
240
  const snapshot = await server.browserAdapter.snapshotPage(
@@ -21,7 +21,7 @@ function firstSentence(text) {
21
21
  // lists them, describes one, or calls one, so an agent can find and use a
22
22
  // tool without every turn paying for its definition. run_steps and
23
23
  // run_tabs steps can use them too.
24
- export function moreToolsTool(hidden, advertise) {
24
+ export function moreToolsTool(hidden, advertise, withDefaultSession) {
25
25
  const lookup = (name) => {
26
26
  const tool = hidden.get(name);
27
27
  if (!tool) {
@@ -72,13 +72,17 @@ export function moreToolsTool(hidden, advertise) {
72
72
  group: groupOf(args.name),
73
73
  };
74
74
  }
75
+ const toolArgs = withDefaultSession(
76
+ tool.definition.inputSchema,
77
+ args.arguments,
78
+ );
75
79
  validateValue(
76
80
  "arguments.arguments",
77
- args.arguments,
81
+ toolArgs,
78
82
  tool.definition.inputSchema,
79
83
  );
80
- tool.validate?.(args.arguments);
81
- return tool.handler(args.arguments, options);
84
+ tool.validate?.(toolArgs);
85
+ return tool.handler(toolArgs, options);
82
86
  },
83
87
  // A call's result is formatted as the tool itself would format it;
84
88
  // the list goes as one line per tool, which costs less than JSON.