@b3os/mcp 0.1.0 → 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 +16 -6
  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,433 @@
1
+ // Shared helpers of the MCP tool runtime (platform-dx, plan 1.2): the types a server and a handler exchange,
2
+ // errors, text shaping, request building, job waiting and base64. src/table.ts and every src/handlers/<product>.ts
3
+ // import them from here, so the handlers never import table.ts (no import cycle). Only what table.ts re-exports is
4
+ // public (`@b3os/mcp/table`); the rest is internal to the package.
5
+
6
+ import { MCP_OPERATIONS } from "../table.gen.ts";
7
+ import type { McpTableOperation, McpTableTool } from "../table-types.ts";
8
+
9
+ export type ContentBlock =
10
+ | { type: "text"; text: string }
11
+ | { type: "image"; data: string; mimeType: string }
12
+ | { type: "resource_link"; uri: string; name: string; mimeType?: string; description?: string };
13
+
14
+ export interface ToolResult {
15
+ content: ContentBlock[];
16
+ structuredContent?: Record<string, unknown>;
17
+ isError?: boolean;
18
+ }
19
+
20
+ export interface ToolContext {
21
+ signal?: AbortSignal;
22
+ /** The message's `_meta.traceparent` (MCP 2026-07-28, SEP-414): the tool's API requests join that trace (PD27). */
23
+ traceparent?: string;
24
+ /** Reports progress on long tools (MCP notifications/progress when the client sent a progressToken). */
25
+ progress?: (completed: number, total?: number, message?: string) => void;
26
+ }
27
+
28
+ /** One API request a tool makes. `path` is built and encoded; `pathValues` are the raw values in template order. */
29
+ export interface ToolRequest {
30
+ operationId: string;
31
+ method: string;
32
+ /** The path template (`/v1/sandboxes/{sandbox_id}/exec`). */
33
+ template: string;
34
+ pathValues: readonly string[];
35
+ path: string;
36
+ query: Record<string, string>;
37
+ /** `json`: `body` is a JSON value; `raw`: `body` is the bytes to send; `none`: no body. */
38
+ bodyKind: "none" | "json" | "raw";
39
+ body?: unknown;
40
+ /**
41
+ * `bytes` for operations that answer with a file (`sandboxesReadFile` without `list`); `events` for an event
42
+ * stream read to its end (`sandboxesStreamLogs` with `follow=false`): the answer is the array of its events'
43
+ * parsed `data`.
44
+ */
45
+ accept: "json" | "bytes" | "events";
46
+ /** `x-b3os-scope` and `x-b3os-served-by` of the operation (the edge routes and filters by them). */
47
+ scope: string;
48
+ servedBy: string;
49
+ }
50
+
51
+ export interface JobLike {
52
+ id: string;
53
+ object?: string;
54
+ status: string;
55
+ progress?: { completed?: number; total?: number | null } | null;
56
+ [k: string]: unknown;
57
+ }
58
+
59
+ /** How a server sends the tools' API requests, as the caller. */
60
+ export interface ToolIO {
61
+ /**
62
+ * Sends one request and resolves with the parsed answer (the JSON value, a `Uint8Array` when `accept` is
63
+ * `bytes`, the array of events when it is `events`). Rejects on an API error with an object carrying `code`, `status`, `detail` (and `errors`,
64
+ * `requestId`): a `B3OSError`, or `toolError(status, problemBody)`.
65
+ */
66
+ request(req: ToolRequest, signal?: AbortSignal): Promise<unknown>;
67
+ /** Fetches a signed artifact URL (the screenshot image). Optional: without it the tool returns the URL only. */
68
+ fetchBytes?(url: string, signal?: AbortSignal): Promise<{ bytes: Uint8Array; contentType?: string } | undefined>;
69
+ /**
70
+ * Follows a job until it finishes or `timeoutMs` passes and returns its latest state (the SDK follows the job's
71
+ * event stream and reports progress). Optional: without it the tool asks the API to wait (`?wait=`) on a create
72
+ * and polls the job on a continuation.
73
+ */
74
+ waitJob?(
75
+ job: JobLike,
76
+ timeoutMs: number,
77
+ signal: AbortSignal | undefined,
78
+ onProgress?: (completed: number, total?: number) => void,
79
+ ): Promise<JobLike>;
80
+ }
81
+
82
+ /** An API error from a server's own request code, in the shape `errorResult` reads. */
83
+ export class ToolCallError extends Error {
84
+ readonly code: string;
85
+ readonly status: number | null;
86
+ readonly detail: string;
87
+ readonly requestId: string | null;
88
+ readonly errors: ReadonlyArray<{ pointer: string; detail: string }>;
89
+ constructor(init: {
90
+ code: string;
91
+ status?: number | null;
92
+ detail?: string;
93
+ requestId?: string | null;
94
+ errors?: ReadonlyArray<{ pointer: string; detail: string }>;
95
+ }) {
96
+ const items = (init.errors ?? []).map((e) => `${e.pointer} ${e.detail}`).join("; ");
97
+ super(`${init.code}: ${init.detail ?? init.code}${items ? ` (${items})` : ""}`);
98
+ this.name = "ToolCallError";
99
+ this.code = init.code;
100
+ this.status = init.status ?? null;
101
+ this.detail = init.detail ?? init.code;
102
+ this.requestId = init.requestId ?? null;
103
+ this.errors = init.errors ?? [];
104
+ }
105
+ }
106
+
107
+ /** A ToolCallError from an HTTP status and an RFC 9457 problem body (or any body, for non-B3OS answers). */
108
+ export function toolError(status: number, body: unknown, requestId?: string | null): ToolCallError {
109
+ const p = (body && typeof body === "object" && !Array.isArray(body) ? body : {}) as Record<string, unknown>;
110
+ const code = typeof p.code === "string" ? p.code : status >= 500 ? "internal" : "invalid_request";
111
+ const detail =
112
+ typeof p.detail === "string" ? p.detail : typeof body === "string" && body ? body.slice(0, 500) : `HTTP ${status}`;
113
+ const items = Array.isArray(p.errors)
114
+ ? (p.errors as Array<Record<string, unknown>>).map((e) => ({
115
+ pointer: String(e.pointer ?? e.path ?? ""),
116
+ detail: String(e.detail ?? e.message ?? ""),
117
+ }))
118
+ : [];
119
+ return new ToolCallError({
120
+ code,
121
+ status,
122
+ detail,
123
+ requestId: requestId ?? (typeof p.instance === "string" ? p.instance : null),
124
+ errors: items,
125
+ });
126
+ }
127
+
128
+ export function invalid(detail: string, pointer?: string): ToolCallError {
129
+ return new ToolCallError({
130
+ code: "invalid_request",
131
+ status: 400,
132
+ detail,
133
+ errors: pointer ? [{ pointer, detail }] : [],
134
+ });
135
+ }
136
+
137
+ export const MAX_TEXT = 100_000;
138
+
139
+ export function clip(text: string, max = MAX_TEXT): string {
140
+ return text.length <= max ? text : `${text.slice(0, max)}\n\n[truncated: ${text.length - max} more characters]`;
141
+ }
142
+
143
+ export function text(t: string, structured?: unknown): ToolResult {
144
+ const r: ToolResult = { content: [{ type: "text", text: t }] };
145
+ if (structured && typeof structured === "object" && !Array.isArray(structured)) {
146
+ r.structuredContent = structured as Record<string, unknown>;
147
+ }
148
+ return r;
149
+ }
150
+
151
+ /** Model-facing JSON: compact (indentation costs tokens on every later model call that re-reads the result). */
152
+ export function json(v: unknown): string {
153
+ return JSON.stringify(v ?? null);
154
+ }
155
+
156
+ /**
157
+ * The page facts render's and vision's answers share (XT-7, common.yaml Warnings, OriginStatusCode, PageState), as
158
+ * the lines a tool's text leads with, under the API's own field names: `status_code 404 · page_state error (status)`,
159
+ * then one `warning: ...` line per warning. Empty for a clean page (a 2xx status, `page_state` ok or absent, no
160
+ * warnings), so a clean page costs no tokens; once something is wrong, the status and the state are both named.
161
+ */
162
+ export function pageReport(answer: unknown): string {
163
+ if (!isObj(answer)) return "";
164
+ const status = typeof answer.status_code === "number" ? answer.status_code : undefined;
165
+ const ps = isObj(answer.page_state) && typeof answer.page_state.state === "string" ? answer.page_state : undefined;
166
+ const warnings = (Array.isArray(answer.warnings) ? answer.warnings : [])
167
+ .filter((w): w is string => typeof w === "string" && !!w.trim())
168
+ .map((w) => `warning: ${w.trim()}`);
169
+ const bad = (status !== undefined && (status < 200 || status > 299)) || (ps && ps.state !== "ok");
170
+ if (!bad && !warnings.length) return "";
171
+ const head: string[] = [];
172
+ if (status !== undefined) head.push(`status_code ${status}`);
173
+ if (ps) head.push(`page_state ${ps.state}${typeof ps.signal === "string" && ps.signal ? ` (${ps.signal})` : ""}`);
174
+ return [...(head.length ? [head.join(" · ")] : []), ...warnings].join("\n");
175
+ }
176
+
177
+ /** At most `max` characters, cut after a sentence when one ends past a third of the way. */
178
+ export function sentence(t: string, max: number): string {
179
+ if (t.length <= max) return t;
180
+ const cut = t.slice(0, max);
181
+ const stop = cut.lastIndexOf(". ");
182
+ return stop > max / 3 ? cut.slice(0, stop + 1) : `${cut.slice(0, max - 3).trimEnd()}...`;
183
+ }
184
+
185
+ /** A JSON Schema without UI-only `x-` keys, for a model to fill. */
186
+ export function forModel(v: unknown): unknown {
187
+ if (Array.isArray(v)) return v.map(forModel);
188
+ if (!isObj(v)) return v;
189
+ const out: Obj = {};
190
+ for (const [k, x] of Object.entries(v)) if (!k.startsWith("x-")) out[k] = forModel(x);
191
+ return out;
192
+ }
193
+
194
+ export type Obj = Record<string, unknown>;
195
+ export const isObj = (v: unknown): v is Obj => !!v && typeof v === "object" && !Array.isArray(v);
196
+
197
+ /** A failed call as an MCP tool error the model can read and correct (never a protocol error). */
198
+ export function errorResult(e: unknown): ToolResult {
199
+ const err = e as {
200
+ code?: unknown;
201
+ status?: unknown;
202
+ detail?: unknown;
203
+ requestId?: unknown;
204
+ errors?: unknown;
205
+ message?: unknown;
206
+ };
207
+ if (err && typeof err.code === "string" && typeof err.detail === "string") {
208
+ const items = Array.isArray(err.errors) ? (err.errors as Array<{ pointer: string; detail: string }>) : [];
209
+ const lines = [`${err.code}: ${err.detail}`];
210
+ for (const it of items) lines.push(` ${it.pointer}: ${it.detail}`);
211
+ if (typeof err.requestId === "string" && err.requestId) lines.push(`(request ${err.requestId})`);
212
+ return {
213
+ isError: true,
214
+ content: [{ type: "text", text: lines.join("\n") }],
215
+ structuredContent: {
216
+ error: {
217
+ code: err.code,
218
+ status: typeof err.status === "number" ? err.status : null,
219
+ detail: err.detail,
220
+ request_id: typeof err.requestId === "string" ? err.requestId : null,
221
+ errors: items,
222
+ },
223
+ },
224
+ };
225
+ }
226
+ const msg = typeof err?.message === "string" ? err.message : String(e);
227
+ return { isError: true, content: [{ type: "text", text: `error: ${msg}` }] };
228
+ }
229
+
230
+ // ---------------------------------------------------------------------------------------------------------------
231
+ // Requests
232
+
233
+ export function op(id: string): McpTableOperation {
234
+ const o = MCP_OPERATIONS[id];
235
+ if (!o) throw new Error(`the MCP table has no operation ${id}`);
236
+ return o;
237
+ }
238
+
239
+ /** Encodes one path value; `.` and `..` would move the request to another operation, so they are refused. */
240
+ export function segment(name: string, v: unknown): string {
241
+ if (typeof v !== "string" && typeof v !== "number") throw invalid(`${name} is required`, `/${name}`);
242
+ const s = String(v);
243
+ if (!s) throw invalid(`${name} is required`, `/${name}`);
244
+ if (s === "." || s === "..") throw invalid(`${name} cannot be "${s}"`, `/${name}`);
245
+ return encodeURIComponent(s);
246
+ }
247
+
248
+ /** A request to any table operation from path values, a query and a body. */
249
+ export function requestFor(
250
+ operationId: string,
251
+ pathValues: readonly unknown[],
252
+ extra: {
253
+ query?: Record<string, unknown>;
254
+ body?: unknown;
255
+ bodyKind?: ToolRequest["bodyKind"];
256
+ accept?: ToolRequest["accept"];
257
+ } = {},
258
+ ): ToolRequest {
259
+ const o = op(operationId);
260
+ if (pathValues.length !== o.pathParams.length)
261
+ throw new Error(`${operationId} takes ${o.pathParams.length} path values`);
262
+ let path = o.path;
263
+ o.pathParams.forEach((name, i) => {
264
+ path = path.replace(`{${name}}`, segment(name, pathValues[i]));
265
+ });
266
+ const query: Record<string, string> = {};
267
+ for (const [k, v] of Object.entries(extra.query ?? {})) {
268
+ if (v === undefined || v === null) continue;
269
+ query[k] = typeof v === "string" ? v : typeof v === "boolean" ? (v ? "true" : "false") : JSON.stringify(v);
270
+ }
271
+ const bodyKind = extra.bodyKind ?? (extra.body === undefined ? "none" : "json");
272
+ return {
273
+ operationId,
274
+ method: o.method,
275
+ template: o.path,
276
+ pathValues: pathValues.map(String),
277
+ path,
278
+ query,
279
+ bodyKind,
280
+ ...(bodyKind === "none" ? {} : { body: extra.body }),
281
+ accept: extra.accept ?? "json",
282
+ scope: o.scope,
283
+ servedBy: o.servedBy,
284
+ };
285
+ }
286
+
287
+ /** The tool's own operation request from its arguments (no tool-only arguments, defaults applied). */
288
+ export function buildRequest(tool: McpTableTool, args: Obj, wait?: number): ToolRequest {
289
+ const pathValues = tool.pathParams.map((p) => args[p]);
290
+ const query: Record<string, unknown> = { ...tool.queryDefaults };
291
+ for (const q of tool.queryParams) {
292
+ if (q.from) {
293
+ if (q.name === "wait" && wait !== undefined) query.wait = wait;
294
+ continue;
295
+ }
296
+ const v = args[q.name];
297
+ if (v === undefined || v === null) continue;
298
+ query[q.name] = q.encode === "01" ? (v ? 1 : 0) : v;
299
+ }
300
+ if (tool.body === "raw") {
301
+ const content = typeof args.content === "string" ? args.content : "";
302
+ const bytes = args.encoding === "base64" ? fromBase64(content) : new TextEncoder().encode(content);
303
+ return requestFor(tool.operationId, pathValues, { query, body: bytes, bodyKind: "raw" });
304
+ }
305
+ let body: Obj | undefined;
306
+ if (tool.body === "json") {
307
+ body = {};
308
+ for (const f of tool.bodyFields) if (args[f] !== undefined && args[f] !== null) body[f] = args[f];
309
+ for (const [k, v] of Object.entries(tool.bodyDefaults)) if (body[k] === undefined) body[k] = v;
310
+ }
311
+ return requestFor(tool.operationId, pathValues, body === undefined ? { query } : { query, body });
312
+ }
313
+
314
+ // ---------------------------------------------------------------------------------------------------------------
315
+ // Running a tool
316
+
317
+ export const TERMINAL = new Set(["succeeded", "failed", "canceled", "completed", "stopped"]);
318
+ export const isTerminal = (status: unknown) => typeof status === "string" && TERMINAL.has(status);
319
+
320
+ export function numArg(args: Obj, k: string, dflt: number): number {
321
+ const v = args[k];
322
+ return typeof v === "number" && Number.isFinite(v) ? v : dflt;
323
+ }
324
+
325
+ export function sleep(ms: number, signal?: AbortSignal): Promise<void> {
326
+ return new Promise((resolve, reject) => {
327
+ if (signal?.aborted) return reject(abortError());
328
+ const t = setTimeout(() => {
329
+ signal?.removeEventListener("abort", onAbort);
330
+ resolve();
331
+ }, ms);
332
+ const onAbort = () => {
333
+ clearTimeout(t);
334
+ reject(abortError());
335
+ };
336
+ signal?.addEventListener("abort", onAbort, { once: true });
337
+ });
338
+ }
339
+
340
+ export function abortError(): ToolCallError {
341
+ return new ToolCallError({ code: "aborted", detail: "the call was canceled" });
342
+ }
343
+
344
+ /** Waits for a job through `io.waitJob`, else by polling its continuation operation, for up to `waitS` seconds. */
345
+ export async function waitFor(
346
+ tool: McpTableTool,
347
+ job: JobLike,
348
+ waitS: number,
349
+ io: ToolIO,
350
+ ctx: ToolContext,
351
+ ): Promise<JobLike> {
352
+ if (isTerminal(job.status) || waitS <= 0) return job;
353
+ const report = (completed: number, total?: number) => ctx.progress?.(completed, total);
354
+ if (io.waitJob) return io.waitJob(job, waitS * 1000, ctx.signal, report);
355
+ const c = tool.continueWith;
356
+ if (!c) return job;
357
+ const deadline = Date.now() + waitS * 1000;
358
+ let delay = 500;
359
+ let cur = job;
360
+ while (!isTerminal(cur.status)) {
361
+ const left = deadline - Date.now();
362
+ if (left <= 0) break;
363
+ await sleep(Math.min(delay, left), ctx.signal);
364
+ delay = Math.min(delay * 2, 2000);
365
+ cur = (await io.request(requestFor(c.operationId, [cur.id]), ctx.signal)) as JobLike;
366
+ const p = cur.progress;
367
+ if (p && typeof p.completed === "number") report(p.completed, p.total ?? undefined);
368
+ }
369
+ return cur;
370
+ }
371
+
372
+ /** Starts the tool's job, or continues the one named by `job_id`, and waits up to `wait_s`. */
373
+ export async function startOrContinue(tool: McpTableTool, args: Obj, io: ToolIO, ctx: ToolContext): Promise<JobLike> {
374
+ const waitS = Math.max(0, Math.min(60, numArg(args, "wait_s", 50)));
375
+ const c = tool.continueWith;
376
+ const jobId = c ? args[c.arg] : undefined;
377
+ if (c && typeof jobId === "string" && jobId) {
378
+ const job = (await io.request(requestFor(c.operationId, [jobId]), ctx.signal)) as JobLike;
379
+ return waitFor(tool, job, waitS, io, ctx);
380
+ }
381
+ // Without waitJob the API waits (`?wait=`, at most 60 s); with it the server answers at once and the SDK follows
382
+ // the job's events, which carry progress.
383
+ const job = (await io.request(buildRequest(tool, args, io.waitJob ? undefined : waitS), ctx.signal)) as JobLike;
384
+ return io.waitJob ? waitFor(tool, job, waitS, io, ctx) : job;
385
+ }
386
+
387
+ export type Runner = (tool: McpTableTool, args: Obj, io: ToolIO, ctx: ToolContext) => Promise<ToolResult>;
388
+
389
+ /** One request; the JSON answer as text and structured content. */
390
+ export const runPlain: Runner = async (tool, args, io, ctx) => {
391
+ const r = await io.request(buildRequest(tool, args), ctx.signal);
392
+ return text(clip(json(r)), r);
393
+ };
394
+
395
+ // ---------------------------------------------------------------------------------------------------------------
396
+ // Base64 without Buffer, so Workers can run the tools too.
397
+
398
+ export const B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
399
+ export function toBase64(bytes: Uint8Array): string {
400
+ let out = "";
401
+ let i = 0;
402
+ for (; i + 2 < bytes.length; i += 3) {
403
+ const n = ((bytes[i] as number) << 16) | ((bytes[i + 1] as number) << 8) | (bytes[i + 2] as number);
404
+ out +=
405
+ B64[(n >> 18) & 63] + (B64[(n >> 12) & 63] as string) + (B64[(n >> 6) & 63] as string) + (B64[n & 63] as string);
406
+ }
407
+ const rest = bytes.length - i;
408
+ if (rest === 1) {
409
+ const n = (bytes[i] as number) << 16;
410
+ out += `${B64[(n >> 18) & 63]}${B64[(n >> 12) & 63]}==`;
411
+ } else if (rest === 2) {
412
+ const n = ((bytes[i] as number) << 16) | ((bytes[i + 1] as number) << 8);
413
+ out += `${B64[(n >> 18) & 63]}${B64[(n >> 12) & 63]}${B64[(n >> 6) & 63]}=`;
414
+ }
415
+ return out;
416
+ }
417
+
418
+ export function fromBase64(s: string): Uint8Array {
419
+ const clean = s.replace(/[^A-Za-z0-9+/]/g, "");
420
+ const out = new Uint8Array(Math.floor((clean.length * 3) / 4));
421
+ let o = 0;
422
+ for (let i = 0; i < clean.length; i += 4) {
423
+ const n =
424
+ (B64.indexOf(clean[i] ?? "A") << 18) |
425
+ (B64.indexOf(clean[i + 1] ?? "A") << 12) |
426
+ ((clean[i + 2] ? B64.indexOf(clean[i + 2] as string) : 0) << 6) |
427
+ (clean[i + 3] ? B64.indexOf(clean[i + 3] as string) : 0);
428
+ out[o++] = (n >> 16) & 255;
429
+ if (clean[i + 2] !== undefined) out[o++] = (n >> 8) & 255;
430
+ if (clean[i + 3] !== undefined) out[o++] = n & 255;
431
+ }
432
+ return out.slice(0, o);
433
+ }
@@ -0,0 +1,144 @@
1
+ // Actions tool handlers of the MCP tool runtime (owner: actions-triggers, plan 1.2): what each actions tool in
2
+ // table/tools/actions.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
+ errorResult,
10
+ forModel,
11
+ isObj,
12
+ json,
13
+ type Obj,
14
+ type Runner,
15
+ requestFor,
16
+ sentence,
17
+ type ToolContext,
18
+ type ToolIO,
19
+ type ToolResult,
20
+ text,
21
+ } from "./_common.ts";
22
+
23
+ export const RUNNERS: Record<string, Runner> = {
24
+ async actions_search(tool, args, io, ctx) {
25
+ const r = (await io.request(buildRequest(tool, args), ctx.signal)) as Obj & { data?: Obj[] };
26
+ const data = r.data ?? [];
27
+ // A trigger hit (kind=trigger or any) has no effect class; it shows its trigger kind instead.
28
+ const tag = (a: Obj) => (a.kind === "trigger" ? `trigger, ${a.trigger_kind}` : a.effects);
29
+ const lines = data.map((a) => `${a.ref} [${tag(a)}] ${a.title}: ${sentence(String(a.description ?? ""), 160)}`);
30
+ if (lines.length) return text(lines.join("\n"), r);
31
+ // match: none says so in words, with what to use instead; a node from before it answers with no data only.
32
+ const fallback = isObj(r.fallback) ? r.fallback : undefined;
33
+ return text(typeof fallback?.detail === "string" ? fallback.detail : "No catalog action matches this query.", r);
34
+ },
35
+
36
+ async actions_describe(tool, args, io, ctx) {
37
+ // What a model needs to call it: the full answer (output schema, MCP mirror) stays in structuredContent.
38
+ const d = (await io.request(buildRequest(tool, args), ctx.signal)) as Obj;
39
+ const conns = Array.isArray(d.connections) ? (d.connections as Obj[]) : [];
40
+ const lines = [`${d.ref} [${d.effects}] ${d.title}`, String(d.description ?? "")];
41
+ if (conns.length)
42
+ lines.push(
43
+ `connections: ${conns.map((c) => `${c.key} (${[c.type, c.required ? "required" : "optional"].filter(Boolean).join(", ")})`).join(", ")}`,
44
+ );
45
+ lines.push(`input_schema: ${json(forModel(d.input_schema))}`);
46
+ return text(lines.join("\n"), d);
47
+ },
48
+
49
+ async actions_call(tool, args, io, ctx) {
50
+ try {
51
+ const r = (await io.request(buildRequest(tool, args), ctx.signal)) as Obj;
52
+ return text(clip(json(r.output)), r);
53
+ } catch (e) {
54
+ const next = connectNext(e);
55
+ if (!next) throw e;
56
+ return next;
57
+ }
58
+ },
59
+ };
60
+
61
+ /** The dashboard link a `connection_required` carries (`connect_url`), from the problem or, when only the detail
62
+ * reached the server (a ToolCallError keeps no extension members), from the detail's "add one at <url>". Only an
63
+ * https URL with no credentials in it is passed on: an agent shows it to a person as a link to open. */
64
+ export function connectUrl(e: unknown): string | undefined {
65
+ const err = e as { code?: unknown; detail?: unknown; problem?: unknown };
66
+ if (err?.code !== "connection_required") return undefined;
67
+ const p = isObj(err.problem) ? err.problem : undefined;
68
+ if (typeof p?.connect_url === "string") return httpsLink(p.connect_url);
69
+ const m =
70
+ typeof err.detail === "string"
71
+ ? /\badd (?:one|it) at (https:\/\/\S+?\/connections\?\S+?)(?:,|\s|$)/.exec(err.detail)
72
+ : null;
73
+ return m?.[1] ? httpsLink(m[1]) : undefined;
74
+ }
75
+
76
+ function httpsLink(raw: string): string | undefined {
77
+ try {
78
+ const u = new URL(raw);
79
+ return u.protocol === "https:" && !u.username && !u.password ? raw : undefined;
80
+ } catch {
81
+ return undefined;
82
+ }
83
+ }
84
+
85
+ /** A `connection_required` answered as the next step: the error, then the link a person opens to add it. */
86
+ function connectNext(e: unknown): ToolResult | undefined {
87
+ const url = connectUrl(e);
88
+ if (!url) return undefined;
89
+ const r = errorResult(e);
90
+ const first = r.content[0];
91
+ const lines = [
92
+ first?.type === "text" ? first.text : "connection_required",
93
+ `Next: ask the user to open ${url} and add the connection (the pack and key are filled in), then call actions_call again with the same input.`,
94
+ ];
95
+ return {
96
+ isError: true,
97
+ content: [{ type: "text", text: lines.join("\n") }],
98
+ structuredContent: { ...(r.structuredContent ?? {}), next_action: { type: "connect", url } },
99
+ };
100
+ }
101
+
102
+ // ---------------------------------------------------------------------------------------------------------------
103
+ // Pack actions as direct tools (`--packs github`, `/mcp?packs=github`)
104
+
105
+ /** A pack action exposed as its own tool, from `GET /v1/actions/describe` (its `mcp` member). */
106
+ export interface PackTool {
107
+ name: string;
108
+ title: string;
109
+ description: string;
110
+ inputSchema: JsonSchemaObject;
111
+ annotations: Record<string, unknown>;
112
+ ref: string;
113
+ }
114
+
115
+ export function packToolFromDescription(d: Obj): PackTool | undefined {
116
+ const m = isObj(d.mcp) ? d.mcp : undefined;
117
+ if (!m || typeof m.name !== "string" || typeof d.ref !== "string") return undefined;
118
+ const title = typeof m.title === "string" ? m.title : String(d.title ?? m.name);
119
+ return {
120
+ name: m.name,
121
+ title,
122
+ description: typeof m.description === "string" ? m.description : String(d.description ?? ""),
123
+ inputSchema: (isObj(m.inputSchema)
124
+ ? m.inputSchema
125
+ : isObj(d.input_schema)
126
+ ? d.input_schema
127
+ : { type: "object", properties: {} }) as JsonSchemaObject,
128
+ annotations: { title, ...(isObj(d.annotations) ? d.annotations : {}) },
129
+ ref: d.ref,
130
+ };
131
+ }
132
+
133
+ /** Calls a pack action tool: the arguments are the action's input. */
134
+ export async function runPackTool(t: PackTool, args: Obj, io: ToolIO, ctx: ToolContext = {}): Promise<ToolResult> {
135
+ try {
136
+ const r = (await io.request(
137
+ requestFor("actionsCall", [], { body: { ref: t.ref, input: args } }),
138
+ ctx.signal,
139
+ )) as Obj;
140
+ return text(clip(json(r.output)), r);
141
+ } catch (e) {
142
+ return errorResult(e);
143
+ }
144
+ }
@@ -0,0 +1,90 @@
1
+ // Render tool handlers of the MCP tool runtime (owner: render, plan 1.2): what each render tool in
2
+ // table/tools/render.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
+ type ContentBlock,
8
+ invalid,
9
+ isObj,
10
+ type Obj,
11
+ pageReport,
12
+ type Runner,
13
+ startOrContinue,
14
+ type ToolIO,
15
+ text,
16
+ toBase64,
17
+ } from "./_common.ts";
18
+
19
+ /** The image content block of an artifact URL, when the server can fetch artifacts (undefined otherwise). */
20
+ async function imageOf(
21
+ url: string | undefined,
22
+ contentType: unknown,
23
+ io: ToolIO,
24
+ signal: AbortSignal | undefined,
25
+ ): Promise<ContentBlock | undefined> {
26
+ if (!url || !io.fetchBytes) return undefined;
27
+ const got = await io.fetchBytes(url, signal).catch(() => undefined);
28
+ if (!got) return undefined;
29
+ return {
30
+ type: "image",
31
+ data: toBase64(got.bytes),
32
+ mimeType: (typeof contentType === "string" ? contentType : got.contentType) ?? "image/png",
33
+ };
34
+ }
35
+
36
+ /**
37
+ * The text of a screenshot answer: size and format, the image link, then what the site answered and what the clean
38
+ * capture did (render.3, XT-7: the response's own field names, so a model reads the same words in JSON and text).
39
+ */
40
+ export function screenshotText(shot: Obj, url: string | undefined): string {
41
+ const lines = [`${shot.width}x${shot.height} ${shot.format}${url ? `\n${url}` : ""}`];
42
+ // XT-7: the same lines vision_scrape leads with (pageReport): `status_code 404 · page_state error (status)`, then
43
+ // one `warning: ...` per warning; nothing for a clean page.
44
+ const report = pageReport(shot);
45
+ if (report) lines.push(report);
46
+ const removed = (Array.isArray(shot.overlays_removed) ? shot.overlays_removed : []).filter(isObj);
47
+ if (removed.length > 0) {
48
+ lines.push(`overlays_removed ${removed.map((r) => `${r.kind} ${r.signal} x${r.count}`).join(", ")}`);
49
+ }
50
+ return lines.join("\n");
51
+ }
52
+
53
+ export const RUNNERS: Record<string, Runner> = {
54
+ async render_screenshot(tool, args, io, ctx) {
55
+ if (!args.url && !args.html) throw invalid("give url or html", "/url");
56
+ const shot = (await io.request(buildRequest(tool, args), ctx.signal)) as Obj;
57
+ const arts = (Array.isArray(shot.artifacts) ? shot.artifacts : []) as Obj[];
58
+ const art = arts[0];
59
+ const url = typeof art?.url === "string" ? art.url : undefined;
60
+ const content: ContentBlock[] = [{ type: "text", text: screenshotText(shot, url) }];
61
+ if (args.include_image !== false) {
62
+ const image = await imageOf(url, art?.content_type, io, ctx.signal);
63
+ if (image) content.push(image);
64
+ }
65
+ return { content, structuredContent: shot };
66
+ },
67
+
68
+ async render_video(tool, args, io, ctx) {
69
+ if (!args.job_id && (!args.source || !args.beats)) throw invalid("give source and beats, or job_id", "/source");
70
+ const v = await startOrContinue(tool, args, io, ctx);
71
+ const result = isObj(v.result) ? v.result : {};
72
+ const arts = (Array.isArray(result.artifacts) ? result.artifacts : []) as Obj[];
73
+ const lines = [`video ${v.id}: ${v.status}`, ...arts.map((a) => `${a.kind} ${a.url ?? ""}`)];
74
+ const err = isObj(v.error) ? v.error : undefined;
75
+ if (err) lines.push(`${err.code}: ${err.detail}`);
76
+ const out = { ...text(lines.join("\n"), v), isError: v.status === "failed" };
77
+ // The poster frame as an image, so a model sees what the video shows without downloading the MP4.
78
+ const poster = arts.find((a) => a.kind === "poster");
79
+ if (v.status === "succeeded" && poster && args.include_poster !== false) {
80
+ const image = await imageOf(
81
+ typeof poster.url === "string" ? poster.url : undefined,
82
+ poster.content_type,
83
+ io,
84
+ ctx.signal,
85
+ );
86
+ if (image) out.content = [...out.content, image];
87
+ }
88
+ return out;
89
+ },
90
+ };