mcp-browser-dev-tools 0.4.1 → 0.5.1

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.
@@ -9,6 +9,7 @@ import {
9
9
  launchBrowserInputSchema,
10
10
  newTabInputSchema,
11
11
  } from "../tool-schemas.mjs";
12
+ import { DEFAULT_SNAPSHOT_NODES } from "./inspection-tools.mjs";
12
13
 
13
14
  const SERVER_NAME = PACKAGE_NAME;
14
15
  const SERVER_VERSION = PACKAGE_VERSION;
@@ -49,8 +50,13 @@ export function browserTools(server) {
49
50
  {
50
51
  definition: {
51
52
  name: "launch_browser",
52
- description:
53
- "Launch a debug-enabled browser, or reuse a reachable one unless port, address, userDataDir, or unsafeArgs is given; on macOS and Linux, never a second browser on a profile in use. Prefer ensure_browser.",
53
+ // unsafeArgs is only in the schema when enabled, so only name it
54
+ // then.
55
+ description: `Launch a debug-enabled browser, or reuse a reachable one unless ${
56
+ server.config.enableUnsafeLaunchArgs
57
+ ? "port, address, userDataDir, or unsafeArgs"
58
+ : "port, address, or userDataDir"
59
+ } is given; never a second browser on a profile in use (except from WSL). Prefer ensure_browser.`,
54
60
  inputSchema: launchBrowserInputSchema(
55
61
  server.config.browserFamily,
56
62
  server.config.enableUnsafeLaunchArgs,
@@ -109,7 +115,7 @@ export function browserTools(server) {
109
115
  definition: {
110
116
  name: "ensure_browser",
111
117
  description:
112
- "Reuse a reachable browser or launch one (with the MCP_BROWSER_USER_DATA_DIR profile when set), optionally opening url in a new tab. On macOS and Linux it never launches twice on one profile.",
118
+ "Reuse a reachable browser or launch one (with the MCP_BROWSER_USER_DATA_DIR profile when set), optionally opening url in a new tab. It never launches twice on one profile (except from WSL).",
113
119
  inputSchema: ensureBrowserInputSchema(
114
120
  server.config.browserFamily,
115
121
  server.config.enableUnsafeLaunchArgs,
@@ -174,7 +180,7 @@ export function browserTools(server) {
174
180
  definition: {
175
181
  name: "attach_tab",
176
182
  description:
177
- "Attach to a tab: returns the sessionId other tools take, and buffers its console and network events from now on.",
183
+ "Attach to a tab: returns the sessionId other tools take and the page's snapshot, as get_snapshot lists it, and buffers its console and network events from now on.",
178
184
  inputSchema: {
179
185
  type: "object",
180
186
  properties: {
@@ -182,13 +188,16 @@ export function browserTools(server) {
182
188
  type: "string",
183
189
  description: "From list_tabs or new_tab.",
184
190
  },
191
+ url: {
192
+ type: "string",
193
+ description:
194
+ "Instead of targetId: the tab whose URL is this, else the one whose URL contains it.",
195
+ },
185
196
  },
186
- required: ["targetId"],
187
197
  additionalProperties: false,
188
198
  },
189
199
  },
190
- handler: async (args) =>
191
- server.browserAdapter.attachToTarget(args.targetId),
200
+ handler: async (args) => attachTab(server, args),
192
201
  },
193
202
  ],
194
203
  [
@@ -212,3 +221,80 @@ export function browserTools(server) {
212
221
  ],
213
222
  ];
214
223
  }
224
+
225
+ // Attaches by targetId, or by url: the tab whose URL equals it, else the one
226
+ // whose URL contains it. Several matches, or none, fail with the tabs to
227
+ // choose from, so the agent needs no list_tabs call to try again. The result
228
+ // carries the page's snapshot, so the agent can act without another call; a
229
+ // snapshot that fails leaves the attach in place and says why.
230
+ async function attachTab(server, { targetId, url }) {
231
+ if ((targetId === undefined) === (url === undefined)) {
232
+ throw new Error("attach_tab takes either targetId or url");
233
+ }
234
+ const session = await server.browserAdapter.attachToTarget(
235
+ targetId ?? (await tabForUrl(server, url)),
236
+ );
237
+ const settled = await settleAfterAttach(server, session.sessionId);
238
+ try {
239
+ const snapshot = await server.browserAdapter.snapshotPage(
240
+ session.sessionId,
241
+ { limit: DEFAULT_SNAPSHOT_NODES, headings: true },
242
+ );
243
+ return {
244
+ ...session,
245
+ nodes: snapshot.nodes,
246
+ ...(snapshot.more > 0 ? { nodesMore: snapshot.more } : {}),
247
+ ...(settled?.settled === false ? { settled: false } : {}),
248
+ };
249
+ } catch (error) {
250
+ return { ...session, snapshotError: error.message };
251
+ }
252
+ }
253
+
254
+ // Waits for the page to settle before the snapshot, as a batch does before a
255
+ // step that reads the page: a page still loading or rendering is listed once
256
+ // its DOM has been quiet for a moment, for at most 2 s (10 s while it
257
+ // navigates). Work the page set going before the attach, such as a timer or
258
+ // a request already in flight, is not seen. Returns null when the page could
259
+ // not be watched.
260
+ async function settleAfterAttach(server, sessionId) {
261
+ const runner = server.stepRunner;
262
+ if (!runner?.changeTracker) {
263
+ return null;
264
+ }
265
+ const context = { sessionId, settles: true };
266
+ try {
267
+ await runner.watchPage(context);
268
+ const now = Date.now();
269
+ context.settling = { endedAt: now, since: now };
270
+ return await runner.settlePage(context);
271
+ } catch {
272
+ await runner.stopWatching(context).catch(() => {});
273
+ return null;
274
+ }
275
+ }
276
+
277
+ const MAX_LISTED_TABS = 10;
278
+
279
+ async function tabForUrl(server, url) {
280
+ const tabs = (await server.browserAdapter.listTargets()).filter(
281
+ (tab) =>
282
+ (tab.type === undefined || tab.type === "page") &&
283
+ typeof tab.url === "string",
284
+ );
285
+ const exact = tabs.filter((tab) => tab.url === url);
286
+ const matches =
287
+ exact.length > 0 ? exact : tabs.filter((tab) => tab.url.includes(url));
288
+ if (matches.length === 1) {
289
+ return matches[0].targetId;
290
+ }
291
+ const listed = (matches.length > 1 ? matches : tabs)
292
+ .slice(0, MAX_LISTED_TABS)
293
+ .map((tab) => `${tab.targetId} ${tab.url}`)
294
+ .join("; ");
295
+ throw new Error(
296
+ matches.length > 1
297
+ ? `${matches.length} tabs match ${url}; pass the targetId of one: ${listed}`
298
+ : `No tab's URL contains ${url}. Open tabs: ${listed || "none"}`,
299
+ );
300
+ }
@@ -9,12 +9,13 @@ import {
9
9
  import {
10
10
  asImageToolResult,
11
11
  asToolResult,
12
+ elementLine,
12
13
  moveScreenshotImage,
13
14
  } from "../tool-results.mjs";
14
15
  import { selectorProperty, sessionWithLimitSchema } from "../tool-schemas.mjs";
15
16
 
16
17
  const DEFAULT_READ_CHARS = 8000;
17
- const DEFAULT_SNAPSHOT_NODES = 100;
18
+ export const DEFAULT_SNAPSHOT_NODES = 100;
18
19
  const MAX_SNAPSHOT_NODES = 500;
19
20
 
20
21
  // The snapshot's nodes are lines already; send them as plain text rather than
@@ -36,6 +37,28 @@ export function formatSnapshotResult(result) {
36
37
  structuredContent: result,
37
38
  };
38
39
  }
40
+ const DEFAULT_QUERY_ELEMENTS = 20;
41
+ const MAX_QUERY_ELEMENTS = 100;
42
+ const MAX_QUERY_NAMES = 20;
43
+
44
+ // Each matched element as its ref and line, then what was asked for; more
45
+ // counts the matches past the limit.
46
+ export function formatQueryResult(result) {
47
+ if (!Array.isArray(result?.elements)) {
48
+ return result;
49
+ }
50
+ const { elements, count, ...rest } = result;
51
+ return {
52
+ ...rest,
53
+ count,
54
+ elements: elements.map(({ ref, node, ...asked }) => ({
55
+ ref,
56
+ element: elementLine(node),
57
+ ...asked,
58
+ })),
59
+ ...(count > elements.length ? { more: count - elements.length } : {}),
60
+ };
61
+ }
39
62
  const MAX_READ_CHARS = 100_000;
40
63
  const DEFAULT_READ_LINKS = 50;
41
64
  const MAX_READ_LINKS = 200;
@@ -199,6 +222,57 @@ export function inspectionTools(server) {
199
222
  }),
200
223
  },
201
224
  ],
225
+ [
226
+ "query_elements",
227
+ {
228
+ definition: {
229
+ name: "query_elements",
230
+ description:
231
+ "List every element a locator matches, each with a ref and a line as in get_snapshot, and when asked its box, attributes, or computed styles. Reads lists, layout, and styles without evaluate_js.",
232
+ inputSchema: {
233
+ type: "object",
234
+ properties: {
235
+ sessionId: { type: "string" },
236
+ selector: selectorProperty(),
237
+ box: {
238
+ type: "boolean",
239
+ description: "Add x, y, width, height in viewport CSS px.",
240
+ },
241
+ attributes: {
242
+ type: "array",
243
+ maxItems: MAX_QUERY_NAMES,
244
+ items: { type: "string" },
245
+ description: "Attribute names to read.",
246
+ },
247
+ styles: {
248
+ type: "array",
249
+ maxItems: MAX_QUERY_NAMES,
250
+ items: { type: "string" },
251
+ description: "Computed CSS properties, e.g. font-size.",
252
+ },
253
+ limit: {
254
+ type: "integer",
255
+ minimum: 1,
256
+ maximum: MAX_QUERY_ELEMENTS,
257
+ description: `Default ${DEFAULT_QUERY_ELEMENTS}.`,
258
+ },
259
+ },
260
+ required: ["sessionId", "selector"],
261
+ additionalProperties: false,
262
+ },
263
+ },
264
+ handler: async (args) =>
265
+ formatQueryResult(
266
+ await server.browserAdapter.queryElements(args.sessionId, {
267
+ selector: args.selector,
268
+ box: args.box === true,
269
+ attributes: args.attributes ?? [],
270
+ styles: args.styles ?? [],
271
+ limit: args.limit ?? DEFAULT_QUERY_ELEMENTS,
272
+ }),
273
+ ),
274
+ },
275
+ ],
202
276
  [
203
277
  "take_screenshot",
204
278
  {