mcp-browser-dev-tools 0.5.1 → 0.5.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.
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 and cost the least on average, while Playwright MCP cost less with four 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.3",
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();
@@ -75,9 +75,14 @@ const STATUS_PROBE_ATTEMPTS = 3;
75
75
 
76
76
  const LAUNCH_GRACE_MS = 30_000;
77
77
 
78
+ const INSTRUCTIONS =
79
+ "Start with attach_tab. To act, prefer run_steps: send the actions you already know, such as every field of a form, in one call.";
80
+
78
81
  // 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.
82
+ // nothing it acts on, so it is left out of what every turn pays for, and
83
+ // sessionId is not required, since a call without it uses the default
84
+ // session (see defaultSessionId). Calls are still validated against the full
85
+ // schema once the default is filled in.
81
86
  function advertisedDefinition(definition) {
82
87
  const strip = (value) => {
83
88
  if (Array.isArray(value)) {
@@ -94,7 +99,16 @@ function advertisedDefinition(definition) {
94
99
  .map(([key, item]) => [key, strip(item)]),
95
100
  );
96
101
  };
97
- return strip(definition);
102
+ const advertised = strip(definition);
103
+ const required = advertised.inputSchema?.required;
104
+ if (required?.includes("sessionId")) {
105
+ const rest = required.filter((name) => name !== "sessionId");
106
+ advertised.inputSchema = { ...advertised.inputSchema, required: rest };
107
+ if (rest.length === 0) {
108
+ delete advertised.inputSchema.required;
109
+ }
110
+ }
111
+ return advertised;
98
112
  }
99
113
 
100
114
  function sleep(ms) {
@@ -301,7 +315,11 @@ export class McpBrowserDevToolsServer {
301
315
  runTabsTool(this.tabRunner, stepTools, this.config.browserFamily),
302
316
  );
303
317
  if (hidden.size > 0) {
304
- tools.push(moreToolsTool(hidden, advertisedDefinition));
318
+ tools.push(
319
+ moreToolsTool(hidden, advertisedDefinition, (schema, args) =>
320
+ this.withDefaultSession(schema, args),
321
+ ),
322
+ );
305
323
  }
306
324
 
307
325
  return new Map(tools);
@@ -389,7 +407,12 @@ export class McpBrowserDevToolsServer {
389
407
  name: SERVER_NAME,
390
408
  version: SERVER_VERSION,
391
409
  },
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.`,
410
+ // One sentence: the rest of the guidance is in the tool
411
+ // descriptions. The Codex CLI appends a server's instructions to
412
+ // every one of its tools when the model lists them, so GPT
413
+ // models pay for 24 copies; Claude Code gives them more weight
414
+ // than a description, and without this one agents batched less.
415
+ instructions: INSTRUCTIONS,
393
416
  });
394
417
  case "notifications/initialized":
395
418
  return null;
@@ -414,6 +437,43 @@ export class McpBrowserDevToolsServer {
414
437
  }
415
438
  }
416
439
 
440
+ // A tool that needs a session and got none uses the tab attached last,
441
+ // while it is still attached, else the only attached tab. Leaving the id
442
+ // out saves the model writing it into every call.
443
+ withDefaultSession(schema, args) {
444
+ // Arguments that are not an object are left for validation to reject.
445
+ if (
446
+ !args ||
447
+ typeof args !== "object" ||
448
+ Array.isArray(args) ||
449
+ args.sessionId !== undefined ||
450
+ !schema?.required?.includes("sessionId")
451
+ ) {
452
+ return args;
453
+ }
454
+ return { ...args, sessionId: this.defaultSessionId() };
455
+ }
456
+
457
+ defaultSessionId() {
458
+ const sessions = this.browserAdapter.listSessions();
459
+ if (
460
+ this.lastAttachedSessionId &&
461
+ sessions.some(
462
+ (session) => session.sessionId === this.lastAttachedSessionId,
463
+ )
464
+ ) {
465
+ return this.lastAttachedSessionId;
466
+ }
467
+ if (sessions.length === 1) {
468
+ return sessions[0].sessionId;
469
+ }
470
+ throw new Error(
471
+ sessions.length === 0
472
+ ? "No tab is attached: call attach_tab first"
473
+ : `${sessions.length} tabs are attached and the one attached last is gone; pass the sessionId of one: ${sessions.map((session) => session.sessionId).join(", ")}`,
474
+ );
475
+ }
476
+
417
477
  async callTool(params = {}) {
418
478
  const startedAt = Date.now();
419
479
  let response = null;
@@ -432,7 +492,10 @@ export class McpBrowserDevToolsServer {
432
492
  );
433
493
  }
434
494
 
435
- const args = params.arguments ?? {};
495
+ const args = this.withDefaultSession(
496
+ tool.definition.inputSchema,
497
+ params.arguments ?? {},
498
+ );
436
499
  validateValue("arguments", args, tool.definition.inputSchema);
437
500
  tool.validate?.(args);
438
501
  const result = await tool.handler(args);
package/src/run-steps.mjs CHANGED
@@ -831,7 +831,7 @@ export function runStepsTool(runner) {
831
831
  {
832
832
  definition: {
833
833
  name: "run_steps",
834
- description: `Run session tools in order in one call: [{"tool":"type","arguments":{"selector":"ref=e3","text":"Ada"}},{"tool":"click","arguments":{"selector":"text=Save"}}]. Arguments omit sessionId. Also: sleep {ms}; if {condition, then, elseIf: [{condition, then}], else, timeoutMs}, which branches on wait_for fields, checked once or until one holds within timeoutMs; repeat {steps, until, max (default ${DEFAULT_REPEAT})}, which reruns steps until until holds. All steps are validated first. A step fails when it throws or reports found: false (not inspect_element); the batch stops there unless continueOnError and reports the page's controls. A batch with actions returns one changes for the whole batch. A step that reads the page after an action or navigation first waits for the page to settle, so it needs no sleep.`,
834
+ description: `Run session tools in order in one call; prefer it to separate calls for the actions you already know, such as every field of a form: [{"tool":"type","arguments":{"selector":"ref=e3","text":"Ada"}},{"tool":"click","arguments":{"selector":"text=Save"}}]. Arguments omit sessionId. Also: sleep {ms}; if {condition, then, elseIf: [{condition, then}], else, timeoutMs}, which branches on wait_for fields, checked once or until one holds within timeoutMs; repeat {steps, until, max (default ${DEFAULT_REPEAT})}, which reruns steps until until holds. All steps are validated first. A step fails when it throws or reports found: false (not inspect_element); the batch stops there unless continueOnError and reports the page's controls. A batch with actions returns one changes for the whole batch. A step that reads the page after an action or navigation first waits for the page to settle, so it needs no sleep.`,
835
835
  inputSchema: runStepsInputSchema(),
836
836
  },
837
837
  handler: async (args) => runner.runSteps(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
+ }
@@ -3,7 +3,7 @@ export function asToolResult(value) {
3
3
  content: [
4
4
  {
5
5
  type: "text",
6
- text: JSON.stringify(value, null, 2),
6
+ text: JSON.stringify(value),
7
7
  },
8
8
  ],
9
9
  structuredContent: value,
@@ -15,7 +15,7 @@ export function asImageToolResult({ value, images }) {
15
15
  content: [
16
16
  {
17
17
  type: "text",
18
- text: JSON.stringify(value, null, 2),
18
+ text: JSON.stringify(value),
19
19
  },
20
20
  ...images,
21
21
  ],
@@ -84,7 +84,7 @@ export function actionTools(server) {
84
84
  definition: {
85
85
  name: "click",
86
86
  description:
87
- "Click with real mouse input at an element's center (fails if something covers it) or at x, y. Accepts alert and confirm dialogs, dismisses prompts. Returns changes: what changed on the page.",
87
+ 'Click with real mouse input at an element\'s center (fails if something covers it) or at x, y. Accepts alert and confirm dialogs, dismisses prompts. Returns changes: what changed on the page. Locators in every tool are 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. Only refs reach into iframes.',
88
88
  inputSchema: sessionSchema(
89
89
  {
90
90
  selector: selectorProperty(),
@@ -180,7 +180,7 @@ export function browserTools(server) {
180
180
  definition: {
181
181
  name: "attach_tab",
182
182
  description:
183
- "Attach to a tab: returns the sessionId other tools take and the page's snapshot, as get_snapshot lists it, and buffers its console and network events from now on.",
183
+ "Start here: attach to a tab by its url, or a targetId from list_tabs or new_tab. Returns the page's snapshot, one line per visible heading and control with a ref such as e12 (f1e3 inside an iframe), and buffers the tab's console and network events from now on. Later calls without sessionId act on the tab attached last.",
184
184
  inputSchema: {
185
185
  type: "object",
186
186
  properties: {
@@ -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.
@@ -189,7 +189,7 @@ export function stateTools(server) {
189
189
  definition: {
190
190
  name: "wait_for",
191
191
  description:
192
- "Wait until every given condition holds, or the first of anyOf; at timeoutMs it fails with the last observed state. Selector checks scroll the element into view.",
192
+ "Wait until every given condition holds, or the first of anyOf; at timeoutMs it fails with the last observed state. Selector checks scroll the element into view. Actions already return what changed once the page settles, so wait only for something that comes later.",
193
193
  inputSchema: waitForInputSchema({
194
194
  expression: server.config.enableEvaluate,
195
195
  }),