@bike4mind/cli 1.2.0 → 2.1.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.
@@ -0,0 +1,1365 @@
1
+ #!/usr/bin/env node
2
+ import { Ct as ttsResponseTooLargeSchema, D as BriefcasePromptIdSchema, F as ImagePromptResolutionSchema, N as GENERATED_IMAGE_EXTENSION_RE, P as ImageModels, St as ttsRequestSchema, T as BRIEFCASE_CATALOG_QUERIES, U as PROMPT_TEXT_MAX, Z as buildPromptContext, _ as requireApiUrl, b as AGENT_QUEST_MANIFEST, ft as questReplyText, g as parseApiUrl, j as DEFAULT_TTS_PROVIDER, n as logger, pt as replacePromptVariables, t as ConfigStore, tt as generatedAudioResponseSchema, ut as joinReplySlots, x as AGENT_QUEST_MCP_URI, xt as ttsBase64ResponseSchema, y as AGENT_QUEST_ID, yt as supportedVoiceGenerationVendor } from "./ConfigStore-BygzEI6H.mjs";
3
+ import { n as NotAuthenticatedError, r as isProviderKeyFailure, t as ApiClient } from "./ApiClient-dIB3YQc2.mjs";
4
+ import { z as z$1 } from "zod";
5
+ import { isAxiosError } from "axios";
6
+ import { Writable } from "node:stream";
7
+ import { createServer } from "node:http";
8
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
9
+ import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
10
+ import { McpServer, ResourceTemplate } from "@modelcontextprotocol/sdk/server/mcp.js";
11
+ import { ErrorCode, GetPromptRequestSchema, ListPromptsRequestSchema, McpError } from "@modelcontextprotocol/sdk/types.js";
12
+ //#region src/mcp/b4mApiClient.ts
13
+ const NOTEBOOK_ID_PATTERN = /^[a-f0-9]{24}$/i;
14
+ /**
15
+ * An empty or dot-segment id collapses `/api/sessions/{id}` to `/api/sessions`, whose DELETE wipes every
16
+ * notebook the caller owns, so write paths refuse anything that is not an ObjectId before any request.
17
+ */
18
+ function notebookPath(notebookId) {
19
+ if (!NOTEBOOK_ID_PATTERN.test(notebookId)) throw new Error(`Invalid notebook id: ${JSON.stringify(notebookId)}`);
20
+ return `/api/sessions/${notebookId}`;
21
+ }
22
+ /**
23
+ * Typed wrapper over {@link ApiClient} exposing exactly the Bike4Mind REST
24
+ * endpoints the MCP tools call. All routes are `baseApi()` routes that accept
25
+ * either an OAuth JWT or an instance API key, so a caller supplies whichever it
26
+ * has via the underlying ApiClient.
27
+ */
28
+ var B4mApiClient = class {
29
+ constructor(baseURL, configStore, apiKey) {
30
+ this.baseURL = baseURL;
31
+ this.client = new ApiClient(baseURL, configStore, apiKey);
32
+ }
33
+ toList(result) {
34
+ if (Array.isArray(result)) return {
35
+ data: result,
36
+ hasMore: false
37
+ };
38
+ return {
39
+ data: result.data ?? [],
40
+ hasMore: result.hasMore ?? false
41
+ };
42
+ }
43
+ async listNotebooks(args) {
44
+ const result = await this.client.get("/api/sessions", { params: {
45
+ ...args.search ? { search: args.search } : {},
46
+ pagination: {
47
+ page: args.page ?? 1,
48
+ limit: args.limit
49
+ }
50
+ } });
51
+ return this.toList(result);
52
+ }
53
+ async getNotebook(notebookId) {
54
+ return this.client.get(`/api/sessions/${encodeURIComponent(notebookId)}`);
55
+ }
56
+ async createNotebook(args) {
57
+ return this.client.post("/api/sessions/create", {
58
+ ...args.name ? { name: args.name } : {},
59
+ ...args.projectId ? { projectId: args.projectId } : {},
60
+ ...args.dataLakeId ? { dataLakeId: args.dataLakeId } : {}
61
+ });
62
+ }
63
+ async renameNotebook(notebookId, name) {
64
+ return this.client.put(notebookPath(notebookId), { name });
65
+ }
66
+ /** Returns the new (cloned) notebook. */
67
+ async cloneNotebook(notebookId) {
68
+ return this.client.post(`${notebookPath(notebookId)}/clone`, {});
69
+ }
70
+ async deleteNotebook(notebookId) {
71
+ return this.client.delete(notebookPath(notebookId), { maxRedirects: 0 });
72
+ }
73
+ /**
74
+ * GET /api/v1/data-lakes is cursor-paginated (flat `limit`/`cursor` params,
75
+ * `{ data, next_cursor }` body), so `toList` does not apply.
76
+ */
77
+ async listDataLakes(args) {
78
+ const result = await this.client.get("/api/v1/data-lakes", { params: {
79
+ limit: args.limit,
80
+ ...args.cursor ? { cursor: args.cursor } : {}
81
+ } });
82
+ return {
83
+ data: result.data ?? [],
84
+ nextCursor: result.next_cursor ?? null
85
+ };
86
+ }
87
+ async sendChat(args) {
88
+ return this.client.post("/api/chat", {
89
+ ...args.notebookId ? { sessionId: args.notebookId } : { newConversation: true },
90
+ message: args.message,
91
+ ...args.model ? { model: args.model } : {},
92
+ ...args.systemPrompt ? { systemPrompt: args.systemPrompt } : {},
93
+ wait: false
94
+ });
95
+ }
96
+ async getQuest(questId) {
97
+ return this.client.get(`/api/quests/${encodeURIComponent(questId)}`);
98
+ }
99
+ async searchKnowledgeBase(args) {
100
+ return (await this.client.post("/api/sessions/semantic-search", {
101
+ query: args.query,
102
+ topK: args.limit,
103
+ ...args.minSimilarity !== void 0 ? { minSimilarity: args.minSimilarity } : {}
104
+ })).scores ?? [];
105
+ }
106
+ async listFiles(args) {
107
+ const result = await this.client.get("/api/files/search", { params: {
108
+ ...args.search ? { search: args.search } : {},
109
+ pagination: {
110
+ page: args.page ?? 1,
111
+ limit: args.limit
112
+ }
113
+ } });
114
+ return this.toList(result);
115
+ }
116
+ async getFile(fileId) {
117
+ return this.client.get(`/api/files/${encodeURIComponent(fileId)}`);
118
+ }
119
+ /** Generate a sound effect; see {@link postGeneratedAudio} for the normalized response. */
120
+ async generateSoundEffect(args) {
121
+ return this.postGeneratedAudio("/api/ai/sound-effects", {
122
+ provider: args.provider,
123
+ text: args.text,
124
+ ...args.durationSeconds !== void 0 ? { durationSeconds: args.durationSeconds } : {},
125
+ ...args.promptInfluence !== void 0 ? { promptInfluence: args.promptInfluence } : {},
126
+ ...args.format ? { format: args.format } : {}
127
+ }, generatedAudioResponseSchema);
128
+ }
129
+ async synthesizeSpeech(args) {
130
+ try {
131
+ return {
132
+ kind: "audio",
133
+ data: await this.postGeneratedAudio("/api/ai/tts", args, ttsBase64ResponseSchema)
134
+ };
135
+ } catch (error) {
136
+ if (isAxiosError(error) && error.response?.status === 413) {
137
+ const oversized = ttsResponseTooLargeSchema.safeParse(error.response.data);
138
+ if (oversized.success && oversized.data.saved && oversized.data.fabFileId) {
139
+ const fallbackFrom = supportedVoiceGenerationVendor.safeParse(error.response.headers?.["x-b4m-tts-provider-fallback-from"]);
140
+ return {
141
+ kind: "saved-too-large",
142
+ data: {
143
+ ...oversized.data,
144
+ fabFileId: oversized.data.fabFileId
145
+ },
146
+ ...fallbackFrom.success ? { fallbackFrom: fallbackFrom.data } : {}
147
+ };
148
+ }
149
+ }
150
+ throw error;
151
+ }
152
+ }
153
+ async generateImage(args) {
154
+ return this.client.post("/api/ai/generate-image", {
155
+ prompt: args.prompt,
156
+ model: args.model,
157
+ ...args.size ? { size: args.size } : {},
158
+ ...args.notebookId ? { sessionId: args.notebookId } : {},
159
+ ...args.projectId ? { projectId: args.projectId } : {},
160
+ ...args.promptResolution ? { prompt_resolution: args.promptResolution } : {}
161
+ });
162
+ }
163
+ /**
164
+ * POST a generated-audio request with `encoding: 'base64'` and normalize any
165
+ * server's answer into the JSON shape `schema` describes. Base64 (never binary)
166
+ * because an oversized result is a 303 in binary mode, and axios drops the
167
+ * X-B4M headers when following it. A server predating the `encoding` field
168
+ * ignores it and streams raw bytes with the save result in X-B4M-Audio-* headers;
169
+ * those are rebuilt into the inline variant. The request is arraybuffer-typed, so
170
+ * a failure body arrives as bytes; {@link decodeArrayBufferErrorBody} restores
171
+ * its JSON shape for {@link mapApiError}.
172
+ */
173
+ async postGeneratedAudio(path, body, schema) {
174
+ const response = await this.client.getAxiosInstance().post(path, {
175
+ ...body,
176
+ encoding: "base64"
177
+ }, { responseType: "arraybuffer" }).catch((error) => {
178
+ throw decodeArrayBufferErrorBody(error);
179
+ });
180
+ const contentType = String(response.headers["content-type"] ?? "application/octet-stream");
181
+ const bytes = Buffer.from(response.data);
182
+ if (/json/i.test(contentType)) return schema.parse(JSON.parse(bytes.toString("utf8")));
183
+ const headerString = (value) => typeof value === "string" ? value : void 0;
184
+ const saved = String(response.headers["x-b4m-audio-saved"] ?? "") === "true";
185
+ return schema.parse({
186
+ delivery: "inline",
187
+ audio: bytes.toString("base64"),
188
+ contentType,
189
+ saved,
190
+ fabFileId: saved ? headerString(response.headers["x-b4m-audio-fab-file-id"]) : void 0,
191
+ fileName: saved ? headerString(response.headers["x-b4m-audio-file-name"]) : void 0,
192
+ fileUrl: saved ? headerString(response.headers["x-b4m-audio-file-url"]) : void 0
193
+ });
194
+ }
195
+ async listProjects(args) {
196
+ const result = await this.client.get("/api/projects", { params: {
197
+ ...args.search ? { search: args.search } : {},
198
+ pagination: {
199
+ page: args.page ?? 1,
200
+ limit: args.limit
201
+ }
202
+ } });
203
+ return this.toList(result);
204
+ }
205
+ async getProject(projectId) {
206
+ return this.client.get(`/api/projects/${encodeURIComponent(projectId)}`);
207
+ }
208
+ async createProject(args) {
209
+ return this.client.post("/api/projects", {
210
+ name: args.name,
211
+ description: args.description,
212
+ ...args.sessionIds?.length ? { sessionIds: args.sessionIds } : {},
213
+ ...args.fileIds?.length ? { fileIds: args.fileIds } : {}
214
+ });
215
+ }
216
+ /**
217
+ * GET /api/artifacts takes flat `limit`/`offset` params (not the nested
218
+ * `pagination` object the session/file/project routes use) and hard-caps
219
+ * `limit` at 100 via a strict zod parse, so callers must not exceed it.
220
+ */
221
+ async listArtifacts(args) {
222
+ const result = await this.client.get("/api/artifacts", { params: {
223
+ ...args.search ? { search: args.search } : {},
224
+ limit: args.limit,
225
+ offset: args.offset ?? 0
226
+ } });
227
+ return {
228
+ data: result.artifacts ?? [],
229
+ hasMore: result.pagination?.hasMore ?? false
230
+ };
231
+ }
232
+ async getArtifact(artifactId) {
233
+ return this.client.get(`/api/artifacts/${encodeURIComponent(artifactId)}`, { params: { includeContent: "true" } });
234
+ }
235
+ /**
236
+ * POST /api/briefcase/catalog: a key -> prompts map, one entry per query key.
237
+ *
238
+ * The route runs csrfProtection, which exempts API-key requests but rejects a
239
+ * login (JWT bearer) request that carries no Origin - and Node sends none. CSRF
240
+ * defends browsers, so a non-browser client naming the backend's own origin is
241
+ * the intended pass, not a bypass.
242
+ */
243
+ async getBriefcaseCatalog(queries) {
244
+ return (await this.client.post("/api/briefcase/catalog", { queries }, { headers: { Origin: new URL(this.baseURL).origin } })).catalog;
245
+ }
246
+ async getBriefcasePrompt(promptId) {
247
+ return (await this.client.get(`/api/briefcase/prompts/${encodeURIComponent(promptId)}`)).prompt;
248
+ }
249
+ };
250
+ /**
251
+ * Turn an API failure into an actionable, transport-agnostic message. `scope` is
252
+ * the recommended API-key scope for the failing tool. A 403 can come from a
253
+ * missing scope OR from a route-level authorization check (CASL forbidden,
254
+ * suspended account), so the message stays broad rather than asserting a scope
255
+ * gap that may not be the cause.
256
+ */
257
+ function mapApiError(error, baseURL, scope) {
258
+ if (error instanceof NotAuthenticatedError) return "not authenticated: no credential configured (set B4M_API_KEY or run `b4m login`)";
259
+ if (isAxiosError(error)) {
260
+ const status = error.response?.status;
261
+ if (status === 401) {
262
+ const providerKeyMessage = providerKeyFailureMessage(error.response?.data);
263
+ if (providerKeyMessage) return providerKeyMessage;
264
+ return "authentication failed (run `b4m login` or set B4M_API_KEY)";
265
+ }
266
+ if (status === 403) {
267
+ if ((error.response?.data)?.code === "FEATURE_DISABLED") return "feature disabled on this Bike4Mind instance (ask an admin to enable it)";
268
+ const csrfMessage = extractServerMessage(error.response?.data);
269
+ if (csrfMessage && /CSRF|request origin/i.test(csrfMessage)) return csrfMessage;
270
+ const base = "API key forbidden: check the key's scopes and account access";
271
+ return scope ? `${base} (recommended scope: ${scope})` : base;
272
+ }
273
+ if (status === 429) {
274
+ const retryAfterSeconds = parseRetryAfterSeconds(error.response?.headers?.["retry-after"]);
275
+ const base = extractServerMessage(error.response?.data) || "rate limit exceeded";
276
+ return retryAfterSeconds !== void 0 ? `${base} (retry after ${retryAfterSeconds}s)` : base;
277
+ }
278
+ if (error.code === "ECONNABORTED" || error.code === "ETIMEDOUT" || /timeout/i.test(error.message)) return `request to Bike4Mind at ${baseURL} timed out`;
279
+ if (error.code === "ECONNREFUSED" || error.message.includes("ECONNREFUSED")) return `cannot reach Bike4Mind at ${baseURL}`;
280
+ const serverMsg = extractServerMessage(error.response?.data);
281
+ if (serverMsg) return serverMsg;
282
+ return error.message;
283
+ }
284
+ return error instanceof Error ? error.message : String(error);
285
+ }
286
+ /**
287
+ * A request made with `responseType: 'arraybuffer'` also decodes its error body
288
+ * as bytes, so a JSON `{ error }` payload reaches us as a Buffer that
289
+ * {@link mapApiError} can't read. Decode it back to a parsed object in place so
290
+ * the server's message survives; leave a non-JSON body untouched.
291
+ */
292
+ function decodeArrayBufferErrorBody(error) {
293
+ if (!isAxiosError(error) || !error.response) return error;
294
+ const { data } = error.response;
295
+ if (typeof data === "string") {
296
+ try {
297
+ error.response.data = JSON.parse(data);
298
+ } catch {}
299
+ return error;
300
+ }
301
+ const bytes = Buffer.isBuffer(data) ? data : data instanceof ArrayBuffer ? Buffer.from(data) : ArrayBuffer.isView(data) ? Buffer.from(data.buffer, data.byteOffset, data.byteLength) : void 0;
302
+ if (!bytes) return error;
303
+ try {
304
+ error.response.data = JSON.parse(bytes.toString("utf8"));
305
+ } catch {}
306
+ return error;
307
+ }
308
+ /**
309
+ * Normalize a Retry-After header (RFC 7231: either delta-seconds or an HTTP-date)
310
+ * to a whole, non-negative number of seconds. Returns undefined when the header is
311
+ * absent or parses as neither, so callers can omit the retry hint entirely.
312
+ */
313
+ function parseRetryAfterSeconds(value) {
314
+ if (value === void 0 || value === null) return void 0;
315
+ const raw = String(value).trim();
316
+ if (/^\d+$/.test(raw)) return Number(raw);
317
+ const dateMs = Date.parse(raw);
318
+ if (Number.isNaN(dateMs)) return void 0;
319
+ return Math.max(0, Math.ceil((dateMs - Date.now()) / 1e3));
320
+ }
321
+ /** Pull a human-readable message out of a JSON error body (`error` or `message` field). */
322
+ function extractServerMessage(data) {
323
+ if (data && typeof data === "object") {
324
+ const record = data;
325
+ if (typeof record.error === "string") return record.error;
326
+ if (typeof record.message === "string") return record.message;
327
+ }
328
+ }
329
+ function providerKeyFailureMessage(data) {
330
+ if (!isProviderKeyFailure(data)) return void 0;
331
+ return `${extractServerMessage(data) ?? "the AI provider could not be used"} (configure or fix the provider API key in Bike4Mind; this is not a Bike4Mind login problem)`;
332
+ }
333
+ //#endregion
334
+ //#region src/mcp/tools.ts
335
+ const TOOL_META = [
336
+ {
337
+ name: "list_notebooks",
338
+ title: "List notebooks",
339
+ description: "List the caller's Bike4Mind notebooks (sessions).",
340
+ scope: "notebooks:read"
341
+ },
342
+ {
343
+ name: "get_notebook",
344
+ title: "Get notebook",
345
+ description: "Fetch a single notebook by id.",
346
+ scope: "notebooks:read"
347
+ },
348
+ {
349
+ name: "create_notebook",
350
+ title: "Create notebook",
351
+ description: "Create a new notebook, optionally inside a project or grounded in a data lake (dataLakeId, see list_lakes). Defaults the name to \"New Notebook\" when omitted.",
352
+ scope: "notebooks:write"
353
+ },
354
+ {
355
+ name: "rename_notebook",
356
+ title: "Rename notebook",
357
+ description: "Rename a notebook.",
358
+ scope: "notebooks:write"
359
+ },
360
+ {
361
+ name: "clone_notebook",
362
+ title: "Clone notebook",
363
+ description: "Clone a notebook into a new one; returns the new notebook.",
364
+ scope: "notebooks:write"
365
+ },
366
+ {
367
+ name: "delete_notebook",
368
+ title: "Delete notebook",
369
+ description: "Permanently delete a notebook and the files its owner uploaded to it; this cannot be undone through the API. Requires confirm: true. On a conflict (409) nothing was deleted, so retry.",
370
+ scope: "notebooks:write"
371
+ },
372
+ {
373
+ name: "list_projects",
374
+ title: "List projects",
375
+ description: "List the Bike4Mind projects the caller can access, including ones shared with them.",
376
+ scope: "projects:read"
377
+ },
378
+ {
379
+ name: "get_project",
380
+ title: "Get project",
381
+ description: "Fetch a single project by id.",
382
+ scope: "projects:read"
383
+ },
384
+ {
385
+ name: "create_project",
386
+ title: "Create project",
387
+ description: "Create a new project. Pass the returned id as projectId to create_notebook to create notebooks inside it.",
388
+ scope: "projects:write"
389
+ },
390
+ {
391
+ name: "send_message",
392
+ title: "Send message",
393
+ description: "Send a chat message and wait for the assistant reply, reporting progress while it is generated; returns the cited sources (citables) the answer was grounded in.",
394
+ scope: "ai:chat"
395
+ },
396
+ {
397
+ name: "search_knowledge_base",
398
+ title: "Search knowledge base",
399
+ description: "Semantic search across the caller's notebooks.",
400
+ scope: "notebooks:read"
401
+ },
402
+ {
403
+ name: "list_lakes",
404
+ title: "List data lakes",
405
+ description: "List the data lakes the caller can reach. Pass a lake's id as dataLakeId to create_notebook to ground a notebook in it.",
406
+ scope: "datalake:read"
407
+ },
408
+ {
409
+ name: "list_files",
410
+ title: "List files",
411
+ description: "Search the caller's files.",
412
+ scope: "files:read"
413
+ },
414
+ {
415
+ name: "get_file",
416
+ title: "Get file",
417
+ description: "Fetch a file's metadata and a signed download URL.",
418
+ scope: "files:read"
419
+ },
420
+ {
421
+ name: "generate_sound_effect",
422
+ title: "Generate sound effect",
423
+ description: "Generate a sound effect from a text description. Returns the saved audio file (with a signed download URL) when the caller keeps generated audio, otherwise the audio inline.",
424
+ scope: "ai:generate"
425
+ },
426
+ {
427
+ name: "text_to_speech",
428
+ title: "Text to speech",
429
+ description: "Synthesize speech from text. Returns a saved audio file with a signed download URL when available, otherwise audio inline.",
430
+ scope: "ai:generate"
431
+ },
432
+ {
433
+ name: "generate_image",
434
+ title: "Generate image",
435
+ description: "Generate an image from a text prompt and wait for the render. Returns the quest and notebook ids plus each image's file name and download URL. Image names are not file ids and do not work with get_file.",
436
+ scope: "ai:generate"
437
+ }
438
+ ];
439
+ TOOL_META.map((t) => t.name);
440
+ const listNotebooksShape = {
441
+ search: z$1.string().optional().describe("Filter notebooks by name/content"),
442
+ limit: z$1.number().int().min(1).max(100).default(25).describe("Maximum notebooks to return"),
443
+ page: z$1.number().int().min(1).default(1).describe("1-based page number; request the next page when hasMore is true")
444
+ };
445
+ const notebookId = (description) => z$1.string().regex(NOTEBOOK_ID_PATTERN, "notebookId must be a 24-character hex ObjectId").describe(description);
446
+ const getNotebookShape = { notebookId: notebookId("The notebook (session) id") };
447
+ const createNotebookShape = {
448
+ name: z$1.string().optional().describe("Name for the new notebook"),
449
+ projectId: z$1.string().optional().describe("Project to create the notebook in"),
450
+ dataLakeId: z$1.string().optional().describe("Data lake id or slug to ground the notebook in (see list_lakes); seeds the lake's retrieval defaults")
451
+ };
452
+ const renameNotebookShape = {
453
+ notebookId: notebookId("The notebook (session) id"),
454
+ name: z$1.string().min(1).describe("The new name")
455
+ };
456
+ const cloneNotebookShape = { notebookId: notebookId("The notebook (session) id to clone") };
457
+ const deleteNotebookShape = {
458
+ notebookId: notebookId("The notebook (session) id to delete"),
459
+ confirm: z$1.literal(true).describe("Must be true; the delete is permanent")
460
+ };
461
+ const listProjectsShape = {
462
+ search: z$1.string().optional().describe("Filter projects by name"),
463
+ limit: z$1.number().int().min(1).max(100).default(25).describe("Maximum projects to return"),
464
+ page: z$1.number().int().min(1).default(1).describe("1-based page number; request the next page when hasMore is true")
465
+ };
466
+ const getProjectShape = { projectId: z$1.string().describe("The project id") };
467
+ const createProjectShape = {
468
+ name: z$1.string().min(1).describe("Name for the new project; must be unique among your projects"),
469
+ description: z$1.string().min(1).describe("Short description of the project"),
470
+ sessionIds: z$1.array(z$1.string()).optional().describe("Notebook (session) ids to add to the project"),
471
+ fileIds: z$1.array(z$1.string()).optional().describe("File ids to add to the project")
472
+ };
473
+ const sendMessageShape = {
474
+ message: z$1.string().describe("The message to send"),
475
+ notebookId: z$1.string().optional().describe("Notebook to send to; omit to start a new notebook (its id is returned as notebookId, pass it back to continue the thread)"),
476
+ model: z$1.string().optional().describe("Model id to use; defaults to the instance default"),
477
+ systemPrompt: z$1.string().max(PROMPT_TEXT_MAX).optional().describe("Caller-supplied system-prompt text for this message only; refines but never overrides other guidance")
478
+ };
479
+ const searchKnowledgeBaseShape = {
480
+ query: z$1.string().describe("The search query"),
481
+ limit: z$1.number().int().min(1).max(100).default(10).describe("Maximum results to return"),
482
+ minSimilarity: z$1.number().min(0).max(1).optional().describe("Minimum cosine similarity threshold")
483
+ };
484
+ const listLakesShape = {
485
+ limit: z$1.number().int().min(1).max(100).default(25).describe("Maximum lakes to return"),
486
+ cursor: z$1.string().optional().describe("Pass back nextCursor from the previous page")
487
+ };
488
+ const listFilesShape = {
489
+ search: z$1.string().optional().describe("Filter files by name/content"),
490
+ limit: z$1.number().int().min(1).max(100).default(25).describe("Maximum files to return"),
491
+ page: z$1.number().int().min(1).default(1).describe("1-based page number; request the next page when hasMore is true")
492
+ };
493
+ const getFileShape = { fileId: z$1.string().describe("The file id") };
494
+ const generateSoundEffectShape = {
495
+ text: z$1.string().min(1).max(1e3).describe("Text description of the sound effect to generate"),
496
+ provider: z$1.enum(["elevenlabs"]).default("elevenlabs").describe("Sound-generation provider"),
497
+ durationSeconds: z$1.number().min(.5).max(30).optional().describe("Length of the sound in seconds (0.5-30); omit to let the provider choose"),
498
+ promptInfluence: z$1.number().min(0).max(1).optional().describe("How strictly to follow the prompt (0 = loose, 1 = strict)"),
499
+ format: z$1.string().optional().describe("Provider output encoding token, e.g. mp3_44100_128")
500
+ };
501
+ const generateImageShape = {
502
+ prompt: z$1.string().min(1).describe("Text description of the image to generate"),
503
+ model: z$1.string().default(ImageModels.GPT_IMAGE_2).describe("Image model id, e.g. gpt-image-2"),
504
+ size: z$1.string().optional().describe("Image size as 'widthxheight', e.g. 1024x1024; omit for the model default"),
505
+ notebookId: z$1.string().optional().describe("Notebook to add the image to; omit to create a new one"),
506
+ projectId: z$1.string().optional().describe("Project for the new notebook when notebookId is omitted"),
507
+ promptResolution: ImagePromptResolutionSchema.optional().describe("'auto' (default) rewrites the prompt against the notebook history; 'literal' sends it as written")
508
+ };
509
+ const textToSpeechShape = {
510
+ ...ttsRequestSchema.omit({ encoding: true }).shape,
511
+ text: ttsRequestSchema.shape.text.describe("Text to speak"),
512
+ provider: ttsRequestSchema.shape.provider.describe(`Speech provider; defaults to ${DEFAULT_TTS_PROVIDER}`),
513
+ preview: ttsRequestSchema.shape.preview.describe("Skip saving a copy to the file browser")
514
+ };
515
+ function notebookSummary(n) {
516
+ return {
517
+ id: n.id,
518
+ name: n.name,
519
+ model: n.lastUsedModel ?? void 0,
520
+ createdAt: n.createdAt ?? n.firstCreated,
521
+ updatedAt: n.updatedAt ?? n.lastUpdated
522
+ };
523
+ }
524
+ function projectSummary(p) {
525
+ return {
526
+ id: p.id,
527
+ name: p.name,
528
+ createdAt: p.createdAt
529
+ };
530
+ }
531
+ function lakeSummary(l) {
532
+ return {
533
+ id: l.id,
534
+ name: l.name,
535
+ slug: l.slug,
536
+ description: l.description ?? void 0,
537
+ builtIn: l.built_in,
538
+ status: l.status,
539
+ fileCount: l.file_count
540
+ };
541
+ }
542
+ async function listNotebooks(client, args) {
543
+ const { data, hasMore } = await client.listNotebooks(args);
544
+ return {
545
+ notebooks: data.map(notebookSummary),
546
+ hasMore
547
+ };
548
+ }
549
+ async function getNotebook(client, args) {
550
+ return client.getNotebook(args.notebookId);
551
+ }
552
+ async function createNotebook(client, args) {
553
+ return client.createNotebook({
554
+ ...args,
555
+ name: args.name ?? "New Notebook"
556
+ });
557
+ }
558
+ async function renameNotebook(client, args) {
559
+ return notebookSummary(await client.renameNotebook(args.notebookId, args.name));
560
+ }
561
+ async function cloneNotebook(client, args) {
562
+ return notebookSummary(await client.cloneNotebook(args.notebookId));
563
+ }
564
+ async function deleteNotebook(client, args) {
565
+ if (args.confirm !== true) throw new Error("delete_notebook requires confirm: true");
566
+ const { newLastNotebookId } = await client.deleteNotebook(args.notebookId);
567
+ return {
568
+ deleted: true,
569
+ notebookId: args.notebookId,
570
+ newLastNotebookId
571
+ };
572
+ }
573
+ async function listProjects(client, args) {
574
+ const { data, hasMore } = await client.listProjects(args);
575
+ return {
576
+ projects: data.map(projectSummary),
577
+ hasMore
578
+ };
579
+ }
580
+ async function getProject(client, args) {
581
+ return client.getProject(args.projectId);
582
+ }
583
+ async function createProject(client, args) {
584
+ return projectSummary(await client.createProject(args));
585
+ }
586
+ /**
587
+ * Queue a chat turn and poll its quest to completion. A failed turn ends `type: 'error'` with its
588
+ * explanation as the reply, which is returned as-is like any other reply.
589
+ */
590
+ async function sendMessage(client, args, { intervalMs = CHAT_POLL_INTERVAL_MS, timeoutMs = CHAT_POLL_TIMEOUT_MS, ...poll } = {}) {
591
+ const ack = await client.sendChat(args);
592
+ const questId = ack.id;
593
+ const quest = await pollQuest(client, {
594
+ questId,
595
+ ref: questRef(questId, ack.sessionId),
596
+ task: "chat completion",
597
+ scope: "ai:chat",
598
+ isFinished: isSettled
599
+ }, {
600
+ ...poll,
601
+ timeoutMs,
602
+ interval: (elapsedMs) => chatPollInterval(elapsedMs, intervalMs)
603
+ });
604
+ const notebookId = args.notebookId ?? ack.sessionId ?? quest.sessionId;
605
+ const citables = (quest.promptMeta?.citables ?? []).map((c) => ({
606
+ id: c.id,
607
+ type: c.type,
608
+ title: c.title,
609
+ url: c.url,
610
+ description: c.description
611
+ }));
612
+ return {
613
+ notebookId,
614
+ questId,
615
+ reply: replyText(quest),
616
+ model: ack.model,
617
+ citables
618
+ };
619
+ }
620
+ async function searchKnowledgeBase(client, args) {
621
+ return { results: await client.searchKnowledgeBase(args) };
622
+ }
623
+ async function listLakes(client, args) {
624
+ const { data, nextCursor } = await client.listDataLakes(args);
625
+ return {
626
+ lakes: data.map(lakeSummary),
627
+ nextCursor
628
+ };
629
+ }
630
+ async function listFiles(client, args) {
631
+ const { data, hasMore } = await client.listFiles(args);
632
+ return {
633
+ files: data,
634
+ hasMore
635
+ };
636
+ }
637
+ async function getFile(client, args) {
638
+ return client.getFile(args.fileId);
639
+ }
640
+ async function generateSoundEffect(client, args) {
641
+ return generatedAudioResult(await client.generateSoundEffect(args), { provider: args.provider });
642
+ }
643
+ const IMAGE_POLL_INTERVAL_MS = 2e3;
644
+ const IMAGE_POLL_TIMEOUT_MS = 3e5;
645
+ const CHAT_POLL_INTERVAL_MS = 2e3;
646
+ const CHAT_POLL_FAST_WINDOW_MS = 3e4;
647
+ const CHAT_POLL_SLOW_INTERVAL_MS = 5e3;
648
+ const CHAT_POLL_TIMEOUT_MS = 9e5;
649
+ const MAX_CONSECUTIVE_POLL_FAILURES = 3;
650
+ const defaultSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
651
+ const chatPollInterval = (elapsedMs, intervalMs) => elapsedMs < CHAT_POLL_FAST_WINDOW_MS ? intervalMs : Math.max(intervalMs, CHAT_POLL_SLOW_INTERVAL_MS);
652
+ const isSettled = (q) => q.status === "done" || q.status === "stopped" || q.type === "error";
653
+ const isImageSettled = (q) => isSettled(q) || !q.status && !!q.images?.length;
654
+ const replyText = (q) => questReplyText(q, joinReplySlots) ?? "";
655
+ const questRef = (questId, notebookId) => `quest ${questId}${notebookId ? `, notebook ${notebookId}` : ""}`;
656
+ const isRateLimited = (err) => isAxiosError(err) && err.response?.status === 429;
657
+ const isPermanentApiError = (err) => {
658
+ const status = isAxiosError(err) ? err.response?.status : void 0;
659
+ return status === 401 || status === 403 || status === 404;
660
+ };
661
+ /** Poll a queued quest until `isFinished`, the timeout, a permanent poll failure, or an abort. */
662
+ async function pollQuest(client, { questId, ref, task, scope, isFinished }, { interval, timeoutMs, sleep = defaultSleep, signal, onProgress, baseURL = "" }) {
663
+ const started = Date.now();
664
+ let failures = 0;
665
+ let retryAfterMs = 0;
666
+ for (;;) {
667
+ signal?.throwIfAborted();
668
+ let quest;
669
+ try {
670
+ quest = await client.getQuest(questId);
671
+ failures = 0;
672
+ if (isFinished(quest)) return quest;
673
+ } catch (err) {
674
+ if (isRateLimited(err)) retryAfterMs = (parseRetryAfterSeconds(isAxiosError(err) && err.response?.headers?.["retry-after"]) ?? 0) * 1e3;
675
+ else {
676
+ failures += 1;
677
+ if (isPermanentApiError(err) || failures >= MAX_CONSECUTIVE_POLL_FAILURES) throw new Error(`${mapApiError(err, baseURL, scope)} (${ref}; the ${task} may still complete)`);
678
+ }
679
+ }
680
+ const elapsed = Date.now() - started;
681
+ if (elapsed >= timeoutMs) throw new Error(`${task} did not finish within ${Math.round(timeoutMs / 1e3)}s (${ref})`);
682
+ signal?.throwIfAborted();
683
+ try {
684
+ await onProgress?.(elapsed, quest);
685
+ } catch (err) {
686
+ logger.warn(`mcp: progress notification failed (${ref}): ${err instanceof Error ? err.message : String(err)}`);
687
+ }
688
+ const intervalMs = interval(elapsed);
689
+ await sleep(Math.min(Math.max(intervalMs, retryAfterMs), Math.max(timeoutMs - elapsed, intervalMs)));
690
+ retryAfterMs = 0;
691
+ }
692
+ }
693
+ /**
694
+ * Queue an image render and poll its quest to completion. A failed render still
695
+ * resolves `status: 'done'`, so `type: 'error'` (reason in `reply`) is the failure signal.
696
+ * Generated images are not FabFiles, so there is no file id: the quest id is the handle,
697
+ * and each image is its generated-file name plus the URL the quest poll resolves for it
698
+ * (`fileUrl` is absent when the server has no CDN configured).
699
+ */
700
+ async function generateImage(client, args, { intervalMs = IMAGE_POLL_INTERVAL_MS, timeoutMs = IMAGE_POLL_TIMEOUT_MS, ...poll } = {}) {
701
+ const ack = await client.generateImage(args);
702
+ const questId = ack.quest.id;
703
+ const ref = questRef(questId, ack.quest.sessionId);
704
+ const quest = await pollQuest(client, {
705
+ questId,
706
+ ref,
707
+ task: "image generation",
708
+ scope: "ai:generate",
709
+ isFinished: isImageSettled
710
+ }, {
711
+ ...poll,
712
+ timeoutMs,
713
+ interval: () => intervalMs
714
+ });
715
+ if (quest.status === "stopped") throw new Error(`image generation was stopped (${ref})`);
716
+ if (quest.type === "error") {
717
+ const code = quest.errorCode ? `${quest.errorCode}: ` : "";
718
+ throw new Error(`${code}${quest.reply || "image generation failed"} (${ref})`);
719
+ }
720
+ const urls = new Map((quest.files ?? []).map((f) => [f.name, f.url]));
721
+ const images = (quest.images ?? []).filter((name) => GENERATED_IMAGE_EXTENSION_RE.test(name)).map((name) => ({
722
+ fileName: name,
723
+ fileUrl: urls.get(name)
724
+ }));
725
+ if (images.length === 0) throw new Error(`${quest.reply || "image generation finished without producing an image"} (${ref})`);
726
+ return {
727
+ notebookId: quest.sessionId ?? ack.quest.sessionId,
728
+ questId,
729
+ model: args.model,
730
+ enhancedPrompt: ack.enhancedPrompt,
731
+ images
732
+ };
733
+ }
734
+ function toResult(value) {
735
+ const structuredContent = value && typeof value === "object" && !Array.isArray(value) ? value : { result: value };
736
+ return {
737
+ content: [{
738
+ type: "text",
739
+ text: JSON.stringify(value, null, 2)
740
+ }],
741
+ structuredContent
742
+ };
743
+ }
744
+ function errorResult(message) {
745
+ return {
746
+ content: [{
747
+ type: "text",
748
+ text: message
749
+ }],
750
+ isError: true
751
+ };
752
+ }
753
+ /**
754
+ * Render a generated-audio response as an MCP result, shared by every audio tool.
755
+ * Oversized audio is reported by its signed URL; a saved copy with a usable URL is
756
+ * reported as a file (like get_file) with no inline bytes. Otherwise the audio rides
757
+ * inline as an `audio` block so a billed result is never lost, with any saved copy
758
+ * still named by id and a skipped save explained. The route forwards the signed URL
759
+ * it minted at upload, so no getFile re-fetch is needed (that fails closed until
760
+ * the async moderation scan runs).
761
+ */
762
+ function generatedAudioResult(response, endpointMetadata) {
763
+ const metadata = {
764
+ ...endpointMetadata,
765
+ contentType: response.contentType
766
+ };
767
+ const saveSkippedReason = response.saveSkippedReason ? { saveSkippedReason: response.saveSkippedReason } : {};
768
+ const file = response.fabFileId ? {
769
+ id: response.fabFileId,
770
+ ...response.fileName ? { fileName: response.fileName } : {},
771
+ ...response.fileUrl ? { fileUrl: response.fileUrl } : {}
772
+ } : void 0;
773
+ if (response.delivery === "url") return toResult({
774
+ ...metadata,
775
+ byteLength: response.bytes,
776
+ url: response.url,
777
+ saved: response.saved === true,
778
+ ...response.saved && file ? { file } : {},
779
+ ...saveSkippedReason
780
+ });
781
+ const byteLength = Buffer.from(response.audio, "base64").length;
782
+ if (response.saved && file && file.fileUrl) return toResult({
783
+ ...metadata,
784
+ byteLength,
785
+ saved: true,
786
+ file
787
+ });
788
+ return inlineAudioResult(response.saved && file ? {
789
+ ...metadata,
790
+ byteLength,
791
+ saved: true,
792
+ file
793
+ } : {
794
+ ...metadata,
795
+ byteLength,
796
+ saved: false,
797
+ ...saveSkippedReason
798
+ }, response.audio, response.contentType);
799
+ }
800
+ /**
801
+ * Metadata as JSON text plus the audio as an MCP `audio` block. The base64 stays
802
+ * out of structuredContent so a potentially large payload is not duplicated.
803
+ */
804
+ function inlineAudioResult(meta, audioBase64, mimeType) {
805
+ return {
806
+ content: [{
807
+ type: "text",
808
+ text: JSON.stringify(meta, null, 2)
809
+ }, {
810
+ type: "audio",
811
+ data: audioBase64,
812
+ mimeType
813
+ }],
814
+ structuredContent: meta
815
+ };
816
+ }
817
+ async function textToSpeech(client, args) {
818
+ const response = await client.synthesizeSpeech(args);
819
+ if (response.kind === "saved-too-large") {
820
+ const { provider, fabFileId, fileUrl } = response.data;
821
+ return toResult({
822
+ saved: true,
823
+ provider,
824
+ ...response.fallbackFrom ? { fallbackFrom: response.fallbackFrom } : {},
825
+ file: {
826
+ id: fabFileId,
827
+ ...fileUrl ? { fileUrl } : {}
828
+ }
829
+ });
830
+ }
831
+ const result = response.data;
832
+ return generatedAudioResult(result, {
833
+ provider: result.provider ?? args.provider ?? "openai",
834
+ ...result.fallbackFrom ? { fallbackFrom: result.fallbackFrom } : {},
835
+ format: result.format
836
+ });
837
+ }
838
+ /**
839
+ * Turn a quest poll's progress callback into MCP `notifications/progress`, or nothing when the
840
+ * client sent no progressToken. Progress also lets a client that resets its request timeout on
841
+ * progress wait out a slow quest.
842
+ */
843
+ function progressReporter({ _meta, sendNotification }, describe) {
844
+ const progressToken = _meta?.progressToken;
845
+ if (progressToken === void 0) return void 0;
846
+ return (elapsedMs, quest) => sendNotification({
847
+ method: "notifications/progress",
848
+ params: {
849
+ progressToken,
850
+ progress: Math.floor(elapsedMs / 1e3),
851
+ message: describe(quest)
852
+ }
853
+ });
854
+ }
855
+ function chatProgress(quest) {
856
+ if (quest?.status !== "running") return "waiting for the reply to start";
857
+ const characters = replyText(quest).length;
858
+ return characters > 0 ? `generating reply (${characters} characters so far)` : "generating reply";
859
+ }
860
+ /**
861
+ * Register the Bike4Mind MCP tools on `server`. Each handler is wrapped so an
862
+ * API failure becomes a structured `isError` result carrying a friendly message
863
+ * (see {@link mapApiError}) rather than throwing across the transport.
864
+ */
865
+ function registerTools(server, client) {
866
+ const baseURL = client.baseURL;
867
+ const meta = (name) => TOOL_META.find((t) => t.name === name);
868
+ const run = async (scope, fn) => {
869
+ try {
870
+ return toResult(await fn());
871
+ } catch (err) {
872
+ return errorResult(mapApiError(err, baseURL, scope));
873
+ }
874
+ };
875
+ server.registerTool("list_notebooks", {
876
+ title: meta("list_notebooks").title,
877
+ description: meta("list_notebooks").description,
878
+ inputSchema: listNotebooksShape
879
+ }, (args) => run("notebooks:read", () => listNotebooks(client, args)));
880
+ server.registerTool("get_notebook", {
881
+ title: meta("get_notebook").title,
882
+ description: meta("get_notebook").description,
883
+ inputSchema: getNotebookShape
884
+ }, (args) => run("notebooks:read", () => getNotebook(client, args)));
885
+ server.registerTool("create_notebook", {
886
+ title: meta("create_notebook").title,
887
+ description: meta("create_notebook").description,
888
+ inputSchema: createNotebookShape
889
+ }, (args) => run("notebooks:write", () => createNotebook(client, args)));
890
+ server.registerTool("rename_notebook", {
891
+ title: meta("rename_notebook").title,
892
+ description: meta("rename_notebook").description,
893
+ inputSchema: renameNotebookShape
894
+ }, (args) => run("notebooks:write", () => renameNotebook(client, args)));
895
+ server.registerTool("clone_notebook", {
896
+ title: meta("clone_notebook").title,
897
+ description: meta("clone_notebook").description,
898
+ inputSchema: cloneNotebookShape
899
+ }, (args) => run("notebooks:write", () => cloneNotebook(client, args)));
900
+ server.registerTool("delete_notebook", {
901
+ title: meta("delete_notebook").title,
902
+ description: meta("delete_notebook").description,
903
+ inputSchema: deleteNotebookShape
904
+ }, (args) => run("notebooks:write", () => deleteNotebook(client, args)));
905
+ server.registerTool("list_projects", {
906
+ title: meta("list_projects").title,
907
+ description: meta("list_projects").description,
908
+ inputSchema: listProjectsShape
909
+ }, (args) => run("projects:read", () => listProjects(client, args)));
910
+ server.registerTool("get_project", {
911
+ title: meta("get_project").title,
912
+ description: meta("get_project").description,
913
+ inputSchema: getProjectShape
914
+ }, (args) => run("projects:read", () => getProject(client, args)));
915
+ server.registerTool("create_project", {
916
+ title: meta("create_project").title,
917
+ description: meta("create_project").description,
918
+ inputSchema: createProjectShape
919
+ }, (args) => run("projects:write", () => createProject(client, args)));
920
+ server.registerTool("send_message", {
921
+ title: meta("send_message").title,
922
+ description: meta("send_message").description,
923
+ inputSchema: sendMessageShape
924
+ }, (args, extra) => run("ai:chat", () => sendMessage(client, args, {
925
+ signal: extra.signal,
926
+ baseURL,
927
+ onProgress: progressReporter(extra, chatProgress)
928
+ })));
929
+ server.registerTool("search_knowledge_base", {
930
+ title: meta("search_knowledge_base").title,
931
+ description: meta("search_knowledge_base").description,
932
+ inputSchema: searchKnowledgeBaseShape
933
+ }, (args) => run("notebooks:read", () => searchKnowledgeBase(client, args)));
934
+ server.registerTool("list_lakes", {
935
+ title: meta("list_lakes").title,
936
+ description: meta("list_lakes").description,
937
+ inputSchema: listLakesShape
938
+ }, (args) => run("datalake:read", () => listLakes(client, args)));
939
+ server.registerTool("list_files", {
940
+ title: meta("list_files").title,
941
+ description: meta("list_files").description,
942
+ inputSchema: listFilesShape
943
+ }, (args) => run("files:read", () => listFiles(client, args)));
944
+ server.registerTool("get_file", {
945
+ title: meta("get_file").title,
946
+ description: meta("get_file").description,
947
+ inputSchema: getFileShape
948
+ }, (args) => run("files:read", () => getFile(client, args)));
949
+ server.registerTool("generate_sound_effect", {
950
+ title: meta("generate_sound_effect").title,
951
+ description: meta("generate_sound_effect").description,
952
+ inputSchema: generateSoundEffectShape
953
+ }, async (args) => {
954
+ try {
955
+ return await generateSoundEffect(client, args);
956
+ } catch (err) {
957
+ return errorResult(mapApiError(err, baseURL, "ai:generate"));
958
+ }
959
+ });
960
+ server.registerTool("text_to_speech", {
961
+ title: meta("text_to_speech").title,
962
+ description: meta("text_to_speech").description,
963
+ inputSchema: textToSpeechShape
964
+ }, async (args) => {
965
+ try {
966
+ return await textToSpeech(client, args);
967
+ } catch (err) {
968
+ return errorResult(mapApiError(err, baseURL, "ai:generate"));
969
+ }
970
+ });
971
+ server.registerTool("generate_image", {
972
+ title: meta("generate_image").title,
973
+ description: meta("generate_image").description,
974
+ inputSchema: generateImageShape
975
+ }, (args, extra) => run("ai:generate", () => generateImage(client, args, {
976
+ signal: extra.signal,
977
+ baseURL,
978
+ onProgress: progressReporter(extra, () => "rendering image")
979
+ })));
980
+ }
981
+ //#endregion
982
+ //#region src/mcp/resources.ts
983
+ const LIST_LIMIT = 100;
984
+ /**
985
+ * Decode a URI-template variable, tolerating an id that was never encoded.
986
+ *
987
+ * The SDK reaches a read callback via `new URL(uri)` -> `uriTemplate.match(url.toString())`,
988
+ * and `URL.toString()` percent-encodes, so an id we listed with `encodeURIComponent`
989
+ * arrives already encoded and must be decoded back before it hits a REST path. A
990
+ * hand-crafted uri with a malformed escape (e.g. `%zz`) would make `decodeURIComponent`
991
+ * throw a bare `URIError` past `mapApiError`; fall back to the raw value instead.
992
+ */
993
+ function safeDecode(value) {
994
+ try {
995
+ return decodeURIComponent(value);
996
+ } catch {
997
+ return value;
998
+ }
999
+ }
1000
+ /**
1001
+ * Register one `b4m://<name>/{id}` JSON resource.
1002
+ *
1003
+ * `list` degrades to an empty array on failure rather than throwing: the SDK's
1004
+ * resources/list handler awaits every registered template's list callback in one
1005
+ * unguarded loop, so a throw here would also blank every sibling template. `read`
1006
+ * still throws - a single read failure has no fan-out.
1007
+ */
1008
+ function registerJsonResource(server, client, spec) {
1009
+ server.registerResource(spec.name, new ResourceTemplate(`b4m://${spec.name}/{id}`, { list: async () => {
1010
+ try {
1011
+ return { resources: (await spec.list()).map((item) => {
1012
+ const label = spec.label(item) ?? spec.id(item);
1013
+ return {
1014
+ uri: `b4m://${spec.name}/${encodeURIComponent(spec.id(item))}`,
1015
+ name: label,
1016
+ title: label,
1017
+ mimeType: "application/json"
1018
+ };
1019
+ }) };
1020
+ } catch (err) {
1021
+ logger.error(`mcp: listing ${spec.name} resources failed: ${mapApiError(err, client.baseURL, spec.scope)}`);
1022
+ return { resources: [] };
1023
+ }
1024
+ } }), {
1025
+ title: spec.title,
1026
+ description: spec.description,
1027
+ mimeType: "application/json"
1028
+ }, async (uri, variables) => {
1029
+ const id = safeDecode(String(variables.id));
1030
+ try {
1031
+ const record = await spec.read(id);
1032
+ return { contents: [{
1033
+ uri: uri.href,
1034
+ mimeType: "application/json",
1035
+ text: JSON.stringify(record, null, 2)
1036
+ }] };
1037
+ } catch (err) {
1038
+ throw new Error(mapApiError(err, client.baseURL, spec.scope));
1039
+ }
1040
+ });
1041
+ }
1042
+ /**
1043
+ * Register `b4m://agent-quest`: the machine-readable invitation to The Open Door.
1044
+ *
1045
+ * A fixed URI rather than a `ResourceTemplate` - there is exactly one manifest, so
1046
+ * there is nothing to list or address by id. It is also the only resource here that
1047
+ * needs no API call and no credentials: the document is a constant in
1048
+ * @bike4mind/common, shared with the public HTTP route that serves it
1049
+ * (apps/client/pages/api/agent-quest/manifest.ts). That means an agent can read the
1050
+ * invitation before it has an API key - which is the point, since the quest is how
1051
+ * it earns one.
1052
+ */
1053
+ function registerAgentQuest(server) {
1054
+ server.registerResource(AGENT_QUEST_ID, AGENT_QUEST_MCP_URI, {
1055
+ title: AGENT_QUEST_MANIFEST.title,
1056
+ description: AGENT_QUEST_MANIFEST.summary,
1057
+ mimeType: "application/json"
1058
+ }, (uri) => ({ contents: [{
1059
+ uri: uri.href,
1060
+ mimeType: "application/json",
1061
+ text: JSON.stringify(AGENT_QUEST_MANIFEST, null, 2)
1062
+ }] }));
1063
+ }
1064
+ /**
1065
+ * Register the Bike4Mind MCP resources: the four templates below, each served as
1066
+ * application/json and backed by its REST list/read pair, plus the credential-free
1067
+ * `b4m://agent-quest` manifest.
1068
+ */
1069
+ function registerResources(server, client) {
1070
+ registerAgentQuest(server);
1071
+ registerJsonResource(server, client, {
1072
+ name: "notebook",
1073
+ title: "Notebook",
1074
+ description: "A Bike4Mind notebook (session)",
1075
+ scope: "notebooks:read",
1076
+ list: async () => (await client.listNotebooks({ limit: LIST_LIMIT })).data,
1077
+ id: (n) => n.id,
1078
+ label: (n) => n.name,
1079
+ read: (id) => client.getNotebook(id)
1080
+ });
1081
+ registerJsonResource(server, client, {
1082
+ name: "file",
1083
+ title: "File",
1084
+ description: "A Bike4Mind file: metadata plus a signed download URL",
1085
+ scope: "files:read",
1086
+ list: async () => (await client.listFiles({ limit: LIST_LIMIT })).data,
1087
+ id: (f) => f.id,
1088
+ label: (f) => f.fileName,
1089
+ read: (id) => client.getFile(id)
1090
+ });
1091
+ registerJsonResource(server, client, {
1092
+ name: "project",
1093
+ title: "Project",
1094
+ description: "A Bike4Mind project",
1095
+ scope: "projects:read",
1096
+ list: async () => (await client.listProjects({ limit: LIST_LIMIT })).data,
1097
+ id: (p) => p.id,
1098
+ label: (p) => p.name,
1099
+ read: (id) => client.getProject(id)
1100
+ });
1101
+ registerJsonResource(server, client, {
1102
+ name: "artifact",
1103
+ title: "Artifact",
1104
+ description: "A Bike4Mind artifact: metadata plus its current content",
1105
+ list: async () => (await client.listArtifacts({ limit: LIST_LIMIT })).data,
1106
+ id: (a) => a.id,
1107
+ label: (a) => a.title,
1108
+ read: (id) => client.getArtifact(id)
1109
+ });
1110
+ }
1111
+ //#endregion
1112
+ //#region src/mcp/prompts.ts
1113
+ /**
1114
+ * The `{{placeholder}}` keys a client supplies as prompt arguments. The clock keys
1115
+ * (currentDate, currentTime, ...) are not arguments: they are filled at get time,
1116
+ * exactly as the web launcher does at click time.
1117
+ */
1118
+ const PROMPT_ARGUMENTS = [
1119
+ {
1120
+ name: "userName",
1121
+ description: "Your name, substituted for {{userName}}"
1122
+ },
1123
+ {
1124
+ name: "userEmail",
1125
+ description: "Your email, substituted for {{userEmail}}"
1126
+ },
1127
+ {
1128
+ name: "userRole",
1129
+ description: "Your role, substituted for {{userRole}}"
1130
+ },
1131
+ {
1132
+ name: "organization",
1133
+ description: "Your organization, substituted for {{organization}}"
1134
+ }
1135
+ ];
1136
+ const PROMPT_ARGUMENT_NAMES = new Set(PROMPT_ARGUMENTS.map((arg) => arg.name));
1137
+ /** Flatten the catalog in category order; a prompt listed under two keys appears once. */
1138
+ function flattenCatalog(catalog) {
1139
+ const byId = /* @__PURE__ */ new Map();
1140
+ for (const { key } of BRIEFCASE_CATALOG_QUERIES) for (const prompt of catalog[key] ?? []) if (!byId.has(prompt.id)) byId.set(prompt.id, prompt);
1141
+ return [...byId.values()];
1142
+ }
1143
+ /**
1144
+ * List the caller's Briefcase catalog as MCP prompts, named by prompt id (display
1145
+ * names are not unique). Degrades to an empty list on failure, like the resource
1146
+ * lists: EnableBriefcase is off by default, so a hard error would fail every
1147
+ * client's startup listing on most instances.
1148
+ */
1149
+ async function listPrompts(client) {
1150
+ try {
1151
+ return { prompts: flattenCatalog(await client.getBriefcaseCatalog(BRIEFCASE_CATALOG_QUERIES)).map((prompt) => ({
1152
+ name: prompt.id,
1153
+ title: prompt.name,
1154
+ description: prompt.description,
1155
+ arguments: PROMPT_ARGUMENTS.map((arg) => ({
1156
+ ...arg,
1157
+ required: false
1158
+ }))
1159
+ })) };
1160
+ } catch (err) {
1161
+ logger.error(`mcp: listing briefcase prompts failed: ${mapApiError(err, client.baseURL)}`);
1162
+ return { prompts: [] };
1163
+ }
1164
+ }
1165
+ function toPromptContext(args, now) {
1166
+ const supplied = Object.entries(args ?? {}).filter(([name, value]) => PROMPT_ARGUMENT_NAMES.has(name) && value !== "");
1167
+ return {
1168
+ ...buildPromptContext(null, null, now),
1169
+ ...Object.fromEntries(supplied)
1170
+ };
1171
+ }
1172
+ /** Resolve one prompt's template against the supplied arguments plus the clock. */
1173
+ async function getPrompt(client, name, args, now) {
1174
+ const notFound = new McpError(ErrorCode.InvalidParams, `Prompt ${name} not found`);
1175
+ const id = BriefcasePromptIdSchema.safeParse(name);
1176
+ if (!id.success) throw notFound;
1177
+ let prompt;
1178
+ try {
1179
+ prompt = await client.getBriefcasePrompt(id.data);
1180
+ } catch (err) {
1181
+ if (isAxiosError(err) && err.response?.status === 404) throw notFound;
1182
+ throw new Error(mapApiError(err, client.baseURL));
1183
+ }
1184
+ if (!prompt.promptText) throw new Error(`Prompt ${name} has no text`);
1185
+ const text = replacePromptVariables(prompt.promptText, toPromptContext(args, now));
1186
+ return {
1187
+ description: prompt.description ?? prompt.name,
1188
+ messages: [{
1189
+ role: "user",
1190
+ content: {
1191
+ type: "text",
1192
+ text
1193
+ }
1194
+ }]
1195
+ };
1196
+ }
1197
+ /**
1198
+ * Expose the Briefcase prompt catalog as MCP prompts. Wired on the low-level
1199
+ * server rather than through `registerPrompt`: the catalog is per-caller server
1200
+ * data that changes at runtime, so it is fetched on every prompts/list instead
1201
+ * of being frozen at build time. Requires the `prompts` capability to be declared
1202
+ * on the server (see buildMcpServer). Claims prompts/list and prompts/get on the
1203
+ * low-level server, so do not also call McpServer.registerPrompt on this server
1204
+ * (a claimed method makes it throw "already exists" at startup).
1205
+ */
1206
+ function registerPrompts(server, client, now = () => /* @__PURE__ */ new Date()) {
1207
+ server.server.setRequestHandler(ListPromptsRequestSchema, () => listPrompts(client));
1208
+ server.server.setRequestHandler(GetPromptRequestSchema, (request) => getPrompt(client, request.params.name, request.params.arguments, now()));
1209
+ }
1210
+ //#endregion
1211
+ //#region src/mcp/server.ts
1212
+ /**
1213
+ * Build a fully-configured Bike4Mind MCP server: the tools, the four resource
1214
+ * templates (`b4m://notebook/{id}`, `b4m://file/{id}`, `b4m://project/{id}`,
1215
+ * `b4m://artifact/{id}`) backed by a {@link B4mApiClient} bound to the given
1216
+ * endpoint and credentials, the credential-free `b4m://agent-quest` manifest, and
1217
+ * the Briefcase prompt catalog as MCP prompts. Tool listing never touches the
1218
+ * network - only tool/resource *calls* and prompt listing/gets hit the API - so a
1219
+ * server built with an unreachable endpoint still advertises its full capability set.
1220
+ */
1221
+ function buildMcpServer(options) {
1222
+ const client = new B4mApiClient(options.baseURL, options.configStore, options.apiKey);
1223
+ const server = new McpServer({
1224
+ name: "bike4mind",
1225
+ version: options.version
1226
+ }, { capabilities: {
1227
+ tools: {},
1228
+ resources: {},
1229
+ prompts: {}
1230
+ } });
1231
+ registerTools(server, client);
1232
+ registerResources(server, client);
1233
+ registerPrompts(server, client);
1234
+ return server;
1235
+ }
1236
+ //#endregion
1237
+ //#region src/mcp/serve.ts
1238
+ /**
1239
+ * `b4m mcp serve` - expose Bike4Mind as an MCP server.
1240
+ *
1241
+ * Two transports: stdio (default, for Claude Desktop and other local clients)
1242
+ * and stateless streamable HTTP (`--http`). Auth precedence is
1243
+ * `--api-key` > `B4M_API_KEY` > the stored OAuth JWT; the endpoint is
1244
+ * `B4M_API_URL` > `--api-url` > the CLI's configured backend.
1245
+ *
1246
+ * Transport contract for stdio: stdout carries the JSON-RPC frame stream and
1247
+ * NOTHING else, so all diagnostics are forced to stderr before ANY other work
1248
+ * runs (mirrors the acp command's captureStdout - see src/commands/acpCommand.ts).
1249
+ *
1250
+ * HTTP mode is deliberately loopback-only (binds 127.0.0.1) with no per-request
1251
+ * auth of its own - it trusts anything that can reach the socket, so it must not
1252
+ * be exposed on a routable interface. DNS-rebinding protection is on as defense
1253
+ * in depth against a browser being tricked into posting to the local port.
1254
+ */
1255
+ const HTTP_PATH = "/mcp";
1256
+ /**
1257
+ * Capture the real stdout for the JSON-RPC frame stream, then redirect
1258
+ * everything else - `console.*` and any stray `process.stdout.write` deep in the
1259
+ * stack - to stderr. A single unrelated byte on stdout corrupts a frame, so the
1260
+ * whole channel is closed rather than trusting no dependency ever prints.
1261
+ */
1262
+ function captureStdout() {
1263
+ const writeToRealStdout = process.stdout.write.bind(process.stdout);
1264
+ const toStderr = (...args) => {
1265
+ process.stderr.write(args.map(String).join(" ") + "\n");
1266
+ };
1267
+ console.log = toStderr;
1268
+ console.info = toStderr;
1269
+ console.debug = toStderr;
1270
+ process.stdout.write = process.stderr.write.bind(process.stderr);
1271
+ return writeToRealStdout;
1272
+ }
1273
+ function resolveBaseURL(options, configStore) {
1274
+ const explicit = process.env.B4M_API_URL ?? options.apiUrl;
1275
+ if (explicit) {
1276
+ const parsed = parseApiUrl(explicit);
1277
+ if ("error" in parsed) throw new Error(`Invalid API URL: ${parsed.error}`);
1278
+ return Promise.resolve(parsed.url);
1279
+ }
1280
+ return configStore.getApiConfig().then((apiConfig) => requireApiUrl(apiConfig));
1281
+ }
1282
+ async function serveStdio(buildOptions, writeFrame) {
1283
+ const server = buildMcpServer(buildOptions);
1284
+ const stdout = new Writable({ write(chunk, _encoding, callback) {
1285
+ if (writeFrame(chunk)) {
1286
+ callback();
1287
+ return;
1288
+ }
1289
+ process.stdout.once("drain", () => callback());
1290
+ } });
1291
+ const transport = new StdioServerTransport(process.stdin, stdout);
1292
+ await server.connect(transport);
1293
+ await new Promise((resolve) => {
1294
+ process.stdin.once("end", resolve);
1295
+ process.stdin.once("close", resolve);
1296
+ });
1297
+ }
1298
+ async function handleHttpRequest(req, res, buildOptions, port) {
1299
+ const server = buildMcpServer(buildOptions);
1300
+ const transport = new StreamableHTTPServerTransport({
1301
+ sessionIdGenerator: void 0,
1302
+ enableJsonResponse: true,
1303
+ enableDnsRebindingProtection: true,
1304
+ allowedHosts: [`127.0.0.1:${port}`, `localhost:${port}`],
1305
+ allowedOrigins: [`http://127.0.0.1:${port}`, `http://localhost:${port}`]
1306
+ });
1307
+ let released = false;
1308
+ const release = () => {
1309
+ if (released) return;
1310
+ released = true;
1311
+ transport.close();
1312
+ server.close();
1313
+ };
1314
+ res.on("finish", release);
1315
+ res.on("close", release);
1316
+ await server.connect(transport);
1317
+ await transport.handleRequest(req, res);
1318
+ }
1319
+ async function serveHttp(buildOptions, port) {
1320
+ const httpServer = createServer((req, res) => {
1321
+ if (new URL(req.url ?? "/", `http://localhost:${port}`).pathname !== HTTP_PATH) {
1322
+ res.writeHead(404, { "Content-Type": "application/json" });
1323
+ res.end(JSON.stringify({ error: `Not found. The MCP endpoint is ${HTTP_PATH}.` }));
1324
+ return;
1325
+ }
1326
+ handleHttpRequest(req, res, buildOptions, port).catch((err) => {
1327
+ logger.error("MCP HTTP request failed", err);
1328
+ if (!res.headersSent) {
1329
+ res.writeHead(500, { "Content-Type": "application/json" });
1330
+ res.end(JSON.stringify({
1331
+ jsonrpc: "2.0",
1332
+ error: {
1333
+ code: -32603,
1334
+ message: "Internal server error"
1335
+ },
1336
+ id: null
1337
+ }));
1338
+ }
1339
+ });
1340
+ });
1341
+ await new Promise((resolve, reject) => {
1342
+ httpServer.once("error", reject);
1343
+ httpServer.listen(port, "127.0.0.1", () => resolve());
1344
+ });
1345
+ process.stderr.write(`Bike4Mind MCP server listening on http://127.0.0.1:${port}${HTTP_PATH}\n`);
1346
+ await new Promise((resolve) => {
1347
+ const shutdown = () => httpServer.close(() => resolve());
1348
+ process.once("SIGINT", shutdown);
1349
+ process.once("SIGTERM", shutdown);
1350
+ });
1351
+ }
1352
+ async function handleMcpServeCommand(options) {
1353
+ const writeFrame = options.http ? void 0 : captureStdout();
1354
+ const configStore = new ConfigStore();
1355
+ const buildOptions = {
1356
+ baseURL: await resolveBaseURL(options, configStore),
1357
+ apiKey: options.apiKey ?? process.env.B4M_API_KEY,
1358
+ configStore,
1359
+ version: options.version
1360
+ };
1361
+ if (writeFrame) await serveStdio(buildOptions, writeFrame);
1362
+ else await serveHttp(buildOptions, options.port ?? 7e3);
1363
+ }
1364
+ //#endregion
1365
+ export { handleMcpServeCommand };