mcp-browser-dev-tools 0.4.0 → 0.5.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.
@@ -5,6 +5,12 @@ import {
5
5
  summarizeNetworkRequests,
6
6
  } from "./session-events.mjs";
7
7
  import { DEFAULT_FIREFOX_BIDI_WS_URL } from "./config.mjs";
8
+ import {
9
+ answerDialog,
10
+ createDialogAnswers,
11
+ reserveDialogAnswers,
12
+ setDialogAnswers,
13
+ } from "./dialog-answers.mjs";
8
14
  import { wrapTopLevelAwait } from "./top-level-await.mjs";
9
15
  import { waitForPageCondition } from "./wait-for.mjs";
10
16
  import {
@@ -27,6 +33,7 @@ import {
27
33
  FrameKeys,
28
34
  probeScope,
29
35
  addFrameSnapshots,
36
+ frameElementQuery,
30
37
  frameElementSnapshot,
31
38
  parseFrameRef,
32
39
  restoreFrameSelector,
@@ -130,6 +137,15 @@ export function normalizeFirefoxContext(context) {
130
137
  };
131
138
  }
132
139
 
140
+ // Firefox would otherwise dismiss dialogs itself before the server answers
141
+ // them as set_dialog_answers says. File pickers keep Firefox's handling.
142
+ const LEAVE_DIALOGS = {
143
+ alert: "ignore",
144
+ beforeUnload: "ignore",
145
+ confirm: "ignore",
146
+ prompt: "ignore",
147
+ };
148
+
133
149
  export function resolveBidiEventContext(method, params = {}) {
134
150
  return (
135
151
  params.context ??
@@ -435,6 +451,7 @@ class FirefoxBidiTabSession {
435
451
  this.lastNavigationAt = null;
436
452
  this.lastReloadAt = null;
437
453
  this.viewportOverride = null;
454
+ this.dialogAnswers = createDialogAnswers();
438
455
  }
439
456
 
440
457
  bufferEvent(method, params) {
@@ -497,6 +514,7 @@ export class FirefoxBidiSessionManager {
497
514
  constructor(config, options = {}) {
498
515
  this.config = config;
499
516
  this.sessions = new Map();
517
+ this.attachingDialogAnswers = new Map();
500
518
  this.websocketFactory =
501
519
  options.websocketFactory ?? ((url) => new WebSocket(url));
502
520
  this.connectionTimeoutMs = options.connectionTimeoutMs ?? 2_000;
@@ -635,11 +653,20 @@ export class FirefoxBidiSessionManager {
635
653
  });
636
654
 
637
655
  if (endpoint.requiresSessionNew) {
638
- const result = await this.send("session.new", {
639
- capabilities: {
640
- alwaysMatch: {},
641
- },
642
- });
656
+ let result;
657
+ try {
658
+ result = await this.send("session.new", {
659
+ capabilities: {
660
+ alwaysMatch: { unhandledPromptBehavior: LEAVE_DIALOGS },
661
+ },
662
+ });
663
+ } catch {
664
+ // A Firefox without per-type prompt handlers rejects the capability
665
+ // and then answers dialogs itself.
666
+ result = await this.send("session.new", {
667
+ capabilities: { alwaysMatch: {} },
668
+ });
669
+ }
643
670
 
644
671
  this.browserSessionId = result.sessionId;
645
672
  this.capabilities = result.capabilities ?? {};
@@ -795,11 +822,7 @@ export class FirefoxBidiSessionManager {
795
822
  }
796
823
 
797
824
  if (message.method === "browsingContext.userPromptOpened") {
798
- const accept = message.params?.type !== "prompt";
799
- this.send("browsingContext.handleUserPrompt", {
800
- context: contextId,
801
- accept,
802
- }).catch(() => {});
825
+ void this.answerUserPrompt(contextId, message.params ?? {});
803
826
  }
804
827
 
805
828
  for (const session of this.sessions.values()) {
@@ -912,23 +935,34 @@ export class FirefoxBidiSessionManager {
912
935
  const session = new FirefoxBidiTabSession(target, {
913
936
  eventBufferSize: this.config.eventBufferSize,
914
937
  });
938
+ // The tab's sessions share its dialog answers.
939
+ const reservation = reserveDialogAnswers(
940
+ this.sessions,
941
+ this.attachingDialogAnswers,
942
+ targetId,
943
+ );
944
+ session.dialogAnswers = reservation.answers;
915
945
 
916
- const subscription = await this.send("session.subscribe", {
917
- events: [
918
- "log.entryAdded",
919
- "network.beforeRequestSent",
920
- "network.responseCompleted",
921
- "network.fetchError",
922
- "browsingContext.load",
923
- "browsingContext.contextDestroyed",
924
- "browsingContext.userPromptOpened",
925
- "browsingContext.userPromptClosed",
926
- ],
927
- contexts: [targetId],
928
- });
929
-
930
- session.subscription = subscription.subscription ?? null;
931
- this.sessions.set(session.id, session);
946
+ let subscription;
947
+ try {
948
+ subscription = await this.send("session.subscribe", {
949
+ events: [
950
+ "log.entryAdded",
951
+ "network.beforeRequestSent",
952
+ "network.responseCompleted",
953
+ "network.fetchError",
954
+ "browsingContext.load",
955
+ "browsingContext.contextDestroyed",
956
+ "browsingContext.userPromptOpened",
957
+ "browsingContext.userPromptClosed",
958
+ ],
959
+ contexts: [targetId],
960
+ });
961
+ session.subscription = subscription.subscription ?? null;
962
+ this.sessions.set(session.id, session);
963
+ } finally {
964
+ reservation.release();
965
+ }
932
966
  await this.installInputRecorder(session);
933
967
  await this.seedBufferedState(session);
934
968
  return session.getSummary();
@@ -1277,7 +1311,9 @@ export class FirefoxBidiSessionManager {
1277
1311
  found: true,
1278
1312
  clicked: true,
1279
1313
  ...(delivery.resent ? { resent: true } : {}),
1280
- ...pointerFields(target, resolved, delivery.node ?? resolved.node),
1314
+ // The element as it was when the click was aimed at it: what it turns
1315
+ // into is in the changes the action reports.
1316
+ ...pointerFields(target, resolved),
1281
1317
  };
1282
1318
  }
1283
1319
 
@@ -1786,6 +1822,56 @@ export class FirefoxBidiSessionManager {
1786
1822
  );
1787
1823
  }
1788
1824
 
1825
+ async setDialogAnswers(sessionId, options) {
1826
+ const session = this.getSession(sessionId);
1827
+ return {
1828
+ sessionId: session.id,
1829
+ ...setDialogAnswers(session.dialogAnswers, options),
1830
+ };
1831
+ }
1832
+
1833
+ tabSessions(contextId) {
1834
+ return [...this.sessions.values()].filter(
1835
+ (session) => session.target.targetId === contextId,
1836
+ );
1837
+ }
1838
+
1839
+ // The top-level context a prompt's context belongs to: itself, or for an
1840
+ // iframe, the tab around it. Only an unknown context costs a lookup.
1841
+ async promptTab(contextId) {
1842
+ if (this.tabSessions(contextId).length > 0) {
1843
+ return contextId;
1844
+ }
1845
+ try {
1846
+ const { contexts = [] } = await this.send("browsingContext.getTree", {});
1847
+ const contains = (node) =>
1848
+ node.context === contextId || (node.children ?? []).some(contains);
1849
+ return contexts.find(contains)?.context ?? contextId;
1850
+ } catch {
1851
+ return contextId;
1852
+ }
1853
+ }
1854
+
1855
+ // Answers a prompt as its tab's sessions say, or with the defaults when no
1856
+ // session is attached. A prompt Firefox handles itself (handler other than
1857
+ // ignore) is left to it, so no once answer is used up.
1858
+ async answerUserPrompt(contextId, params) {
1859
+ if (params.handler !== undefined && params.handler !== "ignore") {
1860
+ return;
1861
+ }
1862
+ const [session] = this.tabSessions(await this.promptTab(contextId));
1863
+ const { accept, text } = answerDialog(
1864
+ session?.dialogAnswers ?? createDialogAnswers(),
1865
+ params.type,
1866
+ params.defaultValue,
1867
+ );
1868
+ this.send("browsingContext.handleUserPrompt", {
1869
+ context: contextId,
1870
+ accept,
1871
+ ...(text === undefined ? {} : { userText: text }),
1872
+ }).catch(() => {});
1873
+ }
1874
+
1789
1875
  async setViewport(sessionId, options) {
1790
1876
  const session = this.getSession(sessionId);
1791
1877
  const params = {
@@ -2157,6 +2243,21 @@ export class FirefoxBidiSessionManager {
2157
2243
  });
2158
2244
  }
2159
2245
 
2246
+ async queryElements(sessionId, options = {}) {
2247
+ const session = this.getSession(sessionId);
2248
+ const route = parseFrameRef(options.selector);
2249
+ if (route) {
2250
+ return frameElementQuery({
2251
+ route,
2252
+ frameKeys: this.frameKeys(session),
2253
+ runInFrame: (key, payload, runOptions) =>
2254
+ this.runInFrame(session, key, payload, runOptions),
2255
+ options,
2256
+ });
2257
+ }
2258
+ return this.runSnapshotAction(sessionId, { action: "query", ...options });
2259
+ }
2260
+
2160
2261
  // Counts trusted input from the start of every later document, and from
2161
2262
  // now on in the current one, so input actions can check that their input
2162
2263
  // arrived. Without it they are reported as sent, unchecked.
@@ -93,6 +93,23 @@ function findJsonMessage(buffer) {
93
93
  return null;
94
94
  }
95
95
 
96
+ // A JSON.parse error quotes part of the input, which can hold tool
97
+ // arguments, and the server logs this error, so it keeps only the size and,
98
+ // when V8 reports one, the position.
99
+ function parseMessage(text) {
100
+ try {
101
+ return JSON.parse(text);
102
+ } catch (error) {
103
+ const bytes = Buffer.byteLength(text, "utf8");
104
+ const position = /at position (\d+)/.exec(error.message)?.[1];
105
+ // No cause: it would carry the quoted input along.
106
+ // eslint-disable-next-line preserve-caught-error
107
+ throw new Error(
108
+ `Invalid JSON message (${bytes} bytes${position === undefined ? "" : `, error at character ${position}`})`,
109
+ );
110
+ }
111
+ }
112
+
96
113
  export function encodeMessage(message, transportMode = "content-length") {
97
114
  const payload = Buffer.from(JSON.stringify(message), "utf8");
98
115
  if (transportMode === "json") {
@@ -147,7 +164,7 @@ export class MessageBuffer {
147
164
  const body = this.buffer.slice(bodyStart, bodyEnd).toString("utf8");
148
165
  this.buffer = this.buffer.slice(bodyEnd);
149
166
  this.transportMode ??= "content-length";
150
- messages.push(JSON.parse(body));
167
+ messages.push(parseMessage(body));
151
168
  continue;
152
169
  }
153
170
 
@@ -159,7 +176,7 @@ export class MessageBuffer {
159
176
  const { consumedBytes, jsonText } = jsonMatch;
160
177
  this.buffer = this.buffer.slice(consumedBytes);
161
178
  this.transportMode ??= "json";
162
- messages.push(JSON.parse(jsonText));
179
+ messages.push(parseMessage(jsonText));
163
180
  }
164
181
  }
165
182
  }
package/src/logger.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { appendFileSync } from "node:fs";
1
+ import { appendFileSync, renameSync, statSync } from "node:fs";
2
2
  import process from "node:process";
3
3
 
4
4
  import { PACKAGE_NAME } from "./package-info.mjs";
@@ -10,6 +10,18 @@ export const LOG_LEVELS = {
10
10
  debug: 3,
11
11
  };
12
12
 
13
+ // When the log file would grow past this, it is renamed to `<file>.1`
14
+ // (replacing any older one) and a new file is started.
15
+ export const LOG_FILE_MAX_BYTES = 10 * 1024 * 1024;
16
+
17
+ function fileSize(filePath) {
18
+ try {
19
+ return statSync(filePath).size;
20
+ } catch {
21
+ return 0;
22
+ }
23
+ }
24
+
13
25
  function normalizeMessage(message) {
14
26
  if (message instanceof Error) {
15
27
  return message.message;
@@ -23,11 +35,30 @@ export function createLogger({
23
35
  output = process.stderr,
24
36
  name = PACKAGE_NAME,
25
37
  filePath = null,
38
+ maxFileBytes = LOG_FILE_MAX_BYTES,
26
39
  } = {}) {
27
40
  const threshold = LOG_LEVELS[level] ?? LOG_LEVELS.error;
41
+ let outputEnabled = true;
42
+
43
+ function appendToFile(line) {
44
+ try {
45
+ const size = fileSize(filePath);
46
+ if (size > 0 && size + Buffer.byteLength(line) > maxFileBytes) {
47
+ renameSync(filePath, `${filePath}.1`);
48
+ }
49
+ appendFileSync(filePath, line);
50
+ } catch {
51
+ // ignore file write errors to avoid crashing the server
52
+ }
53
+ }
28
54
 
29
55
  return {
30
56
  level,
57
+ // Stops writing to `output`, for example once its reader is gone; the
58
+ // log file still gets every line.
59
+ disableOutput() {
60
+ outputEnabled = false;
61
+ },
31
62
  enabled(messageLevel) {
32
63
  return (LOG_LEVELS[messageLevel] ?? -1) <= threshold;
33
64
  },
@@ -37,14 +68,16 @@ export function createLogger({
37
68
  }
38
69
 
39
70
  const line = `[${name}] ${messageLevel}: ${normalizeMessage(message)}\n`;
40
- output.write(line);
41
- if (filePath != null) {
71
+ if (outputEnabled) {
42
72
  try {
43
- appendFileSync(filePath, line);
73
+ output.write(line);
44
74
  } catch {
45
- // ignore file write errors to avoid crashing the server
75
+ outputEnabled = false;
46
76
  }
47
77
  }
78
+ if (filePath != null) {
79
+ appendToFile(line);
80
+ }
48
81
  return true;
49
82
  },
50
83
  error(message, options) {
@@ -18,7 +18,11 @@ import { PACKAGE_NAME, PACKAGE_VERSION } from "./package-info.mjs";
18
18
  import { StepRunner, runStepsTool, stepSchema } from "./run-steps.mjs";
19
19
  import { TOOL_GROUPS } from "./tool-sets.mjs";
20
20
  import { TabRunner, runTabsTool } from "./run-tabs.mjs";
21
- import { asToolResult } from "./tool-results.mjs";
21
+ import {
22
+ asToolResult,
23
+ summarizeElement,
24
+ summarizeWaitedElement,
25
+ } from "./tool-results.mjs";
22
26
 
23
27
  const SERVER_NAME = PACKAGE_NAME;
24
28
 
@@ -250,13 +254,26 @@ export class McpBrowserDevToolsServer {
250
254
  // stay reachable through more_tools and as run_steps and run_tabs
251
255
  // steps, which can use every session tool.
252
256
  const enabled = this.config.tools;
257
+ // Tools that act on an element or wait for one describe it in one
258
+ // line; inspect_element returns the full description.
253
259
  const all = [
254
260
  ...browserTools(this),
255
261
  ...stateTools(this),
256
262
  ...actionTools(this),
257
263
  ...inspectionTools(this),
258
264
  ...performanceTools(this),
259
- ];
265
+ ].map(([name, tool]) => [
266
+ name,
267
+ name === "inspect_element"
268
+ ? tool
269
+ : {
270
+ ...tool,
271
+ handler: async (...args) =>
272
+ (name === "wait_for" ? summarizeWaitedElement : summarizeElement)(
273
+ await tool.handler(...args),
274
+ ),
275
+ },
276
+ ]);
260
277
  const tools = all.filter(([name]) => !enabled || enabled.has(name));
261
278
  const hidden = new Map(
262
279
  all.filter(([name]) => enabled && !enabled.has(name)),
@@ -372,7 +389,7 @@ export class McpBrowserDevToolsServer {
372
389
  name: SERVER_NAME,
373
390
  version: SERVER_VERSION,
374
391
  },
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.`,
392
+ 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). a >> b is b inside a, and has-text=Foo filters by text: tr >> has-text=Ada >> text=Delete. 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.`,
376
393
  });
377
394
  case "notifications/initialized":
378
395
  return null;
@@ -174,10 +174,13 @@ export const MAX_SNAPSHOT_FRAMES = 10;
174
174
  export function parseFrameRef(selector) {
175
175
  const match =
176
176
  typeof selector === "string"
177
- ? selector.trim().match(/^ref=f(\d+)(e\d+)$/)
177
+ ? selector.trim().match(/^ref=f(\d+)(e\d+)(\s+>>\s.*)?$/s)
178
178
  : null;
179
179
  return match
180
- ? { frameKey: `f${match[1]}`, selector: `ref=${match[2]}` }
180
+ ? {
181
+ frameKey: `f${match[1]}`,
182
+ selector: `ref=${match[2]}${match[3] ?? ""}`,
183
+ }
181
184
  : null;
182
185
  }
183
186
 
@@ -257,6 +260,21 @@ export function shiftFramePoints(result, offset) {
257
260
  y: result.point.y + offset.y,
258
261
  };
259
262
  }
263
+ if (Array.isArray(result.elements)) {
264
+ const tenth = (value) => Math.round(value * 10) / 10;
265
+ shifted.elements = result.elements.map((element) =>
266
+ element?.box
267
+ ? {
268
+ ...element,
269
+ box: {
270
+ ...element.box,
271
+ x: tenth(element.box.x + offset.x),
272
+ y: tenth(element.box.y + offset.y),
273
+ },
274
+ }
275
+ : element,
276
+ );
277
+ }
260
278
  if (result.node?.box) {
261
279
  const box = result.node.box;
262
280
  shifted.node = {
@@ -367,6 +385,43 @@ export async function frameElementSnapshot({
367
385
  };
368
386
  }
369
387
 
388
+ // query_elements inside a frame, for a locator that starts with a frame
389
+ // ref: the elements' refs carry the frame's key, and their boxes are in the
390
+ // top page's viewport. The frame is not scrolled into view.
391
+ export async function frameElementQuery({
392
+ route,
393
+ frameKeys,
394
+ runInFrame,
395
+ options,
396
+ }) {
397
+ const entry = frameKeys.get(route.frameKey);
398
+ if (!entry) {
399
+ return unknownFrame(route.frameKey, options.selector);
400
+ }
401
+ const result = await runInFrame(
402
+ route.frameKey,
403
+ {
404
+ action: "query",
405
+ ...options,
406
+ selector: route.selector,
407
+ refStart: entry.refStart ?? 1,
408
+ },
409
+ { scroll: false },
410
+ );
411
+ if (!Array.isArray(result?.elements)) {
412
+ return restoreFrameSelector(result, route, options.selector);
413
+ }
414
+ const { elements, ...rest } = takeNextRef(entry, result);
415
+ return {
416
+ ...rest,
417
+ selector: options.selector,
418
+ elements: elements.map((element) => ({
419
+ ...element,
420
+ ref: `${route.frameKey}${element.ref}`,
421
+ })),
422
+ };
423
+ }
424
+
370
425
  // The scope a delivery probe was armed in: the frame of a frame ref, else
371
426
  // the top document. Passed as the probe's selector, so it is read there.
372
427
  export function probeScope(target) {