@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.
@@ -1,774 +0,0 @@
1
- #!/usr/bin/env node
2
- import { N as PROMPT_TEXT_MAX, _ as AGENT_QUEST_ID, h as requireApiUrl, m as parseApiUrl, n as logger, t as ConfigStore, v as AGENT_QUEST_MANIFEST, y as AGENT_QUEST_MCP_URI } from "./ConfigStore-qV7NrCgZ.mjs";
3
- import { t as ApiClient } from "./ApiClient-D0fQ2FT6.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
- //#region src/mcp/b4mApiClient.ts
12
- /**
13
- * Typed wrapper over {@link ApiClient} exposing exactly the Bike4Mind REST
14
- * endpoints the MCP tools call. All routes are `baseApi()` routes that accept
15
- * either an OAuth JWT or an instance API key, so a caller supplies whichever it
16
- * has via the underlying ApiClient.
17
- */
18
- var B4mApiClient = class {
19
- constructor(baseURL, configStore, apiKey) {
20
- this.baseURL = baseURL;
21
- this.client = new ApiClient(baseURL, configStore, apiKey);
22
- }
23
- toList(result) {
24
- if (Array.isArray(result)) return {
25
- data: result,
26
- hasMore: false
27
- };
28
- return {
29
- data: result.data ?? [],
30
- hasMore: result.hasMore ?? false
31
- };
32
- }
33
- async listNotebooks(args) {
34
- const result = await this.client.get("/api/sessions", { params: {
35
- ...args.search ? { search: args.search } : {},
36
- pagination: {
37
- page: args.page ?? 1,
38
- limit: args.limit
39
- }
40
- } });
41
- return this.toList(result);
42
- }
43
- async getNotebook(notebookId) {
44
- return this.client.get(`/api/sessions/${encodeURIComponent(notebookId)}`);
45
- }
46
- async createNotebook(args) {
47
- return this.client.post("/api/sessions/create", {
48
- ...args.name ? { name: args.name } : {},
49
- ...args.projectId ? { projectId: args.projectId } : {}
50
- });
51
- }
52
- async sendChat(args) {
53
- return this.client.post("/api/chat", {
54
- ...args.notebookId ? { sessionId: args.notebookId } : {},
55
- message: args.message,
56
- ...args.model ? { model: args.model } : {},
57
- ...args.systemPrompt ? { systemPrompt: args.systemPrompt } : {},
58
- wait: true
59
- });
60
- }
61
- async getQuest(questId) {
62
- return this.client.get(`/api/quests/${encodeURIComponent(questId)}`);
63
- }
64
- async searchKnowledgeBase(args) {
65
- return (await this.client.post("/api/sessions/semantic-search", {
66
- query: args.query,
67
- topK: args.limit,
68
- ...args.minSimilarity !== void 0 ? { minSimilarity: args.minSimilarity } : {}
69
- })).scores ?? [];
70
- }
71
- async listFiles(args) {
72
- const result = await this.client.get("/api/files/search", { params: {
73
- ...args.search ? { search: args.search } : {},
74
- pagination: {
75
- page: args.page ?? 1,
76
- limit: args.limit
77
- }
78
- } });
79
- return this.toList(result);
80
- }
81
- async getFile(fileId) {
82
- return this.client.get(`/api/files/${encodeURIComponent(fileId)}`);
83
- }
84
- /**
85
- * Generate a sound effect. Unlike the JSON routes, this one streams raw audio
86
- * bytes, so it goes through the axios instance directly to read the response
87
- * headers (content type + the persisted-FabFile side channel). On failure the
88
- * error body arrives as bytes; {@link decodeArrayBufferErrorBody} restores the
89
- * JSON shape so {@link mapApiError} can surface the server's message.
90
- */
91
- async generateSoundEffect(args) {
92
- try {
93
- const response = await this.client.getAxiosInstance().post("/api/ai/sound-effects", {
94
- provider: args.provider,
95
- text: args.text,
96
- ...args.durationSeconds !== void 0 ? { durationSeconds: args.durationSeconds } : {},
97
- ...args.promptInfluence !== void 0 ? { promptInfluence: args.promptInfluence } : {},
98
- ...args.format ? { format: args.format } : {}
99
- }, { responseType: "arraybuffer" });
100
- const headerString = (value) => typeof value === "string" ? value : void 0;
101
- const saved = String(response.headers["x-b4m-audio-saved"] ?? "") === "true";
102
- return {
103
- audio: Buffer.from(response.data),
104
- contentType: String(response.headers["content-type"] ?? "application/octet-stream"),
105
- saved,
106
- fabFileId: saved ? headerString(response.headers["x-b4m-audio-fab-file-id"]) : void 0,
107
- fileName: saved ? headerString(response.headers["x-b4m-audio-file-name"]) : void 0,
108
- fileUrl: saved ? headerString(response.headers["x-b4m-audio-file-url"]) : void 0
109
- };
110
- } catch (error) {
111
- throw decodeArrayBufferErrorBody(error);
112
- }
113
- }
114
- async listProjects(args) {
115
- const result = await this.client.get("/api/projects", { params: {
116
- ...args.search ? { search: args.search } : {},
117
- pagination: {
118
- page: args.page ?? 1,
119
- limit: args.limit
120
- }
121
- } });
122
- return this.toList(result);
123
- }
124
- async getProject(projectId) {
125
- return this.client.get(`/api/projects/${encodeURIComponent(projectId)}`);
126
- }
127
- /**
128
- * GET /api/artifacts takes flat `limit`/`offset` params (not the nested
129
- * `pagination` object the session/file/project routes use) and hard-caps
130
- * `limit` at 100 via a strict zod parse, so callers must not exceed it.
131
- */
132
- async listArtifacts(args) {
133
- const result = await this.client.get("/api/artifacts", { params: {
134
- ...args.search ? { search: args.search } : {},
135
- limit: args.limit,
136
- offset: args.offset ?? 0
137
- } });
138
- return {
139
- data: result.artifacts ?? [],
140
- hasMore: result.pagination?.hasMore ?? false
141
- };
142
- }
143
- async getArtifact(artifactId) {
144
- return this.client.get(`/api/artifacts/${encodeURIComponent(artifactId)}`, { params: { includeContent: "true" } });
145
- }
146
- };
147
- /**
148
- * Turn an API failure into an actionable, transport-agnostic message. `scope` is
149
- * the recommended API-key scope for the failing tool. A 403 can come from a
150
- * missing scope OR from a route-level authorization check (CASL forbidden,
151
- * suspended account), so the message stays broad rather than asserting a scope
152
- * gap that may not be the cause.
153
- */
154
- function mapApiError(error, baseURL, scope) {
155
- if (isAxiosError(error)) {
156
- const status = error.response?.status;
157
- if (status === 401) return "authentication failed (run `b4m login` or set B4M_API_KEY)";
158
- if (status === 403) {
159
- const base = "API key forbidden: check the key's scopes and account access";
160
- return scope ? `${base} (recommended scope: ${scope})` : base;
161
- }
162
- if (status === 429) {
163
- const retryAfterSeconds = parseRetryAfterSeconds(error.response?.headers?.["retry-after"]);
164
- const base = extractServerMessage(error.response?.data) || "rate limit exceeded";
165
- return retryAfterSeconds !== void 0 ? `${base} (retry after ${retryAfterSeconds}s)` : base;
166
- }
167
- if (error.code === "ECONNABORTED" || error.code === "ETIMEDOUT" || /timeout/i.test(error.message)) return `request to Bike4Mind at ${baseURL} timed out`;
168
- if (error.code === "ECONNREFUSED" || error.message.includes("ECONNREFUSED")) return `cannot reach Bike4Mind at ${baseURL}`;
169
- const serverMsg = extractServerMessage(error.response?.data);
170
- if (serverMsg) return serverMsg;
171
- return error.message;
172
- }
173
- return error instanceof Error ? error.message : String(error);
174
- }
175
- /**
176
- * A request made with `responseType: 'arraybuffer'` also decodes its error body
177
- * as bytes, so a JSON `{ error }` payload reaches us as a Buffer that
178
- * {@link mapApiError} can't read. Decode it back to a parsed object in place so
179
- * the server's message survives; leave a non-JSON body untouched.
180
- */
181
- function decodeArrayBufferErrorBody(error) {
182
- if (!isAxiosError(error) || !error.response) return error;
183
- const { data } = error.response;
184
- if (typeof data === "string") {
185
- try {
186
- error.response.data = JSON.parse(data);
187
- } catch {}
188
- return error;
189
- }
190
- 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;
191
- if (!bytes) return error;
192
- try {
193
- error.response.data = JSON.parse(bytes.toString("utf8"));
194
- } catch {}
195
- return error;
196
- }
197
- /**
198
- * Normalize a Retry-After header (RFC 7231: either delta-seconds or an HTTP-date)
199
- * to a whole, non-negative number of seconds. Returns undefined when the header is
200
- * absent or parses as neither, so callers can omit the retry hint entirely.
201
- */
202
- function parseRetryAfterSeconds(value) {
203
- if (value === void 0 || value === null) return void 0;
204
- const raw = String(value).trim();
205
- if (/^\d+$/.test(raw)) return Number(raw);
206
- const dateMs = Date.parse(raw);
207
- if (Number.isNaN(dateMs)) return void 0;
208
- return Math.max(0, Math.ceil((dateMs - Date.now()) / 1e3));
209
- }
210
- /** Pull a human-readable message out of a JSON error body (`error` or `message` field). */
211
- function extractServerMessage(data) {
212
- if (data && typeof data === "object") {
213
- const record = data;
214
- if (typeof record.error === "string") return record.error;
215
- if (typeof record.message === "string") return record.message;
216
- }
217
- }
218
- //#endregion
219
- //#region src/mcp/tools.ts
220
- const TOOL_META = [
221
- {
222
- name: "list_notebooks",
223
- title: "List notebooks",
224
- description: "List the caller's Bike4Mind notebooks (sessions).",
225
- scope: "notebooks:read"
226
- },
227
- {
228
- name: "get_notebook",
229
- title: "Get notebook",
230
- description: "Fetch a single notebook by id.",
231
- scope: "notebooks:read"
232
- },
233
- {
234
- name: "create_notebook",
235
- title: "Create notebook",
236
- description: "Create a new notebook, optionally inside a project. Defaults the name to \"New Notebook\" when omitted.",
237
- scope: "notebooks:write"
238
- },
239
- {
240
- name: "send_message",
241
- title: "Send message",
242
- description: "Send a chat message and wait for the assistant reply.",
243
- scope: "ai:chat"
244
- },
245
- {
246
- name: "search_knowledge_base",
247
- title: "Search knowledge base",
248
- description: "Semantic search across the caller's notebooks.",
249
- scope: "notebooks:read"
250
- },
251
- {
252
- name: "list_files",
253
- title: "List files",
254
- description: "Search the caller's files.",
255
- scope: "files:read"
256
- },
257
- {
258
- name: "get_file",
259
- title: "Get file",
260
- description: "Fetch a file's metadata and a signed download URL.",
261
- scope: "files:read"
262
- },
263
- {
264
- name: "generate_sound_effect",
265
- title: "Generate sound effect",
266
- 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.",
267
- scope: "ai:generate"
268
- }
269
- ];
270
- TOOL_META.map((t) => t.name);
271
- const listNotebooksShape = {
272
- search: z$1.string().optional().describe("Filter notebooks by name/content"),
273
- limit: z$1.number().int().min(1).max(100).default(25).describe("Maximum notebooks to return"),
274
- page: z$1.number().int().min(1).default(1).describe("1-based page number; request the next page when hasMore is true")
275
- };
276
- const getNotebookShape = { notebookId: z$1.string().describe("The notebook (session) id") };
277
- const createNotebookShape = {
278
- name: z$1.string().optional().describe("Name for the new notebook"),
279
- projectId: z$1.string().optional().describe("Project to create the notebook in")
280
- };
281
- const sendMessageShape = {
282
- message: z$1.string().describe("The message to send"),
283
- notebookId: z$1.string().optional().describe("Notebook to send to; defaults to the most recent"),
284
- model: z$1.string().optional().describe("Model id to use; defaults to the instance default"),
285
- 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")
286
- };
287
- const searchKnowledgeBaseShape = {
288
- query: z$1.string().describe("The search query"),
289
- limit: z$1.number().int().min(1).max(100).default(10).describe("Maximum results to return"),
290
- minSimilarity: z$1.number().min(0).max(1).optional().describe("Minimum cosine similarity threshold")
291
- };
292
- const listFilesShape = {
293
- search: z$1.string().optional().describe("Filter files by name/content"),
294
- limit: z$1.number().int().min(1).max(100).default(25).describe("Maximum files to return"),
295
- page: z$1.number().int().min(1).default(1).describe("1-based page number; request the next page when hasMore is true")
296
- };
297
- const getFileShape = { fileId: z$1.string().describe("The file id") };
298
- const generateSoundEffectShape = {
299
- text: z$1.string().min(1).max(1e3).describe("Text description of the sound effect to generate"),
300
- provider: z$1.enum(["elevenlabs"]).default("elevenlabs").describe("Sound-generation provider"),
301
- 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"),
302
- promptInfluence: z$1.number().min(0).max(1).optional().describe("How strictly to follow the prompt (0 = loose, 1 = strict)"),
303
- format: z$1.string().optional().describe("Provider output encoding token, e.g. mp3_44100_128")
304
- };
305
- function notebookSummary(n) {
306
- return {
307
- id: n.id,
308
- name: n.name,
309
- model: n.lastUsedModel ?? void 0,
310
- createdAt: n.createdAt ?? n.firstCreated,
311
- updatedAt: n.updatedAt ?? n.lastUpdated
312
- };
313
- }
314
- async function listNotebooks(client, args) {
315
- const { data, hasMore } = await client.listNotebooks(args);
316
- return {
317
- notebooks: data.map(notebookSummary),
318
- hasMore
319
- };
320
- }
321
- async function getNotebook(client, args) {
322
- return client.getNotebook(args.notebookId);
323
- }
324
- async function createNotebook(client, args) {
325
- return client.createNotebook({
326
- ...args,
327
- name: args.name ?? "New Notebook"
328
- });
329
- }
330
- async function sendMessage(client, args) {
331
- const res = await client.sendChat(args);
332
- const questId = res.id;
333
- let notebookId = args.notebookId;
334
- if (!notebookId) try {
335
- notebookId = (await client.getQuest(questId)).sessionId;
336
- } catch {
337
- notebookId = void 0;
338
- }
339
- const reply = res.responses && res.responses.length > 0 ? res.responses.join("\n\n") : res.response ?? "";
340
- return {
341
- notebookId,
342
- questId,
343
- reply,
344
- model: res.model
345
- };
346
- }
347
- async function searchKnowledgeBase(client, args) {
348
- return { results: await client.searchKnowledgeBase(args) };
349
- }
350
- async function listFiles(client, args) {
351
- const { data, hasMore } = await client.listFiles(args);
352
- return {
353
- files: data,
354
- hasMore
355
- };
356
- }
357
- async function getFile(client, args) {
358
- return client.getFile(args.fileId);
359
- }
360
- async function generateSoundEffect(client, args) {
361
- const { audio, contentType, saved, fabFileId, fileName, fileUrl } = await client.generateSoundEffect(args);
362
- const base = {
363
- provider: args.provider,
364
- contentType,
365
- byteLength: audio.length
366
- };
367
- if (saved && fabFileId && fileUrl) return {
368
- ...base,
369
- saved: true,
370
- file: {
371
- id: fabFileId,
372
- fileName,
373
- fileUrl
374
- }
375
- };
376
- return {
377
- ...base,
378
- saved: false,
379
- audioBase64: audio.toString("base64")
380
- };
381
- }
382
- function toResult(value) {
383
- const structuredContent = value && typeof value === "object" && !Array.isArray(value) ? value : { result: value };
384
- return {
385
- content: [{
386
- type: "text",
387
- text: JSON.stringify(value, null, 2)
388
- }],
389
- structuredContent
390
- };
391
- }
392
- function errorResult(message) {
393
- return {
394
- content: [{
395
- type: "text",
396
- text: message
397
- }],
398
- isError: true
399
- };
400
- }
401
- /**
402
- * Render a {@link SoundEffectOutcome} as an MCP result. A persisted file becomes
403
- * a JSON metadata result (carrying the signed URL), exactly like get_file. When
404
- * the audio was not persisted, it is returned inline as an `audio` content block
405
- * so the bytes are not lost; the base64 is kept out of structuredContent to avoid
406
- * duplicating a potentially large payload.
407
- */
408
- function soundEffectResult(outcome) {
409
- if (outcome.saved) return toResult({
410
- saved: true,
411
- provider: outcome.provider,
412
- contentType: outcome.contentType,
413
- byteLength: outcome.byteLength,
414
- file: outcome.file
415
- });
416
- const { audioBase64, ...meta } = outcome;
417
- return {
418
- content: [{
419
- type: "text",
420
- text: JSON.stringify(meta, null, 2)
421
- }, {
422
- type: "audio",
423
- data: audioBase64,
424
- mimeType: outcome.contentType
425
- }],
426
- structuredContent: meta
427
- };
428
- }
429
- /**
430
- * Register the Bike4Mind MCP tools on `server`. Each handler is wrapped so an
431
- * API failure becomes a structured `isError` result carrying a friendly message
432
- * (see {@link mapApiError}) rather than throwing across the transport.
433
- */
434
- function registerTools(server, client) {
435
- const baseURL = client.baseURL;
436
- const meta = (name) => TOOL_META.find((t) => t.name === name);
437
- const run = async (scope, fn) => {
438
- try {
439
- return toResult(await fn());
440
- } catch (err) {
441
- return errorResult(mapApiError(err, baseURL, scope));
442
- }
443
- };
444
- server.registerTool("list_notebooks", {
445
- title: meta("list_notebooks").title,
446
- description: meta("list_notebooks").description,
447
- inputSchema: listNotebooksShape
448
- }, (args) => run("notebooks:read", () => listNotebooks(client, args)));
449
- server.registerTool("get_notebook", {
450
- title: meta("get_notebook").title,
451
- description: meta("get_notebook").description,
452
- inputSchema: getNotebookShape
453
- }, (args) => run("notebooks:read", () => getNotebook(client, args)));
454
- server.registerTool("create_notebook", {
455
- title: meta("create_notebook").title,
456
- description: meta("create_notebook").description,
457
- inputSchema: createNotebookShape
458
- }, (args) => run("notebooks:write", () => createNotebook(client, args)));
459
- server.registerTool("send_message", {
460
- title: meta("send_message").title,
461
- description: meta("send_message").description,
462
- inputSchema: sendMessageShape
463
- }, (args) => run("ai:chat", () => sendMessage(client, args)));
464
- server.registerTool("search_knowledge_base", {
465
- title: meta("search_knowledge_base").title,
466
- description: meta("search_knowledge_base").description,
467
- inputSchema: searchKnowledgeBaseShape
468
- }, (args) => run("notebooks:read", () => searchKnowledgeBase(client, args)));
469
- server.registerTool("list_files", {
470
- title: meta("list_files").title,
471
- description: meta("list_files").description,
472
- inputSchema: listFilesShape
473
- }, (args) => run("files:read", () => listFiles(client, args)));
474
- server.registerTool("get_file", {
475
- title: meta("get_file").title,
476
- description: meta("get_file").description,
477
- inputSchema: getFileShape
478
- }, (args) => run("files:read", () => getFile(client, args)));
479
- server.registerTool("generate_sound_effect", {
480
- title: meta("generate_sound_effect").title,
481
- description: meta("generate_sound_effect").description,
482
- inputSchema: generateSoundEffectShape
483
- }, async (args) => {
484
- try {
485
- return soundEffectResult(await generateSoundEffect(client, args));
486
- } catch (err) {
487
- return errorResult(mapApiError(err, baseURL, "ai:generate"));
488
- }
489
- });
490
- }
491
- //#endregion
492
- //#region src/mcp/resources.ts
493
- const LIST_LIMIT = 100;
494
- /**
495
- * Decode a URI-template variable, tolerating an id that was never encoded.
496
- *
497
- * The SDK reaches a read callback via `new URL(uri)` -> `uriTemplate.match(url.toString())`,
498
- * and `URL.toString()` percent-encodes, so an id we listed with `encodeURIComponent`
499
- * arrives already encoded and must be decoded back before it hits a REST path. A
500
- * hand-crafted uri with a malformed escape (e.g. `%zz`) would make `decodeURIComponent`
501
- * throw a bare `URIError` past `mapApiError`; fall back to the raw value instead.
502
- */
503
- function safeDecode(value) {
504
- try {
505
- return decodeURIComponent(value);
506
- } catch {
507
- return value;
508
- }
509
- }
510
- /**
511
- * Register one `b4m://<name>/{id}` JSON resource.
512
- *
513
- * `list` degrades to an empty array on failure rather than throwing: the SDK's
514
- * resources/list handler awaits every registered template's list callback in one
515
- * unguarded loop, so a throw here would also blank every sibling template. `read`
516
- * still throws - a single read failure has no fan-out.
517
- */
518
- function registerJsonResource(server, client, spec) {
519
- server.registerResource(spec.name, new ResourceTemplate(`b4m://${spec.name}/{id}`, { list: async () => {
520
- try {
521
- return { resources: (await spec.list()).map((item) => {
522
- const label = spec.label(item) ?? spec.id(item);
523
- return {
524
- uri: `b4m://${spec.name}/${encodeURIComponent(spec.id(item))}`,
525
- name: label,
526
- title: label,
527
- mimeType: "application/json"
528
- };
529
- }) };
530
- } catch (err) {
531
- logger.error(`mcp: listing ${spec.name} resources failed: ${mapApiError(err, client.baseURL, spec.scope)}`);
532
- return { resources: [] };
533
- }
534
- } }), {
535
- title: spec.title,
536
- description: spec.description,
537
- mimeType: "application/json"
538
- }, async (uri, variables) => {
539
- const id = safeDecode(String(variables.id));
540
- try {
541
- const record = await spec.read(id);
542
- return { contents: [{
543
- uri: uri.href,
544
- mimeType: "application/json",
545
- text: JSON.stringify(record, null, 2)
546
- }] };
547
- } catch (err) {
548
- throw new Error(mapApiError(err, client.baseURL, spec.scope));
549
- }
550
- });
551
- }
552
- /**
553
- * Register `b4m://agent-quest`: the machine-readable invitation to The Open Door.
554
- *
555
- * A fixed URI rather than a `ResourceTemplate` - there is exactly one manifest, so
556
- * there is nothing to list or address by id. It is also the only resource here that
557
- * needs no API call and no credentials: the document is a constant in
558
- * @bike4mind/common, shared with the public HTTP route that serves it
559
- * (apps/client/pages/api/agent-quest/manifest.ts). That means an agent can read the
560
- * invitation before it has an API key - which is the point, since the quest is how
561
- * it earns one.
562
- */
563
- function registerAgentQuest(server) {
564
- server.registerResource(AGENT_QUEST_ID, AGENT_QUEST_MCP_URI, {
565
- title: AGENT_QUEST_MANIFEST.title,
566
- description: AGENT_QUEST_MANIFEST.summary,
567
- mimeType: "application/json"
568
- }, (uri) => ({ contents: [{
569
- uri: uri.href,
570
- mimeType: "application/json",
571
- text: JSON.stringify(AGENT_QUEST_MANIFEST, null, 2)
572
- }] }));
573
- }
574
- /**
575
- * Register the Bike4Mind MCP resources: the four templates below, each served as
576
- * application/json and backed by its REST list/read pair, plus the credential-free
577
- * `b4m://agent-quest` manifest.
578
- */
579
- function registerResources(server, client) {
580
- registerAgentQuest(server);
581
- registerJsonResource(server, client, {
582
- name: "notebook",
583
- title: "Notebook",
584
- description: "A Bike4Mind notebook (session)",
585
- scope: "notebooks:read",
586
- list: async () => (await client.listNotebooks({ limit: LIST_LIMIT })).data,
587
- id: (n) => n.id,
588
- label: (n) => n.name,
589
- read: (id) => client.getNotebook(id)
590
- });
591
- registerJsonResource(server, client, {
592
- name: "file",
593
- title: "File",
594
- description: "A Bike4Mind file: metadata plus a signed download URL",
595
- scope: "files:read",
596
- list: async () => (await client.listFiles({ limit: LIST_LIMIT })).data,
597
- id: (f) => f.id,
598
- label: (f) => f.fileName,
599
- read: (id) => client.getFile(id)
600
- });
601
- registerJsonResource(server, client, {
602
- name: "project",
603
- title: "Project",
604
- description: "A Bike4Mind project",
605
- scope: "projects:read",
606
- list: async () => (await client.listProjects({ limit: LIST_LIMIT })).data,
607
- id: (p) => p.id,
608
- label: (p) => p.name,
609
- read: (id) => client.getProject(id)
610
- });
611
- registerJsonResource(server, client, {
612
- name: "artifact",
613
- title: "Artifact",
614
- description: "A Bike4Mind artifact: metadata plus its current content",
615
- list: async () => (await client.listArtifacts({ limit: LIST_LIMIT })).data,
616
- id: (a) => a.id,
617
- label: (a) => a.title,
618
- read: (id) => client.getArtifact(id)
619
- });
620
- }
621
- //#endregion
622
- //#region src/mcp/server.ts
623
- /**
624
- * Build a fully-configured Bike4Mind MCP server: the tools, the four resource
625
- * templates (`b4m://notebook/{id}`, `b4m://file/{id}`, `b4m://project/{id}`,
626
- * `b4m://artifact/{id}`) backed by a {@link B4mApiClient} bound to the given
627
- * endpoint and credentials, and the credential-free `b4m://agent-quest` manifest.
628
- * Tool listing never touches the network - only tool/resource *calls* hit the API -
629
- * so a server built with an unreachable endpoint still advertises its full
630
- * capability set.
631
- */
632
- function buildMcpServer(options) {
633
- const client = new B4mApiClient(options.baseURL, options.configStore, options.apiKey);
634
- const server = new McpServer({
635
- name: "bike4mind",
636
- version: options.version
637
- }, { capabilities: {
638
- tools: {},
639
- resources: {}
640
- } });
641
- registerTools(server, client);
642
- registerResources(server, client);
643
- return server;
644
- }
645
- //#endregion
646
- //#region src/mcp/serve.ts
647
- /**
648
- * `b4m mcp serve` - expose Bike4Mind as an MCP server.
649
- *
650
- * Two transports: stdio (default, for Claude Desktop and other local clients)
651
- * and stateless streamable HTTP (`--http`). Auth precedence is
652
- * `--api-key` > `B4M_API_KEY` > the stored OAuth JWT; the endpoint is
653
- * `B4M_API_URL` > `--api-url` > the CLI's configured backend.
654
- *
655
- * Transport contract for stdio: stdout carries the JSON-RPC frame stream and
656
- * NOTHING else, so all diagnostics are forced to stderr before ANY other work
657
- * runs (mirrors the acp command's captureStdout - see src/commands/acpCommand.ts).
658
- *
659
- * HTTP mode is deliberately loopback-only (binds 127.0.0.1) with no per-request
660
- * auth of its own - it trusts anything that can reach the socket, so it must not
661
- * be exposed on a routable interface. DNS-rebinding protection is on as defense
662
- * in depth against a browser being tricked into posting to the local port.
663
- */
664
- const HTTP_PATH = "/mcp";
665
- /**
666
- * Capture the real stdout for the JSON-RPC frame stream, then redirect
667
- * everything else - `console.*` and any stray `process.stdout.write` deep in the
668
- * stack - to stderr. A single unrelated byte on stdout corrupts a frame, so the
669
- * whole channel is closed rather than trusting no dependency ever prints.
670
- */
671
- function captureStdout() {
672
- const writeToRealStdout = process.stdout.write.bind(process.stdout);
673
- const toStderr = (...args) => {
674
- process.stderr.write(args.map(String).join(" ") + "\n");
675
- };
676
- console.log = toStderr;
677
- console.info = toStderr;
678
- console.debug = toStderr;
679
- process.stdout.write = process.stderr.write.bind(process.stderr);
680
- return writeToRealStdout;
681
- }
682
- function resolveBaseURL(options, configStore) {
683
- const explicit = process.env.B4M_API_URL ?? options.apiUrl;
684
- if (explicit) {
685
- const parsed = parseApiUrl(explicit);
686
- if ("error" in parsed) throw new Error(`Invalid API URL: ${parsed.error}`);
687
- return Promise.resolve(parsed.url);
688
- }
689
- return configStore.getApiConfig().then((apiConfig) => requireApiUrl(apiConfig));
690
- }
691
- async function serveStdio(buildOptions, writeFrame) {
692
- const server = buildMcpServer(buildOptions);
693
- const stdout = new Writable({ write(chunk, _encoding, callback) {
694
- if (writeFrame(chunk)) {
695
- callback();
696
- return;
697
- }
698
- process.stdout.once("drain", () => callback());
699
- } });
700
- const transport = new StdioServerTransport(process.stdin, stdout);
701
- await server.connect(transport);
702
- await new Promise((resolve) => {
703
- process.stdin.once("end", resolve);
704
- process.stdin.once("close", resolve);
705
- });
706
- }
707
- async function handleHttpRequest(req, res, buildOptions, port) {
708
- const server = buildMcpServer(buildOptions);
709
- const transport = new StreamableHTTPServerTransport({
710
- sessionIdGenerator: void 0,
711
- enableJsonResponse: true,
712
- enableDnsRebindingProtection: true,
713
- allowedHosts: [`127.0.0.1:${port}`, `localhost:${port}`],
714
- allowedOrigins: [`http://127.0.0.1:${port}`, `http://localhost:${port}`]
715
- });
716
- let released = false;
717
- const release = () => {
718
- if (released) return;
719
- released = true;
720
- transport.close();
721
- server.close();
722
- };
723
- res.on("finish", release);
724
- res.on("close", release);
725
- await server.connect(transport);
726
- await transport.handleRequest(req, res);
727
- }
728
- async function serveHttp(buildOptions, port) {
729
- const httpServer = createServer((req, res) => {
730
- if (new URL(req.url ?? "/", `http://localhost:${port}`).pathname !== HTTP_PATH) {
731
- res.writeHead(404, { "Content-Type": "application/json" });
732
- res.end(JSON.stringify({ error: `Not found. The MCP endpoint is ${HTTP_PATH}.` }));
733
- return;
734
- }
735
- handleHttpRequest(req, res, buildOptions, port).catch((err) => {
736
- logger.error("MCP HTTP request failed", err);
737
- if (!res.headersSent) {
738
- res.writeHead(500, { "Content-Type": "application/json" });
739
- res.end(JSON.stringify({
740
- jsonrpc: "2.0",
741
- error: {
742
- code: -32603,
743
- message: "Internal server error"
744
- },
745
- id: null
746
- }));
747
- }
748
- });
749
- });
750
- await new Promise((resolve, reject) => {
751
- httpServer.once("error", reject);
752
- httpServer.listen(port, "127.0.0.1", () => resolve());
753
- });
754
- process.stderr.write(`Bike4Mind MCP server listening on http://127.0.0.1:${port}${HTTP_PATH}\n`);
755
- await new Promise((resolve) => {
756
- const shutdown = () => httpServer.close(() => resolve());
757
- process.once("SIGINT", shutdown);
758
- process.once("SIGTERM", shutdown);
759
- });
760
- }
761
- async function handleMcpServeCommand(options) {
762
- const writeFrame = options.http ? void 0 : captureStdout();
763
- const configStore = new ConfigStore();
764
- const buildOptions = {
765
- baseURL: await resolveBaseURL(options, configStore),
766
- apiKey: options.apiKey ?? process.env.B4M_API_KEY,
767
- configStore,
768
- version: options.version
769
- };
770
- if (writeFrame) await serveStdio(buildOptions, writeFrame);
771
- else await serveHttp(buildOptions, options.port ?? 7e3);
772
- }
773
- //#endregion
774
- export { handleMcpServeCommand };