@b3os/mcp 0.0.1 → 0.1.3

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 (73) hide show
  1. package/README.md +129 -43
  2. package/bin/b3os-mcp.js +14 -3
  3. package/dist/compact.d.ts +27 -0
  4. package/dist/compact.js +138 -0
  5. package/dist/compact.js.map +1 -0
  6. package/dist/handlers/_common.d.ts +150 -0
  7. package/dist/handlers/_common.js +329 -0
  8. package/dist/handlers/_common.js.map +1 -0
  9. package/dist/handlers/actions.d.ts +19 -0
  10. package/dist/handlers/actions.js +110 -0
  11. package/dist/handlers/actions.js.map +1 -0
  12. package/dist/handlers/render.d.ts +7 -0
  13. package/dist/handlers/render.js +72 -0
  14. package/dist/handlers/render.js.map +1 -0
  15. package/dist/handlers/routines.d.ts +20 -0
  16. package/dist/handlers/routines.js +128 -0
  17. package/dist/handlers/routines.js.map +1 -0
  18. package/dist/handlers/sandboxes.d.ts +2 -0
  19. package/dist/handlers/sandboxes.js +100 -0
  20. package/dist/handlers/sandboxes.js.map +1 -0
  21. package/dist/handlers/vision.d.ts +7 -0
  22. package/dist/handlers/vision.js +186 -0
  23. package/dist/handlers/vision.js.map +1 -0
  24. package/dist/index.d.ts +3 -2
  25. package/dist/index.js +3 -2
  26. package/dist/index.js.map +1 -1
  27. package/dist/main.js +88 -7
  28. package/dist/main.js.map +1 -1
  29. package/dist/server.d.ts +68 -1
  30. package/dist/server.js +175 -18
  31. package/dist/server.js.map +1 -1
  32. package/dist/stdio.d.ts +24 -1
  33. package/dist/stdio.js +89 -12
  34. package/dist/stdio.js.map +1 -1
  35. package/dist/table-types.d.ts +84 -0
  36. package/dist/table-types.js +4 -0
  37. package/dist/table-types.js.map +1 -0
  38. package/dist/table.d.ts +54 -0
  39. package/dist/table.gen.d.ts +7 -0
  40. package/dist/table.gen.js +3755 -0
  41. package/dist/table.gen.js.map +1 -0
  42. package/dist/table.js +240 -0
  43. package/dist/table.js.map +1 -0
  44. package/dist/tools.d.ts +61 -47
  45. package/dist/tools.js +231 -705
  46. package/dist/tools.js.map +1 -1
  47. package/package.json +20 -10
  48. package/src/compact.ts +127 -0
  49. package/src/handlers/_common.ts +433 -0
  50. package/src/handlers/actions.ts +144 -0
  51. package/src/handlers/render.ts +90 -0
  52. package/src/handlers/routines.ts +152 -0
  53. package/src/handlers/sandboxes.ts +110 -0
  54. package/src/handlers/vision.ts +213 -0
  55. package/src/index.ts +36 -0
  56. package/src/main.ts +79 -7
  57. package/src/server.ts +225 -19
  58. package/src/stdio.ts +107 -10
  59. package/src/table-types.ts +88 -0
  60. package/src/table.gen.ts +3812 -0
  61. package/src/table.ts +304 -0
  62. package/src/tools.ts +310 -785
  63. package/table/core.mjs +73 -0
  64. package/table/requests.json +1151 -0
  65. package/table/table.json +3764 -0
  66. package/table/tools/actions.mjs +55 -0
  67. package/table/tools/infer.mjs +52 -0
  68. package/table/tools/platform.mjs +76 -0
  69. package/table/tools/render.mjs +126 -0
  70. package/table/tools/routines.mjs +70 -0
  71. package/table/tools/sandboxes.mjs +269 -0
  72. package/table/tools/vision.mjs +316 -0
  73. package/table/tools.mjs +92 -0
package/src/tools.ts CHANGED
@@ -1,52 +1,56 @@
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_.
1
+ // The stdio server's tools: the shared table (src/table.ts, the same tools the edge's /mcp serves) run through the
2
+ // TypeScript SDK, so each request gets the SDK's routing (node socket, sandbox URL or the edge), retries,
3
+ // idempotency keys, timeouts and typed errors. Pack actions can be added as direct tools.
5
4
 
6
5
  import {
7
- type ActionDescription,
8
- type ActStep,
6
+ actionsOps,
9
7
  type B3OS,
10
8
  B3OSError,
11
- type CrawlCreateRequest,
12
- type RunCreateRequest,
13
- type ScrapeRequest,
14
- type ScreenshotCreateRequest,
15
- type VideoCreateRequest,
9
+ inferOps,
10
+ keysOps,
11
+ limitsOps,
12
+ orgsOps,
13
+ projectsOps,
14
+ renderOps,
15
+ requestsOps,
16
+ routinesOps,
17
+ sandboxesOps,
18
+ usageOps,
19
+ vaultOps,
20
+ visionOps,
21
+ webhooksOps,
16
22
  } 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
- }
23
+ import type { Op } from "@b3os/sdk/core";
24
+ import {
25
+ type ContentBlock,
26
+ errorResult,
27
+ fromBase64,
28
+ type JobLike,
29
+ type JsonSchemaObject,
30
+ MCP_TOOLS,
31
+ type McpTableTool,
32
+ type PackTool,
33
+ packToolFromDescription,
34
+ previewFlags,
35
+ type RoutineTool,
36
+ routineToolFromDefinition,
37
+ runPackTool,
38
+ runRoutineTool,
39
+ runTool,
40
+ selectTools,
41
+ type ToolAnnotations,
42
+ type ToolContext,
43
+ type ToolIO,
44
+ type ToolRequest,
45
+ type ToolResult,
46
+ toBase64,
47
+ toolsFor,
48
+ } from "./table.ts";
49
+
50
+ export { compactSchema, detailFor } from "./compact.ts";
51
+
52
+ export type { ContentBlock, JsonSchemaObject, McpTableTool, ToolAnnotations, ToolContext, ToolResult };
53
+ export { errorResult, fromBase64, MCP_TOOLS, previewFlags, selectTools, toBase64 };
50
54
 
51
55
  export interface ToolDef {
52
56
  name: string;
@@ -54,734 +58,248 @@ export interface ToolDef {
54
58
  description: string;
55
59
  inputSchema: JsonSchemaObject;
56
60
  annotations: ToolAnnotations;
61
+ /** Where a tool beside the table comes from: a pack action (its ref) or a published routine (its name). */
62
+ source?: { kind: "action"; ref: string } | { kind: "routine"; name: string };
63
+ /** tools/list `_meta`: Claude Code's `anthropic/maxResultSizeChars` and `anthropic/requiresUserInteraction` (PD6). */
64
+ meta?: Readonly<Record<string, unknown>>;
57
65
  call(b3: B3OS, args: Record<string, unknown>, ctx: ToolContext): Promise<ToolResult>;
58
66
  }
59
67
 
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]`;
68
+ const OPS: ReadonlyMap<string, Op> = new Map(
69
+ [
70
+ actionsOps,
71
+ inferOps,
72
+ keysOps,
73
+ limitsOps,
74
+ orgsOps,
75
+ projectsOps,
76
+ renderOps,
77
+ requestsOps,
78
+ routinesOps,
79
+ sandboxesOps,
80
+ usageOps,
81
+ vaultOps,
82
+ visionOps,
83
+ webhooksOps,
84
+ ].flatMap((ns) => Object.values(ns as Record<string, Op>).map((op) => [op.id, op] as const)),
85
+ );
86
+
87
+ /** The table's requests through the SDK: by operationId, so routing, retries and idempotency are the SDK's. */
88
+ export function sdkIO(b3: B3OS, traceparent?: string): ToolIO {
89
+ // A message's `_meta.traceparent` (PD27): every request of the call carries it, as the caller's span.
90
+ const t = traceparent ? { traceparent } : {};
91
+ const io: ToolIO = {
92
+ async request(req: ToolRequest, signal?: AbortSignal): Promise<unknown> {
93
+ const op = OPS.get(req.operationId);
94
+ const bytes = req.accept === "bytes";
95
+ // The SDK's create: after a lost answer it looks the sandbox up by its metadata tag instead of creating a
96
+ // second one (sandboxes.yaml: look before retrying).
97
+ if (req.operationId === "sandboxesCreateSandbox" && req.bodyKind === "json") {
98
+ return b3.sandboxes.createSandbox(req.body as Parameters<B3OS["sandboxes"]["createSandbox"]>[0], {
99
+ signal,
100
+ ...t,
101
+ });
102
+ }
103
+ if (req.accept === "events" && op) {
104
+ const events: unknown[] = [];
105
+ for await (const ev of b3._stream<unknown>(op, { path: req.pathValues, query: req.query }, { signal, ...t }))
106
+ events.push(ev);
107
+ return events;
108
+ }
109
+ if (!op) {
110
+ return b3.request(
111
+ {
112
+ method: req.method as Op["method"],
113
+ path: req.path,
114
+ query: req.query,
115
+ ...(req.bodyKind === "none" ? {} : { body: req.body }),
116
+ ...(req.bodyKind === "raw" ? { bodyType: "bytes" as const } : {}),
117
+ },
118
+ { signal, ...t },
119
+ );
120
+ }
121
+ return b3._call(
122
+ op,
123
+ {
124
+ path: req.pathValues,
125
+ query: req.query,
126
+ ...(req.bodyKind === "none" ? {} : { body: req.body }),
127
+ ...(req.bodyKind === "raw" ? { bodyType: "bytes" as const } : {}),
128
+ },
129
+ { signal, ...t },
130
+ bytes ? "application/octet-stream" : "application/json",
131
+ bytes ? "bytes" : "auto",
132
+ );
133
+ },
134
+ async fetchBytes(url: string, signal?: AbortSignal) {
135
+ // render.fetchArtifact reads an artifact from the node's own route when this client reaches the node, so a
136
+ // same-host server never pulls the image back over the node's uplink through usercontent.
137
+ const got = await b3.render.fetchArtifact(url, signal ? { signal, ...t } : t).catch(() => undefined);
138
+ return got && { bytes: got.bytes, contentType: got.contentType ?? undefined };
139
+ },
140
+ async waitJob(job: JobLike, timeoutMs: number, signal: AbortSignal | undefined, onProgress) {
141
+ try {
142
+ return (await b3.jobs.wait<JobLike & { object: string }>(job as JobLike & { object: string }, {
143
+ timeoutMs,
144
+ signal,
145
+ ...t,
146
+ throwOnFailure: false,
147
+ onEvent: (ev) => {
148
+ const p = (ev as { progress?: { completed?: number; total?: number | null } }).progress;
149
+ if (p && typeof p.completed === "number") onProgress?.(p.completed, p.total ?? undefined);
150
+ },
151
+ })) as JobLike;
152
+ } catch (e) {
153
+ if (e instanceof B3OSError && e.code === "timeout")
154
+ return (await b3.jobs.get<JobLike & { object: string }>(job.id, { signal, ...t })) as JobLike;
155
+ throw e;
156
+ }
157
+ },
158
+ };
159
+ return io;
64
160
  }
65
161
 
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>;
162
+ const ioCache = new WeakMap<B3OS, ToolIO>();
163
+ function ioFor(b3: B3OS, ctx?: ToolContext): ToolIO {
164
+ if (ctx?.traceparent) return sdkIO(b3, ctx.traceparent);
165
+ let io = ioCache.get(b3);
166
+ if (!io) {
167
+ io = sdkIO(b3);
168
+ ioCache.set(b3, io);
70
169
  }
71
- return r;
170
+ return io;
72
171
  }
73
172
 
74
- function json(v: unknown): string {
75
- return JSON.stringify(v, null, 2);
173
+ function tableTool(t: McpTableTool): ToolDef {
174
+ return {
175
+ name: t.name,
176
+ title: t.title,
177
+ description: t.description,
178
+ inputSchema: t.inputSchema,
179
+ annotations: t.annotations,
180
+ ...(t.meta ? { meta: t.meta } : {}),
181
+ call: (b3, args, ctx) => runTool(t, args, ioFor(b3, ctx), ctx),
182
+ };
76
183
  }
77
184
 
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)}` }] };
185
+ /**
186
+ * The tools for these toolsets (`core` always, plus e.g. `routines`, `infer`; `all` for every one). Preview tools
187
+ * are left out unless their flag is in `flags` (the flags on for the caller's organization; selectTools).
188
+ */
189
+ export function tableTools(toolsets: readonly string[] = [], flags: readonly string[] = []): ToolDef[] {
190
+ return toolsFor(toolsets, flags).map(tableTool);
93
191
  }
94
192
 
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;
193
+ /** Servable tools for table rows a caller already selected (selectTools over MCP_TOOLS, or a test table). */
194
+ export function tableToolDefs(tools: readonly McpTableTool[]): ToolDef[] {
195
+ return tools.map(tableTool);
115
196
  }
116
197
 
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;
198
+ /** The core tool set, in a fixed order (deterministic tools/list for prompt caching); no preview tools. */
199
+ export const coreTools: readonly ToolDef[] = tableTools();
200
+
201
+ /** Which of a pack's tools to serve (`?effects=` and `?actions=` on /mcp, `--effects` and `--actions` on stdio). */
202
+ export interface PackToolFilter {
203
+ /** The most a served tool may do: `read` serves `pure` and `read` actions only. */
204
+ effects?: "pure" | "read" | "write" | "irreversible";
205
+ /**
206
+ * Action keys to serve. `io.b3os/github/create-issue` or `github/create-issue` names one pack's action; a bare
207
+ * key (`create-issue`) applies to every requested pack. A pack with no entry serves all its actions.
208
+ */
209
+ actions?: readonly string[];
129
210
  }
130
211
 
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>;
212
+ export interface PackToolsResult {
213
+ tools: ToolDef[];
214
+ /** One line per requested pack that serves no tools: not in the catalog, or its tool list failed. */
215
+ warnings: string[];
216
+ /** The requested packs those lines are about, as asked for. */
217
+ unresolved: string[];
218
+ /** How long the lists may be cached: the smallest `ttlMs` the node gave (300 s when none answered). */
219
+ ttlMs: number;
136
220
  }
137
221
 
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;
222
+ /** The node's default tool-list lifetime (actions.yaml PackTools.ttlMs). */
223
+ export const PACK_TOOLS_TTL_MS = 300_000;
224
+
225
+ function keysFor(id: string, short: string, actions: readonly string[] | undefined): string[] | undefined {
226
+ if (!actions?.length) return undefined;
227
+ const keys: string[] = [];
228
+ for (const a of actions) {
229
+ const i = a.lastIndexOf("/");
230
+ if (i < 0) keys.push(a);
231
+ else if (a.slice(0, i) === id || a.slice(0, i) === short || a.slice(0, i) === id.split("/")[1])
232
+ keys.push(a.slice(i + 1));
167
233
  }
234
+ return keys.length ? [...new Set(keys)] : undefined;
168
235
  }
169
236
 
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
- };
237
+ function problemText(e: unknown): string {
238
+ if (e instanceof B3OSError) return `${e.code}: ${e.message}`;
239
+ return e instanceof Error ? e.message : String(e);
240
+ }
381
241
 
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 });
242
+ /**
243
+ * The given packs' tools (`github`, or `io.b3os/github`), from one `GET /v1/actions/packs/{ns}/{name}/tools` per
244
+ * pack, all packs at once, named by the registry's `mcp_name` (R-actions-triggers-8). A pack that is not in the
245
+ * catalog, or whose list fails, serves nothing and gets a warning line instead of disappearing silently.
246
+ */
247
+ export async function loadPackTools(
248
+ b3: B3OS,
249
+ packs: readonly string[],
250
+ filter: PackToolFilter = {},
251
+ ): Promise<PackToolsResult> {
252
+ const lists = await Promise.all(
253
+ packs.map(async (want) => {
254
+ try {
255
+ const id = want.includes("/") ? want : await resolvePack(b3, want);
256
+ if (!id) return { want, error: "not in the catalog (actions_search finds packs by name)" };
257
+ const [ns, name] = id.split("/") as [string, string];
258
+ const keys = keysFor(id, want, filter.actions);
259
+ const list = await b3.actions.getPackTools(ns, name, {
260
+ ...(filter.effects ? { effects: filter.effects } : {}),
261
+ ...(keys ? { actions: keys.join(",") } : {}),
262
+ });
263
+ return { want, list };
264
+ } catch (e) {
265
+ return { want, error: problemText(e) };
425
266
  }
267
+ }),
268
+ );
269
+ const out: PackToolsResult = { tools: [], warnings: [], unresolved: [], ttlMs: PACK_TOOLS_TTL_MS };
270
+ let ttl: number | undefined;
271
+ for (const l of lists) {
272
+ if ("error" in l) {
273
+ out.unresolved.push(l.want);
274
+ out.warnings.push(`pack ${l.want} serves no tools: ${l.error}`);
275
+ continue;
426
276
  }
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,
277
+ if (typeof l.list.ttlMs === "number" && l.list.ttlMs > 0) ttl = Math.min(ttl ?? l.list.ttlMs, l.list.ttlMs);
278
+ for (const t of l.list.tools) {
279
+ out.tools.push(
280
+ fromPackTool(
281
+ {
282
+ name: t.name,
283
+ title: t.title,
284
+ description: t.description,
285
+ inputSchema: t.inputSchema as JsonSchemaObject,
286
+ annotations: { title: t.title, ...(t.annotations ?? {}) },
287
+ ref: t.ref,
288
+ },
289
+ t.effects,
290
+ ),
557
291
  );
558
292
  }
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
293
  }
294
+ if (ttl !== undefined) out.ttlMs = ttl;
782
295
  return out;
783
296
  }
784
297
 
298
+ /** One tool per action of the given packs; `loadPackTools` also says which packs served nothing. */
299
+ export async function packTools(b3: B3OS, packs: readonly string[], filter?: PackToolFilter): Promise<ToolDef[]> {
300
+ return (await loadPackTools(b3, packs, filter)).tools;
301
+ }
302
+
785
303
  async function resolvePack(b3: B3OS, short: string): Promise<string | undefined> {
786
304
  for await (const p of b3.actions.listPacks({ q: short, limit: 100 })) {
787
305
  if (p.id === short || p.id.endsWith(`/${short}`)) return p.id;
@@ -789,56 +307,63 @@ async function resolvePack(b3: B3OS, short: string): Promise<string | undefined>
789
307
  return undefined;
790
308
  }
791
309
 
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;
310
+ function fromPackTool(t: PackTool, effects?: string): ToolDef {
795
311
  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
- },
312
+ name: t.name,
313
+ title: t.title,
314
+ description: t.description,
315
+ inputSchema: t.inputSchema,
316
+ annotations: t.annotations as ToolAnnotations,
317
+ // Claude Code asks the user before a tool with this key runs: every direct pack tool whose effect class is
318
+ // irreversible (a payment, a sent message, a deletion; PD6).
319
+ ...(effects === "irreversible" ? { meta: { "anthropic/requiresUserInteraction": true } } : {}),
320
+ source: { kind: "action", ref: t.ref },
321
+ call: (b3, args, ctx) => runPackTool(t, args, ioFor(b3, ctx), ctx),
805
322
  };
806
323
  }
807
324
 
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);
325
+ /**
326
+ * One tool per published, active routine of the project: `names` lists routine names (or ids), or is `["all"]`.
327
+ * A routine that cannot be read is skipped.
328
+ */
329
+ export async function routineTools(b3: B3OS, names: readonly string[]): Promise<ToolDef[]> {
330
+ const wanted = names.includes("all") ? undefined : names;
331
+ const routines: Array<Record<string, unknown>> = [];
332
+ if (wanted) {
333
+ for (const n of wanted) {
334
+ const r = await b3.routines.getRoutine(n).catch(() => undefined);
335
+ if (r) routines.push(r as unknown as Record<string, unknown>);
336
+ }
337
+ } else {
338
+ for await (const r of b3.routines.listRoutines({ limit: 100 }))
339
+ routines.push(r as unknown as Record<string, unknown>);
817
340
  }
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]}=`;
341
+ const out: ToolDef[] = [];
342
+ for (const r of routines) {
343
+ const v = r.version as { number?: number } | undefined;
344
+ if (typeof r.name !== "string" || typeof v?.number !== "number") continue;
345
+ const ver = await b3.routines.getVersion(r.name, String(v.number)).catch(() => undefined);
346
+ const t = ver && routineToolFromDefinition(r, ver as unknown as Record<string, unknown>);
347
+ if (t) out.push(fromRoutineTool(t));
825
348
  }
826
349
  return out;
827
350
  }
828
351
 
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);
352
+ function fromRoutineTool(t: RoutineTool): ToolDef {
353
+ return {
354
+ name: t.name,
355
+ title: t.title,
356
+ description: t.description,
357
+ inputSchema: t.inputSchema,
358
+ annotations: t.annotations as ToolAnnotations,
359
+ source: { kind: "routine", name: t.routine },
360
+ call: (b3, args, ctx) => runRoutineTool(t, args, ioFor(b3, ctx), ctx),
361
+ };
362
+ }
363
+
364
+ /** A pack action's description (`GET /v1/actions/describe`) as a direct tool. */
365
+ export function actionTool(d: Parameters<typeof packToolFromDescription>[0]): ToolDef {
366
+ const t = packToolFromDescription(d);
367
+ if (!t) throw new B3OSError({ code: "invalid_response", status: null, detail: "the action has no MCP definition" });
368
+ return fromPackTool(t);
844
369
  }