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