mcp-browser-dev-tools 0.2.2 → 0.4.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.
@@ -14,6 +14,28 @@ import {
14
14
  import { selectorProperty, sessionWithLimitSchema } from "../tool-schemas.mjs";
15
15
 
16
16
  const DEFAULT_READ_CHARS = 8000;
17
+ const DEFAULT_SNAPSHOT_NODES = 100;
18
+ const MAX_SNAPSHOT_NODES = 500;
19
+
20
+ // The snapshot's nodes are lines already; send them as plain text rather than
21
+ // a JSON array, which costs quotes and escapes on every line.
22
+ export function formatSnapshotResult(result) {
23
+ if (!Array.isArray(result?.nodes)) {
24
+ return asToolResult(result);
25
+ }
26
+ const { nodes, ...rest } = result;
27
+ const lines = [
28
+ `${rest.url ?? ""} ${JSON.stringify(rest.title ?? "")}`.trim(),
29
+ ...nodes,
30
+ ];
31
+ if (rest.more > 0) {
32
+ lines.push(`(${rest.more} more nodes; raise limit or pass a selector)`);
33
+ }
34
+ return {
35
+ content: [{ type: "text", text: lines.join("\n") }],
36
+ structuredContent: result,
37
+ };
38
+ }
17
39
  const MAX_READ_CHARS = 100_000;
18
40
  const DEFAULT_READ_LINKS = 50;
19
41
  const MAX_READ_LINKS = 200;
@@ -25,8 +47,7 @@ export function inspectionTools(server) {
25
47
  {
26
48
  definition: {
27
49
  name: "get_console_messages",
28
- description:
29
- "Read buffered console, log, and exception messages for an attached session.",
50
+ description: "Buffered console messages and exceptions.",
30
51
  inputSchema: sessionWithLimitSchema(),
31
52
  },
32
53
  handler: async (args) => ({
@@ -42,8 +63,7 @@ export function inspectionTools(server) {
42
63
  {
43
64
  definition: {
44
65
  name: "get_network_requests",
45
- description:
46
- "Summarize buffered network requests for an attached session in a DevTools-network-tab style view.",
66
+ description: "Buffered network requests.",
47
67
  inputSchema: sessionWithLimitSchema(),
48
68
  },
49
69
  handler: async (args) => ({
@@ -55,23 +75,58 @@ export function inspectionTools(server) {
55
75
  },
56
76
  ],
57
77
  [
58
- "get_document",
78
+ "get_snapshot",
59
79
  {
60
80
  definition: {
61
- name: "get_document",
62
- description: "Fetch the DOM document tree for an attached page.",
81
+ name: "get_snapshot",
82
+ description:
83
+ 'List visible headings and controls, one line each with a ref, role, name, and state, e.g. e3 textbox "Email" value="ada@example.com". ref=e3 works as any tool\'s selector until the page navigates; controls inside iframes get refs like f1e3. Far cheaper than get_document or a screenshot.',
63
84
  inputSchema: {
64
85
  type: "object",
65
86
  properties: {
66
- sessionId: {
87
+ sessionId: { type: "string" },
88
+ selector: {
67
89
  type: "string",
68
- description: "Session id returned by attach_tab.",
90
+ description: "Only inside this element.",
91
+ },
92
+ limit: {
93
+ type: "integer",
94
+ minimum: 1,
95
+ maximum: MAX_SNAPSHOT_NODES,
96
+ description: `Default ${DEFAULT_SNAPSHOT_NODES}.`,
69
97
  },
98
+ headings: {
99
+ type: "boolean",
100
+ description: "Default true.",
101
+ },
102
+ },
103
+ required: ["sessionId"],
104
+ additionalProperties: false,
105
+ },
106
+ },
107
+ handler: async (args) =>
108
+ server.browserAdapter.snapshotPage(args.sessionId, {
109
+ selector: args.selector,
110
+ limit: args.limit ?? DEFAULT_SNAPSHOT_NODES,
111
+ headings: args.headings ?? true,
112
+ }),
113
+ formatResult: formatSnapshotResult,
114
+ },
115
+ ],
116
+ [
117
+ "get_document",
118
+ {
119
+ definition: {
120
+ name: "get_document",
121
+ description: "The DOM tree (Firefox: the full HTML).",
122
+ inputSchema: {
123
+ type: "object",
124
+ properties: {
125
+ sessionId: { type: "string" },
70
126
  depth: {
71
127
  type: "integer",
72
128
  minimum: 1,
73
- description:
74
- "How many levels of child nodes to include (default 2). Chromium and Edge only; Firefox returns the full document HTML regardless.",
129
+ description: "Default 2.",
75
130
  },
76
131
  },
77
132
  required: ["sessionId"],
@@ -88,14 +143,11 @@ export function inspectionTools(server) {
88
143
  definition: {
89
144
  name: "inspect_element",
90
145
  description:
91
- "Describe one element: its box, visibility, role, accessible name, state, and styles. Scrolls it into view first, so the box reflects the scrolled position.",
146
+ "One element's box, visibility, role, name, state, and styles, after scrolling it into view.",
92
147
  inputSchema: {
93
148
  type: "object",
94
149
  properties: {
95
- sessionId: {
96
- type: "string",
97
- description: "Session id returned by attach_tab.",
98
- },
150
+ sessionId: { type: "string" },
99
151
  selector: selectorProperty(),
100
152
  },
101
153
  required: ["sessionId", "selector"],
@@ -111,30 +163,27 @@ export function inspectionTools(server) {
111
163
  {
112
164
  definition: {
113
165
  name: "read_text",
114
- description: `Read the visible text of the main content (main or role=main, else a single article, else the body), or of selector, as plain lines up to maxChars. With links, also list its links with text and absolute URL, for example search results. inspect_element clips text to 400 characters.`,
166
+ description: `Visible text of the main content, or of selector, as lines up to maxChars; with links, also its links.`,
115
167
  inputSchema: {
116
168
  type: "object",
117
169
  properties: {
118
- sessionId: {
119
- type: "string",
120
- description: "Session id returned by attach_tab.",
121
- },
170
+ sessionId: { type: "string" },
122
171
  selector: selectorProperty(),
123
172
  maxChars: {
124
173
  type: "integer",
125
174
  minimum: 1,
126
175
  maximum: MAX_READ_CHARS,
127
- description: `Most characters of text to return (default ${DEFAULT_READ_CHARS}, at most ${MAX_READ_CHARS}); totalChars and truncated tell whether there was more.`,
176
+ description: `Default ${DEFAULT_READ_CHARS}.`,
128
177
  },
129
178
  links: {
130
179
  type: "boolean",
131
- description: `Also return the http(s) links inside, deduplicated, at most maxLinks (default false).`,
180
+ description: `Also list http(s) links (default false).`,
132
181
  },
133
182
  maxLinks: {
134
183
  type: "integer",
135
184
  minimum: 1,
136
185
  maximum: MAX_READ_LINKS,
137
- description: `Most links to return (default ${DEFAULT_READ_LINKS}, at most ${MAX_READ_LINKS}); moreLinks counts the rest.`,
186
+ description: `Default ${DEFAULT_READ_LINKS}.`,
138
187
  },
139
188
  },
140
189
  required: ["sessionId"],
@@ -156,35 +205,29 @@ export function inspectionTools(server) {
156
205
  definition: {
157
206
  name: "take_screenshot",
158
207
  description:
159
- "Screenshot the page, or one element with selector. Returns base64 data in the JSON by default; output image returns image content instead, and output file (or path) writes a file and returns its path.",
208
+ "Screenshot the page or selector: base64 in the JSON (output data, default), image content (image), or a file (file, or path). cssRect and scale convert image pixels to x, y.",
160
209
  inputSchema: {
161
210
  type: "object",
162
211
  properties: {
163
- sessionId: {
164
- type: "string",
165
- description: "Session id returned by attach_tab.",
166
- },
212
+ sessionId: { type: "string" },
167
213
  format: {
168
214
  type: "string",
169
215
  enum: screenshotFormatsFor(server.config.browserFamily),
170
- description:
171
- "Image format (default png). With path, it must match the extension.",
216
+ description: "Default png; must match path's extension.",
172
217
  },
173
218
  selector: selectorProperty(),
174
219
  output: {
175
220
  type: "string",
176
221
  enum: ["data", "image", "file"],
177
- description:
178
- "data (default) puts base64 in the JSON, image returns image content with metadata in the JSON, file writes a file and returns its path (the default when path is given).",
222
+ description: "Default data; file when path is given.",
179
223
  },
180
224
  path: {
181
225
  type: "string",
182
- description: `Absolute path for output file, ending in ${screenshotFileExtensions(server.config.browserFamily).join(", ")} (the extension sets the format); parent directories are created. Default: a new file in a private temp directory.`,
226
+ description: `Absolute, ending in ${screenshotFileExtensions(server.config.browserFamily).join(", ")}; default a temp file.`,
183
227
  },
184
228
  overwrite: {
185
229
  type: "boolean",
186
- description:
187
- "For output file: replace path if it already exists (default false: fail instead).",
230
+ description: "Replace an existing file.",
188
231
  },
189
232
  },
190
233
  required: ["sessionId"],
@@ -210,20 +253,15 @@ export function inspectionTools(server) {
210
253
  {
211
254
  definition: {
212
255
  name: "get_events",
213
- description:
214
- "Read buffered console, log, exception, and network events for an attached session.",
256
+ description: "Buffered console, network, page, and dialog events.",
215
257
  inputSchema: {
216
258
  type: "object",
217
259
  properties: {
218
- sessionId: {
219
- type: "string",
220
- description: "Session id returned by attach_tab.",
221
- },
260
+ sessionId: { type: "string" },
222
261
  limit: {
223
262
  type: "integer",
224
263
  minimum: 1,
225
- description:
226
- "Return the most recent N events from the session buffer (default 50).",
264
+ description: "Most recent N (default 50).",
227
265
  },
228
266
  },
229
267
  required: ["sessionId"],
@@ -246,28 +284,24 @@ export function inspectionTools(server) {
246
284
  {
247
285
  definition: {
248
286
  name: "evaluate_js",
249
- description: "Evaluate JavaScript in the attached page context.",
287
+ description:
288
+ "Run JavaScript in the page; top-level await works, and the last expression's value is returned.",
250
289
  inputSchema: {
251
290
  type: "object",
252
291
  properties: {
253
- sessionId: {
254
- type: "string",
255
- description: "Session id returned by attach_tab.",
256
- },
292
+ sessionId: { type: "string" },
257
293
  expression: {
258
294
  type: "string",
259
- description:
260
- "JavaScript to evaluate in the page's main world. Top-level await works, and the value of the last expression statement is returned.",
295
+ description: "JavaScript.",
261
296
  },
262
297
  awaitPromise: {
263
298
  type: "boolean",
264
- description:
265
- "Wait for a returned promise to settle and return its result (default true).",
299
+ description: "Default true.",
266
300
  },
267
301
  returnByValue: {
268
302
  type: "boolean",
269
303
  description:
270
- "Return a JSON value (default true); false returns a short description of the object. Chromium and Edge only; Firefox always returns a serialized value.",
304
+ "JSON value (default true); false gives a short description (Chromium only).",
271
305
  },
272
306
  },
273
307
  required: ["sessionId", "expression"],
@@ -0,0 +1,108 @@
1
+ import { validateValue } from "../json-schema.mjs";
2
+ import { asToolResult } from "../tool-results.mjs";
3
+ import { TOOL_GROUPS } from "../tool-sets.mjs";
4
+
5
+ function groupOf(name) {
6
+ return (
7
+ Object.entries(TOOL_GROUPS).find(([, names]) =>
8
+ names.includes(name),
9
+ )?.[0] ?? null
10
+ );
11
+ }
12
+
13
+ // The first sentence, ending at a period: descriptions use "?" inside
14
+ // glob syntax.
15
+ function firstSentence(text) {
16
+ const match = text.match(/^.*?\.(\s|$)/s);
17
+ return (match ? match[0] : text).trim();
18
+ }
19
+
20
+ // The tools MCP_BROWSER_TOOLS leaves out of the list are still there: this
21
+ // lists them, describes one, or calls one, so an agent can find and use a
22
+ // tool without every turn paying for its definition. run_steps and
23
+ // run_tabs steps can use them too.
24
+ export function moreToolsTool(hidden, advertise) {
25
+ const lookup = (name) => {
26
+ const tool = hidden.get(name);
27
+ if (!tool) {
28
+ throw new Error(
29
+ `${name} is not one of the tools more_tools offers: ${Array.from(hidden.keys()).join(", ")}`,
30
+ );
31
+ }
32
+ return tool;
33
+ };
34
+ return [
35
+ "more_tools",
36
+ {
37
+ definition: {
38
+ name: "more_tools",
39
+ description:
40
+ "Tools not listed here to keep each turn small: drag, cookies and storage, request mocking, HAR, performance, and more. No arguments lists them; name describes one; name with arguments calls it. They also work as run_steps steps.",
41
+ inputSchema: {
42
+ type: "object",
43
+ properties: {
44
+ name: { type: "string" },
45
+ arguments: {
46
+ type: "object",
47
+ description: "Call the tool with these arguments.",
48
+ },
49
+ },
50
+ additionalProperties: false,
51
+ },
52
+ },
53
+ handler: async (args, options) => {
54
+ if (args.name === undefined) {
55
+ if (args.arguments !== undefined) {
56
+ throw new Error("more_tools needs name to call a tool");
57
+ }
58
+ return {
59
+ tools: Array.from(hidden, ([name, tool]) => ({
60
+ name,
61
+ group: groupOf(name),
62
+ description: firstSentence(tool.definition.description),
63
+ })),
64
+ usage:
65
+ 'more_tools {"name":"set_network"} shows a tool\'s arguments; {"name":"set_network","arguments":{...}} calls it, as does a run_steps step.',
66
+ };
67
+ }
68
+ const tool = lookup(args.name);
69
+ if (args.arguments === undefined) {
70
+ return {
71
+ ...advertise(tool.definition),
72
+ group: groupOf(args.name),
73
+ };
74
+ }
75
+ validateValue(
76
+ "arguments.arguments",
77
+ args.arguments,
78
+ tool.definition.inputSchema,
79
+ );
80
+ tool.validate?.(args.arguments);
81
+ return tool.handler(args.arguments, options);
82
+ },
83
+ // A call's result is formatted as the tool itself would format it;
84
+ // the list goes as one line per tool, which costs less than JSON.
85
+ formatResult: (result, args) => {
86
+ if (args.name !== undefined && args.arguments !== undefined) {
87
+ return (lookup(args.name).formatResult ?? asToolResult)(
88
+ result,
89
+ args.arguments,
90
+ );
91
+ }
92
+ if (args.name !== undefined) {
93
+ return asToolResult(result);
94
+ }
95
+ const lines = result.tools.map(
96
+ ({ name, group, description }) =>
97
+ `${name} (${group}): ${description}`,
98
+ );
99
+ return {
100
+ content: [
101
+ { type: "text", text: [...lines, result.usage].join("\n") },
102
+ ],
103
+ structuredContent: result,
104
+ };
105
+ },
106
+ },
107
+ ];
108
+ }
@@ -0,0 +1,183 @@
1
+ import { lstat, mkdtemp, writeFile } from "node:fs/promises";
2
+ import { tmpdir } from "node:os";
3
+ import path from "node:path";
4
+
5
+ import {
6
+ SCREENSHOT_FILE_MODE,
7
+ writeScreenshotFile,
8
+ } from "../screenshot-output.mjs";
9
+ import { sessionSchema } from "../tool-schemas.mjs";
10
+ import { checkVideoPath, encodeVideo } from "../video-output.mjs";
11
+
12
+ // A trace can show signed-in pages, so it is written like a screenshot:
13
+ // private to the user, never through a symlink, and not over an existing
14
+ // file unless asked.
15
+ async function writeTempTrace(data) {
16
+ const dir = await mkdtemp(path.join(tmpdir(), "mcp-browser-dev-tools-"));
17
+ const file = path.join(dir, "trace.json");
18
+ await writeFile(file, data, { flag: "wx", mode: SCREENSHOT_FILE_MODE });
19
+ return file;
20
+ }
21
+
22
+ // Checked before the trace stops, so a bad path does not cost the trace.
23
+ async function checkTracePath(args) {
24
+ if (args.path === undefined) {
25
+ return;
26
+ }
27
+ if (!path.isAbsolute(args.path) || !args.path.endsWith(".json")) {
28
+ throw new Error("record_trace path must be absolute and end in .json");
29
+ }
30
+ if (!args.overwrite) {
31
+ const exists = await lstat(args.path).then(
32
+ () => true,
33
+ () => false,
34
+ );
35
+ if (exists) {
36
+ throw new Error(
37
+ `${args.path} already exists; pass overwrite: true to replace it`,
38
+ );
39
+ }
40
+ }
41
+ }
42
+
43
+ // A trace that cannot be written where asked goes to a temp file instead,
44
+ // so the recording is not lost.
45
+ async function writeTrace(data, args) {
46
+ if (args.path === undefined) {
47
+ return { path: await writeTempTrace(data) };
48
+ }
49
+ try {
50
+ return { path: await writeScreenshotFile(args.path, data, args.overwrite) };
51
+ } catch (error) {
52
+ return {
53
+ path: await writeTempTrace(data),
54
+ error: `Could not write ${args.path} (${error.message}); the trace was saved to a temp file instead`,
55
+ };
56
+ }
57
+ }
58
+
59
+ export function performanceTools(server) {
60
+ return [
61
+ [
62
+ "get_performance",
63
+ {
64
+ definition: {
65
+ name: "get_performance",
66
+ description:
67
+ "Load timing, Web Vitals (TTFB, FCP, LCP with its element, CLS, slowest interaction) with ratings, long tasks, and the slowest resources; on Chromium also heap, DOM, layout, and script counters.",
68
+ inputSchema: sessionSchema({}, []),
69
+ },
70
+ handler: async (args) =>
71
+ server.browserAdapter.getPerformance(args.sessionId),
72
+ },
73
+ ],
74
+ [
75
+ "record_trace",
76
+ {
77
+ definition: {
78
+ name: "record_trace",
79
+ description:
80
+ "Record a Chromium performance trace: start, act, then stop writes a JSON file that DevTools' Performance panel opens.",
81
+ inputSchema: sessionSchema(
82
+ {
83
+ action: { type: "string", enum: ["start", "stop"] },
84
+ screenshots: {
85
+ type: "boolean",
86
+ description: "With start: include filmstrip screenshots.",
87
+ },
88
+ path: {
89
+ type: "string",
90
+ description:
91
+ "With stop: absolute .json path; default a temp file.",
92
+ },
93
+ overwrite: { type: "boolean" },
94
+ },
95
+ ["action"],
96
+ ),
97
+ },
98
+ handler: async (args) => {
99
+ if (args.action === "start") {
100
+ return server.browserAdapter.startTrace(args.sessionId, {
101
+ screenshots: args.screenshots,
102
+ });
103
+ }
104
+ await checkTracePath(args);
105
+ const { data, durationMs } = await server.browserAdapter.stopTrace(
106
+ args.sessionId,
107
+ );
108
+ return {
109
+ ...(await writeTrace(data, args)),
110
+ bytes: data.length,
111
+ durationMs,
112
+ };
113
+ },
114
+ },
115
+ ],
116
+ [
117
+ "record_video",
118
+ {
119
+ definition: {
120
+ name: "record_video",
121
+ description:
122
+ "Record what a Chromium tab shows to an MP4: start, act, then stop encodes the frames with ffmpeg (on PATH or MCP_BROWSER_FFMPEG; without it, stop returns the frames and the command). For 1920x1080, set_viewport first.",
123
+ inputSchema: sessionSchema(
124
+ {
125
+ action: { type: "string", enum: ["start", "stop"] },
126
+ fps: {
127
+ type: "integer",
128
+ minimum: 1,
129
+ maximum: 60,
130
+ description: "With start: output frame rate; default 30.",
131
+ },
132
+ quality: {
133
+ type: "integer",
134
+ minimum: 1,
135
+ maximum: 100,
136
+ description: "With start: JPEG quality; default 80.",
137
+ },
138
+ maxWidth: {
139
+ type: "integer",
140
+ minimum: 1,
141
+ description:
142
+ "With start: frames are scaled to fit; default the viewport.",
143
+ },
144
+ maxHeight: { type: "integer", minimum: 1 },
145
+ maxDurationMs: {
146
+ type: "integer",
147
+ minimum: 1000,
148
+ maximum: 1_800_000,
149
+ description:
150
+ "With start: capture stops by itself after this; default 600000.",
151
+ },
152
+ path: {
153
+ type: "string",
154
+ description:
155
+ "With stop: absolute .mp4 path; default a temp file.",
156
+ },
157
+ overwrite: { type: "boolean" },
158
+ },
159
+ ["action"],
160
+ ),
161
+ },
162
+ handler: async (args) => {
163
+ if (args.action === "start") {
164
+ const { dir, recording } = await server.browserAdapter.startVideo(
165
+ args.sessionId,
166
+ {
167
+ fps: args.fps,
168
+ quality: args.quality,
169
+ maxWidth: args.maxWidth,
170
+ maxHeight: args.maxHeight,
171
+ maxDurationMs: args.maxDurationMs,
172
+ },
173
+ );
174
+ return { recording, dir };
175
+ }
176
+ await checkVideoPath(args);
177
+ const capture = await server.browserAdapter.stopVideo(args.sessionId);
178
+ return encodeVideo(capture, args, server.config);
179
+ },
180
+ },
181
+ ],
182
+ ];
183
+ }