@browsa/mcp 0.3.3 → 0.6.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.
Files changed (3) hide show
  1. package/README.md +128 -83
  2. package/dist/server.js +1226 -144
  3. package/package.json +2 -2
package/dist/server.js CHANGED
@@ -3,38 +3,983 @@
3
3
  // src/server.ts
4
4
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
5
5
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
6
- import {
7
- CallToolRequestSchema,
8
- ListToolsRequestSchema
9
- } from "@modelcontextprotocol/sdk/types.js";
10
- import { Client, BrowsaError } from "browsa";
6
+ import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
7
+
8
+ // src/config.ts
9
+ var VERSION = "0.6.0";
11
10
  var API_KEY = process.env.BROWSA_API_KEY;
12
- var BASE_URL = process.env.BROWSA_BASE_URL;
11
+ var BASE_URL = (process.env.BROWSA_BASE_URL || "https://browsa.io").replace(/\/+$/, "");
12
+ var BASE_URL_SET = !!process.env.BROWSA_BASE_URL;
13
+ var DEFAULT_COUNTRY = process.env.BROWSA_COUNTRY || void 0;
14
+ var KEYS_URL = "https://app.browsa.io/dashboard/keys";
15
+ var NO_KEY_MESSAGE = "BROWSA_API_KEY is not set. Add it to this MCP server's env (mint one at " + KEYS_URL + "), then restart the server.";
16
+ var REDACT = !/^(0|off|false|no)$/i.test(process.env.BROWSA_MCP_REDACT ?? "");
17
+ var GROUPS = {
18
+ tasks: ["run_task", "get_job", "cancel_job", "respond_to_job", "list_job_files"],
19
+ robots: ["list_robots", "run_robot", "get_robot_run"],
20
+ schedules: ["create_schedule", "list_schedules"],
21
+ webhooks: ["list_webhooks", "create_webhook", "delete_webhook"],
22
+ cdp: ["start_browser", "stop_browser"],
23
+ captcha: ["solve_captcha_task"],
24
+ admin: ["credits", "list_browsers", "list_identities", "proxy_network", "list_llm_keys", "list_models"]
25
+ };
26
+ var CORE_TOOLS = ["open", "observe", "act", "read", "screenshot", "secrets", "handoff", "flow", "close"];
27
+ function toolsSetting(argv) {
28
+ for (let i = 0; i < argv.length; i++) {
29
+ const a = argv[i];
30
+ if (a.startsWith("--tools=")) return a.slice("--tools=".length);
31
+ if (a === "--tools" && i + 1 < argv.length) return argv[i + 1];
32
+ }
33
+ return process.env.BROWSA_MCP_TOOLS ?? "";
34
+ }
35
+ function enabledExtras(setting = toolsSetting(process.argv.slice(2))) {
36
+ const tools2 = /* @__PURE__ */ new Set();
37
+ const unknown = [];
38
+ const all = Object.values(GROUPS).flat();
39
+ for (const raw of setting.split(/[,\s]+/)) {
40
+ const w = raw.trim().toLowerCase();
41
+ if (!w || w === "core") continue;
42
+ if (w === "all") all.forEach((t) => tools2.add(t));
43
+ else if (GROUPS[w]) GROUPS[w].forEach((t) => tools2.add(t));
44
+ else if (all.includes(w)) tools2.add(w);
45
+ else unknown.push(raw.trim());
46
+ }
47
+ return { tools: tools2, unknown };
48
+ }
49
+
50
+ // src/api.ts
51
+ import { BrowsaError } from "browsa";
52
+ function headers(json) {
53
+ const h = { "X-API-Key": API_KEY ?? "", Accept: "application/json", "User-Agent": `browsa-mcp/${VERSION}` };
54
+ if (json) h["Content-Type"] = "application/json";
55
+ return h;
56
+ }
57
+ async function parse(resp) {
58
+ const body = await resp.json().catch(() => ({}));
59
+ if (!resp.ok) {
60
+ throw new BrowsaError(body?.error || body?.message || `HTTP ${resp.status}`, {
61
+ code: body?.code ?? `HTTP_${resp.status}`,
62
+ requestId: body?.request_id,
63
+ status: resp.status
64
+ });
65
+ }
66
+ return body;
67
+ }
68
+ async function apiGet(path, timeoutMs = 9e4) {
69
+ return parse(await fetch(`${BASE_URL}${path}`, { headers: headers(false), signal: AbortSignal.timeout(timeoutMs) }));
70
+ }
71
+ async function apiPost(path, payload, timeoutMs = 9e4) {
72
+ return parse(await fetch(`${BASE_URL}${path}`, {
73
+ method: "POST",
74
+ headers: headers(true),
75
+ body: JSON.stringify(payload ?? {}),
76
+ signal: AbortSignal.timeout(timeoutMs)
77
+ }));
78
+ }
79
+ async function apiDelete(path, timeoutMs = 3e4) {
80
+ return parse(await fetch(`${BASE_URL}${path}`, { method: "DELETE", headers: headers(false), signal: AbortSignal.timeout(timeoutMs) }));
81
+ }
82
+
83
+ // src/flow.ts
84
+ function newRecording(startUrl) {
85
+ return { startUrl, steps: [], reads: 0, notes: [] };
86
+ }
87
+ function describeTarget(t) {
88
+ const what = t.name ? JSON.stringify(t.name) : t.css ? t.css : "the element";
89
+ return `${t.role || "element"} ${what}`;
90
+ }
91
+ function cleanTarget(t) {
92
+ if (!t) return void 0;
93
+ const out = {};
94
+ if (t.role) out.role = t.role;
95
+ if (t.name) out.name = t.name;
96
+ if (t.css) out.css = t.css;
97
+ return Object.keys(out).length ? out : void 0;
98
+ }
99
+ function secretToken(ref) {
100
+ const r = ref.trim();
101
+ const totp = /^TOTP:([A-Za-z0-9_]{1,64})$/i.exec(r);
102
+ if (totp) return `{{totp:${totp[1].toUpperCase()}}}`;
103
+ const part = /^([A-Za-z0-9_]{1,64}):(username|password)$/i.exec(r);
104
+ if (part) return `{{secret:${part[1].toUpperCase()}:${part[2].toLowerCase()}}}`;
105
+ return `{{secret:${r.toUpperCase()}}}`;
106
+ }
107
+ function recordAct(rec, args, target, url, secretRef) {
108
+ const n = rec.steps.length + 1;
109
+ const id = `s${n}`;
110
+ const t = cleanTarget(target);
111
+ const need = (kind) => {
112
+ if (t) return void 0;
113
+ const note = `${kind} on [${args.id ?? "?"}] not recorded: the element was not in a view (observe first)`;
114
+ rec.notes.push(note);
115
+ return note;
116
+ };
117
+ switch (args.action) {
118
+ case "navigate":
119
+ rec.steps.push({ id, kind: "navigate", url: String(args.url) });
120
+ return;
121
+ case "back":
122
+ case "forward":
123
+ case "reload":
124
+ if (url) rec.steps.push({ id, kind: "navigate", url });
125
+ return;
126
+ case "click":
127
+ case "check":
128
+ case "uncheck": {
129
+ if (args.x !== void 0 && !args.id && !args.role) {
130
+ const note = "click at a point not recorded: a replay needs an element";
131
+ rec.notes.push(note);
132
+ return note;
133
+ }
134
+ const miss = need(args.action);
135
+ if (miss) return miss;
136
+ rec.steps.push({ id, kind: "click", target: t, goal: `click the ${describeTarget(t)}` });
137
+ return;
138
+ }
139
+ case "type": {
140
+ const miss = need("type");
141
+ if (miss) return miss;
142
+ const text = secretRef ? secretToken(secretRef) : String(args.text ?? "");
143
+ const step = { id, kind: "type", target: t, text, goal: `type into the ${describeTarget(t)}` };
144
+ if (args.submit) step.submit = true;
145
+ rec.steps.push(step);
146
+ return;
147
+ }
148
+ case "select": {
149
+ const miss = need("select");
150
+ if (miss) return miss;
151
+ rec.steps.push({ id, kind: "select", target: t, value: String(args.option ?? ""), goal: `choose ${JSON.stringify(args.option)} in the ${describeTarget(t)}` });
152
+ return;
153
+ }
154
+ case "press":
155
+ rec.steps.push({ id, kind: "press", keys: String(args.keys ?? "") });
156
+ return;
157
+ case "scroll":
158
+ if (typeof args.dy === "number" && args.dy !== 0) rec.steps.push({ id, kind: "scroll", value: String(args.dy) });
159
+ else if (args.to) rec.steps.push({ id, kind: "scroll", value: args.to === "top" ? "up" : "down", pages: 50 });
160
+ return;
161
+ case "wait":
162
+ if (args.for === "text" && args.text) {
163
+ rec.steps.push({ id, kind: "wait", for: { text: String(args.text) }, timeout_ms: Math.min(Math.max(Number(args.timeout) || 15e3, 100), 12e4) });
164
+ } else if (args.for === "url-change" && url) {
165
+ rec.steps.push({ id, kind: "wait", for: { url }, timeout_ms: Math.min(Math.max(Number(args.timeout) || 15e3, 100), 12e4) });
166
+ }
167
+ return;
168
+ }
169
+ if (!["solve_captcha", "press_and_hold", "hover"].includes(args.action)) {
170
+ const note = `${args.action} not recorded: replays have no such step`;
171
+ rec.notes.push(note);
172
+ return note;
173
+ }
174
+ return;
175
+ }
176
+ function fieldName(s, i, seen) {
177
+ let n = s.toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "").slice(0, 40);
178
+ if (!n || !/^[a-z]/.test(n)) n = `col${i + 1}`;
179
+ while (seen.has(n)) n += "_";
180
+ seen.add(n);
181
+ return n;
182
+ }
183
+ function recordRead(rec, as, selector, headers2) {
184
+ if (!selector) {
185
+ const note = "read not recorded: the API gave no selector for that container (inside a frame, or the API is older)";
186
+ rec.notes.push(note);
187
+ return { note };
188
+ }
189
+ rec.reads++;
190
+ const into = `read_${rec.reads}`;
191
+ const id = `s${rec.steps.length + 1}`;
192
+ let how;
193
+ if (as === "table") {
194
+ const seen = /* @__PURE__ */ new Set();
195
+ const fields = {};
196
+ const cols = headers2.length ? headers2 : ["col1"];
197
+ cols.forEach((h, i) => {
198
+ fields[fieldName(h, i, seen)] = `:scope > :nth-child(${i + 1})`;
199
+ });
200
+ how = { css: `${selector} tbody tr`, fields, into, allow_empty: true };
201
+ } else if (as === "links") {
202
+ how = { css: `${selector} a[href]`, fields: { text: ".", href: "@href" }, into, allow_empty: true };
203
+ } else {
204
+ how = { css: selector, into };
205
+ }
206
+ rec.steps.push({ id, kind: "extract", from: "page", how, goal: `read the ${as} of ${selector}` });
207
+ return { into };
208
+ }
209
+ function replaceAll(s, find, by) {
210
+ return find ? s.split(find).join(by) : s;
211
+ }
212
+ function parameterize(v, params) {
213
+ if (typeof v === "string") {
214
+ let s = v;
215
+ for (const [name, ex] of Object.entries(params)) {
216
+ if (!ex) continue;
217
+ const tok = `{{${name}}}`;
218
+ s = replaceAll(s, ex, tok);
219
+ s = replaceAll(s, encodeURIComponent(ex), tok);
220
+ s = replaceAll(s, ex.replace(/ /g, "+"), tok);
221
+ }
222
+ return s;
223
+ }
224
+ if (Array.isArray(v)) return v.map((x) => parameterize(x, params));
225
+ if (v && typeof v === "object") {
226
+ const out = {};
227
+ for (const [k, x] of Object.entries(v)) out[k] = k === "target" || k === "how" ? x : parameterize(x, params);
228
+ return out;
229
+ }
230
+ return v;
231
+ }
232
+ function buildRecipe(rec, name, params) {
233
+ const steps = rec.steps.map((s) => parameterize(s, params));
234
+ const startsWeb = /^https?:\/\//.test(rec.startUrl);
235
+ if (startsWeb && steps[0]?.kind !== "navigate") {
236
+ steps.unshift({ id: "s0", kind: "navigate", url: parameterize(rec.startUrl, params) });
237
+ }
238
+ const paramProps = {};
239
+ for (const p of Object.keys(params)) paramProps[p] = { type: "string" };
240
+ const outProps = {};
241
+ for (let i = 1; i <= rec.reads; i++) outProps[`read_${i}`] = { type: "array" };
242
+ const recipe = {
243
+ name,
244
+ version: 1,
245
+ params: { type: "object", properties: paramProps, required: Object.keys(params) },
246
+ output: { type: "object", properties: outProps },
247
+ steps,
248
+ meta: { source: "mcp", recorded_steps: steps.length }
249
+ };
250
+ if (startsWeb && parameterize(rec.startUrl, params) === rec.startUrl) recipe.start_url = rec.startUrl;
251
+ return recipe;
252
+ }
253
+ function flowName(raw) {
254
+ return String(raw ?? "").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 63);
255
+ }
256
+
257
+ // src/viewtext.ts
258
+ var ELEMENT = /^\s*(?:[~+-] )?\[(\d+)\] ([A-Za-z][\w-]*)(?: "((?:[^"\\]|\\.)*)")?/;
259
+ function unquote(s) {
260
+ return s.replace(/\\(["\\])/g, "$1");
261
+ }
262
+ function elementsOf(text) {
263
+ const out = /* @__PURE__ */ new Map();
264
+ for (const line of text.split("\n")) {
265
+ const m = ELEMENT.exec(line);
266
+ if (m) out.set(Number(m[1]), { role: m[2], name: m[3] !== void 0 ? unquote(m[3]) : "" });
267
+ }
268
+ return out;
269
+ }
270
+ function indentOf(line) {
271
+ return line.length - line.trimStart().length;
272
+ }
273
+ function matcher(query) {
274
+ const re = /^\/(.+)\/([a-z]*)$/s.exec(query.trim());
275
+ if (re) {
276
+ try {
277
+ const flags = re[2].includes("i") ? re[2] : re[2] + "i";
278
+ const rx = new RegExp(re[1], flags.replace(/[gy]/g, ""));
279
+ return (s) => rx.test(s);
280
+ } catch {
281
+ }
282
+ }
283
+ const q = query.trim().toLowerCase();
284
+ return (s) => s.toLowerCase().includes(q);
285
+ }
286
+ var SUMMARY = /^(page |dialog: |above the fold:|below the fold:|off to the side:|behind dialog:|… )/;
287
+ function findInView(text, query, maxMatches = 25, maxChars = 2400) {
288
+ const lines = text.split("\n");
289
+ const head = lines[0]?.startsWith("page ") ? lines[0] : "";
290
+ const test = matcher(query);
291
+ const stack = [];
292
+ const hits = [];
293
+ let count = 0;
294
+ for (let i = head ? 1 : 0; i < lines.length; i++) {
295
+ const line = lines[i];
296
+ if (!line.trim()) continue;
297
+ const ind = indentOf(line);
298
+ while (stack.length && stack[stack.length - 1].indent >= ind) stack.pop();
299
+ if (!SUMMARY.test(line.trim()) && test(line)) {
300
+ count++;
301
+ if (hits.length < maxMatches) {
302
+ const parent = [...stack].reverse().find((s) => ELEMENT.test(s.line));
303
+ let hit = line.trim();
304
+ if (parent) {
305
+ const p = parent.line.trim();
306
+ hit += ` (in ${p.length > 60 ? p.slice(0, 57) + "..." : p})`;
307
+ }
308
+ hits.push(hit);
309
+ }
310
+ }
311
+ if (ELEMENT.test(line)) stack.push({ indent: ind, line });
312
+ }
313
+ let body = hits.join("\n");
314
+ if (body.length > maxChars) {
315
+ body = body.slice(0, maxChars);
316
+ body = body.slice(0, body.lastIndexOf("\n") > 0 ? body.lastIndexOf("\n") : body.length);
317
+ }
318
+ const shown = body ? body.split("\n").length : 0;
319
+ const out = [`find ${JSON.stringify(query)}: ${count} match${count === 1 ? "" : "es"}`];
320
+ if (head) out.push(head);
321
+ if (body) out.push(body);
322
+ if (count > shown) out.push(`\u2026 ${count - shown} more (narrow find, or observe with expand)`);
323
+ if (!count) out.push("nothing on the page matches; try other words, or scroll and observe");
324
+ return out.join("\n");
325
+ }
326
+ function subtreeLines(text, id) {
327
+ const lines = text.split("\n");
328
+ const start = lines.findIndex((l) => {
329
+ const m = ELEMENT.exec(l);
330
+ return !!m && Number(m[1]) === id && !/^\s*[~+-] /.test(l);
331
+ });
332
+ if (start < 0) return "";
333
+ const base = indentOf(lines[start]);
334
+ const out = [lines[start].slice(base)];
335
+ for (let i = start + 1; i < lines.length; i++) {
336
+ const l = lines[i];
337
+ if (!l.trim()) continue;
338
+ if (indentOf(l) <= base) break;
339
+ out.push(l.slice(base));
340
+ }
341
+ return out.join("\n");
342
+ }
343
+ function tokensOf(s) {
344
+ return Math.ceil(s.length / 4);
345
+ }
346
+
347
+ // src/core.ts
348
+ var BID = { type: "string", description: "Default: the last browser used." };
349
+ var ACTIONS = ["click", "type", "press", "select", "check", "uncheck", "hover", "scroll", "navigate", "back", "forward", "reload", "wait", "upload", "dialog", "press_and_hold", "solve_captcha"];
350
+ var DEFAULT_BUDGET = 1500;
351
+ var MAX_BUDGET = 6e3;
352
+ var DIFF_MAX_TOKENS = 400;
353
+ var coreTools = [
354
+ {
355
+ name: "open",
356
+ description: "Open a cloud browser (Phantom) and go to url. Returns the browser id, a live view link and the first view. Close it when done.",
357
+ inputSchema: {
358
+ type: "object",
359
+ properties: {
360
+ url: { type: "string" },
361
+ where: { type: "string", enum: ["cloud"] },
362
+ country: { type: "string", description: "Exit country, e.g. us. Needs a proxy." },
363
+ profile: { type: "string", description: "Saved identity id: keeps its cookies and logins." },
364
+ proxy: { type: "object", description: "{network: datacenter|residential, country?} or your own {server, username?, password?}." },
365
+ ttl: { type: "string", description: "e.g. 10m (default), 1h." }
366
+ }
367
+ }
368
+ },
369
+ {
370
+ name: "observe",
371
+ description: 'The page as text: one line per element, [id] role "name" state. Use ids with act. find returns only the matching lines.',
372
+ inputSchema: {
373
+ type: "object",
374
+ properties: {
375
+ browser_id: BID,
376
+ scope: { type: "string", enum: ["viewport", "page"] },
377
+ budget: { type: "integer", description: "Tokens, default 1500, max 6000." },
378
+ expand: { type: "integer", description: "Container id to list in full." },
379
+ find: { type: "string", description: "Text or /regex/ to look for on the whole page." },
380
+ tab: { type: "string" }
381
+ }
382
+ }
383
+ },
384
+ {
385
+ name: "act",
386
+ description: "One action with real input. Answers what changed or a fresh view. First line: ok, failed, blocked, challenge, stale, dialog or secret_origin.",
387
+ inputSchema: {
388
+ type: "object",
389
+ required: ["action"],
390
+ properties: {
391
+ browser_id: BID,
392
+ action: { type: "string", enum: ACTIONS },
393
+ id: { type: "integer" },
394
+ role: { type: "string", description: "With name: the element by role and name, instead of id." },
395
+ name: { type: "string" },
396
+ x: { type: "number", description: "click at a viewport point, with y." },
397
+ y: { type: "number" },
398
+ text: { type: "string", description: "type: text. wait: text to wait for. dialog: prompt answer." },
399
+ secret: { type: "string", description: "type: a saved secret instead of text, e.g. NAME:password, TOTP:NAME. Never shown." },
400
+ clear: { type: "boolean" },
401
+ submit: { type: "boolean", description: "type: press Enter after." },
402
+ keys: { type: "string", description: 'press: Enter, Control+A, "Tab Tab Enter".' },
403
+ option: { type: "string", description: "select: option text or value." },
404
+ double: { type: "boolean" },
405
+ right: { type: "boolean" },
406
+ dy: { type: "integer", description: "scroll: pixels, + is down." },
407
+ to: { type: "string", enum: ["top", "bottom"] },
408
+ url: { type: "string" },
409
+ ms: { type: "integer" },
410
+ for: { type: "string", enum: ["text", "id-gone", "url-change"] },
411
+ timeout: { type: "integer" },
412
+ files: { type: "array", items: { type: "string" } },
413
+ accept: { type: "boolean", description: "dialog: accept or dismiss." },
414
+ tab: { type: "string" }
415
+ }
416
+ }
417
+ },
418
+ {
419
+ name: "read",
420
+ description: "The full content of one container by id, with no model: text, a table as TSV, or links.",
421
+ inputSchema: {
422
+ type: "object",
423
+ required: ["id"],
424
+ properties: { browser_id: BID, id: { type: "integer" }, as: { type: "string", enum: ["text", "table", "links"] } }
425
+ }
426
+ },
427
+ {
428
+ name: "screenshot",
429
+ description: "JPEG of the viewport (pixels / scale = act x,y), the full page, or one element.",
430
+ inputSchema: { type: "object", properties: { browser_id: BID, id: { type: "integer" }, full: { type: "boolean" } } }
431
+ },
432
+ {
433
+ name: "secrets",
434
+ description: "Saved secrets: names, kinds, the sites they may be typed on, one-time-code flag. Never values. Type one with act secret.",
435
+ inputSchema: { type: "object", properties: {} }
436
+ },
437
+ {
438
+ name: "handoff",
439
+ description: "A single-use live link for a person to take over (captcha, login, a decision). The next observe or act says when they are done.",
440
+ inputSchema: {
441
+ type: "object",
442
+ required: ["reason"],
443
+ properties: {
444
+ browser_id: BID,
445
+ reason: { type: "string" },
446
+ scope: { type: "string", enum: ["control", "view"] },
447
+ wait_s: { type: "integer", description: "Wait up to this long (max 900) for the page to change." }
448
+ }
449
+ }
450
+ },
451
+ {
452
+ name: "flow",
453
+ description: "Record act and read steps (start), save them (save), replay with no model (run), list. A broken step answers site_changed.",
454
+ inputSchema: {
455
+ type: "object",
456
+ required: ["op"],
457
+ properties: {
458
+ op: { type: "string", enum: ["start", "save", "run", "list"] },
459
+ name: { type: "string" },
460
+ params: { type: "object", description: "save: {param: example value typed}. run: {param: value}." },
461
+ version: { type: "integer" },
462
+ browser_id: BID
463
+ }
464
+ }
465
+ },
466
+ {
467
+ name: "close",
468
+ description: "Close a browser and stop its billing.",
469
+ inputSchema: { type: "object", properties: { browser_id: BID } }
470
+ }
471
+ ];
472
+ var browsers = /* @__PURE__ */ new Map();
473
+ var lastBrowser;
474
+ function stateOf(id) {
475
+ let b = browsers.get(id);
476
+ if (!b) {
477
+ b = { id, last: "", sessions: /* @__PURE__ */ new Map(), elements: /* @__PURE__ */ new Map(), url: "", title: "" };
478
+ browsers.set(id, b);
479
+ }
480
+ return b;
481
+ }
482
+ var ToolError = class extends Error {
483
+ };
484
+ function browserOf(args) {
485
+ const id = String(args.browser_id || lastBrowser || "");
486
+ if (!id) throw new ToolError("error: no browser yet\nnext: call open first");
487
+ lastBrowser = id;
488
+ return stateOf(id);
489
+ }
490
+ function forget(id) {
491
+ browsers.delete(id);
492
+ if (lastBrowser === id) lastBrowser = void 0;
493
+ }
494
+ function explain(e, tool, browserId) {
495
+ if (e instanceof ToolError) return e.message;
496
+ if (!(e instanceof BrowsaError)) {
497
+ const msg = e?.name === "TimeoutError" ? "the API did not answer in time" : e?.message || String(e);
498
+ return `error: ${msg}
499
+ next: try again; if it keeps failing, observe to see the page`;
500
+ }
501
+ const code = e.code || "";
502
+ const head = `error: ${code ? code + ": " : ""}${e.message}`;
503
+ const next = (s) => `${head}
504
+ next: ${s}`;
505
+ switch (true) {
506
+ case (code === "AGENT_NOT_RUNNING" || code === "NOT_FOUND" && /agent/i.test(e.message)):
507
+ if (browserId) forget(browserId);
508
+ return next("this browser is gone (it expired or was closed); call open for a new one");
509
+ case code === "BROWSER_BUSY":
510
+ return next("another call is still running on this browser; retry in a few seconds");
511
+ case code === "BROWSER_UNREACHABLE":
512
+ return tool === "act" ? next("the connection dropped during the action, so it may or may not have happened; call observe before acting again") : next("the browser could not be reached; retry, or close it and open a new one");
513
+ case code === "TAB_NOT_FOUND":
514
+ return next("that tab is closed; observe without tab lists the open tabs");
515
+ case code === "DIALOG_OPEN":
516
+ return next("a dialog is open; call act with action dialog and accept true or false first");
517
+ case code === "STALE":
518
+ return next("the page changed; call observe and use the new ids");
519
+ case (e.status === 401 || code === "INVALID_API_KEY" || code === "MISSING_API_KEY"):
520
+ return next(`BROWSA_API_KEY was refused; mint a key at ${KEYS_URL} and restart the server`);
521
+ case (e.status === 402 || /CREDIT/.test(code)):
522
+ return next("not enough credits; top up at https://app.browsa.io/dashboard/billing");
523
+ case e.status === 429:
524
+ return next("too many requests; wait a little and retry");
525
+ case code === "SECRETS_UNAVAILABLE":
526
+ return next("secrets are not enabled on this Browsa server yet; type the text yourself or call handoff");
527
+ case code === "SECRET_NOT_FOUND":
528
+ return next("call secrets for the saved names");
529
+ case code === "SECRET_REF_INVALID":
530
+ return next("use one of the refs that secrets lists, e.g. NAME:password or TOTP:NAME");
531
+ case code === "CAPTCHA_UNAVAILABLE":
532
+ return next("captcha solving is off here; call handoff so a person can solve it");
533
+ case code === "REPLAY_UNAVAILABLE":
534
+ return next("flows are not switched on for this workspace yet; keep using act");
535
+ case (e.status === 404 && tool === "handoff"):
536
+ return next("live links are not on for this workspace; ask the person to open the dashboard's live view");
537
+ case (e.status === 404 && tool === "screenshot"):
538
+ return next("that element is gone; observe and use a current id");
539
+ }
540
+ return e.requestId ? `${head} (request ${e.requestId})` : head;
541
+ }
542
+ async function pageCall(b, route, body) {
543
+ const tab = body.tab ?? b.last;
544
+ const session = tab ? b.sessions.get(tab) : void 0;
545
+ if (session) body.session = session;
546
+ const r = await apiPost(`/v1/agents/${encodeURIComponent(b.id)}/${route}`, body, 12e4);
547
+ if (r?.tab && r?.session) {
548
+ b.last = r.tab;
549
+ b.sessions.set(r.tab, r.session);
550
+ }
551
+ if (typeof r?.url === "string") b.url = r.url;
552
+ if (typeof r?.title === "string") b.title = r.title;
553
+ const t = r?.tab ?? tab ?? "";
554
+ let els = b.elements.get(t);
555
+ if (!els || r?.ids_reset || r?.fresh_view === "new page" || r?.navigation && !r.navigation.same_document) {
556
+ els = /* @__PURE__ */ new Map();
557
+ b.elements.set(t, els);
558
+ }
559
+ if (typeof r?.text === "string") for (const [id, e] of elementsOf(r.text)) els.set(id, e);
560
+ return r;
561
+ }
562
+ function tabsLine(r) {
563
+ if (!Array.isArray(r?.tabs) || r.tabs.length < 2) return "";
564
+ return "\ntabs: " + r.tabs.map((t) => `${t.id} ${JSON.stringify(t.title || t.url || "")}${t.active ? " (this one)" : ""}`).join(" | ");
565
+ }
566
+ function handoffLine(b, r) {
567
+ const h = b.handoff;
568
+ if (!h) return "";
569
+ const challenge = r?.challenge?.kind ?? (r?.state === "challenge" ? "challenge" : "");
570
+ const done = r?.url && r.url !== h.url || h.challenge && !challenge;
571
+ if (done) {
572
+ b.handoff = void 0;
573
+ const why = h.challenge && !challenge ? `the ${h.challenge} check is gone` : r?.url !== h.url ? `the page is now ${r.url}` : "the page changed";
574
+ return `handoff: done (${why}); the person has finished, carry on from this page
575
+ `;
576
+ }
577
+ const mins = Math.max(1, Math.round((Date.now() - h.at) / 6e4));
578
+ return `handoff: still waiting for the person (link sent ${mins} min ago, expires ${h.expiresAt}); acting now may get in their way
579
+ `;
580
+ }
581
+ async function open(args) {
582
+ if (args.where && args.where !== "cloud") throw new ToolError("error: only cloud browsers for now\nnext: call open without where");
583
+ const body = { ttl: args.ttl || "10m" };
584
+ const country = args.country ?? DEFAULT_COUNTRY;
585
+ if (country) body.country = country;
586
+ if (args.profile) body.agent_id = args.profile;
587
+ if (args.proxy) body.proxy = args.proxy;
588
+ const a = await apiPost("/v1/agents", body, 12e4);
589
+ const id = String(a.id);
590
+ const b = stateOf(id);
591
+ lastBrowser = id;
592
+ const egress = args.proxy?.network ? `Browsa ${args.proxy.network} proxy` : args.proxy ? "your proxy" : "Browsa's address";
593
+ const head = [`ok: browser ${id} is open (Phantom, cloud, ${egress}), expires ${a.expires_at ?? "with its ttl"}; close it when done`];
594
+ if (a.live_url) head.push(`live view (single use, for a person): ${a.live_url}`);
595
+ if (!args.url) {
596
+ head.push("the page is blank; next: act with action navigate and a url");
597
+ return head.join("\n");
598
+ }
599
+ try {
600
+ const r = await pageCall(b, "act", { action: "navigate", url: String(args.url) });
601
+ let view = String(r.text ?? "");
602
+ if (tokensOf(view) > DEFAULT_BUDGET * 1.1) view = String((await pageCall(b, "observe", { budget: DEFAULT_BUDGET })).text ?? view);
603
+ return `${head.join("\n")}
604
+ ${statusLine(r)}
605
+ ${stripStatus(view)}${tabsLine(r)}`;
606
+ } catch (e) {
607
+ return `${head.join("\n")}
608
+ ${explain(e, "act", id)}`;
609
+ }
610
+ }
611
+ function clampBudget(v) {
612
+ const n = Math.floor(Number(v));
613
+ if (!Number.isFinite(n) || n <= 0) return DEFAULT_BUDGET;
614
+ return Math.min(Math.max(n, 100), MAX_BUDGET);
615
+ }
616
+ async function observe(args) {
617
+ const b = browserOf(args);
618
+ const body = {};
619
+ if (args.tab) body.tab = args.tab;
620
+ if (args.expand) body.expand = Number(args.expand);
621
+ if (typeof args.find === "string" && args.find.trim()) {
622
+ body.scope = "page";
623
+ body.budget = -1;
624
+ const r2 = await pageCall(b, "observe", body);
625
+ return handoffLine(b, r2) + findInView(String(r2.text ?? ""), args.find) + tabsLine(r2);
626
+ }
627
+ if (args.scope) body.scope = args.scope;
628
+ body.budget = clampBudget(args.budget);
629
+ const r = await pageCall(b, "observe", body);
630
+ return handoffLine(b, r) + String(r.text ?? "") + tabsLine(r);
631
+ }
632
+ var STATUS_PREFIX = /^(failed|blocked|challenge|secret_origin|stale|not solved|solved): /;
633
+ function stripStatus(text) {
634
+ return text.split("\n").filter((l) => !STATUS_PREFIX.test(l)).join("\n");
635
+ }
636
+ function statusLine(r) {
637
+ const status = String(r?.status ?? "ok");
638
+ const reason = r?.reason ? String(r.reason) : "";
639
+ if (r?.dialog && (status === "ok" || status === "blocked")) {
640
+ const d = r.dialog;
641
+ const what = d?.message ? ` (${d.type ?? "dialog"}: ${JSON.stringify(String(d.message).slice(0, 120))})` : "";
642
+ return `dialog: a dialog is open${what}; next: act with action dialog and accept true or false`;
643
+ }
644
+ switch (status) {
645
+ case "ok":
646
+ return "ok";
647
+ case "stale":
648
+ return "stale: the page changed and those ids are gone; nothing was done. Fresh view:";
649
+ case "failed":
650
+ if (/unknown id|element gone|no element with role/.test(reason)) return `failed: ${reason}; next: use an id from this view, or observe`;
651
+ return `failed: ${reason}`;
652
+ case "blocked":
653
+ return `blocked: ${reason}; next: close what covers it (click it, or press Escape) and retry`;
654
+ case "challenge":
655
+ return `challenge: ${reason}; next: act solve_captcha, and if it stays, handoff`;
656
+ case "secret_origin":
657
+ return `secret_origin: ${reason}; next: check the page, secrets lists where each secret may be typed`;
658
+ }
659
+ return reason ? `${status}: ${reason}` : status;
660
+ }
661
+ async function act(args) {
662
+ const b = browserOf(args);
663
+ const { browser_id: _drop, ...body } = args;
664
+ if (typeof body.action !== "string") throw new ToolError('error: action is required\nnext: e.g. {"action": "click", "id": 12}');
665
+ const rec = b.recording;
666
+ if (rec) body.record = true;
667
+ const before = b.elements.get(String(args.tab ?? b.last));
668
+ const r = await pageCall(b, "act", body);
669
+ const status = String(r?.status ?? "ok");
670
+ const hand = handoffLine(b, r);
671
+ if (body.secret && status === "ok" && !r?.secret) {
672
+ return hand + "failed: this Browsa server cannot type secrets yet, so nothing was typed\nnext: type the value with text if the person gave it to you, or call handoff so they can type it";
673
+ }
674
+ if (body.action === "solve_captcha") {
675
+ const lines = String(r.text ?? "").split("\n");
676
+ const first = lines.shift() ?? "";
677
+ const head = status === "ok" ? `ok: captcha ${first}` : `failed: captcha ${first}; next: call handoff so a person can solve it`;
678
+ return hand + head + "\n" + lines.join("\n") + tabsLine(r);
679
+ }
680
+ let text = stripStatus(String(r.text ?? ""));
681
+ if (status === "ok" && !r.dialog) {
682
+ const fresh = !!r.fresh_view;
683
+ if (!fresh && tokensOf(text) > DIFF_MAX_TOKENS || fresh && tokensOf(text) > DEFAULT_BUDGET * 1.1) {
684
+ const echo = text.split("\n")[0];
685
+ const v = await pageCall(b, "observe", { budget: DEFAULT_BUDGET, ...args.tab ? { tab: args.tab } : {} });
686
+ text = `${echo}
687
+ ${fresh ? "fresh view" : "large change, fresh view"}:
688
+ ${v.text ?? ""}`;
689
+ }
690
+ }
691
+ let note = "";
692
+ if (rec && status === "ok") {
693
+ const t = r.target ?? (args.id ? before?.get(Number(args.id)) : void 0) ?? (args.role || args.name ? { role: args.role, name: args.name } : void 0);
694
+ const n = recordAct(rec, body, t, String(r.url ?? b.url), r.secret ?? args.secret);
695
+ if (n) note = `
696
+ flow: ${n}`;
697
+ }
698
+ return hand + statusLine(r) + "\n" + text + tabsLine(r) + note;
699
+ }
700
+ function tsv(cells) {
701
+ return cells.map((c) => String(c ?? "").replace(/[\t\r\n]+/g, " ")).join(" ");
702
+ }
703
+ async function read(args) {
704
+ const b = browserOf(args);
705
+ const id = Math.floor(Number(args.id));
706
+ if (!id) throw new ToolError("error: id is required\nnext: an id of a container from observe");
707
+ const as = ["text", "table", "links"].includes(args.as) ? args.as : "text";
708
+ const r = await pageCall(b, "observe", { expand: id, scope: "page", budget: -1, json: true, selector: true });
709
+ const text = String(r.text ?? "");
710
+ if (/^note: expand was ignored/m.test(text)) {
711
+ return "stale: the page changed and that id is gone. Fresh view:\n" + text.replace(/^note: .*\n/, "");
712
+ }
713
+ const els = Array.isArray(r.view?.elements) ? r.view.elements : [];
714
+ const parent = /* @__PURE__ */ new Map();
715
+ for (const e of els) if (e?.id) parent.set(e.id, e.parent ?? 0);
716
+ const inside = (e) => {
717
+ let p = e?.parent ?? 0;
718
+ for (let i = 0; p && i < 200; i++) {
719
+ if (p === id) return true;
720
+ p = parent.get(p) ?? 0;
721
+ }
722
+ return false;
723
+ };
724
+ let out = "";
725
+ let headers2 = [];
726
+ if (as === "table") {
727
+ const rows = els.filter((e) => e?.kind === "row" && (inside(e) || e.parent === id));
728
+ const head = rows.find((e) => e.header);
729
+ headers2 = head ? head.cells ?? [] : [];
730
+ out = rows.map((e) => tsv(e.cells ?? [])).join("\n");
731
+ if (!rows.length) out = "(no table rows in that element; try as text)";
732
+ } else if (as === "links") {
733
+ const links = els.filter((e) => e?.role === "link" && (inside(e) || e.id === id));
734
+ out = links.map((e) => tsv([e.name ?? "", e.state?.href ?? ""])).join("\n");
735
+ if (!links.length) out = "(no links in that element)";
736
+ } else {
737
+ out = subtreeLines(text, id);
738
+ if (!out) {
739
+ return `failed: no element [${id}] in the current view; next: observe and use a current id`;
740
+ }
741
+ }
742
+ const MAX = 24e3;
743
+ if (out.length > MAX) out = out.slice(0, MAX) + `
744
+ \u2026 cut at ${MAX} characters`;
745
+ let note = "";
746
+ if (b.recording) {
747
+ const res = recordRead(b.recording, as, String(r.selector ?? ""), headers2);
748
+ note = res.into ? `
749
+ flow: recorded as ${res.into}` : `
750
+ flow: ${res.note}`;
751
+ }
752
+ return `ok: [${id}] as ${as}
753
+ ${out}${note}`;
754
+ }
755
+ async function screenshot(args) {
756
+ const b = browserOf(args);
757
+ const shot = {};
758
+ if (args.full) shot.full = true;
759
+ if (args.id) shot.id = Number(args.id);
760
+ const r = await pageCall(b, "observe", { screenshot: shot });
761
+ const s = r?.screenshot;
762
+ if (!s?.data) {
763
+ throw new ToolError("error: this Browsa server cannot take screenshots yet\nnext: use observe; screenshots come with the next API release");
764
+ }
765
+ const what = args.id ? `element [${args.id}]` : args.full ? "full page" : "viewport";
766
+ let text = `ok: ${what}, ${s.width}x${s.height}`;
767
+ if (!args.id && !args.full) text += `, scale ${s.scale}: act x = pixel x / ${s.scale}`;
768
+ if (s.truncated) text += " (cut at the first 6000 px of the page)";
769
+ return { text, image: { data: s.data, mime: s.mime || "image/jpeg" } };
770
+ }
771
+ function where(origins) {
772
+ if (!origins?.length) return "no sites yet (set them on the Secrets page; it can not be typed)";
773
+ if (origins.length === 1 && origins[0] === "*") return "any https site";
774
+ return origins.map((o) => {
775
+ const h = o.replace(/^https:\/\//, "");
776
+ return h.startsWith("*.") ? `${h.slice(2)} and subdomains` : h;
777
+ }).join(", ");
778
+ }
779
+ async function secrets() {
780
+ let body;
781
+ try {
782
+ body = await apiGet("/v1/secrets");
783
+ } catch (e) {
784
+ if (e instanceof BrowsaError && (e.status === 404 || e.status === 503 || e.status === 405)) {
785
+ return "secrets: not available on this Browsa server yet\nnext: type values yourself, or call handoff for a login";
786
+ }
787
+ throw e;
788
+ }
789
+ const list = Array.isArray(body?.secrets) ? body.secrets : [];
790
+ if (!list.length) return "secrets: none saved\nnext: save logins and keys at https://app.browsa.io (Secrets); values never pass through here";
791
+ const lines = [`secrets: ${list.length} (values are never shown; type one with act {action: "type", id, secret: REF})`];
792
+ for (const s of list) {
793
+ const refs = Array.isArray(s.placeholders) ? s.placeholders.join(", ") : s.name;
794
+ let line = `${s.name} ${s.type} on ${where(s.origins)} refs ${refs}`;
795
+ if (s.has_totp) line += " one-time code";
796
+ if (s.description) line += ` ${JSON.stringify(String(s.description).slice(0, 120))}`;
797
+ lines.push(line);
798
+ }
799
+ return lines.join("\n");
800
+ }
801
+ async function handoff(args) {
802
+ const b = browserOf(args);
803
+ const reason = String(args.reason ?? "").trim();
804
+ if (!reason) throw new ToolError('error: reason is required\nnext: say what the person should do, e.g. "solve the captcha"');
805
+ const scope = args.scope === "view" ? "view" : "control";
806
+ const waitS = Math.min(Math.max(Math.floor(Number(args.wait_s) || 0), 0), 900);
807
+ const base = await pageCall(b, "observe", { budget: 200 });
808
+ const link = await apiPost(`/v1/agents/${encodeURIComponent(b.id)}/live`, { scope, ttl_seconds: Math.min(Math.max(waitS + 600, 300), 3600) });
809
+ b.handoff = {
810
+ link: link.live_url,
811
+ expiresAt: link.expires_at ?? "",
812
+ reason,
813
+ at: Date.now(),
814
+ url: String(base.url ?? b.url),
815
+ challenge: base.challenge?.kind ?? (base.state === "challenge" ? "challenge" : ""),
816
+ title: String(base.title ?? "")
817
+ };
818
+ const head = `waiting: give this link to the person (single use, ${scope}, expires ${link.expires_at ?? "soon"}):
819
+ ${link.live_url}
820
+ reason: ${reason}`;
821
+ if (!waitS) return `${head}
822
+ next: the next observe or act says when the page changed (they are done)`;
823
+ const deadline = Date.now() + waitS * 1e3;
824
+ while (Date.now() < deadline) {
825
+ await new Promise((res) => setTimeout(res, Math.min(HANDOFF_POLL_MS, Math.max(0, deadline - Date.now()))));
826
+ const r = await pageCall(b, "observe", { budget: DEFAULT_BUDGET });
827
+ const line = handoffLine(b, r);
828
+ if (line.startsWith("handoff: done")) return `${head}
829
+ ${line}${r.text ?? ""}`;
830
+ }
831
+ return `${head}
832
+ handoff: still waiting after ${waitS}s
833
+ next: ask the person, then observe`;
834
+ }
835
+ var HANDOFF_POLL_MS = Number(process.env.BROWSA_HANDOFF_POLL_MS) || 3e3;
836
+ var RUN_DONE = /* @__PURE__ */ new Set(["ok", "failed", "cancelled"]);
837
+ var FLOW_POLL_S = Number(process.env.BROWSA_FLOW_WAIT_S) || 60;
838
+ async function findFlow(name) {
839
+ const body = await apiGet("/v1/recipes?limit=200");
840
+ const list = Array.isArray(body?.recipes) ? body.recipes : [];
841
+ return list.find((r) => r.name === name && r.status !== "draft");
842
+ }
843
+ function failingStep(run) {
844
+ const layers = Array.isArray(run?.layers) ? run.layers : Array.isArray(run?.layers?.steps) ? run.layers.steps : [];
845
+ const bad = layers.find((l) => l && (l.ok === false || l.error || l.status === "failed"));
846
+ if (!bad) return "";
847
+ const s = JSON.stringify(bad);
848
+ return s.length > 300 ? s.slice(0, 297) + "..." : s;
849
+ }
850
+ async function flow(args) {
851
+ const op = String(args.op ?? "");
852
+ if (op === "list") {
853
+ const body = await apiGet("/v1/recipes?limit=200");
854
+ const list = (Array.isArray(body?.recipes) ? body.recipes : []).filter((r) => r.status !== "draft");
855
+ if (!list.length) return "flows: none saved\nnext: flow start, then act and read, then flow save";
856
+ return [`flows: ${list.length}`, ...list.map((r) => `${r.name} v${r.current_version ?? "?"} ${r.price_credits} credits per run id ${r.id}`)].join("\n");
857
+ }
858
+ if (op === "start") {
859
+ const b = browserOf(args);
860
+ await pageCall(b, "observe", { budget: 100 });
861
+ b.recording = newRecording(b.url);
862
+ return `recording: every act and read on ${b.id} from now on (starting at ${b.url || "a blank page"})
863
+ next: do the task with act and read, then flow {op: "save", name, params: {param: example value}}`;
864
+ }
865
+ if (op === "save") {
866
+ const b = browserOf(args);
867
+ const rec = b.recording;
868
+ if (!rec) throw new ToolError('error: nothing is being recorded\nnext: flow {op: "start"} first');
869
+ const name = flowName(args.name);
870
+ if (!name) throw new ToolError('error: name is required\nnext: e.g. flow {op: "save", name: "book-search"}');
871
+ if (!rec.steps.length) throw new ToolError("error: no steps recorded yet\nnext: do the task with act and read first");
872
+ const params = {};
873
+ for (const [k, v] of Object.entries(args.params ?? {})) {
874
+ const key = String(k).toLowerCase().replace(/[^a-z0-9_]/g, "_");
875
+ if (key && v !== void 0 && v !== null && String(v) !== "") params[key] = String(v);
876
+ }
877
+ if (await findFlow(name)) throw new ToolError(`error: a flow named ${name} exists
878
+ next: pick another name`);
879
+ const recipe = buildRecipe(rec, name, params);
880
+ const saved = await apiPost("/v1/recipes", { recipe, name });
881
+ b.recording = void 0;
882
+ const lines = [`ok: saved flow ${name} (v${saved.current_version ?? 1}, ${recipe.steps.length} steps, ${saved.price_credits} credits per successful run, id ${saved.id})`];
883
+ const example = Object.keys(params).length ? `, params: ${JSON.stringify(Object.fromEntries(Object.keys(params).map((p) => [p, "..."])))}` : "";
884
+ lines.push(`run it: flow {op: "run", name: "${name}"${example}}`);
885
+ if (rec.notes.length) lines.push(...rec.notes.slice(0, 10).map((n) => `note: ${n}`));
886
+ return lines.join("\n");
887
+ }
888
+ if (op === "run") {
889
+ const name = flowName(args.name);
890
+ if (!name) throw new ToolError('error: name is required\nnext: flow {op: "list"} shows the names');
891
+ const f = await findFlow(name);
892
+ if (!f) throw new ToolError(`error: no flow named ${name}
893
+ next: flow {op: "list"}`);
894
+ const body = { params: args.params ?? {}, wait: FLOW_POLL_S };
895
+ if (args.version) body.version = Number(args.version);
896
+ let run = await apiPost(`/v1/recipes/${encodeURIComponent(f.id)}/run`, body, (FLOW_POLL_S + 30) * 1e3);
897
+ const deadline = Date.now() + 4 * FLOW_POLL_S * 1e3;
898
+ while (!RUN_DONE.has(run?.status) && Date.now() < deadline) {
899
+ run = await apiGet(`/v1/recipe-runs/${encodeURIComponent(run.id)}?wait=${FLOW_POLL_S}`, (FLOW_POLL_S + 30) * 1e3);
900
+ }
901
+ const secs = run.duration_ms ? `${(run.duration_ms / 1e3).toFixed(1)} s` : "";
902
+ const pinNote = args.version && run.version && Number(args.version) !== Number(run.version) ? `
903
+ note: v${args.version} was asked, this server ran v${run.version} (pinning a version needs a newer API)` : "";
904
+ if (run.status === "ok") {
905
+ return `ok: flow ${name} v${run.version} ran${secs ? " in " + secs : ""}, no model calls, ${run.credits ?? 0} credits${pinNote}
906
+ ${JSON.stringify(run.output ?? {}, null, 1)}`;
907
+ }
908
+ if (!RUN_DONE.has(run?.status)) return `running: flow ${name} is still running (run ${run.id})
909
+ next: flow run again later, or check the dashboard`;
910
+ const code = run.error_code || run.status;
911
+ const step = failingStep(run);
912
+ if (code === "site_changed") {
913
+ return `site_changed: flow ${name} v${run.version} failed at a step the site no longer has${step ? `
914
+ step: ${step}` : ""}
915
+ ${run.error_message ?? ""}
916
+ next: open the page, flow start, redo the steps with act, flow save under a new name (failed runs are free)`;
917
+ }
918
+ return `failed: ${code}: ${run.error_message ?? ""}${step ? `
919
+ step: ${step}` : ""}
920
+ next: failed runs are free; check the params, or redo the task with act`;
921
+ }
922
+ throw new ToolError("error: op must be start, save, run or list");
923
+ }
924
+ async function close(args) {
925
+ const b = browserOf(args);
926
+ const dropped = b.recording ? " (the unsaved recording was dropped)" : "";
927
+ try {
928
+ await apiDelete(`/v1/agents/${encodeURIComponent(b.id)}`);
929
+ } catch (e) {
930
+ if (!(e instanceof BrowsaError && (e.status === 404 || e.code === "AGENT_NOT_RUNNING"))) throw e;
931
+ }
932
+ forget(b.id);
933
+ return `ok: closed ${b.id}${dropped}`;
934
+ }
935
+ async function callCore(name, args) {
936
+ const browserId = args.browser_id || lastBrowser;
937
+ try {
938
+ switch (name) {
939
+ case "open":
940
+ return { text: await open(args) };
941
+ case "observe":
942
+ return { text: await observe(args) };
943
+ case "act":
944
+ return { text: await act(args) };
945
+ case "read":
946
+ return { text: await read(args) };
947
+ case "screenshot":
948
+ return await screenshot(args);
949
+ case "secrets":
950
+ return { text: await secrets() };
951
+ case "handoff":
952
+ return { text: await handoff(args) };
953
+ case "flow":
954
+ return { text: await flow(args) };
955
+ case "close":
956
+ return { text: await close(args) };
957
+ }
958
+ } catch (e) {
959
+ return { text: explain(e, name, browserId), isError: true };
960
+ }
961
+ return { text: `error: unknown tool ${name}`, isError: true };
962
+ }
963
+
964
+ // src/legacy.ts
965
+ import { Client } from "browsa";
966
+ var CAPTCHA_URL = (process.env.BROWSA_CAPTCHA_URL || (BASE_URL_SET ? `${BASE_URL}/captcha-api` : "https://captcha.browsa.io")).replace(/\/+$/, "");
13
967
  var DEFAULT_LLM = process.env.BROWSA_LLM || void 0;
14
968
  var BYOK_DEFAULT_LLM = "claude-opus-5-5";
15
969
  var DEFAULT_LLM_KEY = process.env.BROWSA_LLM_API_KEY || void 0;
16
970
  var DEFAULT_LLM_KEY_ID = process.env.BROWSA_LLM_KEY_ID || void 0;
17
- var DEFAULT_COUNTRY = process.env.BROWSA_COUNTRY;
971
+ var DEFAULT_COUNTRY2 = process.env.BROWSA_COUNTRY;
18
972
  var LLM_KEYS_URL = "https://app.browsa.io/dashboard/llm-keys";
19
- var NO_KEY_MESSAGE = "BROWSA_API_KEY is not set. Add it to this MCP server's env (mint one at https://app.browsa.io/dashboard/keys), then restart the server.";
20
- if (!API_KEY) {
21
- console.error("[browsa-mcp] BROWSA_API_KEY is not set: tools are listed, but every call will fail until it is.");
22
- console.error(" Mint one at https://app.browsa.io/dashboard/keys");
23
- }
24
- var client = API_KEY ? new Client({ apiKey: API_KEY, ...BASE_URL ? { baseUrl: BASE_URL } : {} }) : null;
25
- var server = new Server(
26
- { name: "browsa", version: "0.3.3" },
27
- { capabilities: { tools: {} } }
28
- );
973
+ var client = API_KEY ? new Client({ apiKey: API_KEY, ...BASE_URL_SET ? { baseUrl: BASE_URL } : {} }) : null;
29
974
  var REASONING_PROP = {
30
975
  type: "string",
31
976
  enum: ["low", "medium", "high"],
32
977
  description: "How much the model reasons. Omit for the tier's or the provider's default."
33
978
  };
34
- var tools = [
979
+ var legacyTools = [
35
980
  {
36
981
  name: "run_task",
37
- description: "Run a browser-driven AI task on a fresh Phantom cloud browser. Returns the final result, the outcome and the total steps. `status: completed` only means the run ended: read `outcome`. `outcome: failed` with `status: completed` means the agent finished but could not do the task, and `final_result` says what stopped it. Use this when the user asks for anything web-shaped: scrape, fill, click, extract, login, place an order, search, summarize a page, etc. The browser is a real macOS-Chrome-fingerprinted Phantom browser with built-in CAPTCHA solving (Turnstile, hCaptcha, reCAPTCHA, ALTCHA, FunCaptcha) and behavioral humanization. Default timeout: 10 minutes.",
982
+ description: "Run a browser-driven AI task on a fresh Phantom cloud browser. Returns the final result, the outcome and the total steps. `status: completed` only means the run ended: read `outcome`. `outcome: failed` with `status: completed` means the agent finished but could not do the task, and `final_result` says what stopped it. Use this when the user asks for anything web-shaped: scrape, fill, click, extract, login, place an order, search, summarize a page, etc. The browser is a real macOS-Chrome-fingerprinted Phantom browser with built-in captcha solving (the measured types are listed at https://browsa.io/captcha) and behavioral humanization. Default timeout: 10 minutes.",
38
983
  inputSchema: {
39
984
  type: "object",
40
985
  required: ["task"],
@@ -45,7 +990,7 @@ var tools = [
45
990
  },
46
991
  llm: {
47
992
  type: "string",
48
- description: `LLM identifier, e.g. anthropic:claude-sonnet-5-5, openai:gpt-4o, google:gemini-2.5-flash${DEFAULT_LLM ? ` (default: ${DEFAULT_LLM})` : ""}. Omit to use the workspace's default saved key with its provider's default model; if no key is saved at all, the task runs on Browsa's hosted model and the result says so. Hosted tiers need no LLM key and add a flat credit surcharge per task (see list_models): "browsa" (default hosted model), "browsa-fast" (fastest and lightest), "browsa-smart" (for harder tasks). When you name a model, there is no hosted fallback.`
993
+ description: `LLM identifier, provider:model, e.g. anthropic:claude-sonnet-5-5${DEFAULT_LLM ? ` (default: ${DEFAULT_LLM})` : ""}. Omit to use the workspace's default saved key with its provider's default model; if no key is saved at all, the task runs on Browsa's hosted model and the result says so. Hosted tiers need no LLM key and add a flat credit surcharge per task (see list_models): "browsa" (default hosted model), "browsa-fast" (fastest and lightest), "browsa-smart" (for harder tasks). When you name a model, there is no hosted fallback.`
49
994
  },
50
995
  reasoning: REASONING_PROP,
51
996
  llm_key_id: {
@@ -58,7 +1003,7 @@ var tools = [
58
1003
  },
59
1004
  country: {
60
1005
  type: "string",
61
- description: `2-letter egress country (e.g. US, GB, DE). Default: ${DEFAULT_COUNTRY ?? "auto"}.`
1006
+ description: `2-letter egress country (e.g. US, GB, DE). Default: ${DEFAULT_COUNTRY2 ?? "auto"}.`
62
1007
  },
63
1008
  max_steps: { type: "integer", description: "Max agent steps. Default 25. Increase for complex multi-page tasks." },
64
1009
  initial_url: { type: "string", description: "Optional pre-navigation URL (saves the first agent step)." },
@@ -119,7 +1064,7 @@ var tools = [
119
1064
  },
120
1065
  {
121
1066
  name: "start_browser",
122
- description: "Start a real cloud browser and return its CDP URL, so you can drive it yourself with Playwright or Puppeteer (connect_over_cdp) instead of handing the work to run_task. Use this when you want to write the browser steps, or need the page open across several of your own tool calls. Billed per browser; always call stop_browser when you are done. Without a proxy the browser uses Browsa's data-center IP.",
1067
+ description: "Start a real cloud browser and return its CDP URL, so you can drive it yourself with any CDP client instead of handing the work to run_task (the core open, observe and act tools need no CDP). Use this when you want to write the browser steps, or need the page open across several of your own tool calls. Billed per browser; always call stop_browser when you are done. Without a proxy the browser uses Browsa's data-center IP.",
123
1068
  inputSchema: {
124
1069
  type: "object",
125
1070
  properties: {
@@ -161,57 +1106,6 @@ var tools = [
161
1106
  properties: { browser_id: { type: "string", description: "The id returned by start_browser." } }
162
1107
  }
163
1108
  },
164
- {
165
- name: "observe",
166
- description: 'Read the page of a browser started with start_browser, as compact text: one line per element, [id] role "name" state, inside a token budget. Use the ids with the act tool. No Playwright or CDP needed, and no extra charge. Ids stay valid across observe and act calls until the page loads a new document. On a full-page bot check nothing is read and the first lines say so.',
167
- inputSchema: {
168
- type: "object",
169
- required: ["browser_id"],
170
- properties: {
171
- browser_id: { type: "string", description: "The id returned by start_browser." },
172
- scope: { type: "string", enum: ["viewport", "page"], description: "viewport (default): what is in the viewport, the rest counted. page: the whole page." },
173
- budget: { type: "integer", description: "Approximate tokens for the view. Default 2000." },
174
- expand: { type: "integer", description: "Id of a container, table, list or select to list in full." },
175
- tab: { type: "string", description: "Tab id, from the tabs line of an earlier observe. Default: the tab used last." }
176
- }
177
- }
178
- },
179
- {
180
- name: "act",
181
- description: "Perform one action in a browser started with start_browser and get back what changed (~ changed, + added, - removed), or a new view after a navigation. Input is sent as real mouse and key events. Name the element by id from observe, or by role and name, or click a point with x and y. The first line of the answer says failed, blocked, challenge or stale when the action did not go through. stale: the ids are from a view that no longer exists, nothing was done, and a new view follows.",
182
- inputSchema: {
183
- type: "object",
184
- required: ["browser_id", "action"],
185
- properties: {
186
- browser_id: { type: "string", description: "The id returned by start_browser." },
187
- action: {
188
- type: "string",
189
- enum: ["click", "type", "press", "select", "check", "uncheck", "hover", "scroll", "navigate", "back", "forward", "reload", "wait", "upload", "dialog"]
190
- },
191
- id: { type: "integer", description: "Target element id, from observe." },
192
- role: { type: "string", description: "With name: the first element with this role and name, instead of id." },
193
- name: { type: "string" },
194
- x: { type: "number", description: "click: a viewport point instead of an element (with y)." },
195
- y: { type: "number" },
196
- text: { type: "string", description: "type: the text. wait for text: the text. dialog: the prompt answer." },
197
- clear: { type: "boolean", description: "type: empty the field first." },
198
- submit: { type: "boolean", description: "type: press Enter afterwards." },
199
- keys: { type: "string", description: 'press: Enter, Escape, Control+A, or a sequence such as "Tab Tab Enter".' },
200
- option: { type: "string", description: "select: option text or value." },
201
- double: { type: "boolean", description: "click: double click." },
202
- right: { type: "boolean", description: "click: right button." },
203
- dy: { type: "integer", description: "scroll: pixels, positive is down." },
204
- to: { type: "string", enum: ["top", "bottom"], description: "scroll." },
205
- url: { type: "string", description: "navigate." },
206
- ms: { type: "integer", description: "wait: a fixed time in milliseconds, at most 30000." },
207
- for: { type: "string", enum: ["text", "id-gone", "url-change"], description: "wait: for text to appear, an element to go, or the URL to change." },
208
- timeout: { type: "integer", description: "wait: milliseconds, default 10000, at most 30000." },
209
- files: { type: "array", items: { type: "string" }, description: "upload: file paths on the browser's machine." },
210
- accept: { type: "boolean", description: "dialog: accept (true) or dismiss." },
211
- tab: { type: "string", description: "Tab id. Default: the tab used last." }
212
- }
213
- }
214
- },
215
1109
  {
216
1110
  name: "list_browsers",
217
1111
  description: "List this workspace's browsers (burners and saved identities) with their status.",
@@ -254,7 +1148,7 @@ var tools = [
254
1148
  },
255
1149
  {
256
1150
  name: "list_identities",
257
- description: "List persistent browser identities (long-lived cookies/history/fingerprint, billed monthly). Use one in run_task via profile_id to reuse a warmed-up session \u2014 critical for sites that fingerprint cookie age, session continuity, or behavioral history (Akamai, Cloudflare-strict, DataDome).",
1151
+ description: "List persistent browser identities (long-lived cookies/history/fingerprint, billed monthly). Use one in run_task via profile_id (or open via profile) to reuse a warmed-up session: it matters on sites that check cookie age, session continuity or behavioral history.",
258
1152
  inputSchema: { type: "object", properties: {} }
259
1153
  },
260
1154
  {
@@ -306,9 +1200,59 @@ var tools = [
306
1200
  required: ["job_id"],
307
1201
  properties: { job_id: { type: "string", description: "The job id from run_task / create_task." } }
308
1202
  }
1203
+ },
1204
+ {
1205
+ name: "list_robots",
1206
+ description: "List this workspace's robots: saved browser jobs over a recorded recipe, each with its input rows, schedule, model/proxy/browser settings, health (pass rate, last failure) and last run. price_credits is what one successful row costs (the recipe's price, the same as the agent task); failed rows are free. Robots are made at https://app.browsa.io (Robots) or with the API.",
1207
+ inputSchema: {
1208
+ type: "object",
1209
+ properties: { limit: { type: "number", description: "At most this many robots (default 50)." } }
1210
+ }
1211
+ },
1212
+ {
1213
+ name: "run_robot",
1214
+ description: "Run a robot over all its input rows (or the rows you pass, for this run only). Replays the recorded recipe on Phantom with no model, so it is fast. Costs the robot's price_credits per successful row; failed rows are free. Returns the run; with wait_seconds it waits for the rows and returns them.",
1215
+ inputSchema: {
1216
+ type: "object",
1217
+ required: ["robot_id"],
1218
+ properties: {
1219
+ robot_id: { type: "string", description: "From list_robots." },
1220
+ inputs: {
1221
+ type: "array",
1222
+ items: { type: "object" },
1223
+ description: `Rows for this run only, e.g. [{"url": "https://..."}]. Omit to use the robot's saved rows.`
1224
+ },
1225
+ wait_seconds: { type: "number", description: "Wait up to this long for the run to finish (0 to 300, default 0)." }
1226
+ }
1227
+ }
1228
+ },
1229
+ {
1230
+ name: "get_robot_run",
1231
+ description: "Read one robot run: status (queued, running, completed, partial, failed), credits charged, and a row per input with its output, typed error (blocked, needs_login, site_changed, invalid_output, timeout) and the fields a monitor flagged as changed.",
1232
+ inputSchema: {
1233
+ type: "object",
1234
+ required: ["run_id"],
1235
+ properties: { run_id: { type: "string", description: "From run_robot or list_robots (last_run.id)." } }
1236
+ }
1237
+ },
1238
+ {
1239
+ name: "solve_captcha_task",
1240
+ description: "Solve one captcha through Browsa's captcha API (the common createTask / getTaskResult format) and return its solution: a token to submit with the site's form, the text in an image, or the grid tiles to click. Use it when code or a page outside a Browsa browser needs a captcha answer; inside run_task the browser solves captchas itself. Charged only when solved. Measured pass rates per type: https://browsa.io/captcha. Token tasks can take up to about 2 minutes.",
1241
+ inputSchema: {
1242
+ type: "object",
1243
+ required: ["task"],
1244
+ properties: {
1245
+ task: {
1246
+ type: "object",
1247
+ description: "The createTask task. `type` is one of: ImageToTextTask {body: base64 image} -> {text}; ReCaptchaV2Classification {image: base64, question: '/m/...' id or words} -> {objects}; ReCaptchaV2TaskProxyLess / ReCaptchaV2EnterpriseTaskProxyLess {websiteURL, websiteKey, isInvisible?} -> {gRecaptchaResponse}; ReCaptchaV3TaskProxyLess / ReCaptchaV3EnterpriseTaskProxyLess {websiteURL, websiteKey, pageAction?} -> {gRecaptchaResponse}; AntiTurnstileTaskProxyLess {websiteURL, websiteKey, metadata?: {action?, cdata?}} -> {token}. Without ProxyLess the task also needs proxy: 'http://user:pass@host:port'. Other services' names (RecaptchaV2TaskProxyless, TurnstileTaskProxyless) are accepted.",
1248
+ properties: { type: { type: "string" } },
1249
+ required: ["type"]
1250
+ },
1251
+ timeout_seconds: { type: "number", description: "How long to wait for the solution. Default 180, at most 600." }
1252
+ }
1253
+ }
309
1254
  }
310
1255
  ];
311
- server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools }));
312
1256
  function ok(payload) {
313
1257
  return {
314
1258
  content: [{ type: "text", text: typeof payload === "string" ? payload : JSON.stringify(payload, null, 2) }]
@@ -362,7 +1306,7 @@ function llmKeyError(e, choice) {
362
1306
  case "LLM_KEY_PROVIDER_MISMATCH":
363
1307
  return fail("The saved LLM key is for a different provider than llm. Omit llm to use the key's default model, or pick a matching model.", extra);
364
1308
  case "LLM_MODEL_REQUIRED":
365
- return fail("This saved key is an OpenAI-compatible key, so the model must be named: pass llm with the model id your endpoint serves.", extra);
1309
+ return fail("This saved key is for a compatible endpoint (openai_compatible), so the model must be named: pass llm with the model id your endpoint serves.", extra);
366
1310
  case "LLM_KEYS_UNAVAILABLE":
367
1311
  return fail(
368
1312
  `Saved LLM keys are not available on this Browsa server. Set BROWSA_LLM_API_KEY in the MCP env, pass llm_api_key, or pass llm:"browsa" to run on Browsa's hosted model.`,
@@ -372,9 +1316,8 @@ function llmKeyError(e, choice) {
372
1316
  return null;
373
1317
  }
374
1318
  async function proxyNetwork() {
375
- const base = (BASE_URL || "https://browsa.io").replace(/\/+$/, "");
376
- const resp = await fetch(`${base}/v1/proxy-network`, {
377
- headers: { "X-API-Key": API_KEY, Accept: "application/json", "User-Agent": "browsa-mcp/0.3.3" }
1319
+ const resp = await fetch(`${BASE_URL}/v1/proxy-network`, {
1320
+ headers: { "X-API-Key": API_KEY, Accept: "application/json", "User-Agent": "browsa-mcp" }
378
1321
  });
379
1322
  const body = await resp.json().catch(() => ({}));
380
1323
  if (resp.status === 404) return { enabled: false, tiers: [] };
@@ -396,55 +1339,6 @@ function proxyUsage(raw) {
396
1339
  if (!raw || typeof raw.proxy_network !== "string" || !raw.proxy_network) return {};
397
1340
  return { proxy_network: raw.proxy_network, proxy_bytes: raw.proxy_bytes ?? 0, proxy_credits: raw.proxy_credits ?? 0 };
398
1341
  }
399
- async function apiGet(path) {
400
- const base = (BASE_URL || "https://browsa.io").replace(/\/+$/, "");
401
- const resp = await fetch(`${base}${path}`, {
402
- headers: { "X-API-Key": API_KEY, Accept: "application/json", "User-Agent": "browsa-mcp/0.3.3" }
403
- });
404
- const body = await resp.json().catch(() => ({}));
405
- if (!resp.ok) {
406
- throw new BrowsaError(body?.error || `HTTP ${resp.status}`, { code: body?.code, requestId: body?.request_id, status: resp.status });
407
- }
408
- return body;
409
- }
410
- async function apiPost(path, payload, timeoutMs = 9e4) {
411
- const base = (BASE_URL || "https://browsa.io").replace(/\/+$/, "");
412
- const resp = await fetch(`${base}${path}`, {
413
- method: "POST",
414
- headers: {
415
- "X-API-Key": API_KEY,
416
- Accept: "application/json",
417
- "Content-Type": "application/json",
418
- "User-Agent": "browsa-mcp/0.3.3"
419
- },
420
- body: JSON.stringify(payload),
421
- signal: AbortSignal.timeout(timeoutMs)
422
- });
423
- const body = await resp.json().catch(() => ({}));
424
- if (!resp.ok) {
425
- throw new BrowsaError(body?.error || `HTTP ${resp.status}`, { code: body?.code, requestId: body?.request_id, status: resp.status });
426
- }
427
- return body;
428
- }
429
- var pageSessions = /* @__PURE__ */ new Map();
430
- async function pageCall(route, args) {
431
- const { browser_id, ...body } = args;
432
- const seen = pageSessions.get(browser_id);
433
- const session = seen ? seen.tabs.get(body.tab ?? seen.last) : void 0;
434
- if (session) body.session = session;
435
- const r = await apiPost(`/v1/agents/${encodeURIComponent(browser_id)}/${route}`, body);
436
- if (r?.tab && r?.session) {
437
- const next = seen ?? { last: "", tabs: /* @__PURE__ */ new Map() };
438
- next.last = r.tab;
439
- next.tabs.set(r.tab, r.session);
440
- pageSessions.set(browser_id, next);
441
- }
442
- let text = r?.text ?? "";
443
- if (Array.isArray(r?.tabs) && r.tabs.length > 1) {
444
- text += "\ntabs: " + r.tabs.map((t) => `${t.id} ${JSON.stringify(t.title || t.url || "")}${t.active ? " (this one)" : ""}`).join(" | ");
445
- }
446
- return text;
447
- }
448
1342
  async function listModels() {
449
1343
  const body = await apiGet("/v1/models");
450
1344
  return { hosted: body?.hosted ?? [], own_key: body?.own_key ?? {} };
@@ -481,13 +1375,134 @@ async function listLlmKeys() {
481
1375
  manage_at: LLM_KEYS_URL
482
1376
  };
483
1377
  }
484
- server.setRequestHandler(CallToolRequestSchema, async (req) => {
485
- const name = req.params.name;
486
- const args = req.params.arguments ?? {};
487
- let choice = null;
488
- if (!API_KEY) {
489
- return { content: [{ type: "text", text: NO_KEY_MESSAGE }], isError: true };
1378
+ var ROBOT_RUN_DONE = ["completed", "partial", "failed"];
1379
+ var ROBOT_POLL_MS = Number(process.env.BROWSA_ROBOT_POLL_MS) || 3e3;
1380
+ function robotSummary(r) {
1381
+ const h = r?.health ?? {};
1382
+ const s = r?.schedule;
1383
+ const lr = r?.last_run;
1384
+ return {
1385
+ id: r?.id,
1386
+ name: r?.name,
1387
+ status: r?.status,
1388
+ paused_reason: r?.paused_reason ?? null,
1389
+ recipe_id: r?.recipe_id ?? null,
1390
+ inputs_count: r?.inputs_count ?? (Array.isArray(r?.inputs) ? r.inputs.length : 0),
1391
+ price_credits: h.price_credits ?? null,
1392
+ pass_rate: h.pass_rate ?? null,
1393
+ last_failure: h.last_failure ?? null,
1394
+ schedule: s ? { interval_seconds: s.interval_seconds, at: s.at ?? null, tz: s.tz ?? null, next_run_at: s.next_run_at ?? null, enabled: s.enabled } : null,
1395
+ settings: r?.settings ?? { model: null, proxy: null, browser: null },
1396
+ alerts_unread: r?.alerts_unread ?? 0,
1397
+ last_run: lr ? { id: lr.id, status: lr.status, rows_ok: lr.rows_ok, rows_failed: lr.rows_failed, credits: lr.credits, finished_at: lr.finished_at ?? null } : null
1398
+ };
1399
+ }
1400
+ function robotRunView(run) {
1401
+ const out = {
1402
+ id: run?.id,
1403
+ robot_id: run?.robot_id,
1404
+ status: run?.status,
1405
+ trigger: run?.trigger,
1406
+ rows_total: run?.rows_total,
1407
+ rows_ok: run?.rows_ok,
1408
+ rows_failed: run?.rows_failed,
1409
+ rows_pending: run?.rows_pending,
1410
+ credits: run?.credits,
1411
+ stop_reason: run?.stop_reason ?? null,
1412
+ finished_at: run?.finished_at ?? null
1413
+ };
1414
+ if (Array.isArray(run?.rows)) {
1415
+ out.rows = run.rows.map((r) => ({
1416
+ row: r.row,
1417
+ input: r.input,
1418
+ status: r.status,
1419
+ output: r.output ?? null,
1420
+ ...r.error_code ? { error_code: r.error_code, error_message: r.error_message } : {},
1421
+ credits: r.credits,
1422
+ ...Array.isArray(r.changed_fields) && r.changed_fields.length ? { changed_fields: r.changed_fields } : {}
1423
+ }));
1424
+ }
1425
+ return out;
1426
+ }
1427
+ async function runRobot(args) {
1428
+ const id = String(args.robot_id || "");
1429
+ if (!id) return fail("robot_id is required");
1430
+ const body = {};
1431
+ if (Array.isArray(args.inputs)) body.inputs = args.inputs;
1432
+ let run = await apiPost(`/v1/robots/${encodeURIComponent(id)}/run`, body, 3e4);
1433
+ const waitMs = Math.min(Math.max(Number(args.wait_seconds) || 0, 0), 300) * 1e3;
1434
+ const deadline = Date.now() + waitMs;
1435
+ while (waitMs > 0 && !ROBOT_RUN_DONE.includes(run?.status) && Date.now() < deadline) {
1436
+ await new Promise((r) => setTimeout(r, Math.min(ROBOT_POLL_MS, Math.max(0, deadline - Date.now()))));
1437
+ run = await apiGet(`/v1/robot-runs/${encodeURIComponent(run.id)}`);
1438
+ }
1439
+ return ok(robotRunView(run));
1440
+ }
1441
+ var CAPTCHA_ALIASES = {
1442
+ recaptchav2taskproxyless: ["ReCaptchaV2TaskProxyLess", "ReCaptchaV2TaskProxyLess"],
1443
+ nocaptchataskproxyless: ["ReCaptchaV2TaskProxyLess", "ReCaptchaV2TaskProxyLess"],
1444
+ recaptchav2task: ["ReCaptchaV2TaskProxyLess", "ReCaptchaV2Task"],
1445
+ recaptchav2enterprisetaskproxyless: ["ReCaptchaV2EnterpriseTaskProxyLess", "ReCaptchaV2EnterpriseTaskProxyLess"],
1446
+ recaptchav2enterprisetask: ["ReCaptchaV2EnterpriseTaskProxyLess", "ReCaptchaV2EnterpriseTask"],
1447
+ recaptchav3taskproxyless: ["ReCaptchaV3TaskProxyLess", "ReCaptchaV3TaskProxyLess"],
1448
+ recaptchav3task: ["ReCaptchaV3TaskProxyLess", "ReCaptchaV3Task"],
1449
+ recaptchav3enterprisetaskproxyless: ["ReCaptchaV3EnterpriseTaskProxyLess", "ReCaptchaV3EnterpriseTaskProxyLess"],
1450
+ recaptchav3enterprisetask: ["ReCaptchaV3EnterpriseTaskProxyLess", "ReCaptchaV3EnterpriseTask"],
1451
+ turnstiletaskproxyless: ["AntiTurnstileTaskProxyLess", "AntiTurnstileTaskProxyLess"],
1452
+ antiturnstiletaskproxyless: ["AntiTurnstileTaskProxyLess", "AntiTurnstileTaskProxyLess"],
1453
+ turnstiletask: ["AntiTurnstileTaskProxyLess", "AntiTurnstileTask"],
1454
+ antiturnstiletask: ["AntiTurnstileTaskProxyLess", "AntiTurnstileTask"],
1455
+ imagetotexttask: ["ImageToTextTask", "ImageToTextTask"],
1456
+ recaptchav2classification: ["ReCaptchaV2Classification", "ReCaptchaV2Classification"]
1457
+ };
1458
+ async function captchaCall(method, payload) {
1459
+ const resp = await fetch(`${CAPTCHA_URL}/${method}`, {
1460
+ method: "POST",
1461
+ headers: { "Content-Type": "application/json", Accept: "application/json", "User-Agent": "browsa-mcp" },
1462
+ body: JSON.stringify({ clientKey: API_KEY, ...payload }),
1463
+ signal: AbortSignal.timeout(3e4)
1464
+ });
1465
+ const body = await resp.json().catch(() => null);
1466
+ if (!body || typeof body !== "object" || !("errorId" in body)) {
1467
+ throw new BrowsaError(`captcha API: unexpected answer (HTTP ${resp.status})`, { code: `HTTP_${resp.status}`, status: resp.status });
1468
+ }
1469
+ return body;
1470
+ }
1471
+ async function solveCaptchaTask(args) {
1472
+ const task = { ...args.task ?? {} };
1473
+ if (typeof task.type !== "string" || !task.type) return fail("task.type is required");
1474
+ const pair = CAPTCHA_ALIASES[task.type.toLowerCase()];
1475
+ if (pair) task.type = task.proxy || task.proxyAddress ? pair[1] : pair[0];
1476
+ const timeoutMs = Math.min(Math.max(Number(args.timeout_seconds) || 180, 5), 600) * 1e3;
1477
+ const failed = (b) => fail(b.errorDescription || b.errorCode, {
1478
+ code: b.errorCode,
1479
+ task_id: b.taskId,
1480
+ charged: false,
1481
+ ...b.errorCode === "ERROR_TASK_NOT_SUPPORTED" ? { measured_types: "https://browsa.io/captcha" } : {}
1482
+ });
1483
+ const created = await captchaCall("createTask", { task });
1484
+ if (created.errorId) return failed(created);
1485
+ const started = Date.now();
1486
+ if (created.status === "ready" && created.solution) {
1487
+ return ok({ task_id: created.taskId, type: task.type, solution: created.solution, seconds: 0 });
490
1488
  }
1489
+ const deadline = started + timeoutMs;
1490
+ while (Date.now() < deadline) {
1491
+ await new Promise((r2) => setTimeout(r2, Math.min(CAPTCHA_POLL_MS, Math.max(0, deadline - Date.now()))));
1492
+ const r = await captchaCall("getTaskResult", { taskId: created.taskId });
1493
+ if (r.errorId) return failed(r);
1494
+ if (r.status === "ready") {
1495
+ return ok({ task_id: created.taskId, type: task.type, solution: r.solution, seconds: Math.round((Date.now() - started) / 100) / 10 });
1496
+ }
1497
+ }
1498
+ return fail(
1499
+ `no solution after ${Math.round(timeoutMs / 1e3)}s; the task may still finish (charged only if solved)`,
1500
+ { code: "TIMEOUT", task_id: created.taskId }
1501
+ );
1502
+ }
1503
+ var CAPTCHA_POLL_MS = Number(process.env.BROWSA_CAPTCHA_POLL_MS) || 3e3;
1504
+ async function callLegacy(name, args) {
1505
+ let choice = null;
491
1506
  try {
492
1507
  switch (name) {
493
1508
  case "run_task": {
@@ -501,7 +1516,7 @@ server.setRequestHandler(CallToolRequestSchema, async (req) => {
501
1516
  llmApiKey: c.llmApiKey,
502
1517
  llmKeyId: c.llmKeyId,
503
1518
  reasoning: args.reasoning,
504
- country: args.country ?? DEFAULT_COUNTRY,
1519
+ country: args.country ?? DEFAULT_COUNTRY2,
505
1520
  maxSteps: args.max_steps,
506
1521
  initialUrl: args.initial_url,
507
1522
  ja3Profile: args.ja3_profile,
@@ -553,7 +1568,7 @@ server.setRequestHandler(CallToolRequestSchema, async (req) => {
553
1568
  case "start_browser": {
554
1569
  const a = await client.createAgent({
555
1570
  ttl: args.ttl ?? "10m",
556
- country: args.country ?? DEFAULT_COUNTRY,
1571
+ country: args.country ?? DEFAULT_COUNTRY2,
557
1572
  osType: args.os_type,
558
1573
  agent_id: args.profile_id,
559
1574
  proxy: args.proxy
@@ -561,8 +1576,8 @@ server.setRequestHandler(CallToolRequestSchema, async (req) => {
561
1576
  return ok({
562
1577
  browser_id: a.id,
563
1578
  status: a.status,
564
- // Connect with playwright.chromium.connect_over_cdp(cdp_http,
565
- // headers={"X-API-Key": <your key>}); cdp_url is the page socket.
1579
+ // Connect a CDP client to cdp_http with the header
1580
+ // X-API-Key: <your key>; cdp_url is the page socket.
566
1581
  cdp_http: a.cdp_http,
567
1582
  cdp_url: a.cdp_url,
568
1583
  live_url: a.live_url,
@@ -576,10 +1591,6 @@ server.setRequestHandler(CallToolRequestSchema, async (req) => {
576
1591
  case "stop_browser":
577
1592
  await client.destroyAgent(args.browser_id);
578
1593
  return ok({ stopped: args.browser_id });
579
- case "observe":
580
- return ok(await pageCall("observe", args));
581
- case "act":
582
- return ok(await pageCall("act", args));
583
1594
  case "list_browsers":
584
1595
  return ok(await client.listIdentities());
585
1596
  case "credits":
@@ -605,7 +1616,7 @@ server.setRequestHandler(CallToolRequestSchema, async (req) => {
605
1616
  llmKeyId: c.llmKeyId,
606
1617
  reasoning: args.reasoning,
607
1618
  intervalSeconds: args.interval_seconds,
608
- country: args.country ?? DEFAULT_COUNTRY,
1619
+ country: args.country ?? DEFAULT_COUNTRY2,
609
1620
  maxSteps: args.max_steps,
610
1621
  initialUrl: args.initial_url
611
1622
  })
@@ -642,6 +1653,18 @@ server.setRequestHandler(CallToolRequestSchema, async (req) => {
642
1653
  return ok(await proxyNetwork());
643
1654
  case "list_models":
644
1655
  return ok(await listModels());
1656
+ case "list_robots": {
1657
+ const lim = Number(args.limit) > 0 ? `?limit=${Math.floor(Number(args.limit))}` : "";
1658
+ const body = await apiGet(`/v1/robots${lim}`);
1659
+ return ok({ robots: (body?.robots ?? []).map(robotSummary) });
1660
+ }
1661
+ case "run_robot":
1662
+ return await runRobot(args);
1663
+ case "get_robot_run":
1664
+ if (!args.run_id) return fail("run_id is required");
1665
+ return ok(robotRunView(await apiGet(`/v1/robot-runs/${encodeURIComponent(String(args.run_id))}`)));
1666
+ case "solve_captcha_task":
1667
+ return await solveCaptchaTask(args);
645
1668
  default:
646
1669
  return fail(`unknown tool: ${name}`);
647
1670
  }
@@ -657,11 +1680,70 @@ server.setRequestHandler(CallToolRequestSchema, async (req) => {
657
1680
  }
658
1681
  return fail(e.message || String(e));
659
1682
  }
1683
+ }
1684
+
1685
+ // src/redact.ts
1686
+ var SENSITIVE = /^(?:.*[_.-])?(?:token|access_?token|refresh_?token|id_?token|auth|authorization|key|api_?key|apikey|secret|client_?secret|password|passwd|pwd|pass|session|session_?id|sessionid|sid|jsessionid|phpsessid|code|otp|ticket|signature|sig|credential|jwt|assertion|saml_?response|nonce)(?:[_.-].*)?$/i;
1687
+ var SAFE = /* @__PURE__ */ new Set(["country_code", "countrycode", "zip_code", "zipcode", "postal_code", "postcode", "currency_code", "lang_code", "keyword", "keywords", "keys", "token_type", "key_type"]);
1688
+ function isSensitiveParam(name) {
1689
+ const n = name.toLowerCase();
1690
+ if (SAFE.has(n)) return false;
1691
+ return SENSITIVE.test(n);
1692
+ }
1693
+ var PARAM = /([?&#;])([A-Za-z0-9_.\-[\]%]{1,64})=([^&#;\s"'<>\\)\]]+)/g;
1694
+ function redactUrls(text) {
1695
+ if (!text || text.indexOf("=") < 0) return text;
1696
+ return text.replace(PARAM, (all, sep, name, value) => {
1697
+ let decoded = name;
1698
+ try {
1699
+ decoded = decodeURIComponent(name);
1700
+ } catch {
1701
+ }
1702
+ if (!isSensitiveParam(decoded.replace(/\[\]$/, ""))) return all;
1703
+ if (value === "***") return all;
1704
+ return `${sep}${name}=***`;
1705
+ });
1706
+ }
1707
+
1708
+ // src/server.ts
1709
+ if (!API_KEY) {
1710
+ console.error("[browsa-mcp] BROWSA_API_KEY is not set: tools are listed, but every call will fail until it is.");
1711
+ console.error(` Mint one at ${KEYS_URL}`);
1712
+ }
1713
+ var extras = enabledExtras();
1714
+ for (const w of extras.unknown) {
1715
+ console.error(`[browsa-mcp] BROWSA_MCP_TOOLS: unknown group or tool "${w}" (groups: ${Object.keys(GROUPS).join(", ")}, all)`);
1716
+ }
1717
+ var tools = [...coreTools, ...legacyTools.filter((t) => extras.tools.has(t.name))];
1718
+ var listed = new Set(tools.map((t) => t.name));
1719
+ var server = new Server({ name: "browsa", version: VERSION }, { capabilities: { tools: {} } });
1720
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools }));
1721
+ var clean = (s) => REDACT ? redactUrls(s) : s;
1722
+ server.setRequestHandler(CallToolRequestSchema, async (req) => {
1723
+ const name = req.params.name;
1724
+ const args = req.params.arguments ?? {};
1725
+ if (!listed.has(name)) {
1726
+ const group = Object.entries(GROUPS).find(([, t]) => t.includes(name))?.[0];
1727
+ const text = group ? `error: ${name} is in the optional group "${group}"
1728
+ next: set BROWSA_MCP_TOOLS=${group} (or all) in this server's env and restart it` : `error: unknown tool ${name}`;
1729
+ return { isError: true, content: [{ type: "text", text }] };
1730
+ }
1731
+ if (!API_KEY) return { isError: true, content: [{ type: "text", text: NO_KEY_MESSAGE }] };
1732
+ if (CORE_TOOLS.includes(name)) {
1733
+ const r2 = await callCore(name, args);
1734
+ const content = [];
1735
+ if (r2.image) content.push({ type: "image", data: r2.image.data, mimeType: r2.image.mime });
1736
+ content.push({ type: "text", text: clean(r2.text) });
1737
+ return { ...r2.isError ? { isError: true } : {}, content };
1738
+ }
1739
+ const r = await callLegacy(name, args);
1740
+ for (const c of r.content ?? []) if (c.type === "text") c.text = clean(c.text);
1741
+ return r;
660
1742
  });
661
1743
  async function main() {
662
1744
  const transport = new StdioServerTransport();
663
1745
  await server.connect(transport);
664
- console.error("[browsa-mcp] ready (tools=" + tools.length + ")");
1746
+ console.error(`[browsa-mcp] ${VERSION} ready (tools=${tools.length})`);
665
1747
  }
666
1748
  main().catch((e) => {
667
1749
  console.error("[browsa-mcp] fatal:", e);