@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.
- package/README.md +129 -43
- package/bin/b3os-mcp.js +14 -3
- package/dist/compact.d.ts +27 -0
- package/dist/compact.js +138 -0
- package/dist/compact.js.map +1 -0
- package/dist/handlers/_common.d.ts +150 -0
- package/dist/handlers/_common.js +329 -0
- package/dist/handlers/_common.js.map +1 -0
- package/dist/handlers/actions.d.ts +19 -0
- package/dist/handlers/actions.js +110 -0
- package/dist/handlers/actions.js.map +1 -0
- package/dist/handlers/render.d.ts +7 -0
- package/dist/handlers/render.js +72 -0
- package/dist/handlers/render.js.map +1 -0
- package/dist/handlers/routines.d.ts +20 -0
- package/dist/handlers/routines.js +128 -0
- package/dist/handlers/routines.js.map +1 -0
- package/dist/handlers/sandboxes.d.ts +2 -0
- package/dist/handlers/sandboxes.js +100 -0
- package/dist/handlers/sandboxes.js.map +1 -0
- package/dist/handlers/vision.d.ts +7 -0
- package/dist/handlers/vision.js +186 -0
- package/dist/handlers/vision.js.map +1 -0
- package/dist/index.d.ts +3 -2
- package/dist/index.js +3 -2
- package/dist/index.js.map +1 -1
- package/dist/main.js +88 -7
- package/dist/main.js.map +1 -1
- package/dist/server.d.ts +68 -1
- package/dist/server.js +175 -18
- package/dist/server.js.map +1 -1
- package/dist/stdio.d.ts +24 -1
- package/dist/stdio.js +89 -12
- package/dist/stdio.js.map +1 -1
- package/dist/table-types.d.ts +84 -0
- package/dist/table-types.js +4 -0
- package/dist/table-types.js.map +1 -0
- package/dist/table.d.ts +54 -0
- package/dist/table.gen.d.ts +7 -0
- package/dist/table.gen.js +3755 -0
- package/dist/table.gen.js.map +1 -0
- package/dist/table.js +240 -0
- package/dist/table.js.map +1 -0
- package/dist/tools.d.ts +61 -47
- package/dist/tools.js +231 -705
- package/dist/tools.js.map +1 -1
- package/package.json +20 -10
- package/src/compact.ts +127 -0
- package/src/handlers/_common.ts +433 -0
- package/src/handlers/actions.ts +144 -0
- package/src/handlers/render.ts +90 -0
- package/src/handlers/routines.ts +152 -0
- package/src/handlers/sandboxes.ts +110 -0
- package/src/handlers/vision.ts +213 -0
- package/src/index.ts +36 -0
- package/src/main.ts +79 -7
- package/src/server.ts +225 -19
- package/src/stdio.ts +107 -10
- package/src/table-types.ts +88 -0
- package/src/table.gen.ts +3812 -0
- package/src/table.ts +304 -0
- package/src/tools.ts +310 -785
- package/table/core.mjs +73 -0
- package/table/requests.json +1151 -0
- package/table/table.json +3764 -0
- package/table/tools/actions.mjs +55 -0
- package/table/tools/infer.mjs +52 -0
- package/table/tools/platform.mjs +76 -0
- package/table/tools/render.mjs +126 -0
- package/table/tools/routines.mjs +70 -0
- package/table/tools/sandboxes.mjs +269 -0
- package/table/tools/vision.mjs +316 -0
- package/table/tools.mjs +92 -0
package/src/table.ts
ADDED
|
@@ -0,0 +1,304 @@
|
|
|
1
|
+
// The shared MCP tool runtime: what a tool sends and what it answers, for every server that serves the table
|
|
2
|
+
// (this package's stdio server and the edge's /mcp). It depends on nothing but the generated table: a server gives
|
|
3
|
+
// it a `ToolIO` (how to send an API request with the caller's credential) and gets MCP tool results back. Behavior
|
|
4
|
+
// that is not one request per call lives here too, once: job continuation (`job_id`, `wait_s`), browser sessions
|
|
5
|
+
// opened and closed around `vision_act`, the screenshot image, Markdown-first text for models.
|
|
6
|
+
//
|
|
7
|
+
// Per product (plan 1.2): src/handlers/<product>.ts holds a product's tool handlers (RUNNERS, merged below) and
|
|
8
|
+
// its direct-tool helpers; src/handlers/_common.ts the shared types and helpers. This file selects tools, checks
|
|
9
|
+
// arguments, runs a tool through its handler (or one plain request), and is the public `@b3os/mcp/table` module.
|
|
10
|
+
|
|
11
|
+
import {
|
|
12
|
+
abortError,
|
|
13
|
+
errorResult,
|
|
14
|
+
invalid,
|
|
15
|
+
isObj,
|
|
16
|
+
type Obj,
|
|
17
|
+
type Runner,
|
|
18
|
+
runPlain,
|
|
19
|
+
ToolCallError,
|
|
20
|
+
type ToolContext,
|
|
21
|
+
type ToolIO,
|
|
22
|
+
type ToolResult,
|
|
23
|
+
toolError,
|
|
24
|
+
} from "./handlers/_common.ts";
|
|
25
|
+
import { RUNNERS as actionRunners } from "./handlers/actions.ts";
|
|
26
|
+
import { RUNNERS as renderRunners } from "./handlers/render.ts";
|
|
27
|
+
import { type RoutineTool, RUNNERS as routineRunners } from "./handlers/routines.ts";
|
|
28
|
+
import { RUNNERS as sandboxRunners } from "./handlers/sandboxes.ts";
|
|
29
|
+
import { RUNNERS as visionRunners } from "./handlers/vision.ts";
|
|
30
|
+
import { MCP_INSTRUCTIONS, MCP_OPERATIONS, MCP_TOOLS } from "./table.gen.ts";
|
|
31
|
+
import type { JsonSchemaObject, McpTableTool } from "./table-types.ts";
|
|
32
|
+
|
|
33
|
+
export type { ContentBlock, JobLike, ToolContext, ToolIO, ToolRequest, ToolResult } from "./handlers/_common.ts";
|
|
34
|
+
export {
|
|
35
|
+
buildRequest,
|
|
36
|
+
errorResult,
|
|
37
|
+
fromBase64,
|
|
38
|
+
MAX_TEXT,
|
|
39
|
+
requestFor,
|
|
40
|
+
ToolCallError,
|
|
41
|
+
toBase64,
|
|
42
|
+
toolError,
|
|
43
|
+
} from "./handlers/_common.ts";
|
|
44
|
+
export { type PackTool, packToolFromDescription, runPackTool } from "./handlers/actions.ts";
|
|
45
|
+
export { type RoutineTool, routineToolFromDefinition } from "./handlers/routines.ts";
|
|
46
|
+
export type * from "./table-types.ts";
|
|
47
|
+
export { MCP_INSTRUCTIONS, MCP_OPERATIONS, MCP_TOOLS };
|
|
48
|
+
|
|
49
|
+
// ---------------------------------------------------------------------------------------------------------------
|
|
50
|
+
// Tool selection and argument checks
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* The tools a server lists from `tools`: the core set plus the named opt-in toolsets (`all`: every group), in table
|
|
54
|
+
* order. A tool of a preview operation (`stage: "preview"`, W3-0b-8) is left out unless its flag is in `flags`, the
|
|
55
|
+
* flags that are on for the caller's organization: the default tools/list never shows one, `all` included.
|
|
56
|
+
*/
|
|
57
|
+
export function selectTools<T extends Pick<McpTableTool, "group" | "stage" | "flag">>(
|
|
58
|
+
tools: readonly T[],
|
|
59
|
+
toolsets: readonly string[] = [],
|
|
60
|
+
flags: readonly string[] = [],
|
|
61
|
+
): T[] {
|
|
62
|
+
const want = new Set(["core", ...toolsets.map((s) => s.trim()).filter(Boolean)]);
|
|
63
|
+
const on = new Set(flags);
|
|
64
|
+
return tools.filter(
|
|
65
|
+
(t) => (want.has("all") || want.has(t.group)) && (t.stage !== "preview" || (!!t.flag && on.has(t.flag))),
|
|
66
|
+
);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** The tools a server lists: the core set plus the named opt-in toolsets, in table order (selectTools). */
|
|
70
|
+
export function toolsFor(toolsets: readonly string[] = [], flags: readonly string[] = []): McpTableTool[] {
|
|
71
|
+
return selectTools(MCP_TOOLS, toolsets, flags);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** The flags that gate a preview tool of the table; a server needs the caller's flags only when this is non-empty. */
|
|
75
|
+
export function previewFlags(tools: readonly Pick<McpTableTool, "stage" | "flag">[] = MCP_TOOLS): string[] {
|
|
76
|
+
return [...new Set(tools.flatMap((t) => (t.stage === "preview" && t.flag ? [t.flag] : [])))];
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** The toolset names the table defines (`core` first). */
|
|
80
|
+
export function toolsets(): string[] {
|
|
81
|
+
return [...new Set(MCP_TOOLS.map((t) => t.group))];
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export function findTool(name: string): McpTableTool | undefined {
|
|
85
|
+
return MCP_TOOLS.find((t) => t.name === name);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function typeOk(schema: Obj, v: unknown): boolean {
|
|
89
|
+
const t = schema.type;
|
|
90
|
+
const types = Array.isArray(t) ? (t as string[]) : typeof t === "string" ? [t] : [];
|
|
91
|
+
if (!types.length) return true; // oneOf and friends: the API validates
|
|
92
|
+
return types.some((ty) => {
|
|
93
|
+
switch (ty) {
|
|
94
|
+
case "string":
|
|
95
|
+
return typeof v === "string";
|
|
96
|
+
case "integer":
|
|
97
|
+
return typeof v === "number" && Number.isInteger(v);
|
|
98
|
+
case "number":
|
|
99
|
+
return typeof v === "number" && Number.isFinite(v);
|
|
100
|
+
case "boolean":
|
|
101
|
+
return typeof v === "boolean";
|
|
102
|
+
case "object":
|
|
103
|
+
return isObj(v);
|
|
104
|
+
case "array":
|
|
105
|
+
return Array.isArray(v);
|
|
106
|
+
case "null":
|
|
107
|
+
return v === null;
|
|
108
|
+
default:
|
|
109
|
+
return true;
|
|
110
|
+
}
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Checks the arguments' top level against the tool's input schema: no unknown arguments, required ones present,
|
|
116
|
+
* primitive types and enums right. Deeper checks are the API's (its 400 comes back as a readable tool error).
|
|
117
|
+
*/
|
|
118
|
+
export function checkArgs(tool: McpTableTool, args: Obj): void {
|
|
119
|
+
const schema = tool.inputSchema as JsonSchemaObject;
|
|
120
|
+
const props = schema.properties as Record<string, Obj>;
|
|
121
|
+
const problems: Array<{ pointer: string; detail: string }> = [];
|
|
122
|
+
for (const k of Object.keys(args)) {
|
|
123
|
+
if (!(k in props)) problems.push({ pointer: `/${k}`, detail: `is not an argument of ${tool.name}` });
|
|
124
|
+
}
|
|
125
|
+
for (const k of schema.required ?? []) {
|
|
126
|
+
if (args[k] === undefined || args[k] === null) problems.push({ pointer: `/${k}`, detail: "is required" });
|
|
127
|
+
}
|
|
128
|
+
for (const [k, v] of Object.entries(args)) {
|
|
129
|
+
const p = props[k];
|
|
130
|
+
if (!p || v === undefined || v === null) continue;
|
|
131
|
+
if (!typeOk(p, v)) problems.push({ pointer: `/${k}`, detail: `must be ${JSON.stringify(p.type)}` });
|
|
132
|
+
else if (Array.isArray(p.enum) && !p.enum.some((e) => e === v))
|
|
133
|
+
problems.push({ pointer: `/${k}`, detail: `must be one of ${p.enum.map((e) => JSON.stringify(e)).join(", ")}` });
|
|
134
|
+
}
|
|
135
|
+
if (problems.length) {
|
|
136
|
+
throw new ToolCallError({
|
|
137
|
+
code: "invalid_request",
|
|
138
|
+
status: 400,
|
|
139
|
+
detail: `invalid arguments for ${tool.name}`,
|
|
140
|
+
errors: problems,
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// ---------------------------------------------------------------------------------------------------------------
|
|
146
|
+
// Running a tool
|
|
147
|
+
|
|
148
|
+
/** Runs one table tool: checks its arguments, makes its requests through `io`, and formats the answer. */
|
|
149
|
+
export async function runTool(
|
|
150
|
+
tool: McpTableTool | string,
|
|
151
|
+
args: Obj,
|
|
152
|
+
io: ToolIO,
|
|
153
|
+
ctx: ToolContext = {},
|
|
154
|
+
): Promise<ToolResult> {
|
|
155
|
+
const t = typeof tool === "string" ? findTool(tool) : tool;
|
|
156
|
+
if (!t) return errorResult(invalid(`unknown tool ${String(tool)}`));
|
|
157
|
+
try {
|
|
158
|
+
checkArgs(t, args);
|
|
159
|
+
const run = RUNNERS[t.name] ?? runPlain;
|
|
160
|
+
return await run(t, args, io, ctx);
|
|
161
|
+
} catch (e) {
|
|
162
|
+
if (ctx.signal?.aborted && !(e as { code?: unknown })?.code) return errorResult(abortError());
|
|
163
|
+
return errorResult(e);
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* The handler modules' RUNNERS merged, refusing a tool name two modules both handle (review L1, W3-0b-3): a plain
|
|
169
|
+
* spread let the later module take over the other product's handler without touching that product's file.
|
|
170
|
+
*/
|
|
171
|
+
export function mergeRunners(
|
|
172
|
+
modules: Readonly<Record<string, Readonly<Record<string, Runner>>>>,
|
|
173
|
+
): Record<string, Runner> {
|
|
174
|
+
const out: Record<string, Runner> = {};
|
|
175
|
+
const owner: Record<string, string> = {};
|
|
176
|
+
for (const [file, runners] of Object.entries(modules))
|
|
177
|
+
for (const [name, run] of Object.entries(runners)) {
|
|
178
|
+
if (Object.hasOwn(out, name))
|
|
179
|
+
throw new Error(`src/handlers/${file}.ts: a runner for ${name} is also in src/handlers/${owner[name]}.ts`);
|
|
180
|
+
out[name] = run;
|
|
181
|
+
owner[name] = file;
|
|
182
|
+
}
|
|
183
|
+
return out;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
const RUNNERS: Record<string, Runner> = mergeRunners({
|
|
187
|
+
vision: visionRunners,
|
|
188
|
+
render: renderRunners,
|
|
189
|
+
sandboxes: sandboxRunners,
|
|
190
|
+
routines: routineRunners,
|
|
191
|
+
actions: actionRunners,
|
|
192
|
+
});
|
|
193
|
+
|
|
194
|
+
// ---------------------------------------------------------------------------------------------------------------
|
|
195
|
+
// A ToolIO over plain fetch: what a server without the SDK uses (the edge's /mcp: its sub-request function as
|
|
196
|
+
// `fetch`, the API host as `baseUrl`, the caller's Authorization header). One attempt per request, no retries.
|
|
197
|
+
|
|
198
|
+
export interface HttpIOOptions {
|
|
199
|
+
/** Sends a request (the edge passes its sub-request dispatcher). */
|
|
200
|
+
fetch: (req: Request) => Promise<Response>;
|
|
201
|
+
/** `https://beta-api.b3os.org`, a node URL, or a test server. */
|
|
202
|
+
baseUrl: string;
|
|
203
|
+
/** Sent on every API request: `authorization`, `traceparent`. */
|
|
204
|
+
headers?: Record<string, string>;
|
|
205
|
+
/** Fetches artifact URLs (another host); defaults to the global fetch. */
|
|
206
|
+
fetchArtifact?: (url: string, init: { signal?: AbortSignal }) => Promise<Response>;
|
|
207
|
+
/** A fresh Idempotency-Key for operations that take one; defaults to crypto.randomUUID(). */
|
|
208
|
+
idempotencyKey?: () => string;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** The parsed `data` of each event in a finished `text/event-stream` body (comments and non-JSON data skipped). */
|
|
212
|
+
export function sseEvents(body: string): unknown[] {
|
|
213
|
+
const out: unknown[] = [];
|
|
214
|
+
for (const block of body.replace(/\r\n?/g, "\n").split(/\n\n+/)) {
|
|
215
|
+
const data = block
|
|
216
|
+
.split("\n")
|
|
217
|
+
.filter((l) => l.startsWith("data:"))
|
|
218
|
+
.map((l) => l.slice(5).replace(/^ /, ""))
|
|
219
|
+
.join("\n");
|
|
220
|
+
if (!data) continue;
|
|
221
|
+
try {
|
|
222
|
+
out.push(JSON.parse(data));
|
|
223
|
+
} catch {
|
|
224
|
+
// not JSON: skipped
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
return out;
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
export function httpIO(opts: HttpIOOptions): ToolIO {
|
|
231
|
+
const base = opts.baseUrl.replace(/\/+$/, "");
|
|
232
|
+
return {
|
|
233
|
+
async request(req, signal) {
|
|
234
|
+
const qs = new URLSearchParams(req.query).toString();
|
|
235
|
+
const headers = new Headers(opts.headers ?? {});
|
|
236
|
+
headers.set(
|
|
237
|
+
"accept",
|
|
238
|
+
req.accept === "bytes"
|
|
239
|
+
? "application/octet-stream"
|
|
240
|
+
: req.accept === "events"
|
|
241
|
+
? "text/event-stream"
|
|
242
|
+
: "application/json",
|
|
243
|
+
);
|
|
244
|
+
let body: RequestInit["body"] | undefined;
|
|
245
|
+
if (req.bodyKind === "json") {
|
|
246
|
+
headers.set("content-type", "application/json");
|
|
247
|
+
body = JSON.stringify(req.body);
|
|
248
|
+
} else if (req.bodyKind === "raw") {
|
|
249
|
+
headers.set("content-type", "application/octet-stream");
|
|
250
|
+
body = req.body as Uint8Array;
|
|
251
|
+
}
|
|
252
|
+
if (MCP_OPERATIONS[req.operationId]?.idempotent && !headers.has("idempotency-key")) {
|
|
253
|
+
headers.set("idempotency-key", (opts.idempotencyKey ?? (() => crypto.randomUUID()))());
|
|
254
|
+
}
|
|
255
|
+
const res = await opts.fetch(
|
|
256
|
+
new Request(`${base}${req.path}${qs ? `?${qs}` : ""}`, {
|
|
257
|
+
method: req.method,
|
|
258
|
+
headers,
|
|
259
|
+
...(body !== undefined ? { body } : {}),
|
|
260
|
+
...(signal ? { signal } : {}),
|
|
261
|
+
}),
|
|
262
|
+
);
|
|
263
|
+
const rid = res.headers.get("x-request-id");
|
|
264
|
+
if (res.status >= 400) {
|
|
265
|
+
const t = await res.text();
|
|
266
|
+
let parsed: unknown = t;
|
|
267
|
+
try {
|
|
268
|
+
parsed = t ? JSON.parse(t) : null;
|
|
269
|
+
} catch {
|
|
270
|
+
// not JSON: keep the text
|
|
271
|
+
}
|
|
272
|
+
throw toolError(res.status, parsed, rid);
|
|
273
|
+
}
|
|
274
|
+
if (req.accept === "bytes") return new Uint8Array(await res.arrayBuffer());
|
|
275
|
+
if (req.accept === "events") return sseEvents(await res.text());
|
|
276
|
+
const t = await res.text();
|
|
277
|
+
if (!t) return null;
|
|
278
|
+
try {
|
|
279
|
+
return JSON.parse(t);
|
|
280
|
+
} catch {
|
|
281
|
+
return t;
|
|
282
|
+
}
|
|
283
|
+
},
|
|
284
|
+
async fetchBytes(url, signal) {
|
|
285
|
+
const f = opts.fetchArtifact ?? ((u: string, init: { signal?: AbortSignal }) => fetch(u, init));
|
|
286
|
+
const res = await f(url, signal ? { signal } : {}).catch(() => undefined);
|
|
287
|
+
if (!res?.ok) return undefined;
|
|
288
|
+
return {
|
|
289
|
+
bytes: new Uint8Array(await res.arrayBuffer()),
|
|
290
|
+
contentType: res.headers.get("content-type") ?? undefined,
|
|
291
|
+
};
|
|
292
|
+
},
|
|
293
|
+
};
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/** Runs a routine tool: the arguments are the run's input; the result is routine_run's. */
|
|
297
|
+
export async function runRoutineTool(
|
|
298
|
+
t: RoutineTool,
|
|
299
|
+
args: Obj,
|
|
300
|
+
io: ToolIO,
|
|
301
|
+
ctx: ToolContext = {},
|
|
302
|
+
): Promise<ToolResult> {
|
|
303
|
+
return runTool("routine_run", { routine: t.routine, input: args, wait_s: 50 }, io, ctx);
|
|
304
|
+
}
|