@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
@@ -0,0 +1,152 @@
1
+ // Routines tool handlers of the MCP tool runtime (owner: routines, plan 1.2): what each routines tool in
2
+ // table/tools/routines.mjs sends and how it answers, beyond one plain request. src/table.ts merges every product's
3
+ // RUNNERS.
4
+
5
+ import type { JsonSchemaObject } from "../table-types.ts";
6
+ import {
7
+ buildRequest,
8
+ clip,
9
+ invalid,
10
+ isObj,
11
+ json,
12
+ type Obj,
13
+ type Runner,
14
+ requestFor,
15
+ startOrContinue,
16
+ text,
17
+ } from "./_common.ts";
18
+
19
+ const ms = (v: unknown) =>
20
+ typeof v === "number" ? (v >= 1000 ? `${(v / 1000).toFixed(2)} s` : `${+v.toPrecision(3)} ms`) : "";
21
+
22
+ /**
23
+ * A run as an agent reads it: the status line, where and why it failed, one line per step, then the output. The
24
+ * full run is the structured content.
25
+ */
26
+ export function runText(run: Obj): string {
27
+ const steps = Array.isArray(run.steps) ? run.steps.filter(isObj) : [];
28
+ const trigger = isObj(run.trigger) ? run.trigger : {};
29
+ const head = [`run ${run.id}: ${run.status}`];
30
+ if (run.version_number !== undefined) head.push(`v${run.version_number}`);
31
+ if (trigger.type) head.push(`trigger ${trigger.type}${trigger.id ? ` ${trigger.id}` : ""}`);
32
+ const timing = isObj(run.timing) ? run.timing : {};
33
+ if (timing.total_ms !== undefined) head.push(ms(timing.total_ms));
34
+ const lines = [head.join(", ")];
35
+ const err = isObj(run.error) ? run.error : undefined;
36
+ if (err) {
37
+ const at = typeof err.step === "string" ? err.step : steps.find((s) => s.status === "failed")?.id;
38
+ const stepErr = steps.find((s) => s.id === at)?.error;
39
+ const code = isObj(stepErr) && typeof stepErr.code === "string" ? stepErr.code : err.code;
40
+ const detail = isObj(stepErr) && typeof stepErr.detail === "string" ? stepErr.detail : err.detail;
41
+ lines.push(at ? `failed at step ${at}: ${code}: ${detail}` : `${err.code}: ${err.detail}`);
42
+ }
43
+ // An ephemeral run read after it ended kept its summary only: say so instead of listing no steps.
44
+ if (run.steps_kept === false) lines.push("steps: not kept (an ephemeral run keeps only its summary once it ends)");
45
+ else if (steps.length) {
46
+ lines.push("steps:");
47
+ for (const s of steps) {
48
+ const e = isObj(s.error) && typeof s.error.code === "string" ? ` ${s.error.code}` : "";
49
+ const tries = typeof s.attempt === "number" && s.attempt > 1 ? ` (attempt ${s.attempt})` : "";
50
+ const copied = s.replayed ? " (copied)" : "";
51
+ const waits = s.status === "waiting" && isObj(s.waiting_for) ? ` ${waitingFor(s.waiting_for)}` : "";
52
+ lines.push(` ${s.id} ${s.uses ?? ""} ${s.status}${waits}${e}${tries}${copied} ${ms(s.duration_ms)}`.trimEnd());
53
+ }
54
+ }
55
+ if (run.result !== undefined) lines.push(`output: ${json(run.result)}`);
56
+ return lines.join("\n");
57
+ }
58
+
59
+ /**
60
+ * What a waiting step waits for, in a few words: an event (and its match), a person's answer (the prompt's title;
61
+ * the routine sent them a link), or a signal, with the deadline.
62
+ */
63
+ function waitingFor(w: Obj): string {
64
+ const until = typeof w.until === "string" ? ` until ${w.until}` : "";
65
+ if (typeof w.event === "string") return `for event ${w.event}${isObj(w.match) ? ` ${json(w.match)}` : ""}${until}`;
66
+ if (w.token || isObj(w.prompt)) {
67
+ const title = isObj(w.prompt) && typeof w.prompt.title === "string" ? `: ${w.prompt.title}` : "";
68
+ const sig = typeof w.signal === "string" ? ` (signal ${w.signal}${w.token ? ", or its link" : ""})` : "";
69
+ return `for a person's answer${title}${sig}${until}`;
70
+ }
71
+ return typeof w.signal === "string" ? `for signal ${w.signal}${until}` : until.trim();
72
+ }
73
+
74
+ export const RUNNERS: Record<string, Runner> = {
75
+ async routine_get_run(tool, args, io, ctx) {
76
+ const run = await io.request(buildRequest(tool, args), ctx.signal);
77
+ if (!isObj(run)) return text(clip(json(run)));
78
+ return { ...text(clip(runText(run)), run), isError: run.status === "failed" };
79
+ },
80
+
81
+ async routine_validate(tool, args, io, ctx) {
82
+ let def: unknown = args.definition;
83
+ if (typeof def === "string") {
84
+ try {
85
+ def = JSON.parse(def);
86
+ } catch {
87
+ throw invalid("definition must be a JSON object (send YAML to PUT /v1/routines/{name} instead)", "/definition");
88
+ }
89
+ }
90
+ if (!isObj(def)) throw invalid("give definition: the routine as a JSON object", "/definition");
91
+ const v = await io.request(requestFor(tool.operationId, [], { body: def }), ctx.signal);
92
+ if (!isObj(v)) return text(clip(json(v)));
93
+ const diags = Array.isArray(v.diagnostics) ? v.diagnostics.filter(isObj) : [];
94
+ const lines = [v.valid ? `valid: ${v.steps ?? "?"} steps` : `not valid: ${diags.length} problems`];
95
+ for (const d of diags) lines.push(`${d.severity ?? "error"} ${d.pointer || "/"} ${d.code}: ${d.detail}`);
96
+ return text(clip(lines.join("\n")), v);
97
+ },
98
+
99
+ async routine_run(tool, args, io, ctx) {
100
+ if (!args.job_id && !args.routine) throw invalid("give routine (start a run) or job_id (continue one)", "/routine");
101
+ const run = await startOrContinue(tool, args, io, ctx);
102
+ const lines = [`run ${run.id}: ${run.status}`];
103
+ if (run.result !== undefined) lines.push(json(run.result));
104
+ const err = isObj(run.error) ? run.error : undefined;
105
+ if (err) lines.push(`${err.code}: ${err.detail}`);
106
+ return { ...text(clip(lines.join("\n")), run), isError: run.status === "failed" };
107
+ },
108
+ };
109
+
110
+ // ---------------------------------------------------------------------------------------------------------------
111
+ // Published routines as direct tools (`--routines digest,triage` or `all`, `/mcp?routines=...`): routine.schema.json
112
+ // names the tool routine_<name> with - mapped to _, its description is the definition's, its input schema the
113
+ // definition's `inputs`.
114
+
115
+ /** A routine exposed as its own tool. */
116
+ export interface RoutineTool {
117
+ name: string;
118
+ title: string;
119
+ description: string;
120
+ inputSchema: JsonSchemaObject;
121
+ annotations: Record<string, unknown>;
122
+ /** The routine's name (what the run is started with). */
123
+ routine: string;
124
+ }
125
+
126
+ const ROUTINE_TOOL_WAIT =
127
+ "The tool waits up to 50 s for the run, then returns its run_ id: continue with routine_run job_id.";
128
+
129
+ /** The tool for a routine (`GET /v1/routines/{routine}`) and its active version (`GET …/versions/{n}`). */
130
+ export function routineToolFromDefinition(routine: Obj, version: Obj): RoutineTool | undefined {
131
+ const name = typeof routine.name === "string" ? routine.name : undefined;
132
+ if (!name || routine.status === "paused") return undefined;
133
+ const def = isObj(version.definition) ? version.definition : {};
134
+ const inputs = isObj(def.inputs) ? def.inputs : undefined;
135
+ const schema: JsonSchemaObject =
136
+ inputs && (inputs.type === undefined || inputs.type === "object")
137
+ ? ({
138
+ ...inputs,
139
+ type: "object",
140
+ properties: isObj(inputs.properties) ? inputs.properties : {},
141
+ } as JsonSchemaObject)
142
+ : { type: "object", properties: {}, additionalProperties: false };
143
+ const text = String(def.description ?? routine.description ?? "").trim() || `Run the routine ${name}.`;
144
+ return {
145
+ name: `routine_${name.replace(/-/g, "_")}`.slice(0, 64),
146
+ title: `Routine ${name}`,
147
+ description: `${text} ${ROUTINE_TOOL_WAIT}`,
148
+ inputSchema: schema,
149
+ annotations: { title: `Routine ${name}`, readOnlyHint: false, openWorldHint: true },
150
+ routine: name,
151
+ };
152
+ }
@@ -0,0 +1,110 @@
1
+ // Sandboxes tool handlers of the MCP tool runtime (owner: sandboxes, plan 1.2): what each sandboxes tool in
2
+ // table/tools/sandboxes.mjs sends and how it answers, beyond one plain request. src/table.ts merges every product's
3
+ // RUNNERS.
4
+
5
+ import {
6
+ buildRequest,
7
+ clip,
8
+ invalid,
9
+ isObj,
10
+ json,
11
+ MAX_TEXT,
12
+ numArg,
13
+ type Obj,
14
+ type Runner,
15
+ text,
16
+ toBase64,
17
+ } from "./_common.ts";
18
+
19
+ export const RUNNERS: Record<string, Runner> = {
20
+ async sandbox_logs(tool, args, io, ctx) {
21
+ const events = (await io.request({ ...buildRequest(tool, args), accept: "events" }, ctx.signal)) as unknown;
22
+ const max = numArg(args, "max_chars", 50_000);
23
+ const procs = new Map<string, { stdout: string; stderr: string; exit?: Obj }>();
24
+ const of = (pid: unknown) => {
25
+ const k = String(pid ?? "?");
26
+ let p = procs.get(k);
27
+ if (!p) procs.set(k, (p = { stdout: "", stderr: "" }));
28
+ return p;
29
+ };
30
+ for (const e of Array.isArray(events) ? (events as Obj[]) : []) {
31
+ if (!isObj(e)) continue;
32
+ if (e.type === "log.stdout" && typeof e.data === "string") of(e.pid).stdout += e.data;
33
+ else if (e.type === "log.stderr" && typeof e.data === "string") of(e.pid).stderr += e.data;
34
+ else if (e.type === "process.exited") of(e.pid).exit = e;
35
+ }
36
+ const tail = (s: string) => (s.length > max ? `[... ${s.length - max} characters cut]\n${s.slice(-max)}` : s);
37
+ const parts: string[] = [];
38
+ for (const [pid, p] of procs) {
39
+ const x = p.exit;
40
+ const state = x
41
+ ? `exited ${x.exit_code ?? (x.signal ? `signal ${x.signal}` : "")}`.trimEnd()
42
+ : "running or no exit seen";
43
+ parts.push(`pid ${pid} (${state})`);
44
+ if (p.stdout) parts.push(`stdout:\n${tail(p.stdout)}`);
45
+ if (p.stderr) parts.push(`stderr:\n${tail(p.stderr)}`);
46
+ }
47
+ const structured = {
48
+ processes: [...procs].map(([pid, p]) => ({
49
+ pid: Number(pid) || pid,
50
+ stdout_chars: p.stdout.length,
51
+ stderr_chars: p.stderr.length,
52
+ ...(p.exit ? { exit_code: p.exit.exit_code ?? null, signal: p.exit.signal ?? null } : {}),
53
+ })),
54
+ };
55
+ return text(parts.length ? clip(parts.join("\n")) : "no output", structured);
56
+ },
57
+
58
+ async sandbox_create(tool, args, io, ctx) {
59
+ const s = (await io.request(buildRequest(tool, args), ctx.signal)) as Obj;
60
+ return text(`${s.id} ${s.status} (${s.vcpu} vCPU, ${s.memory_mib} MiB, until ${s.expires_at ?? "-"})`, s);
61
+ },
62
+
63
+ async sandbox_exec(tool, args, io, ctx) {
64
+ const cmd = args.cmd;
65
+ if (typeof cmd !== "string" && !(Array.isArray(cmd) && cmd.every((c) => typeof c === "string")))
66
+ throw invalid("cmd is a string or an array of strings", "/cmd");
67
+ const r = (await io.request(buildRequest(tool, args), ctx.signal)) as Obj;
68
+ if (args.background === true) return text(`started pid ${r.pid} (${r.status ?? "running"})`, r);
69
+ const out = [`exit ${r.exit_code ?? `signal ${r.signal}`}${r.timed_out ? " (timed out)" : ""}`];
70
+ if (r.stdout) out.push(`stdout:\n${clip(String(r.stdout), 60_000)}`);
71
+ if (r.stderr) out.push(`stderr:\n${clip(String(r.stderr), 30_000)}`);
72
+ return { ...text(out.join("\n"), r), isError: r.exit_code !== 0 };
73
+ },
74
+
75
+ async sandbox_read_file(tool, args, io, ctx) {
76
+ const path = String(args.path);
77
+ if (args.list === true) {
78
+ const l = (await io.request(buildRequest(tool, args), ctx.signal)) as { data?: Obj[] };
79
+ return text(
80
+ (l.data ?? [])
81
+ .map((e) => `${e.type === "directory" ? "d" : "-"} ${String(e.size).padStart(10)} ${e.path}`)
82
+ .join("\n"),
83
+ l,
84
+ );
85
+ }
86
+ const req = { ...buildRequest(tool, args), accept: "bytes" as const };
87
+ const got = await io.request(req, ctx.signal);
88
+ const bytes = got instanceof Uint8Array ? got : new TextEncoder().encode(typeof got === "string" ? got : json(got));
89
+ try {
90
+ const decoded = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
91
+ return text(clip(decoded, numArg(args, "max_chars", MAX_TEXT)), {
92
+ path,
93
+ bytes: bytes.byteLength,
94
+ encoding: "utf8",
95
+ });
96
+ } catch {
97
+ return text(toBase64(bytes), { path, bytes: bytes.byteLength, encoding: "base64" });
98
+ }
99
+ },
100
+
101
+ async sandbox_write_file(tool, args, io, ctx) {
102
+ const e = (await io.request(buildRequest(tool, args), ctx.signal)) as Obj;
103
+ return text(`wrote ${e.size} bytes to ${e.path}`, e);
104
+ },
105
+
106
+ async sandbox_delete(tool, args, io, ctx) {
107
+ const s = (await io.request(buildRequest(tool, args), ctx.signal)) as Obj;
108
+ return text(`${s.id} ${s.status}`, s);
109
+ },
110
+ };
@@ -0,0 +1,213 @@
1
+ // Vision tool handlers of the MCP tool runtime (owner: vision, plan 1.2): what each vision tool in
2
+ // table/tools/vision.mjs sends and how it answers, beyond one plain request. src/table.ts merges every product's
3
+ // RUNNERS.
4
+
5
+ import type { McpTableTool } from "../table-types.ts";
6
+ import {
7
+ buildRequest,
8
+ type ContentBlock,
9
+ clip,
10
+ invalid,
11
+ isObj,
12
+ json,
13
+ MAX_TEXT,
14
+ numArg,
15
+ type Obj,
16
+ pageReport,
17
+ type Runner,
18
+ requestFor,
19
+ startOrContinue,
20
+ type ToolContext,
21
+ type ToolIO,
22
+ type ToolResult,
23
+ text,
24
+ } from "./_common.ts";
25
+
26
+ /**
27
+ * The image block of a vision screenshot (`ScreenshotData` in vision.yaml: `format`, `width`, `height`,
28
+ * `data_base64`), or none when the value is not one.
29
+ */
30
+ export function screenshotBlock(shot: unknown): ContentBlock | undefined {
31
+ if (!isObj(shot) || typeof shot.data_base64 !== "string" || !shot.data_base64) return undefined;
32
+ const format = typeof shot.format === "string" ? shot.format : "";
33
+ if (!["jpeg", "png", "webp"].includes(format)) return undefined;
34
+ return { type: "image", data: shot.data_base64, mimeType: `image/${format}` };
35
+ }
36
+
37
+ /** A job with pages (a crawl, a batch): start or continue it, wait, then read its pages as Markdown. */
38
+ async function pagedJob(
39
+ kind: "crawl" | "batch",
40
+ tool: McpTableTool,
41
+ args: Obj,
42
+ io: ToolIO,
43
+ ctx: ToolContext,
44
+ ): Promise<ToolResult> {
45
+ const job = await startOrContinue(tool, args, io, ctx);
46
+ const prog = isObj(job.progress) ? job.progress : undefined;
47
+ const head = `${kind} ${job.id}: ${job.status}${prog ? ` (${prog.completed}/${prog.total ?? "?"} pages)` : ""}`;
48
+ if (job.status !== "succeeded" && job.status !== "running") return text(head, job);
49
+ const per = numArg(args, "max_chars_per_page", 4000);
50
+ const pagesOp = tool.continueWith?.pages;
51
+ const pages: string[] = [];
52
+ let cursor: string | undefined;
53
+ while (pagesOp && pages.length < 500) {
54
+ const page = (await io.request(
55
+ requestFor(pagesOp.operationId, [job.id], { query: { limit: 100, ...(cursor ? { cursor } : {}) } }),
56
+ ctx.signal,
57
+ )) as { data?: Obj[]; next_cursor?: string | null };
58
+ for (const p of page.data ?? []) {
59
+ const scrape = isObj(p.scrape) ? p.scrape : {};
60
+ const err = isObj(p.error) ? p.error : {};
61
+ pages.push(
62
+ `## ${p.url}\n${p.status === "succeeded" ? clip(String(scrape.markdown ?? ""), per) : `failed: ${err.detail ?? ""}`}`,
63
+ );
64
+ if (pages.length >= 500) break;
65
+ }
66
+ cursor = page.next_cursor ?? undefined;
67
+ if (!cursor) break;
68
+ }
69
+ return text(clip([head, ...pages].join("\n\n")), {
70
+ id: job.id,
71
+ status: job.status,
72
+ progress: job.progress,
73
+ pages: pages.length,
74
+ });
75
+ }
76
+
77
+ export const RUNNERS: Record<string, Runner> = {
78
+ async vision_scrape(tool, args, io, ctx) {
79
+ const page = (await io.request(buildRequest(tool, args), ctx.signal)) as Obj;
80
+ const max = numArg(args, "max_chars", MAX_TEXT);
81
+ const cache = isObj(page.cache) ? page.cache : {};
82
+ // XT-7: a wall, an error page or a warning leads the text under the response's own field names (render's
83
+ // screenshot text reads the same); a clean page adds nothing.
84
+ const report = pageReport(page);
85
+ const parts: string[] = [
86
+ ...(report ? [report] : []),
87
+ `${page.status_code} ${page.final_url} (${page.tier}, cache ${cache.state})`,
88
+ ];
89
+ const meta = isObj(page.metadata) ? page.metadata : {};
90
+ const title = typeof meta.title === "string" ? meta.title.trim() : "";
91
+ const md = typeof page.markdown === "string" ? page.markdown.trimStart() : "";
92
+ if (title && !md.startsWith(`# ${title}`)) parts.push(`# ${title}`);
93
+ for (const k of ["markdown", "text", "html", "raw_html"])
94
+ if (typeof page[k] === "string") parts.push(page[k] as string);
95
+ if (page.json !== undefined) parts.push(json(page.json));
96
+ if (Array.isArray(page.links) && page.links.length) parts.push(`Links:\n${page.links.join("\n")}`);
97
+ const content: ContentBlock[] = [{ type: "text", text: clip(parts.join("\n\n"), max) }];
98
+ const image = screenshotBlock(page.screenshot);
99
+ if (image) content.push(image);
100
+ const { markdown: _m, html: _h, raw_html: _r, text: _t, screenshot, ...rest } = page;
101
+ // The image travels as its block; the structured result keeps what describes it.
102
+ const shotInfo = isObj(screenshot)
103
+ ? { format: screenshot.format, width: screenshot.width, height: screenshot.height }
104
+ : undefined;
105
+ return { content, structuredContent: shotInfo ? { ...rest, screenshot: shotInfo } : rest };
106
+ },
107
+
108
+ async vision_map(tool, args, io, ctx) {
109
+ const r = (await io.request(buildRequest(tool, args), ctx.signal)) as Obj;
110
+ const links = (Array.isArray(r.links) ? r.links : []) as Array<{ url: string; title?: string }>;
111
+ const lines = links.map((l) => (l.title ? `${l.url} ${l.title}` : l.url));
112
+ return text(clip(`${links.length} URLs\n${lines.join("\n")}`), { url: r.url, links });
113
+ },
114
+
115
+ async vision_search(tool, args, io, ctx) {
116
+ const r = (await io.request(buildRequest(tool, args), ctx.signal)) as Obj;
117
+ const results = (Array.isArray(r.results) ? r.results : []) as Obj[];
118
+ const per = numArg(args, "max_chars_per_result", 4000);
119
+ const blocks = results.map((h) => {
120
+ const desc = typeof h.description === "string" ? `\n${h.description}` : "";
121
+ const head = `${h.position}. ${h.title}\n${h.url}${desc}`;
122
+ const scrape = isObj(h.scrape) ? h.scrape : undefined;
123
+ const err = isObj(h.error) ? h.error : undefined;
124
+ if (scrape) return `${head}\n\n${clip(String(scrape.markdown ?? ""), per)}`;
125
+ if (err) return `${head}\nnot scraped: ${String(err.detail ?? err.code ?? "")}`;
126
+ return head;
127
+ });
128
+ // The structured result keeps each result's link and error; the pages travel in the text.
129
+ const listed = results.map(({ scrape: _s, ...rest }) => rest);
130
+ const warnings = Array.isArray(r.warnings) ? r.warnings : [];
131
+ const head = `${results.length} results for "${String(r.query ?? "")}"`;
132
+ return text(clip([head, ...warnings.map(String), ...blocks].join("\n\n")), {
133
+ query: r.query,
134
+ results: listed,
135
+ ...(warnings.length ? { warnings } : {}),
136
+ });
137
+ },
138
+
139
+ vision_crawl(tool, args, io, ctx) {
140
+ if (!args.job_id && !args.url) throw invalid("give url (start a crawl) or job_id (continue one)", "/url");
141
+ return pagedJob("crawl", tool, args, io, ctx);
142
+ },
143
+
144
+ vision_batch(tool, args, io, ctx) {
145
+ if (!args.job_id && !(Array.isArray(args.urls) && args.urls.length))
146
+ throw invalid("give urls (start a batch) or job_id (continue one)", "/urls");
147
+ return pagedJob("batch", tool, args, io, ctx);
148
+ },
149
+
150
+ async vision_act(tool, args, io, ctx) {
151
+ const given = (Array.isArray(args.actions) ? args.actions : []) as Obj[];
152
+ const url = typeof args.url === "string" && args.url ? args.url : undefined;
153
+ const actions: Obj[] = [...(url ? [{ kind: "navigate", url }] : []), ...given];
154
+ if (!actions.length) throw invalid("give url or actions", "/actions");
155
+ if (!actions.some((s) => s.kind === "markdown" || s.kind === "screenshot")) actions.push({ kind: "markdown" });
156
+ let sid = typeof args.session_id === "string" && args.session_id ? args.session_id : undefined;
157
+ const created = !sid;
158
+ const profile = typeof args.profile === "string" && args.profile ? args.profile : undefined;
159
+ if (sid && profile) throw invalid("profile loads into a new session; leave out session_id or profile", "/profile");
160
+ if (!sid) {
161
+ const s = (await io.request(
162
+ requestFor("visionCreateSession", [], { body: { timeout_s: 600, ...(profile ? { profile } : {}) } }),
163
+ ctx.signal,
164
+ )) as Obj;
165
+ sid = String(s.id);
166
+ }
167
+ try {
168
+ const r = (await io.request(
169
+ requestFor(tool.operationId, [sid], {
170
+ body: { actions, continue_on_error: args.continue_on_error === true },
171
+ }),
172
+ ctx.signal,
173
+ )) as { ok?: boolean; results?: Obj[] };
174
+ const results = r.results ?? [];
175
+ const content: ContentBlock[] = [];
176
+ const lines: string[] = [`session ${sid}: ${r.ok ? "ok" : "an action failed"}`];
177
+ results.forEach((s, i) => {
178
+ const err = isObj(s.error) ? s.error : undefined;
179
+ lines.push(
180
+ `${i}. ${s.kind} ${s.status}${s.url ? ` ${s.url}` : ""}${err ? ` (${err.code}: ${err.detail})` : ""}`,
181
+ );
182
+ // A step's warnings (a screenshot cut at the 16,384 px limit, a Markdown read of the whole page) say
183
+ // what the image or text leaves out.
184
+ if (Array.isArray(s.warnings)) for (const w of s.warnings) lines.push(` warning: ${String(w)}`);
185
+ if (typeof s.markdown === "string" && s.markdown) lines.push(clip(s.markdown, 50_000));
186
+ if (s.value !== undefined) lines.push(json(s.value));
187
+ const image = screenshotBlock(s.screenshot);
188
+ if (image) {
189
+ content.push(image);
190
+ lines.push(` (the screenshot follows as image ${content.length})`);
191
+ }
192
+ });
193
+ content.unshift({ type: "text", text: clip(lines.join("\n")) });
194
+ return {
195
+ content,
196
+ structuredContent: {
197
+ session_id: sid,
198
+ ok: r.ok,
199
+ results: results.map(({ screenshot, ...x }) =>
200
+ isObj(screenshot)
201
+ ? { ...x, screenshot: { format: screenshot.format, width: screenshot.width, height: screenshot.height } }
202
+ : x,
203
+ ),
204
+ },
205
+ isError: !r.ok,
206
+ };
207
+ } finally {
208
+ if (created && args.keep_session !== true) {
209
+ await io.request(requestFor("visionCloseSession", [sid]), undefined).catch(() => undefined);
210
+ }
211
+ }
212
+ },
213
+ };
package/src/index.ts CHANGED
@@ -3,6 +3,7 @@
3
3
 
4
4
  export {
5
5
  INSTRUCTIONS,
6
+ instructionsWith,
6
7
  type JsonRpcRequest,
7
8
  type JsonRpcResponse,
8
9
  LEGACY_VERSIONS,
@@ -13,15 +14,50 @@ export {
13
14
  SERVER_INFO,
14
15
  } from "./server.ts";
15
16
  export { defaultClient, type StdioOptions, serveStdio, storedLogin } from "./stdio.ts";
17
+ export {
18
+ buildRequest,
19
+ checkArgs,
20
+ findTool,
21
+ type HttpIOOptions,
22
+ httpIO,
23
+ type JobLike,
24
+ MCP_INSTRUCTIONS,
25
+ MCP_OPERATIONS,
26
+ MCP_TOOLS,
27
+ type McpTableTool,
28
+ type PackTool,
29
+ packToolFromDescription,
30
+ previewFlags,
31
+ type RoutineTool,
32
+ requestFor,
33
+ routineToolFromDefinition,
34
+ runPackTool,
35
+ runRoutineTool,
36
+ runTool,
37
+ selectTools,
38
+ ToolCallError,
39
+ type ToolIO,
40
+ type ToolRequest,
41
+ toolError,
42
+ toolsets,
43
+ toolsFor,
44
+ } from "./table.ts";
16
45
  export {
17
46
  actionTool,
18
47
  type ContentBlock,
19
48
  coreTools,
20
49
  errorResult,
21
50
  type JsonSchemaObject,
51
+ loadPackTools,
52
+ PACK_TOOLS_TTL_MS,
53
+ type PackToolFilter,
54
+ type PackToolsResult,
22
55
  packTools,
56
+ routineTools,
57
+ sdkIO,
23
58
  type ToolAnnotations,
24
59
  type ToolContext,
25
60
  type ToolDef,
26
61
  type ToolResult,
62
+ tableTools,
27
63
  } from "./tools.ts";
package/src/main.ts CHANGED
@@ -1,25 +1,97 @@
1
- // `b3os-mcp [--packs github,slack]`: the stdio entry point MCP clients start.
1
+ // `b3os-mcp [--packs github,slack] [--effects read] [--actions github/create-issue]`: the stdio entry point MCP
2
+ // clients start.
2
3
 
4
+ import { SERVER_INFO } from "./server.ts";
3
5
  import { serveStdio } from "./stdio.ts";
6
+ import { toolsets as toolsetNames } from "./table.ts";
7
+ import type { PackToolFilter } from "./tools.ts";
8
+
9
+ const EFFECTS = ["pure", "read", "write", "irreversible"] as const;
10
+
11
+ const list = (s: string | undefined) =>
12
+ (s ?? "")
13
+ .split(",")
14
+ .map((x) => x.trim())
15
+ .filter(Boolean);
4
16
 
5
17
  export async function main(argv: string[]): Promise<number> {
6
18
  let packs: string[] | undefined;
19
+ let routines: string[] | undefined;
20
+ let toolsets: string[] | undefined;
21
+ let effects: string | undefined;
22
+ let actions: string[] | undefined;
23
+ let preview: string[] | undefined;
24
+ let only: string[] | undefined;
25
+ let detail: string | undefined;
7
26
  for (let i = 0; i < argv.length; i++) {
8
27
  const a = argv[i] as string;
9
- if (a === "--packs") packs = (argv[++i] ?? "").split(",").filter(Boolean);
10
- else if (a.startsWith("--packs=")) packs = a.slice(8).split(",").filter(Boolean);
28
+ if (a === "--packs") packs = list(argv[++i]);
29
+ else if (a.startsWith("--packs=")) packs = list(a.slice(8));
30
+ else if (a === "--routines") routines = list(argv[++i]);
31
+ else if (a.startsWith("--routines=")) routines = list(a.slice(11));
32
+ else if (a === "--toolsets") toolsets = list(argv[++i]);
33
+ else if (a.startsWith("--toolsets=")) toolsets = list(a.slice(11));
34
+ else if (a === "--effects") effects = argv[++i];
35
+ else if (a.startsWith("--effects=")) effects = a.slice(10);
36
+ else if (a === "--actions") actions = list(argv[++i]);
37
+ else if (a.startsWith("--actions=")) actions = list(a.slice(10));
38
+ else if (a === "--preview") preview = list(argv[++i]);
39
+ else if (a.startsWith("--preview=")) preview = list(a.slice(10));
40
+ else if (a === "--tools") only = list(argv[++i]);
41
+ else if (a.startsWith("--tools=")) only = list(a.slice(8));
42
+ else if (a === "--detail") detail = argv[++i];
43
+ else if (a.startsWith("--detail=")) detail = a.slice(9);
11
44
  else if (a === "--help" || a === "-h") {
12
45
  process.stderr.write(
13
- "usage: b3os-mcp [--packs github,slack]\n" +
14
- "Serves the B3OS MCP tools over stdio. Credentials: B3OS_API_KEY, else the b3os login token.\n",
46
+ `usage: b3os-mcp [--packs github,slack] [--routines digest,triage|all] [--toolsets ${toolsetNames()
47
+ .filter((s) => s !== "core")
48
+ .join(",")}|all]\n` +
49
+ "Serves the B3OS MCP tools over stdio: the core tools, plus the actions of --packs, the published\n" +
50
+ "routines of --routines as routine_<name> tools and the tools of --toolsets (also B3OS_MCP_PACKS,\n" +
51
+ "B3OS_MCP_ROUTINES, B3OS_MCP_TOOLSETS). --effects pure|read|write|irreversible serves only pack tools\n" +
52
+ "that do at most that; --actions github/create-issue,slack/post-message serves only those actions of\n" +
53
+ "their packs (a bare key applies to every pack; B3OS_MCP_EFFECTS, B3OS_MCP_ACTIONS). --preview\n" +
54
+ "flag,... also lists the tools of preview operations behind those feature flags (B3OS_MCP_PREVIEW);\n" +
55
+ "the API answers 404 feature_not_enabled unless the flag is on for your organization. --tools\n" +
56
+ "vision_scrape,sandbox_exec lists and serves only those tools (B3OS_MCP_TOOLS). tools/list sends compact\n" +
57
+ "schemas (types, enums, required; a refused call quotes the full description); --detail full sends the\n" +
58
+ "full ones (B3OS_MCP_DETAIL). Credentials: B3OS_API_KEY, else the b3os login token.\n",
15
59
  );
16
60
  return 0;
17
61
  } else if (a === "--version") {
18
- process.stdout.write("b3os-mcp 0.0.1\n");
62
+ process.stdout.write(`b3os-mcp ${SERVER_INFO.version}\n`);
19
63
  return 0;
64
+ } else if (a.startsWith("-")) {
65
+ // An MCP client starts this process, so a typo must not stop it; say so where its log shows stderr.
66
+ process.stderr.write(
67
+ `b3os-mcp: ignoring ${a.split("=")[0]}, which is not an option (b3os-mcp --help lists them)\n`,
68
+ );
20
69
  }
21
70
  }
22
- await serveStdio({ packs: packs ?? process.env.B3OS_MCP_PACKS?.split(",").filter(Boolean) });
71
+ effects ??= process.env.B3OS_MCP_EFFECTS || undefined;
72
+ if (effects !== undefined && !(EFFECTS as readonly string[]).includes(effects)) {
73
+ process.stderr.write(`b3os-mcp: --effects must be one of ${EFFECTS.join(", ")} (got ${effects})\n`);
74
+ return 2;
75
+ }
76
+ actions ??= list(process.env.B3OS_MCP_ACTIONS);
77
+ detail ??= process.env.B3OS_MCP_DETAIL || undefined;
78
+ if (detail !== undefined && detail !== "full" && detail !== "compact") {
79
+ process.stderr.write(`b3os-mcp: --detail must be compact or full (got ${detail})\n`);
80
+ return 2;
81
+ }
82
+ const packFilter: PackToolFilter = {
83
+ ...(effects ? { effects: effects as PackToolFilter["effects"] } : {}),
84
+ ...(actions.length ? { actions } : {}),
85
+ };
86
+ await serveStdio({
87
+ packFilter,
88
+ packs: packs ?? list(process.env.B3OS_MCP_PACKS),
89
+ routines: routines ?? list(process.env.B3OS_MCP_ROUTINES),
90
+ toolsets: toolsets ?? list(process.env.B3OS_MCP_TOOLSETS),
91
+ flags: preview ?? list(process.env.B3OS_MCP_PREVIEW),
92
+ only: only ?? list(process.env.B3OS_MCP_TOOLS),
93
+ ...(detail ? { detail: detail as "compact" | "full" } : {}),
94
+ });
23
95
  return 0;
24
96
  }
25
97