@bike4mind/cli 2.0.0 → 3.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/{AgentHistoryStore-DIMzvf-y.mjs → AgentHistoryStore-DVxv1kSO.mjs} +7940 -7014
- package/dist/{ConfigStore-DIs-K9oD.mjs → ConfigStore-51UaP9pJ.mjs} +12333 -7008
- package/dist/{ImageStore-kVo-oHoS.mjs → ImageStore-DuI3tgwQ.mjs} +8 -6
- package/dist/SandboxRuntimeAdapter-Bt1wPpld.mjs +2 -0
- package/dist/{WorkItemsClient-Cow6nXx7.mjs → WorkItemsClient-BMY0Qq1s.mjs} +78 -9
- package/dist/{buildAgent-DOvEp92a.mjs → buildAgent-CrSRKYU_.mjs} +106 -43
- package/dist/commands/acpCommand.mjs +26 -35
- package/dist/commands/apiCommand.mjs +1 -1
- package/dist/commands/doctorCommand.mjs +3 -3
- package/dist/commands/envCommand.mjs +1 -1
- package/dist/commands/headlessCommand.mjs +15 -24
- package/dist/commands/mcpCommand.mjs +3 -3
- package/dist/commands/pluginCommand.mjs +2 -2
- package/dist/commands/updateCommand.mjs +5 -15
- package/dist/dist-BsG2Hlp-.mjs +739 -0
- package/dist/index.mjs +670 -340
- package/dist/{package-Dl_F2Fah.mjs → package-DEsNSP54.mjs} +1 -1
- package/dist/serve-BaHzVbcm.mjs +1511 -0
- package/dist/store-BkMur6uk.mjs +2 -0
- package/dist/{store-CvjTpQPs.mjs → store-BxmPEI3v.mjs} +10 -0
- package/dist/types-I45lMh7Q.mjs +2 -0
- package/dist/{updateChecker-CQW8bxo6.mjs → updateChecker-CCLVVdH0.mjs} +36 -13
- package/package.json +27 -26
- package/dist/ApiClient-BTI0-m0g.mjs +0 -316
- package/dist/SandboxRuntimeAdapter-BmHELLuM.mjs +0 -3
- package/dist/serve-Y2zMbfGs.mjs +0 -938
- package/dist/store-BG3e54c8.mjs +0 -3
- package/dist/types-CdIKgWWe.mjs +0 -3
- package/dist/{bashExecute-CrdPpBqk-DCATrE-D.mjs → bashExecute-CrdPpBqk-CgK1gZa2.mjs} +1 -1
- package/dist/{grepSearch-BgoOOwGe-DtlV8Gn-.mjs → grepSearch-BgoOOwGe-B388GxRD.mjs} +2 -2
package/dist/serve-Y2zMbfGs.mjs
DELETED
|
@@ -1,938 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env node
|
|
2
|
-
import { R as PROMPT_TEXT_MAX, Y as generatedAudioResponseSchema, _ as requireApiUrl, b as AGENT_QUEST_MANIFEST, dt as ttsBase64ResponseSchema, ft as ttsRequestSchema, g as parseApiUrl, k as DEFAULT_TTS_PROVIDER, n as logger, pt as ttsResponseTooLargeSchema, t as ConfigStore, ut as supportedVoiceGenerationVendor, x as AGENT_QUEST_MCP_URI, y as AGENT_QUEST_ID } from "./ConfigStore-DIs-K9oD.mjs";
|
|
3
|
-
import { n as NotAuthenticatedError, r as isProviderKeyFailure, t as ApiClient } from "./ApiClient-BTI0-m0g.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
|
-
...args.dataLakeId ? { dataLakeId: args.dataLakeId } : {}
|
|
51
|
-
});
|
|
52
|
-
}
|
|
53
|
-
/**
|
|
54
|
-
* GET /api/v1/data-lakes is cursor-paginated (flat `limit`/`cursor` params,
|
|
55
|
-
* `{ data, next_cursor }` body), so `toList` does not apply.
|
|
56
|
-
*/
|
|
57
|
-
async listDataLakes(args) {
|
|
58
|
-
const result = await this.client.get("/api/v1/data-lakes", { params: {
|
|
59
|
-
limit: args.limit,
|
|
60
|
-
...args.cursor ? { cursor: args.cursor } : {}
|
|
61
|
-
} });
|
|
62
|
-
return {
|
|
63
|
-
data: result.data ?? [],
|
|
64
|
-
nextCursor: result.next_cursor ?? null
|
|
65
|
-
};
|
|
66
|
-
}
|
|
67
|
-
async sendChat(args) {
|
|
68
|
-
return this.client.post("/api/chat", {
|
|
69
|
-
...args.notebookId ? { sessionId: args.notebookId } : { newConversation: true },
|
|
70
|
-
message: args.message,
|
|
71
|
-
...args.model ? { model: args.model } : {},
|
|
72
|
-
...args.systemPrompt ? { systemPrompt: args.systemPrompt } : {},
|
|
73
|
-
wait: true
|
|
74
|
-
});
|
|
75
|
-
}
|
|
76
|
-
async getQuest(questId) {
|
|
77
|
-
return this.client.get(`/api/quests/${encodeURIComponent(questId)}`);
|
|
78
|
-
}
|
|
79
|
-
async searchKnowledgeBase(args) {
|
|
80
|
-
return (await this.client.post("/api/sessions/semantic-search", {
|
|
81
|
-
query: args.query,
|
|
82
|
-
topK: args.limit,
|
|
83
|
-
...args.minSimilarity !== void 0 ? { minSimilarity: args.minSimilarity } : {}
|
|
84
|
-
})).scores ?? [];
|
|
85
|
-
}
|
|
86
|
-
async listFiles(args) {
|
|
87
|
-
const result = await this.client.get("/api/files/search", { params: {
|
|
88
|
-
...args.search ? { search: args.search } : {},
|
|
89
|
-
pagination: {
|
|
90
|
-
page: args.page ?? 1,
|
|
91
|
-
limit: args.limit
|
|
92
|
-
}
|
|
93
|
-
} });
|
|
94
|
-
return this.toList(result);
|
|
95
|
-
}
|
|
96
|
-
async getFile(fileId) {
|
|
97
|
-
return this.client.get(`/api/files/${encodeURIComponent(fileId)}`);
|
|
98
|
-
}
|
|
99
|
-
/** Generate a sound effect; see {@link postGeneratedAudio} for the normalized response. */
|
|
100
|
-
async generateSoundEffect(args) {
|
|
101
|
-
return this.postGeneratedAudio("/api/ai/sound-effects", {
|
|
102
|
-
provider: args.provider,
|
|
103
|
-
text: args.text,
|
|
104
|
-
...args.durationSeconds !== void 0 ? { durationSeconds: args.durationSeconds } : {},
|
|
105
|
-
...args.promptInfluence !== void 0 ? { promptInfluence: args.promptInfluence } : {},
|
|
106
|
-
...args.format ? { format: args.format } : {}
|
|
107
|
-
}, generatedAudioResponseSchema);
|
|
108
|
-
}
|
|
109
|
-
async synthesizeSpeech(args) {
|
|
110
|
-
try {
|
|
111
|
-
return {
|
|
112
|
-
kind: "audio",
|
|
113
|
-
data: await this.postGeneratedAudio("/api/ai/tts", args, ttsBase64ResponseSchema)
|
|
114
|
-
};
|
|
115
|
-
} catch (error) {
|
|
116
|
-
if (isAxiosError(error) && error.response?.status === 413) {
|
|
117
|
-
const oversized = ttsResponseTooLargeSchema.safeParse(error.response.data);
|
|
118
|
-
if (oversized.success && oversized.data.saved && oversized.data.fabFileId) {
|
|
119
|
-
const fallbackFrom = supportedVoiceGenerationVendor.safeParse(error.response.headers?.["x-b4m-tts-provider-fallback-from"]);
|
|
120
|
-
return {
|
|
121
|
-
kind: "saved-too-large",
|
|
122
|
-
data: {
|
|
123
|
-
...oversized.data,
|
|
124
|
-
fabFileId: oversized.data.fabFileId
|
|
125
|
-
},
|
|
126
|
-
...fallbackFrom.success ? { fallbackFrom: fallbackFrom.data } : {}
|
|
127
|
-
};
|
|
128
|
-
}
|
|
129
|
-
}
|
|
130
|
-
throw error;
|
|
131
|
-
}
|
|
132
|
-
}
|
|
133
|
-
/**
|
|
134
|
-
* POST a generated-audio request with `encoding: 'base64'` and normalize any
|
|
135
|
-
* server's answer into the JSON shape `schema` describes. Base64 (never binary)
|
|
136
|
-
* because an oversized result is a 303 in binary mode, and axios drops the
|
|
137
|
-
* X-B4M headers when following it. A server predating the `encoding` field
|
|
138
|
-
* ignores it and streams raw bytes with the save result in X-B4M-Audio-* headers;
|
|
139
|
-
* those are rebuilt into the inline variant. The request is arraybuffer-typed, so
|
|
140
|
-
* a failure body arrives as bytes; {@link decodeArrayBufferErrorBody} restores
|
|
141
|
-
* its JSON shape for {@link mapApiError}.
|
|
142
|
-
*/
|
|
143
|
-
async postGeneratedAudio(path, body, schema) {
|
|
144
|
-
const response = await this.client.getAxiosInstance().post(path, {
|
|
145
|
-
...body,
|
|
146
|
-
encoding: "base64"
|
|
147
|
-
}, { responseType: "arraybuffer" }).catch((error) => {
|
|
148
|
-
throw decodeArrayBufferErrorBody(error);
|
|
149
|
-
});
|
|
150
|
-
const contentType = String(response.headers["content-type"] ?? "application/octet-stream");
|
|
151
|
-
const bytes = Buffer.from(response.data);
|
|
152
|
-
if (/json/i.test(contentType)) return schema.parse(JSON.parse(bytes.toString("utf8")));
|
|
153
|
-
const headerString = (value) => typeof value === "string" ? value : void 0;
|
|
154
|
-
const saved = String(response.headers["x-b4m-audio-saved"] ?? "") === "true";
|
|
155
|
-
return schema.parse({
|
|
156
|
-
delivery: "inline",
|
|
157
|
-
audio: bytes.toString("base64"),
|
|
158
|
-
contentType,
|
|
159
|
-
saved,
|
|
160
|
-
fabFileId: saved ? headerString(response.headers["x-b4m-audio-fab-file-id"]) : void 0,
|
|
161
|
-
fileName: saved ? headerString(response.headers["x-b4m-audio-file-name"]) : void 0,
|
|
162
|
-
fileUrl: saved ? headerString(response.headers["x-b4m-audio-file-url"]) : void 0
|
|
163
|
-
});
|
|
164
|
-
}
|
|
165
|
-
async listProjects(args) {
|
|
166
|
-
const result = await this.client.get("/api/projects", { params: {
|
|
167
|
-
...args.search ? { search: args.search } : {},
|
|
168
|
-
pagination: {
|
|
169
|
-
page: args.page ?? 1,
|
|
170
|
-
limit: args.limit
|
|
171
|
-
}
|
|
172
|
-
} });
|
|
173
|
-
return this.toList(result);
|
|
174
|
-
}
|
|
175
|
-
async getProject(projectId) {
|
|
176
|
-
return this.client.get(`/api/projects/${encodeURIComponent(projectId)}`);
|
|
177
|
-
}
|
|
178
|
-
/**
|
|
179
|
-
* GET /api/artifacts takes flat `limit`/`offset` params (not the nested
|
|
180
|
-
* `pagination` object the session/file/project routes use) and hard-caps
|
|
181
|
-
* `limit` at 100 via a strict zod parse, so callers must not exceed it.
|
|
182
|
-
*/
|
|
183
|
-
async listArtifacts(args) {
|
|
184
|
-
const result = await this.client.get("/api/artifacts", { params: {
|
|
185
|
-
...args.search ? { search: args.search } : {},
|
|
186
|
-
limit: args.limit,
|
|
187
|
-
offset: args.offset ?? 0
|
|
188
|
-
} });
|
|
189
|
-
return {
|
|
190
|
-
data: result.artifacts ?? [],
|
|
191
|
-
hasMore: result.pagination?.hasMore ?? false
|
|
192
|
-
};
|
|
193
|
-
}
|
|
194
|
-
async getArtifact(artifactId) {
|
|
195
|
-
return this.client.get(`/api/artifacts/${encodeURIComponent(artifactId)}`, { params: { includeContent: "true" } });
|
|
196
|
-
}
|
|
197
|
-
};
|
|
198
|
-
/**
|
|
199
|
-
* Turn an API failure into an actionable, transport-agnostic message. `scope` is
|
|
200
|
-
* the recommended API-key scope for the failing tool. A 403 can come from a
|
|
201
|
-
* missing scope OR from a route-level authorization check (CASL forbidden,
|
|
202
|
-
* suspended account), so the message stays broad rather than asserting a scope
|
|
203
|
-
* gap that may not be the cause.
|
|
204
|
-
*/
|
|
205
|
-
function mapApiError(error, baseURL, scope) {
|
|
206
|
-
if (error instanceof NotAuthenticatedError) return "not authenticated: no credential configured (set B4M_API_KEY or run `b4m login`)";
|
|
207
|
-
if (isAxiosError(error)) {
|
|
208
|
-
const status = error.response?.status;
|
|
209
|
-
if (status === 401) {
|
|
210
|
-
const providerKeyMessage = providerKeyFailureMessage(error.response?.data);
|
|
211
|
-
if (providerKeyMessage) return providerKeyMessage;
|
|
212
|
-
return "authentication failed (run `b4m login` or set B4M_API_KEY)";
|
|
213
|
-
}
|
|
214
|
-
if (status === 403) {
|
|
215
|
-
if ((error.response?.data)?.code === "FEATURE_DISABLED") return "feature disabled on this Bike4Mind instance (ask an admin to enable it)";
|
|
216
|
-
const base = "API key forbidden: check the key's scopes and account access";
|
|
217
|
-
return scope ? `${base} (recommended scope: ${scope})` : base;
|
|
218
|
-
}
|
|
219
|
-
if (status === 429) {
|
|
220
|
-
const retryAfterSeconds = parseRetryAfterSeconds(error.response?.headers?.["retry-after"]);
|
|
221
|
-
const base = extractServerMessage(error.response?.data) || "rate limit exceeded";
|
|
222
|
-
return retryAfterSeconds !== void 0 ? `${base} (retry after ${retryAfterSeconds}s)` : base;
|
|
223
|
-
}
|
|
224
|
-
if (error.code === "ECONNABORTED" || error.code === "ETIMEDOUT" || /timeout/i.test(error.message)) return `request to Bike4Mind at ${baseURL} timed out`;
|
|
225
|
-
if (error.code === "ECONNREFUSED" || error.message.includes("ECONNREFUSED")) return `cannot reach Bike4Mind at ${baseURL}`;
|
|
226
|
-
const serverMsg = extractServerMessage(error.response?.data);
|
|
227
|
-
if (serverMsg) return serverMsg;
|
|
228
|
-
return error.message;
|
|
229
|
-
}
|
|
230
|
-
return error instanceof Error ? error.message : String(error);
|
|
231
|
-
}
|
|
232
|
-
/**
|
|
233
|
-
* A request made with `responseType: 'arraybuffer'` also decodes its error body
|
|
234
|
-
* as bytes, so a JSON `{ error }` payload reaches us as a Buffer that
|
|
235
|
-
* {@link mapApiError} can't read. Decode it back to a parsed object in place so
|
|
236
|
-
* the server's message survives; leave a non-JSON body untouched.
|
|
237
|
-
*/
|
|
238
|
-
function decodeArrayBufferErrorBody(error) {
|
|
239
|
-
if (!isAxiosError(error) || !error.response) return error;
|
|
240
|
-
const { data } = error.response;
|
|
241
|
-
if (typeof data === "string") {
|
|
242
|
-
try {
|
|
243
|
-
error.response.data = JSON.parse(data);
|
|
244
|
-
} catch {}
|
|
245
|
-
return error;
|
|
246
|
-
}
|
|
247
|
-
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;
|
|
248
|
-
if (!bytes) return error;
|
|
249
|
-
try {
|
|
250
|
-
error.response.data = JSON.parse(bytes.toString("utf8"));
|
|
251
|
-
} catch {}
|
|
252
|
-
return error;
|
|
253
|
-
}
|
|
254
|
-
/**
|
|
255
|
-
* Normalize a Retry-After header (RFC 7231: either delta-seconds or an HTTP-date)
|
|
256
|
-
* to a whole, non-negative number of seconds. Returns undefined when the header is
|
|
257
|
-
* absent or parses as neither, so callers can omit the retry hint entirely.
|
|
258
|
-
*/
|
|
259
|
-
function parseRetryAfterSeconds(value) {
|
|
260
|
-
if (value === void 0 || value === null) return void 0;
|
|
261
|
-
const raw = String(value).trim();
|
|
262
|
-
if (/^\d+$/.test(raw)) return Number(raw);
|
|
263
|
-
const dateMs = Date.parse(raw);
|
|
264
|
-
if (Number.isNaN(dateMs)) return void 0;
|
|
265
|
-
return Math.max(0, Math.ceil((dateMs - Date.now()) / 1e3));
|
|
266
|
-
}
|
|
267
|
-
/** Pull a human-readable message out of a JSON error body (`error` or `message` field). */
|
|
268
|
-
function extractServerMessage(data) {
|
|
269
|
-
if (data && typeof data === "object") {
|
|
270
|
-
const record = data;
|
|
271
|
-
if (typeof record.error === "string") return record.error;
|
|
272
|
-
if (typeof record.message === "string") return record.message;
|
|
273
|
-
}
|
|
274
|
-
}
|
|
275
|
-
function providerKeyFailureMessage(data) {
|
|
276
|
-
if (!isProviderKeyFailure(data)) return void 0;
|
|
277
|
-
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)`;
|
|
278
|
-
}
|
|
279
|
-
//#endregion
|
|
280
|
-
//#region src/mcp/tools.ts
|
|
281
|
-
const TOOL_META = [
|
|
282
|
-
{
|
|
283
|
-
name: "list_notebooks",
|
|
284
|
-
title: "List notebooks",
|
|
285
|
-
description: "List the caller's Bike4Mind notebooks (sessions).",
|
|
286
|
-
scope: "notebooks:read"
|
|
287
|
-
},
|
|
288
|
-
{
|
|
289
|
-
name: "get_notebook",
|
|
290
|
-
title: "Get notebook",
|
|
291
|
-
description: "Fetch a single notebook by id.",
|
|
292
|
-
scope: "notebooks:read"
|
|
293
|
-
},
|
|
294
|
-
{
|
|
295
|
-
name: "create_notebook",
|
|
296
|
-
title: "Create notebook",
|
|
297
|
-
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.",
|
|
298
|
-
scope: "notebooks:write"
|
|
299
|
-
},
|
|
300
|
-
{
|
|
301
|
-
name: "send_message",
|
|
302
|
-
title: "Send message",
|
|
303
|
-
description: "Send a chat message and wait for the assistant reply; returns the cited sources (citables) the answer was grounded in.",
|
|
304
|
-
scope: "ai:chat"
|
|
305
|
-
},
|
|
306
|
-
{
|
|
307
|
-
name: "search_knowledge_base",
|
|
308
|
-
title: "Search knowledge base",
|
|
309
|
-
description: "Semantic search across the caller's notebooks.",
|
|
310
|
-
scope: "notebooks:read"
|
|
311
|
-
},
|
|
312
|
-
{
|
|
313
|
-
name: "list_lakes",
|
|
314
|
-
title: "List data lakes",
|
|
315
|
-
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.",
|
|
316
|
-
scope: "datalake:read"
|
|
317
|
-
},
|
|
318
|
-
{
|
|
319
|
-
name: "list_files",
|
|
320
|
-
title: "List files",
|
|
321
|
-
description: "Search the caller's files.",
|
|
322
|
-
scope: "files:read"
|
|
323
|
-
},
|
|
324
|
-
{
|
|
325
|
-
name: "get_file",
|
|
326
|
-
title: "Get file",
|
|
327
|
-
description: "Fetch a file's metadata and a signed download URL.",
|
|
328
|
-
scope: "files:read"
|
|
329
|
-
},
|
|
330
|
-
{
|
|
331
|
-
name: "generate_sound_effect",
|
|
332
|
-
title: "Generate sound effect",
|
|
333
|
-
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.",
|
|
334
|
-
scope: "ai:generate"
|
|
335
|
-
},
|
|
336
|
-
{
|
|
337
|
-
name: "text_to_speech",
|
|
338
|
-
title: "Text to speech",
|
|
339
|
-
description: "Synthesize speech from text. Returns a saved audio file with a signed download URL when available, otherwise audio inline.",
|
|
340
|
-
scope: "ai:generate"
|
|
341
|
-
}
|
|
342
|
-
];
|
|
343
|
-
TOOL_META.map((t) => t.name);
|
|
344
|
-
const listNotebooksShape = {
|
|
345
|
-
search: z$1.string().optional().describe("Filter notebooks by name/content"),
|
|
346
|
-
limit: z$1.number().int().min(1).max(100).default(25).describe("Maximum notebooks to return"),
|
|
347
|
-
page: z$1.number().int().min(1).default(1).describe("1-based page number; request the next page when hasMore is true")
|
|
348
|
-
};
|
|
349
|
-
const getNotebookShape = { notebookId: z$1.string().describe("The notebook (session) id") };
|
|
350
|
-
const createNotebookShape = {
|
|
351
|
-
name: z$1.string().optional().describe("Name for the new notebook"),
|
|
352
|
-
projectId: z$1.string().optional().describe("Project to create the notebook in"),
|
|
353
|
-
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")
|
|
354
|
-
};
|
|
355
|
-
const sendMessageShape = {
|
|
356
|
-
message: z$1.string().describe("The message to send"),
|
|
357
|
-
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)"),
|
|
358
|
-
model: z$1.string().optional().describe("Model id to use; defaults to the instance default"),
|
|
359
|
-
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")
|
|
360
|
-
};
|
|
361
|
-
const searchKnowledgeBaseShape = {
|
|
362
|
-
query: z$1.string().describe("The search query"),
|
|
363
|
-
limit: z$1.number().int().min(1).max(100).default(10).describe("Maximum results to return"),
|
|
364
|
-
minSimilarity: z$1.number().min(0).max(1).optional().describe("Minimum cosine similarity threshold")
|
|
365
|
-
};
|
|
366
|
-
const listLakesShape = {
|
|
367
|
-
limit: z$1.number().int().min(1).max(100).default(25).describe("Maximum lakes to return"),
|
|
368
|
-
cursor: z$1.string().optional().describe("Pass back nextCursor from the previous page")
|
|
369
|
-
};
|
|
370
|
-
const listFilesShape = {
|
|
371
|
-
search: z$1.string().optional().describe("Filter files by name/content"),
|
|
372
|
-
limit: z$1.number().int().min(1).max(100).default(25).describe("Maximum files to return"),
|
|
373
|
-
page: z$1.number().int().min(1).default(1).describe("1-based page number; request the next page when hasMore is true")
|
|
374
|
-
};
|
|
375
|
-
const getFileShape = { fileId: z$1.string().describe("The file id") };
|
|
376
|
-
const generateSoundEffectShape = {
|
|
377
|
-
text: z$1.string().min(1).max(1e3).describe("Text description of the sound effect to generate"),
|
|
378
|
-
provider: z$1.enum(["elevenlabs"]).default("elevenlabs").describe("Sound-generation provider"),
|
|
379
|
-
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"),
|
|
380
|
-
promptInfluence: z$1.number().min(0).max(1).optional().describe("How strictly to follow the prompt (0 = loose, 1 = strict)"),
|
|
381
|
-
format: z$1.string().optional().describe("Provider output encoding token, e.g. mp3_44100_128")
|
|
382
|
-
};
|
|
383
|
-
const textToSpeechShape = {
|
|
384
|
-
...ttsRequestSchema.omit({ encoding: true }).shape,
|
|
385
|
-
text: ttsRequestSchema.shape.text.describe("Text to speak"),
|
|
386
|
-
provider: ttsRequestSchema.shape.provider.describe(`Speech provider; defaults to ${DEFAULT_TTS_PROVIDER}`),
|
|
387
|
-
preview: ttsRequestSchema.shape.preview.describe("Skip saving a copy to the file browser")
|
|
388
|
-
};
|
|
389
|
-
function notebookSummary(n) {
|
|
390
|
-
return {
|
|
391
|
-
id: n.id,
|
|
392
|
-
name: n.name,
|
|
393
|
-
model: n.lastUsedModel ?? void 0,
|
|
394
|
-
createdAt: n.createdAt ?? n.firstCreated,
|
|
395
|
-
updatedAt: n.updatedAt ?? n.lastUpdated
|
|
396
|
-
};
|
|
397
|
-
}
|
|
398
|
-
function lakeSummary(l) {
|
|
399
|
-
return {
|
|
400
|
-
id: l.id,
|
|
401
|
-
name: l.name,
|
|
402
|
-
slug: l.slug,
|
|
403
|
-
description: l.description ?? void 0,
|
|
404
|
-
builtIn: l.built_in,
|
|
405
|
-
status: l.status,
|
|
406
|
-
fileCount: l.file_count
|
|
407
|
-
};
|
|
408
|
-
}
|
|
409
|
-
async function listNotebooks(client, args) {
|
|
410
|
-
const { data, hasMore } = await client.listNotebooks(args);
|
|
411
|
-
return {
|
|
412
|
-
notebooks: data.map(notebookSummary),
|
|
413
|
-
hasMore
|
|
414
|
-
};
|
|
415
|
-
}
|
|
416
|
-
async function getNotebook(client, args) {
|
|
417
|
-
return client.getNotebook(args.notebookId);
|
|
418
|
-
}
|
|
419
|
-
async function createNotebook(client, args) {
|
|
420
|
-
return client.createNotebook({
|
|
421
|
-
...args,
|
|
422
|
-
name: args.name ?? "New Notebook"
|
|
423
|
-
});
|
|
424
|
-
}
|
|
425
|
-
async function sendMessage(client, args) {
|
|
426
|
-
const res = await client.sendChat(args);
|
|
427
|
-
const questId = res.id;
|
|
428
|
-
let quest;
|
|
429
|
-
try {
|
|
430
|
-
quest = await client.getQuest(questId);
|
|
431
|
-
} catch {
|
|
432
|
-
quest = void 0;
|
|
433
|
-
}
|
|
434
|
-
const notebookId = args.notebookId ?? res.sessionId ?? quest?.sessionId;
|
|
435
|
-
const citables = quest ? (quest.promptMeta?.citables ?? []).map((c) => ({
|
|
436
|
-
id: c.id,
|
|
437
|
-
type: c.type,
|
|
438
|
-
title: c.title,
|
|
439
|
-
url: c.url,
|
|
440
|
-
description: c.description
|
|
441
|
-
})) : void 0;
|
|
442
|
-
return {
|
|
443
|
-
notebookId,
|
|
444
|
-
questId,
|
|
445
|
-
reply: res.responses && res.responses.length > 0 ? res.responses.join("\n\n") : res.response ?? "",
|
|
446
|
-
model: res.model,
|
|
447
|
-
citables
|
|
448
|
-
};
|
|
449
|
-
}
|
|
450
|
-
async function searchKnowledgeBase(client, args) {
|
|
451
|
-
return { results: await client.searchKnowledgeBase(args) };
|
|
452
|
-
}
|
|
453
|
-
async function listLakes(client, args) {
|
|
454
|
-
const { data, nextCursor } = await client.listDataLakes(args);
|
|
455
|
-
return {
|
|
456
|
-
lakes: data.map(lakeSummary),
|
|
457
|
-
nextCursor
|
|
458
|
-
};
|
|
459
|
-
}
|
|
460
|
-
async function listFiles(client, args) {
|
|
461
|
-
const { data, hasMore } = await client.listFiles(args);
|
|
462
|
-
return {
|
|
463
|
-
files: data,
|
|
464
|
-
hasMore
|
|
465
|
-
};
|
|
466
|
-
}
|
|
467
|
-
async function getFile(client, args) {
|
|
468
|
-
return client.getFile(args.fileId);
|
|
469
|
-
}
|
|
470
|
-
async function generateSoundEffect(client, args) {
|
|
471
|
-
return generatedAudioResult(await client.generateSoundEffect(args), { provider: args.provider });
|
|
472
|
-
}
|
|
473
|
-
function toResult(value) {
|
|
474
|
-
const structuredContent = value && typeof value === "object" && !Array.isArray(value) ? value : { result: value };
|
|
475
|
-
return {
|
|
476
|
-
content: [{
|
|
477
|
-
type: "text",
|
|
478
|
-
text: JSON.stringify(value, null, 2)
|
|
479
|
-
}],
|
|
480
|
-
structuredContent
|
|
481
|
-
};
|
|
482
|
-
}
|
|
483
|
-
function errorResult(message) {
|
|
484
|
-
return {
|
|
485
|
-
content: [{
|
|
486
|
-
type: "text",
|
|
487
|
-
text: message
|
|
488
|
-
}],
|
|
489
|
-
isError: true
|
|
490
|
-
};
|
|
491
|
-
}
|
|
492
|
-
/**
|
|
493
|
-
* Render a generated-audio response as an MCP result, shared by every audio tool.
|
|
494
|
-
* Oversized audio is reported by its signed URL; a saved copy with a usable URL is
|
|
495
|
-
* reported as a file (like get_file) with no inline bytes. Otherwise the audio rides
|
|
496
|
-
* inline as an `audio` block so a billed result is never lost, with any saved copy
|
|
497
|
-
* still named by id and a skipped save explained. The route forwards the signed URL
|
|
498
|
-
* it minted at upload, so no getFile re-fetch is needed (that fails closed until
|
|
499
|
-
* the async moderation scan runs).
|
|
500
|
-
*/
|
|
501
|
-
function generatedAudioResult(response, endpointMetadata) {
|
|
502
|
-
const metadata = {
|
|
503
|
-
...endpointMetadata,
|
|
504
|
-
contentType: response.contentType
|
|
505
|
-
};
|
|
506
|
-
const saveSkippedReason = response.saveSkippedReason ? { saveSkippedReason: response.saveSkippedReason } : {};
|
|
507
|
-
const file = response.fabFileId ? {
|
|
508
|
-
id: response.fabFileId,
|
|
509
|
-
...response.fileName ? { fileName: response.fileName } : {},
|
|
510
|
-
...response.fileUrl ? { fileUrl: response.fileUrl } : {}
|
|
511
|
-
} : void 0;
|
|
512
|
-
if (response.delivery === "url") return toResult({
|
|
513
|
-
...metadata,
|
|
514
|
-
byteLength: response.bytes,
|
|
515
|
-
url: response.url,
|
|
516
|
-
saved: response.saved === true,
|
|
517
|
-
...response.saved && file ? { file } : {},
|
|
518
|
-
...saveSkippedReason
|
|
519
|
-
});
|
|
520
|
-
const byteLength = Buffer.from(response.audio, "base64").length;
|
|
521
|
-
if (response.saved && file && file.fileUrl) return toResult({
|
|
522
|
-
...metadata,
|
|
523
|
-
byteLength,
|
|
524
|
-
saved: true,
|
|
525
|
-
file
|
|
526
|
-
});
|
|
527
|
-
return inlineAudioResult(response.saved && file ? {
|
|
528
|
-
...metadata,
|
|
529
|
-
byteLength,
|
|
530
|
-
saved: true,
|
|
531
|
-
file
|
|
532
|
-
} : {
|
|
533
|
-
...metadata,
|
|
534
|
-
byteLength,
|
|
535
|
-
saved: false,
|
|
536
|
-
...saveSkippedReason
|
|
537
|
-
}, response.audio, response.contentType);
|
|
538
|
-
}
|
|
539
|
-
/**
|
|
540
|
-
* Metadata as JSON text plus the audio as an MCP `audio` block. The base64 stays
|
|
541
|
-
* out of structuredContent so a potentially large payload is not duplicated.
|
|
542
|
-
*/
|
|
543
|
-
function inlineAudioResult(meta, audioBase64, mimeType) {
|
|
544
|
-
return {
|
|
545
|
-
content: [{
|
|
546
|
-
type: "text",
|
|
547
|
-
text: JSON.stringify(meta, null, 2)
|
|
548
|
-
}, {
|
|
549
|
-
type: "audio",
|
|
550
|
-
data: audioBase64,
|
|
551
|
-
mimeType
|
|
552
|
-
}],
|
|
553
|
-
structuredContent: meta
|
|
554
|
-
};
|
|
555
|
-
}
|
|
556
|
-
async function textToSpeech(client, args) {
|
|
557
|
-
const response = await client.synthesizeSpeech(args);
|
|
558
|
-
if (response.kind === "saved-too-large") {
|
|
559
|
-
const { provider, fabFileId, fileUrl } = response.data;
|
|
560
|
-
return toResult({
|
|
561
|
-
saved: true,
|
|
562
|
-
provider,
|
|
563
|
-
...response.fallbackFrom ? { fallbackFrom: response.fallbackFrom } : {},
|
|
564
|
-
file: {
|
|
565
|
-
id: fabFileId,
|
|
566
|
-
...fileUrl ? { fileUrl } : {}
|
|
567
|
-
}
|
|
568
|
-
});
|
|
569
|
-
}
|
|
570
|
-
const result = response.data;
|
|
571
|
-
return generatedAudioResult(result, {
|
|
572
|
-
provider: result.provider ?? args.provider ?? "openai",
|
|
573
|
-
...result.fallbackFrom ? { fallbackFrom: result.fallbackFrom } : {},
|
|
574
|
-
format: result.format
|
|
575
|
-
});
|
|
576
|
-
}
|
|
577
|
-
/**
|
|
578
|
-
* Register the Bike4Mind MCP tools on `server`. Each handler is wrapped so an
|
|
579
|
-
* API failure becomes a structured `isError` result carrying a friendly message
|
|
580
|
-
* (see {@link mapApiError}) rather than throwing across the transport.
|
|
581
|
-
*/
|
|
582
|
-
function registerTools(server, client) {
|
|
583
|
-
const baseURL = client.baseURL;
|
|
584
|
-
const meta = (name) => TOOL_META.find((t) => t.name === name);
|
|
585
|
-
const run = async (scope, fn) => {
|
|
586
|
-
try {
|
|
587
|
-
return toResult(await fn());
|
|
588
|
-
} catch (err) {
|
|
589
|
-
return errorResult(mapApiError(err, baseURL, scope));
|
|
590
|
-
}
|
|
591
|
-
};
|
|
592
|
-
server.registerTool("list_notebooks", {
|
|
593
|
-
title: meta("list_notebooks").title,
|
|
594
|
-
description: meta("list_notebooks").description,
|
|
595
|
-
inputSchema: listNotebooksShape
|
|
596
|
-
}, (args) => run("notebooks:read", () => listNotebooks(client, args)));
|
|
597
|
-
server.registerTool("get_notebook", {
|
|
598
|
-
title: meta("get_notebook").title,
|
|
599
|
-
description: meta("get_notebook").description,
|
|
600
|
-
inputSchema: getNotebookShape
|
|
601
|
-
}, (args) => run("notebooks:read", () => getNotebook(client, args)));
|
|
602
|
-
server.registerTool("create_notebook", {
|
|
603
|
-
title: meta("create_notebook").title,
|
|
604
|
-
description: meta("create_notebook").description,
|
|
605
|
-
inputSchema: createNotebookShape
|
|
606
|
-
}, (args) => run("notebooks:write", () => createNotebook(client, args)));
|
|
607
|
-
server.registerTool("send_message", {
|
|
608
|
-
title: meta("send_message").title,
|
|
609
|
-
description: meta("send_message").description,
|
|
610
|
-
inputSchema: sendMessageShape
|
|
611
|
-
}, (args) => run("ai:chat", () => sendMessage(client, args)));
|
|
612
|
-
server.registerTool("search_knowledge_base", {
|
|
613
|
-
title: meta("search_knowledge_base").title,
|
|
614
|
-
description: meta("search_knowledge_base").description,
|
|
615
|
-
inputSchema: searchKnowledgeBaseShape
|
|
616
|
-
}, (args) => run("notebooks:read", () => searchKnowledgeBase(client, args)));
|
|
617
|
-
server.registerTool("list_lakes", {
|
|
618
|
-
title: meta("list_lakes").title,
|
|
619
|
-
description: meta("list_lakes").description,
|
|
620
|
-
inputSchema: listLakesShape
|
|
621
|
-
}, (args) => run("datalake:read", () => listLakes(client, args)));
|
|
622
|
-
server.registerTool("list_files", {
|
|
623
|
-
title: meta("list_files").title,
|
|
624
|
-
description: meta("list_files").description,
|
|
625
|
-
inputSchema: listFilesShape
|
|
626
|
-
}, (args) => run("files:read", () => listFiles(client, args)));
|
|
627
|
-
server.registerTool("get_file", {
|
|
628
|
-
title: meta("get_file").title,
|
|
629
|
-
description: meta("get_file").description,
|
|
630
|
-
inputSchema: getFileShape
|
|
631
|
-
}, (args) => run("files:read", () => getFile(client, args)));
|
|
632
|
-
server.registerTool("generate_sound_effect", {
|
|
633
|
-
title: meta("generate_sound_effect").title,
|
|
634
|
-
description: meta("generate_sound_effect").description,
|
|
635
|
-
inputSchema: generateSoundEffectShape
|
|
636
|
-
}, async (args) => {
|
|
637
|
-
try {
|
|
638
|
-
return await generateSoundEffect(client, args);
|
|
639
|
-
} catch (err) {
|
|
640
|
-
return errorResult(mapApiError(err, baseURL, "ai:generate"));
|
|
641
|
-
}
|
|
642
|
-
});
|
|
643
|
-
server.registerTool("text_to_speech", {
|
|
644
|
-
title: meta("text_to_speech").title,
|
|
645
|
-
description: meta("text_to_speech").description,
|
|
646
|
-
inputSchema: textToSpeechShape
|
|
647
|
-
}, async (args) => {
|
|
648
|
-
try {
|
|
649
|
-
return await textToSpeech(client, args);
|
|
650
|
-
} catch (err) {
|
|
651
|
-
return errorResult(mapApiError(err, baseURL, "ai:generate"));
|
|
652
|
-
}
|
|
653
|
-
});
|
|
654
|
-
}
|
|
655
|
-
//#endregion
|
|
656
|
-
//#region src/mcp/resources.ts
|
|
657
|
-
const LIST_LIMIT = 100;
|
|
658
|
-
/**
|
|
659
|
-
* Decode a URI-template variable, tolerating an id that was never encoded.
|
|
660
|
-
*
|
|
661
|
-
* The SDK reaches a read callback via `new URL(uri)` -> `uriTemplate.match(url.toString())`,
|
|
662
|
-
* and `URL.toString()` percent-encodes, so an id we listed with `encodeURIComponent`
|
|
663
|
-
* arrives already encoded and must be decoded back before it hits a REST path. A
|
|
664
|
-
* hand-crafted uri with a malformed escape (e.g. `%zz`) would make `decodeURIComponent`
|
|
665
|
-
* throw a bare `URIError` past `mapApiError`; fall back to the raw value instead.
|
|
666
|
-
*/
|
|
667
|
-
function safeDecode(value) {
|
|
668
|
-
try {
|
|
669
|
-
return decodeURIComponent(value);
|
|
670
|
-
} catch {
|
|
671
|
-
return value;
|
|
672
|
-
}
|
|
673
|
-
}
|
|
674
|
-
/**
|
|
675
|
-
* Register one `b4m://<name>/{id}` JSON resource.
|
|
676
|
-
*
|
|
677
|
-
* `list` degrades to an empty array on failure rather than throwing: the SDK's
|
|
678
|
-
* resources/list handler awaits every registered template's list callback in one
|
|
679
|
-
* unguarded loop, so a throw here would also blank every sibling template. `read`
|
|
680
|
-
* still throws - a single read failure has no fan-out.
|
|
681
|
-
*/
|
|
682
|
-
function registerJsonResource(server, client, spec) {
|
|
683
|
-
server.registerResource(spec.name, new ResourceTemplate(`b4m://${spec.name}/{id}`, { list: async () => {
|
|
684
|
-
try {
|
|
685
|
-
return { resources: (await spec.list()).map((item) => {
|
|
686
|
-
const label = spec.label(item) ?? spec.id(item);
|
|
687
|
-
return {
|
|
688
|
-
uri: `b4m://${spec.name}/${encodeURIComponent(spec.id(item))}`,
|
|
689
|
-
name: label,
|
|
690
|
-
title: label,
|
|
691
|
-
mimeType: "application/json"
|
|
692
|
-
};
|
|
693
|
-
}) };
|
|
694
|
-
} catch (err) {
|
|
695
|
-
logger.error(`mcp: listing ${spec.name} resources failed: ${mapApiError(err, client.baseURL, spec.scope)}`);
|
|
696
|
-
return { resources: [] };
|
|
697
|
-
}
|
|
698
|
-
} }), {
|
|
699
|
-
title: spec.title,
|
|
700
|
-
description: spec.description,
|
|
701
|
-
mimeType: "application/json"
|
|
702
|
-
}, async (uri, variables) => {
|
|
703
|
-
const id = safeDecode(String(variables.id));
|
|
704
|
-
try {
|
|
705
|
-
const record = await spec.read(id);
|
|
706
|
-
return { contents: [{
|
|
707
|
-
uri: uri.href,
|
|
708
|
-
mimeType: "application/json",
|
|
709
|
-
text: JSON.stringify(record, null, 2)
|
|
710
|
-
}] };
|
|
711
|
-
} catch (err) {
|
|
712
|
-
throw new Error(mapApiError(err, client.baseURL, spec.scope));
|
|
713
|
-
}
|
|
714
|
-
});
|
|
715
|
-
}
|
|
716
|
-
/**
|
|
717
|
-
* Register `b4m://agent-quest`: the machine-readable invitation to The Open Door.
|
|
718
|
-
*
|
|
719
|
-
* A fixed URI rather than a `ResourceTemplate` - there is exactly one manifest, so
|
|
720
|
-
* there is nothing to list or address by id. It is also the only resource here that
|
|
721
|
-
* needs no API call and no credentials: the document is a constant in
|
|
722
|
-
* @bike4mind/common, shared with the public HTTP route that serves it
|
|
723
|
-
* (apps/client/pages/api/agent-quest/manifest.ts). That means an agent can read the
|
|
724
|
-
* invitation before it has an API key - which is the point, since the quest is how
|
|
725
|
-
* it earns one.
|
|
726
|
-
*/
|
|
727
|
-
function registerAgentQuest(server) {
|
|
728
|
-
server.registerResource(AGENT_QUEST_ID, AGENT_QUEST_MCP_URI, {
|
|
729
|
-
title: AGENT_QUEST_MANIFEST.title,
|
|
730
|
-
description: AGENT_QUEST_MANIFEST.summary,
|
|
731
|
-
mimeType: "application/json"
|
|
732
|
-
}, (uri) => ({ contents: [{
|
|
733
|
-
uri: uri.href,
|
|
734
|
-
mimeType: "application/json",
|
|
735
|
-
text: JSON.stringify(AGENT_QUEST_MANIFEST, null, 2)
|
|
736
|
-
}] }));
|
|
737
|
-
}
|
|
738
|
-
/**
|
|
739
|
-
* Register the Bike4Mind MCP resources: the four templates below, each served as
|
|
740
|
-
* application/json and backed by its REST list/read pair, plus the credential-free
|
|
741
|
-
* `b4m://agent-quest` manifest.
|
|
742
|
-
*/
|
|
743
|
-
function registerResources(server, client) {
|
|
744
|
-
registerAgentQuest(server);
|
|
745
|
-
registerJsonResource(server, client, {
|
|
746
|
-
name: "notebook",
|
|
747
|
-
title: "Notebook",
|
|
748
|
-
description: "A Bike4Mind notebook (session)",
|
|
749
|
-
scope: "notebooks:read",
|
|
750
|
-
list: async () => (await client.listNotebooks({ limit: LIST_LIMIT })).data,
|
|
751
|
-
id: (n) => n.id,
|
|
752
|
-
label: (n) => n.name,
|
|
753
|
-
read: (id) => client.getNotebook(id)
|
|
754
|
-
});
|
|
755
|
-
registerJsonResource(server, client, {
|
|
756
|
-
name: "file",
|
|
757
|
-
title: "File",
|
|
758
|
-
description: "A Bike4Mind file: metadata plus a signed download URL",
|
|
759
|
-
scope: "files:read",
|
|
760
|
-
list: async () => (await client.listFiles({ limit: LIST_LIMIT })).data,
|
|
761
|
-
id: (f) => f.id,
|
|
762
|
-
label: (f) => f.fileName,
|
|
763
|
-
read: (id) => client.getFile(id)
|
|
764
|
-
});
|
|
765
|
-
registerJsonResource(server, client, {
|
|
766
|
-
name: "project",
|
|
767
|
-
title: "Project",
|
|
768
|
-
description: "A Bike4Mind project",
|
|
769
|
-
scope: "projects:read",
|
|
770
|
-
list: async () => (await client.listProjects({ limit: LIST_LIMIT })).data,
|
|
771
|
-
id: (p) => p.id,
|
|
772
|
-
label: (p) => p.name,
|
|
773
|
-
read: (id) => client.getProject(id)
|
|
774
|
-
});
|
|
775
|
-
registerJsonResource(server, client, {
|
|
776
|
-
name: "artifact",
|
|
777
|
-
title: "Artifact",
|
|
778
|
-
description: "A Bike4Mind artifact: metadata plus its current content",
|
|
779
|
-
list: async () => (await client.listArtifacts({ limit: LIST_LIMIT })).data,
|
|
780
|
-
id: (a) => a.id,
|
|
781
|
-
label: (a) => a.title,
|
|
782
|
-
read: (id) => client.getArtifact(id)
|
|
783
|
-
});
|
|
784
|
-
}
|
|
785
|
-
//#endregion
|
|
786
|
-
//#region src/mcp/server.ts
|
|
787
|
-
/**
|
|
788
|
-
* Build a fully-configured Bike4Mind MCP server: the tools, the four resource
|
|
789
|
-
* templates (`b4m://notebook/{id}`, `b4m://file/{id}`, `b4m://project/{id}`,
|
|
790
|
-
* `b4m://artifact/{id}`) backed by a {@link B4mApiClient} bound to the given
|
|
791
|
-
* endpoint and credentials, and the credential-free `b4m://agent-quest` manifest.
|
|
792
|
-
* Tool listing never touches the network - only tool/resource *calls* hit the API -
|
|
793
|
-
* so a server built with an unreachable endpoint still advertises its full
|
|
794
|
-
* capability set.
|
|
795
|
-
*/
|
|
796
|
-
function buildMcpServer(options) {
|
|
797
|
-
const client = new B4mApiClient(options.baseURL, options.configStore, options.apiKey);
|
|
798
|
-
const server = new McpServer({
|
|
799
|
-
name: "bike4mind",
|
|
800
|
-
version: options.version
|
|
801
|
-
}, { capabilities: {
|
|
802
|
-
tools: {},
|
|
803
|
-
resources: {}
|
|
804
|
-
} });
|
|
805
|
-
registerTools(server, client);
|
|
806
|
-
registerResources(server, client);
|
|
807
|
-
return server;
|
|
808
|
-
}
|
|
809
|
-
//#endregion
|
|
810
|
-
//#region src/mcp/serve.ts
|
|
811
|
-
/**
|
|
812
|
-
* `b4m mcp serve` - expose Bike4Mind as an MCP server.
|
|
813
|
-
*
|
|
814
|
-
* Two transports: stdio (default, for Claude Desktop and other local clients)
|
|
815
|
-
* and stateless streamable HTTP (`--http`). Auth precedence is
|
|
816
|
-
* `--api-key` > `B4M_API_KEY` > the stored OAuth JWT; the endpoint is
|
|
817
|
-
* `B4M_API_URL` > `--api-url` > the CLI's configured backend.
|
|
818
|
-
*
|
|
819
|
-
* Transport contract for stdio: stdout carries the JSON-RPC frame stream and
|
|
820
|
-
* NOTHING else, so all diagnostics are forced to stderr before ANY other work
|
|
821
|
-
* runs (mirrors the acp command's captureStdout - see src/commands/acpCommand.ts).
|
|
822
|
-
*
|
|
823
|
-
* HTTP mode is deliberately loopback-only (binds 127.0.0.1) with no per-request
|
|
824
|
-
* auth of its own - it trusts anything that can reach the socket, so it must not
|
|
825
|
-
* be exposed on a routable interface. DNS-rebinding protection is on as defense
|
|
826
|
-
* in depth against a browser being tricked into posting to the local port.
|
|
827
|
-
*/
|
|
828
|
-
const HTTP_PATH = "/mcp";
|
|
829
|
-
/**
|
|
830
|
-
* Capture the real stdout for the JSON-RPC frame stream, then redirect
|
|
831
|
-
* everything else - `console.*` and any stray `process.stdout.write` deep in the
|
|
832
|
-
* stack - to stderr. A single unrelated byte on stdout corrupts a frame, so the
|
|
833
|
-
* whole channel is closed rather than trusting no dependency ever prints.
|
|
834
|
-
*/
|
|
835
|
-
function captureStdout() {
|
|
836
|
-
const writeToRealStdout = process.stdout.write.bind(process.stdout);
|
|
837
|
-
const toStderr = (...args) => {
|
|
838
|
-
process.stderr.write(args.map(String).join(" ") + "\n");
|
|
839
|
-
};
|
|
840
|
-
console.log = toStderr;
|
|
841
|
-
console.info = toStderr;
|
|
842
|
-
console.debug = toStderr;
|
|
843
|
-
process.stdout.write = process.stderr.write.bind(process.stderr);
|
|
844
|
-
return writeToRealStdout;
|
|
845
|
-
}
|
|
846
|
-
function resolveBaseURL(options, configStore) {
|
|
847
|
-
const explicit = process.env.B4M_API_URL ?? options.apiUrl;
|
|
848
|
-
if (explicit) {
|
|
849
|
-
const parsed = parseApiUrl(explicit);
|
|
850
|
-
if ("error" in parsed) throw new Error(`Invalid API URL: ${parsed.error}`);
|
|
851
|
-
return Promise.resolve(parsed.url);
|
|
852
|
-
}
|
|
853
|
-
return configStore.getApiConfig().then((apiConfig) => requireApiUrl(apiConfig));
|
|
854
|
-
}
|
|
855
|
-
async function serveStdio(buildOptions, writeFrame) {
|
|
856
|
-
const server = buildMcpServer(buildOptions);
|
|
857
|
-
const stdout = new Writable({ write(chunk, _encoding, callback) {
|
|
858
|
-
if (writeFrame(chunk)) {
|
|
859
|
-
callback();
|
|
860
|
-
return;
|
|
861
|
-
}
|
|
862
|
-
process.stdout.once("drain", () => callback());
|
|
863
|
-
} });
|
|
864
|
-
const transport = new StdioServerTransport(process.stdin, stdout);
|
|
865
|
-
await server.connect(transport);
|
|
866
|
-
await new Promise((resolve) => {
|
|
867
|
-
process.stdin.once("end", resolve);
|
|
868
|
-
process.stdin.once("close", resolve);
|
|
869
|
-
});
|
|
870
|
-
}
|
|
871
|
-
async function handleHttpRequest(req, res, buildOptions, port) {
|
|
872
|
-
const server = buildMcpServer(buildOptions);
|
|
873
|
-
const transport = new StreamableHTTPServerTransport({
|
|
874
|
-
sessionIdGenerator: void 0,
|
|
875
|
-
enableJsonResponse: true,
|
|
876
|
-
enableDnsRebindingProtection: true,
|
|
877
|
-
allowedHosts: [`127.0.0.1:${port}`, `localhost:${port}`],
|
|
878
|
-
allowedOrigins: [`http://127.0.0.1:${port}`, `http://localhost:${port}`]
|
|
879
|
-
});
|
|
880
|
-
let released = false;
|
|
881
|
-
const release = () => {
|
|
882
|
-
if (released) return;
|
|
883
|
-
released = true;
|
|
884
|
-
transport.close();
|
|
885
|
-
server.close();
|
|
886
|
-
};
|
|
887
|
-
res.on("finish", release);
|
|
888
|
-
res.on("close", release);
|
|
889
|
-
await server.connect(transport);
|
|
890
|
-
await transport.handleRequest(req, res);
|
|
891
|
-
}
|
|
892
|
-
async function serveHttp(buildOptions, port) {
|
|
893
|
-
const httpServer = createServer((req, res) => {
|
|
894
|
-
if (new URL(req.url ?? "/", `http://localhost:${port}`).pathname !== HTTP_PATH) {
|
|
895
|
-
res.writeHead(404, { "Content-Type": "application/json" });
|
|
896
|
-
res.end(JSON.stringify({ error: `Not found. The MCP endpoint is ${HTTP_PATH}.` }));
|
|
897
|
-
return;
|
|
898
|
-
}
|
|
899
|
-
handleHttpRequest(req, res, buildOptions, port).catch((err) => {
|
|
900
|
-
logger.error("MCP HTTP request failed", err);
|
|
901
|
-
if (!res.headersSent) {
|
|
902
|
-
res.writeHead(500, { "Content-Type": "application/json" });
|
|
903
|
-
res.end(JSON.stringify({
|
|
904
|
-
jsonrpc: "2.0",
|
|
905
|
-
error: {
|
|
906
|
-
code: -32603,
|
|
907
|
-
message: "Internal server error"
|
|
908
|
-
},
|
|
909
|
-
id: null
|
|
910
|
-
}));
|
|
911
|
-
}
|
|
912
|
-
});
|
|
913
|
-
});
|
|
914
|
-
await new Promise((resolve, reject) => {
|
|
915
|
-
httpServer.once("error", reject);
|
|
916
|
-
httpServer.listen(port, "127.0.0.1", () => resolve());
|
|
917
|
-
});
|
|
918
|
-
process.stderr.write(`Bike4Mind MCP server listening on http://127.0.0.1:${port}${HTTP_PATH}\n`);
|
|
919
|
-
await new Promise((resolve) => {
|
|
920
|
-
const shutdown = () => httpServer.close(() => resolve());
|
|
921
|
-
process.once("SIGINT", shutdown);
|
|
922
|
-
process.once("SIGTERM", shutdown);
|
|
923
|
-
});
|
|
924
|
-
}
|
|
925
|
-
async function handleMcpServeCommand(options) {
|
|
926
|
-
const writeFrame = options.http ? void 0 : captureStdout();
|
|
927
|
-
const configStore = new ConfigStore();
|
|
928
|
-
const buildOptions = {
|
|
929
|
-
baseURL: await resolveBaseURL(options, configStore),
|
|
930
|
-
apiKey: options.apiKey ?? process.env.B4M_API_KEY,
|
|
931
|
-
configStore,
|
|
932
|
-
version: options.version
|
|
933
|
-
};
|
|
934
|
-
if (writeFrame) await serveStdio(buildOptions, writeFrame);
|
|
935
|
-
else await serveHttp(buildOptions, options.port ?? 7e3);
|
|
936
|
-
}
|
|
937
|
-
//#endregion
|
|
938
|
-
export { handleMcpServeCommand };
|