mcp-browser-dev-tools 0.2.2 → 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.
package/src/run-steps.mjs CHANGED
@@ -1,3 +1,5 @@
1
+ import { CHANGE_REPORTING_TOOLS } from "./action-changes.mjs";
2
+ import { parseFrameRef } from "./page-context.mjs";
1
3
  import { validateValue } from "./json-schema.mjs";
2
4
  import { checkPageCondition, normalizeWaitForOptions } from "./wait-for.mjs";
3
5
  import { asImageToolResult, moveScreenshotImage } from "./tool-results.mjs";
@@ -93,20 +95,21 @@ export function repeatStepSchema(conditionOptions) {
93
95
  };
94
96
  }
95
97
 
96
- export function stepSchema(stepTools) {
98
+ // Without stepTools, the schema leaves the tool names out: the definitions
99
+ // clients see describe them in a few words, and prepareSteps still checks
100
+ // each step against the full list.
101
+ export function stepSchema(stepTools = null) {
97
102
  return {
98
103
  type: "object",
99
104
  properties: {
100
105
  tool: {
101
106
  type: "string",
102
- enum: ["sleep", "if", "repeat", ...stepTools],
103
- description:
104
- "A tool that takes sessionId, sleep to pause, if to branch, or repeat to loop.",
107
+ ...(stepTools ? { enum: ["sleep", "if", "repeat", ...stepTools] } : {}),
108
+ description: "A tool that takes sessionId, or sleep, if, repeat.",
105
109
  },
106
110
  arguments: {
107
111
  type: "object",
108
- description:
109
- "The tool's arguments without sessionId (default {}). sleep takes { ms }; if takes { condition, then, elseIf, else }; repeat takes { steps, until, max }.",
112
+ description: "The tool's arguments without sessionId.",
110
113
  },
111
114
  },
112
115
  required: ["tool"],
@@ -114,26 +117,21 @@ export function stepSchema(stepTools) {
114
117
  };
115
118
  }
116
119
 
117
- export function runStepsInputSchema(stepTools) {
120
+ export function runStepsInputSchema() {
118
121
  return {
119
122
  type: "object",
120
123
  properties: {
121
- sessionId: {
122
- type: "string",
123
- description:
124
- "Session id returned by attach_tab. Every step runs on this session.",
125
- },
124
+ sessionId: { type: "string" },
126
125
  steps: {
127
126
  type: "array",
128
127
  minItems: 1,
129
128
  maxItems: MAX_RUN_STEPS,
130
- description: `Steps to run in order (at most ${MAX_RUN_STEPS}, counting steps inside if branches and repeat bodies once; if and repeat nest at most ${MAX_STEP_DEPTH} deep).`,
131
- items: stepSchema(stepTools),
129
+ description: `At most ${MAX_RUN_STEPS}, counting nested steps.`,
130
+ items: stepSchema(),
132
131
  },
133
132
  continueOnError: {
134
133
  type: "boolean",
135
- description:
136
- "Run the remaining steps after a step fails (default false: stop at the first failure).",
134
+ description: "Default false.",
137
135
  },
138
136
  },
139
137
  required: ["sessionId", "steps"],
@@ -181,11 +179,53 @@ export function extractStepImages(tool, result, images) {
181
179
  return result;
182
180
  }
183
181
 
182
+ // Whether a prepared batch runs an action that reports its changes,
183
+ // including inside if branches and repeat bodies.
184
+ function containsChangeReportingStep(steps) {
185
+ return steps.some(
186
+ (step) =>
187
+ CHANGE_REPORTING_TOOLS.has(step.tool) ||
188
+ (step.steps && containsChangeReportingStep(step.steps)) ||
189
+ (step.branches &&
190
+ step.branches.some((branch) =>
191
+ containsChangeReportingStep(branch.steps),
192
+ )) ||
193
+ (step.else && containsChangeReportingStep(step.else)),
194
+ );
195
+ }
196
+
197
+ // The frame a batch acts in, when every action in it names an element of
198
+ // the same frame by a frame ref; its changes are then that frame's.
199
+ function batchFrame(steps) {
200
+ const frames = new Set();
201
+ const visit = (list) => {
202
+ for (const step of list) {
203
+ if (CHANGE_REPORTING_TOOLS.has(step.tool)) {
204
+ frames.add(parseFrameRef(step.args?.selector)?.frameKey ?? null);
205
+ }
206
+ visit(step.steps ?? []);
207
+ for (const branch of step.branches ?? []) {
208
+ visit(branch.steps);
209
+ }
210
+ visit(step.else ?? []);
211
+ }
212
+ };
213
+ visit(steps);
214
+ return frames.size === 1 ? [...frames][0] : null;
215
+ }
216
+
184
217
  // Validates and runs run_steps batches against the server's tools.
185
218
  export class StepRunner {
186
- constructor({ getTools, browserAdapter, stepSchema, conditionOptions }) {
219
+ constructor({
220
+ getTools,
221
+ browserAdapter,
222
+ changeTracker = null,
223
+ stepSchema,
224
+ conditionOptions,
225
+ }) {
187
226
  this.getTools = getTools;
188
227
  this.browserAdapter = browserAdapter;
228
+ this.changeTracker = changeTracker;
189
229
  this.stepSchema = stepSchema;
190
230
  this.conditionOptions = conditionOptions;
191
231
  }
@@ -396,9 +436,13 @@ export class StepRunner {
396
436
  } else {
397
437
  // run_tabs prepares steps before it opens their tab, so the session
398
438
  // comes from the context rather than the prepared arguments.
439
+ // The batch reports its changes once, at the end.
399
440
  result = await this.getTools()
400
441
  .get(step.tool)
401
- .handler({ ...step.args, sessionId: context.sessionId });
442
+ .handler(
443
+ { ...step.args, sessionId: context.sessionId },
444
+ { reportChanges: false },
445
+ );
402
446
  }
403
447
 
404
448
  const entry = {
@@ -411,7 +455,8 @@ export class StepRunner {
411
455
  if (result?.found === false && step.tool !== "inspect_element") {
412
456
  entry.ok = false;
413
457
  entry.error =
414
- result.error ?? `No element matches selector ${step.args.selector}`;
458
+ result.error ??
459
+ `No element matches selector ${result.selector ?? step.args.selector}`;
415
460
  }
416
461
  return entry;
417
462
  }
@@ -475,9 +520,16 @@ export class StepRunner {
475
520
  // Validate every step, including both branches of each if, first, so a
476
521
  // typo in a late step does not leave the page half-changed.
477
522
  const steps = this.prepareSteps(args.steps, context, "arguments.steps", 0);
523
+ const baseline =
524
+ this.changeTracker && containsChangeReportingStep(steps)
525
+ ? await this.changeTracker.begin(args.sessionId, batchFrame(steps))
526
+ : null;
478
527
  const results = await this.executeSteps(steps, context);
479
528
  const ok =
480
529
  results.length === steps.length && results.every((result) => result.ok);
530
+ const changes = baseline
531
+ ? { changes: await this.changeTracker.settle(baseline) }
532
+ : {};
481
533
 
482
534
  return {
483
535
  value: {
@@ -486,6 +538,7 @@ export class StepRunner {
486
538
  ranSteps: results.length,
487
539
  skippedSteps: steps.length - results.length,
488
540
  steps: results,
541
+ ...changes,
489
542
  ...(ok ? {} : await this.describePageAfterFailure(args.sessionId)),
490
543
  },
491
544
  images: context.images,
@@ -493,15 +546,14 @@ export class StepRunner {
493
546
  }
494
547
  }
495
548
 
496
- export function runStepsTool(runner, stepTools) {
549
+ export function runStepsTool(runner) {
497
550
  return [
498
551
  "run_steps",
499
552
  {
500
553
  definition: {
501
554
  name: "run_steps",
502
- description:
503
- 'Run tools on one attached session in order, in a single call, to act and check the result together: [{"tool":"click","arguments":{"selector":"text=Save"}},{"tool":"wait_for","arguments":{"selector":"#status","textIncludes":"Saved"}},{"tool":"take_screenshot"}]. Each step names a tool that takes sessionId (or sleep) with that tool\'s arguments minus sessionId. if branches once, without waiting, on conditions with the wait_for fields: {"tool":"if","arguments":{"condition":{"selector":"text=Accept cookies"},"then":[...],"elseIf":[{"condition":{...},"then":[...]}],"else":[...]}}; the result reports the branch taken and what each condition observed. repeat retries or polls: {"tool":"repeat","arguments":{"steps":[...],"until":{"selector":"#list","textIncludes":"Order #1042"},"max":5}} runs its steps, then checks until once, at most max passes (default 5, at most 10); it fails if until never holds, and a failing step ends the loop. All steps are validated before any runs. A step fails when its tool throws or reports found: false (except inspect_element); the batch stops there unless continueOnError, and the result then includes page, the visible controls with a locator for each. Screenshots come back as image content; each step result keeps image, its 1-based position. Prefer wait_for over sleep.',
504
- inputSchema: runStepsInputSchema(stepTools),
555
+ description: `Run session tools in order in one call: [{"tool":"type","arguments":{"selector":"ref=e3","text":"Ada"}},{"tool":"click","arguments":{"selector":"text=Save"}}]. Arguments omit sessionId. Also: sleep {ms}; if {condition, then, elseIf: [{condition, then}], else}, which branches once on wait_for fields; repeat {steps, until, max (default ${DEFAULT_REPEAT})}, which reruns steps until until holds. All steps are validated first. A step fails when it throws or reports found: false (not inspect_element); the batch stops there unless continueOnError and reports the page's controls. A batch with actions returns one changes for the whole batch. Prefer wait_for to sleep.`,
556
+ inputSchema: runStepsInputSchema(),
505
557
  },
506
558
  handler: async (args) => runner.runSteps(args),
507
559
  formatResult: asImageToolResult,
package/src/run-tabs.mjs CHANGED
@@ -14,26 +14,24 @@ export function runTabsInputSchema(stepTools, browserFamily) {
14
14
  type: "array",
15
15
  minItems: 1,
16
16
  maxItems: MAX_TABS,
17
- description: `At most ${MAX_TABS}, each with url (opens a new tab there) or sessionId (an attached tab), plus its steps.`,
17
+ description: `At most ${MAX_TABS}, each with url or sessionId, and steps.`,
18
18
  items: {
19
19
  type: "object",
20
20
  properties: {
21
21
  url: {
22
22
  type: "string",
23
- description:
24
- "Open a new tab, attach to it, and load this URL before the steps.",
23
+ description: "Open this in a new tab.",
25
24
  },
26
25
  waitUntil: waitUntilProperty(),
27
26
  sessionId: {
28
27
  type: "string",
29
- description:
30
- "Run the steps in this attached session instead of opening a tab.",
28
+ description: "Use this session instead.",
31
29
  },
32
30
  steps: {
33
31
  type: "array",
34
32
  maxItems: MAX_RUN_STEPS,
35
- description: `Steps to run in this tab, as in run_steps (at most ${MAX_RUN_STEPS}, default none).`,
36
- items: withoutDescriptions(stepSchema(stepTools)),
33
+ description: "As in run_steps.",
34
+ items: withoutDescriptions(stepSchema()),
37
35
  },
38
36
  },
39
37
  additionalProperties: false,
@@ -44,8 +42,7 @@ export function runTabsInputSchema(stepTools, browserFamily) {
44
42
  browserFamily: {
45
43
  type: "string",
46
44
  enum: ["chromium", "firefox"],
47
- description:
48
- "Browser to open the url tabs in. Required when a tab gives url.",
45
+ description: "Required for url tabs in auto mode.",
49
46
  },
50
47
  }
51
48
  : {}),
@@ -53,23 +50,21 @@ export function runTabsInputSchema(stepTools, browserFamily) {
53
50
  type: "integer",
54
51
  minimum: 1,
55
52
  maximum: MAX_TABS,
56
- description: `How many tabs run at once (default: all of them, at most ${MAX_TABS}). Lower it for sites that limit how fast they are read.`,
53
+ description: "Tabs at once (default all).",
57
54
  },
58
55
  timeoutMs: {
59
56
  type: "integer",
60
57
  minimum: 1,
61
58
  maximum: MAX_TAB_TIMEOUT_MS,
62
- description: `How long each tab may take, from opening to its last step, before it fails (default ${DEFAULT_TAB_TIMEOUT_MS}).`,
59
+ description: `ms per tab (default ${DEFAULT_TAB_TIMEOUT_MS}).`,
63
60
  },
64
61
  keepTabs: {
65
62
  type: "boolean",
66
- description:
67
- "Leave the tabs opened for url open and attached, and report their sessionId (default false: close them).",
63
+ description: "Keep url tabs open and attached (default false).",
68
64
  },
69
65
  continueOnError: {
70
66
  type: "boolean",
71
- description:
72
- "Within each tab, run the remaining steps after a step fails (default false). A failing tab never stops the others.",
67
+ description: "Within each tab (default false).",
73
68
  },
74
69
  },
75
70
  required: ["tabs"],
@@ -281,7 +276,7 @@ export function runTabsTool(runner, stepTools, configuredFamily) {
281
276
  {
282
277
  definition: {
283
278
  name: "run_tabs",
284
- description: `Run step lists in several tabs at the same time and return every tab's results in one reply, for example to read search results side by side: {"tabs":[{"url":"https://example.com/a","steps":[{"tool":"read_text"}]},{"url":"https://example.com/b","steps":[{"tool":"read_text"}]}]}. A url tab opens a new tab, loads it, runs its steps, and closes unless keepTabs; a sessionId tab uses that attached tab. Steps are as in run_steps and are all validated first. Tabs run at once (at most ${MAX_TABS}; concurrency lowers that); each has timeoutMs (default ${DEFAULT_TAB_TIMEOUT_MS}) and fails without stopping the others.`,
279
+ description: `Run steps in several tabs at once and get every tab's results in one reply: {"tabs":[{"url":"https://a.example","steps":[{"tool":"read_text"}]},{"url":"https://b.example","steps":[{"tool":"read_text"}]}]}. A url tab opens, runs its steps, and closes unless keepTabs; a sessionId tab uses that session. Steps are as in run_steps. A tab that fails or passes timeoutMs does not stop the others.`,
285
280
  inputSchema: runTabsInputSchema(stepTools, configuredFamily),
286
281
  },
287
282
  handler: async (args) => runner.runTabs(args, configuredFamily),
@@ -112,6 +112,88 @@ export async function writeScreenshotFile(filePath, image, overwrite) {
112
112
  return filePath;
113
113
  }
114
114
 
115
+ // The pixel size from a PNG, JPEG, or WebP header, or null.
116
+ export function imageSize(image) {
117
+ if (image.length >= 24 && image.readUInt32BE(0) === 0x89504e47) {
118
+ return { width: image.readUInt32BE(16), height: image.readUInt32BE(20) };
119
+ }
120
+ if (image.length >= 4 && image[0] === 0xff && image[1] === 0xd8) {
121
+ let offset = 2;
122
+ while (offset + 9 < image.length && image[offset] === 0xff) {
123
+ const marker = image[offset + 1];
124
+ const length = image.readUInt16BE(offset + 2);
125
+ const frame =
126
+ marker >= 0xc0 &&
127
+ marker <= 0xcf &&
128
+ ![0xc4, 0xc8, 0xcc].includes(marker);
129
+ if (frame) {
130
+ return {
131
+ width: image.readUInt16BE(offset + 7),
132
+ height: image.readUInt16BE(offset + 5),
133
+ };
134
+ }
135
+ offset += 2 + length;
136
+ }
137
+ return null;
138
+ }
139
+ if (
140
+ image.length >= 30 &&
141
+ image.toString("ascii", 0, 4) === "RIFF" &&
142
+ image.toString("ascii", 8, 12) === "WEBP"
143
+ ) {
144
+ const chunk = image.toString("ascii", 12, 16);
145
+ if (chunk === "VP8 ") {
146
+ return {
147
+ width: image.readUInt16LE(26) & 0x3fff,
148
+ height: image.readUInt16LE(28) & 0x3fff,
149
+ };
150
+ }
151
+ if (chunk === "VP8L") {
152
+ const bits = image.readUInt32LE(21);
153
+ return {
154
+ width: (bits & 0x3fff) + 1,
155
+ height: ((bits >> 14) & 0x3fff) + 1,
156
+ };
157
+ }
158
+ if (chunk === "VP8X") {
159
+ return {
160
+ width: image.readUIntLE(24, 3) + 1,
161
+ height: image.readUIntLE(27, 3) + 1,
162
+ };
163
+ }
164
+ }
165
+ return null;
166
+ }
167
+
168
+ // Where the image sits in the viewport and how many image pixels make one
169
+ // CSS pixel, so a point seen in the image converts to click coordinates:
170
+ // x = cssRect.x + imageX / scale. An element's screenshot covers its clip;
171
+ // a page screenshot covers the viewport.
172
+ async function screenshotGeometry(server, sessionId, screenshot) {
173
+ const size = imageSize(Buffer.from(screenshot.data, "base64"));
174
+ if (!size) {
175
+ return {};
176
+ }
177
+ let cssRect;
178
+ if (screenshot.clip) {
179
+ const { x, y, width, height } = screenshot.clip;
180
+ cssRect = { x, y, width, height };
181
+ } else {
182
+ try {
183
+ const { viewport } = await server.browserAdapter.getPageState(sessionId);
184
+ cssRect = { x: 0, y: 0, width: viewport.width, height: viewport.height };
185
+ } catch {
186
+ return { ...size };
187
+ }
188
+ }
189
+ const scale = cssRect.width > 0 ? size.width / cssRect.width : null;
190
+ return {
191
+ ...size,
192
+ cssRect,
193
+ ...(scale ? { scale: Math.round(scale * 1000) / 1000 } : {}),
194
+ };
195
+ }
196
+
115
197
  export async function takeScreenshot(server, args) {
116
198
  const { output, format, filePath } = screenshotTarget(
117
199
  args,
@@ -124,7 +206,16 @@ export async function takeScreenshot(server, args) {
124
206
  selector: args.selector,
125
207
  },
126
208
  );
127
- if (output !== "file" || screenshot?.found === false) {
209
+ if (screenshot?.found === false) {
210
+ return screenshot;
211
+ }
212
+ if (typeof screenshot?.data === "string") {
213
+ Object.assign(
214
+ screenshot,
215
+ await screenshotGeometry(server, args.sessionId, screenshot),
216
+ );
217
+ }
218
+ if (output !== "file") {
128
219
  return screenshot;
129
220
  }
130
221
 
@@ -6,6 +6,63 @@ function normalizeLimit(limit, fallback = 50) {
6
6
  return Number.isInteger(limit) && limit > 0 ? limit : fallback;
7
7
  }
8
8
 
9
+ const IN_FLIGHT_LIMIT = 500;
10
+ // The requests a page's result depends on. Images, scripts, and styles are
11
+ // left out, and so are long-lived connections (WebSocket, EventSource) and
12
+ // beacons. A request of unknown type (from a Firefox that does not report
13
+ // it) is kept.
14
+ const IN_FLIGHT_TYPES = new Set(["document", "fetch", "xhr"]);
15
+
16
+ function dependsOn(event) {
17
+ const type = String(event.resourceType ?? "").toLowerCase();
18
+ return (
19
+ /^https?:/i.test(event.url ?? "") &&
20
+ (!type || IN_FLIGHT_TYPES.has(type) || Boolean(event.navigation))
21
+ );
22
+ }
23
+
24
+ // The http(s) document, fetch, and XHR requests that started and have not
25
+ // finished, kept apart from the bounded event buffer so a slow request is
26
+ // not forgotten when its start event is evicted. Only these are kept, so a
27
+ // burst of images cannot push them out. A redirect hop restarts a request
28
+ // under the same id, after BiDi has completed the previous hop. The oldest
29
+ // entries are dropped past the limit, since a request whose end is never
30
+ // reported would otherwise stay.
31
+ export class InFlightRequests {
32
+ constructor(limit = IN_FLIGHT_LIMIT) {
33
+ this.limit = limit;
34
+ this.requests = new Map();
35
+ }
36
+
37
+ observe(event) {
38
+ if (event?.kind !== "network" || !event.requestId) {
39
+ return;
40
+ }
41
+ if (event.phase === "request") {
42
+ if (!dependsOn(event)) {
43
+ return;
44
+ }
45
+ const previous = this.requests.get(event.requestId);
46
+ this.requests.delete(event.requestId);
47
+ this.requests.set(event.requestId, {
48
+ url: event.url ?? null,
49
+ resourceType: event.resourceType ?? null,
50
+ navigation: event.navigation ?? null,
51
+ startedAt: previous?.startedAt ?? event.capturedAt ?? null,
52
+ });
53
+ if (this.requests.size > this.limit) {
54
+ this.requests.delete(this.requests.keys().next().value);
55
+ }
56
+ } else if (event.completed) {
57
+ this.requests.delete(event.requestId);
58
+ }
59
+ }
60
+
61
+ list() {
62
+ return Array.from(this.requests.values());
63
+ }
64
+ }
65
+
9
66
  export function filterConsoleMessages(events = [], limit = 50) {
10
67
  const safeLimit = normalizeLimit(limit);
11
68
  return events