@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
package/README.md CHANGED
@@ -1,39 +1,130 @@
1
1
  # @b3os/mcp
2
2
 
3
- The B3OS MCP server over stdio. MCP clients start it with `npx -y @b3os/mcp`; `b3os mcp install --client
4
- claude|cursor|codex` writes that entry for you. It reads `B3OS_API_KEY`, else the `b3os login` token, else the
5
- node socket or sandbox URL (the SDK's routing rules).
3
+ B3OS tools for any MCP client: vision (web pages and browsers), render, infer, sandboxes, routines and actions, running
4
+ next to the GPUs on the B3IQ machine that serves open models.
5
+
6
+ The B3OS MCP server over stdio, and the tool table both B3OS MCP servers serve. MCP clients start the stdio server
7
+ with `npx -y @b3os/mcp@0.1`; `b3os mcp install --client claude|cursor|codex` writes that entry for you. It reads
8
+ `B3OS_API_KEY`, else the `b3os login` token, else the node socket or sandbox URL (the SDK's routing rules). It
9
+ reads the login as the SDK does: on a developer's machine only (not in CI, on GitHub Actions or in a B3OS
10
+ sandbox), and only for the API host the login was issued by.
11
+
12
+ ## One tool table
13
+
14
+ `table/tools/<product>.mjs` (one file per product, owned by it) defines every tool once: its name, title, description,
15
+ the API operation it calls, which of that operation's path parameters, query parameters and body fields it takes, and
16
+ the few arguments the tool itself consumes (`job_id`, `wait_s`, `max_chars`, `include_image`, `keep_session`).
17
+ `scripts/gen-table.mjs` copies each field's schema from `packages/spec/dist/openapi.json` (refs inlined, depth and
18
+ validation detail trimmed, long descriptions shortened) into `src/table.gen.ts` and `table/table.json`
19
+ (`b3os-mcp-table/1`), so tool arguments cannot drift from the API: a tool's arguments are the REST request's own
20
+ fields, same names, same nesting. `table/core.mjs` holds the server instructions, the core group in tools/list order
21
+ (`CORE`) and the order of the product modules; `table/tools.mjs` composes the table from them (core tools first, then
22
+ each product's opt-in tools). `src/table.ts` is the shared runtime: argument checks, the requests each tool makes, job
23
+ continuation, browser sessions around `vision_act`, the screenshot image, Markdown-first results; each product's
24
+ handlers are in `src/handlers/<product>.ts` and the shared helpers in `src/handlers/_common.ts`. It imports nothing
25
+ but the table, so any JavaScript runtime (Node, Workers) can serve it through a `ToolIO`:
6
26
 
7
- ## Tools
27
+ ```ts
28
+ import { MCP_INSTRUCTIONS, httpIO, runTool, toolsFor } from "@b3os/mcp/table";
29
+
30
+ const io = httpIO({ fetch: subRequest, baseUrl: "https://beta-api.b3os.org", headers: { authorization } });
31
+ const tools = toolsFor(["routines"]); // core + opt-in toolsets, in table order
32
+ const result = await runTool("vision_scrape", { url: "https://example.com" }, io, { signal });
33
+ ```
8
34
 
9
- Fifteen core tools, always listed in this order (deterministic `tools/list` keeps prompt caches warm):
35
+ The stdio server runs the same table through `@b3os/sdk` (`sdkIO`: SDK routing, retries, idempotency keys and
36
+ event streams for job progress). `table/requests.json` records the requests every tool makes for fixed
37
+ arguments; another server of the table can replay it. `node scripts/gen-table.mjs --check` fails when the table
38
+ is stale against the spec.
39
+
40
+ ## Instructions
41
+
42
+ Both servers send the same server-level instruction (`MCP_INSTRUCTIONS`, in `initialize` and `server/discover`):
43
+ prefer `vision_scrape` over a client's built-in web fetch for reading pages, run code, installs and file
44
+ processing in a sandbox rather than on the user's machine, reach third-party services through `actions_search`
45
+ → `actions_describe` → `actions_call`, and continue long jobs with `job_id`.
46
+
47
+ ## Tools
10
48
 
11
- | Tool | Calls |
49
+ Fifteen core tools, always listed in this order (a deterministic `tools/list` keeps prompt caches warm):
50
+
51
+ | Tool | Operation | Notes |
52
+ |---|---|---|
53
+ | `vision_scrape` | `visionScrape` | Markdown first (or html, text, links, JSON from a schema, a screenshot image); `max_chars` truncates |
54
+ | `vision_map` | `visionMap` | a site's URLs, optionally ranked for a phrase |
55
+ | `vision_crawl` | `visionCreateCrawl` | waits up to `wait_s`, then returns the job id; `job_id` continues and returns the pages (`visionListCrawlPages`) |
56
+ | `vision_act` | `visionAct` | opens a session (`visionCreateSession`) unless `session_id`, runs the `actions`, closes it unless `keep_session` |
57
+ | `render_screenshot` | `renderCreateScreenshot` | the image as MCP image content (unless `include_image: false`) plus its signed URL |
58
+ | `render_video` | `renderCreateVideo` | waits up to `wait_s`; `job_id` continues (`renderGetVideo`) |
59
+ | `sandbox_create` | `sandboxesCreateSandbox` | stops after `timeout_s`, 300 s unless given (the API's default) |
60
+ | `sandbox_exec` | `sandboxesExec` | exit code, stdout, stderr; `background: true` returns the process |
61
+ | `sandbox_read_file` | `sandboxesReadFile` | UTF-8 text or base64, or a directory listing with `list: true` |
62
+ | `sandbox_write_file` | `sandboxesWriteFile` | UTF-8 or base64 `content`; parent directories are created |
63
+ | `sandbox_delete` | `sandboxesDeleteSandbox` | |
64
+ | `routine_run` | `routinesCreateRun` | waits up to `wait_s`; `job_id` continues (`routinesGetRun`) |
65
+ | `actions_search` | `actionsSearch` | refs to pass on |
66
+ | `actions_describe` | `actionsDescribe` | input and output schemas, effect class, connections |
67
+ | `actions_call` | `actionsCall` | credentials come from vault connections, never from arguments |
68
+
69
+ Opt-in toolsets (`--toolsets routines,infer`, `B3OS_MCP_TOOLSETS`, or `all`; the edge: `/mcp?toolsets=`):
70
+
71
+ | Toolset | Tools |
12
72
  |---|---|
13
- | `vision_scrape` | `vision.scrape`: a URL as Markdown (or html, text, links, a screenshot image) |
14
- | `vision_map` | `vision.map`: a site's URLs, optionally ranked for a phrase |
15
- | `vision_crawl` | `vision.createCrawl` and `listCrawlPages`; waits up to `wait_s`, then returns the job id (call again with `job_id`) |
16
- | `vision_act` | `vision.createSession`, `act`, `closeSession`: browser actions in one call; `keep_session` keeps the session |
17
- | `render_screenshot` | `render.createScreenshot`: the image as MCP image content plus its signed URL |
18
- | `render_video` | `render.createVideo` / `getVideo`: waits up to `wait_s`, returns artifact URLs or the job id |
19
- | `sandbox_create` | `sandboxes.createSandbox` |
20
- | `sandbox_exec` | `sandboxes.exec` (buffered): exit code, stdout, stderr |
21
- | `sandbox_read_file` | `sandboxes.readFile`: UTF-8 text or base64, or a directory listing |
22
- | `sandbox_write_file` | `sandboxes.writeFile` (UTF-8 or base64 content, parents created) |
23
- | `sandbox_delete` | `sandboxes.deleteSandbox` |
24
- | `routine_run` | `routines.createRun`: waits up to `wait_s` for the output; `job_id` continues |
25
- | `actions_search` | `actions.search` |
26
- | `actions_describe` | `actions.describe`: input and output schemas, effect class, connections |
27
- | `actions_call` | `actions.call`; credentials come from vault connections, never from arguments |
73
+ | `sandboxes` | `sandbox_run_code`, `sandbox_pause`, `sandbox_resume`, `sandbox_list`, `sandbox_get`, `sandbox_fork`, `sandbox_snapshot`, `sandbox_list_snapshots`, `sandbox_get_snapshot`, `sandbox_delete_snapshot`, `sandbox_list_templates`, `sandbox_get_template`, `sandbox_set_timeout`, `sandbox_port_url`, `sandbox_logs` (background processes' buffered output, read once with `follow=false`), `sandbox_list_processes`, `sandbox_kill_process` |
74
+ | `vision` | `vision_search` (the web's top results, and each one's page when asked), `vision_batch` (waits up to `wait_s`; `job_id` continues and returns the pages), `vision_cancel_batch`, `vision_cancel_crawl`, `vision_create_session`, `vision_list_sessions`, `vision_get_session`, `vision_close_session`, `vision_save_profile` (a signed-in session's state saved under a name), `vision_list_profiles`, `vision_get_profile`, `vision_update_profile` (name, domains, expiry, metadata), `vision_delete_profile` |
75
+ | `routines` | `routine_get_run`, `routine_validate` (checks a definition without publishing it), `routine_signal` |
76
+ | `infer` | `infer_chat` (the node's model), `infer_models`, `infer_voices` (the speech models' voices) |
77
+ | `platform` | `usage_get`, `limits_get`, `requests_list`, `requests_get` (the node's request log), `webhooks_list_deliveries`, `webhooks_send_test` |
78
+
79
+ tools/list sends compact schemas (platform-dx.7, `src/compact.ts`): each tool's name, title and description, and its
80
+ arguments' names, types, enums and required fields; an object or array argument also keeps the first sentence of its
81
+ description (where the table gives its shape by example), not its nested properties. Every call is still checked
82
+ against the full schema, and a refused call's answer ends with the full description of each argument its errors
83
+ name. `--detail full` (`B3OS_MCP_DETAIL`; the edge: `/mcp?detail=full`) lists the full schemas, and `--tools
84
+ vision_scrape,sandbox_exec` (`B3OS_MCP_TOOLS`; the edge: `/mcp?tools=`) lists and serves only those tools. The 15 core
85
+ tools list in 11,604 bytes instead of 22,080 (render_video 1,405 instead of 4,033); in the eval
86
+ (`bench/platform/mcp-payload`, results `bench/platform/results/20261103T0040Z-mcp-payload`, one run, dev)
87
+ `b3os/qwen3.5-9b` read the compact list as 3,151 tokens instead of 6,232 and chose the expected tool for 30 of 30
88
+ requests (29 of 30 with the full list).
89
+
90
+ Preview operations (`x-b3os-stage: preview`, behind an `x-b3os-flag`) are left out of every tools/list, `all`
91
+ included, until the flag is on for your organization. The table marks their tools `stage: "preview"` with the
92
+ `flag`; `selectTools(tools, toolsets, flags)` and `toolsFor(toolsets, flags)` list one only when its flag is in
93
+ `flags`. The edge's `/mcp` lists a core preview tool to an organization whose D1 `feature_flags` row is on; the
94
+ stdio server takes `--preview <flag>,...` (`B3OS_MCP_PREVIEW`), and the API still answers `404
95
+ feature_not_enabled` to an organization without the flag. No operation is preview today.
96
+
97
+ Not tools, on purpose: the sandbox PTY and stream tickets (`openPty`, `createTicket`: an interactive WebSocket,
98
+ which a tool call cannot hold; `sandbox_exec` and `sandbox_logs` cover commands and output), and the operations
99
+ that move credentials through the model's context (`visionCreateProfile` and `visionUpdateProfile`'s `state`,
100
+ `visionExportProfileState`, `webhooksGetSecret`, `webhooksRotateSecret`; use `vision_save_profile` after signing
101
+ in with `vision_act`, and the CLI or SDK for webhook secrets).
102
+
103
+ `vision_scrape`, `vision_map` and `vision_crawl` take `respect_robots` (decision D10: robots.txt is consulted only
104
+ when it is set). This branch's spec does not have the field yet (it is in vision.yaml on ws2/vision), so the
105
+ table carries an authored schema for it (`ahead` in `table/tools/vision.mjs`). The tools send it only when it is given;
106
+ a node without vision's change may refuse it as an unknown field (this branch's ScrapeRequest and MapRequest
107
+ allow no other fields).
28
108
 
29
109
  Marketplace actions are reached through `actions_search` → `actions_describe` → `actions_call` (ARCHITECTURE §5.5).
30
110
  `--packs github,slack` (or `B3OS_MCP_PACKS`) also lists every action of those packs as its own tool, under the
31
- registry's MCP name (`github__create-issue`) with the pack's annotations.
32
-
33
- API errors come back as tool results with `isError: true` and the error's code, detail, validation pointers and
34
- request id, so a model can correct its call. Long jobs send `notifications/progress` when the request carries a
35
- `progressToken`, and `notifications/cancelled` aborts the call. Text output is truncated at 100,000 characters by
36
- default (`max_chars` on `vision_scrape`).
111
+ registry's MCP name (`github__create-issue`) with the pack's annotations, from one
112
+ `GET /v1/actions/packs/{namespace}/{name}/tools` per pack, all at once (`loadPackTools`). `--effects read` and
113
+ `--actions github/create-issue` (`B3OS_MCP_EFFECTS`, `B3OS_MCP_ACTIONS`; the edge: `?effects=`, `?actions=`) narrow
114
+ the list. A pack that serves nothing goes to stderr, into `tools/list` `_meta.warnings` and into the instructions,
115
+ and as a `notifications/message` warning only to a client that asked for log messages (`logging/setLevel`, or a
116
+ request's `logLevel`; MCP 2026-07-28 forbids unsolicited ones).
117
+ `--routines daily-digest,triage` or `--routines all` (or `B3OS_MCP_ROUTINES`; the edge: `/mcp?routines=`) lists the
118
+ project's published, active routines as tools named `routine_<name>` (`-` becomes `_`), described by the
119
+ definition's `description` and taking its `inputs` schema; a call starts a run of the active version and waits up to
120
+ 50 s, then returns the `run_` id to continue with `routine_run`. `routineToolFromDefinition` and `runRoutineTool`
121
+ are exported for other servers of the table.
122
+
123
+ Arguments are checked against the tool's schema before any request (unknown arguments, missing required ones,
124
+ primitive types and enums); API errors come back as tool results with `isError: true` and the error's code,
125
+ detail, validation pointers and request id, so a model can correct its call. Long jobs send
126
+ `notifications/progress` when the request carries a `progressToken`, and `notifications/cancelled` aborts the
127
+ call's HTTP request. Text output is truncated at 100,000 characters by default.
37
128
 
38
129
  ## Protocol
39
130
 
@@ -49,29 +140,24 @@ Dual-era, per the MCP 2026-07-28 versioning rules:
49
140
 
50
141
  `ping`, `resources/list`, `resources/templates/list` and `prompts/list` (empty) answer too. Logs go to stderr only.
51
142
 
52
- ## Reuse
53
-
54
- The tool table and the protocol handler do not depend on Node and run in a Worker, so another transport can serve
55
- exactly the same tools:
56
-
57
- ```ts
58
- import { McpServer } from "@b3os/mcp/server";
59
- import { coreTools } from "@b3os/mcp/tools";
60
- import { B3OS } from "@b3os/sdk";
61
-
62
- const server = new McpServer({ client: new B3OS({ apiKey, fetch: forward }) });
63
- await server.handle(jsonRpcMessage, (out) => respond(out));
64
- ```
65
-
66
143
  ## Development
67
144
 
68
145
  ```sh
146
+ node packages/mcp/scripts/gen-table.mjs # after editing table/** or the spec (--check in CI)
69
147
  pnpm --filter @b3os/mcp typecheck
70
- pnpm --filter @b3os/mcp test # protocol, tools against a local API, cancellation, the stdio process
148
+ pnpm --filter @b3os/mcp test # table, protocol, tools against a local API, every tool against Prism
71
149
  pnpm --filter @b3os/mcp build && bash packages/mcp/test/interop/run.sh
72
150
  # opt-in: the official MCP TypeScript client (@modelcontextprotocol/sdk 1.32.1)
73
151
  # connects over stdio, lists and calls tools, and cancels a call
74
152
  ```
75
153
 
76
154
  The interop check covers the `initialize` handshake (that client negotiates 2025-11-25, its newest version; it does
77
- not implement the stateless 2026-07-28 revision), so the 2026-07-28 path is covered by the unit tests only.
155
+ not implement the stateless 2026-07-28 revision).
156
+
157
+ `bash packages/mcp/test/clients/run.sh [claude] [codex] [cursor]` (opt-in, after building sdk, mcp and cli) runs
158
+ the MCP clients installed on the machine against this checkout, configured by `b3os mcp install` in isolated
159
+ config directories, with no model turn: Claude Code health-checks the stdio and the remote entry, Codex's own MCP
160
+ client lists and calls tools through `codex app-server`, cursor-agent lists tools. `B3OS_MCP_TRACE=<file>` makes
161
+ the stdio server append one line per received message (method, protocol revision, tool name; never arguments),
162
+ which is how the revision each client speaks was observed: Claude Code 2.1.311 uses 2026-07-28 (`server/discover`,
163
+ then `tools/list`), Codex 0.164.0 the 2025-06-18 `initialize` handshake.
package/bin/b3os-mcp.js CHANGED
@@ -1,5 +1,16 @@
1
1
  #!/usr/bin/env node
2
2
  // `b3os-mcp` launcher for the built server (MCP clients run `npx -y @b3os/mcp`).
3
- import { main } from "../dist/main.js";
4
-
5
- process.exitCode = await main(process.argv.slice(2));
3
+ // The Node check runs before the server loads (a dynamic import), so an older Node prints one line on stderr, which
4
+ // MCP clients show in their server log, and exits 2. NEEDS matches "engines" in package.json
5
+ // (packages/sdk/test/node-version.test.ts).
6
+ const NEEDS = [22, 3];
7
+ const [major, minor] = process.versions.node.split(".").map(Number);
8
+ if (major < NEEDS[0] || (major === NEEDS[0] && minor < NEEDS[1])) {
9
+ process.stderr.write(
10
+ `b3os-mcp needs Node.js ${NEEDS.join(".")} or newer; this is Node.js ${process.versions.node}. Install a current LTS release from https://nodejs.org.\n`,
11
+ );
12
+ process.exitCode = 2;
13
+ } else {
14
+ const { main } = await import("../dist/main.js");
15
+ process.exitCode = await main(process.argv.slice(2));
16
+ }
@@ -0,0 +1,27 @@
1
+ type Obj = Record<string, unknown>;
2
+ /** Longest first sentence kept for an object or array argument. */
3
+ export declare const MAX_ARG_DESCRIPTION = 160;
4
+ /**
5
+ * The first sentence of `text`, at most MAX_ARG_DESCRIPTION characters: up to the first ". " (or ".\n") that is
6
+ * outside backticks, braces, brackets and parentheses, so an inline example such as `{say: 'Open billing.'}` is never
7
+ * cut in half. A longer sentence is cut at a word boundary and ends with an ellipsis.
8
+ */
9
+ export declare function firstSentence(text: string): string;
10
+ /** The compact form of a tool's input schema. */
11
+ export declare function compactSchema(schema: Obj): Obj;
12
+ /**
13
+ * The full description of the argument a JSON pointer names (`/beats/0/do/0/kind` finds `beats`, then each level
14
+ * that has one, and keeps the deepest), or null. Pointers are the API's and checkArgs' `errors[].pointer`.
15
+ */
16
+ export declare function argumentDetail(schema: Obj, pointer: string): {
17
+ path: string;
18
+ description: string;
19
+ } | null;
20
+ /**
21
+ * The lines a refused call adds for the arguments its errors name: each argument's full description, once, so a
22
+ * model that wrote a call from the compact listing gets the detail it left out exactly when it needs it.
23
+ */
24
+ export declare function detailFor(schema: Obj, errors: readonly {
25
+ pointer: string;
26
+ }[]): string[];
27
+ export {};
@@ -0,0 +1,138 @@
1
+ // The MCP payload budget (platform-dx.7): what `tools/list` sends by default. A model reads every listed schema on
2
+ // every turn, and the full table cost 22,080 bytes for the 15 core tools (2026-11-03; 21,475 on production on 11-02,
3
+ // about 16% of a 32,768-token context, challenge.md 1.2), most of it argument prose.
4
+ //
5
+ // The compact listing keeps what picks a tool and shapes a call:
6
+ // - the tool's name, title and description, unchanged;
7
+ // - every top-level argument with its type, enum and requiredness;
8
+ // - for an object or array argument, the first sentence of its description (where the table gives its shape by
9
+ // example, such as render_video's beats) and its required fields; not its nested properties;
10
+ // - for an array, its items' type and enum.
11
+ // Left out: scalar arguments' prose, defaults, patterns, bounds, formats and nested properties. The full schema still
12
+ // checks every call, and a refused call quotes the full description of each argument it names (detailFor, used by
13
+ // server.ts). `detail: "full"` (`?detail=full` on /mcp, `--detail full` or B3OS_MCP_DETAIL=full on stdio) lists the
14
+ // full schemas.
15
+ const isObj = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
16
+ /** Longest first sentence kept for an object or array argument. */
17
+ export const MAX_ARG_DESCRIPTION = 160;
18
+ /**
19
+ * The first sentence of `text`, at most MAX_ARG_DESCRIPTION characters: up to the first ". " (or ".\n") that is
20
+ * outside backticks, braces, brackets and parentheses, so an inline example such as `{say: 'Open billing.'}` is never
21
+ * cut in half. A longer sentence is cut at a word boundary and ends with an ellipsis.
22
+ */
23
+ export function firstSentence(text) {
24
+ let depth = 0;
25
+ let code = false;
26
+ let end = text.length;
27
+ for (let i = 0; i < text.length; i++) {
28
+ const ch = text[i];
29
+ if (ch === "`")
30
+ code = !code;
31
+ else if (!code && (ch === "{" || ch === "[" || ch === "("))
32
+ depth++;
33
+ else if (!code && (ch === "}" || ch === "]" || ch === ")"))
34
+ depth = Math.max(0, depth - 1);
35
+ else if (!code && depth === 0 && ch === "." && (i + 1 === text.length || /\s/.test(text[i + 1] ?? ""))) {
36
+ end = i + 1;
37
+ break;
38
+ }
39
+ }
40
+ const s = text.slice(0, end).replace(/\s+/g, " ").trim();
41
+ if (s.length <= MAX_ARG_DESCRIPTION)
42
+ return s;
43
+ const cut = s.slice(0, MAX_ARG_DESCRIPTION - 1);
44
+ const space = cut.lastIndexOf(" ");
45
+ return `${(space > 80 ? cut.slice(0, space) : cut).replace(/[,;:]$/, "")}…`;
46
+ }
47
+ const typeOf = (s) => s.type;
48
+ const isComposite = (s) => {
49
+ const t = typeOf(s);
50
+ const types = Array.isArray(t) ? t : [t];
51
+ return types.includes("object") || types.includes("array");
52
+ };
53
+ /** An array's items: their type and enum only (an object item is just `{type: "object"}`). */
54
+ function items(schema) {
55
+ if (!isObj(schema))
56
+ return schema;
57
+ const out = {};
58
+ if (schema.type !== undefined)
59
+ out.type = schema.type;
60
+ if (Array.isArray(schema.enum))
61
+ out.enum = schema.enum;
62
+ if (schema.const !== undefined)
63
+ out.const = schema.const;
64
+ return out;
65
+ }
66
+ /** One top-level argument in the compact listing. */
67
+ function argument(schema) {
68
+ if (!isObj(schema))
69
+ return schema;
70
+ const out = {};
71
+ for (const k of ["type", "enum", "const"])
72
+ if (schema[k] !== undefined)
73
+ out[k] = schema[k];
74
+ if (Array.isArray(schema.required) && schema.required.length)
75
+ out.required = schema.required;
76
+ if (schema.items !== undefined)
77
+ out.items = items(schema.items);
78
+ for (const k of ["oneOf", "anyOf"])
79
+ if (Array.isArray(schema[k]))
80
+ out[k] = schema[k].map(items);
81
+ if (isComposite(schema) && out.enum === undefined && typeof schema.description === "string") {
82
+ out.description = firstSentence(schema.description);
83
+ }
84
+ return out;
85
+ }
86
+ /** The compact form of a tool's input schema. */
87
+ export function compactSchema(schema) {
88
+ const out = { type: schema.type ?? "object" };
89
+ if (isObj(schema.properties)) {
90
+ out.properties = Object.fromEntries(Object.entries(schema.properties).map(([k, v]) => [k, argument(v)]));
91
+ }
92
+ if (Array.isArray(schema.required) && schema.required.length)
93
+ out.required = schema.required;
94
+ if (schema.additionalProperties === false)
95
+ out.additionalProperties = false;
96
+ return out;
97
+ }
98
+ /**
99
+ * The full description of the argument a JSON pointer names (`/beats/0/do/0/kind` finds `beats`, then each level
100
+ * that has one, and keeps the deepest), or null. Pointers are the API's and checkArgs' `errors[].pointer`.
101
+ */
102
+ export function argumentDetail(schema, pointer) {
103
+ const segs = pointer
104
+ .split("/")
105
+ .slice(1)
106
+ .map((s) => s.replace(/~1/g, "/").replace(/~0/g, "~"));
107
+ let cur = schema;
108
+ let found = null;
109
+ const seen = [];
110
+ for (const seg of segs) {
111
+ if (!isObj(cur))
112
+ break;
113
+ if (isObj(cur.properties) && seg in cur.properties)
114
+ cur = cur.properties[seg];
115
+ else if (cur.items !== undefined && /^\d+$/.test(seg))
116
+ cur = cur.items;
117
+ else
118
+ break;
119
+ seen.push(seg);
120
+ if (isObj(cur) && typeof cur.description === "string")
121
+ found = { path: seen.join("."), description: cur.description };
122
+ }
123
+ return found;
124
+ }
125
+ /**
126
+ * The lines a refused call adds for the arguments its errors name: each argument's full description, once, so a
127
+ * model that wrote a call from the compact listing gets the detail it left out exactly when it needs it.
128
+ */
129
+ export function detailFor(schema, errors) {
130
+ const out = new Map();
131
+ for (const e of errors) {
132
+ const d = argumentDetail(schema, e.pointer);
133
+ if (d && !out.has(d.path))
134
+ out.set(d.path, d.description.replace(/\s+/g, " ").trim());
135
+ }
136
+ return [...out].map(([path, d]) => `${path}: ${d}`);
137
+ }
138
+ //# sourceMappingURL=compact.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"compact.js","sourceRoot":"","sources":["../src/compact.ts"],"names":[],"mappings":"AAAA,mHAAmH;AACnH,qHAAqH;AACrH,qFAAqF;AACrF,EAAE;AACF,iEAAiE;AACjE,yDAAyD;AACzD,qEAAqE;AACrE,iHAAiH;AACjH,iGAAiG;AACjG,8CAA8C;AAC9C,sHAAsH;AACtH,kHAAkH;AAClH,oHAAoH;AACpH,gBAAgB;AAIhB,MAAM,KAAK,GAAG,CAAC,CAAU,EAAY,EAAE,CAAC,OAAO,CAAC,KAAK,QAAQ,IAAI,CAAC,KAAK,IAAI,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;AAEjG,mEAAmE;AACnE,MAAM,CAAC,MAAM,mBAAmB,GAAG,GAAG,CAAC;AAEvC;;;;GAIG;AACH,MAAM,UAAU,aAAa,CAAC,IAAY;IACxC,IAAI,KAAK,GAAG,CAAC,CAAC;IACd,IAAI,IAAI,GAAG,KAAK,CAAC;IACjB,IAAI,GAAG,GAAG,IAAI,CAAC,MAAM,CAAC;IACtB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;QACrC,MAAM,EAAE,GAAG,IAAI,CAAC,CAAC,CAAC,CAAC;QACnB,IAAI,EAAE,KAAK,GAAG;YAAE,IAAI,GAAG,CAAC,IAAI,CAAC;aACxB,IAAI,CAAC,IAAI,IAAI,CAAC,EAAE,KAAK,GAAG,IAAI,EAAE,KAAK,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K,CAAC;AACf,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,SAAS,CAAC,MAAW,EAAE,MAAsC;IAC3E,MAAM,GAAG,GAAG,IAAI,GAAG,EAAkB,CAAC;IACtC,KAAK,MAAM,CAAC,IAAI,MAAM,EAAE,CAAC;QACvB,MAAM,CAAC,GAAG,cAAc,CAAC,MAAM,EAAE,CAAC,CAAC,OAAO,CAAC,CAAC;QAC5C,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,CAAC;YAAE,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,WAAW,CAAC,OAAO,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC;IACxF,CAAC;IACD,OAAO,CAAC,GAAG,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,EAAE,EAAE,CAAC,GAAG,IAAI,KAAK,CAAC,EAAE,CAAC,CAAC;AACtD,CAAC"}
@@ -0,0 +1,150 @@
1
+ import type { McpTableOperation, McpTableTool } from "../table-types.ts";
2
+ export type ContentBlock = {
3
+ type: "text";
4
+ text: string;
5
+ } | {
6
+ type: "image";
7
+ data: string;
8
+ mimeType: string;
9
+ } | {
10
+ type: "resource_link";
11
+ uri: string;
12
+ name: string;
13
+ mimeType?: string;
14
+ description?: string;
15
+ };
16
+ export interface ToolResult {
17
+ content: ContentBlock[];
18
+ structuredContent?: Record<string, unknown>;
19
+ isError?: boolean;
20
+ }
21
+ export interface ToolContext {
22
+ signal?: AbortSignal;
23
+ /** The message's `_meta.traceparent` (MCP 2026-07-28, SEP-414): the tool's API requests join that trace (PD27). */
24
+ traceparent?: string;
25
+ /** Reports progress on long tools (MCP notifications/progress when the client sent a progressToken). */
26
+ progress?: (completed: number, total?: number, message?: string) => void;
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
+ export interface JobLike {
51
+ id: string;
52
+ object?: string;
53
+ status: string;
54
+ progress?: {
55
+ completed?: number;
56
+ total?: number | null;
57
+ } | null;
58
+ [k: string]: unknown;
59
+ }
60
+ /** How a server sends the tools' API requests, as the caller. */
61
+ export interface ToolIO {
62
+ /**
63
+ * Sends one request and resolves with the parsed answer (the JSON value, a `Uint8Array` when `accept` is
64
+ * `bytes`, the array of events when it is `events`). Rejects on an API error with an object carrying `code`, `status`, `detail` (and `errors`,
65
+ * `requestId`): a `B3OSError`, or `toolError(status, problemBody)`.
66
+ */
67
+ request(req: ToolRequest, signal?: AbortSignal): Promise<unknown>;
68
+ /** Fetches a signed artifact URL (the screenshot image). Optional: without it the tool returns the URL only. */
69
+ fetchBytes?(url: string, signal?: AbortSignal): Promise<{
70
+ bytes: Uint8Array;
71
+ contentType?: string;
72
+ } | undefined>;
73
+ /**
74
+ * Follows a job until it finishes or `timeoutMs` passes and returns its latest state (the SDK follows the job's
75
+ * event stream and reports progress). Optional: without it the tool asks the API to wait (`?wait=`) on a create
76
+ * and polls the job on a continuation.
77
+ */
78
+ waitJob?(job: JobLike, timeoutMs: number, signal: AbortSignal | undefined, onProgress?: (completed: number, total?: number) => void): Promise<JobLike>;
79
+ }
80
+ /** An API error from a server's own request code, in the shape `errorResult` reads. */
81
+ export declare class ToolCallError extends Error {
82
+ readonly code: string;
83
+ readonly status: number | null;
84
+ readonly detail: string;
85
+ readonly requestId: string | null;
86
+ readonly errors: ReadonlyArray<{
87
+ pointer: string;
88
+ detail: string;
89
+ }>;
90
+ constructor(init: {
91
+ code: string;
92
+ status?: number | null;
93
+ detail?: string;
94
+ requestId?: string | null;
95
+ errors?: ReadonlyArray<{
96
+ pointer: string;
97
+ detail: string;
98
+ }>;
99
+ });
100
+ }
101
+ /** A ToolCallError from an HTTP status and an RFC 9457 problem body (or any body, for non-B3OS answers). */
102
+ export declare function toolError(status: number, body: unknown, requestId?: string | null): ToolCallError;
103
+ export declare function invalid(detail: string, pointer?: string): ToolCallError;
104
+ export declare const MAX_TEXT = 100000;
105
+ export declare function clip(text: string, max?: number): string;
106
+ export declare function text(t: string, structured?: unknown): ToolResult;
107
+ /** Model-facing JSON: compact (indentation costs tokens on every later model call that re-reads the result). */
108
+ export declare function json(v: unknown): string;
109
+ /**
110
+ * The page facts render's and vision's answers share (XT-7, common.yaml Warnings, OriginStatusCode, PageState), as
111
+ * the lines a tool's text leads with, under the API's own field names: `status_code 404 · page_state error (status)`,
112
+ * then one `warning: ...` line per warning. Empty for a clean page (a 2xx status, `page_state` ok or absent, no
113
+ * warnings), so a clean page costs no tokens; once something is wrong, the status and the state are both named.
114
+ */
115
+ export declare function pageReport(answer: unknown): string;
116
+ /** At most `max` characters, cut after a sentence when one ends past a third of the way. */
117
+ export declare function sentence(t: string, max: number): string;
118
+ /** A JSON Schema without UI-only `x-` keys, for a model to fill. */
119
+ export declare function forModel(v: unknown): unknown;
120
+ export type Obj = Record<string, unknown>;
121
+ export declare const isObj: (v: unknown) => v is Obj;
122
+ /** A failed call as an MCP tool error the model can read and correct (never a protocol error). */
123
+ export declare function errorResult(e: unknown): ToolResult;
124
+ export declare function op(id: string): McpTableOperation;
125
+ /** Encodes one path value; `.` and `..` would move the request to another operation, so they are refused. */
126
+ export declare function segment(name: string, v: unknown): string;
127
+ /** A request to any table operation from path values, a query and a body. */
128
+ export declare function requestFor(operationId: string, pathValues: readonly unknown[], extra?: {
129
+ query?: Record<string, unknown>;
130
+ body?: unknown;
131
+ bodyKind?: ToolRequest["bodyKind"];
132
+ accept?: ToolRequest["accept"];
133
+ }): ToolRequest;
134
+ /** The tool's own operation request from its arguments (no tool-only arguments, defaults applied). */
135
+ export declare function buildRequest(tool: McpTableTool, args: Obj, wait?: number): ToolRequest;
136
+ export declare const TERMINAL: Set<string>;
137
+ export declare const isTerminal: (status: unknown) => boolean;
138
+ export declare function numArg(args: Obj, k: string, dflt: number): number;
139
+ export declare function sleep(ms: number, signal?: AbortSignal): Promise<void>;
140
+ export declare function abortError(): ToolCallError;
141
+ /** Waits for a job through `io.waitJob`, else by polling its continuation operation, for up to `waitS` seconds. */
142
+ export declare function waitFor(tool: McpTableTool, job: JobLike, waitS: number, io: ToolIO, ctx: ToolContext): Promise<JobLike>;
143
+ /** Starts the tool's job, or continues the one named by `job_id`, and waits up to `wait_s`. */
144
+ export declare function startOrContinue(tool: McpTableTool, args: Obj, io: ToolIO, ctx: ToolContext): Promise<JobLike>;
145
+ export type Runner = (tool: McpTableTool, args: Obj, io: ToolIO, ctx: ToolContext) => Promise<ToolResult>;
146
+ /** One request; the JSON answer as text and structured content. */
147
+ export declare const runPlain: Runner;
148
+ export declare const B64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
149
+ export declare function toBase64(bytes: Uint8Array): string;
150
+ export declare function fromBase64(s: string): Uint8Array;