mcp-browser-dev-tools 0.0.6 → 0.1.0

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
@@ -16,9 +16,10 @@ It is designed for a local trust boundary:
16
16
  - Tab lifecycle tools to create and close browser tabs through MCP
17
17
  - Inspection tools for DOM lookup, richer element details, cookies, storage, console messages, network requests, HAR-like exports, screenshots, tab listing, and buffered events
18
18
  - Page interaction tools for navigation, reload, click, hover, type, select, key presses, scroll, and viewport overrides
19
- - Wait conditions for selector visibility, URL changes, and document ready state
19
+ - Wait conditions for selector visibility, element text, URL changes, and document ready state
20
+ - Batched steps that run several actions and checks in one call, with `if`/`else` branches on the page state
20
21
  - One-shot debug bundle capture for page state, storage summary, recent console, recent network, and screenshots
21
- - Optional JavaScript evaluation behind an explicit environment flag
22
+ - JavaScript evaluation in the page, on by default and removable with an environment flag
22
23
  - Helper commands to check browser connectivity, launch a debug-enabled browser, and relay CDP traffic across a local machine boundary
23
24
 
24
25
  ## Requirements
@@ -208,11 +209,11 @@ Manual Windows browser relay into WSL:
208
209
 
209
210
  If you only want a single CDP browser, switch `MCP_BROWSER_FAMILY` back to `chromium` or `edge` and omit `FIREFOX_BIDI_WS_URL`.
210
211
 
211
- Enable `evaluate_js`:
212
+ Disable `evaluate_js`:
212
213
 
213
214
  ```json
214
215
  {
215
- "MCP_BROWSER_ENABLE_EVAL": "1"
216
+ "MCP_BROWSER_ENABLE_EVAL": "0"
216
217
  }
217
218
  ```
218
219
 
@@ -236,7 +237,8 @@ If you use WSL with a Windows Chrome or Edge browser, prefer `serve --bootstrap-
236
237
  - `MCP_BROWSER_EVENT_BUFFER_SIZE` sets the per-session buffered event limit
237
238
  - `MCP_BROWSER_LOG_LEVEL` controls diagnostic logging to `stderr`: `error`, `warn`, `info`, or `debug`
238
239
  - `MCP_BROWSER_DEBUG_STDIO=1` emits raw MCP stdio transport diagnostics to `stderr`
239
- - `MCP_BROWSER_ENABLE_EVAL=1` enables `evaluate_js`
240
+ - `MCP_BROWSER_TIMING_LOG` names a file that gets one JSON line per tool call with the tool name, duration, success, and response size (text characters and image count); the benchmark in `PERFORMANCE.md` uses it
241
+ - `MCP_BROWSER_ENABLE_EVAL=0` (or `false`) disables `evaluate_js`, which is enabled by default
240
242
  - `MCP_BROWSER_ENABLE_UNSAFE_LAUNCH_ARGS=1` exposes the `unsafeArgs` launch option on `launch_browser` and `ensure_browser`
241
243
  - `MCP_BROWSER_ALLOW_REMOTE_ENDPOINTS=1` allows non-loopback CDP or BiDi endpoints
242
244
  - `MCP_BROWSER_ALLOW_REMOTE_CDP=1` is still accepted as a legacy alias
@@ -292,10 +294,11 @@ If you use WSL with a Windows Chrome or Edge browser, prefer `serve --bootstrap-
292
294
  - `inspect_element`
293
295
  - `take_screenshot`
294
296
  - `get_events`
297
+ - `run_steps`
295
298
 
296
- `evaluate_js` is intentionally disabled by default. Enable it only when you want the broker to allow page-side code execution.
299
+ `evaluate_js` is enabled by default, as page evaluation is in most browser MCP servers. Set `MCP_BROWSER_ENABLE_EVAL=0` to remove it from the tool list. Treat that as a way to narrow the tool surface, not as a security boundary: the other tools already read page content, cookies, and storage and can navigate anywhere, and any local process that reaches the debugging port can evaluate code through the browser protocol directly. To control page-side code execution per call, use your MCP client's tool permissions.
297
300
 
298
- Unsafe browser launch flags are also disabled by default. If you enable `MCP_BROWSER_ENABLE_UNSAFE_LAUNCH_ARGS=1`, pass only full flag strings such as `--remote-allow-origins=http://localhost:9222`. This does not enable `evaluate_js`, and it still does not let callers replace broker-managed launch flags like `--remote-debugging-port` or `--user-data-dir`.
301
+ Unsafe browser launch flags are also disabled by default. If you enable `MCP_BROWSER_ENABLE_UNSAFE_LAUNCH_ARGS=1`, pass only full flag strings such as `--remote-allow-origins=http://localhost:9222`. It still does not let callers replace broker-managed launch flags like `--remote-debugging-port` or `--user-data-dir`.
299
302
 
300
303
  For tools that take `sessionId`, call `attach_tab` first and reuse the returned session.
301
304
 
@@ -314,6 +317,50 @@ Interaction and inspection tools accept these locator forms:
314
317
 
315
318
  `take_screenshot` returns base64 image data plus metadata such as `mimeType`, `byteLength`, and `scope`. Pass `selector` to capture a single element instead of the full page.
316
319
 
320
+ `output` changes how the image comes back. `image` returns an MCP image content block, with only the metadata in the JSON. `file` writes the decoded image to a file and returns its `path` instead of base64 data; passing `path` implies `file`. `path` must be absolute and end in `.png`, `.jpg`, `.jpeg`, or `.webp` (not `.webp` on Firefox), which also sets the format; missing parent directories are created. An existing file is only replaced with `overwrite: true`, and a symlink at `path` is replaced rather than written through. Without `path`, the image goes to a new private directory under the system temp directory. Files are created readable only by the current user. Without `output` or `path`, `take_screenshot` returns base64 data as before.
321
+
322
+ ### Batched Steps
323
+
324
+ `run_steps` runs several session tools in order in one call, so an action and the check of its result take one round trip instead of several:
325
+
326
+ ```json
327
+ {
328
+ "sessionId": "chromium:session-1",
329
+ "steps": [
330
+ { "tool": "click", "arguments": { "selector": "text=Save" } },
331
+ { "tool": "sleep", "arguments": { "ms": 300 } },
332
+ { "tool": "take_screenshot" }
333
+ ]
334
+ }
335
+ ```
336
+
337
+ Any tool that takes `sessionId` can be a step, with its arguments minus `sessionId`, plus `sleep` (`ms`, at most 30000). Up to 50 steps are validated before any of them runs. A step fails when its tool throws or reports `found: false` for a missing element (`inspect_element` excepted, since it may be checking that an element is gone). The call stops at the first failing step unless `continueOnError` is true, and reports each step's result or error. Screenshots come back as image content blocks instead of base64 text; the step result keeps the metadata and an `image` field with the 1-based position of its image.
338
+
339
+ An `if` step branches on the page state without a round trip back to the client:
340
+
341
+ ```json
342
+ {
343
+ "tool": "if",
344
+ "arguments": {
345
+ "condition": { "selector": "#status", "textIncludes": "failed" },
346
+ "then": [{ "tool": "click", "arguments": { "selector": "text=Retry" } }],
347
+ "elseIf": [
348
+ {
349
+ "condition": { "urlIncludes": "/login" },
350
+ "then": [
351
+ { "tool": "take_screenshot", "arguments": { "output": "image" } }
352
+ ]
353
+ }
354
+ ],
355
+ "else": [{ "tool": "get_page_state" }]
356
+ }
357
+ }
358
+ ```
359
+
360
+ Each condition takes the same fields as `wait_for` (`selector` with `state`, `textEquals`, `textIncludes`, plus `url`, `urlIncludes`, `readyState`), and all given fields must hold. `condition` and then each `elseIf` entry are checked in order, once and without waiting, and the first one that holds runs its `then`; `else` runs when none does. Put a `wait_for` or `sleep` step first if the page may still be changing. Every branch is validated up front, the 50-step limit counts steps inside branches, and an `if` placed inside a branch nests at most 4 levels deep. The `if` result reports the `branch` taken (`then`, `elseIf[i]`, or `else`), each condition it `checked` with what was observed (URL, whether the element was found and visible, its text), and the branch's step results; a failing step inside a branch fails the `if` and stops the batch like any other step.
361
+
362
+ Text conditions compare the element's visible text with whitespace collapsed, and only its first 400 characters are read: `textIncludes` does not see text past that point, and `textEquals` never matches an element with longer text.
363
+
317
364
  ### Session Snapshots
318
365
 
319
366
  - `get_cookies` returns bounded page-visible cookies from the attached page context
@@ -339,7 +386,7 @@ Playwright is still the stronger choice for deterministic browser automation and
339
386
 
340
387
  - it is MCP-native, so AI clients call a bounded tool surface instead of generating and executing Playwright scripts
341
388
  - it can inspect an already-open browser tab or create a fresh one, then inspect the current session state, cookies, login state, extensions, console, and network history
342
- - it is designed for local AI debugging workflows, including loopback-only defaults, opt-in evaluation, and the Windows-to-WSL relay path
389
+ - it is designed for local AI debugging workflows, including loopback-only defaults and the Windows-to-WSL relay path
343
390
  - it presents one MCP interface across Chromium CDP and Firefox BiDi instead of requiring the AI client to know browser protocol details
344
391
 
345
392
  Use Playwright when you want reproducible automation. Use this project when you want an AI assistant to inspect and manipulate a live browser session through MCP.
@@ -354,8 +401,8 @@ Use Playwright when you want reproducible automation. Use this project when you
354
401
  ## Safety Defaults
355
402
 
356
403
  - The broker only allows loopback browser endpoints unless you opt in
357
- - The default tool surface is read-focused
358
- - Arbitrary page evaluation is opt-in
404
+ - Tools can both read and act on the page: they click, type, navigate, and run page JavaScript through `evaluate_js`, using whatever session the browser profile is signed in to, so point the broker at a profile you are willing to let an agent use
405
+ - `evaluate_js` can be removed from the tool surface with `MCP_BROWSER_ENABLE_EVAL=0`
359
406
  - Clients interact with a bounded MCP tool surface instead of raw browser protocol calls
360
407
 
361
408
  ## Development
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "mcp-browser-dev-tools",
3
- "version": "0.0.6",
3
+ "version": "0.1.0",
4
4
  "description": "Local MCP server for Chromium DevTools Protocol and Firefox WebDriver BiDi",
5
5
  "author": "Hinaser <rindo.hinase@gmail.com>",
6
6
  "license": "MIT",
@@ -75,6 +75,8 @@
75
75
  "check": "node --run lint && node --run format:check && node --run test",
76
76
  "prepare": "husky",
77
77
  "pack:check": "node scripts/pack-check.mjs",
78
+ "bench": "node bench/run.mjs",
79
+ "bench:summary": "node bench/summarize.mjs",
78
80
  "prepublishOnly": "node --run check",
79
81
  "test": "node --test"
80
82
  },
package/src/config.mjs CHANGED
@@ -41,6 +41,10 @@ export function isTruthyFlag(value) {
41
41
  return value === "1" || value === "true";
42
42
  }
43
43
 
44
+ export function isFalsyFlag(value) {
45
+ return value === "0" || value === "false";
46
+ }
47
+
44
48
  export function isLoopbackOrigin(value) {
45
49
  const url = new URL(value);
46
50
  return isLoopbackHost(url.hostname);
@@ -114,7 +118,7 @@ export function loadConfig(env = process.env) {
114
118
  firefoxBidiWsUrl,
115
119
  allowRemoteEndpoints,
116
120
  allowRemoteCdp: allowRemoteEndpoints,
117
- enableEvaluate: isTruthyFlag(env.MCP_BROWSER_ENABLE_EVAL),
121
+ enableEvaluate: !isFalsyFlag(env.MCP_BROWSER_ENABLE_EVAL),
118
122
  enableUnsafeLaunchArgs: isTruthyFlag(
119
123
  env.MCP_BROWSER_ENABLE_UNSAFE_LAUNCH_ARGS,
120
124
  ),
@@ -126,6 +130,7 @@ export function loadConfig(env = process.env) {
126
130
  debugStdio: logging.debugStdio,
127
131
  logFile: logging.logFile,
128
132
  userDataDir: env.MCP_BROWSER_USER_DATA_DIR?.trim() || null,
133
+ timingLogFile: env.MCP_BROWSER_TIMING_LOG?.trim() || null,
129
134
  protocolVersion:
130
135
  env.MCP_PROTOCOL_VERSION?.trim() || DEFAULT_PROTOCOL_VERSION,
131
136
  };
@@ -1,10 +1,24 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import {
3
+ appendFile,
4
+ mkdir,
5
+ mkdtemp,
6
+ rename,
7
+ rm,
8
+ writeFile,
9
+ } from "node:fs/promises";
10
+ import { tmpdir } from "node:os";
11
+ import path from "node:path";
12
+
1
13
  import { encodeMessage, MessageBuffer } from "./json-rpc-stdio.mjs";
14
+ import { parseKeyCombo } from "./keyboard.mjs";
2
15
  import { createLogger } from "./logger.mjs";
3
16
  import {
4
17
  launchBrowser as launchLocalBrowser,
5
18
  supportedLaunchFamilies,
6
19
  } from "./browser-launch-service.mjs";
7
20
  import { PACKAGE_NAME, PACKAGE_VERSION } from "./package-info.mjs";
21
+ import { checkPageCondition, normalizeWaitForOptions } from "./wait-for.mjs";
8
22
 
9
23
  const SERVER_NAME = PACKAGE_NAME;
10
24
  const SERVER_VERSION = PACKAGE_VERSION;
@@ -49,6 +63,19 @@ function asToolResult(value) {
49
63
  };
50
64
  }
51
65
 
66
+ function asImageToolResult({ value, images }) {
67
+ return {
68
+ content: [
69
+ {
70
+ type: "text",
71
+ text: JSON.stringify(value, null, 2),
72
+ },
73
+ ...images,
74
+ ],
75
+ structuredContent: value,
76
+ };
77
+ }
78
+
52
79
  function emptyObjectSchema() {
53
80
  return {
54
81
  type: "object",
@@ -88,6 +115,28 @@ function validateValue(path, value, schema) {
88
115
  return;
89
116
  }
90
117
 
118
+ if (schema.type === "array") {
119
+ if (!Array.isArray(value)) {
120
+ throw new Error(`${path} must be an array`);
121
+ }
122
+
123
+ if (schema.minItems !== undefined && value.length < schema.minItems) {
124
+ throw new Error(`${path} must have at least ${schema.minItems} items`);
125
+ }
126
+
127
+ if (schema.maxItems !== undefined && value.length > schema.maxItems) {
128
+ throw new Error(`${path} must have at most ${schema.maxItems} items`);
129
+ }
130
+
131
+ if (schema.items) {
132
+ value.forEach((item, index) => {
133
+ validateValue(`${path}[${index}]`, item, schema.items);
134
+ });
135
+ }
136
+
137
+ return;
138
+ }
139
+
91
140
  if (schema.type === "string") {
92
141
  if (typeof value !== "string") {
93
142
  throw new Error(`${path} must be a string`);
@@ -117,6 +166,10 @@ function validateValue(path, value, schema) {
117
166
  throw new Error(`${path} must be >= ${schema.minimum}`);
118
167
  }
119
168
 
169
+ if (schema.maximum !== undefined && value > schema.maximum) {
170
+ throw new Error(`${path} must be <= ${schema.maximum}`);
171
+ }
172
+
120
173
  return;
121
174
  }
122
175
 
@@ -137,6 +190,109 @@ function screenshotFormatsFor(browserFamily) {
137
190
  : ["png", "jpeg", "webp"];
138
191
  }
139
192
 
193
+ const SCREENSHOT_FILE_FORMATS = {
194
+ ".png": "png",
195
+ ".jpg": "jpeg",
196
+ ".jpeg": "jpeg",
197
+ ".webp": "webp",
198
+ };
199
+
200
+ function screenshotFileExtensions(browserFamily) {
201
+ const allowed = screenshotFormatsFor(browserFamily);
202
+ return Object.entries(SCREENSHOT_FILE_FORMATS)
203
+ .filter(([, format]) => allowed.includes(format))
204
+ .map(([extension]) => extension);
205
+ }
206
+
207
+ // Only image extensions are accepted, so a screenshot path can never replace
208
+ // a config file or script.
209
+ function screenshotTarget(args, browserFamily) {
210
+ const output = args.output ?? (args.path === undefined ? "data" : "file");
211
+ if (output !== "file") {
212
+ if (args.path !== undefined || args.overwrite !== undefined) {
213
+ throw new Error(
214
+ `take_screenshot path and overwrite require output file, not ${output}`,
215
+ );
216
+ }
217
+ return { output, format: args.format ?? "png", filePath: null };
218
+ }
219
+
220
+ if (args.path === undefined) {
221
+ return { output, format: args.format ?? "png", filePath: null };
222
+ }
223
+
224
+ if (!path.isAbsolute(args.path)) {
225
+ throw new Error("take_screenshot path must be absolute");
226
+ }
227
+
228
+ const format = SCREENSHOT_FILE_FORMATS[path.extname(args.path).toLowerCase()];
229
+ if (!format || !screenshotFormatsFor(browserFamily).includes(format)) {
230
+ throw new Error(
231
+ `take_screenshot path must end with ${screenshotFileExtensions(browserFamily).join(", ")}`,
232
+ );
233
+ }
234
+
235
+ if (args.format !== undefined && args.format !== format) {
236
+ throw new Error(
237
+ `take_screenshot format ${args.format} does not match the ${format} path extension`,
238
+ );
239
+ }
240
+
241
+ return { output, format, filePath: args.path };
242
+ }
243
+
244
+ // Screenshots can show signed-in pages, so files are private to the user.
245
+ const SCREENSHOT_FILE_MODE = 0o600;
246
+
247
+ async function writeTempScreenshot(image, format) {
248
+ // mkdtemp makes a fresh 0700 directory, which other users on a shared /tmp
249
+ // cannot pre-create or read.
250
+ const dir = await mkdtemp(path.join(tmpdir(), "mcp-browser-dev-tools-"));
251
+ const filePath = path.join(
252
+ dir,
253
+ `screenshot.${format === "jpeg" ? "jpg" : format}`,
254
+ );
255
+ await writeFile(filePath, image, { flag: "wx", mode: SCREENSHOT_FILE_MODE });
256
+ return filePath;
257
+ }
258
+
259
+ async function writeScreenshotFile(filePath, image, overwrite) {
260
+ await mkdir(path.dirname(filePath), { recursive: true });
261
+ if (!overwrite) {
262
+ // O_EXCL also refuses an existing symlink instead of following it.
263
+ try {
264
+ await writeFile(filePath, image, {
265
+ flag: "wx",
266
+ mode: SCREENSHOT_FILE_MODE,
267
+ });
268
+ } catch (error) {
269
+ if (error.code === "EEXIST") {
270
+ throw new Error(
271
+ `${filePath} already exists; pass overwrite: true to replace it`,
272
+ { cause: error },
273
+ );
274
+ }
275
+ throw error;
276
+ }
277
+ return filePath;
278
+ }
279
+
280
+ // Renaming a new file into place replaces a symlink at filePath rather
281
+ // than writing through it to a file without an image extension.
282
+ const tempPath = `${filePath}.${randomUUID()}.tmp`;
283
+ try {
284
+ await writeFile(tempPath, image, {
285
+ flag: "wx",
286
+ mode: SCREENSHOT_FILE_MODE,
287
+ });
288
+ await rename(tempPath, filePath);
289
+ } catch (error) {
290
+ await rm(tempPath, { force: true });
291
+ throw error;
292
+ }
293
+ return filePath;
294
+ }
295
+
140
296
  function sessionWithLimitSchema(description) {
141
297
  return {
142
298
  type: "object",
@@ -193,6 +349,41 @@ function waitUntilProperty() {
193
349
  };
194
350
  }
195
351
 
352
+ function pageConditionProperties() {
353
+ return {
354
+ selector: selectorProperty(),
355
+ state: {
356
+ type: "string",
357
+ enum: ["present", "visible", "hidden"],
358
+ description:
359
+ "Selector state (default visible). present: in the DOM. hidden: absent or not visible. Requires selector.",
360
+ },
361
+ url: {
362
+ type: "string",
363
+ description: "The page URL equals this string exactly.",
364
+ },
365
+ urlIncludes: {
366
+ type: "string",
367
+ description: "The page URL contains this string.",
368
+ },
369
+ readyState: {
370
+ type: "string",
371
+ enum: ["interactive", "complete"],
372
+ description: "document.readyState has reached this state or later.",
373
+ },
374
+ textEquals: {
375
+ type: "string",
376
+ description:
377
+ "The selector's visible text equals this string, comparing with whitespace collapsed; only the first 400 characters of the element's text are read, so textEquals never matches longer text. Requires selector; not with state hidden.",
378
+ },
379
+ textIncludes: {
380
+ type: "string",
381
+ description:
382
+ "The selector's visible text contains this string, comparing with whitespace collapsed; only the first 400 characters of the element's text are searched. Requires selector; not with state hidden.",
383
+ },
384
+ };
385
+ }
386
+
196
387
  function waitForInputSchema() {
197
388
  return {
198
389
  type: "object",
@@ -201,27 +392,7 @@ function waitForInputSchema() {
201
392
  type: "string",
202
393
  description: "Session id returned by attach_tab.",
203
394
  },
204
- selector: selectorProperty(),
205
- state: {
206
- type: "string",
207
- enum: ["present", "visible", "hidden"],
208
- description:
209
- "Selector state to wait for (default visible). present: in the DOM. hidden: absent or not visible. Requires selector.",
210
- },
211
- url: {
212
- type: "string",
213
- description: "Wait until the page URL equals this string exactly.",
214
- },
215
- urlIncludes: {
216
- type: "string",
217
- description: "Wait until the page URL contains this string.",
218
- },
219
- readyState: {
220
- type: "string",
221
- enum: ["interactive", "complete"],
222
- description:
223
- "Wait until document.readyState reaches this state or later.",
224
- },
395
+ ...pageConditionProperties(),
225
396
  timeoutMs: {
226
397
  type: "integer",
227
398
  minimum: 1,
@@ -238,6 +409,149 @@ function waitForInputSchema() {
238
409
  };
239
410
  }
240
411
 
412
+ const MAX_RUN_STEPS = 50;
413
+ const MAX_STEP_DEPTH = 4;
414
+ const MAX_SLEEP_MS = 30_000;
415
+
416
+ function sleepStepSchema() {
417
+ return {
418
+ type: "object",
419
+ properties: {
420
+ ms: {
421
+ type: "integer",
422
+ minimum: 0,
423
+ maximum: MAX_SLEEP_MS,
424
+ description: `Milliseconds to wait (at most ${MAX_SLEEP_MS}).`,
425
+ },
426
+ },
427
+ required: ["ms"],
428
+ additionalProperties: false,
429
+ };
430
+ }
431
+
432
+ function ifStepSchema() {
433
+ const condition = {
434
+ type: "object",
435
+ properties: pageConditionProperties(),
436
+ additionalProperties: false,
437
+ };
438
+ const steps = {
439
+ type: "array",
440
+ items: { type: "object" },
441
+ };
442
+ return {
443
+ type: "object",
444
+ properties: {
445
+ condition,
446
+ then: steps,
447
+ elseIf: {
448
+ type: "array",
449
+ items: {
450
+ type: "object",
451
+ properties: { condition, then: steps },
452
+ required: ["condition"],
453
+ additionalProperties: false,
454
+ },
455
+ },
456
+ else: steps,
457
+ },
458
+ required: ["condition"],
459
+ additionalProperties: false,
460
+ };
461
+ }
462
+
463
+ function stepSchema(stepTools) {
464
+ return {
465
+ type: "object",
466
+ properties: {
467
+ tool: {
468
+ type: "string",
469
+ enum: ["sleep", "if", ...stepTools],
470
+ description:
471
+ "A tool that takes sessionId, sleep to pause, or if to branch.",
472
+ },
473
+ arguments: {
474
+ type: "object",
475
+ description:
476
+ "That tool's arguments without sessionId (default {}). sleep takes { ms }. if takes { condition, then, elseIf, else }: each condition has the wait_for condition fields, checked once without waiting, all of which must hold; then and else are step lists; elseIf is a list of { condition, then } checked in order after condition, and the first condition that holds runs its then.",
477
+ },
478
+ },
479
+ required: ["tool"],
480
+ additionalProperties: false,
481
+ };
482
+ }
483
+
484
+ function runStepsInputSchema(stepTools) {
485
+ return {
486
+ type: "object",
487
+ properties: {
488
+ sessionId: {
489
+ type: "string",
490
+ description:
491
+ "Session id returned by attach_tab. Every step runs on this session.",
492
+ },
493
+ steps: {
494
+ type: "array",
495
+ minItems: 1,
496
+ maxItems: MAX_RUN_STEPS,
497
+ description: `Steps to run in order (at most ${MAX_RUN_STEPS}, counting steps inside if branches; if nests at most ${MAX_STEP_DEPTH} deep).`,
498
+ items: stepSchema(stepTools),
499
+ },
500
+ continueOnError: {
501
+ type: "boolean",
502
+ description:
503
+ "Run the remaining steps after a step fails (default false: stop at the first failure).",
504
+ },
505
+ },
506
+ required: ["sessionId", "steps"],
507
+ additionalProperties: false,
508
+ };
509
+ }
510
+
511
+ function moveScreenshotImage(screenshot, images) {
512
+ if (typeof screenshot?.data !== "string") {
513
+ return screenshot;
514
+ }
515
+
516
+ const { data, ...metadata } = screenshot;
517
+ images.push({ type: "image", data, mimeType: screenshot.mimeType });
518
+ return { ...metadata, image: images.length };
519
+ }
520
+
521
+ // Moves screenshot data out of a step result so the client receives it as
522
+ // image content, leaving `image` (1-based position among the images) behind.
523
+ function extractStepImages(tool, result, images) {
524
+ if (tool === "take_screenshot") {
525
+ return moveScreenshotImage(result, images);
526
+ }
527
+
528
+ if (tool === "capture_debug_report" && result?.screenshot) {
529
+ return {
530
+ ...result,
531
+ screenshot: moveScreenshotImage(result.screenshot, images),
532
+ };
533
+ }
534
+
535
+ return result;
536
+ }
537
+
538
+ function parseSessionSnapshot(text) {
539
+ let snapshot;
540
+ try {
541
+ snapshot = JSON.parse(text);
542
+ } catch {
543
+ throw new Error("restore_session_snapshot snapshot must be valid JSON");
544
+ }
545
+
546
+ if (!snapshot || typeof snapshot !== "object") {
547
+ throw new Error(
548
+ "restore_session_snapshot snapshot must decode to an object",
549
+ );
550
+ }
551
+
552
+ return snapshot;
553
+ }
554
+
241
555
  function compareSessionsSchema(properties, required) {
242
556
  return {
243
557
  type: "object",
@@ -715,6 +1029,235 @@ export class McpBrowserDevToolsServer {
715
1029
  };
716
1030
  }
717
1031
 
1032
+ async takeScreenshot(args) {
1033
+ const { output, format, filePath } = screenshotTarget(
1034
+ args,
1035
+ this.config.browserFamily,
1036
+ );
1037
+ const screenshot = await this.browserAdapter.takeScreenshot(
1038
+ args.sessionId,
1039
+ format,
1040
+ {
1041
+ selector: args.selector,
1042
+ },
1043
+ );
1044
+ if (output !== "file" || screenshot?.found === false) {
1045
+ return screenshot;
1046
+ }
1047
+
1048
+ if (typeof screenshot?.data !== "string") {
1049
+ throw new Error("The browser returned no screenshot data");
1050
+ }
1051
+
1052
+ const { data, ...metadata } = screenshot;
1053
+ const image = Buffer.from(data, "base64");
1054
+ const savedPath = filePath
1055
+ ? await writeScreenshotFile(filePath, image, args.overwrite)
1056
+ : await writeTempScreenshot(image, format);
1057
+ return { ...metadata, path: savedPath };
1058
+ }
1059
+
1060
+ prepareSteps(steps, context, pathPrefix, depth) {
1061
+ return steps.map((step, index) => {
1062
+ const stepPath = `${pathPrefix}[${index}]`;
1063
+ validateValue(stepPath, step, this.stepSchema);
1064
+ context.count += 1;
1065
+ if (context.count > MAX_RUN_STEPS) {
1066
+ throw new Error(
1067
+ `run_steps allows at most ${MAX_RUN_STEPS} steps, counting steps inside if branches`,
1068
+ );
1069
+ }
1070
+
1071
+ const path = `${stepPath}.arguments`;
1072
+ const stepArgs = step.arguments ?? {};
1073
+ if (step.tool === "sleep") {
1074
+ validateValue(path, stepArgs, sleepStepSchema());
1075
+ return { tool: step.tool, args: stepArgs };
1076
+ }
1077
+
1078
+ if (step.tool === "if") {
1079
+ if (depth >= MAX_STEP_DEPTH) {
1080
+ throw new Error(
1081
+ `${path} nests if deeper than ${MAX_STEP_DEPTH} levels`,
1082
+ );
1083
+ }
1084
+ validateValue(path, stepArgs, ifStepSchema());
1085
+ const prepareBranch = (branch, branchPath) => ({
1086
+ condition: normalizeWaitForOptions(
1087
+ branch.condition,
1088
+ `${branchPath}.condition`,
1089
+ ),
1090
+ steps: this.prepareSteps(
1091
+ branch.then ?? [],
1092
+ context,
1093
+ `${branchPath}.then`,
1094
+ depth + 1,
1095
+ ),
1096
+ });
1097
+ return {
1098
+ tool: step.tool,
1099
+ branches: [
1100
+ { name: "then", ...prepareBranch(stepArgs, path) },
1101
+ ...(stepArgs.elseIf ?? []).map((branch, branchIndex) => ({
1102
+ name: `elseIf[${branchIndex}]`,
1103
+ ...prepareBranch(branch, `${path}.elseIf[${branchIndex}]`),
1104
+ })),
1105
+ ],
1106
+ else: this.prepareSteps(
1107
+ stepArgs.else ?? [],
1108
+ context,
1109
+ `${path}.else`,
1110
+ depth + 1,
1111
+ ),
1112
+ };
1113
+ }
1114
+
1115
+ if (stepArgs.sessionId !== undefined) {
1116
+ throw new Error(
1117
+ `${path}.sessionId is not allowed; run_steps passes its own sessionId`,
1118
+ );
1119
+ }
1120
+
1121
+ const toolArgs = { ...stepArgs, sessionId: context.sessionId };
1122
+ const tool = this.tools.get(step.tool);
1123
+ validateValue(path, toolArgs, tool.definition.inputSchema);
1124
+ tool.validate?.(toolArgs);
1125
+ return { tool: step.tool, args: toolArgs };
1126
+ });
1127
+ }
1128
+
1129
+ async checkStepCondition(condition, context) {
1130
+ const check = await checkPageCondition({
1131
+ getPageState: () => this.browserAdapter.getPageState(context.sessionId),
1132
+ inspectElement: (selector) =>
1133
+ this.browserAdapter.inspectElement(context.sessionId, selector),
1134
+ normalized: condition,
1135
+ });
1136
+ const observed = {};
1137
+ if (check.page) {
1138
+ observed.url = check.page.url ?? null;
1139
+ observed.readyState = check.page.readyState ?? null;
1140
+ }
1141
+ if (condition.selector) {
1142
+ observed.found = Boolean(check.element?.found);
1143
+ observed.visible = check.element?.node?.visible === true;
1144
+ if (condition.textEquals !== null || condition.textIncludes !== null) {
1145
+ observed.text = check.text;
1146
+ }
1147
+ }
1148
+ return { matched: check.matched, observed };
1149
+ }
1150
+
1151
+ // Checks the then and elseIf conditions in order and runs the first branch
1152
+ // whose condition holds, or else when none does.
1153
+ async runIfStep(step, context) {
1154
+ const checked = [];
1155
+ let selected = null;
1156
+ for (const branch of step.branches) {
1157
+ const { matched, observed } = await this.checkStepCondition(
1158
+ branch.condition,
1159
+ context,
1160
+ );
1161
+ checked.push({ branch: branch.name, matched, observed });
1162
+ if (matched) {
1163
+ selected = branch;
1164
+ break;
1165
+ }
1166
+ }
1167
+
1168
+ const steps = await this.executeSteps(
1169
+ selected ? selected.steps : step.else,
1170
+ context,
1171
+ );
1172
+ return {
1173
+ ok: steps.every((result) => result.ok),
1174
+ result: {
1175
+ matched: selected !== null,
1176
+ branch: selected ? selected.name : "else",
1177
+ checked,
1178
+ steps,
1179
+ },
1180
+ };
1181
+ }
1182
+
1183
+ async runStep(step, context) {
1184
+ if (step.tool === "if") {
1185
+ return this.runIfStep(step, context);
1186
+ }
1187
+
1188
+ let result;
1189
+ if (step.tool === "sleep") {
1190
+ await sleep(step.args.ms);
1191
+ result = { sleptMs: step.args.ms };
1192
+ } else {
1193
+ result = await this.tools.get(step.tool).handler(step.args);
1194
+ }
1195
+
1196
+ const entry = {
1197
+ ok: true,
1198
+ result: extractStepImages(step.tool, result, context.images),
1199
+ };
1200
+ // Actions report a missing element as found: false instead of throwing;
1201
+ // later steps usually depend on it, so treat it as a failure.
1202
+ // inspect_element may be checking that something is gone.
1203
+ if (result?.found === false && step.tool !== "inspect_element") {
1204
+ entry.ok = false;
1205
+ entry.error =
1206
+ result.error ?? `No element matches selector ${step.args.selector}`;
1207
+ }
1208
+ return entry;
1209
+ }
1210
+
1211
+ async executeSteps(steps, context) {
1212
+ const results = [];
1213
+ for (const [index, step] of steps.entries()) {
1214
+ const startedAt = Date.now();
1215
+ let entry;
1216
+ try {
1217
+ entry = await this.runStep(step, context);
1218
+ } catch (error) {
1219
+ entry = { ok: false, error: error.message };
1220
+ }
1221
+
1222
+ results.push({
1223
+ index,
1224
+ tool: step.tool,
1225
+ durationMs: Date.now() - startedAt,
1226
+ ...entry,
1227
+ });
1228
+ if (!entry.ok && !context.continueOnError) {
1229
+ break;
1230
+ }
1231
+ }
1232
+ return results;
1233
+ }
1234
+
1235
+ async runSteps(args) {
1236
+ const context = {
1237
+ sessionId: args.sessionId,
1238
+ continueOnError: args.continueOnError === true,
1239
+ images: [],
1240
+ count: 0,
1241
+ };
1242
+ // Validate every step, including both branches of each if, first, so a
1243
+ // typo in a late step does not leave the page half-changed.
1244
+ const steps = this.prepareSteps(args.steps, context, "arguments.steps", 0);
1245
+ const results = await this.executeSteps(steps, context);
1246
+
1247
+ return {
1248
+ value: {
1249
+ sessionId: args.sessionId,
1250
+ ok:
1251
+ results.length === steps.length &&
1252
+ results.every((result) => result.ok),
1253
+ ranSteps: results.length,
1254
+ skippedSteps: steps.length - results.length,
1255
+ steps: results,
1256
+ },
1257
+ images: context.images,
1258
+ };
1259
+ }
1260
+
718
1261
  createTools() {
719
1262
  const tools = [
720
1263
  [
@@ -1041,35 +1584,24 @@ export class McpBrowserDevToolsServer {
1041
1584
  definition: {
1042
1585
  name: "wait_for",
1043
1586
  description:
1044
- "Wait until every given condition holds on an attached session: selector state, exact url, urlIncludes substring, and readyState. Give at least one condition. Polls until the conditions match or timeoutMs passes, then fails with the last observed state. A selector check scrolls the matched element into view on each poll.",
1587
+ "Wait until every given condition holds on an attached session: selector state, selector text (textEquals, textIncludes), exact url, urlIncludes substring, and readyState. Give at least one of selector, url, urlIncludes, or readyState. Polls until the conditions match or timeoutMs passes, then fails with the last observed state. A selector check scrolls the matched element into view on each poll.",
1045
1588
  inputSchema: waitForInputSchema(),
1046
1589
  },
1047
- handler: async (args) => {
1048
- if (
1049
- !args.selector &&
1050
- !args.url &&
1051
- !args.urlIncludes &&
1052
- !args.readyState
1053
- ) {
1054
- throw new Error(
1055
- "wait_for requires at least one of selector, url, urlIncludes, or readyState",
1056
- );
1057
- }
1058
-
1059
- if (!args.selector && args.state !== undefined) {
1060
- throw new Error("wait_for state requires selector");
1061
- }
1062
-
1063
- return this.browserAdapter.waitFor(args.sessionId, {
1590
+ validate: (args) => {
1591
+ normalizeWaitForOptions(args);
1592
+ },
1593
+ handler: async (args) =>
1594
+ this.browserAdapter.waitFor(args.sessionId, {
1064
1595
  selector: args.selector,
1065
1596
  state: args.state,
1066
1597
  url: args.url,
1067
1598
  urlIncludes: args.urlIncludes,
1068
1599
  readyState: args.readyState,
1600
+ textEquals: args.textEquals,
1601
+ textIncludes: args.textIncludes,
1069
1602
  timeoutMs: args.timeoutMs,
1070
1603
  pollIntervalMs: args.pollIntervalMs,
1071
- });
1072
- },
1604
+ }),
1073
1605
  },
1074
1606
  ],
1075
1607
  [
@@ -1151,30 +1683,17 @@ export class McpBrowserDevToolsServer {
1151
1683
  "Restore a bounded session snapshot into the currently attached page context. Restores only page-visible cookies plus localStorage/sessionStorage on the current origin.",
1152
1684
  inputSchema: restoreSessionSnapshotInputSchema(),
1153
1685
  },
1154
- handler: async (args) => {
1155
- let snapshot;
1156
- try {
1157
- snapshot = JSON.parse(args.snapshot);
1158
- } catch {
1159
- throw new Error(
1160
- "restore_session_snapshot snapshot must be valid JSON",
1161
- );
1162
- }
1163
-
1164
- if (!snapshot || typeof snapshot !== "object") {
1165
- throw new Error(
1166
- "restore_session_snapshot snapshot must decode to an object",
1167
- );
1168
- }
1169
-
1170
- return this.browserAdapter.restoreSessionSnapshot(
1686
+ validate: (args) => {
1687
+ parseSessionSnapshot(args.snapshot);
1688
+ },
1689
+ handler: async (args) =>
1690
+ this.browserAdapter.restoreSessionSnapshot(
1171
1691
  args.sessionId,
1172
- snapshot,
1692
+ parseSessionSnapshot(args.snapshot),
1173
1693
  {
1174
1694
  clearStorage: args.clearStorage,
1175
1695
  },
1176
- );
1177
- },
1696
+ ),
1178
1697
  },
1179
1698
  ],
1180
1699
  [
@@ -1248,7 +1767,7 @@ export class McpBrowserDevToolsServer {
1248
1767
  definition: {
1249
1768
  name: "click",
1250
1769
  description:
1251
- "Click a single element located by CSS, text=..., role=..., or name=... syntax. Sends real mouse input at the element center and fails if another element covers that point. A JavaScript alert or confirm dialog that this opens is accepted automatically and a prompt is dismissed; get_events reports it as a dialog event.",
1770
+ "Click a single element located by CSS, text=..., role=..., or name=... syntax. Sends real mouse input at the element center and fails if another element covers that point. A JavaScript alert or confirm dialog that this opens is accepted automatically and a prompt is dismissed; get_events reports it as a dialog event. To check the result in the same call, run it as a run_steps step followed by wait_for, inspect_element, or take_screenshot.",
1252
1771
  inputSchema: sessionSchema(
1253
1772
  {
1254
1773
  selector: selectorProperty(),
@@ -1284,7 +1803,7 @@ export class McpBrowserDevToolsServer {
1284
1803
  definition: {
1285
1804
  name: "type",
1286
1805
  description:
1287
- "Type text into an input, textarea, or contenteditable element using real text input, replacing existing content unless clear is false.",
1806
+ "Type text into an input, textarea, or contenteditable element using real text input, replacing existing content unless clear is false. To check the result in the same call, run it as a run_steps step followed by wait_for, inspect_element, or take_screenshot.",
1288
1807
  inputSchema: sessionSchema(
1289
1808
  {
1290
1809
  selector: selectorProperty(),
@@ -1314,7 +1833,7 @@ export class McpBrowserDevToolsServer {
1314
1833
  definition: {
1315
1834
  name: "select",
1316
1835
  description:
1317
- "Select an option in a native <select> element and fire input and change events. Provide value, label, or both; the first option matching either is selected, and the call fails if none matches. Custom dropdowns built from other elements need click instead.",
1836
+ "Select an option in a native <select> element and fire input and change events. Provide value, label, or both; the first option matching either is selected, and the call fails if none matches. Custom dropdowns built from other elements need click instead. To check the result in the same call, run it as a run_steps step followed by wait_for, inspect_element, or take_screenshot.",
1318
1837
  inputSchema: sessionSchema(
1319
1838
  {
1320
1839
  selector: selectorProperty(),
@@ -1332,16 +1851,16 @@ export class McpBrowserDevToolsServer {
1332
1851
  ["selector"],
1333
1852
  ),
1334
1853
  },
1335
- handler: async (args) => {
1854
+ validate: (args) => {
1336
1855
  if (!args.value && !args.label) {
1337
1856
  throw new Error("select requires either value or label");
1338
1857
  }
1339
-
1340
- return this.browserAdapter.select(args.sessionId, args.selector, {
1858
+ },
1859
+ handler: async (args) =>
1860
+ this.browserAdapter.select(args.sessionId, args.selector, {
1341
1861
  value: args.value,
1342
1862
  label: args.label,
1343
- });
1344
- },
1863
+ }),
1345
1864
  },
1346
1865
  ],
1347
1866
  [
@@ -1350,7 +1869,7 @@ export class McpBrowserDevToolsServer {
1350
1869
  definition: {
1351
1870
  name: "press_key",
1352
1871
  description:
1353
- "Press a key or key combination (for example Enter, Tab, Escape, ArrowDown, Shift+Tab, Meta+a) with real keyboard input on the focused element, or on selector after focusing it. Fails if selector cannot take focus. A JavaScript alert or confirm dialog that this opens is accepted automatically and a prompt is dismissed; get_events reports it as a dialog event.",
1872
+ "Press a key or key combination (for example Enter, Tab, Escape, ArrowDown, Shift+Tab, Meta+a) with real keyboard input on the focused element, or on selector after focusing it. Fails if selector cannot take focus. A JavaScript alert or confirm dialog that this opens is accepted automatically and a prompt is dismissed; get_events reports it as a dialog event. To check the result in the same call, run it as a run_steps step followed by wait_for, inspect_element, or take_screenshot.",
1354
1873
  inputSchema: sessionSchema(
1355
1874
  {
1356
1875
  key: {
@@ -1363,6 +1882,9 @@ export class McpBrowserDevToolsServer {
1363
1882
  ["key"],
1364
1883
  ),
1365
1884
  },
1885
+ validate: (args) => {
1886
+ parseKeyCombo(args.key);
1887
+ },
1366
1888
  handler: async (args) =>
1367
1889
  this.browserAdapter.pressKey(
1368
1890
  args.sessionId,
@@ -1401,7 +1923,7 @@ export class McpBrowserDevToolsServer {
1401
1923
  [],
1402
1924
  ),
1403
1925
  },
1404
- handler: async (args) => {
1926
+ validate: (args) => {
1405
1927
  if (
1406
1928
  !args.selector &&
1407
1929
  args.deltaX === undefined &&
@@ -1411,14 +1933,14 @@ export class McpBrowserDevToolsServer {
1411
1933
  "scroll requires either selector or deltaX/deltaY values",
1412
1934
  );
1413
1935
  }
1414
-
1415
- return this.browserAdapter.scroll(args.sessionId, {
1936
+ },
1937
+ handler: async (args) =>
1938
+ this.browserAdapter.scroll(args.sessionId, {
1416
1939
  selector: args.selector,
1417
1940
  deltaX: args.deltaX,
1418
1941
  deltaY: args.deltaY,
1419
1942
  block: args.block,
1420
- });
1421
- },
1943
+ }),
1422
1944
  },
1423
1945
  ],
1424
1946
  [
@@ -1556,7 +2078,7 @@ export class McpBrowserDevToolsServer {
1556
2078
  definition: {
1557
2079
  name: "take_screenshot",
1558
2080
  description:
1559
- "Capture a screenshot from an attached page or a single element when selector is provided.",
2081
+ "Capture a screenshot from an attached page or a single element when selector is provided. By default the image comes back as base64 data in the JSON result; output image returns it as image content instead, and output file (or path) writes it to a file and returns the path.",
1560
2082
  inputSchema: {
1561
2083
  type: "object",
1562
2084
  properties: {
@@ -1567,22 +2089,42 @@ export class McpBrowserDevToolsServer {
1567
2089
  format: {
1568
2090
  type: "string",
1569
2091
  enum: screenshotFormatsFor(this.config.browserFamily),
1570
- description: "Image format (default png).",
2092
+ description:
2093
+ "Image format (default png). With path, it must match the extension.",
1571
2094
  },
1572
2095
  selector: selectorProperty(),
2096
+ output: {
2097
+ type: "string",
2098
+ enum: ["data", "image", "file"],
2099
+ description:
2100
+ "How to return the image: data puts base64 data in the JSON result, image returns an image content block with only metadata in the JSON, file writes the decoded image to a file and returns its path (default data, or file when path is given).",
2101
+ },
2102
+ path: {
2103
+ type: "string",
2104
+ description: `Absolute file path for output file, ending in ${screenshotFileExtensions(this.config.browserFamily).join(", ")}; the extension sets the format. Missing parent directories are created. Default: a new file in a private directory under the system temp directory.`,
2105
+ },
2106
+ overwrite: {
2107
+ type: "boolean",
2108
+ description:
2109
+ "For output file: replace path if it already exists (default false: fail instead).",
2110
+ },
1573
2111
  },
1574
2112
  required: ["sessionId"],
1575
2113
  additionalProperties: false,
1576
2114
  },
1577
2115
  },
1578
- handler: async (args) =>
1579
- this.browserAdapter.takeScreenshot(
1580
- args.sessionId,
1581
- args.format ?? "png",
1582
- {
1583
- selector: args.selector,
1584
- },
1585
- ),
2116
+ validate: (args) => {
2117
+ screenshotTarget(args, this.config.browserFamily);
2118
+ },
2119
+ handler: async (args) => this.takeScreenshot(args),
2120
+ formatResult: (result, args) => {
2121
+ if (args.output !== "image") {
2122
+ return asToolResult(result);
2123
+ }
2124
+ const images = [];
2125
+ const value = moveScreenshotImage(result, images);
2126
+ return asImageToolResult({ value, images });
2127
+ },
1586
2128
  },
1587
2129
  ],
1588
2130
  [
@@ -1663,6 +2205,26 @@ export class McpBrowserDevToolsServer {
1663
2205
  ]);
1664
2206
  }
1665
2207
 
2208
+ const stepTools = tools
2209
+ .filter(([, tool]) =>
2210
+ tool.definition.inputSchema.required?.includes("sessionId"),
2211
+ )
2212
+ .map(([name]) => name);
2213
+ this.stepSchema = stepSchema(stepTools);
2214
+ tools.push([
2215
+ "run_steps",
2216
+ {
2217
+ definition: {
2218
+ name: "run_steps",
2219
+ description:
2220
+ 'Run several tools on one attached session in order, in a single call. Use it to act and check the result together, for example [{"tool":"click","arguments":{"selector":"text=Save"}},{"tool":"sleep","arguments":{"ms":300}},{"tool":"take_screenshot"}]. Each step names a tool that takes sessionId (or sleep) and gives that tool\'s arguments without sessionId. To branch on the page state, use an if step, for example {"tool":"if","arguments":{"condition":{"selector":"#status","textIncludes":"failed"},"then":[{"tool":"click","arguments":{"selector":"text=Retry"}}],"elseIf":[{"condition":{"urlIncludes":"/login"},"then":[{"tool":"take_screenshot","arguments":{"output":"image"}}]}],"else":[]}}; conditions are checked once, in order, without waiting, so put wait_for or sleep before the if when the page may still be changing. The if result reports the branch taken (then, elseIf[i], or else), each checked condition with what was observed, and the branch\'s step results. Every step, including both branches, is validated before any runs. A step fails when its tool throws or reports found: false (except inspect_element). Stops at the first failing step unless continueOnError is true, and returns each step\'s result or error. Screenshots come back as image content; the step result keeps the metadata plus image, the 1-based position of its image. Prefer wait_for over sleep when there is a condition to wait for.',
2221
+ inputSchema: runStepsInputSchema(stepTools),
2222
+ },
2223
+ handler: async (args) => this.runSteps(args),
2224
+ formatResult: asImageToolResult,
2225
+ },
2226
+ ]);
2227
+
1666
2228
  return new Map(tools);
1667
2229
  }
1668
2230
 
@@ -1749,7 +2311,7 @@ export class McpBrowserDevToolsServer {
1749
2311
  version: SERVER_VERSION,
1750
2312
  },
1751
2313
  instructions:
1752
- "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.",
2314
+ '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. To act on a page and check the result, prefer run_steps: send the actions you already know (such as every field of a form), a wait_for, and the check (take_screenshot with output image, or inspect_element) in one call instead of several round trips, for example {"sessionId":"<id>","steps":[{"tool":"type","arguments":{"selector":"#search","text":"headphones"}},{"tool":"press_key","arguments":{"key":"Enter"}},{"tool":"wait_for","arguments":{"selector":"#results"}},{"tool":"take_screenshot","arguments":{"output":"image"}}]}. Add an if step when the page can be in more than one state.',
1753
2315
  });
1754
2316
  case "notifications/initialized":
1755
2317
  return null;
@@ -1773,14 +2335,54 @@ export class McpBrowserDevToolsServer {
1773
2335
  }
1774
2336
 
1775
2337
  async callTool(params = {}) {
1776
- const tool = this.tools.get(params.name);
1777
- if (!tool) {
1778
- throw new Error(`Unknown tool: ${params.name}`);
2338
+ const startedAt = Date.now();
2339
+ let response = null;
2340
+ try {
2341
+ const tool = this.tools.get(params.name);
2342
+ if (!tool) {
2343
+ throw new Error(`Unknown tool: ${params.name}`);
2344
+ }
2345
+
2346
+ const args = params.arguments ?? {};
2347
+ validateValue("arguments", args, tool.definition.inputSchema);
2348
+ tool.validate?.(args);
2349
+ const result = await tool.handler(args);
2350
+ response = (tool.formatResult ?? asToolResult)(result, args);
2351
+ return response;
2352
+ } finally {
2353
+ await this.logTiming(params.name, startedAt, response);
1779
2354
  }
2355
+ }
1780
2356
 
1781
- const args = params.arguments ?? {};
1782
- validateValue("arguments", args, tool.definition.inputSchema);
1783
- const result = await tool.handler(args);
1784
- return asToolResult(result);
2357
+ // Appends one JSON line per tool call when MCP_BROWSER_TIMING_LOG is set.
2358
+ // responseChars and images approximate what the call costs the client.
2359
+ async logTiming(name, startedAt, response) {
2360
+ if (!this.config.timingLogFile) {
2361
+ return;
2362
+ }
2363
+
2364
+ const content = response?.content ?? [];
2365
+ const entry = {
2366
+ ts: new Date(startedAt).toISOString(),
2367
+ tool: name ?? null,
2368
+ ms: Date.now() - startedAt,
2369
+ ok: response !== null,
2370
+ responseChars: content
2371
+ .filter((block) => block.type === "text")
2372
+ .reduce((total, block) => total + block.text.length, 0),
2373
+ images: content.filter((block) => block.type === "image").length,
2374
+ };
2375
+ // ok is whether the call returned; a batch that stopped at a failing
2376
+ // step still returns, so its own outcome is logged as stepsOk.
2377
+ if (name === "run_steps" && response?.structuredContent) {
2378
+ entry.steps = response.structuredContent.ranSteps;
2379
+ entry.stepsOk = response.structuredContent.ok;
2380
+ }
2381
+
2382
+ try {
2383
+ await appendFile(this.config.timingLogFile, `${JSON.stringify(entry)}\n`);
2384
+ } catch (error) {
2385
+ this.logger.error(`failed to write timing log: ${error.message}`);
2386
+ }
1785
2387
  }
1786
2388
  }
package/src/wait-for.mjs CHANGED
@@ -34,6 +34,49 @@ function normalizeInteger(value, fallback) {
34
34
  return Number.isInteger(value) && value > 0 ? value : fallback;
35
35
  }
36
36
 
37
+ function normalizeText(value) {
38
+ return typeof value === "string" ? value.replace(/\s+/g, " ").trim() : "";
39
+ }
40
+
41
+ // Text conditions compare whitespace-normalized visible text, which the page
42
+ // context clips to 400 characters and marks with a trailing "...".
43
+ const PAGE_TEXT_LIMIT = 400;
44
+ const CLIP_MARKER = "...";
45
+
46
+ function readElementText(result) {
47
+ const raw = result?.node?.innerText ?? result?.node?.textContent;
48
+ const clipped =
49
+ typeof raw === "string" &&
50
+ raw.length === PAGE_TEXT_LIMIT + CLIP_MARKER.length &&
51
+ raw.endsWith(CLIP_MARKER);
52
+ return {
53
+ text: normalizeText(clipped ? raw.slice(0, PAGE_TEXT_LIMIT) : raw),
54
+ clipped,
55
+ };
56
+ }
57
+
58
+ function elementText(result) {
59
+ return readElementText(result).text;
60
+ }
61
+
62
+ function textMatches(result, options) {
63
+ if (options.textEquals === null && options.textIncludes === null) {
64
+ return true;
65
+ }
66
+
67
+ if (!result?.found) {
68
+ return false;
69
+ }
70
+
71
+ // Clipped text is only a prefix, so it can never prove equality.
72
+ const { text, clipped } = readElementText(result);
73
+ return (
74
+ (options.textEquals === null ||
75
+ (!clipped && text === options.textEquals)) &&
76
+ (options.textIncludes === null || text.includes(options.textIncludes))
77
+ );
78
+ }
79
+
37
80
  function readyStateMatches(current, expected) {
38
81
  const currentRank = READY_STATE_ORDER[current] ?? -1;
39
82
  const expectedRank = READY_STATE_ORDER[expected] ?? -1;
@@ -72,6 +115,12 @@ function buildTimeoutMessage(options, lastPage, lastElement) {
72
115
  if (options.readyState) {
73
116
  conditions.push(`readyState to reach ${options.readyState}`);
74
117
  }
118
+ if (options.textEquals !== null) {
119
+ conditions.push(`text to equal ${JSON.stringify(options.textEquals)}`);
120
+ }
121
+ if (options.textIncludes !== null) {
122
+ conditions.push(`text to include ${JSON.stringify(options.textIncludes)}`);
123
+ }
75
124
 
76
125
  const observed = [];
77
126
  if (lastPage?.url) {
@@ -85,19 +134,33 @@ function buildTimeoutMessage(options, lastPage, lastElement) {
85
134
  `last selector found=${Boolean(lastElement.found)} visible=${lastElement.node?.visible === true}`,
86
135
  );
87
136
  }
137
+ if (
138
+ (options.textEquals !== null || options.textIncludes !== null) &&
139
+ lastElement?.found
140
+ ) {
141
+ observed.push(`last text=${JSON.stringify(elementText(lastElement))}`);
142
+ }
88
143
 
89
144
  return `Timed out after ${options.timeoutMs}ms waiting for ${conditions.join(
90
145
  ", ",
91
146
  )}${observed.length > 0 ? `; ${observed.join("; ")}` : ""}`;
92
147
  }
93
148
 
94
- export function normalizeWaitForOptions(options = {}) {
149
+ export function normalizeWaitForOptions(options = {}, label = "wait_for") {
95
150
  const normalized = {
96
151
  selector: normalizeOptionalString(options.selector),
97
152
  state: normalizeSelectorState(options.state),
98
153
  url: normalizeOptionalString(options.url),
99
154
  urlIncludes: normalizeOptionalString(options.urlIncludes),
100
155
  readyState: normalizeReadyState(options.readyState),
156
+ textEquals:
157
+ typeof options.textEquals === "string"
158
+ ? normalizeText(options.textEquals)
159
+ : null,
160
+ textIncludes:
161
+ typeof options.textIncludes === "string"
162
+ ? normalizeText(options.textIncludes)
163
+ : null,
101
164
  timeoutMs: normalizeInteger(options.timeoutMs, 10_000),
102
165
  pollIntervalMs: normalizeInteger(options.pollIntervalMs, 100),
103
166
  };
@@ -109,17 +172,69 @@ export function normalizeWaitForOptions(options = {}) {
109
172
  !normalized.readyState
110
173
  ) {
111
174
  throw new Error(
112
- "wait_for requires at least one of selector, url, urlIncludes, or readyState",
175
+ `${label} requires at least one of selector, url, urlIncludes, or readyState`,
113
176
  );
114
177
  }
115
178
 
116
179
  if (!normalized.selector && options.state !== undefined) {
117
- throw new Error("wait_for state requires selector");
180
+ throw new Error(`${label} state requires selector`);
181
+ }
182
+
183
+ const hasText =
184
+ normalized.textEquals !== null || normalized.textIncludes !== null;
185
+ if (hasText && !normalized.selector) {
186
+ throw new Error(`${label} textEquals and textIncludes require selector`);
187
+ }
188
+
189
+ if (hasText && normalized.state === "hidden") {
190
+ throw new Error(
191
+ `${label} textEquals and textIncludes cannot be combined with state hidden`,
192
+ );
118
193
  }
119
194
 
120
195
  return normalized;
121
196
  }
122
197
 
198
+ // Checks normalized conditions once against the current page.
199
+ export async function checkPageCondition({
200
+ getPageState,
201
+ inspectElement,
202
+ normalized,
203
+ }) {
204
+ let page = null;
205
+ let element = null;
206
+ if (normalized.url || normalized.urlIncludes || normalized.readyState) {
207
+ page = await getPageState();
208
+ }
209
+
210
+ if (normalized.selector) {
211
+ element = await inspectElement(normalized.selector);
212
+ if (element?.error) {
213
+ throw new Error(element.error);
214
+ }
215
+ }
216
+
217
+ const matched =
218
+ (normalized.selector
219
+ ? selectorMatches(element, normalized.state) &&
220
+ textMatches(element, normalized)
221
+ : true) &&
222
+ (normalized.url ? page?.url === normalized.url : true) &&
223
+ (normalized.urlIncludes
224
+ ? page?.url?.includes(normalized.urlIncludes) === true
225
+ : true) &&
226
+ (normalized.readyState
227
+ ? readyStateMatches(page?.readyState, normalized.readyState)
228
+ : true);
229
+
230
+ return {
231
+ matched,
232
+ page,
233
+ element,
234
+ text: element?.found ? elementText(element) : null,
235
+ };
236
+ }
237
+
123
238
  export async function waitForPageCondition({
124
239
  getPageState,
125
240
  inspectElement,
@@ -128,40 +243,19 @@ export async function waitForPageCondition({
128
243
  const normalized = normalizeWaitForOptions(options);
129
244
  const startedAt = Date.now();
130
245
  let attempts = 0;
131
- let lastPage = null;
132
- let lastElement = null;
133
246
 
134
247
  while (true) {
135
248
  attempts += 1;
136
249
 
137
- if (normalized.url || normalized.urlIncludes || normalized.readyState) {
138
- lastPage = await getPageState();
139
- }
140
-
141
- if (normalized.selector) {
142
- lastElement = await inspectElement(normalized.selector);
143
- if (lastElement?.error) {
144
- throw new Error(lastElement.error);
145
- }
146
- }
250
+ const check = await checkPageCondition({
251
+ getPageState,
252
+ inspectElement,
253
+ normalized,
254
+ });
255
+ const lastPage = check.page;
256
+ const lastElement = check.element;
147
257
 
148
- const matchedSelector = normalized.selector
149
- ? selectorMatches(lastElement, normalized.state)
150
- : true;
151
- const matchedUrl = normalized.url ? lastPage?.url === normalized.url : true;
152
- const matchedUrlIncludes = normalized.urlIncludes
153
- ? lastPage?.url?.includes(normalized.urlIncludes) === true
154
- : true;
155
- const matchedReadyState = normalized.readyState
156
- ? readyStateMatches(lastPage?.readyState, normalized.readyState)
157
- : true;
158
-
159
- if (
160
- matchedSelector &&
161
- matchedUrl &&
162
- matchedUrlIncludes &&
163
- matchedReadyState
164
- ) {
258
+ if (check.matched) {
165
259
  const browserFamily =
166
260
  lastPage?.browserFamily ?? lastElement?.browserFamily ?? null;
167
261
 
@@ -178,6 +272,8 @@ export async function waitForPageCondition({
178
272
  url: normalized.url,
179
273
  urlIncludes: normalized.urlIncludes,
180
274
  readyState: normalized.readyState,
275
+ textEquals: normalized.textEquals,
276
+ textIncludes: normalized.textIncludes,
181
277
  },
182
278
  page: lastPage,
183
279
  element: normalized.selector