@browsa/mcp 0.5.0 → 0.7.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 -89
  2. package/dist/server.js +1160 -160
  3. package/package.json +2 -2
package/dist/server.js CHANGED
@@ -3,40 +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";
11
- var VERSION = "0.5.0";
6
+ import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
7
+
8
+ // src/config.ts
9
+ var VERSION = "0.7.0";
12
10
  var API_KEY = process.env.BROWSA_API_KEY;
13
- var BASE_URL = process.env.BROWSA_BASE_URL;
14
- var CAPTCHA_URL = (process.env.BROWSA_CAPTCHA_URL || (BASE_URL ? `${BASE_URL.replace(/\/+$/, "")}/captcha-api` : "https://captcha.browsa.io")).replace(/\/+$/, "");
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", "list_captcha_types", "report_captcha_result"],
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(/\/+$/, "");
15
967
  var DEFAULT_LLM = process.env.BROWSA_LLM || void 0;
16
968
  var BYOK_DEFAULT_LLM = "claude-opus-5-5";
17
969
  var DEFAULT_LLM_KEY = process.env.BROWSA_LLM_API_KEY || void 0;
18
970
  var DEFAULT_LLM_KEY_ID = process.env.BROWSA_LLM_KEY_ID || void 0;
19
- var DEFAULT_COUNTRY = process.env.BROWSA_COUNTRY;
971
+ var DEFAULT_COUNTRY2 = process.env.BROWSA_COUNTRY;
20
972
  var LLM_KEYS_URL = "https://app.browsa.io/dashboard/llm-keys";
21
- 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.";
22
- if (!API_KEY) {
23
- console.error("[browsa-mcp] BROWSA_API_KEY is not set: tools are listed, but every call will fail until it is.");
24
- console.error(" Mint one at https://app.browsa.io/dashboard/keys");
25
- }
26
- var client = API_KEY ? new Client({ apiKey: API_KEY, ...BASE_URL ? { baseUrl: BASE_URL } : {} }) : null;
27
- var server = new Server(
28
- { name: "browsa", version: VERSION },
29
- { capabilities: { tools: {} } }
30
- );
973
+ var client = API_KEY ? new Client({ apiKey: API_KEY, ...BASE_URL_SET ? { baseUrl: BASE_URL } : {} }) : null;
31
974
  var REASONING_PROP = {
32
975
  type: "string",
33
976
  enum: ["low", "medium", "high"],
34
977
  description: "How much the model reasons. Omit for the tier's or the provider's default."
35
978
  };
36
- var tools = [
979
+ var legacyTools = [
37
980
  {
38
981
  name: "run_task",
39
- 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.",
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. When the run creates a login (a signup), the result may list it in `saved_secrets` (saved as a workspace secret, never the value).",
40
983
  inputSchema: {
41
984
  type: "object",
42
985
  required: ["task"],
@@ -47,7 +990,7 @@ var tools = [
47
990
  },
48
991
  llm: {
49
992
  type: "string",
50
- 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.`
51
994
  },
52
995
  reasoning: REASONING_PROP,
53
996
  llm_key_id: {
@@ -60,7 +1003,7 @@ var tools = [
60
1003
  },
61
1004
  country: {
62
1005
  type: "string",
63
- 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"}.`
64
1007
  },
65
1008
  max_steps: { type: "integer", description: "Max agent steps. Default 25. Increase for complex multi-page tasks." },
66
1009
  initial_url: { type: "string", description: "Optional pre-navigation URL (saves the first agent step)." },
@@ -72,6 +1015,16 @@ var tools = [
72
1015
  type: "string",
73
1016
  description: "Id of a persistent identity (agt_..., from list_identities). If set, reuses that browser identity (cookies, history, fingerprint stay sticky). Omit for a fresh burner."
74
1017
  },
1018
+ secret_ids: {
1019
+ type: "array",
1020
+ items: { type: "string" },
1021
+ maxItems: 20,
1022
+ description: "Names or ids of workspace secrets the task may type; refer to them in the task as secrets.NAME (or secrets.NAME.username, .password, .totp)."
1023
+ },
1024
+ save_secrets: {
1025
+ type: "boolean",
1026
+ description: "Set false to stop the run from saving a login it creates as a workspace secret (on by default)."
1027
+ },
75
1028
  timeout_minutes: {
76
1029
  type: "integer",
77
1030
  description: "Max wall-clock minutes to wait before returning. Default 10.",
@@ -121,7 +1074,7 @@ var tools = [
121
1074
  },
122
1075
  {
123
1076
  name: "start_browser",
124
- 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.",
1077
+ 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.",
125
1078
  inputSchema: {
126
1079
  type: "object",
127
1080
  properties: {
@@ -163,57 +1116,6 @@ var tools = [
163
1116
  properties: { browser_id: { type: "string", description: "The id returned by start_browser." } }
164
1117
  }
165
1118
  },
166
- {
167
- name: "observe",
168
- 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.',
169
- inputSchema: {
170
- type: "object",
171
- required: ["browser_id"],
172
- properties: {
173
- browser_id: { type: "string", description: "The id returned by start_browser." },
174
- scope: { type: "string", enum: ["viewport", "page"], description: "viewport (default): what is in the viewport, the rest counted. page: the whole page." },
175
- budget: { type: "integer", description: "Approximate tokens for the view. Default 2000." },
176
- expand: { type: "integer", description: "Id of a container, table, list or select to list in full." },
177
- tab: { type: "string", description: "Tab id, from the tabs line of an earlier observe. Default: the tab used last." }
178
- }
179
- }
180
- },
181
- {
182
- name: "act",
183
- 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.",
184
- inputSchema: {
185
- type: "object",
186
- required: ["browser_id", "action"],
187
- properties: {
188
- browser_id: { type: "string", description: "The id returned by start_browser." },
189
- action: {
190
- type: "string",
191
- enum: ["click", "type", "press", "select", "check", "uncheck", "hover", "scroll", "navigate", "back", "forward", "reload", "wait", "upload", "dialog"]
192
- },
193
- id: { type: "integer", description: "Target element id, from observe." },
194
- role: { type: "string", description: "With name: the first element with this role and name, instead of id." },
195
- name: { type: "string" },
196
- x: { type: "number", description: "click: a viewport point instead of an element (with y)." },
197
- y: { type: "number" },
198
- text: { type: "string", description: "type: the text. wait for text: the text. dialog: the prompt answer." },
199
- clear: { type: "boolean", description: "type: empty the field first." },
200
- submit: { type: "boolean", description: "type: press Enter afterwards." },
201
- keys: { type: "string", description: 'press: Enter, Escape, Control+A, or a sequence such as "Tab Tab Enter".' },
202
- option: { type: "string", description: "select: option text or value." },
203
- double: { type: "boolean", description: "click: double click." },
204
- right: { type: "boolean", description: "click: right button." },
205
- dy: { type: "integer", description: "scroll: pixels, positive is down." },
206
- to: { type: "string", enum: ["top", "bottom"], description: "scroll." },
207
- url: { type: "string", description: "navigate." },
208
- ms: { type: "integer", description: "wait: a fixed time in milliseconds, at most 30000." },
209
- for: { type: "string", enum: ["text", "id-gone", "url-change"], description: "wait: for text to appear, an element to go, or the URL to change." },
210
- timeout: { type: "integer", description: "wait: milliseconds, default 10000, at most 30000." },
211
- files: { type: "array", items: { type: "string" }, description: "upload: file paths on the browser's machine." },
212
- accept: { type: "boolean", description: "dialog: accept (true) or dismiss." },
213
- tab: { type: "string", description: "Tab id. Default: the tab used last." }
214
- }
215
- }
216
- },
217
1119
  {
218
1120
  name: "list_browsers",
219
1121
  description: "List this workspace's browsers (burners and saved identities) with their status.",
@@ -256,7 +1158,7 @@ var tools = [
256
1158
  },
257
1159
  {
258
1160
  name: "list_identities",
259
- 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).",
1161
+ 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.",
260
1162
  inputSchema: { type: "object", properties: {} }
261
1163
  },
262
1164
  {
@@ -345,7 +1247,7 @@ var tools = [
345
1247
  },
346
1248
  {
347
1249
  name: "solve_captcha_task",
348
- description: "Solve one captcha through Browsa's captcha API (createTask / getTaskResult, the format CapSolver, Anti-Captcha and CapMonster share) 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.",
1250
+ 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.",
349
1251
  inputSchema: {
350
1252
  type: "object",
351
1253
  required: ["task"],
@@ -359,9 +1261,31 @@ var tools = [
359
1261
  timeout_seconds: { type: "number", description: "How long to wait for the solution. Default 180, at most 600." }
360
1262
  }
361
1263
  }
1264
+ },
1265
+ {
1266
+ name: "list_captcha_types",
1267
+ description: "List the captcha task types Browsa's captcha API accepts: whether each is live or off, its required and optional parameters, its price per solve and, where measured, its pass rate with the date of the run. Call it before solve_captcha_task when unsure of a type name or of a parameter: names are case-sensitive. Uses no credits.",
1268
+ inputSchema: {
1269
+ type: "object",
1270
+ properties: {
1271
+ type: { type: "string", description: "Only this type, with the description of every parameter." },
1272
+ live_only: { type: "boolean", description: "Leave out the types that are switched off." }
1273
+ }
1274
+ }
1275
+ },
1276
+ {
1277
+ name: "report_captcha_result",
1278
+ description: "Tell Browsa whether the site accepted a solution from solve_captcha_task: correct=true records that it worked, correct=false that the site refused it. Reports are recorded and used to improve solving. A task can be reported once, within 15 minutes of the solve. Report only what the site itself answered.",
1279
+ inputSchema: {
1280
+ type: "object",
1281
+ required: ["task_id", "correct"],
1282
+ properties: {
1283
+ task_id: { type: "string", description: "task_id from solve_captcha_task." },
1284
+ correct: { type: "boolean", description: "true when the site accepted the solution, false when it refused it." }
1285
+ }
1286
+ }
362
1287
  }
363
1288
  ];
364
- server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools }));
365
1289
  function ok(payload) {
366
1290
  return {
367
1291
  content: [{ type: "text", text: typeof payload === "string" ? payload : JSON.stringify(payload, null, 2) }]
@@ -415,7 +1339,7 @@ function llmKeyError(e, choice) {
415
1339
  case "LLM_KEY_PROVIDER_MISMATCH":
416
1340
  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);
417
1341
  case "LLM_MODEL_REQUIRED":
418
- 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);
1342
+ 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);
419
1343
  case "LLM_KEYS_UNAVAILABLE":
420
1344
  return fail(
421
1345
  `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.`,
@@ -425,9 +1349,8 @@ function llmKeyError(e, choice) {
425
1349
  return null;
426
1350
  }
427
1351
  async function proxyNetwork() {
428
- const base = (BASE_URL || "https://browsa.io").replace(/\/+$/, "");
429
- const resp = await fetch(`${base}/v1/proxy-network`, {
430
- headers: { "X-API-Key": API_KEY, Accept: "application/json", "User-Agent": `browsa-mcp/${VERSION}` }
1352
+ const resp = await fetch(`${BASE_URL}/v1/proxy-network`, {
1353
+ headers: { "X-API-Key": API_KEY, Accept: "application/json", "User-Agent": "browsa-mcp" }
431
1354
  });
432
1355
  const body = await resp.json().catch(() => ({}));
433
1356
  if (resp.status === 404) return { enabled: false, tiers: [] };
@@ -449,55 +1372,6 @@ function proxyUsage(raw) {
449
1372
  if (!raw || typeof raw.proxy_network !== "string" || !raw.proxy_network) return {};
450
1373
  return { proxy_network: raw.proxy_network, proxy_bytes: raw.proxy_bytes ?? 0, proxy_credits: raw.proxy_credits ?? 0 };
451
1374
  }
452
- async function apiGet(path) {
453
- const base = (BASE_URL || "https://browsa.io").replace(/\/+$/, "");
454
- const resp = await fetch(`${base}${path}`, {
455
- headers: { "X-API-Key": API_KEY, Accept: "application/json", "User-Agent": `browsa-mcp/${VERSION}` }
456
- });
457
- const body = await resp.json().catch(() => ({}));
458
- if (!resp.ok) {
459
- throw new BrowsaError(body?.error || `HTTP ${resp.status}`, { code: body?.code, requestId: body?.request_id, status: resp.status });
460
- }
461
- return body;
462
- }
463
- async function apiPost(path, payload, timeoutMs = 9e4) {
464
- const base = (BASE_URL || "https://browsa.io").replace(/\/+$/, "");
465
- const resp = await fetch(`${base}${path}`, {
466
- method: "POST",
467
- headers: {
468
- "X-API-Key": API_KEY,
469
- Accept: "application/json",
470
- "Content-Type": "application/json",
471
- "User-Agent": `browsa-mcp/${VERSION}`
472
- },
473
- body: JSON.stringify(payload),
474
- signal: AbortSignal.timeout(timeoutMs)
475
- });
476
- const body = await resp.json().catch(() => ({}));
477
- if (!resp.ok) {
478
- throw new BrowsaError(body?.error || `HTTP ${resp.status}`, { code: body?.code, requestId: body?.request_id, status: resp.status });
479
- }
480
- return body;
481
- }
482
- var pageSessions = /* @__PURE__ */ new Map();
483
- async function pageCall(route, args) {
484
- const { browser_id, ...body } = args;
485
- const seen = pageSessions.get(browser_id);
486
- const session = seen ? seen.tabs.get(body.tab ?? seen.last) : void 0;
487
- if (session) body.session = session;
488
- const r = await apiPost(`/v1/agents/${encodeURIComponent(browser_id)}/${route}`, body);
489
- if (r?.tab && r?.session) {
490
- const next = seen ?? { last: "", tabs: /* @__PURE__ */ new Map() };
491
- next.last = r.tab;
492
- next.tabs.set(r.tab, r.session);
493
- pageSessions.set(browser_id, next);
494
- }
495
- let text = r?.text ?? "";
496
- if (Array.isArray(r?.tabs) && r.tabs.length > 1) {
497
- text += "\ntabs: " + r.tabs.map((t) => `${t.id} ${JSON.stringify(t.title || t.url || "")}${t.active ? " (this one)" : ""}`).join(" | ");
498
- }
499
- return text;
500
- }
501
1375
  async function listModels() {
502
1376
  const body = await apiGet("/v1/models");
503
1377
  return { hosted: body?.hosted ?? [], own_key: body?.own_key ?? {} };
@@ -514,6 +1388,23 @@ function llmResultFields(job) {
514
1388
  if (!r || typeof r !== "object") return {};
515
1389
  return { llm_tier: r.llm_tier, reasoning: r.reasoning, usage: r.usage, llm_cost_usd: r.llm_cost_usd };
516
1390
  }
1391
+ function savedSecretFields(job) {
1392
+ const r = job.raw?.result;
1393
+ if (!r || typeof r !== "object") return {};
1394
+ const saved = Array.isArray(r.saved_secrets) ? r.saved_secrets.filter((s) => s && typeof s === "object").map((s) => ({
1395
+ name: s.name,
1396
+ id: s.id,
1397
+ type: s.type,
1398
+ origins: s.origins,
1399
+ ...s.username_masked ? { username_masked: s.username_masked } : {},
1400
+ existing: s.existing === true
1401
+ })) : [];
1402
+ const notSaved = r.secrets_not_saved && typeof r.secrets_not_saved === "object" && r.secrets_not_saved.code ? { code: r.secrets_not_saved.code, message: r.secrets_not_saved.message } : void 0;
1403
+ return {
1404
+ ...saved.length ? { saved_secrets: saved } : {},
1405
+ ...notSaved ? { secrets_not_saved: notSaved } : {}
1406
+ };
1407
+ }
517
1408
  async function listLlmKeys() {
518
1409
  const body = await apiGet("/v1/llm-keys");
519
1410
  return {
@@ -615,9 +1506,9 @@ var CAPTCHA_ALIASES = {
615
1506
  recaptchav2classification: ["ReCaptchaV2Classification", "ReCaptchaV2Classification"]
616
1507
  };
617
1508
  async function captchaCall(method, payload) {
618
- const resp = await fetch(`${CAPTCHA_URL}/${method}`, {
1509
+ const resp = await fetch(`${CAPTCHA_URL}/${method}`, payload === null ? { method: "GET", headers: { Accept: "application/json", "User-Agent": "browsa-mcp" }, signal: AbortSignal.timeout(3e4) } : {
619
1510
  method: "POST",
620
- headers: { "Content-Type": "application/json", Accept: "application/json", "User-Agent": `browsa-mcp/${VERSION}` },
1511
+ headers: { "Content-Type": "application/json", Accept: "application/json", "User-Agent": "browsa-mcp" },
621
1512
  body: JSON.stringify({ clientKey: API_KEY, ...payload }),
622
1513
  signal: AbortSignal.timeout(3e4)
623
1514
  });
@@ -636,22 +1527,33 @@ async function solveCaptchaTask(args) {
636
1527
  const failed = (b) => fail(b.errorDescription || b.errorCode, {
637
1528
  code: b.errorCode,
638
1529
  task_id: b.taskId,
639
- charged: false,
640
- ...b.errorCode === "ERROR_TASK_NOT_SUPPORTED" ? { measured_types: "https://browsa.io/captcha" } : {}
1530
+ charged: b.charged === true,
1531
+ ...b.fix ? { fix: b.fix } : {},
1532
+ ...b.errorCode === "ERROR_TASK_NOT_SUPPORTED" ? { measured_types: "https://browsa.io/captcha", next: "call list_captcha_types for the type names and their parameters" } : {}
641
1533
  });
642
- const created = await captchaCall("createTask", { task });
643
- if (created.errorId) return failed(created);
644
1534
  const started = Date.now();
645
- if (created.status === "ready" && created.solution) {
646
- return ok({ task_id: created.taskId, type: task.type, solution: created.solution, seconds: 0 });
647
- }
648
1535
  const deadline = started + timeoutMs;
1536
+ const hold = () => Math.max(0, Math.min(CAPTCHA_WAIT_S, Math.floor((deadline - Date.now()) / 1e3)));
1537
+ const solved = (b) => ok({
1538
+ task_id: created.taskId,
1539
+ type: task.type,
1540
+ solution: b.solution,
1541
+ seconds: typeof b.solveSeconds === "number" ? b.solveSeconds : Math.round((Date.now() - started) / 100) / 10,
1542
+ ...b.cost ? { cost: b.cost } : {},
1543
+ next: "when the site has answered, call report_captcha_result with correct=true or correct=false"
1544
+ });
1545
+ const created = await captchaCall("createTask", { task, ...hold() ? { waitSeconds: hold() } : {} });
1546
+ if (created.errorId) return failed(created);
1547
+ if (created.status === "ready" && created.solution) return solved(created);
649
1548
  while (Date.now() < deadline) {
650
- await new Promise((r2) => setTimeout(r2, Math.min(CAPTCHA_POLL_MS, Math.max(0, deadline - Date.now()))));
651
- const r = await captchaCall("getTaskResult", { taskId: created.taskId });
1549
+ const wait = hold();
1550
+ if (!wait) await new Promise((r2) => setTimeout(r2, Math.min(CAPTCHA_POLL_MS, Math.max(0, deadline - Date.now()))));
1551
+ const asked = Date.now();
1552
+ const r = await captchaCall("getTaskResult", { taskId: created.taskId, ...wait ? { waitSeconds: wait } : {} });
652
1553
  if (r.errorId) return failed(r);
653
- if (r.status === "ready") {
654
- return ok({ task_id: created.taskId, type: task.type, solution: r.solution, seconds: Math.round((Date.now() - started) / 100) / 10 });
1554
+ if (r.status === "ready") return solved(r);
1555
+ if (wait && Date.now() - asked < 1e3) {
1556
+ await new Promise((res) => setTimeout(res, Math.min(CAPTCHA_POLL_MS, Math.max(0, deadline - Date.now()))));
655
1557
  }
656
1558
  }
657
1559
  return fail(
@@ -660,13 +1562,47 @@ async function solveCaptchaTask(args) {
660
1562
  );
661
1563
  }
662
1564
  var CAPTCHA_POLL_MS = Number(process.env.BROWSA_CAPTCHA_POLL_MS) || 3e3;
663
- server.setRequestHandler(CallToolRequestSchema, async (req) => {
664
- const name = req.params.name;
665
- const args = req.params.arguments ?? {};
666
- let choice = null;
667
- if (!API_KEY) {
668
- return { content: [{ type: "text", text: NO_KEY_MESSAGE }], isError: true };
1565
+ var CAPTCHA_WAIT_S = 20;
1566
+ async function listCaptchaTypes(args) {
1567
+ const r = await captchaCall("types", null);
1568
+ if (r.errorId || !Array.isArray(r.types)) return fail(r.errorDescription || "the type catalogue is not available", { code: r.errorCode });
1569
+ const names = (ps) => (ps ?? []).map((p) => p.name);
1570
+ const measured = (t) => (t.measured ?? []).map((m) => ({ what: m.name, passes: `${m.passes} of ${m.attempts}`, median_seconds: m.medianSeconds, measured_on: m.measuredOn, exit: m.exit }));
1571
+ if (typeof args.type === "string" && args.type) {
1572
+ const want = args.type.toLowerCase();
1573
+ const t = r.types.find((x) => String(x.type).toLowerCase() === want);
1574
+ if (!t) return fail(`no type named ${args.type}`, { types: r.types.map((x) => x.type) });
1575
+ return ok({ ...t, measured: measured(t) });
669
1576
  }
1577
+ const types = r.types.filter((t) => !args.live_only || t.status === "live").map((t) => ({
1578
+ type: t.type,
1579
+ what: t.summary,
1580
+ status: t.status,
1581
+ ...t.offReason ? { off_reason: t.offReason } : {},
1582
+ required: [...names(t.required), ...(t.requiredOneOf ?? []).map((g) => names(g).join(" or "))],
1583
+ optional: names(t.optional),
1584
+ proxy: t.proxy,
1585
+ credits_per_solve: t.price?.creditsPerSolve,
1586
+ measured: measured(t)
1587
+ }));
1588
+ return ok({ types, note: "Names are case-sensitive. A failed solve is not charged. Pass `type` for one type's parameter descriptions." });
1589
+ }
1590
+ async function reportCaptchaResult(args) {
1591
+ if (typeof args.task_id !== "string" || !args.task_id) return fail("task_id is required");
1592
+ if (typeof args.correct !== "boolean") return fail("correct must be true or false");
1593
+ const r = await captchaCall(args.correct ? "reportCorrect" : "reportIncorrect", { taskId: args.task_id });
1594
+ if (r.errorId) {
1595
+ return fail(r.errorDescription || r.errorCode, {
1596
+ code: r.errorCode,
1597
+ task_id: args.task_id,
1598
+ ...r.fix ? { fix: r.fix } : {},
1599
+ ...typeof r.refunded === "boolean" ? { refunded: r.refunded } : {}
1600
+ });
1601
+ }
1602
+ return ok({ task_id: args.task_id, outcome: r.outcome, refunded: r.refunded === true, refund: r.refund, message: r.message });
1603
+ }
1604
+ async function callLegacy(name, args) {
1605
+ let choice = null;
670
1606
  try {
671
1607
  switch (name) {
672
1608
  case "run_task": {
@@ -680,11 +1616,14 @@ server.setRequestHandler(CallToolRequestSchema, async (req) => {
680
1616
  llmApiKey: c.llmApiKey,
681
1617
  llmKeyId: c.llmKeyId,
682
1618
  reasoning: args.reasoning,
683
- country: args.country ?? DEFAULT_COUNTRY,
1619
+ country: args.country ?? DEFAULT_COUNTRY2,
684
1620
  maxSteps: args.max_steps,
685
1621
  initialUrl: args.initial_url,
686
1622
  ja3Profile: args.ja3_profile,
687
1623
  profileId: args.profile_id,
1624
+ // Sent as is (snake_case) and only when given.
1625
+ secret_ids: Array.isArray(args.secret_ids) && args.secret_ids.length ? args.secret_ids : void 0,
1626
+ save_secrets: typeof args.save_secrets === "boolean" ? args.save_secrets : void 0,
688
1627
  timeoutMs: (args.timeout_minutes ?? 10) * 6e4
689
1628
  })
690
1629
  );
@@ -700,6 +1639,7 @@ server.setRequestHandler(CallToolRequestSchema, async (req) => {
700
1639
  llm_key_masked: job.raw?.llm_key_masked,
701
1640
  llm_key_source: job.raw?.llm_key_source,
702
1641
  ...llmResultFields(job),
1642
+ ...savedSecretFields(job),
703
1643
  final_result: job.finalResult,
704
1644
  error: job.errorMessage,
705
1645
  error_code: job.errorCode
@@ -715,6 +1655,7 @@ server.setRequestHandler(CallToolRequestSchema, async (req) => {
715
1655
  live_url: job.liveUrl,
716
1656
  input_question: job.inputQuestion,
717
1657
  ...llmResultFields(job),
1658
+ ...savedSecretFields(job),
718
1659
  final_result: job.finalResult,
719
1660
  error: job.errorMessage,
720
1661
  error_code: job.errorCode,
@@ -732,7 +1673,7 @@ server.setRequestHandler(CallToolRequestSchema, async (req) => {
732
1673
  case "start_browser": {
733
1674
  const a = await client.createAgent({
734
1675
  ttl: args.ttl ?? "10m",
735
- country: args.country ?? DEFAULT_COUNTRY,
1676
+ country: args.country ?? DEFAULT_COUNTRY2,
736
1677
  osType: args.os_type,
737
1678
  agent_id: args.profile_id,
738
1679
  proxy: args.proxy
@@ -740,8 +1681,8 @@ server.setRequestHandler(CallToolRequestSchema, async (req) => {
740
1681
  return ok({
741
1682
  browser_id: a.id,
742
1683
  status: a.status,
743
- // Connect with playwright.chromium.connect_over_cdp(cdp_http,
744
- // headers={"X-API-Key": <your key>}); cdp_url is the page socket.
1684
+ // Connect a CDP client to cdp_http with the header
1685
+ // X-API-Key: <your key>; cdp_url is the page socket.
745
1686
  cdp_http: a.cdp_http,
746
1687
  cdp_url: a.cdp_url,
747
1688
  live_url: a.live_url,
@@ -755,10 +1696,6 @@ server.setRequestHandler(CallToolRequestSchema, async (req) => {
755
1696
  case "stop_browser":
756
1697
  await client.destroyAgent(args.browser_id);
757
1698
  return ok({ stopped: args.browser_id });
758
- case "observe":
759
- return ok(await pageCall("observe", args));
760
- case "act":
761
- return ok(await pageCall("act", args));
762
1699
  case "list_browsers":
763
1700
  return ok(await client.listIdentities());
764
1701
  case "credits":
@@ -784,7 +1721,7 @@ server.setRequestHandler(CallToolRequestSchema, async (req) => {
784
1721
  llmKeyId: c.llmKeyId,
785
1722
  reasoning: args.reasoning,
786
1723
  intervalSeconds: args.interval_seconds,
787
- country: args.country ?? DEFAULT_COUNTRY,
1724
+ country: args.country ?? DEFAULT_COUNTRY2,
788
1725
  maxSteps: args.max_steps,
789
1726
  initialUrl: args.initial_url
790
1727
  })
@@ -833,6 +1770,10 @@ server.setRequestHandler(CallToolRequestSchema, async (req) => {
833
1770
  return ok(robotRunView(await apiGet(`/v1/robot-runs/${encodeURIComponent(String(args.run_id))}`)));
834
1771
  case "solve_captcha_task":
835
1772
  return await solveCaptchaTask(args);
1773
+ case "list_captcha_types":
1774
+ return await listCaptchaTypes(args);
1775
+ case "report_captcha_result":
1776
+ return await reportCaptchaResult(args);
836
1777
  default:
837
1778
  return fail(`unknown tool: ${name}`);
838
1779
  }
@@ -848,11 +1789,70 @@ server.setRequestHandler(CallToolRequestSchema, async (req) => {
848
1789
  }
849
1790
  return fail(e.message || String(e));
850
1791
  }
1792
+ }
1793
+
1794
+ // src/redact.ts
1795
+ 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;
1796
+ 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"]);
1797
+ function isSensitiveParam(name) {
1798
+ const n = name.toLowerCase();
1799
+ if (SAFE.has(n)) return false;
1800
+ return SENSITIVE.test(n);
1801
+ }
1802
+ var PARAM = /([?&#;])([A-Za-z0-9_.\-[\]%]{1,64})=([^&#;\s"'<>\\)\]]+)/g;
1803
+ function redactUrls(text) {
1804
+ if (!text || text.indexOf("=") < 0) return text;
1805
+ return text.replace(PARAM, (all, sep, name, value) => {
1806
+ let decoded = name;
1807
+ try {
1808
+ decoded = decodeURIComponent(name);
1809
+ } catch {
1810
+ }
1811
+ if (!isSensitiveParam(decoded.replace(/\[\]$/, ""))) return all;
1812
+ if (value === "***") return all;
1813
+ return `${sep}${name}=***`;
1814
+ });
1815
+ }
1816
+
1817
+ // src/server.ts
1818
+ if (!API_KEY) {
1819
+ console.error("[browsa-mcp] BROWSA_API_KEY is not set: tools are listed, but every call will fail until it is.");
1820
+ console.error(` Mint one at ${KEYS_URL}`);
1821
+ }
1822
+ var extras = enabledExtras();
1823
+ for (const w of extras.unknown) {
1824
+ console.error(`[browsa-mcp] BROWSA_MCP_TOOLS: unknown group or tool "${w}" (groups: ${Object.keys(GROUPS).join(", ")}, all)`);
1825
+ }
1826
+ var tools = [...coreTools, ...legacyTools.filter((t) => extras.tools.has(t.name))];
1827
+ var listed = new Set(tools.map((t) => t.name));
1828
+ var server = new Server({ name: "browsa", version: VERSION }, { capabilities: { tools: {} } });
1829
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({ tools }));
1830
+ var clean = (s) => REDACT ? redactUrls(s) : s;
1831
+ server.setRequestHandler(CallToolRequestSchema, async (req) => {
1832
+ const name = req.params.name;
1833
+ const args = req.params.arguments ?? {};
1834
+ if (!listed.has(name)) {
1835
+ const group = Object.entries(GROUPS).find(([, t]) => t.includes(name))?.[0];
1836
+ const text = group ? `error: ${name} is in the optional group "${group}"
1837
+ next: set BROWSA_MCP_TOOLS=${group} (or all) in this server's env and restart it` : `error: unknown tool ${name}`;
1838
+ return { isError: true, content: [{ type: "text", text }] };
1839
+ }
1840
+ if (!API_KEY) return { isError: true, content: [{ type: "text", text: NO_KEY_MESSAGE }] };
1841
+ if (CORE_TOOLS.includes(name)) {
1842
+ const r2 = await callCore(name, args);
1843
+ const content = [];
1844
+ if (r2.image) content.push({ type: "image", data: r2.image.data, mimeType: r2.image.mime });
1845
+ content.push({ type: "text", text: clean(r2.text) });
1846
+ return { ...r2.isError ? { isError: true } : {}, content };
1847
+ }
1848
+ const r = await callLegacy(name, args);
1849
+ for (const c of r.content ?? []) if (c.type === "text") c.text = clean(c.text);
1850
+ return r;
851
1851
  });
852
1852
  async function main() {
853
1853
  const transport = new StdioServerTransport();
854
1854
  await server.connect(transport);
855
- console.error("[browsa-mcp] ready (tools=" + tools.length + ")");
1855
+ console.error(`[browsa-mcp] ${VERSION} ready (tools=${tools.length})`);
856
1856
  }
857
1857
  main().catch((e) => {
858
1858
  console.error("[browsa-mcp] fatal:", e);