codex-browser-use 0.0.0-stage → 4.8.2

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/server.js ADDED
@@ -0,0 +1,1121 @@
1
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
3
+ import { z } from "zod";
4
+ import { BridgeBrowser } from "./bridge-browser.js";
5
+ import { defaultBridgeFile, readBackend } from "./backend-discovery.js";
6
+ import { BrowserScriptSession } from "./script-runner.js";
7
+
8
+ const bridgeFile = process.env.BROWSER_USE_BRIDGE_FILE ?? defaultBridgeFile();
9
+ const stringOrNumber = z.union([z.string(), z.number()]).transform((value) => String(value));
10
+ const returnStateEnum = z.enum(["none", "diff", "full", "screenshot", "both"]);
11
+ const axModeEnum = z.enum(["full", "compact", "interactive"]);
12
+ const tabGroupColorEnum = z.enum(["grey", "blue", "red", "yellow", "green", "pink", "purple", "cyan", "orange"]);
13
+ const keepEntrySchema = z.object({
14
+ tab_id: stringOrNumber,
15
+ mode: z.enum(["handoff", "deliverable"]).optional(),
16
+ focus: z.boolean().optional(),
17
+ });
18
+ const keepParamSchema = z.union([
19
+ z.enum(["handoff", "deliverable"]),
20
+ z.array(keepEntrySchema),
21
+ ]);
22
+
23
+ /**
24
+ * Normalize inline `keep` parameter + script-tracked kept tabs into unique keep entries.
25
+ * @param {"handoff"|"deliverable"|Array<{tab_id:unknown, mode?:string, focus?:boolean}>|undefined} keep
26
+ * @param {unknown} fallbackTabId
27
+ * @param {Array<{tab_id:unknown, mode?:string, focus?:boolean}>} [extraKept]
28
+ */
29
+ function resolveKeepEntries(keep, fallbackTabId, extraKept = []) {
30
+ const merged = new Map();
31
+ for (const entry of extraKept) {
32
+ if (entry?.tab_id != null) {
33
+ merged.set(String(entry.tab_id), {
34
+ mode: entry.mode === "deliverable" ? "deliverable" : "handoff",
35
+ ...(entry.focus === true ? { focus: true } : {}),
36
+ });
37
+ }
38
+ }
39
+ if (typeof keep === "string") {
40
+ if (fallbackTabId != null && fallbackTabId !== "") {
41
+ const prev = merged.get(String(fallbackTabId));
42
+ merged.set(String(fallbackTabId), {
43
+ mode: keep,
44
+ ...(prev?.focus === true ? { focus: true } : {}),
45
+ });
46
+ }
47
+ } else if (Array.isArray(keep)) {
48
+ for (const entry of keep) {
49
+ if (entry?.tab_id != null) {
50
+ const prev = merged.get(String(entry.tab_id));
51
+ merged.set(String(entry.tab_id), {
52
+ mode: entry.mode === "deliverable" ? "deliverable" : "handoff",
53
+ ...(entry.focus === true || (entry.focus === undefined && prev?.focus === true) ? { focus: true } : {}),
54
+ });
55
+ }
56
+ }
57
+ }
58
+ return [...merged.entries()].map(([tab_id, cfg]) => ({
59
+ tab_id,
60
+ mode: cfg.mode,
61
+ ...(cfg.focus === true ? { focus: true } : {}),
62
+ }));
63
+ }
64
+
65
+ /**
66
+ * Return false for static validation, script syntax, or local file-helper errors so
67
+ * error handling skips dumping an unrelated `<ax_state>` tree into context.
68
+ * @param {unknown} error
69
+ * @param {string} msg
70
+ * @returns {boolean}
71
+ */
72
+ function shouldAttachErrorState(error, msg) {
73
+ if (
74
+ error instanceof SyntaxError ||
75
+ error instanceof ReferenceError ||
76
+ error instanceof TypeError ||
77
+ error instanceof RangeError ||
78
+ ["SyntaxError", "ReferenceError", "TypeError", "RangeError"].includes(/** @type {any} */ (error)?.name)
79
+ ) {
80
+ return false;
81
+ }
82
+ if (
83
+ /^Browser evaluate (is read-only|could not parse|requires a JavaScript expression)/i.test(msg) ||
84
+ /^(saveFile|readFile|saveScreenshot) (requires|payload exceeds)/i.test(msg) ||
85
+ /^Maximum \d+ images per browser_run call exceeded/i.test(msg) ||
86
+ /^No browser tab is active/i.test(msg)
87
+ ) {
88
+ return false;
89
+ }
90
+ return true;
91
+ }
92
+
93
+ /** @type {Promise<BridgeBrowser>|null} */
94
+ let browserPromise = null;
95
+
96
+ /** @returns {Promise<BridgeBrowser>} */
97
+ function defaultGetBrowser() {
98
+ browserPromise ??= BridgeBrowser.connect({ bridgeFile }).catch((error) => {
99
+ browserPromise = null;
100
+ throw error;
101
+ });
102
+ return browserPromise;
103
+ }
104
+
105
+ /** @param {unknown} value */
106
+ function text(value) {
107
+ return {
108
+ content: [{ type: "text", text: typeof value === "string" ? value : JSON.stringify(value, null, 2) }],
109
+ };
110
+ }
111
+
112
+ /** @param {unknown} handler */
113
+ function guarded(handler) {
114
+ return async (args) => {
115
+ try {
116
+ return await handler(args);
117
+ } catch (error) {
118
+ return {
119
+ isError: true,
120
+ content: [{ type: "text", text: error instanceof Error ? error.message : String(error) }],
121
+ };
122
+ }
123
+ };
124
+ }
125
+
126
+ /** @param {{axText?:string, screenshotBase64?:string|null, screenshotMimeType?:string|null, notifications?:string[]}} state @param {Record<string, unknown>} [meta] */
127
+ function stateResponse(state, meta) {
128
+ const parts = [];
129
+ if (meta && Object.keys(meta).length > 0) parts.push(JSON.stringify(meta));
130
+ if (state.notifications?.length) {
131
+ parts.push(`<notifications>\n${state.notifications.map((n) => `- ${n}`).join("\n")}\n</notifications>`);
132
+ }
133
+ if (state.axText) parts.push(state.axText);
134
+ const content = [{ type: "text", text: parts.join("\n") }];
135
+ if (state.screenshotBase64) {
136
+ content.push({
137
+ type: "image",
138
+ data: state.screenshotBase64,
139
+ mimeType: state.screenshotMimeType || "image/jpeg",
140
+ });
141
+ }
142
+ return { content };
143
+ }
144
+
145
+ /**
146
+ * Attach optional post-action state (diff/full AX tree or screenshot) to reduce tool round-trips.
147
+ * @param {BridgeBrowser} browser
148
+ * @param {unknown} tabId
149
+ * @param {Record<string, unknown>} actionResult
150
+ * @param {string|undefined} returnState
151
+ */
152
+ async function withOptionalState(browser, tabId, actionResult, returnState = "none") {
153
+ if (!returnState || returnState === "none") return text(actionResult);
154
+ const targetTabId = actionResult?.tab_id ?? tabId;
155
+ if (returnState === "screenshot") {
156
+ const capture = await browser.screenshot(targetTabId);
157
+ return {
158
+ content: [
159
+ { type: "text", text: JSON.stringify(actionResult) },
160
+ { type: "image", data: capture.data, mimeType: capture.mimeType },
161
+ ],
162
+ };
163
+ }
164
+ const state = await browser.getState(targetTabId, {
165
+ screenshot: returnState === "both",
166
+ diff: returnState === "diff",
167
+ full: returnState === "full" || returnState === "both",
168
+ });
169
+ return stateResponse(state, actionResult);
170
+ }
171
+
172
+ const batchStepSchema = z.object({
173
+ action: z.enum([
174
+ "new_tab", "select_tab", "close_tab", "goto", "back", "forward", "reload",
175
+ "click", "set_value", "type_text", "press_key", "select_option", "hover",
176
+ "drag", "scroll", "locator_click", "locator_fill", "upload_files", "wait",
177
+ "handle_dialog", "set_viewport", "reset_viewport", "name_session",
178
+ "get_state", "get_content", "evaluate", "read_tab",
179
+ ]).describe("Action type to execute"),
180
+ tab_id: stringOrNumber.optional(),
181
+ url: z.string().optional(),
182
+ wait_until: z.enum(["commit", "domcontentloaded", "load", "networkidle"]).optional(),
183
+ element_index: stringOrNumber.optional(),
184
+ x: z.number().optional(),
185
+ y: z.number().optional(),
186
+ click_count: z.number().int().min(1).max(3).optional(),
187
+ mouse_button: z.enum(["left", "right", "middle"]).optional(),
188
+ modifiers: z.union([z.string(), z.array(z.string())]).optional(),
189
+ value: z.union([z.string(), z.array(z.string())]).optional(),
190
+ label: z.union([z.string(), z.array(z.string())]).optional(),
191
+ index: z.union([z.number().int(), z.array(z.number().int())]).optional(),
192
+ text: z.string().optional(),
193
+ key: z.string().optional(),
194
+ direction: z.enum(["up", "down", "left", "right"]).optional(),
195
+ pages: z.number().int().min(1).max(20).optional(),
196
+ selector: z.string().optional(),
197
+ frame: z.string().optional(),
198
+ force: z.boolean().optional(),
199
+ width: z.number().int().min(100).max(4096).optional(),
200
+ height: z.number().int().min(100).max(4096).optional(),
201
+ device_scale_factor: z.number().min(0).max(8).optional(),
202
+ mobile: z.boolean().optional(),
203
+ from_index: stringOrNumber.optional(),
204
+ to_index: stringOrNumber.optional(),
205
+ from_x: z.number().optional(),
206
+ from_y: z.number().optional(),
207
+ to_x: z.number().optional(),
208
+ to_y: z.number().optional(),
209
+ files: z.array(z.string()).optional(),
210
+ state: z.enum(["attached", "detached", "visible", "hidden"]).optional(),
211
+ load_state: z.enum(["domcontentloaded", "load", "networkidle"]).optional(),
212
+ timeout_ms: z.number().int().min(0).max(60_000).optional(),
213
+ accept: z.boolean().optional(),
214
+ prompt_text: z.string().optional(),
215
+ name: z.string().min(1).max(80).optional(),
216
+ color: tabGroupColorEnum.optional(),
217
+ expression: z.string().optional(),
218
+ format: z.enum(["text", "markdown", "tables", "links"]).optional(),
219
+ max_chars: z.number().int().min(200).max(100_000).optional(),
220
+ mode: axModeEnum.optional(),
221
+ });
222
+
223
+ const compactBatchStepSchema = z.object({
224
+ action: batchStepSchema.shape.action,
225
+ tab_id: stringOrNumber.optional(),
226
+ url: z.string().optional(),
227
+ selector: z.string().optional(),
228
+ element_index: stringOrNumber.optional(),
229
+ value: z.union([z.string(), z.array(z.string())]).optional(),
230
+ text: z.string().optional(),
231
+ key: z.string().optional(),
232
+ }).passthrough();
233
+
234
+ const ALL_TOOL_NAMES = [
235
+ "browser_status", "browser_run", "browser_batch", "browser_get_state",
236
+ "browser_click", "browser_set_value", "browser_type_text", "browser_press_key",
237
+ "browser_select_option", "browser_hover", "browser_drag", "browser_scroll",
238
+ "browser_locator_click", "browser_locator_fill", "browser_wait_for",
239
+ "browser_upload_files", "browser_screenshot", "browser_evaluate",
240
+ "browser_get_content", "browser_dom_snapshot", "browser_inspect_element",
241
+ "browser_console_logs", "browser_network_logs", "browser_set_viewport",
242
+ "browser_name_session", "browser_handle_dialog",
243
+ "browser_list_tabs", "browser_new_tab", "browser_select_tab", "browser_close_tab",
244
+ "browser_goto", "browser_back", "browser_forward", "browser_reload",
245
+ "browser_end_turn", "browser_reset",
246
+ ];
247
+
248
+ const COMPACT_TOOLS = [
249
+ "browser_run", "browser_batch", "browser_get_state", "browser_goto",
250
+ "browser_list_tabs", "browser_screenshot", "browser_end_turn",
251
+ ];
252
+
253
+ const STANDARD_TOOLS = [
254
+ ...COMPACT_TOOLS,
255
+ "browser_status", "browser_get_content", "browser_select_tab",
256
+ "browser_new_tab", "browser_close_tab", "browser_evaluate", "browser_reset",
257
+ ];
258
+
259
+ export const TOOL_PROFILES = {
260
+ compact: COMPACT_TOOLS,
261
+ standard: STANDARD_TOOLS,
262
+ full: ALL_TOOL_NAMES,
263
+ };
264
+
265
+ /**
266
+ * Resolve MCP tool surface profile from `--profile` CLI flag or `BROWSER_USE_TOOL_PROFILE`.
267
+ * @param {string[]} [argv]
268
+ * @param {Record<string, string|undefined>} [env]
269
+ * @returns {"compact"|"standard"|"full"}
270
+ */
271
+ export function resolveToolProfile(argv = process.argv.slice(2), env = process.env) {
272
+ let profile = env?.BROWSER_USE_TOOL_PROFILE || "full";
273
+ for (let i = 0; i < argv.length; i++) {
274
+ const arg = argv[i];
275
+ if (arg === "--profile") {
276
+ profile = argv[++i] || "";
277
+ } else if (arg.startsWith("--profile=")) {
278
+ profile = arg.slice("--profile=".length);
279
+ }
280
+ }
281
+ if (!Object.hasOwn(TOOL_PROFILES, profile)) {
282
+ throw new Error(`Invalid browser-use profile ${JSON.stringify(profile)}. Choose compact, standard, or full.`);
283
+ }
284
+ return /** @type {"compact"|"standard"|"full"} */ (profile);
285
+ }
286
+
287
+ /**
288
+ * Register the Browser Use MCP surface filtered by profile (`full` = 36 tools, `standard` = 14, `compact` = 7).
289
+ * @param {McpServer} server
290
+ * @param {{getBrowser?:()=>Promise<BridgeBrowser>, resetBrowser?:()=>Promise<void>, profile?:"compact"|"standard"|"full"}} [deps]
291
+ */
292
+ export function registerTools(server, deps = {}) {
293
+ const profile = deps.profile ?? "full";
294
+ if (!Object.hasOwn(TOOL_PROFILES, profile)) {
295
+ throw new Error(`Invalid browser-use profile ${JSON.stringify(profile)}. Choose compact, standard, or full.`);
296
+ }
297
+ const activeTools = TOOL_PROFILES[profile];
298
+ const allowedTools = new Set(activeTools);
299
+ const registerTool = (name, description, schema, handler) => {
300
+ if (allowedTools.has(name)) {
301
+ server.tool(name, description, schema, handler);
302
+ }
303
+ };
304
+
305
+ const scriptSession = new BrowserScriptSession();
306
+ const getBrowser = deps.getBrowser ?? defaultGetBrowser;
307
+ const resetBrowser = deps.resetBrowser ?? (async () => {
308
+ scriptSession.reset();
309
+ const browser = browserPromise ? await browserPromise.catch(() => null) : null;
310
+ browserPromise = null;
311
+ await browser?.close();
312
+ });
313
+
314
+ registerTool(
315
+ "browser_status",
316
+ "Report the Chrome bridge descriptor, connection state, and available tools. Does not open a browser session.",
317
+ {},
318
+ guarded(async () => {
319
+ let bridge;
320
+ try {
321
+ await readBackend(bridgeFile);
322
+ bridge = { state: "ready", file: bridgeFile };
323
+ } catch (error) {
324
+ bridge = { state: "unavailable", file: bridgeFile, reason: error instanceof Error ? error.message : String(error) };
325
+ }
326
+ return text({
327
+ bridge,
328
+ connected: deps.getBrowser ? undefined : browserPromise !== null,
329
+ node: process.version,
330
+ profile,
331
+ tools: activeTools,
332
+ });
333
+ }),
334
+ );
335
+
336
+ registerTool(
337
+ "browser_run",
338
+ "Execute an async JavaScript browser script with persistent session bindings (`browser`/`page`, `ariaSnapshot()`, `ax.write()`, `content.export()`, read-only `evaluate`, `viewImage`, `saveFile`, `readFile`, `saveScreenshot`, `dev.responseBody`, `tabs.content`, `markDeliverable`) and optional `end_turn`.",
339
+ {
340
+ code: z.string().min(1).describe("Async JS body with browser/page, log, sleep, saveFile, saveScreenshot"),
341
+ tab_id: stringOrNumber.optional().describe("Optional initial tab_id"),
342
+ timeout_ms: z.number().int().min(500).max(300_000).optional().describe("Timeout ms (default 45000, max 300000)"),
343
+ return_state: returnStateEnum.optional().describe("Post-script state (default diff if result undefined, else none)"),
344
+ mode: axModeEnum.optional().describe("AX mode: compact (default), full, or interactive"),
345
+ end_turn: z.boolean().optional().describe("End turn after script succeeds"),
346
+ keep: keepParamSchema.optional().describe('Keep mode ("handoff" | "deliverable") or [{ tab_id, mode }]'),
347
+ ungroup: z.boolean().optional().describe("Ungroup tabs on finish"),
348
+ max_lines: z.number().int().min(1).max(10_000).optional().describe("Max AX lines (default 1500)"),
349
+ reset_context: z.boolean().optional().describe("Reset persisted variables"),
350
+ },
351
+ async ({ code, tab_id, timeout_ms, return_state, mode, end_turn, keep, ungroup, max_lines, reset_context }) => {
352
+ let browser = null;
353
+ let run = null;
354
+ try {
355
+ if (reset_context === true) scriptSession.reset();
356
+ browser = await getBrowser();
357
+ run = await scriptSession.run(browser, code, {
358
+ tabId: tab_id,
359
+ timeoutMs: timeout_ms ?? 45_000,
360
+ });
361
+
362
+ const shouldEndTurn = end_turn === true || (end_turn !== false && (keep !== undefined || run.keptTabs.length > 0 || run.endTurnRequested));
363
+ const effectiveReturnState = return_state ?? (!shouldEndTurn && run.value === undefined ? "diff" : "none");
364
+
365
+ let state = null;
366
+ const images = [...run.images];
367
+ if (effectiveReturnState === "screenshot" && run.activeTabId) {
368
+ const cap = await browser.screenshot(run.activeTabId).catch(() => null);
369
+ if (cap) images.push({ data: cap.data, mimeType: cap.mimeType });
370
+ } else if (effectiveReturnState !== "none" && run.activeTabId) {
371
+ state = await browser.getState(run.activeTabId, {
372
+ screenshot: effectiveReturnState === "both",
373
+ diff: effectiveReturnState === "diff",
374
+ full: effectiveReturnState === "full" || effectiveReturnState === "both",
375
+ maxLines: max_lines ?? 1_500,
376
+ mode: mode ?? "compact",
377
+ }).catch(() => null);
378
+ if (state?.screenshotBase64) {
379
+ images.push({ data: state.screenshotBase64, mimeType: state.screenshotMimeType || "image/jpeg" });
380
+ }
381
+ }
382
+
383
+ let endTurnResult = null;
384
+ if (shouldEndTurn) {
385
+ const entries = resolveKeepEntries(keep, run.activeTabId, run.keptTabs);
386
+ endTurnResult = await browser.endTurn({
387
+ keep: entries,
388
+ ungroup: ungroup === true || run.ungroupOnEndTurn === true,
389
+ });
390
+ scriptSession.syncActiveTab(browser);
391
+ } else if (keep !== undefined || run.keptTabs.length > 0) {
392
+ const entries = resolveKeepEntries(keep, run.activeTabId, run.keptTabs);
393
+ await browser.markTabs(entries).catch(() => {});
394
+ }
395
+
396
+ const mergedNotifications = [...new Set([...(run.notifications ?? []), ...(state?.notifications ?? [])])];
397
+ const payload = {
398
+ ok: true,
399
+ tab_id: run.activeTabId,
400
+ ...(run.value !== undefined ? { result: run.value } : {}),
401
+ ...(run.savedFiles?.length > 0 ? { saved_files: run.savedFiles } : {}),
402
+ ...(run.logs.length > 0 ? { logs: run.logs } : {}),
403
+ ...(endTurnResult ? { end_turn: endTurnResult } : {}),
404
+ };
405
+ const parts = [JSON.stringify(payload, null, 2)];
406
+ if (mergedNotifications.length > 0) {
407
+ parts.push(`<notifications>\n${mergedNotifications.map((n) => `- ${n}`).join("\n")}\n</notifications>`);
408
+ }
409
+ if (state?.axText) parts.push(state.axText);
410
+
411
+ const content = [{ type: "text", text: parts.join("\n") }];
412
+ for (const img of images) {
413
+ content.push({ type: "image", data: img.data, mimeType: img.mimeType || "image/jpeg" });
414
+ }
415
+ return { content };
416
+ } catch (error) {
417
+ const msg = error instanceof Error ? error.message : String(error);
418
+ const fallbackTab = run?.activeTabId ?? tab_id ?? browser?.activeTabId;
419
+ const errState = (browser && fallbackTab != null && shouldAttachErrorState(error, msg))
420
+ ? await browser.getState(fallbackTab, {
421
+ screenshot: false,
422
+ diff: true,
423
+ mode: mode ?? "compact",
424
+ maxLines: Math.min(max_lines ?? 250, 250),
425
+ allowUnindexedBaseline: true,
426
+ }).catch(() => null)
427
+ : null;
428
+ const parts = [msg];
429
+ if (errState?.notifications?.length) {
430
+ parts.push(`<notifications>\n${errState.notifications.map((n) => `- ${n}`).join("\n")}\n</notifications>`);
431
+ }
432
+ if (errState?.axText) parts.push(errState.axText);
433
+ return { isError: true, content: [{ type: "text", text: parts.join("\n") }] };
434
+ }
435
+ },
436
+ );
437
+
438
+ registerTool(
439
+ "browser_batch",
440
+ "Execute multiple browser actions sequentially in one tool call with automatic settling and final state/diff.",
441
+ {
442
+ steps: z.array(profile === "compact" ? compactBatchStepSchema : batchStepSchema).min(1).max(50).describe("Ordered action steps"),
443
+ tab_id: stringOrNumber.optional().describe("Optional tab_id"),
444
+ return_state: returnStateEnum.optional().describe("Final state (default diff)"),
445
+ mode: axModeEnum.optional().describe("AX mode: compact (default), full, or interactive"),
446
+ max_lines: z.number().int().min(1).max(10_000).optional().describe("Max AX lines (default 1500)"),
447
+ stop_on_error: z.boolean().optional().describe("Stop on first error (default true)"),
448
+ end_turn: z.boolean().optional().describe("End turn after all steps succeed"),
449
+ keep: keepParamSchema.optional().describe('Keep mode ("handoff"|"deliverable") or [{ tab_id, mode }]'),
450
+ ungroup: z.boolean().optional().describe("Ungroup tabs on finish"),
451
+ },
452
+ guarded(async ({ steps, tab_id, return_state, mode, max_lines, stop_on_error, end_turn, keep, ungroup }) => {
453
+ const browser = await getBrowser();
454
+ const result = await browser.batch(steps, {
455
+ tabId: tab_id,
456
+ returnState: return_state ?? "diff",
457
+ mode: mode ?? "compact",
458
+ maxLines: max_lines ?? 1_500,
459
+ stopOnError: stop_on_error !== false,
460
+ });
461
+ let endTurnResult = null;
462
+ const shouldEndTurn = result.ok && (end_turn === true || (end_turn !== false && keep !== undefined));
463
+ if (shouldEndTurn) {
464
+ const fallbackTab = result.state?.tab_id ?? tab_id ?? browser.activeTabId;
465
+ endTurnResult = await browser.endTurn({
466
+ keep: resolveKeepEntries(keep, fallbackTab),
467
+ ungroup: ungroup === true,
468
+ });
469
+ scriptSession.syncActiveTab(browser);
470
+ } else if (result.ok && keep !== undefined) {
471
+ const fallbackTab = result.state?.tab_id ?? tab_id ?? browser.activeTabId;
472
+ await browser.markTabs(resolveKeepEntries(keep, fallbackTab)).catch(() => {});
473
+ }
474
+ const summary = {
475
+ ok: result.ok,
476
+ completed_steps: result.completed_steps.length,
477
+ ...(result.ok ? {} : { failed_step: result.failed_step, error: result.error }),
478
+ ...(endTurnResult ? { end_turn: endTurnResult } : {}),
479
+ };
480
+ if (!result.state) {
481
+ const out = endTurnResult ? { ...result, end_turn: endTurnResult } : result;
482
+ return { ...(result.ok ? {} : { isError: true }), content: [{ type: "text", text: JSON.stringify(out, null, 2) }] };
483
+ }
484
+ const response = stateResponse(result.state, summary);
485
+ return result.ok ? response : { isError: true, ...response };
486
+ }),
487
+ );
488
+
489
+ registerTool(
490
+ "browser_list_tabs",
491
+ "List Chrome tabs (session + open user tabs) with tab_id, title, url, active, owned, and origin ('agent' | 'user').",
492
+ {},
493
+ guarded(async () => text(await (await getBrowser()).listTabs())),
494
+ );
495
+
496
+ registerTool(
497
+ "browser_new_tab",
498
+ "Open a new tab, optionally navigating to a URL. The new tab becomes the active tab.",
499
+ { url: z.string().optional().describe("URL to open in the new tab") },
500
+ guarded(async ({ url }) => text(await (await getBrowser()).newTab(url))),
501
+ );
502
+
503
+ registerTool(
504
+ "browser_select_tab",
505
+ "Select an existing tab by tab_id (automatically claiming already-open user tabs in Chrome into this session) and make it the active tab.",
506
+ { tab_id: stringOrNumber.describe("Tab ID from browser_list_tabs to activate and control") },
507
+ guarded(async ({ tab_id }) => text(await (await getBrowser()).selectTab(tab_id))),
508
+ );
509
+
510
+ registerTool(
511
+ "browser_close_tab",
512
+ "Close a tab owned by this browser session.",
513
+ { tab_id: stringOrNumber.describe("Tab ID to close") },
514
+ guarded(async ({ tab_id }) => text(await (await getBrowser()).closeTab(tab_id))),
515
+ );
516
+
517
+ registerTool(
518
+ "browser_goto",
519
+ "Navigate a tab to a URL (auto-creating a tab if none exists), wait for load, and return the accessibility tree by default.",
520
+ {
521
+ url: z.string().describe("Destination URL"),
522
+ tab_id: stringOrNumber.optional().describe("Optional tab_id; defaults to the active tab"),
523
+ wait_until: z.enum(["commit", "domcontentloaded", "load", "networkidle"]).optional().describe("Load condition. Defaults to load"),
524
+ return_state: returnStateEnum.optional().describe("State to return after navigation. Defaults to diff"),
525
+ },
526
+ guarded(async ({ url, tab_id, wait_until, return_state }) => {
527
+ const browser = await getBrowser();
528
+ const result = await browser.goto(url, tab_id, { waitUntil: wait_until ?? "load" });
529
+ return withOptionalState(browser, tab_id, result, return_state ?? "diff");
530
+ }),
531
+ );
532
+
533
+ registerTool(
534
+ "browser_back",
535
+ "Navigate the active tab back in browsing history.",
536
+ {
537
+ tab_id: stringOrNumber.optional().describe("Optional tab_id"),
538
+ return_state: returnStateEnum.optional().describe("Optional post-action state"),
539
+ },
540
+ guarded(async ({ tab_id, return_state }) => {
541
+ const browser = await getBrowser();
542
+ const result = await browser.history("back", tab_id);
543
+ return withOptionalState(browser, tab_id, result, return_state);
544
+ }),
545
+ );
546
+
547
+ registerTool(
548
+ "browser_forward",
549
+ "Navigate the active tab forward in browsing history.",
550
+ {
551
+ tab_id: stringOrNumber.optional().describe("Optional tab_id"),
552
+ return_state: returnStateEnum.optional().describe("Optional post-action state"),
553
+ },
554
+ guarded(async ({ tab_id, return_state }) => {
555
+ const browser = await getBrowser();
556
+ const result = await browser.history("forward", tab_id);
557
+ return withOptionalState(browser, tab_id, result, return_state);
558
+ }),
559
+ );
560
+
561
+ registerTool(
562
+ "browser_reload",
563
+ "Reload the active tab and wait for the document to finish loading.",
564
+ {
565
+ tab_id: stringOrNumber.optional().describe("Optional tab_id"),
566
+ return_state: returnStateEnum.optional().describe("Optional post-action state"),
567
+ },
568
+ guarded(async ({ tab_id, return_state }) => {
569
+ const browser = await getBrowser();
570
+ const result = await browser.reload(tab_id);
571
+ return withOptionalState(browser, tab_id, result, return_state);
572
+ }),
573
+ );
574
+
575
+ registerTool(
576
+ "browser_get_state",
577
+ "Return the page accessibility tree as <ax_state> (diff-first unless full=true), plus optional screenshot.",
578
+ {
579
+ tab_id: stringOrNumber.optional().describe("Optional tab_id"),
580
+ screenshot: z.boolean().optional().describe("Include viewport screenshot (default false)"),
581
+ full_page: z.boolean().optional().describe("Full-page screenshot when screenshot=true"),
582
+ format: z.enum(["jpeg", "png"]).optional().describe("Screenshot format (default jpeg)"),
583
+ full: z.boolean().optional().describe("Return full AX tree instead of diff"),
584
+ mode: axModeEnum.optional().describe("AX mode: full (default), compact, or interactive"),
585
+ max_lines: z.number().int().min(1).max(10_000).optional().describe("Max accessibility lines (default 2000)"),
586
+ },
587
+ guarded(async ({ tab_id, screenshot, full_page, format, full, mode, max_lines }) => stateResponse(
588
+ await (await getBrowser()).getState(tab_id, {
589
+ screenshot: screenshot === true,
590
+ fullPage: full_page === true,
591
+ format: format ?? "jpeg",
592
+ diff: full !== true,
593
+ full: full === true,
594
+ mode: mode ?? "full",
595
+ maxLines: max_lines ?? 2_000,
596
+ }),
597
+ )),
598
+ );
599
+
600
+ registerTool(
601
+ "browser_click",
602
+ "Click elements by element_index (or comma-separated indices) or viewport coordinates (x, y), with Shadow-DOM hit-testing.",
603
+ {
604
+ element_index: stringOrNumber.optional().describe("Element index, or comma-separated indices such as '11, 12, 11'"),
605
+ x: z.number().optional().describe("Viewport X coordinate when clicking without element_index"),
606
+ y: z.number().optional().describe("Viewport Y coordinate when clicking without element_index"),
607
+ click_count: z.number().int().min(1).max(3).optional().describe("Clicks per element. Defaults to 1"),
608
+ mouse_button: z.enum(["left", "right", "middle"]).optional().describe("Mouse button. Defaults to left"),
609
+ modifiers: z.union([z.string(), z.array(z.string())]).optional().describe("Modifier keys held during click"),
610
+ tab_id: stringOrNumber.optional().describe("Optional tab_id"),
611
+ return_state: returnStateEnum.optional().describe("Optional post-action state"),
612
+ },
613
+ guarded(async ({ element_index, x, y, click_count, mouse_button, modifiers, tab_id, return_state }) => {
614
+ const browser = await getBrowser();
615
+ const result = await browser.click(element_index, {
616
+ tabId: tab_id,
617
+ x,
618
+ y,
619
+ clickCount: click_count ?? 1,
620
+ button: mouse_button ?? "left",
621
+ modifiers,
622
+ settle: Boolean(return_state && return_state !== "none"),
623
+ });
624
+ return withOptionalState(browser, tab_id, result, return_state);
625
+ }),
626
+ );
627
+
628
+ registerTool(
629
+ "browser_set_value",
630
+ "Semantically set the value of an input, textarea, checkbox/radio ('true'/'false'), select, or contenteditable element by element_index.",
631
+ {
632
+ element_index: stringOrNumber.describe("Element index"),
633
+ value: z.string().describe("Value to assign"),
634
+ tab_id: stringOrNumber.optional().describe("Optional tab_id"),
635
+ return_state: returnStateEnum.optional().describe("Optional post-action state"),
636
+ },
637
+ guarded(async ({ element_index, value, tab_id, return_state }) => {
638
+ const browser = await getBrowser();
639
+ const result = await browser.setValue(element_index, value, { tabId: tab_id });
640
+ return withOptionalState(browser, tab_id, result, return_state);
641
+ }),
642
+ );
643
+
644
+ registerTool(
645
+ "browser_type_text",
646
+ "Insert literal text into the focused element, optionally focusing an element_index first.",
647
+ {
648
+ text: z.string().describe("Text to type"),
649
+ element_index: stringOrNumber.optional().describe("Optional element index to focus first"),
650
+ tab_id: stringOrNumber.optional().describe("Optional tab_id"),
651
+ return_state: returnStateEnum.optional().describe("Optional post-action state"),
652
+ },
653
+ guarded(async ({ text: value, element_index, tab_id, return_state }) => {
654
+ const browser = await getBrowser();
655
+ const result = await browser.typeText(value, { tabId: tab_id, elementIndex: element_index });
656
+ return withOptionalState(browser, tab_id, result, return_state);
657
+ }),
658
+ );
659
+
660
+ registerTool(
661
+ "browser_press_key",
662
+ "Press a key or chord such as Return, Tab, Escape, or super+a.",
663
+ {
664
+ key: z.string().describe("Key or chord to press"),
665
+ element_index: stringOrNumber.optional().describe("Optional element index to focus first"),
666
+ tab_id: stringOrNumber.optional().describe("Optional tab_id"),
667
+ return_state: returnStateEnum.optional().describe("Optional post-action state"),
668
+ },
669
+ guarded(async ({ key, element_index, tab_id, return_state }) => {
670
+ const browser = await getBrowser();
671
+ const result = await browser.pressKey(key, {
672
+ tabId: tab_id,
673
+ elementIndex: element_index,
674
+ settle: Boolean(return_state && return_state !== "none"),
675
+ });
676
+ return withOptionalState(browser, tab_id, result, return_state);
677
+ }),
678
+ );
679
+
680
+ registerTool(
681
+ "browser_select_option",
682
+ "Select one or more options on a <select> element by value, label, or index using element_index or a locator.",
683
+ {
684
+ element_index: stringOrNumber.optional().describe("Element index of the <select>"),
685
+ selector: z.string().optional().describe("Locator expression if not using element_index"),
686
+ frame: z.string().optional().describe("Optional iframe CSS selector chain (>>) "),
687
+ value: z.union([z.string(), z.array(z.string())]).optional().describe("Option value(s)"),
688
+ label: z.union([z.string(), z.array(z.string())]).optional().describe("Option label(s)"),
689
+ index: z.union([z.number().int(), z.array(z.number().int())]).optional().describe("0-based option index/indices"),
690
+ tab_id: stringOrNumber.optional().describe("Optional tab_id"),
691
+ return_state: returnStateEnum.optional().describe("Optional post-action state"),
692
+ },
693
+ guarded(async ({ element_index, selector, frame, value, label, index, tab_id, return_state }) => {
694
+ const browser = await getBrowser();
695
+ const result = await browser.selectOption({ tabId: tab_id, elementIndex: element_index, selector, frame, value, label, index });
696
+ return withOptionalState(browser, tab_id, result, return_state);
697
+ }),
698
+ );
699
+
700
+ registerTool(
701
+ "browser_hover",
702
+ "Hover the pointer over an element_index, locator selector, or viewport coordinates (x, y).",
703
+ {
704
+ element_index: stringOrNumber.optional().describe("Element index to hover"),
705
+ selector: z.string().optional().describe("Locator expression to hover"),
706
+ frame: z.string().optional().describe("Optional iframe CSS selector chain (>>)"),
707
+ x: z.number().optional().describe("Viewport X coordinate"),
708
+ y: z.number().optional().describe("Viewport Y coordinate"),
709
+ tab_id: stringOrNumber.optional().describe("Optional tab_id"),
710
+ return_state: returnStateEnum.optional().describe("Optional post-action state"),
711
+ },
712
+ guarded(async ({ element_index, selector, frame, x, y, tab_id, return_state }) => {
713
+ const browser = await getBrowser();
714
+ const result = await browser.hover({ tabId: tab_id, elementIndex: element_index, selector, frame, x, y });
715
+ return withOptionalState(browser, tab_id, result, return_state);
716
+ }),
717
+ );
718
+
719
+ registerTool(
720
+ "browser_drag",
721
+ "Drag from a start element/coordinate to a target element/coordinate.",
722
+ {
723
+ from_index: stringOrNumber.optional().describe("Start element_index"),
724
+ to_index: stringOrNumber.optional().describe("End element_index"),
725
+ from_x: z.number().optional().describe("Start X coordinate"),
726
+ from_y: z.number().optional().describe("Start Y coordinate"),
727
+ to_x: z.number().optional().describe("End X coordinate"),
728
+ to_y: z.number().optional().describe("End Y coordinate"),
729
+ steps: z.number().int().min(2).max(30).optional().describe("Intermediate mouse move steps. Defaults to 8"),
730
+ tab_id: stringOrNumber.optional().describe("Optional tab_id"),
731
+ return_state: returnStateEnum.optional().describe("Optional post-action state"),
732
+ },
733
+ guarded(async ({ from_index, to_index, from_x, from_y, to_x, to_y, steps, tab_id, return_state }) => {
734
+ const browser = await getBrowser();
735
+ const result = await browser.drag({
736
+ tabId: tab_id,
737
+ fromIndex: from_index,
738
+ toIndex: to_index,
739
+ fromX: from_x,
740
+ fromY: from_y,
741
+ toX: to_x,
742
+ toY: to_y,
743
+ steps,
744
+ });
745
+ return withOptionalState(browser, tab_id, result, return_state);
746
+ }),
747
+ );
748
+
749
+ registerTool(
750
+ "browser_scroll",
751
+ "Scroll the page, or a scrollable element_index / coordinate, by whole pages.",
752
+ {
753
+ direction: z.enum(["up", "down", "left", "right"]).describe("Scroll direction"),
754
+ pages: z.number().int().min(1).max(20).optional().describe("Pages to scroll. Defaults to 1"),
755
+ element_index: stringOrNumber.optional().describe("Optional element to scroll"),
756
+ x: z.number().optional().describe("Optional viewport X coordinate"),
757
+ y: z.number().optional().describe("Optional viewport Y coordinate"),
758
+ tab_id: stringOrNumber.optional().describe("Optional tab_id"),
759
+ return_state: returnStateEnum.optional().describe("Optional post-action state"),
760
+ },
761
+ guarded(async ({ direction, pages, element_index, x, y, tab_id, return_state }) => {
762
+ const browser = await getBrowser();
763
+ const result = await browser.scroll(direction, { tabId: tab_id, elementIndex: element_index, x, y, pages: pages ?? 1 });
764
+ return withOptionalState(browser, tab_id, result, return_state);
765
+ }),
766
+ );
767
+
768
+ registerTool(
769
+ "browser_locator_click",
770
+ "Click a single element matched by CSS, text=..., role=..., label=..., placeholder=..., testid=..., or chained >> locators (with built-in actionability auto-wait and open Shadow DOM / iframe piercing).",
771
+ {
772
+ selector: z.string().describe("Locator expression"),
773
+ frame: z.string().optional().describe("CSS selector of an iframe, nested with >>"),
774
+ click_count: z.number().int().min(1).max(3).optional().describe("Number of clicks. Defaults to 1"),
775
+ mouse_button: z.enum(["left", "right", "middle"]).optional().describe("Mouse button. Defaults to left"),
776
+ modifiers: z.union([z.string(), z.array(z.string())]).optional().describe("Modifier keys held during click"),
777
+ force: z.boolean().optional().describe("Bypass visibility/enabled/coverage checks. Defaults to false"),
778
+ timeout_ms: z.number().int().min(0).max(60_000).optional().describe("Auto-wait timeout in ms (0 disables retry). Defaults to 3000"),
779
+ tab_id: stringOrNumber.optional().describe("Optional tab_id"),
780
+ return_state: returnStateEnum.optional().describe("Optional post-action state"),
781
+ },
782
+ guarded(async ({ selector, frame, click_count, mouse_button, modifiers, force, timeout_ms, tab_id, return_state }) => {
783
+ const browser = await getBrowser();
784
+ const result = await browser.locatorClick(selector, {
785
+ tabId: tab_id,
786
+ frame,
787
+ clickCount: click_count ?? 1,
788
+ button: mouse_button ?? "left",
789
+ modifiers,
790
+ force: force === true,
791
+ timeoutMs: timeout_ms,
792
+ settle: Boolean(return_state && return_state !== "none"),
793
+ });
794
+ return withOptionalState(browser, tab_id, result, return_state);
795
+ }),
796
+ );
797
+
798
+ registerTool(
799
+ "browser_locator_fill",
800
+ "Fill a single element matched by CSS, text=..., role=..., label=..., placeholder=..., testid=..., or chained >> locators (with built-in auto-wait).",
801
+ {
802
+ selector: z.string().describe("Locator expression"),
803
+ value: z.string().describe("Value to fill"),
804
+ frame: z.string().optional().describe("CSS selector of an iframe, nested with >>"),
805
+ force: z.boolean().optional().describe("Bypass visibility/enabled checks. Defaults to false"),
806
+ timeout_ms: z.number().int().min(0).max(60_000).optional().describe("Auto-wait timeout in ms (0 disables retry). Defaults to 3000"),
807
+ tab_id: stringOrNumber.optional().describe("Optional tab_id"),
808
+ return_state: returnStateEnum.optional().describe("Optional post-action state"),
809
+ },
810
+ guarded(async ({ selector, value, frame, force, timeout_ms, tab_id, return_state }) => {
811
+ const browser = await getBrowser();
812
+ const result = await browser.locatorFill(selector, value, {
813
+ tabId: tab_id,
814
+ frame,
815
+ force: force === true,
816
+ timeoutMs: timeout_ms,
817
+ });
818
+ return withOptionalState(browser, tab_id, result, return_state);
819
+ }),
820
+ );
821
+
822
+ registerTool(
823
+ "browser_wait_for",
824
+ "Wait until a selector reaches a state, text appears on the page, URL matches, or load_state completes.",
825
+ {
826
+ selector: z.string().optional().describe("Locator expression to wait for"),
827
+ text: z.string().optional().describe("Visible text substring to wait for"),
828
+ url: z.string().optional().describe("URL or substring to wait for"),
829
+ load_state: z.enum(["domcontentloaded", "load", "networkidle"]).optional().describe("Document load state to wait for"),
830
+ state: z.enum(["attached", "detached", "visible", "hidden"]).optional().describe("Selector state. Defaults to visible"),
831
+ frame: z.string().optional().describe("Optional iframe CSS selector chain"),
832
+ timeout_ms: z.number().int().min(100).max(60_000).optional().describe("Timeout in ms. Defaults to 10000"),
833
+ tab_id: stringOrNumber.optional().describe("Optional tab_id"),
834
+ },
835
+ guarded(async ({ selector, text: expectedText, url, load_state, state, frame, timeout_ms, tab_id }) => text(
836
+ await (await getBrowser()).waitFor({
837
+ tabId: tab_id,
838
+ selector,
839
+ text: expectedText,
840
+ url,
841
+ loadState: load_state,
842
+ state: state ?? "visible",
843
+ frame,
844
+ timeoutMs: timeout_ms ?? 10_000,
845
+ }),
846
+ )),
847
+ );
848
+
849
+ registerTool(
850
+ "browser_upload_files",
851
+ "Set absolute local file path(s) on an <input type='file'> element (by element_index or CSS selector) or an active file chooser.",
852
+ {
853
+ files: z.array(z.string()).min(1).describe("Absolute local file paths"),
854
+ element_index: stringOrNumber.optional().describe("Element index of the file input"),
855
+ selector: z.string().optional().describe("CSS selector of the file input"),
856
+ frame: z.string().optional().describe("Optional iframe CSS selector chain"),
857
+ tab_id: stringOrNumber.optional().describe("Optional tab_id"),
858
+ return_state: returnStateEnum.optional().describe("Optional post-action state"),
859
+ },
860
+ guarded(async ({ files, element_index, selector, frame, tab_id, return_state }) => {
861
+ const browser = await getBrowser();
862
+ const result = await browser.uploadFiles(files, { tabId: tab_id, elementIndex: element_index, selector, frame });
863
+ return withOptionalState(browser, tab_id, result, return_state);
864
+ }),
865
+ );
866
+
867
+ registerTool(
868
+ "browser_screenshot",
869
+ "Capture a CSS-scaled screenshot (JPEG quality 75, max width 1280px by default).",
870
+ {
871
+ full_page: z.boolean().optional().describe("Capture beyond the viewport"),
872
+ format: z.enum(["jpeg", "png"]).optional().describe("Image format (default jpeg)"),
873
+ quality: z.number().int().min(10).max(100).optional().describe("JPEG quality 10-100 (default 75)"),
874
+ max_width: z.number().int().min(320).max(4096).optional().describe("Cap viewport screenshot CSS width (default 1280)"),
875
+ clip: z.object({
876
+ x: z.number(),
877
+ y: z.number(),
878
+ width: z.number().positive(),
879
+ height: z.number().positive(),
880
+ }).optional().describe("Optional viewport clip rectangle"),
881
+ tab_id: stringOrNumber.optional().describe("Optional tab_id"),
882
+ },
883
+ guarded(async ({ full_page, format, quality, max_width, clip, tab_id }) => {
884
+ const capture = await (await getBrowser()).screenshot(tab_id, {
885
+ fullPage: full_page === true,
886
+ format: format ?? "jpeg",
887
+ quality: quality ?? 75,
888
+ ...(max_width !== undefined ? { maxWidth: max_width } : {}),
889
+ clip,
890
+ });
891
+ return { content: [{ type: "image", data: capture.data, mimeType: capture.mimeType }] };
892
+ }),
893
+ );
894
+
895
+ registerTool(
896
+ "browser_evaluate",
897
+ "Evaluate a read-only JavaScript expression in the page and return its value. Assignment, DOM mutation, navigation, and network calls are rejected.",
898
+ {
899
+ expression: z.string().describe("Read-only JavaScript expression"),
900
+ tab_id: stringOrNumber.optional().describe("Optional tab_id"),
901
+ },
902
+ guarded(async ({ expression, tab_id }) => text(await (await getBrowser()).evaluate(expression, { tabId: tab_id }))),
903
+ );
904
+
905
+ registerTool(
906
+ "browser_get_content",
907
+ "Return page content as plain text, clean Readability-style markdown, extracted tables, or links.",
908
+ {
909
+ tab_id: stringOrNumber.optional().describe("Optional tab_id"),
910
+ format: z.enum(["text", "markdown", "tables", "links"]).optional().describe("Extraction format (default text)"),
911
+ max_chars: z.number().int().min(200).max(100_000).optional().describe("Character limit (default 16000 for structured formats)"),
912
+ },
913
+ guarded(async ({ tab_id, format, max_chars }) => {
914
+ const opts = (format || max_chars !== undefined)
915
+ ? { ...(format ? { format } : {}), ...(max_chars !== undefined ? { maxChars: max_chars } : {}) }
916
+ : undefined;
917
+ const result = await (await getBrowser()).getContent(tab_id, opts);
918
+ return text(format === "tables" || format === "links" ? result : (result.content ?? result.text));
919
+ }),
920
+ );
921
+
922
+ registerTool(
923
+ "browser_dom_snapshot",
924
+ "Return a compact visible DOM tree (default) or clean YAML ARIA snapshot (`format=\"aria\"`) for fast selector discovery or line filtering.",
925
+ {
926
+ format: z.enum(["dom", "aria"]).optional().describe('Snapshot format: "dom" (compact visible DOM) or "aria" (YAML ARIA tree). Defaults to "dom"'),
927
+ mode: axModeEnum.optional().describe("ARIA compression mode when format='aria': full (default), compact, or interactive"),
928
+ max_chars: z.number().int().min(1_000).max(100_000).optional().describe("Character limit for DOM format. Defaults to 24000"),
929
+ max_lines: z.number().int().min(1).max(10_000).optional().describe("Line limit for ARIA format. Defaults to 2000"),
930
+ tab_id: stringOrNumber.optional().describe("Optional tab_id"),
931
+ },
932
+ guarded(async ({ format, mode, max_chars, max_lines, tab_id }) => text(
933
+ await (await getBrowser()).domSnapshot({
934
+ tabId: tab_id,
935
+ format: format ?? "dom",
936
+ mode: mode ?? "full",
937
+ maxChars: max_chars ?? 24_000,
938
+ maxLines: max_lines ?? 2_000,
939
+ }),
940
+ )),
941
+ );
942
+
943
+ registerTool(
944
+ "browser_inspect_element",
945
+ "Inspect the element(s) at viewport coordinates (x, y) and return ranked locator candidates.",
946
+ {
947
+ x: z.number().describe("Viewport X coordinate"),
948
+ y: z.number().describe("Viewport Y coordinate"),
949
+ tab_id: stringOrNumber.optional().describe("Optional tab_id"),
950
+ },
951
+ guarded(async ({ x, y, tab_id }) => text(await (await getBrowser()).inspectElement(x, y, { tabId: tab_id }))),
952
+ );
953
+
954
+ registerTool(
955
+ "browser_console_logs",
956
+ "Read captured console messages and uncaught page exceptions for the tab.",
957
+ {
958
+ levels: z.array(z.enum(["log", "info", "warn", "error", "debug"])).optional().describe("Filter by log level"),
959
+ filter: z.string().optional().describe("Case-insensitive substring filter"),
960
+ limit: z.number().int().min(1).max(500).optional().describe("Max entries. Defaults to 100"),
961
+ clear: z.boolean().optional().describe("Clear buffer after reading. Defaults to false"),
962
+ tab_id: stringOrNumber.optional().describe("Optional tab_id"),
963
+ },
964
+ guarded(async ({ levels, filter, limit, clear, tab_id }) => text(
965
+ await (await getBrowser()).consoleLogs({ tabId: tab_id, levels, filter, limit: limit ?? 100, clear: clear === true }),
966
+ )),
967
+ );
968
+
969
+ registerTool(
970
+ "browser_network_logs",
971
+ "Read captured network requests, HTTP status codes, and failed requests for the tab.",
972
+ {
973
+ filter: z.string().optional().describe("Case-insensitive substring filter matched against URL, method, or error"),
974
+ status_min: z.number().int().min(100).max(599).optional().describe("Minimum HTTP status code"),
975
+ status_max: z.number().int().min(100).max(599).optional().describe("Maximum HTTP status code"),
976
+ failed_only: z.boolean().optional().describe("Include only failed requests or HTTP status >= 400. Defaults to false"),
977
+ resource_types: z.array(z.string()).optional().describe("Filter by resource type such as Document, Fetch, XHR, Script"),
978
+ limit: z.number().int().min(1).max(300).optional().describe("Max entries. Defaults to 100"),
979
+ clear: z.boolean().optional().describe("Clear buffer after reading. Defaults to false"),
980
+ tab_id: stringOrNumber.optional().describe("Optional tab_id"),
981
+ },
982
+ guarded(async ({ filter, status_min, status_max, failed_only, resource_types, limit, clear, tab_id }) => text(
983
+ await (await getBrowser()).networkLogs({
984
+ tabId: tab_id,
985
+ filter,
986
+ statusMin: status_min,
987
+ statusMax: status_max,
988
+ failedOnly: failed_only === true,
989
+ resourceTypes: resource_types,
990
+ limit: limit ?? 100,
991
+ clear: clear === true,
992
+ }),
993
+ )),
994
+ );
995
+
996
+ registerTool(
997
+ "browser_set_viewport",
998
+ "Override the tab viewport dimensions and mobile emulation for responsive layout testing, or reset back to normal.",
999
+ {
1000
+ width: z.number().int().min(100).max(4096).optional().describe("Viewport width in CSS pixels (required unless reset=true)"),
1001
+ height: z.number().int().min(100).max(4096).optional().describe("Viewport height in CSS pixels (required unless reset=true)"),
1002
+ device_scale_factor: z.number().min(0).max(8).optional().describe("Device scale factor. Defaults to 1"),
1003
+ mobile: z.boolean().optional().describe("Enable mobile viewport metrics. Defaults to false"),
1004
+ reset: z.boolean().optional().describe("Clear viewport override and restore default viewport. Defaults to false"),
1005
+ tab_id: stringOrNumber.optional().describe("Optional tab_id"),
1006
+ return_state: returnStateEnum.optional().describe("Optional post-action state"),
1007
+ },
1008
+ guarded(async ({ width, height, device_scale_factor, mobile, reset, tab_id, return_state }) => {
1009
+ const browser = await getBrowser();
1010
+ const result = reset === true
1011
+ ? await browser.resetViewport(tab_id)
1012
+ : await browser.setViewport({
1013
+ tabId: tab_id,
1014
+ width,
1015
+ height,
1016
+ deviceScaleFactor: device_scale_factor ?? 1,
1017
+ mobile: mobile === true,
1018
+ });
1019
+ return withOptionalState(browser, tab_id, result, return_state);
1020
+ }),
1021
+ );
1022
+
1023
+ registerTool(
1024
+ "browser_name_session",
1025
+ "Name the current browser automation session and group session-owned tabs inside a labeled Chrome tab group.",
1026
+ {
1027
+ name: z.string().min(1).max(80).describe("Visible Chrome tab group title"),
1028
+ color: tabGroupColorEnum.optional().describe("Chrome tab group color (grey, blue, red, yellow, green, pink, purple, cyan, orange). Defaults to blue"),
1029
+ },
1030
+ guarded(async ({ name, color }) => text(
1031
+ await (await getBrowser()).nameSession(name, { color: color ?? "blue" }),
1032
+ )),
1033
+ );
1034
+
1035
+ registerTool(
1036
+ "browser_handle_dialog",
1037
+ "Accept or dismiss the JavaScript dialog currently open in the tab.",
1038
+ {
1039
+ accept: z.boolean().describe("true accepts, false dismisses"),
1040
+ prompt_text: z.string().optional().describe("Text to enter for a prompt dialog"),
1041
+ tab_id: stringOrNumber.optional().describe("Optional tab_id"),
1042
+ return_state: returnStateEnum.optional().describe("Optional post-action state"),
1043
+ },
1044
+ guarded(async ({ accept, prompt_text, tab_id, return_state }) => {
1045
+ const browser = await getBrowser();
1046
+ const result = await browser.handleDialog({ tabId: tab_id, accept, promptText: prompt_text });
1047
+ return withOptionalState(browser, tab_id, result, return_state);
1048
+ }),
1049
+ );
1050
+
1051
+ registerTool(
1052
+ "browser_end_turn",
1053
+ "End agent turn: keep handoff/deliverable tabs open and close unmarked tabs.",
1054
+ {
1055
+ keep: z.array(keepEntrySchema).optional().describe("Kept tabs"),
1056
+ ungroup: z.boolean().optional().describe("Ungroup tabs on finish"),
1057
+ },
1058
+ guarded(async ({ keep, ungroup }) => {
1059
+ const browser = await getBrowser();
1060
+ const res = await browser.endTurn({ keep: keep ?? [], ungroup: ungroup === true });
1061
+ scriptSession.syncActiveTab(browser);
1062
+ return text(res);
1063
+ }),
1064
+ );
1065
+
1066
+ registerTool(
1067
+ "browser_reset",
1068
+ "Discard the current browser session and reset persisted `browser_run` variables.",
1069
+ {},
1070
+ guarded(async () => {
1071
+ scriptSession.reset();
1072
+ await resetBrowser();
1073
+ return text({ ok: true, reset: true });
1074
+ }),
1075
+ );
1076
+ }
1077
+
1078
+ /**
1079
+ * Create a configured McpServer instance (useful for standalone run and unit tests).
1080
+ * @param {{getBrowser?:()=>Promise<BridgeBrowser>, resetBrowser?:()=>Promise<void>, profile?:"compact"|"standard"|"full"}} [deps]
1081
+ * @returns {McpServer}
1082
+ */
1083
+ export function createStandaloneServer(deps = {}) {
1084
+ const profile = deps.profile ?? resolveToolProfile();
1085
+ const server = new McpServer(
1086
+ { name: "browser-use", version: "4.8.2" },
1087
+ {
1088
+ instructions: [
1089
+ "Browser use through a local Chrome bridge. Can create new session tabs or inspect and claim existing open user tabs in Chrome (via `browser_list_tabs` + `browser_select_tab` or `tab_id`, or `browser.tabs.list()` / `browser.user.openTabs()` + `browser.tabs.read()` / `browser.user.claimTab()` in `browser_run`). Claimed user tabs join the session Chrome Tab Group and are released (kept open & grouped) when a turn ends.",
1090
+ "Tab & Group Hygiene: Use 1 concise task name via `browser.nameSession()` for an entire workflow so tabs across turns consolidate into 1 Chrome Tab Group (avoid spawning separate groups per turn). Before opening a new tab (`tabs.new(url)`), check `browser.user.openTabs()` / `tabs.list()` and reuse an existing tab for the same URL. Close ephemeral tabs with `keep: []` and pass `ungroup: true` when finishing if kept tabs no longer need a group label.",
1091
+ "Speed & efficiency (Probe 1 -> Batch Loop All): When facing repetitive UI rows/modals/pages, inspect 1 sample item first, then pack the full loop (clicks, chunked reads, `saveFile()`, pagination) or known deterministic click sequence into ONE `browser_run` call (up to 300000ms) instead of repeating small calls. Includes persistent variables (`const`/`let`/`class`), bound tabs (`browser.tabs.new()` / `browser.tabs.get(id)` / parallel `browser.tabs.content(urls)` returning structured `.links`/`.tables`), `browser.nameSession()`, `browser.groups`, auto-waiting locators (including async CKEditor sync), `locator.screenshot()` / `saveScreenshot()`, `dev.enableNetwork({ captureBodies: true })` + `dev.responseBody(id)`, `markDeliverable`/`markHandoff`, and `browser.endTurn()`/`browser.end_turn()`.",
1092
+ "Diff-first & inspect-first: Start with `ariaSnapshot({ mode: \"compact\" })` or `browser_get_state` / `ax.write()` before guessing selectors; narrow multi-matches with `.first()`/`.nth(i)` and use `reload()` rather than `goto(sameUrl)`. Request `screenshot: true` / `ax.write('screenshot')` / `saveScreenshot(..., { emit: true })` when visual inspection or Proof of Work is needed.",
1093
+ "Pass end_turn/keep/ungroup to browser_run or browser_batch (or call `browser.endTurn()`/`markDeliverable()` inside `browser_run`), `browser_name_session` / `browser.nameSession()` to group tabs visually, and `browser_end_turn` at the end for tabs that must survive cleanup.",
1094
+ ].join("\n"),
1095
+ },
1096
+ );
1097
+ registerTools(server, { ...deps, profile });
1098
+ return server;
1099
+ }
1100
+
1101
+ export async function main() {
1102
+ const server = createStandaloneServer();
1103
+ await server.connect(new StdioServerTransport());
1104
+
1105
+ const shutdown = async () => {
1106
+ const browser = browserPromise ? await browserPromise.catch(() => null) : null;
1107
+ browserPromise = null;
1108
+ await browser?.close().catch(() => {});
1109
+ process.exit(0);
1110
+ };
1111
+ process.on("SIGINT", shutdown);
1112
+ process.on("SIGTERM", shutdown);
1113
+ process.stdin.once("end", shutdown);
1114
+ }
1115
+
1116
+ if (process.argv[1] && process.argv[1].endsWith("server.js")) {
1117
+ main().catch((error) => {
1118
+ console.error("Fatal browser-use error:", error);
1119
+ process.exit(1);
1120
+ });
1121
+ }