mcp-browser-dev-tools 0.2.1 → 0.3.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.
@@ -0,0 +1,82 @@
1
+ import { setTimeout as sleep } from "node:timers/promises";
2
+
3
+ export const INPUT_NOT_DELIVERED = "INPUT_NOT_DELIVERED";
4
+
5
+ // Input normally reaches the page before the browser acknowledges it, so
6
+ // these re-checks only cover a late delivery.
7
+ const RECHECK_DELAYS_MS = [50, 150];
8
+
9
+ // A browser can acknowledge input it never delivers: Chrome has been seen
10
+ // dropping every CDP input event to a tab after a navigation while still
11
+ // reporting success. So send the input and check with the probe the page
12
+ // script armed that it arrived. If it did not, and the probe can be sure of
13
+ // that, recover and send it once more. Input that still does not arrive is
14
+ // reported as an error rather than a success that did nothing. When the
15
+ // probe cannot be sure, because page listeners might have hidden the input,
16
+ // it is not sent again, so an action is never repeated.
17
+ //
18
+ // readProbe(disarm) returns the probe reading ({ delivered, conclusive,
19
+ // node }), or null when delivery cannot be checked, for example because the
20
+ // page navigated away. The page removes the probe once input arrives;
21
+ // disarm removes it when giving up.
22
+ export async function sendCheckedInput({ send, readProbe, recover, describe }) {
23
+ let settled = false;
24
+ const settle = (reading, resent) => {
25
+ settled = true;
26
+ return { node: reading?.node ?? null, resent };
27
+ };
28
+
29
+ let resent = false;
30
+ try {
31
+ await send();
32
+ let reading = await awaitDelivery(readProbe);
33
+ if (reading.delivered) {
34
+ return settle(reading, false);
35
+ }
36
+
37
+ if (reading.conclusive) {
38
+ await recover?.();
39
+ // The first input may have arrived, or the page navigated, while
40
+ // recovering; sending again then would repeat it or reach another page.
41
+ reading = (await readProbe(false)) ?? { delivered: true };
42
+ if (reading.delivered) {
43
+ return settle(reading, false);
44
+ }
45
+
46
+ await send();
47
+ resent = true;
48
+ reading = await awaitDelivery(readProbe);
49
+ if (reading.delivered) {
50
+ return settle(reading, true);
51
+ }
52
+ }
53
+ } finally {
54
+ if (!settled) {
55
+ await readProbe(true);
56
+ }
57
+ }
58
+
59
+ const error = new Error(
60
+ resent
61
+ ? `${describe} was sent twice, but the browser delivered no input events to the page, so it had no effect. The tab may not be accepting input yet, for example just after a navigation. Wait and try again, or act from the page with evaluate_js (for example element.click()).`
62
+ : `${describe} was sent, but no input events reached the page, so it most likely had no effect. It was not sent again, because a page listener may have hidden it. Check the page; if nothing changed, wait and try again, or act from the page with evaluate_js (for example element.click()).`,
63
+ );
64
+ error.code = INPUT_NOT_DELIVERED;
65
+ throw error;
66
+ }
67
+
68
+ // The reading once the input has arrived or the re-checks are used up. A
69
+ // probe that cannot be read counts as delivered.
70
+ async function awaitDelivery(readProbe) {
71
+ let reading;
72
+ for (const delay of [0, ...RECHECK_DELAYS_MS]) {
73
+ if (delay) {
74
+ await sleep(delay);
75
+ }
76
+ reading = (await readProbe(false)) ?? { delivered: true };
77
+ if (reading.delivered) {
78
+ break;
79
+ }
80
+ }
81
+ return reading;
82
+ }
@@ -14,10 +14,16 @@ export function validateValue(path, value, schema) {
14
14
 
15
15
  if (schema.additionalProperties === false) {
16
16
  for (const key of Object.keys(value)) {
17
- if (!(key in properties)) {
17
+ if (!Object.hasOwn(properties, key)) {
18
18
  throw new Error(`${path}.${key} is not allowed`);
19
19
  }
20
20
  }
21
+ } else if (typeof schema.additionalProperties === "object") {
22
+ for (const [key, item] of Object.entries(value)) {
23
+ if (!Object.hasOwn(properties, key)) {
24
+ validateValue(`${path}.${key}`, item, schema.additionalProperties);
25
+ }
26
+ }
21
27
  }
22
28
 
23
29
  for (const [key, propertySchema] of Object.entries(properties)) {
@@ -95,5 +101,12 @@ export function validateValue(path, value, schema) {
95
101
  if (schema.minimum !== undefined && value < schema.minimum) {
96
102
  throw new Error(`${path} must be >= ${schema.minimum}`);
97
103
  }
104
+
105
+ if (
106
+ schema.exclusiveMinimum !== undefined &&
107
+ value <= schema.exclusiveMinimum
108
+ ) {
109
+ throw new Error(`${path} must be > ${schema.exclusiveMinimum}`);
110
+ }
98
111
  }
99
112
  }
@@ -1,6 +1,9 @@
1
+ import { ChangeTracker } from "./action-changes.mjs";
1
2
  import { actionTools } from "./tools/action-tools.mjs";
2
3
  import { browserTools } from "./tools/browser-tools.mjs";
3
4
  import { inspectionTools } from "./tools/inspection-tools.mjs";
5
+ import { moreToolsTool } from "./tools/more-tools.mjs";
6
+ import { performanceTools } from "./tools/performance-tools.mjs";
4
7
  import { stateTools } from "./tools/state-tools.mjs";
5
8
  import { appendFile } from "node:fs/promises";
6
9
  import { launchBrowser as launchLocalBrowser } from "./browser-launch-service.mjs";
@@ -13,6 +16,7 @@ import { validateValue } from "./json-schema.mjs";
13
16
  import { createLogger } from "./logger.mjs";
14
17
  import { PACKAGE_NAME, PACKAGE_VERSION } from "./package-info.mjs";
15
18
  import { StepRunner, runStepsTool, stepSchema } from "./run-steps.mjs";
19
+ import { TOOL_GROUPS } from "./tool-sets.mjs";
16
20
  import { TabRunner, runTabsTool } from "./run-tabs.mjs";
17
21
  import { asToolResult } from "./tool-results.mjs";
18
22
 
@@ -67,6 +71,28 @@ const STATUS_PROBE_ATTEMPTS = 3;
67
71
 
68
72
  const LAUNCH_GRACE_MS = 30_000;
69
73
 
74
+ // The definition clients see: additionalProperties: false tells a model
75
+ // nothing it acts on, so it is left out of what every turn pays for. Calls
76
+ // are still validated against the full schema.
77
+ function advertisedDefinition(definition) {
78
+ const strip = (value) => {
79
+ if (Array.isArray(value)) {
80
+ return value.map(strip);
81
+ }
82
+ if (!value || typeof value !== "object") {
83
+ return value;
84
+ }
85
+ return Object.fromEntries(
86
+ Object.entries(value)
87
+ .filter(
88
+ ([key, item]) => !(key === "additionalProperties" && item === false),
89
+ )
90
+ .map(([key, item]) => [key, strip(item)]),
91
+ );
92
+ };
93
+ return strip(definition);
94
+ }
95
+
70
96
  function sleep(ms) {
71
97
  return new Promise((resolve) => {
72
98
  setTimeout(resolve, ms);
@@ -219,25 +245,37 @@ export class McpBrowserDevToolsServer {
219
245
  }
220
246
 
221
247
  createTools() {
222
- const tools = [
248
+ this.changeTracker = new ChangeTracker(this.browserAdapter);
249
+ // config.tools is the set listed to clients (null for all). The others
250
+ // stay reachable through more_tools and as run_steps and run_tabs
251
+ // steps, which can use every session tool.
252
+ const enabled = this.config.tools;
253
+ const all = [
223
254
  ...browserTools(this),
224
255
  ...stateTools(this),
225
256
  ...actionTools(this),
226
257
  ...inspectionTools(this),
258
+ ...performanceTools(this),
227
259
  ];
260
+ const tools = all.filter(([name]) => !enabled || enabled.has(name));
261
+ const hidden = new Map(
262
+ all.filter(([name]) => enabled && !enabled.has(name)),
263
+ );
264
+ this.stepToolMap = new Map(all);
228
265
 
229
- const stepTools = tools
266
+ const stepTools = all
230
267
  .filter(([, tool]) =>
231
268
  tool.definition.inputSchema.required?.includes("sessionId"),
232
269
  )
233
270
  .map(([name]) => name);
234
271
  this.stepRunner = new StepRunner({
235
- getTools: () => this.tools,
272
+ getTools: () => this.stepToolMap,
236
273
  browserAdapter: this.browserAdapter,
274
+ changeTracker: this.changeTracker,
237
275
  stepSchema: stepSchema(stepTools),
238
276
  conditionOptions: { expression: this.config.enableEvaluate },
239
277
  });
240
- tools.push(runStepsTool(this.stepRunner, stepTools));
278
+ tools.push(runStepsTool(this.stepRunner));
241
279
  this.tabRunner = new TabRunner({
242
280
  stepRunner: this.stepRunner,
243
281
  browserAdapter: this.browserAdapter,
@@ -245,6 +283,9 @@ export class McpBrowserDevToolsServer {
245
283
  tools.push(
246
284
  runTabsTool(this.tabRunner, stepTools, this.config.browserFamily),
247
285
  );
286
+ if (hidden.size > 0) {
287
+ tools.push(moreToolsTool(hidden, advertisedDefinition));
288
+ }
248
289
 
249
290
  return new Map(tools);
250
291
  }
@@ -331,8 +372,7 @@ export class McpBrowserDevToolsServer {
331
372
  name: SERVER_NAME,
332
373
  version: SERVER_VERSION,
333
374
  },
334
- instructions:
335
- '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. To read several pages, open them together with run_tabs and read each with read_text. Locators: plain CSS (or css=) takes the first match; text=Foo takes the first visible element whose text equals Foo, else contains it, in document order, so it can match a wrapper; role=button[name="Save"] matches ARIA role and accessible name (equal or containing) without a visibility check; name=Foo takes the first visible element whose accessible name equals or contains Foo, and a matched <label> resolves to its control when that control is visible. Comparisons are case-sensitive; iframes and shadow roots are not searched.',
375
+ instructions: `Browser tools for Chromium (CDP) and Firefox (BiDi). Call attach_tab first; tools that take sessionId use the one it returns. To see a page, call get_snapshot: one line per visible heading and control (iframes too), each with a ref such as e12 or f1e3, 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 changes once the page settles: controls added, removed, or updated, new text such as an error or a toast, URL and title, console errors, and after a navigation the new page's snapshot. That is usually the check; add wait_for only for something later. Read several pages at once with run_tabs and read_text. Locators: ref=e12 is a get_snapshot element, until the page navigates; plain CSS (or css=) takes the first match; text=Foo the first visible element whose text equals, else contains, Foo; role=button[name="Save"] matches role and accessible name; name=Foo the first visible element whose accessible name equals or contains Foo (a label resolves to its control). Matching is case-sensitive; only refs reach into iframes. x and y are viewport CSS pixels; a screenshot's cssRect and scale convert image pixels. more_tools lists the tools not listed here (drag, cookies, request mocking, HAR, performance) and calls them; they also work as run_steps steps.`,
336
376
  });
337
377
  case "notifications/initialized":
338
378
  return null;
@@ -340,7 +380,9 @@ export class McpBrowserDevToolsServer {
340
380
  return success(id, {});
341
381
  case "tools/list":
342
382
  return success(id, {
343
- tools: Array.from(this.tools.values(), (tool) => tool.definition),
383
+ tools: Array.from(this.tools.values(), (tool) =>
384
+ advertisedDefinition(tool.definition),
385
+ ),
344
386
  });
345
387
  case "tools/call":
346
388
  return success(id, await this.callTool(message.params));
@@ -361,7 +403,16 @@ export class McpBrowserDevToolsServer {
361
403
  try {
362
404
  const tool = this.tools.get(params.name);
363
405
  if (!tool) {
364
- throw new Error(`Unknown tool: ${params.name}`);
406
+ const group = Object.entries(TOOL_GROUPS).find(([, names]) =>
407
+ names.includes(params.name),
408
+ )?.[0];
409
+ throw new Error(
410
+ params.name === "evaluate_js" && !this.config.enableEvaluate
411
+ ? "evaluate_js is turned off by MCP_BROWSER_ENABLE_EVAL=0"
412
+ : group
413
+ ? `${params.name} is not listed directly; call it through more_tools ({"name":"${params.name}","arguments":{...}}) or as a run_steps step, or list it with MCP_BROWSER_TOOLS=${group}`
414
+ : `Unknown tool: ${params.name}`,
415
+ );
365
416
  }
366
417
 
367
418
  const args = params.arguments ?? {};
@@ -0,0 +1,156 @@
1
+ // set_network: block or mock requests by URL glob, add request headers,
2
+ // and emulate offline or slow networks. The state lives on the session; a
3
+ // call replaces the fields it gives and keeps the rest.
4
+
5
+ // The glob syntax of CDP's Fetch patterns, so a rule matches the same URLs
6
+ // on both browsers: * is any run of characters, ? exactly one, and a
7
+ // backslash escapes the next character.
8
+ export function globToRegExp(glob) {
9
+ let source = "";
10
+ for (let index = 0; index < glob.length; index += 1) {
11
+ const char = glob[index];
12
+ if (char === "\\" && index + 1 < glob.length) {
13
+ index += 1;
14
+ source += glob[index].replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
15
+ } else if (char === "*") {
16
+ source += ".*";
17
+ } else if (char === "?") {
18
+ source += ".";
19
+ } else {
20
+ source += char.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
21
+ }
22
+ }
23
+ return new RegExp(`^${source}$`, "s");
24
+ }
25
+
26
+ // Runs fn after the session's earlier network calls, so overlapping calls
27
+ // (and a detach) apply one at a time in the order they came.
28
+ export async function inNetworkTurn(session, fn) {
29
+ const previous = session.networkTurn ?? Promise.resolve();
30
+ let finished;
31
+ session.networkTurn = new Promise((resolve) => {
32
+ finished = resolve;
33
+ });
34
+ await previous.catch(() => {});
35
+ try {
36
+ return await fn();
37
+ } finally {
38
+ finished();
39
+ }
40
+ }
41
+
42
+ export function emptyNetworkState() {
43
+ return {
44
+ rules: [],
45
+ headers: {},
46
+ offline: false,
47
+ latencyMs: 0,
48
+ downloadKbps: null,
49
+ uploadKbps: null,
50
+ };
51
+ }
52
+
53
+ const HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
54
+
55
+ // Browsers reject a request or response with a malformed header, which
56
+ // would leave a paused request unanswered, so headers are checked first.
57
+ function checkHeaders(headers, where) {
58
+ for (const [name, value] of Object.entries(headers ?? {})) {
59
+ if (!HEADER_NAME.test(name)) {
60
+ throw new Error(`${where} has an invalid header name: ${name}`);
61
+ }
62
+ if (/[\r\n\0]/.test(String(value))) {
63
+ throw new Error(`${where} header ${name} has a line break in its value`);
64
+ }
65
+ }
66
+ }
67
+
68
+ // The state after a set_network call: reset starts from nothing, and each
69
+ // field given replaces the one before. Rule hit counts start at zero.
70
+ export function applyNetworkOptions(current, options) {
71
+ checkHeaders(options.headers, "headers");
72
+ for (const [index, rule] of (options.rules ?? []).entries()) {
73
+ checkHeaders(rule.headers, `rules[${index}]`);
74
+ if (rule.contentType !== undefined) {
75
+ checkHeaders({ "content-type": rule.contentType }, `rules[${index}]`);
76
+ }
77
+ }
78
+ const state = options.reset
79
+ ? emptyNetworkState()
80
+ : { ...(current ?? emptyNetworkState()) };
81
+ if (options.rules !== undefined) {
82
+ state.rules = options.rules.map((rule) => ({
83
+ url: rule.url,
84
+ action: rule.action,
85
+ status: rule.status ?? 200,
86
+ contentType: rule.contentType ?? null,
87
+ body: rule.body ?? "",
88
+ headers: rule.headers ?? {},
89
+ pattern: globToRegExp(rule.url),
90
+ hits: 0,
91
+ }));
92
+ }
93
+ for (const key of [
94
+ "headers",
95
+ "offline",
96
+ "latencyMs",
97
+ "downloadKbps",
98
+ "uploadKbps",
99
+ ]) {
100
+ if (options[key] !== undefined) {
101
+ state[key] = options[key];
102
+ }
103
+ }
104
+ return state;
105
+ }
106
+
107
+ export function throttled(state) {
108
+ return Boolean(state.latencyMs || state.downloadKbps || state.uploadKbps);
109
+ }
110
+
111
+ // The first rule whose pattern matches url, with its hit counted.
112
+ export function takeMatchingRule(state, url) {
113
+ const rule = state?.rules.find((candidate) => candidate.pattern.test(url));
114
+ if (rule) {
115
+ rule.hits += 1;
116
+ }
117
+ return rule ?? null;
118
+ }
119
+
120
+ // A mock's response headers as name/value pairs. Mocks usually stand in
121
+ // for an API the page fetches across origins, so CORS is allowed unless
122
+ // the rule says otherwise.
123
+ export function mockHeaders(rule) {
124
+ const headers = { ...rule.headers };
125
+ const names = new Set(Object.keys(headers).map((name) => name.toLowerCase()));
126
+ if (rule.contentType && !names.has("content-type")) {
127
+ headers["content-type"] = rule.contentType;
128
+ }
129
+ if (!names.has("access-control-allow-origin")) {
130
+ headers["access-control-allow-origin"] = "*";
131
+ }
132
+ return Object.entries(headers).map(([name, value]) => ({
133
+ name,
134
+ value: String(value),
135
+ }));
136
+ }
137
+
138
+ export function describeNetworkState(state) {
139
+ return {
140
+ rules: state.rules.map(({ url, action, status, hits }) => ({
141
+ url,
142
+ action,
143
+ ...(action === "mock" ? { status } : {}),
144
+ hits,
145
+ })),
146
+ headers: Object.keys(state.headers),
147
+ offline: state.offline,
148
+ ...(throttled(state)
149
+ ? {
150
+ latencyMs: state.latencyMs,
151
+ downloadKbps: state.downloadKbps,
152
+ uploadKbps: state.uploadKbps,
153
+ }
154
+ : {}),
155
+ };
156
+ }