@b3os/mcp 0.1.0 → 0.2.0
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 +3754 -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 +16 -6
- 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 +3763 -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/server.ts
CHANGED
|
@@ -3,21 +3,31 @@
|
|
|
3
3
|
// call `server/discover`, and get `resultType` plus cache hints on list results. Tool calls run concurrently;
|
|
4
4
|
// `notifications/cancelled` aborts one.
|
|
5
5
|
|
|
6
|
-
import { type B3OS, SDK_VERSION } from "@b3os/sdk";
|
|
7
|
-
import {
|
|
6
|
+
import { type B3OS, SDK_VERSION, TRACEPARENT_RE } from "@b3os/sdk";
|
|
7
|
+
import { compactSchema, detailFor } from "./compact.ts";
|
|
8
|
+
import { MCP_INSTRUCTIONS } from "./table.ts";
|
|
9
|
+
import {
|
|
10
|
+
errorResult,
|
|
11
|
+
loadPackTools,
|
|
12
|
+
type PackToolFilter,
|
|
13
|
+
routineTools,
|
|
14
|
+
type ToolDef,
|
|
15
|
+
type ToolResult,
|
|
16
|
+
tableTools,
|
|
17
|
+
} from "./tools.ts";
|
|
8
18
|
|
|
9
19
|
export const MODERN_VERSIONS = ["2026-07-28"] as const;
|
|
10
20
|
export const LEGACY_VERSIONS = ["2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"] as const;
|
|
11
21
|
const META_VERSION = "io.modelcontextprotocol/protocolVersion";
|
|
12
22
|
const META_SERVER_INFO = "io.modelcontextprotocol/serverInfo";
|
|
13
23
|
|
|
14
|
-
export const SERVER_INFO = { name: "b3os", title: "B3OS", version: "0.
|
|
24
|
+
export const SERVER_INFO = { name: "b3os", title: "B3OS", version: "0.2.0" };
|
|
15
25
|
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
26
|
+
/** MCP log levels, most verbose first (RFC 5424 severities). */
|
|
27
|
+
const LOG_LEVELS: readonly string[] = ["debug", "info", "notice", "warning", "error", "critical", "alert", "emergency"];
|
|
28
|
+
|
|
29
|
+
/** The server-level instruction (the shared table's, the same text the edge's /mcp sends). */
|
|
30
|
+
export const INSTRUCTIONS = MCP_INSTRUCTIONS;
|
|
21
31
|
|
|
22
32
|
type Id = string | number;
|
|
23
33
|
|
|
@@ -41,10 +51,53 @@ export interface McpServerOptions {
|
|
|
41
51
|
client: B3OS;
|
|
42
52
|
/** Packs whose actions become direct tools (`github`, `io.b3os/slack`). */
|
|
43
53
|
packs?: readonly string[];
|
|
54
|
+
/** Published routines that become direct tools `routine_<name>` (names, or `all`). */
|
|
55
|
+
routines?: readonly string[];
|
|
56
|
+
/** Opt-in toolsets of the shared table beside the core tools (`sandboxes`, `vision`, `routines`, `infer`, `platform`). */
|
|
57
|
+
toolsets?: readonly string[];
|
|
58
|
+
/**
|
|
59
|
+
* Feature flags on for the caller's organization (`x-b3os-flag`). A table tool of a preview operation is listed,
|
|
60
|
+
* and callable, only when its flag is here; by default none is (W3-0b-8).
|
|
61
|
+
*/
|
|
62
|
+
flags?: readonly string[];
|
|
44
63
|
/** Replace the tool set (tests, custom servers). */
|
|
45
64
|
tools?: readonly ToolDef[];
|
|
46
65
|
/** How long clients may cache tools/list (modern protocol). Default 5 minutes. */
|
|
47
66
|
ttlMs?: number;
|
|
67
|
+
/** Which of the packs' tools to serve (`effects`, `actions`). */
|
|
68
|
+
packFilter?: PackToolFilter;
|
|
69
|
+
/**
|
|
70
|
+
* Told about each pack that serves no tools and each pack or routine tool left out because its name is taken
|
|
71
|
+
* (the stdio server writes them to stderr). The same lines go to the client as `notifications/message`, in
|
|
72
|
+
* `tools/list` as `_meta.warnings`, and unresolved packs are named in the instructions.
|
|
73
|
+
*/
|
|
74
|
+
onWarning?: (message: string) => void;
|
|
75
|
+
/**
|
|
76
|
+
* Warnings about a `tools` set built by the caller (the edge loads pack tools itself and caches them), and the
|
|
77
|
+
* requested packs that serve nothing, for the instructions.
|
|
78
|
+
*/
|
|
79
|
+
warnings?: readonly string[];
|
|
80
|
+
unresolvedPacks?: readonly string[];
|
|
81
|
+
/**
|
|
82
|
+
* How tools/list writes input schemas (platform-dx.7, compact.ts): `compact` (the default) keeps names, types,
|
|
83
|
+
* enums, requiredness and object arguments' first sentence; `full` lists the table's schemas as they are. Calls
|
|
84
|
+
* are always checked against the full schema.
|
|
85
|
+
*/
|
|
86
|
+
detail?: "compact" | "full";
|
|
87
|
+
/** List and serve only these tools, by name (`?tools=` on /mcp, `--tools` on stdio); unknown names are warned about. */
|
|
88
|
+
only?: readonly string[];
|
|
89
|
+
/**
|
|
90
|
+
* The text of an `unauthorized` tool error, in place of the API's: what the agent should ask the user to do. The
|
|
91
|
+
* stdio server sets it (an agent cannot send an Authorization header, but the user can run `b3os login`); the
|
|
92
|
+
* edge's /mcp does not, so its errors stay the API's.
|
|
93
|
+
*/
|
|
94
|
+
authHelp?: (apiDetail: string) => string;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** The instructions, plus a line naming the requested packs this session cannot serve. */
|
|
98
|
+
export function instructionsWith(unresolved: readonly string[]): string {
|
|
99
|
+
if (!unresolved.length) return INSTRUCTIONS;
|
|
100
|
+
return `${INSTRUCTIONS}\n\nNot available in this session: the tools of ${unresolved.join(", ")} (see the warnings in tools/list). Their actions can still be found with actions_search and run with actions_call.`;
|
|
48
101
|
}
|
|
49
102
|
|
|
50
103
|
const ERR = {
|
|
@@ -59,9 +112,24 @@ const ERR = {
|
|
|
59
112
|
export class McpServer {
|
|
60
113
|
private readonly client: B3OS;
|
|
61
114
|
private readonly packs: readonly string[];
|
|
115
|
+
private readonly routines: readonly string[];
|
|
116
|
+
private readonly toolsets: readonly string[];
|
|
117
|
+
private readonly flags: readonly string[];
|
|
118
|
+
private readonly onWarning: ((message: string) => void) | undefined;
|
|
119
|
+
private readonly packFilter: PackToolFilter;
|
|
120
|
+
private readonly warnings: string[];
|
|
121
|
+
private readonly unresolved: string[];
|
|
122
|
+
/** How many warnings went to the client as notifications/message already. */
|
|
123
|
+
private notified = 0;
|
|
124
|
+
/** The level a legacy client set with `logging/setLevel` (none: no log notifications). */
|
|
125
|
+
private logLevel: string | undefined;
|
|
62
126
|
private tools: readonly ToolDef[] | undefined;
|
|
63
127
|
private toolsLoading: Promise<readonly ToolDef[]> | undefined;
|
|
64
128
|
private readonly ttlMs: number;
|
|
129
|
+
private readonly detail: "compact" | "full";
|
|
130
|
+
private readonly only: ReadonlySet<string> | null;
|
|
131
|
+
private onlyChecked = false;
|
|
132
|
+
private readonly authHelp: McpServerOptions["authHelp"];
|
|
65
133
|
/** The version a legacy `initialize` negotiated, for this process (stdio) or session. */
|
|
66
134
|
legacyVersion: string | undefined;
|
|
67
135
|
private readonly inflight = new Map<Id, AbortController>();
|
|
@@ -69,16 +137,94 @@ export class McpServer {
|
|
|
69
137
|
constructor(opts: McpServerOptions) {
|
|
70
138
|
this.client = opts.client;
|
|
71
139
|
this.packs = opts.packs ?? [];
|
|
140
|
+
this.routines = opts.routines ?? [];
|
|
141
|
+
this.toolsets = opts.toolsets ?? [];
|
|
142
|
+
this.flags = opts.flags ?? [];
|
|
72
143
|
this.tools = opts.tools;
|
|
73
144
|
this.ttlMs = opts.ttlMs ?? 300_000;
|
|
145
|
+
this.onWarning = opts.onWarning;
|
|
146
|
+
this.packFilter = opts.packFilter ?? {};
|
|
147
|
+
this.warnings = [...(opts.warnings ?? [])];
|
|
148
|
+
this.unresolved = [...(opts.unresolvedPacks ?? [])];
|
|
149
|
+
this.detail = opts.detail ?? "compact";
|
|
150
|
+
this.only = opts.only?.length ? new Set(opts.only) : null;
|
|
151
|
+
this.authHelp = opts.authHelp;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** The tools this server lists and serves: every tool, or the ones `only` names. */
|
|
155
|
+
private async listed(): Promise<readonly ToolDef[]> {
|
|
156
|
+
const all = await this.toolList();
|
|
157
|
+
if (!this.only) return all;
|
|
158
|
+
if (!this.onlyChecked) {
|
|
159
|
+
this.onlyChecked = true;
|
|
160
|
+
const names = new Set(all.map((t) => t.name));
|
|
161
|
+
const unknown = [...this.only].filter((n) => !names.has(n));
|
|
162
|
+
if (unknown.length) this.warn(`tools= names no tool here: ${unknown.slice(0, 10).join(", ")}`);
|
|
163
|
+
}
|
|
164
|
+
return all.filter((t) => this.only?.has(t.name));
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
private warn(message: string): void {
|
|
168
|
+
this.warnings.push(message);
|
|
169
|
+
this.onWarning?.(message);
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* Sends the warnings the client has not seen yet as `notifications/message` (level warning), only when the client
|
|
174
|
+
* asked for log messages at warning or below: a legacy session that set a level with `logging/setLevel`, or a
|
|
175
|
+
* request that carries `logLevel` (MCP 2026-07-28 forbids unsolicited log notifications; PD7). Otherwise the
|
|
176
|
+
* warnings reach the client only through `_meta.warnings` and the instructions (and stderr on stdio).
|
|
177
|
+
*/
|
|
178
|
+
private flushWarnings(send: (m: Outgoing) => void, requestLevel?: unknown): void {
|
|
179
|
+
const level = typeof requestLevel === "string" ? requestLevel : this.logLevel;
|
|
180
|
+
if (!level || !LOG_LEVELS.includes(level) || LOG_LEVELS.indexOf(level) > LOG_LEVELS.indexOf("warning")) return;
|
|
181
|
+
for (; this.notified < this.warnings.length; this.notified++) {
|
|
182
|
+
send({
|
|
183
|
+
jsonrpc: "2.0",
|
|
184
|
+
method: "notifications/message",
|
|
185
|
+
params: { level: "warning", logger: "b3os", data: this.warnings[this.notified] },
|
|
186
|
+
});
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** Whether this server can have anything to warn about (it then declares the logging capability). */
|
|
191
|
+
private get mayWarn(): boolean {
|
|
192
|
+
return this.packs.length > 0 || this.routines.length > 0 || this.warnings.length > 0;
|
|
74
193
|
}
|
|
75
194
|
|
|
76
195
|
private async toolList(): Promise<readonly ToolDef[]> {
|
|
77
196
|
if (this.tools) return this.tools;
|
|
78
197
|
this.toolsLoading ??= (async () => {
|
|
79
|
-
const
|
|
80
|
-
const
|
|
81
|
-
|
|
198
|
+
const base = tableTools(this.toolsets, this.flags);
|
|
199
|
+
const [packs, routines] = await Promise.all([
|
|
200
|
+
this.packs.length ? loadPackTools(this.client, this.packs, this.packFilter) : undefined,
|
|
201
|
+
this.routines.length
|
|
202
|
+
? routineTools(this.client, this.routines).catch((e: unknown) => {
|
|
203
|
+
this.warn(`routines serve no tools: ${(e as Error)?.message ?? String(e)}`);
|
|
204
|
+
return [] as ToolDef[];
|
|
205
|
+
})
|
|
206
|
+
: [],
|
|
207
|
+
]);
|
|
208
|
+
for (const w of packs?.warnings ?? []) this.warn(w);
|
|
209
|
+
this.unresolved.push(...(packs?.unresolved ?? []));
|
|
210
|
+
const extra = [...(packs?.tools ?? []), ...routines];
|
|
211
|
+
const seen = new Set(base.map((t) => t.name));
|
|
212
|
+
const tools = [...base];
|
|
213
|
+
for (const t of extra) {
|
|
214
|
+
if (!seen.has(t.name)) {
|
|
215
|
+
seen.add(t.name);
|
|
216
|
+
tools.push(t);
|
|
217
|
+
continue;
|
|
218
|
+
}
|
|
219
|
+
// routine_<name> of a routine called run, get-run or signal is a table tool's name, and two long names can
|
|
220
|
+
// share their first 64 characters: say so instead of dropping the tool silently.
|
|
221
|
+
const src = t.source;
|
|
222
|
+
this.warn(
|
|
223
|
+
src?.kind === "routine"
|
|
224
|
+
? `not serving routine ${src.name} as a tool: the name ${t.name} is taken; run it with routine_run (routine: "${src.name}")`
|
|
225
|
+
: `not serving ${src?.kind === "action" ? `action ${src.ref}` : t.title} as a tool: the name ${t.name} is taken; call it with actions_call`,
|
|
226
|
+
);
|
|
227
|
+
}
|
|
82
228
|
this.tools = tools;
|
|
83
229
|
return tools;
|
|
84
230
|
})();
|
|
@@ -163,27 +309,42 @@ export class McpServer {
|
|
|
163
309
|
const asked = typeof p.protocolVersion === "string" ? p.protocolVersion : undefined;
|
|
164
310
|
const version = asked && (LEGACY_VERSIONS as readonly string[]).includes(asked) ? asked : LEGACY_VERSIONS[0];
|
|
165
311
|
this.legacyVersion = version;
|
|
312
|
+
// Pack and routine tools load first, so the instructions can name the packs that serve nothing.
|
|
313
|
+
if (this.mayWarn) await this.toolList();
|
|
166
314
|
return {
|
|
167
315
|
protocolVersion: version,
|
|
168
|
-
capabilities: { tools: { listChanged: false } },
|
|
316
|
+
capabilities: { tools: { listChanged: false }, ...(this.mayWarn ? { logging: {} } : {}) },
|
|
169
317
|
serverInfo: version >= "2025-06-18" ? SERVER_INFO : { name: SERVER_INFO.name, version: SERVER_INFO.version },
|
|
170
|
-
instructions:
|
|
318
|
+
instructions: instructionsWith(this.unresolved),
|
|
171
319
|
};
|
|
172
320
|
}
|
|
173
321
|
case "server/discover":
|
|
322
|
+
if (this.mayWarn) await this.toolList();
|
|
174
323
|
return {
|
|
175
324
|
resultType: "complete",
|
|
176
325
|
supportedVersions: [...MODERN_VERSIONS, ...LEGACY_VERSIONS],
|
|
326
|
+
// Logging is deprecated in 2026-07-28; a modern request asks for log messages with `logLevel`.
|
|
177
327
|
capabilities: { tools: {} },
|
|
178
328
|
_meta: { [META_SERVER_INFO]: SERVER_INFO },
|
|
179
|
-
instructions:
|
|
329
|
+
instructions: instructionsWith(this.unresolved),
|
|
180
330
|
ttlMs: this.ttlMs,
|
|
181
|
-
cacheScope: "public",
|
|
331
|
+
cacheScope: this.mayWarn ? "private" : "public",
|
|
182
332
|
};
|
|
183
333
|
case "ping":
|
|
184
334
|
return {};
|
|
335
|
+
case "logging/setLevel": {
|
|
336
|
+
const level = p.level;
|
|
337
|
+
if (typeof level !== "string" || !LOG_LEVELS.includes(level))
|
|
338
|
+
throw new RpcError(ERR.invalidParams, `level must be one of ${LOG_LEVELS.join(", ")}`);
|
|
339
|
+
this.logLevel = level;
|
|
340
|
+
return {};
|
|
341
|
+
}
|
|
185
342
|
case "tools/list": {
|
|
186
|
-
const tools = await this.
|
|
343
|
+
const tools = await this.listed();
|
|
344
|
+
this.flushWarnings(
|
|
345
|
+
send,
|
|
346
|
+
p.logLevel ?? (p._meta as Record<string, unknown> | undefined)?.["io.modelcontextprotocol/logLevel"],
|
|
347
|
+
);
|
|
187
348
|
const newer = modern || (this.legacyVersion ?? LEGACY_VERSIONS[0]) >= "2025-06-18";
|
|
188
349
|
return this.withMeta(
|
|
189
350
|
modern,
|
|
@@ -192,9 +353,12 @@ export class McpServer {
|
|
|
192
353
|
name: t.name,
|
|
193
354
|
...(newer ? { title: t.title } : {}),
|
|
194
355
|
description: t.description,
|
|
195
|
-
inputSchema: t.inputSchema,
|
|
196
|
-
annotations
|
|
356
|
+
inputSchema: this.detail === "full" ? t.inputSchema : compactSchema(t.inputSchema),
|
|
357
|
+
// A client that reads the tool's own title (2025-06-18 on) gets no second copy in the annotations.
|
|
358
|
+
annotations: newer && this.detail !== "full" ? withoutTitle(t.annotations) : t.annotations,
|
|
359
|
+
...(t.meta ? { _meta: t.meta } : {}),
|
|
197
360
|
})),
|
|
361
|
+
...(this.warnings.length ? { _meta: { warnings: [...this.warnings] } } : {}),
|
|
198
362
|
},
|
|
199
363
|
true,
|
|
200
364
|
);
|
|
@@ -202,7 +366,7 @@ export class McpServer {
|
|
|
202
366
|
case "tools/call": {
|
|
203
367
|
const name = p.name;
|
|
204
368
|
if (typeof name !== "string") throw new RpcError(ERR.invalidParams, "tools/call needs a tool name");
|
|
205
|
-
const tool = (await this.
|
|
369
|
+
const tool = (await this.listed()).find((t) => t.name === name);
|
|
206
370
|
if (!tool) throw new RpcError(ERR.invalidParams, `Unknown tool: ${name}`);
|
|
207
371
|
const args = (p.arguments ?? {}) as Record<string, unknown>;
|
|
208
372
|
if (typeof args !== "object" || Array.isArray(args))
|
|
@@ -210,10 +374,14 @@ export class McpServer {
|
|
|
210
374
|
const ac = new AbortController();
|
|
211
375
|
this.inflight.set(id, ac);
|
|
212
376
|
const token = (p._meta as Record<string, unknown> | undefined)?.progressToken;
|
|
377
|
+
// Trace context per message (PD27): it wins over the transport's (the HTTP header the edge's client carries).
|
|
378
|
+
const tp = (p._meta as Record<string, unknown> | undefined)?.traceparent;
|
|
379
|
+
const traceparent = typeof tp === "string" && TRACEPARENT_RE.test(tp.trim()) ? tp.trim() : undefined;
|
|
213
380
|
let result: ToolResult;
|
|
214
381
|
try {
|
|
215
382
|
result = await tool.call(this.client, args, {
|
|
216
383
|
signal: ac.signal,
|
|
384
|
+
...(traceparent ? { traceparent } : {}),
|
|
217
385
|
progress:
|
|
218
386
|
token === undefined
|
|
219
387
|
? undefined
|
|
@@ -234,6 +402,8 @@ export class McpServer {
|
|
|
234
402
|
} finally {
|
|
235
403
|
this.inflight.delete(id);
|
|
236
404
|
}
|
|
405
|
+
if (result.isError && this.authHelp) result = withAuthHelp(result, this.authHelp);
|
|
406
|
+
if (result.isError && this.detail !== "full") result = withArgumentDetail(result, tool.inputSchema);
|
|
237
407
|
const newer = modern || (this.legacyVersion ?? LEGACY_VERSIONS[0]) >= "2025-06-18";
|
|
238
408
|
const out: Record<string, unknown> = { content: result.content };
|
|
239
409
|
if (result.isError) out.isError = true;
|
|
@@ -253,6 +423,42 @@ export class McpServer {
|
|
|
253
423
|
}
|
|
254
424
|
}
|
|
255
425
|
|
|
426
|
+
function withoutTitle<T extends { title?: unknown }>(annotations: T): Omit<T, "title"> {
|
|
427
|
+
const { title: _title, ...rest } = annotations;
|
|
428
|
+
return rest;
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
/**
|
|
432
|
+
* A refused call's answer from the compact listing (platform-dx.7): the full description of every argument the
|
|
433
|
+
* errors name, after the error lines, so the detail tools/list left out arrives when a call needs it.
|
|
434
|
+
*/
|
|
435
|
+
function withArgumentDetail(result: ToolResult, schema: Record<string, unknown>): ToolResult {
|
|
436
|
+
const errors = (result.structuredContent as { error?: { errors?: unknown } } | undefined)?.error?.errors;
|
|
437
|
+
if (!Array.isArray(errors) || !errors.length) return result;
|
|
438
|
+
const lines = detailFor(
|
|
439
|
+
schema,
|
|
440
|
+
errors.filter((e): e is { pointer: string } => typeof (e as { pointer?: unknown })?.pointer === "string"),
|
|
441
|
+
);
|
|
442
|
+
if (!lines.length) return result;
|
|
443
|
+
return {
|
|
444
|
+
...result,
|
|
445
|
+
content: [...result.content, { type: "text", text: `About those arguments:\n${lines.join("\n")}` }],
|
|
446
|
+
};
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
/** An `unauthorized` tool error with the server's `authHelp` text in place of the API's detail. */
|
|
450
|
+
function withAuthHelp(result: ToolResult, help: NonNullable<McpServerOptions["authHelp"]>): ToolResult {
|
|
451
|
+
const error = (result.structuredContent as { error?: Record<string, unknown> } | undefined)?.error;
|
|
452
|
+
if (!error || error.code !== "unauthorized") return result;
|
|
453
|
+
const detail = help(typeof error.detail === "string" ? error.detail : "");
|
|
454
|
+
const rid = typeof error.request_id === "string" && error.request_id ? `\n(request ${error.request_id})` : "";
|
|
455
|
+
return {
|
|
456
|
+
...result,
|
|
457
|
+
content: [{ type: "text", text: `unauthorized: ${detail}${rid}` }],
|
|
458
|
+
structuredContent: { ...result.structuredContent, error: { ...error, detail } },
|
|
459
|
+
};
|
|
460
|
+
}
|
|
461
|
+
|
|
256
462
|
class RpcError extends Error {
|
|
257
463
|
readonly code: number;
|
|
258
464
|
readonly data: unknown;
|
package/src/stdio.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// The stdio transport: newline-delimited JSON-RPC on stdin/stdout, logs on stderr only (MCP stdio rules).
|
|
2
2
|
|
|
3
|
-
import { readFileSync } from "node:fs";
|
|
3
|
+
import { appendFileSync, readFileSync } from "node:fs";
|
|
4
4
|
import { homedir } from "node:os";
|
|
5
5
|
import { join } from "node:path";
|
|
6
6
|
import { B3OS, DEFAULT_BASE_URL } from "@b3os/sdk";
|
|
@@ -9,6 +9,29 @@ import { McpServer, type McpServerOptions, type Outgoing } from "./server.ts";
|
|
|
9
9
|
export interface StdioOptions extends Partial<McpServerOptions> {
|
|
10
10
|
input?: NodeJS.ReadableStream;
|
|
11
11
|
output?: { write(s: string): unknown };
|
|
12
|
+
/**
|
|
13
|
+
* Appends one JSON line per received message (time, method, protocol revision, tool name; never arguments or
|
|
14
|
+
* results) to this file: how to see what a client speaks. Default: $B3OS_MCP_TRACE.
|
|
15
|
+
*/
|
|
16
|
+
traceFile?: string;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** What a trace line records about one message: no parameters, so no argument or credential ever lands in it. */
|
|
20
|
+
function traceLine(m: unknown): string {
|
|
21
|
+
const o = (m && typeof m === "object" ? m : {}) as {
|
|
22
|
+
method?: unknown;
|
|
23
|
+
id?: unknown;
|
|
24
|
+
params?: Record<string, unknown>;
|
|
25
|
+
};
|
|
26
|
+
const meta = (o.params?._meta ?? {}) as Record<string, unknown>;
|
|
27
|
+
const rev = meta["io.modelcontextprotocol/protocolVersion"] ?? o.params?.protocolVersion;
|
|
28
|
+
return `${JSON.stringify({
|
|
29
|
+
ts: new Date().toISOString(),
|
|
30
|
+
method: typeof o.method === "string" ? o.method : null,
|
|
31
|
+
request: o.id !== undefined && o.id !== null,
|
|
32
|
+
protocol: typeof rev === "string" ? rev : null,
|
|
33
|
+
...(o.method === "tools/call" && typeof o.params?.name === "string" ? { tool: o.params.name } : {}),
|
|
34
|
+
})}\n`;
|
|
12
35
|
}
|
|
13
36
|
|
|
14
37
|
/** The `b3os login` token, when there is one (same file as the CLI: $XDG_CONFIG_HOME/b3os/credentials.json). */
|
|
@@ -29,27 +52,94 @@ export function storedLogin(): { token: string; base_url?: string } | undefined
|
|
|
29
52
|
}
|
|
30
53
|
}
|
|
31
54
|
|
|
32
|
-
/**
|
|
55
|
+
/**
|
|
56
|
+
* Drops B3OS_* variables whose value is an unexpanded client reference (`${env:B3OS_API_KEY}`,
|
|
57
|
+
* `${B3OS_BASE_URL}`): Cursor passes the reference itself when the variable is unset in its environment, and such
|
|
58
|
+
* a value is never a key or URL. The stored login (or the defaults) then apply. Returns the names dropped.
|
|
59
|
+
*/
|
|
60
|
+
export function dropUnexpandedReferences(env: NodeJS.ProcessEnv = process.env): string[] {
|
|
61
|
+
const dropped: string[] = [];
|
|
62
|
+
for (const [k, v] of Object.entries(env)) {
|
|
63
|
+
if (k.startsWith("B3OS_") && typeof v === "string" && /^\$\{[^}]*\}$/.test(v.trim())) {
|
|
64
|
+
delete env[k];
|
|
65
|
+
dropped.push(k);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
return dropped;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* A client from B3OS_API_KEY (or the node socket / sandbox URL), else the stored CLI login under the SDK's rules
|
|
73
|
+
* (core/login.ts): only on a developer's machine, never in CI, on GitHub Actions or in a B3OS sandbox, and only
|
|
74
|
+
* for the API host the login was issued by, so B3OS_BASE_URL naming another host gets no key.
|
|
75
|
+
*/
|
|
33
76
|
export function defaultClient(): B3OS {
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
77
|
+
return new B3OS();
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** Where a client's key came from, found by comparing values (never printed). */
|
|
81
|
+
export type CredentialSource = "B3OS_API_KEY" | "b3os login" | "a key" | "none";
|
|
82
|
+
|
|
83
|
+
export function credentialSource(client: B3OS): CredentialSource {
|
|
84
|
+
const key = client.apiKey;
|
|
85
|
+
if (!key) return "none";
|
|
86
|
+
if (process.env.B3OS_API_KEY === key) return "B3OS_API_KEY";
|
|
87
|
+
if (storedLogin()?.token === key) return "b3os login";
|
|
88
|
+
return "a key";
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* What an `unauthorized` tool error tells the agent, by where the server's credential came from. An agent cannot
|
|
93
|
+
* sign in or send headers; the person it works for can run `b3os login`.
|
|
94
|
+
*/
|
|
95
|
+
export function authHelpFor(source: CredentialSource): (apiDetail: string) => string {
|
|
96
|
+
return (apiDetail) => {
|
|
97
|
+
const why = apiDetail.replace(/[.\s]+$/, "");
|
|
98
|
+
switch (source) {
|
|
99
|
+
case "none":
|
|
100
|
+
return (
|
|
101
|
+
"Not signed in to B3OS. Ask the user to run `b3os login` in a terminal (or to set B3OS_API_KEY in this " +
|
|
102
|
+
"MCP server's settings), then call the tool again."
|
|
103
|
+
);
|
|
104
|
+
case "b3os login":
|
|
105
|
+
return `B3OS refused the user's b3os login (${why}). Ask the user to run \`b3os login\` again, then call the tool again.`;
|
|
106
|
+
case "B3OS_API_KEY":
|
|
107
|
+
return (
|
|
108
|
+
`B3OS refused the key in B3OS_API_KEY (${why}). Ask the user to put a working key in this MCP server's ` +
|
|
109
|
+
"settings, or to remove it and run `b3os login`."
|
|
110
|
+
);
|
|
111
|
+
default:
|
|
112
|
+
return `B3OS refused this server's API key (${why}). Ask the user for a working key.`;
|
|
113
|
+
}
|
|
114
|
+
};
|
|
41
115
|
}
|
|
42
116
|
|
|
43
117
|
/** Serves MCP over stdin/stdout until stdin ends. */
|
|
44
118
|
export async function serveStdio(opts: StdioOptions = {}): Promise<void> {
|
|
119
|
+
if (!opts.client) {
|
|
120
|
+
const dropped = dropUnexpandedReferences();
|
|
121
|
+
if (dropped.length)
|
|
122
|
+
process.stderr.write(`b3os-mcp: ignoring ${dropped.join(", ")}: the MCP client passed an unexpanded reference\n`);
|
|
123
|
+
}
|
|
45
124
|
const client = opts.client ?? defaultClient();
|
|
46
|
-
const
|
|
125
|
+
const source = credentialSource(client);
|
|
126
|
+
if (source === "none" && client.routes.nodeKind === "edge")
|
|
127
|
+
process.stderr.write(
|
|
128
|
+
"b3os-mcp: not signed in, so each tool call will ask the user to run b3os login (or to set B3OS_API_KEY)\n",
|
|
129
|
+
);
|
|
130
|
+
const server = new McpServer({
|
|
131
|
+
onWarning: (m) => process.stderr.write(`b3os-mcp: ${m}\n`),
|
|
132
|
+
authHelp: authHelpFor(source),
|
|
133
|
+
...opts,
|
|
134
|
+
client,
|
|
135
|
+
});
|
|
47
136
|
const input = opts.input ?? process.stdin;
|
|
48
137
|
const output = opts.output ?? process.stdout;
|
|
49
138
|
const send = (m: Outgoing) => {
|
|
50
139
|
output.write(`${JSON.stringify(m)}\n`);
|
|
51
140
|
};
|
|
52
141
|
const pending = new Set<Promise<void>>();
|
|
142
|
+
const trace = opts.traceFile ?? process.env.B3OS_MCP_TRACE;
|
|
53
143
|
let buf = "";
|
|
54
144
|
const dispatch = (line: string) => {
|
|
55
145
|
const t = line.trim();
|
|
@@ -63,6 +153,13 @@ export async function serveStdio(opts: StdioOptions = {}): Promise<void> {
|
|
|
63
153
|
}
|
|
64
154
|
const items = Array.isArray(msg) ? msg : [msg];
|
|
65
155
|
for (const item of items) {
|
|
156
|
+
if (trace) {
|
|
157
|
+
try {
|
|
158
|
+
appendFileSync(trace, traceLine(item));
|
|
159
|
+
} catch {
|
|
160
|
+
// tracing never breaks the server
|
|
161
|
+
}
|
|
162
|
+
}
|
|
66
163
|
const p = server.handle(item, send).catch((e: unknown) => {
|
|
67
164
|
process.stderr.write(`b3os-mcp: ${(e as Error)?.stack ?? e}\n`);
|
|
68
165
|
});
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
// Types of the MCP tool table (src/table.gen.ts, table/table.json): what a server needs to list a tool and to turn
|
|
2
|
+
// its arguments into an API request. No runtime code, so any consumer can import it.
|
|
3
|
+
|
|
4
|
+
export interface JsonSchemaObject {
|
|
5
|
+
type: "object";
|
|
6
|
+
properties: Record<string, unknown>;
|
|
7
|
+
required?: string[];
|
|
8
|
+
additionalProperties?: boolean;
|
|
9
|
+
[k: string]: unknown;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface ToolAnnotations {
|
|
13
|
+
title?: string;
|
|
14
|
+
readOnlyHint?: boolean;
|
|
15
|
+
destructiveHint?: boolean;
|
|
16
|
+
idempotentHint?: boolean;
|
|
17
|
+
openWorldHint?: boolean;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** An API operation a tool calls. */
|
|
21
|
+
export interface McpTableOperation {
|
|
22
|
+
method: string;
|
|
23
|
+
path: string;
|
|
24
|
+
pathParams: readonly string[];
|
|
25
|
+
scope: string;
|
|
26
|
+
servedBy: string;
|
|
27
|
+
/** Takes `Idempotency-Key` (routes.json `idempotent_key`). */
|
|
28
|
+
idempotent: boolean;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** A query parameter of the tool's operation: an argument of the same name, or filled from a tool argument. */
|
|
32
|
+
export interface McpTableQueryParam {
|
|
33
|
+
name: string;
|
|
34
|
+
/** Filled from this tool argument instead (`wait` from `wait_s`). */
|
|
35
|
+
from?: string;
|
|
36
|
+
/** The argument is a boolean sent as `1` / `0` (the API's integer flag). */
|
|
37
|
+
encode?: "01";
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** An operation the tool calls after the main one when an argument is present (`job_id` continues a job). */
|
|
41
|
+
export interface McpTableContinuation {
|
|
42
|
+
arg: string;
|
|
43
|
+
operationId: string;
|
|
44
|
+
method: string;
|
|
45
|
+
path: string;
|
|
46
|
+
pathParam: string;
|
|
47
|
+
/** A paginated companion read after the job (a crawl's pages). */
|
|
48
|
+
pages?: { operationId: string; method: string; path: string };
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export interface McpTableTool {
|
|
52
|
+
name: string;
|
|
53
|
+
/** `core` tools are always listed; other groups are opt-in toolsets. */
|
|
54
|
+
group: string;
|
|
55
|
+
title: string;
|
|
56
|
+
description: string;
|
|
57
|
+
annotations: ToolAnnotations;
|
|
58
|
+
inputSchema: JsonSchemaObject;
|
|
59
|
+
/** The operation the tool calls (operationId in packages/spec/dist/openapi.json). */
|
|
60
|
+
operationId: string;
|
|
61
|
+
method: string;
|
|
62
|
+
path: string;
|
|
63
|
+
/** `x-b3os-scope`: the edge lists a tool only to credentials that hold it. */
|
|
64
|
+
scope: string;
|
|
65
|
+
servedBy: string;
|
|
66
|
+
/**
|
|
67
|
+
* `preview`: the operation is `x-b3os-stage: preview` (common.yaml). The tool is listed only to an organization
|
|
68
|
+
* with `flag` on (selectTools); absent for every other stage.
|
|
69
|
+
*/
|
|
70
|
+
stage?: "preview";
|
|
71
|
+
/** The operation's `x-b3os-flag`, set with `stage: "preview"`. */
|
|
72
|
+
flag?: string;
|
|
73
|
+
/** Path parameters, each an argument of the same name. */
|
|
74
|
+
pathParams: readonly string[];
|
|
75
|
+
queryParams: readonly McpTableQueryParam[];
|
|
76
|
+
/** `json`: `bodyFields` arguments become the JSON body; `raw`: `content` (+ `encoding`) is the binary body. */
|
|
77
|
+
body: "none" | "json" | "raw";
|
|
78
|
+
bodyFields: readonly string[];
|
|
79
|
+
rawFields: readonly string[];
|
|
80
|
+
/** Arguments the tool consumes itself; never sent to the API. */
|
|
81
|
+
toolArgs: readonly string[];
|
|
82
|
+
/** Sent when the caller leaves them out. */
|
|
83
|
+
bodyDefaults: Readonly<Record<string, unknown>>;
|
|
84
|
+
queryDefaults: Readonly<Record<string, unknown>>;
|
|
85
|
+
continueWith?: McpTableContinuation;
|
|
86
|
+
/** Client-specific keys for tools/list `_meta` (Claude Code's `anthropic/maxResultSizeChars`, PD6). */
|
|
87
|
+
meta?: Readonly<Record<string, unknown>>;
|
|
88
|
+
}
|