@b3os/mcp 0.2.2 → 0.2.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.
- package/README.md +7 -4
- package/dist/handlers/_common.d.ts +13 -0
- package/dist/handlers/_common.js +12 -0
- package/dist/handlers/_common.js.map +1 -1
- package/dist/handlers/platform.js +15 -3
- package/dist/handlers/platform.js.map +1 -1
- package/dist/handlers/render.js +25 -0
- package/dist/handlers/render.js.map +1 -1
- package/dist/handlers/routines.js +21 -0
- package/dist/handlers/routines.js.map +1 -1
- package/dist/handlers/sandboxes.js +232 -15
- package/dist/handlers/sandboxes.js.map +1 -1
- package/dist/handlers/vision.d.ts +1 -6
- package/dist/handlers/vision.js +1 -13
- package/dist/handlers/vision.js.map +1 -1
- package/dist/server.d.ts +4 -0
- package/dist/server.js +4 -1
- package/dist/server.js.map +1 -1
- package/dist/stdio.d.ts +8 -0
- package/dist/stdio.js +18 -1
- package/dist/stdio.js.map +1 -1
- package/dist/table.gen.js +899 -2
- package/dist/table.gen.js.map +1 -1
- package/package.json +2 -2
- package/src/handlers/_common.ts +16 -0
- package/src/handlers/platform.ts +20 -3
- package/src/handlers/render.ts +26 -0
- package/src/handlers/routines.ts +22 -0
- package/src/handlers/sandboxes.ts +259 -11
- package/src/handlers/vision.ts +1 -11
- package/src/server.ts +7 -1
- package/src/stdio.ts +21 -1
- package/src/table.gen.ts +916 -2
- package/table/requests.json +227 -0
- package/table/table.json +944 -25
- package/table/tools/agents.mjs +3 -1
- package/table/tools/render.mjs +39 -0
- package/table/tools/routines.mjs +18 -0
- package/table/tools/sandboxes.mjs +167 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@b3os/mcp",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.3",
|
|
4
4
|
"description": "B3OS MCP server over stdio, and the shared MCP tool table both B3OS MCP servers serve: vision, render, infer, sandboxes, routines and actions as tools.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"type": "module",
|
|
@@ -49,7 +49,7 @@
|
|
|
49
49
|
"gen:check": "node scripts/gen-table.mjs --check"
|
|
50
50
|
},
|
|
51
51
|
"dependencies": {
|
|
52
|
-
"@b3os/sdk": "0.2.
|
|
52
|
+
"@b3os/sdk": "0.2.3"
|
|
53
53
|
},
|
|
54
54
|
"devDependencies": {
|
|
55
55
|
"@types/node": "24.19.2",
|
package/src/handlers/_common.ts
CHANGED
|
@@ -23,6 +23,11 @@ export interface ToolContext {
|
|
|
23
23
|
traceparent?: string;
|
|
24
24
|
/** Reports progress on long tools (MCP notifications/progress when the client sent a progressToken). */
|
|
25
25
|
progress?: (completed: number, total?: number, message?: string) => void;
|
|
26
|
+
/**
|
|
27
|
+
* Saves bytes to a local file and says where (render_screenshot's save_to). Only a server on the user's machine
|
|
28
|
+
* has it (the stdio server, src/stdio.ts); a tool given save_to without it refuses.
|
|
29
|
+
*/
|
|
30
|
+
saveFile?: (path: string, bytes: Uint8Array) => Promise<{ saved_to: string; bytes: number }>;
|
|
26
31
|
}
|
|
27
32
|
|
|
28
33
|
/** One API request a tool makes. `path` is built and encoded; `pathValues` are the raw values in template order. */
|
|
@@ -174,6 +179,17 @@ export function pageReport(answer: unknown): string {
|
|
|
174
179
|
return [...(head.length ? [head.join(" · ")] : []), ...warnings].join("\n");
|
|
175
180
|
}
|
|
176
181
|
|
|
182
|
+
/**
|
|
183
|
+
* The image block of a screenshot in vision's `ScreenshotData` shape (vision.yaml: `format`, `width`, `height`,
|
|
184
|
+
* `data_base64`; a desktop's screenshot has it too), or none when the value is not one.
|
|
185
|
+
*/
|
|
186
|
+
export function screenshotBlock(shot: unknown): ContentBlock | undefined {
|
|
187
|
+
if (!isObj(shot) || typeof shot.data_base64 !== "string" || !shot.data_base64) return undefined;
|
|
188
|
+
const format = typeof shot.format === "string" ? shot.format : "";
|
|
189
|
+
if (!["jpeg", "png", "webp"].includes(format)) return undefined;
|
|
190
|
+
return { type: "image", data: shot.data_base64, mimeType: `image/${format}` };
|
|
191
|
+
}
|
|
192
|
+
|
|
177
193
|
/** At most `max` characters, cut after a sentence when one ends past a third of the way. */
|
|
178
194
|
export function sentence(t: string, max: number): string {
|
|
179
195
|
if (t.length <= max) return t;
|
package/src/handlers/platform.ts
CHANGED
|
@@ -224,9 +224,16 @@ function traceLines(t: TraceRow, partial: boolean): string[] {
|
|
|
224
224
|
|
|
225
225
|
/** A span of a trace in a line or two: number, offset, duration, kind, operation, status, request id, then what it
|
|
226
226
|
* called (model, tokens, time to first token, tools chosen) and its error. */
|
|
227
|
-
function spanLines(
|
|
227
|
+
function spanLines(
|
|
228
|
+
s: Obj,
|
|
229
|
+
n: number,
|
|
230
|
+
call: Obj | undefined,
|
|
231
|
+
manySandboxes: boolean,
|
|
232
|
+
parent: number | undefined,
|
|
233
|
+
): string[] {
|
|
228
234
|
const off = typeof s.offset_ms === "number" ? `+${ms(s.offset_ms)}` : "";
|
|
229
235
|
const facts: string[] = [];
|
|
236
|
+
if (parent) facts.push(`made by #${parent}`);
|
|
230
237
|
if (call && typeof call.model === "string") facts.push(call.model);
|
|
231
238
|
const usage = usageOf(s.usage);
|
|
232
239
|
const tokens = isObj(call?.tokens) ? call.tokens : undefined;
|
|
@@ -586,12 +593,21 @@ export const RUNNERS: Record<string, Runner> = {
|
|
|
586
593
|
const window = spans.slice(from - 1, from - 1 + max);
|
|
587
594
|
const to = from - 1 + window.length;
|
|
588
595
|
const manySandboxes = new Set(spans.map((s) => s.sandbox_id).filter(Boolean)).size > 1;
|
|
596
|
+
// A span made for another span of the trace (an MCP product tool's request) names that span's number.
|
|
597
|
+
const numberOf = new Map<string, number>();
|
|
598
|
+
spans.forEach((s, i) => {
|
|
599
|
+
if (typeof s.span_id === "string" && !numberOf.has(s.span_id)) numberOf.set(s.span_id, i + 1);
|
|
600
|
+
});
|
|
601
|
+
const parentOf = (s: Obj) =>
|
|
602
|
+
typeof s.parent_span_id === "string" && s.parent_span_id !== s.span_id
|
|
603
|
+
? numberOf.get(s.parent_span_id)
|
|
604
|
+
: undefined;
|
|
589
605
|
if (window.length) {
|
|
590
606
|
lines.push(
|
|
591
|
-
`spans ${from}-${to} of ${spans.length} in start order (offset from the first call, duration${trace.nested ===
|
|
607
|
+
`spans ${from}-${to} of ${spans.length} in start order (offset from the first call, duration${trace.nested === true ? "; a call made for another says which" : ""}):`,
|
|
592
608
|
);
|
|
593
609
|
window.forEach((s, i) => {
|
|
594
|
-
lines.push(...spanLines(s, from + i, calls.get(String(s.request_id)), manySandboxes));
|
|
610
|
+
lines.push(...spanLines(s, from + i, calls.get(String(s.request_id)), manySandboxes, parentOf(s)));
|
|
595
611
|
});
|
|
596
612
|
} else lines.push(`no spans from #${from}: the trace has ${spans.length}`);
|
|
597
613
|
const rest: string[] = [];
|
|
@@ -623,6 +639,7 @@ export const RUNNERS: Record<string, Runner> = {
|
|
|
623
639
|
error_code: s.error_code ?? null,
|
|
624
640
|
offset_ms: s.offset_ms,
|
|
625
641
|
duration_ms: s.duration_ms,
|
|
642
|
+
...(parentOf(s) ? { parent: parentOf(s) } : {}),
|
|
626
643
|
usage: s.usage,
|
|
627
644
|
...(calls.get(String(s.request_id))?.model ? { model: calls.get(String(s.request_id))?.model } : {}),
|
|
628
645
|
})),
|
package/src/handlers/render.ts
CHANGED
|
@@ -156,6 +156,32 @@ export const RUNNERS: Record<string, Runner> = {
|
|
|
156
156
|
return { content, structuredContent: shot };
|
|
157
157
|
},
|
|
158
158
|
|
|
159
|
+
// render_screenshot_file (the render toolset): the same capture, saved to a file on the user's machine by the
|
|
160
|
+
// local server, answered with the path, size and URL and never the image (about 100 KB of base64 the model would
|
|
161
|
+
// carry). render_screenshot stays as it is: loop-v2 pins its definition (test/pinned.test.ts).
|
|
162
|
+
async render_screenshot_file(tool, args, io, ctx) {
|
|
163
|
+
if (!args.url && !args.html) throw invalid("give url or html", "/url");
|
|
164
|
+
if (typeof args.path !== "string" || !args.path) throw invalid("give path: the file to save the image to", "/path");
|
|
165
|
+
const shot = (await io.request(buildRequest(tool, args), ctx.signal)) as Obj;
|
|
166
|
+
const arts = (Array.isArray(shot.artifacts) ? shot.artifacts : []) as Obj[];
|
|
167
|
+
const url = typeof arts[0]?.url === "string" ? (arts[0].url as string) : undefined;
|
|
168
|
+
// A server that cannot write files (the hosted /mcp) still took the screenshot: it says so, with the URL.
|
|
169
|
+
if (!ctx.saveFile)
|
|
170
|
+
return text(
|
|
171
|
+
`${screenshotText(shot, url)}\nnot saved: only the local server (npx @b3os/mcp, b3os mcp serve) writes files; download the URL`,
|
|
172
|
+
{ ...shot, saved_to: null },
|
|
173
|
+
);
|
|
174
|
+
const got = url && io.fetchBytes ? await io.fetchBytes(url, ctx.signal).catch(() => undefined) : undefined;
|
|
175
|
+
if (!got) throw invalid("the image could not be downloaded to save it; render_screenshot returns its URL", "/path");
|
|
176
|
+
const saved = await ctx.saveFile(args.path, got.bytes).catch((e: unknown) => {
|
|
177
|
+
throw invalid((e as Error).message, "/path");
|
|
178
|
+
});
|
|
179
|
+
return text(`${screenshotText(shot, url)}\nsaved_to ${saved.saved_to} (${saved.bytes} bytes)`, {
|
|
180
|
+
...shot,
|
|
181
|
+
...saved,
|
|
182
|
+
});
|
|
183
|
+
},
|
|
184
|
+
|
|
159
185
|
async render_inspect(tool, args, io, ctx) {
|
|
160
186
|
if (!args.url === !args.video_id) throw invalid("give url or video_id, not both", "/url");
|
|
161
187
|
const ins = (await io.request(buildRequest(tool, args), ctx.signal)) as Obj;
|
package/src/handlers/routines.ts
CHANGED
|
@@ -246,6 +246,28 @@ export const RUNNERS: Record<string, Runner> = {
|
|
|
246
246
|
return text(clip(lines.join("\n")), v);
|
|
247
247
|
},
|
|
248
248
|
|
|
249
|
+
async routine_publish(tool, args, io, ctx) {
|
|
250
|
+
let def: unknown = args.definition;
|
|
251
|
+
if (typeof def === "string") {
|
|
252
|
+
try {
|
|
253
|
+
def = JSON.parse(def);
|
|
254
|
+
} catch {
|
|
255
|
+
throw invalid("definition must be a JSON object (the routine's YAML as JSON)", "/definition");
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
if (!isObj(def)) throw invalid("give definition: the routine as a JSON object", "/definition");
|
|
259
|
+
const name = typeof args.routine === "string" && args.routine ? args.routine : def.name;
|
|
260
|
+
if (typeof name !== "string" || !name)
|
|
261
|
+
throw invalid("give the routine's name in definition.name", "/definition/name");
|
|
262
|
+
const r = await io.request(requestFor(tool.operationId, [name], { body: def }), ctx.signal);
|
|
263
|
+
if (!isObj(r)) return text(clip(json(r)));
|
|
264
|
+
const v = isObj(r.version) ? r.version : {};
|
|
265
|
+
return text(
|
|
266
|
+
`published ${r.name ?? name} (${r.id ?? "?"}) version ${v.number ?? "?"}: run it with routine_run, routine ${r.name ?? name}`,
|
|
267
|
+
r,
|
|
268
|
+
);
|
|
269
|
+
},
|
|
270
|
+
|
|
249
271
|
async routine_run(tool, args, io, ctx) {
|
|
250
272
|
if (!args.job_id && !args.routine) throw invalid("give routine (start a run) or job_id (continue one)", "/routine");
|
|
251
273
|
const run = await startOrContinue(tool, args, io, ctx);
|
|
@@ -1,21 +1,273 @@
|
|
|
1
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
|
|
3
|
-
// RUNNERS.
|
|
2
|
+
// table/tools/sandboxes.mjs sends and how it answers, beyond one plain request, the desktop toolset's included
|
|
3
|
+
// (B3-7326). src/table.ts merges every product's RUNNERS.
|
|
4
4
|
|
|
5
5
|
import {
|
|
6
6
|
buildRequest,
|
|
7
|
+
type ContentBlock,
|
|
7
8
|
clip,
|
|
9
|
+
int,
|
|
8
10
|
invalid,
|
|
9
11
|
isObj,
|
|
10
12
|
json,
|
|
13
|
+
listOf,
|
|
11
14
|
MAX_TEXT,
|
|
15
|
+
ms,
|
|
16
|
+
nextCursor,
|
|
12
17
|
numArg,
|
|
13
18
|
type Obj,
|
|
14
19
|
type Runner,
|
|
20
|
+
requestFor,
|
|
21
|
+
screenshotBlock,
|
|
22
|
+
ToolCallError,
|
|
23
|
+
type ToolResult,
|
|
15
24
|
text,
|
|
16
25
|
toBase64,
|
|
17
26
|
} from "./_common.ts";
|
|
18
27
|
|
|
28
|
+
/** A `cmd` argument is a shell line or an argv of strings. */
|
|
29
|
+
function checkCmd(cmd: unknown): void {
|
|
30
|
+
if (typeof cmd !== "string" && !(Array.isArray(cmd) && cmd.every((c) => typeof c === "string")))
|
|
31
|
+
throw invalid("cmd is a string or an array of strings", "/cmd");
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** An exec answer as a model reads it (sandbox_exec, desktop_run): the exit code, then stdout and stderr. */
|
|
35
|
+
function execResult(args: Obj, r: Obj, extra?: Obj): ToolResult {
|
|
36
|
+
const structured = extra ? { ...r, ...extra } : r;
|
|
37
|
+
if (args.background === true) return text(`started pid ${r.pid} (${r.status ?? "running"})`, structured);
|
|
38
|
+
const out = [`exit ${r.exit_code ?? `signal ${r.signal}`}${r.timed_out ? " (timed out)" : ""}`];
|
|
39
|
+
if (r.stdout) out.push(`stdout:\n${clip(String(r.stdout), 60_000)}`);
|
|
40
|
+
if (r.stderr) out.push(`stderr:\n${clip(String(r.stderr), 30_000)}`);
|
|
41
|
+
return { ...text(out.join("\n"), structured), isError: r.exit_code !== 0 };
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** One sandbox on one line: id, status, size and expiry. */
|
|
45
|
+
const sandboxLine = (s: Obj) =>
|
|
46
|
+
`${s.id} ${s.status} (${s.vcpu} vCPU, ${s.memory_mib} MiB, until ${s.expires_at ?? "-"})`;
|
|
47
|
+
|
|
48
|
+
// ---------------------------------------------------------------------------------------------------------------
|
|
49
|
+
// The desktop toolset (B3-7326, research/desk-v0.md §2): desktops are sandboxes of the `desktop` template.
|
|
50
|
+
|
|
51
|
+
/** The template desktop_create starts and desktop_list keeps (its `defaults` in table/tools/sandboxes.mjs). */
|
|
52
|
+
const DESKTOP_TEMPLATE = "desktop";
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* desktop_act's defaults (research/desk-v0.md §2, the MCP defaults): a screenshot after every call, JPEG at 80,
|
|
56
|
+
* taken once the screen has been still for 80 ms or after 1,000 ms. The API's own default is neither.
|
|
57
|
+
*/
|
|
58
|
+
const ACT_SCREENSHOT: Readonly<Obj> = { format: "jpeg", quality: 80 };
|
|
59
|
+
const ACT_SETTLE: Readonly<Obj> = { quiet_ms: 80, max_ms: 1000 };
|
|
60
|
+
|
|
61
|
+
/** desktop_list reads at most this many pages of 100 sandboxes (the list has no template filter). */
|
|
62
|
+
const LIST_PAGES = 10;
|
|
63
|
+
|
|
64
|
+
const isDesktop = (s: Obj) => (isObj(s.template) ? s.template.name : s.template) === DESKTOP_TEMPLATE;
|
|
65
|
+
|
|
66
|
+
/** desktop_act's `screenshot` or `settle` as the API field: `false` is none, an object goes as given, else dflt. */
|
|
67
|
+
function option(v: unknown, dflt: Readonly<Obj>): Obj | undefined {
|
|
68
|
+
if (v === false) return undefined;
|
|
69
|
+
return isObj(v) ? v : { ...dflt };
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** The bytes a base64 string holds. */
|
|
73
|
+
const b64Bytes = (s: string) =>
|
|
74
|
+
Math.max(0, Math.floor((s.length * 3) / 4) - (s.endsWith("==") ? 2 : s.endsWith("=") ? 1 : 0));
|
|
75
|
+
|
|
76
|
+
/** A screenshot without its image data, for the text and structured result (the image travels as its block). */
|
|
77
|
+
function shotInfo(shot: Obj): Obj {
|
|
78
|
+
const data = typeof shot.data_base64 === "string" ? shot.data_base64 : "";
|
|
79
|
+
return { format: shot.format, width: shot.width, height: shot.height, bytes: b64Bytes(data) };
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const shotLine = (i: Obj) => `screenshot ${i.width}x${i.height} ${i.format}, ${int(Number(i.bytes) || 0)} bytes`;
|
|
83
|
+
|
|
84
|
+
/** Exec answered 409 sandbox_not_running: the desktop is paused (or stopped), and the command did not start. */
|
|
85
|
+
function notRunning(e: unknown): boolean {
|
|
86
|
+
const err = e as { code?: unknown; status?: unknown } | null;
|
|
87
|
+
return err?.code === "sandbox_not_running" && err?.status === 409;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** A limit's count against its maximum, when the answer has one. */
|
|
91
|
+
function count(v: unknown): { running: number; limit: number } | undefined {
|
|
92
|
+
return isObj(v) && typeof v.running === "number" && typeof v.limit === "number"
|
|
93
|
+
? { running: v.running, limit: v.limit }
|
|
94
|
+
: undefined;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* desktop_room's text from a `SandboxCapacity` answer: how many more desktops fit now and which limit binds (the
|
|
99
|
+
* first to stop them while there is room, the one that refuses the next create when there is none), then the counts.
|
|
100
|
+
*/
|
|
101
|
+
function roomText(c: Obj): string {
|
|
102
|
+
const shape = `${c.vcpu} vCPU, ${c.memory_mib} MiB`;
|
|
103
|
+
const org = count(c.org);
|
|
104
|
+
const desk = count(c.desktops);
|
|
105
|
+
const node = isObj(c.node) ? c.node : {};
|
|
106
|
+
const nodeRoom = typeof node.room === "number" ? node.room : undefined;
|
|
107
|
+
const used = (n: { running: number; limit: number } | undefined) =>
|
|
108
|
+
`${n?.running ?? "?"} of ${n?.limit ?? "?"} running or paused`;
|
|
109
|
+
const label: Record<string, string> = {
|
|
110
|
+
org_concurrency: `your organization's sandbox limit (sandboxes.concurrent: ${used(org)})`,
|
|
111
|
+
desktops: `your organization's desktop limit (sandboxes.desktops_concurrent: ${used(desk)})`,
|
|
112
|
+
node: nodeRoom === 0 ? "the node (its memory or disk is full)" : `the node's memory (room for ${nodeRoom ?? "?"})`,
|
|
113
|
+
};
|
|
114
|
+
const room = typeof c.room === "number" ? c.room : 0;
|
|
115
|
+
const lines: string[] = [];
|
|
116
|
+
if (room > 0) {
|
|
117
|
+
// While there is room `binding` is null: name the limit with the fewest left, the one the next wave meets.
|
|
118
|
+
const left: Array<[string, number | undefined]> = [
|
|
119
|
+
["desktops", desk && desk.limit - desk.running],
|
|
120
|
+
["org_concurrency", org && org.limit - org.running],
|
|
121
|
+
["node", nodeRoom],
|
|
122
|
+
];
|
|
123
|
+
const first = left.find(([, n]) => n === room)?.[0];
|
|
124
|
+
lines.push(
|
|
125
|
+
`${room} more desktop${room === 1 ? "" : "s"} (${shape}) can be created now` +
|
|
126
|
+
(first ? `; ${label[first]} binds first.` : "."),
|
|
127
|
+
);
|
|
128
|
+
} else {
|
|
129
|
+
const b = typeof c.binding === "string" ? c.binding : undefined;
|
|
130
|
+
const retry = typeof c.retry_after_s === "number" ? ` Look again in ${c.retry_after_s} s.` : "";
|
|
131
|
+
const paused = b === "node" ? "" : " Running and paused desktops count: delete the ones you are done with.";
|
|
132
|
+
const which = b && label[b] ? label[b] : "a limit";
|
|
133
|
+
lines.push(`No room for another desktop (${shape}) now: ${which} refuses the next create.${retry}${paused}`);
|
|
134
|
+
}
|
|
135
|
+
const parts = [
|
|
136
|
+
org ? `org sandboxes ${org.running} of ${org.limit}` : "",
|
|
137
|
+
desk ? `desktops ${desk.running} of ${desk.limit}` : "",
|
|
138
|
+
`node room ${nodeRoom ?? "unknown"}${typeof node.parked === "number" ? `, ${node.parked} parked` : ""}`,
|
|
139
|
+
].filter(Boolean);
|
|
140
|
+
lines.push(parts.join(" · "));
|
|
141
|
+
return lines.join("\n");
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** desktop_act's text: a header, one line per action, the pointer and the settle, then what the screenshot is. */
|
|
145
|
+
function actText(actions: readonly unknown[], r: Obj, wanted: boolean): { text: string; failed: boolean } {
|
|
146
|
+
const results = (Array.isArray(r.results) ? r.results : []).filter(isObj);
|
|
147
|
+
const bad = results.findIndex((x) => x.ok !== true);
|
|
148
|
+
const n = actions.length;
|
|
149
|
+
const lines = [
|
|
150
|
+
`${n} action${n === 1 ? "" : "s"}: ${bad < 0 ? "all ok" : `action ${bad} failed and the batch stopped there`}`,
|
|
151
|
+
];
|
|
152
|
+
results.forEach((x, i) => {
|
|
153
|
+
const a = actions[i];
|
|
154
|
+
const name = isObj(a) && typeof a.action === "string" ? a.action : "action";
|
|
155
|
+
const state = x.ok === true ? "ok" : typeof x.error === "string" && x.error ? `failed: ${x.error}` : "not run";
|
|
156
|
+
lines.push(`${i}. ${name} ${state} (${x.delivery}, retry ${x.retry})`);
|
|
157
|
+
});
|
|
158
|
+
const cur = isObj(r.cursor) ? r.cursor : undefined;
|
|
159
|
+
const pointer = cur
|
|
160
|
+
? `cursor (${cur.x}, ${cur.y})`
|
|
161
|
+
: "cursor unknown: the desktop's X server went away during the batch";
|
|
162
|
+
const settled = typeof r.settled_by === "string" ? ` · settled_by ${r.settled_by} in ${ms(r.settled_ms) || "?"}` : "";
|
|
163
|
+
lines.push(pointer + settled);
|
|
164
|
+
const shot = isObj(r.screenshot) ? r.screenshot : undefined;
|
|
165
|
+
if (shot) lines.push(`${shotLine(shotInfo(shot))} (the image follows)`);
|
|
166
|
+
else if (wanted) lines.push("no screenshot: it could not be taken; desktop_screenshot takes one");
|
|
167
|
+
return { text: lines.join("\n"), failed: bad >= 0 };
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
const DESKTOP_RUNNERS: Record<string, Runner> = {
|
|
171
|
+
async desktop_create(tool, args, io, ctx) {
|
|
172
|
+
const s = (await io.request(buildRequest(tool, args), ctx.signal)) as Obj;
|
|
173
|
+
return text(
|
|
174
|
+
`${sandboxLine(s)}\nLook with desktop_screenshot, use the mouse and keyboard with desktop_act, run commands ` +
|
|
175
|
+
`with desktop_run; desktop_delete ${s.id} when the task is done.`,
|
|
176
|
+
s,
|
|
177
|
+
);
|
|
178
|
+
},
|
|
179
|
+
|
|
180
|
+
async desktop_list(tool, args, io, ctx) {
|
|
181
|
+
const status = typeof args.status === "string" && args.status ? args.status : undefined;
|
|
182
|
+
const found: Obj[] = [];
|
|
183
|
+
let cursor: string | undefined;
|
|
184
|
+
let scanned = 0;
|
|
185
|
+
for (let page = 0; page < LIST_PAGES; page++) {
|
|
186
|
+
const query = { ...(status ? { status } : {}), limit: 100, ...(cursor ? { cursor } : {}) };
|
|
187
|
+
const r = await io.request(requestFor(tool.operationId, [], { query }), ctx.signal);
|
|
188
|
+
const rows = listOf(r);
|
|
189
|
+
scanned += rows.length;
|
|
190
|
+
found.push(...rows.filter(isDesktop));
|
|
191
|
+
cursor = nextCursor(r);
|
|
192
|
+
if (!cursor) break;
|
|
193
|
+
}
|
|
194
|
+
const what = `${status ? `${status} ` : ""}desktop`;
|
|
195
|
+
const head = found.length ? `${found.length} ${what}${found.length === 1 ? "" : "s"}` : `no ${what}s`;
|
|
196
|
+
const lines = found.map((s) => {
|
|
197
|
+
const meta = isObj(s.metadata) && Object.keys(s.metadata).length ? ` metadata ${json(s.metadata)}` : "";
|
|
198
|
+
return sandboxLine(s) + meta;
|
|
199
|
+
});
|
|
200
|
+
if (cursor) lines.push(`(read the newest ${scanned} sandboxes; older ones were not read)`);
|
|
201
|
+
const desktops = found.map((s) => ({
|
|
202
|
+
id: s.id,
|
|
203
|
+
status: s.status,
|
|
204
|
+
vcpu: s.vcpu,
|
|
205
|
+
memory_mib: s.memory_mib,
|
|
206
|
+
expires_at: s.expires_at ?? null,
|
|
207
|
+
created_at: s.created_at ?? null,
|
|
208
|
+
metadata: s.metadata ?? {},
|
|
209
|
+
}));
|
|
210
|
+
return text(clip([head, ...lines].join("\n")), { desktops, ...(cursor ? { complete: false } : {}) });
|
|
211
|
+
},
|
|
212
|
+
|
|
213
|
+
async desktop_delete(tool, args, io, ctx) {
|
|
214
|
+
const s = (await io.request(buildRequest(tool, args), ctx.signal)) as Obj;
|
|
215
|
+
return text(`${s.id} ${s.status}`, s);
|
|
216
|
+
},
|
|
217
|
+
|
|
218
|
+
async desktop_room(tool, args, io, ctx) {
|
|
219
|
+
const c = (await io.request(buildRequest(tool, args), ctx.signal)) as Obj;
|
|
220
|
+
return text(roomText(isObj(c) ? c : {}), c);
|
|
221
|
+
},
|
|
222
|
+
|
|
223
|
+
async desktop_screenshot(tool, args, io, ctx) {
|
|
224
|
+
const shot = await io.request(buildRequest(tool, args), ctx.signal);
|
|
225
|
+
const image = screenshotBlock(shot);
|
|
226
|
+
if (!image || !isObj(shot))
|
|
227
|
+
throw new ToolCallError({ code: "invalid_response", detail: "the screenshot answer holds no image" });
|
|
228
|
+
const info = shotInfo(shot);
|
|
229
|
+
return { content: [{ type: "text", text: shotLine(info) }, image], structuredContent: info };
|
|
230
|
+
},
|
|
231
|
+
|
|
232
|
+
async desktop_act(tool, args, io, ctx) {
|
|
233
|
+
const actions = Array.isArray(args.actions) ? (args.actions as unknown[]) : [];
|
|
234
|
+
if (!actions.length) throw invalid("actions holds 1 to 32 actions", "/actions");
|
|
235
|
+
const screenshot = option(args.screenshot, ACT_SCREENSHOT);
|
|
236
|
+
// settle waits before the screenshot only: with screenshot: false it is sent only when the caller gave one.
|
|
237
|
+
const settle = screenshot ? option(args.settle, ACT_SETTLE) : isObj(args.settle) ? args.settle : undefined;
|
|
238
|
+
const body = { actions, ...(screenshot ? { screenshot } : {}), ...(settle ? { settle } : {}) };
|
|
239
|
+
const r = (await io.request(requestFor(tool.operationId, [args.sandbox_id], { body }), ctx.signal)) as Obj;
|
|
240
|
+
const { text: t, failed } = actText(actions, isObj(r) ? r : {}, !!screenshot);
|
|
241
|
+
const content: ContentBlock[] = [{ type: "text", text: t }];
|
|
242
|
+
const image = screenshotBlock(r?.screenshot);
|
|
243
|
+
if (image) content.push(image);
|
|
244
|
+
const { screenshot: shot, ...rest } = isObj(r) ? r : ({} as Obj);
|
|
245
|
+
return {
|
|
246
|
+
content,
|
|
247
|
+
structuredContent: { ...rest, screenshot: isObj(shot) ? shotInfo(shot) : null },
|
|
248
|
+
isError: failed,
|
|
249
|
+
};
|
|
250
|
+
},
|
|
251
|
+
|
|
252
|
+
async desktop_run(tool, args, io, ctx) {
|
|
253
|
+
checkCmd(args.cmd);
|
|
254
|
+
const req = buildRequest(tool, args);
|
|
255
|
+
let r: Obj;
|
|
256
|
+
let resumed = false;
|
|
257
|
+
try {
|
|
258
|
+
r = (await io.request(req, ctx.signal)) as Obj;
|
|
259
|
+
} catch (e) {
|
|
260
|
+
if (!notRunning(e)) throw e;
|
|
261
|
+
// A paused desktop answers exec with 409 sandbox_not_running and the command never started: resume it once
|
|
262
|
+
// and run the command. A stopped desktop cannot be resumed; that answer is the tool's error.
|
|
263
|
+
await io.request(requestFor("sandboxesResumeSandbox", [args.sandbox_id]), ctx.signal);
|
|
264
|
+
resumed = true;
|
|
265
|
+
r = (await io.request(req, ctx.signal)) as Obj;
|
|
266
|
+
}
|
|
267
|
+
return execResult(args, r, resumed ? { resumed: true } : undefined);
|
|
268
|
+
},
|
|
269
|
+
};
|
|
270
|
+
|
|
19
271
|
export const RUNNERS: Record<string, Runner> = {
|
|
20
272
|
async sandbox_logs(tool, args, io, ctx) {
|
|
21
273
|
const events = (await io.request({ ...buildRequest(tool, args), accept: "events" }, ctx.signal)) as unknown;
|
|
@@ -57,19 +309,13 @@ export const RUNNERS: Record<string, Runner> = {
|
|
|
57
309
|
|
|
58
310
|
async sandbox_create(tool, args, io, ctx) {
|
|
59
311
|
const s = (await io.request(buildRequest(tool, args), ctx.signal)) as Obj;
|
|
60
|
-
return text(
|
|
312
|
+
return text(sandboxLine(s), s);
|
|
61
313
|
},
|
|
62
314
|
|
|
63
315
|
async sandbox_exec(tool, args, io, ctx) {
|
|
64
|
-
|
|
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");
|
|
316
|
+
checkCmd(args.cmd);
|
|
67
317
|
const r = (await io.request(buildRequest(tool, args), ctx.signal)) as Obj;
|
|
68
|
-
|
|
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 };
|
|
318
|
+
return execResult(args, r);
|
|
73
319
|
},
|
|
74
320
|
|
|
75
321
|
async sandbox_read_file(tool, args, io, ctx) {
|
|
@@ -107,4 +353,6 @@ export const RUNNERS: Record<string, Runner> = {
|
|
|
107
353
|
const s = (await io.request(buildRequest(tool, args), ctx.signal)) as Obj;
|
|
108
354
|
return text(`${s.id} ${s.status}`, s);
|
|
109
355
|
},
|
|
356
|
+
|
|
357
|
+
...DESKTOP_RUNNERS,
|
|
110
358
|
};
|
package/src/handlers/vision.ts
CHANGED
|
@@ -16,6 +16,7 @@ import {
|
|
|
16
16
|
pageReport,
|
|
17
17
|
type Runner,
|
|
18
18
|
requestFor,
|
|
19
|
+
screenshotBlock,
|
|
19
20
|
startOrContinue,
|
|
20
21
|
type ToolContext,
|
|
21
22
|
type ToolIO,
|
|
@@ -23,17 +24,6 @@ import {
|
|
|
23
24
|
text,
|
|
24
25
|
} from "./_common.ts";
|
|
25
26
|
|
|
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
27
|
/** A job with pages (a crawl, a batch): start or continue it, wait, then read its pages as Markdown. */
|
|
38
28
|
async function pagedJob(
|
|
39
29
|
kind: "crawl" | "batch",
|
package/src/server.ts
CHANGED
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
|
|
6
6
|
import { type B3OS, SDK_VERSION, TRACEPARENT_RE } from "@b3os/sdk";
|
|
7
7
|
import { compactSchema, detailFor } from "./compact.ts";
|
|
8
|
+
import type { ToolContext } from "./handlers/_common.ts";
|
|
8
9
|
import { MCP_INSTRUCTIONS } from "./table.ts";
|
|
9
10
|
import {
|
|
10
11
|
errorResult,
|
|
@@ -21,7 +22,7 @@ export const LEGACY_VERSIONS = ["2025-11-25", "2025-06-18", "2025-03-26", "2024-
|
|
|
21
22
|
const META_VERSION = "io.modelcontextprotocol/protocolVersion";
|
|
22
23
|
const META_SERVER_INFO = "io.modelcontextprotocol/serverInfo";
|
|
23
24
|
|
|
24
|
-
export const SERVER_INFO = { name: "b3os", title: "B3OS", version: "0.2.
|
|
25
|
+
export const SERVER_INFO = { name: "b3os", title: "B3OS", version: "0.2.3" };
|
|
25
26
|
|
|
26
27
|
/** MCP log levels, most verbose first (RFC 5424 severities). */
|
|
27
28
|
const LOG_LEVELS: readonly string[] = ["debug", "info", "notice", "warning", "error", "critical", "alert", "emergency"];
|
|
@@ -49,6 +50,8 @@ export type Outgoing = JsonRpcResponse | { jsonrpc: "2.0"; method: string; param
|
|
|
49
50
|
|
|
50
51
|
export interface McpServerOptions {
|
|
51
52
|
client: B3OS;
|
|
53
|
+
/** Saves a tool's file on the user's machine (the stdio server's; ToolContext.saveFile). */
|
|
54
|
+
saveFile?: ToolContext["saveFile"];
|
|
52
55
|
/** Packs whose actions become direct tools (`github`, `io.b3os/slack`). */
|
|
53
56
|
packs?: readonly string[];
|
|
54
57
|
/** Published routines that become direct tools `routine_<name>` (names, or `all`). */
|
|
@@ -130,6 +133,7 @@ export class McpServer {
|
|
|
130
133
|
private readonly only: ReadonlySet<string> | null;
|
|
131
134
|
private onlyChecked = false;
|
|
132
135
|
private readonly authHelp: McpServerOptions["authHelp"];
|
|
136
|
+
private readonly saveFile: McpServerOptions["saveFile"];
|
|
133
137
|
/** The version a legacy `initialize` negotiated, for this process (stdio) or session. */
|
|
134
138
|
legacyVersion: string | undefined;
|
|
135
139
|
private readonly inflight = new Map<Id, AbortController>();
|
|
@@ -149,6 +153,7 @@ export class McpServer {
|
|
|
149
153
|
this.detail = opts.detail ?? "compact";
|
|
150
154
|
this.only = opts.only?.length ? new Set(opts.only) : null;
|
|
151
155
|
this.authHelp = opts.authHelp;
|
|
156
|
+
this.saveFile = opts.saveFile;
|
|
152
157
|
}
|
|
153
158
|
|
|
154
159
|
/** The tools this server lists and serves: every tool, or the ones `only` names. */
|
|
@@ -381,6 +386,7 @@ export class McpServer {
|
|
|
381
386
|
try {
|
|
382
387
|
result = await tool.call(this.client, args, {
|
|
383
388
|
signal: ac.signal,
|
|
389
|
+
...(this.saveFile ? { saveFile: this.saveFile } : {}),
|
|
384
390
|
...(traceparent ? { traceparent } : {}),
|
|
385
391
|
progress:
|
|
386
392
|
token === undefined
|
package/src/stdio.ts
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
// The stdio transport: newline-delimited JSON-RPC on stdin/stdout, logs on stderr only (MCP stdio rules).
|
|
2
2
|
|
|
3
3
|
import { appendFileSync, readFileSync } from "node:fs";
|
|
4
|
+
import { mkdir, writeFile } from "node:fs/promises";
|
|
4
5
|
import { homedir } from "node:os";
|
|
5
|
-
import { join } from "node:path";
|
|
6
|
+
import { dirname, isAbsolute, join, relative, resolve } from "node:path";
|
|
6
7
|
import { B3OS, DEFAULT_BASE_URL } from "@b3os/sdk";
|
|
7
8
|
import { McpServer, type McpServerOptions, type Outgoing } from "./server.ts";
|
|
8
9
|
|
|
@@ -16,6 +17,24 @@ export interface StdioOptions extends Partial<McpServerOptions> {
|
|
|
16
17
|
traceFile?: string;
|
|
17
18
|
}
|
|
18
19
|
|
|
20
|
+
/**
|
|
21
|
+
* Saves a tool's file (render_screenshot's save_to) under `root`, the server's working folder (the client's project):
|
|
22
|
+
* a path that leaves it is refused, so a tool call cannot write over a file elsewhere on the machine.
|
|
23
|
+
*/
|
|
24
|
+
export function saveInside(
|
|
25
|
+
root: string,
|
|
26
|
+
): (path: string, bytes: Uint8Array) => Promise<{ saved_to: string; bytes: number }> {
|
|
27
|
+
return async (path, bytes) => {
|
|
28
|
+
const abs = resolve(root, path);
|
|
29
|
+
const rel = relative(root, abs);
|
|
30
|
+
if (!rel || rel.startsWith("..") || isAbsolute(rel))
|
|
31
|
+
throw Object.assign(new Error(`save_to must be a file inside ${root}`), { code: "invalid_request", status: 400 });
|
|
32
|
+
await mkdir(dirname(abs), { recursive: true });
|
|
33
|
+
await writeFile(abs, bytes);
|
|
34
|
+
return { saved_to: rel, bytes: bytes.byteLength };
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
|
|
19
38
|
/** What a trace line records about one message: no parameters, so no argument or credential ever lands in it. */
|
|
20
39
|
function traceLine(m: unknown): string {
|
|
21
40
|
const o = (m && typeof m === "object" ? m : {}) as {
|
|
@@ -130,6 +149,7 @@ export async function serveStdio(opts: StdioOptions = {}): Promise<void> {
|
|
|
130
149
|
const server = new McpServer({
|
|
131
150
|
onWarning: (m) => process.stderr.write(`b3os-mcp: ${m}\n`),
|
|
132
151
|
authHelp: authHelpFor(source),
|
|
152
|
+
saveFile: saveInside(process.cwd()),
|
|
133
153
|
...opts,
|
|
134
154
|
client,
|
|
135
155
|
});
|