@b3os/mcp 0.0.0-stage → 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/tools.ts ADDED
@@ -0,0 +1,844 @@
1
+ // The B3OS MCP tool set: 15 core tools (ARCHITECTURE §5.5: ≤15, with marketplace actions reached through
2
+ // actions_search → actions_describe → actions_call) plus optional per-pack tools. Runtime-agnostic (only
3
+ // @b3os/sdk), so the stdio server here and the edge's streamable-HTTP /mcp can serve the same definitions.
4
+ // Tool names use the §2 MCP prefixes: vision_, render_, sandbox_, routine_, actions_.
5
+
6
+ import {
7
+ type ActionDescription,
8
+ type ActStep,
9
+ type B3OS,
10
+ B3OSError,
11
+ type CrawlCreateRequest,
12
+ type RunCreateRequest,
13
+ type ScrapeRequest,
14
+ type ScreenshotCreateRequest,
15
+ type VideoCreateRequest,
16
+ } from "@b3os/sdk";
17
+
18
+ export interface JsonSchemaObject {
19
+ type: "object";
20
+ properties: Record<string, unknown>;
21
+ required?: string[];
22
+ additionalProperties?: boolean;
23
+ [k: string]: unknown;
24
+ }
25
+
26
+ export interface ToolAnnotations {
27
+ title?: string;
28
+ readOnlyHint?: boolean;
29
+ destructiveHint?: boolean;
30
+ idempotentHint?: boolean;
31
+ openWorldHint?: boolean;
32
+ }
33
+
34
+ export type ContentBlock =
35
+ | { type: "text"; text: string }
36
+ | { type: "image"; data: string; mimeType: string }
37
+ | { type: "resource_link"; uri: string; name: string; mimeType?: string; description?: string };
38
+
39
+ export interface ToolResult {
40
+ content: ContentBlock[];
41
+ structuredContent?: Record<string, unknown>;
42
+ isError?: boolean;
43
+ }
44
+
45
+ export interface ToolContext {
46
+ signal?: AbortSignal;
47
+ /** Reports progress on long tools (MCP notifications/progress when the client sent a progressToken). */
48
+ progress?: (completed: number, total?: number, message?: string) => void;
49
+ }
50
+
51
+ export interface ToolDef {
52
+ name: string;
53
+ title: string;
54
+ description: string;
55
+ inputSchema: JsonSchemaObject;
56
+ annotations: ToolAnnotations;
57
+ call(b3: B3OS, args: Record<string, unknown>, ctx: ToolContext): Promise<ToolResult>;
58
+ }
59
+
60
+ const MAX_TEXT = 100_000;
61
+
62
+ function clip(text: string, max = MAX_TEXT): string {
63
+ return text.length <= max ? text : `${text.slice(0, max)}\n\n[truncated: ${text.length - max} more characters]`;
64
+ }
65
+
66
+ function text(t: string, structured?: unknown): ToolResult {
67
+ const r: ToolResult = { content: [{ type: "text", text: t }] };
68
+ if (structured && typeof structured === "object" && !Array.isArray(structured)) {
69
+ r.structuredContent = structured as Record<string, unknown>;
70
+ }
71
+ return r;
72
+ }
73
+
74
+ function json(v: unknown): string {
75
+ return JSON.stringify(v, null, 2);
76
+ }
77
+
78
+ /** A failed call as an MCP tool error the model can read and correct (never a protocol error). */
79
+ export function errorResult(e: unknown): ToolResult {
80
+ if (e instanceof B3OSError) {
81
+ const lines = [`${e.code}: ${e.detail}`];
82
+ for (const it of e.errors) lines.push(` ${it.pointer}: ${it.detail}`);
83
+ if (e.requestId) lines.push(`(request ${e.requestId})`);
84
+ return {
85
+ isError: true,
86
+ content: [{ type: "text", text: lines.join("\n") }],
87
+ structuredContent: {
88
+ error: { code: e.code, status: e.status, detail: e.detail, request_id: e.requestId, errors: e.errors },
89
+ },
90
+ };
91
+ }
92
+ return { isError: true, content: [{ type: "text", text: `error: ${(e as Error)?.message ?? String(e)}` }] };
93
+ }
94
+
95
+ function str(args: Record<string, unknown>, k: string, required = false): string | undefined {
96
+ const v = args[k];
97
+ if (v === undefined || v === null || v === "") {
98
+ if (required)
99
+ throw new B3OSError({
100
+ code: "invalid_request",
101
+ status: 400,
102
+ detail: `${k} is required`,
103
+ errors: [{ pointer: `/${k}`, detail: "is required" }],
104
+ });
105
+ return undefined;
106
+ }
107
+ if (typeof v !== "string")
108
+ throw new B3OSError({
109
+ code: "invalid_request",
110
+ status: 400,
111
+ detail: `${k} must be a string`,
112
+ errors: [{ pointer: `/${k}`, detail: "must be a string" }],
113
+ });
114
+ return v;
115
+ }
116
+
117
+ function num(args: Record<string, unknown>, k: string): number | undefined {
118
+ const v = args[k];
119
+ if (v === undefined || v === null) return undefined;
120
+ if (typeof v !== "number" || !Number.isFinite(v)) {
121
+ throw new B3OSError({
122
+ code: "invalid_request",
123
+ status: 400,
124
+ detail: `${k} must be a number`,
125
+ errors: [{ pointer: `/${k}`, detail: "must be a number" }],
126
+ });
127
+ }
128
+ return v;
129
+ }
130
+
131
+ /** Copies the listed keys that are present. */
132
+ function pick<T extends object>(args: Record<string, unknown>, keys: string[]): Partial<T> {
133
+ const out: Record<string, unknown> = {};
134
+ for (const k of keys) if (args[k] !== undefined && args[k] !== null) out[k] = args[k];
135
+ return out as Partial<T>;
136
+ }
137
+
138
+ const waitSchema = {
139
+ type: "integer",
140
+ minimum: 0,
141
+ maximum: 60,
142
+ default: 50,
143
+ description:
144
+ "Seconds to wait for the job before returning its id and status (call again with job_id to keep waiting).",
145
+ };
146
+
147
+ async function waitForJob<J extends { id: string; status: string }>(
148
+ b3: B3OS,
149
+ job: J,
150
+ waitS: number,
151
+ ctx: ToolContext,
152
+ ): Promise<J> {
153
+ if (job.status === "succeeded" || job.status === "failed" || job.status === "canceled" || waitS <= 0) return job;
154
+ try {
155
+ return await b3.jobs.wait<J & { object: string }>(job as J & { object: string }, {
156
+ timeoutMs: waitS * 1000,
157
+ signal: ctx.signal,
158
+ throwOnFailure: false,
159
+ onEvent: (ev) => {
160
+ const p = (ev as { progress?: { completed?: number; total?: number | null } }).progress;
161
+ if (p && typeof p.completed === "number") ctx.progress?.(p.completed, p.total ?? undefined);
162
+ },
163
+ });
164
+ } catch (e) {
165
+ if (e instanceof B3OSError && e.code === "timeout") return (await b3.jobs.get<J & { object: string }>(job.id)) as J;
166
+ throw e;
167
+ }
168
+ }
169
+
170
+ // ---------------------------------------------------------------------------------------------------------------
171
+
172
+ const visionScrape: ToolDef = {
173
+ name: "vision_scrape",
174
+ title: "Scrape a web page",
175
+ description:
176
+ "Fetch one URL and return its main content as Markdown (or html, text, links). Uses the cache, a plain HTTP " +
177
+ "fetch, or a real browser when the page needs JavaScript. Respects robots.txt.",
178
+ inputSchema: {
179
+ type: "object",
180
+ properties: {
181
+ url: { type: "string", description: "Absolute http(s) URL." },
182
+ formats: {
183
+ type: "array",
184
+ items: { type: "string", enum: ["markdown", "html", "raw_html", "text", "links", "metadata", "screenshot"] },
185
+ default: ["markdown"],
186
+ },
187
+ only_main_content: {
188
+ type: "boolean",
189
+ default: true,
190
+ description: "false keeps headers, navigation and footers.",
191
+ },
192
+ engine: { type: "string", enum: ["auto", "fetch", "browser"], default: "auto" },
193
+ wait_for_ms: { type: "integer", minimum: 0, maximum: 30000 },
194
+ max_age_ms: { type: "integer", minimum: 0, description: "Accept a cached copy up to this old; 0 fetches fresh." },
195
+ max_chars: {
196
+ type: "integer",
197
+ minimum: 1000,
198
+ default: MAX_TEXT,
199
+ description: "Truncate text output to this many characters.",
200
+ },
201
+ },
202
+ required: ["url"],
203
+ additionalProperties: false,
204
+ },
205
+ annotations: { title: "Scrape a web page", readOnlyHint: true, openWorldHint: true },
206
+ async call(b3, args, ctx) {
207
+ const body = {
208
+ url: str(args, "url", true),
209
+ ...pick<ScrapeRequest>(args, ["formats", "only_main_content", "engine", "wait_for_ms", "max_age_ms"]),
210
+ } as ScrapeRequest;
211
+ const page = await b3.vision.scrape(body, { signal: ctx.signal });
212
+ const max = num(args, "max_chars") ?? MAX_TEXT;
213
+ const parts: string[] = [`${page.status_code} ${page.final_url} (${page.tier}, cache ${page.cache.state})`];
214
+ if (page.metadata?.title) parts.push(`# ${page.metadata.title}`);
215
+ if (page.markdown !== undefined) parts.push(page.markdown);
216
+ if (page.text !== undefined) parts.push(page.text);
217
+ if (page.html !== undefined) parts.push(page.html);
218
+ if (page.raw_html !== undefined) parts.push(page.raw_html);
219
+ if (page.links?.length) parts.push(`Links:\n${page.links.join("\n")}`);
220
+ const content: ContentBlock[] = [{ type: "text", text: clip(parts.join("\n\n"), max) }];
221
+ const shot = page.screenshot as { data?: string; content_type?: string; url?: string } | undefined;
222
+ if (shot?.data && shot.content_type) content.push({ type: "image", data: shot.data, mimeType: shot.content_type });
223
+ const { markdown, html, raw_html, text: t, ...meta } = page;
224
+ void markdown;
225
+ void html;
226
+ void raw_html;
227
+ void t;
228
+ return { content, structuredContent: meta as unknown as Record<string, unknown> };
229
+ },
230
+ };
231
+
232
+ const visionMap: ToolDef = {
233
+ name: "vision_map",
234
+ title: "List a site's URLs",
235
+ description:
236
+ "Discover the URLs of a site from its links and sitemaps, optionally ordered by relevance to a search phrase.",
237
+ inputSchema: {
238
+ type: "object",
239
+ properties: {
240
+ url: { type: "string", description: "The site's start URL." },
241
+ search: { type: "string", description: "Order results by relevance to this phrase." },
242
+ limit: { type: "integer", minimum: 1, maximum: 5000, default: 200 },
243
+ include_subdomains: { type: "boolean", default: true },
244
+ },
245
+ required: ["url"],
246
+ additionalProperties: false,
247
+ },
248
+ annotations: { title: "List a site's URLs", readOnlyHint: true, openWorldHint: true },
249
+ async call(b3, args, ctx) {
250
+ const r = await b3.vision.map(
251
+ {
252
+ url: str(args, "url", true) as string,
253
+ limit: num(args, "limit") ?? 200,
254
+ ...pick(args, ["search", "include_subdomains"]),
255
+ },
256
+ { signal: ctx.signal },
257
+ );
258
+ const lines = r.links.map((l) => (l.title ? `${l.url} ${l.title}` : l.url));
259
+ return text(clip(`${r.links.length} URLs\n${lines.join("\n")}`), { url: r.url, links: r.links });
260
+ },
261
+ };
262
+
263
+ const visionCrawl: ToolDef = {
264
+ name: "vision_crawl",
265
+ title: "Crawl a site",
266
+ description:
267
+ "Crawl a site breadth first (links and sitemaps, robots.txt honored, at most 500 pages) and return the pages " +
268
+ "as Markdown. Waits up to wait_s seconds; if the crawl is still running, call again with job_id.",
269
+ inputSchema: {
270
+ type: "object",
271
+ properties: {
272
+ url: { type: "string", description: "Where to start (omit when passing job_id)." },
273
+ job_id: { type: "string", description: "A crawl_… id from an earlier call, to keep waiting or read its pages." },
274
+ limit: { type: "integer", minimum: 1, maximum: 500, default: 20 },
275
+ max_depth: { type: "integer", minimum: 0, maximum: 20 },
276
+ include_paths: { type: "array", items: { type: "string" }, description: "RE2 regexes a URL path must match." },
277
+ exclude_paths: { type: "array", items: { type: "string" } },
278
+ wait_s: waitSchema,
279
+ max_chars_per_page: { type: "integer", minimum: 200, default: 4000 },
280
+ },
281
+ additionalProperties: false,
282
+ },
283
+ annotations: { title: "Crawl a site", readOnlyHint: true, openWorldHint: true },
284
+ async call(b3, args, ctx) {
285
+ const jobId = str(args, "job_id");
286
+ let job = jobId
287
+ ? await b3.vision.getCrawl(jobId, { signal: ctx.signal })
288
+ : await b3.vision.createCrawl(
289
+ {
290
+ url: str(args, "url", true) as string,
291
+ limit: num(args, "limit") ?? 20,
292
+ scrape: { formats: ["markdown"] },
293
+ ...pick<CrawlCreateRequest>(args, ["max_depth", "include_paths", "exclude_paths"]),
294
+ },
295
+ { signal: ctx.signal },
296
+ );
297
+ job = await waitForJob(b3, job, num(args, "wait_s") ?? 50, ctx);
298
+ const head = `crawl ${job.id}: ${job.status}${job.progress ? ` (${job.progress.completed}/${job.progress.total ?? "?"} pages)` : ""}`;
299
+ if (job.status !== "succeeded" && job.status !== "running") return text(head, job);
300
+ const per = num(args, "max_chars_per_page") ?? 4000;
301
+ const pages: string[] = [];
302
+ for await (const p of b3.vision.listCrawlPages(job.id, { limit: 100 }, { signal: ctx.signal })) {
303
+ pages.push(
304
+ `## ${p.url}\n${p.status === "succeeded" ? clip(p.scrape?.markdown ?? "", per) : `failed: ${p.error?.detail ?? ""}`}`,
305
+ );
306
+ if (pages.length >= 500) break;
307
+ }
308
+ return text(clip([head, ...pages].join("\n\n")), {
309
+ id: job.id,
310
+ status: job.status,
311
+ progress: job.progress,
312
+ pages: pages.length,
313
+ });
314
+ },
315
+ };
316
+
317
+ const visionAct: ToolDef = {
318
+ name: "vision_act",
319
+ title: "Drive a browser",
320
+ description:
321
+ "Run browser actions in a real Chrome session in one call: navigate, click, hover, type, key, scroll, select, " +
322
+ "wait, evaluate, screenshot, markdown. Without session_id a session is created for this call and closed after " +
323
+ "it (keep_session: true keeps it and returns its id for the next call).",
324
+ inputSchema: {
325
+ type: "object",
326
+ properties: {
327
+ url: { type: "string", description: "Navigate here first." },
328
+ steps: {
329
+ type: "array",
330
+ description:
331
+ "Actions in order. Each has `kind` and its fields: navigate {url}, click {target}, type {target, text}, " +
332
+ "key {key}, scroll {target?|y}, select {target, value}, wait {for: {selector|text|url|network_idle}}, " +
333
+ "evaluate {expression}, screenshot {full_page?}, markdown {}. A target is {selector} or {text} or {role, name}.",
334
+ items: { type: "object", properties: { kind: { type: "string" } }, required: ["kind"] },
335
+ },
336
+ session_id: { type: "string", description: "A brs_… session from an earlier call." },
337
+ keep_session: { type: "boolean", default: false },
338
+ },
339
+ additionalProperties: false,
340
+ },
341
+ annotations: { title: "Drive a browser", readOnlyHint: false, openWorldHint: true },
342
+ async call(b3, args, ctx) {
343
+ const steps = (Array.isArray(args.steps) ? args.steps : []) as ActStep[];
344
+ const url = str(args, "url");
345
+ const actions: ActStep[] = [...(url ? [{ kind: "navigate", url } as ActStep] : []), ...steps];
346
+ if (!actions.length) throw new B3OSError({ code: "invalid_request", status: 400, detail: "give url or steps" });
347
+ if (!actions.some((s) => s.kind === "markdown" || s.kind === "screenshot"))
348
+ actions.push({ kind: "markdown" } as ActStep);
349
+ let sid = str(args, "session_id");
350
+ const created = !sid;
351
+ if (!sid) sid = (await b3.vision.createSession({ timeout_s: 600 }, { signal: ctx.signal })).id;
352
+ try {
353
+ const r = await b3.vision.act(sid, { actions, continue_on_error: false }, { signal: ctx.signal });
354
+ const content: ContentBlock[] = [];
355
+ const lines: string[] = [`session ${sid}: ${r.ok ? "ok" : "an action failed"}`];
356
+ r.results.forEach((s, i) => {
357
+ lines.push(
358
+ `${i}. ${s.kind} ${s.status}${s.url ? ` ${s.url}` : ""}${s.error ? ` (${s.error.code}: ${s.error.detail})` : ""}`,
359
+ );
360
+ if (s.markdown) lines.push(clip(s.markdown, 50_000));
361
+ if (s.value !== undefined) lines.push(json(s.value));
362
+ const shot = s.screenshot as { data?: string; content_type?: string } | undefined;
363
+ if (shot?.data && shot.content_type)
364
+ content.push({ type: "image", data: shot.data, mimeType: shot.content_type });
365
+ });
366
+ content.unshift({ type: "text", text: clip(lines.join("\n")) });
367
+ return {
368
+ content,
369
+ structuredContent: {
370
+ session_id: sid,
371
+ ok: r.ok,
372
+ results: r.results.map(({ screenshot, ...x }) => (void screenshot, x)),
373
+ },
374
+ isError: !r.ok,
375
+ };
376
+ } finally {
377
+ if (created && !args.keep_session) await b3.vision.closeSession(sid).catch(() => undefined);
378
+ }
379
+ },
380
+ };
381
+
382
+ const renderScreenshot: ToolDef = {
383
+ name: "render_screenshot",
384
+ title: "Take a screenshot",
385
+ description:
386
+ "Capture a page (or an element, or the full page) in a warm browser, optionally styled with a background and " +
387
+ "window frame. Returns the image and a signed URL to it.",
388
+ inputSchema: {
389
+ type: "object",
390
+ properties: {
391
+ url: { type: "string" },
392
+ html: { type: "string", description: "Render this HTML instead of a URL." },
393
+ width: { type: "integer", minimum: 320, maximum: 3840, default: 1600 },
394
+ height: { type: "integer", minimum: 240, maximum: 2160, default: 900 },
395
+ full_page: { type: "boolean", default: false },
396
+ selector: { type: "string", description: "Capture only this element." },
397
+ background: { type: "string", description: "Style preset, for example midnight." },
398
+ frame: { type: "string", description: "Window frame preset, for example browser-dark." },
399
+ format: { type: "string", enum: ["webp", "png", "jpeg"], default: "png" },
400
+ },
401
+ additionalProperties: false,
402
+ },
403
+ annotations: { title: "Take a screenshot", readOnlyHint: true, openWorldHint: true },
404
+ async call(b3, args, ctx) {
405
+ const body: ScreenshotCreateRequest = {
406
+ viewport: { width: num(args, "width") ?? 1600, height: num(args, "height") ?? 900 },
407
+ format: (str(args, "format") as ScreenshotCreateRequest["format"]) ?? "png",
408
+ ...pick<ScreenshotCreateRequest>(args, ["url", "html", "full_page"]),
409
+ };
410
+ const sel = str(args, "selector");
411
+ if (sel) body.target = { selector: sel };
412
+ const bg = str(args, "background");
413
+ const fr = str(args, "frame");
414
+ if (bg || fr) body.style = { ...(bg ? { background: bg } : {}), ...(fr ? { frame: fr } : {}) };
415
+ const shot = await b3.render.createScreenshot(body, { signal: ctx.signal });
416
+ const art = shot.artifacts[0];
417
+ const content: ContentBlock[] = [
418
+ { type: "text", text: `${shot.width}x${shot.height} ${shot.format}${art?.url ? `\n${art.url}` : ""}` },
419
+ ];
420
+ if (art?.url) {
421
+ const res = await fetch(art.url, { signal: ctx.signal }).catch(() => undefined);
422
+ if (res?.ok) {
423
+ const bytes = new Uint8Array(await res.arrayBuffer());
424
+ content.push({ type: "image", data: toBase64(bytes), mimeType: art.content_type });
425
+ }
426
+ }
427
+ return { content, structuredContent: shot as unknown as Record<string, unknown> };
428
+ },
429
+ };
430
+
431
+ const renderVideo: ToolDef = {
432
+ name: "render_video",
433
+ title: "Render a product video",
434
+ description:
435
+ "Record a scripted product demo (beats of browser steps, optional narration and captions) as MP4 and GIF. " +
436
+ "`request` is a render video request (docs: /render). Waits up to wait_s; call again with job_id to keep waiting.",
437
+ inputSchema: {
438
+ type: "object",
439
+ properties: {
440
+ request: {
441
+ type: "object",
442
+ description: "VideoCreateRequest: {source: {url}, beats: [...], voice?, captions?, style?}.",
443
+ },
444
+ job_id: { type: "string", description: "A vid_… id from an earlier call." },
445
+ wait_s: waitSchema,
446
+ },
447
+ additionalProperties: false,
448
+ },
449
+ annotations: { title: "Render a product video", readOnlyHint: false, openWorldHint: true },
450
+ async call(b3, args, ctx) {
451
+ const id = str(args, "job_id");
452
+ const req = args.request as VideoCreateRequest | undefined;
453
+ if (!id && !req) throw new B3OSError({ code: "invalid_request", status: 400, detail: "give request or job_id" });
454
+ let v = id
455
+ ? await b3.render.getVideo(id, { signal: ctx.signal })
456
+ : await b3.render.createVideo(req as VideoCreateRequest, { signal: ctx.signal });
457
+ v = await waitForJob(b3, v, num(args, "wait_s") ?? 50, ctx);
458
+ const arts = v.result?.artifacts ?? [];
459
+ const lines = [`video ${v.id}: ${v.status}`, ...arts.map((a) => `${a.kind} ${a.url ?? ""}`)];
460
+ if (v.error) lines.push(`${v.error.code}: ${v.error.detail}`);
461
+ return { ...text(lines.join("\n"), v), isError: v.status === "failed" };
462
+ },
463
+ };
464
+
465
+ const sandboxCreate: ToolDef = {
466
+ name: "sandbox_create",
467
+ title: "Create a sandbox",
468
+ description:
469
+ "Start a Firecracker microVM (Ubuntu 24.04 with Python 3.12, Node 24 and git in the `base` template) in a few " +
470
+ "milliseconds. It stops after timeout_s. Use sandbox_exec, sandbox_read_file and sandbox_write_file on its id.",
471
+ inputSchema: {
472
+ type: "object",
473
+ properties: {
474
+ template: { type: "string", default: "base", description: "base, code-interpreter or agent." },
475
+ vcpu: { type: "integer", minimum: 1, default: 1 },
476
+ memory_mib: { type: "integer", minimum: 128, default: 512 },
477
+ timeout_s: { type: "integer", minimum: 10, maximum: 86400, default: 600 },
478
+ env: { type: "object", additionalProperties: { type: "string" } },
479
+ },
480
+ additionalProperties: false,
481
+ },
482
+ annotations: { title: "Create a sandbox", readOnlyHint: false, destructiveHint: false, openWorldHint: false },
483
+ async call(b3, args, ctx) {
484
+ const s = await b3.sandboxes.createSandbox(
485
+ { timeout_s: num(args, "timeout_s") ?? 600, ...pick(args, ["template", "vcpu", "memory_mib", "env"]) },
486
+ { signal: ctx.signal },
487
+ );
488
+ return text(`${s.id} ${s.status} (${s.vcpu} vCPU, ${s.memory_mib} MiB, until ${s.expires_at ?? "-"})`, s);
489
+ },
490
+ };
491
+
492
+ const sandboxExec: ToolDef = {
493
+ name: "sandbox_exec",
494
+ title: "Run a command in a sandbox",
495
+ description:
496
+ "Run a shell command (string) or an argv array in a sandbox and return its exit code, stdout and stderr.",
497
+ inputSchema: {
498
+ type: "object",
499
+ properties: {
500
+ sandbox_id: { type: "string" },
501
+ cmd: { oneOf: [{ type: "string" }, { type: "array", items: { type: "string" } }] },
502
+ cwd: { type: "string", default: "/workspace" },
503
+ env: { type: "object", additionalProperties: { type: "string" } },
504
+ stdin: { type: "string" },
505
+ timeout_ms: { type: "integer", minimum: 1, maximum: 60000, default: 30000 },
506
+ },
507
+ required: ["sandbox_id", "cmd"],
508
+ additionalProperties: false,
509
+ },
510
+ annotations: {
511
+ title: "Run a command in a sandbox",
512
+ readOnlyHint: false,
513
+ destructiveHint: true,
514
+ openWorldHint: false,
515
+ },
516
+ async call(b3, args, ctx) {
517
+ const id = str(args, "sandbox_id", true) as string;
518
+ const cmd = args.cmd;
519
+ if (typeof cmd !== "string" && !(Array.isArray(cmd) && cmd.every((c) => typeof c === "string"))) {
520
+ throw new B3OSError({ code: "invalid_request", status: 400, detail: "cmd is a string or an array of strings" });
521
+ }
522
+ const r = await b3.sandboxes.exec(
523
+ id,
524
+ { cmd, ...pick(args, ["cwd", "env", "stdin", "timeout_ms"]) },
525
+ { signal: ctx.signal },
526
+ );
527
+ const out = [`exit ${r.exit_code ?? `signal ${r.signal}`}${r.timed_out ? " (timed out)" : ""}`];
528
+ if (r.stdout) out.push(`stdout:\n${clip(r.stdout, 60_000)}`);
529
+ if (r.stderr) out.push(`stderr:\n${clip(r.stderr, 30_000)}`);
530
+ return { ...text(out.join("\n"), r), isError: r.exit_code !== 0 };
531
+ },
532
+ };
533
+
534
+ const sandboxRead: ToolDef = {
535
+ name: "sandbox_read_file",
536
+ title: "Read a file in a sandbox",
537
+ description: "Read a file from a sandbox (UTF-8 text, or base64 for binary), or list a directory with list: true.",
538
+ inputSchema: {
539
+ type: "object",
540
+ properties: {
541
+ sandbox_id: { type: "string" },
542
+ path: { type: "string", description: "Absolute path, for example /workspace/main.py." },
543
+ list: { type: "boolean", default: false },
544
+ },
545
+ required: ["sandbox_id", "path"],
546
+ additionalProperties: false,
547
+ },
548
+ annotations: { title: "Read a file in a sandbox", readOnlyHint: true, openWorldHint: false },
549
+ async call(b3, args, ctx) {
550
+ const id = str(args, "sandbox_id", true) as string;
551
+ const path = str(args, "path", true) as string;
552
+ if (args.list) {
553
+ const l = await b3.sandboxes.readFile(id, { path, list: 1 }, { signal: ctx.signal });
554
+ return text(
555
+ l.data.map((e) => `${e.type === "directory" ? "d" : "-"} ${String(e.size).padStart(10)} ${e.path}`).join("\n"),
556
+ l,
557
+ );
558
+ }
559
+ const bytes = await b3.sandboxes.readFile(id, { path }, { signal: ctx.signal });
560
+ const decoded = new TextDecoder("utf-8", { fatal: true });
561
+ try {
562
+ return text(clip(decoded.decode(bytes)), { path, bytes: bytes.byteLength, encoding: "utf8" });
563
+ } catch {
564
+ return text(toBase64(bytes), { path, bytes: bytes.byteLength, encoding: "base64" });
565
+ }
566
+ },
567
+ };
568
+
569
+ const sandboxWrite: ToolDef = {
570
+ name: "sandbox_write_file",
571
+ title: "Write a file in a sandbox",
572
+ description: "Write a file in a sandbox, replacing it if it exists; parent directories are created.",
573
+ inputSchema: {
574
+ type: "object",
575
+ properties: {
576
+ sandbox_id: { type: "string" },
577
+ path: { type: "string" },
578
+ content: { type: "string" },
579
+ encoding: { type: "string", enum: ["utf8", "base64"], default: "utf8" },
580
+ mode: { type: "string", description: "Octal mode for a new file, for example 0755." },
581
+ },
582
+ required: ["sandbox_id", "path", "content"],
583
+ additionalProperties: false,
584
+ },
585
+ annotations: { title: "Write a file in a sandbox", readOnlyHint: false, destructiveHint: true, openWorldHint: false },
586
+ async call(b3, args, ctx) {
587
+ const content = str(args, "content") ?? "";
588
+ const data = args.encoding === "base64" ? fromBase64(content) : content;
589
+ const e = await b3.sandboxes.writeFile(
590
+ str(args, "sandbox_id", true) as string,
591
+ { path: str(args, "path", true) as string, mkdir: 1, ...(str(args, "mode") ? { mode: str(args, "mode") } : {}) },
592
+ data,
593
+ { signal: ctx.signal },
594
+ );
595
+ return text(`wrote ${e.size} bytes to ${e.path}`, e);
596
+ },
597
+ };
598
+
599
+ const sandboxDelete: ToolDef = {
600
+ name: "sandbox_delete",
601
+ title: "Delete a sandbox",
602
+ description: "Stop a sandbox and destroy its memory and disk. Snapshots are kept.",
603
+ inputSchema: {
604
+ type: "object",
605
+ properties: { sandbox_id: { type: "string" } },
606
+ required: ["sandbox_id"],
607
+ additionalProperties: false,
608
+ },
609
+ annotations: {
610
+ title: "Delete a sandbox",
611
+ readOnlyHint: false,
612
+ destructiveHint: true,
613
+ idempotentHint: true,
614
+ openWorldHint: false,
615
+ },
616
+ async call(b3, args, ctx) {
617
+ const s = await b3.sandboxes.deleteSandbox(str(args, "sandbox_id", true) as string, { signal: ctx.signal });
618
+ return text(`${s.id} ${s.status}`, s);
619
+ },
620
+ };
621
+
622
+ const routineRun: ToolDef = {
623
+ name: "routine_run",
624
+ title: "Run a routine",
625
+ description:
626
+ "Start a run of a published routine (by name or rtn_ id) with an input object and wait up to wait_s for its " +
627
+ "output; call again with job_id to keep waiting.",
628
+ inputSchema: {
629
+ type: "object",
630
+ properties: {
631
+ routine: { type: "string", description: "Routine name or rtn_… id (omit with job_id)." },
632
+ input: { type: "object" },
633
+ job_id: { type: "string", description: "A run_… id from an earlier call." },
634
+ wait_s: waitSchema,
635
+ },
636
+ additionalProperties: false,
637
+ },
638
+ annotations: { title: "Run a routine", readOnlyHint: false, openWorldHint: true },
639
+ async call(b3, args, ctx) {
640
+ const id = str(args, "job_id");
641
+ let run = id
642
+ ? await b3.routines.getRun(id, { signal: ctx.signal })
643
+ : await b3.routines.createRun(
644
+ str(args, "routine", true) as string,
645
+ pick<RunCreateRequest>(args, ["input"]) as RunCreateRequest,
646
+ { signal: ctx.signal },
647
+ );
648
+ run = await waitForJob(b3, run, num(args, "wait_s") ?? 50, ctx);
649
+ const lines = [`run ${run.id}: ${run.status}`];
650
+ if (run.result !== undefined) lines.push(json(run.result));
651
+ if (run.error) lines.push(`${run.error.code}: ${run.error.detail}`);
652
+ return { ...text(clip(lines.join("\n")), run), isError: run.status === "failed" };
653
+ },
654
+ };
655
+
656
+ const actionsSearch: ToolDef = {
657
+ name: "actions_search",
658
+ title: "Search marketplace actions",
659
+ description:
660
+ "Find marketplace actions (GitHub, Slack, Linear, Notion, HTTP and more) by what they do. Returns refs to pass to " +
661
+ "actions_describe (for the input schema) and actions_call.",
662
+ inputSchema: {
663
+ type: "object",
664
+ properties: {
665
+ q: { type: "string", description: "What the action should do, in words." },
666
+ pack: { type: "string", description: "Only this pack, for example io.b3os/github." },
667
+ limit: { type: "integer", minimum: 1, maximum: 50, default: 10 },
668
+ },
669
+ required: ["q"],
670
+ additionalProperties: false,
671
+ },
672
+ annotations: { title: "Search marketplace actions", readOnlyHint: true, openWorldHint: false },
673
+ async call(b3, args, ctx) {
674
+ const r = await b3.actions.search(
675
+ { q: str(args, "q", true) as string, ...pick(args, ["pack", "limit"]) },
676
+ { signal: ctx.signal },
677
+ );
678
+ const lines = r.data.map((a) => `${a.ref} [${a.effects}] ${a.title}: ${a.description}`);
679
+ return text(lines.length ? lines.join("\n") : "no matching actions", { data: r.data });
680
+ },
681
+ };
682
+
683
+ const actionsDescribe: ToolDef = {
684
+ name: "actions_describe",
685
+ title: "Describe an action",
686
+ description: "Get an action's input and output JSON Schemas, effect class and the connections it needs.",
687
+ inputSchema: {
688
+ type: "object",
689
+ properties: {
690
+ ref: {
691
+ type: "string",
692
+ description: "Action ref from actions_search, for example io.b3os/github/create-issue@1.",
693
+ },
694
+ },
695
+ required: ["ref"],
696
+ additionalProperties: false,
697
+ },
698
+ annotations: { title: "Describe an action", readOnlyHint: true, openWorldHint: false },
699
+ async call(b3, args, ctx) {
700
+ const d = await b3.actions.describe({ ref: str(args, "ref", true) as string }, { signal: ctx.signal });
701
+ return text(
702
+ json({
703
+ ref: d.ref,
704
+ title: d.title,
705
+ description: d.description,
706
+ effects: d.effects,
707
+ input_schema: d.input_schema,
708
+ output_schema: d.output_schema,
709
+ connections: d.connections,
710
+ }),
711
+ d,
712
+ );
713
+ },
714
+ };
715
+
716
+ const actionsCall: ToolDef = {
717
+ name: "actions_call",
718
+ title: "Call an action",
719
+ description:
720
+ "Run a marketplace action with an input object. Credentials come from your stored connections (vault), never " +
721
+ "from arguments; name one per connection key in `connections` when you have several.",
722
+ inputSchema: {
723
+ type: "object",
724
+ properties: {
725
+ ref: { type: "string" },
726
+ input: { type: "object" },
727
+ connections: {
728
+ type: "object",
729
+ additionalProperties: { type: "string" },
730
+ description: "Connection key to conn_… id.",
731
+ },
732
+ },
733
+ required: ["ref"],
734
+ additionalProperties: false,
735
+ },
736
+ annotations: { title: "Call an action", readOnlyHint: false, openWorldHint: true },
737
+ async call(b3, args, ctx) {
738
+ const r = await b3.actions.call(
739
+ {
740
+ ref: str(args, "ref", true) as string,
741
+ input: (args.input as Record<string, unknown>) ?? {},
742
+ ...pick(args, ["connections"]),
743
+ },
744
+ { signal: ctx.signal },
745
+ );
746
+ return text(clip(json(r.output)), r);
747
+ },
748
+ };
749
+
750
+ /** The core tool set, in a fixed order (deterministic tools/list for prompt caching). */
751
+ export const coreTools: readonly ToolDef[] = [
752
+ visionScrape,
753
+ visionMap,
754
+ visionCrawl,
755
+ visionAct,
756
+ renderScreenshot,
757
+ renderVideo,
758
+ sandboxCreate,
759
+ sandboxExec,
760
+ sandboxRead,
761
+ sandboxWrite,
762
+ sandboxDelete,
763
+ routineRun,
764
+ actionsSearch,
765
+ actionsDescribe,
766
+ actionsCall,
767
+ ];
768
+
769
+ /** One tool per action of the given packs (`github`, or `io.b3os/github`), named by the registry's `mcp_name`. */
770
+ export async function packTools(b3: B3OS, packs: readonly string[]): Promise<ToolDef[]> {
771
+ const out: ToolDef[] = [];
772
+ for (const want of packs) {
773
+ const id = want.includes("/") ? want : await resolvePack(b3, want);
774
+ if (!id) continue;
775
+ const [ns, name] = id.split("/") as [string, string];
776
+ const pack = await b3.actions.getPack(ns, name);
777
+ for (const a of pack.actions) {
778
+ const d: ActionDescription = await b3.actions.describe({ ref: a.ref });
779
+ out.push(actionTool(d));
780
+ }
781
+ }
782
+ return out;
783
+ }
784
+
785
+ async function resolvePack(b3: B3OS, short: string): Promise<string | undefined> {
786
+ for await (const p of b3.actions.listPacks({ q: short, limit: 100 })) {
787
+ if (p.id === short || p.id.endsWith(`/${short}`)) return p.id;
788
+ }
789
+ return undefined;
790
+ }
791
+
792
+ export function actionTool(d: ActionDescription): ToolDef {
793
+ const m = d.mcp as { name: string; title?: string; description?: string; inputSchema?: JsonSchemaObject };
794
+ const ann = d.annotations as ToolAnnotations;
795
+ return {
796
+ name: m.name,
797
+ title: m.title ?? d.title,
798
+ description: m.description ?? d.description,
799
+ inputSchema: m.inputSchema ?? (d.input_schema as JsonSchemaObject),
800
+ annotations: { title: m.title ?? d.title, ...ann },
801
+ async call(b3, args, ctx) {
802
+ const r = await b3.actions.call({ ref: d.ref, input: args }, { signal: ctx.signal });
803
+ return text(clip(json(r.output)), r);
804
+ },
805
+ };
806
+ }
807
+
808
+ // Base64 without Buffer, so Workers can run the tools too.
809
+ const B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
810
+ export function toBase64(bytes: Uint8Array): string {
811
+ let out = "";
812
+ let i = 0;
813
+ for (; i + 2 < bytes.length; i += 3) {
814
+ const n = ((bytes[i] as number) << 16) | ((bytes[i + 1] as number) << 8) | (bytes[i + 2] as number);
815
+ out +=
816
+ B64[(n >> 18) & 63] + (B64[(n >> 12) & 63] as string) + (B64[(n >> 6) & 63] as string) + (B64[n & 63] as string);
817
+ }
818
+ const rest = bytes.length - i;
819
+ if (rest === 1) {
820
+ const n = (bytes[i] as number) << 16;
821
+ out += `${B64[(n >> 18) & 63]}${B64[(n >> 12) & 63]}==`;
822
+ } else if (rest === 2) {
823
+ const n = ((bytes[i] as number) << 16) | ((bytes[i + 1] as number) << 8);
824
+ out += `${B64[(n >> 18) & 63]}${B64[(n >> 12) & 63]}${B64[(n >> 6) & 63]}=`;
825
+ }
826
+ return out;
827
+ }
828
+
829
+ export function fromBase64(s: string): Uint8Array {
830
+ const clean = s.replace(/[^A-Za-z0-9+/]/g, "");
831
+ const out = new Uint8Array(Math.floor((clean.length * 3) / 4));
832
+ let o = 0;
833
+ for (let i = 0; i < clean.length; i += 4) {
834
+ const n =
835
+ (B64.indexOf(clean[i] ?? "A") << 18) |
836
+ (B64.indexOf(clean[i + 1] ?? "A") << 12) |
837
+ ((clean[i + 2] ? B64.indexOf(clean[i + 2] as string) : 0) << 6) |
838
+ (clean[i + 3] ? B64.indexOf(clean[i + 3] as string) : 0);
839
+ out[o++] = (n >> 16) & 255;
840
+ if (clean[i + 2] !== undefined) out[o++] = (n >> 8) & 255;
841
+ if (clean[i + 3] !== undefined) out[o++] = n & 255;
842
+ }
843
+ return out.slice(0, o);
844
+ }