@brainbox-labs/sdk 0.0.0-stage → 0.23.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 +346 -2
- package/dist/athena-R67AV2DO.js +13 -0
- package/dist/bin.d.ts +1 -0
- package/dist/bin.js +57 -0
- package/dist/chunk-43LDD7YT.js +139 -0
- package/dist/chunk-4J77FNJJ.js +192 -0
- package/dist/chunk-AJR44IFE.js +47 -0
- package/dist/chunk-GVWDS5TG.js +112 -0
- package/dist/chunk-MF3BADT7.js +544 -0
- package/dist/chunk-MLKGABMK.js +9 -0
- package/dist/chunk-VEXUCOXR.js +387 -0
- package/dist/chunk-XFLBPF4A.js +169 -0
- package/dist/chunk-YRH35U57.js +178 -0
- package/dist/column-profiler-FJCAQQAS.js +23 -0
- package/dist/docs-loader-B2l0cO36.d.ts +25 -0
- package/dist/docs-loader-VA4KBG6Y.js +11 -0
- package/dist/index-qV0gq2eJ.d.ts +148 -0
- package/dist/index.d.ts +476 -0
- package/dist/index.js +523 -0
- package/dist/ingest/public.d.ts +178 -0
- package/dist/ingest/public.js +63 -0
- package/dist/ingest-DICRS7WW.js +13 -0
- package/dist/introspect-KQOOQEZM.js +11 -0
- package/dist/schema-reader-4ZVTUZIX.js +150 -0
- package/dist/serve/index.d.ts +2 -0
- package/dist/serve/index.js +8 -0
- package/dist/sql-parser-TB26PFXS.js +198 -0
- package/dist/sync-MXG4WALD.js +260 -0
- package/dist/trino-TUQ7CIRM.js +13 -0
- package/package.json +79 -4
|
@@ -0,0 +1,544 @@
|
|
|
1
|
+
import {
|
|
2
|
+
createBrainExecutor,
|
|
3
|
+
createTenantBrainExecutor
|
|
4
|
+
} from "./chunk-GVWDS5TG.js";
|
|
5
|
+
import {
|
|
6
|
+
__export
|
|
7
|
+
} from "./chunk-MLKGABMK.js";
|
|
8
|
+
|
|
9
|
+
// src/serve/index.ts
|
|
10
|
+
var serve_exports = {};
|
|
11
|
+
__export(serve_exports, {
|
|
12
|
+
MCP: () => MCP
|
|
13
|
+
});
|
|
14
|
+
|
|
15
|
+
// src/serve/mcp.ts
|
|
16
|
+
import { AsyncLocalStorage } from "async_hooks";
|
|
17
|
+
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
|
|
18
|
+
import express from "express";
|
|
19
|
+
|
|
20
|
+
// src/serve/sync.ts
|
|
21
|
+
function slug(s) {
|
|
22
|
+
return s.toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "") || "project";
|
|
23
|
+
}
|
|
24
|
+
var SyncEngine = class {
|
|
25
|
+
tools = [];
|
|
26
|
+
listeners = [];
|
|
27
|
+
timer = null;
|
|
28
|
+
opts;
|
|
29
|
+
constructor(opts) {
|
|
30
|
+
if (opts.projectId !== void 0 && opts.projects !== void 0) {
|
|
31
|
+
throw new Error("[BrainBox] SyncEngine accepts either `projectId` or `projects`, not both.");
|
|
32
|
+
}
|
|
33
|
+
if (opts.projectId === void 0 && (opts.projects === void 0 || opts.projects.length === 0)) {
|
|
34
|
+
throw new Error("[BrainBox] SyncEngine requires either `projectId` or a non-empty `projects` list.");
|
|
35
|
+
}
|
|
36
|
+
if (opts.projects !== void 0 && !opts.projects.some((p) => p.role === "overlay")) {
|
|
37
|
+
throw new Error("[BrainBox] SyncEngine `projects` must include exactly one `role: 'overlay'` entry.");
|
|
38
|
+
}
|
|
39
|
+
this.opts = { ...opts, apiUrl: opts.apiUrl.replace(/\/+$/, "") };
|
|
40
|
+
}
|
|
41
|
+
onUpdate(fn) {
|
|
42
|
+
this.listeners.push(fn);
|
|
43
|
+
}
|
|
44
|
+
getTools() {
|
|
45
|
+
return this.tools;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Fetch tools once immediately (required to start the server).
|
|
49
|
+
* If pollIntervalMs is set, also starts polling for updates.
|
|
50
|
+
* Throws if the initial fetch fails.
|
|
51
|
+
*/
|
|
52
|
+
async start() {
|
|
53
|
+
await this.fetch();
|
|
54
|
+
if (this.opts.pollIntervalMs) {
|
|
55
|
+
this.timer = setInterval(() => {
|
|
56
|
+
this.fetch().catch((err) => console.error("[BrainBox] Sync error:", err));
|
|
57
|
+
}, this.opts.pollIntervalMs);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
stop() {
|
|
61
|
+
if (this.timer) {
|
|
62
|
+
clearInterval(this.timer);
|
|
63
|
+
this.timer = null;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
async fetch() {
|
|
67
|
+
const incoming = this.opts.projects ? await this.fetchMultiProject(this.opts.projects) : await this.fetchRawTools(this.opts.projectId);
|
|
68
|
+
if (this.hasChanged(incoming)) {
|
|
69
|
+
this.tools = incoming;
|
|
70
|
+
for (const fn of this.listeners) fn(this.tools);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
async fetchMultiProject(projects) {
|
|
74
|
+
const overlay = projects.find((p) => p.role === "overlay");
|
|
75
|
+
const settled = await Promise.allSettled(
|
|
76
|
+
projects.map(async (project) => ({ project, tools: await this.fetchRawTools(project.projectId) }))
|
|
77
|
+
);
|
|
78
|
+
const fulfilled = settled.filter(
|
|
79
|
+
(r) => r.status === "fulfilled"
|
|
80
|
+
);
|
|
81
|
+
const overlayResult = fulfilled.find((r) => r.value.project.projectId === overlay.projectId);
|
|
82
|
+
if (!overlayResult) {
|
|
83
|
+
const failure = settled.find((r) => r.status === "rejected");
|
|
84
|
+
throw new Error(
|
|
85
|
+
`[BrainBox] Failed to sync tools from the tenant overlay project (${overlay.projectId})` + (failure ? `: ${String(failure.reason)}` : ".")
|
|
86
|
+
);
|
|
87
|
+
}
|
|
88
|
+
const bases = projects.filter((p) => p.role !== "overlay");
|
|
89
|
+
const brainTools = overlayResult.value.tools.filter((t) => t.execution.type === "brain").map((t) => this.withProjectIdParam(t, overlay, bases));
|
|
90
|
+
const nonBrainTools = [];
|
|
91
|
+
for (const { value } of fulfilled) {
|
|
92
|
+
const { project, tools } = value;
|
|
93
|
+
for (const tool of tools) {
|
|
94
|
+
if (tool.execution.type === "brain") continue;
|
|
95
|
+
const tagged = {
|
|
96
|
+
...tool,
|
|
97
|
+
sourceProject: { projectId: project.projectId, role: project.role }
|
|
98
|
+
};
|
|
99
|
+
nonBrainTools.push(
|
|
100
|
+
project.role === "overlay" ? tagged : { ...tagged, name: `${slug(project.name ?? project.projectId)}__${tool.name}` }
|
|
101
|
+
);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
return [...brainTools, ...nonBrainTools];
|
|
105
|
+
}
|
|
106
|
+
withProjectIdParam(tool, overlay, bases) {
|
|
107
|
+
const baseList = bases.length > 0 ? bases.map((b) => `${b.name ?? b.projectId} (${b.projectId})`).join(", ") : "(none)";
|
|
108
|
+
return {
|
|
109
|
+
...tool,
|
|
110
|
+
inputSchema: {
|
|
111
|
+
...tool.inputSchema,
|
|
112
|
+
properties: {
|
|
113
|
+
...tool.inputSchema.properties,
|
|
114
|
+
projectId: {
|
|
115
|
+
type: "string",
|
|
116
|
+
description: `Project to read from. Defaults to the tenant overlay (${overlay.name ?? overlay.projectId}) \u2014 pass a readable base project ID to read from that brain instead. Write tools always target the overlay regardless of this value. Readable base projects: ${baseList}.`
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
async fetchRawTools(projectId) {
|
|
123
|
+
const { apiKey } = this.opts;
|
|
124
|
+
const url = `${this.opts.apiUrl}/api/projects/${encodeURIComponent(projectId)}/tools`;
|
|
125
|
+
const res = await globalThis.fetch(url, {
|
|
126
|
+
headers: { Authorization: `Bearer ${apiKey}` }
|
|
127
|
+
});
|
|
128
|
+
if (!res.ok) {
|
|
129
|
+
throw new Error(`[BrainBox] Tools API ${res.status}: ${await res.text()}`);
|
|
130
|
+
}
|
|
131
|
+
const contentType = res.headers.get("content-type") ?? "";
|
|
132
|
+
if (!contentType.includes("application/json")) {
|
|
133
|
+
throw new Error(
|
|
134
|
+
`[BrainBox] Tools API returned non-JSON (${contentType}) from ${url}.
|
|
135
|
+
Is BRAINBOX_API_URL set correctly? (e.g. http://localhost:5002 for local emulator)
|
|
136
|
+
Is the emulator running?`
|
|
137
|
+
);
|
|
138
|
+
}
|
|
139
|
+
return res.json();
|
|
140
|
+
}
|
|
141
|
+
hasChanged(incoming) {
|
|
142
|
+
if (incoming.length !== this.tools.length) return true;
|
|
143
|
+
const key = (t) => `${t.sourceProject?.projectId ?? ""}::${t.name}`;
|
|
144
|
+
const currentVersions = new Map(this.tools.map((t) => [key(t), t.version]));
|
|
145
|
+
return incoming.some((t) => currentVersions.get(key(t)) !== t.version);
|
|
146
|
+
}
|
|
147
|
+
};
|
|
148
|
+
|
|
149
|
+
// src/serve/connectors/sql.ts
|
|
150
|
+
import pg from "pg";
|
|
151
|
+
var { Pool } = pg;
|
|
152
|
+
var SqlExecutor = class {
|
|
153
|
+
pool;
|
|
154
|
+
constructor(url) {
|
|
155
|
+
this.pool = new Pool({ connectionString: url });
|
|
156
|
+
}
|
|
157
|
+
async query(sql, params = []) {
|
|
158
|
+
const result = await this.pool.query(sql, params);
|
|
159
|
+
return result.rows;
|
|
160
|
+
}
|
|
161
|
+
async end() {
|
|
162
|
+
await this.pool.end();
|
|
163
|
+
}
|
|
164
|
+
};
|
|
165
|
+
var NoopSqlClient = class {
|
|
166
|
+
async query(_sql) {
|
|
167
|
+
throw new Error(
|
|
168
|
+
"[BrainBox] No SQL connector configured. Pass connectors.sql.url to BrainBoxMCP."
|
|
169
|
+
);
|
|
170
|
+
}
|
|
171
|
+
};
|
|
172
|
+
|
|
173
|
+
// src/serve/server.ts
|
|
174
|
+
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
|
|
175
|
+
import {
|
|
176
|
+
ListToolsRequestSchema,
|
|
177
|
+
CallToolRequestSchema
|
|
178
|
+
} from "@modelcontextprotocol/sdk/types.js";
|
|
179
|
+
|
|
180
|
+
// src/serve/middleware.ts
|
|
181
|
+
async function runMiddlewareChain(middlewares, ctx) {
|
|
182
|
+
let idx = 0;
|
|
183
|
+
const next = async () => {
|
|
184
|
+
if (idx < middlewares.length) {
|
|
185
|
+
await middlewares[idx++](ctx, next);
|
|
186
|
+
}
|
|
187
|
+
};
|
|
188
|
+
await next();
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
// src/serve/dispatch.ts
|
|
192
|
+
function maxPlaceholderIndex(sql) {
|
|
193
|
+
const matches = sql.match(/\$(\d+)/g);
|
|
194
|
+
if (!matches) return 0;
|
|
195
|
+
return matches.reduce((max, token) => {
|
|
196
|
+
const idx = parseInt(token.slice(1), 10);
|
|
197
|
+
return Number.isNaN(idx) ? max : Math.max(max, idx);
|
|
198
|
+
}, 0);
|
|
199
|
+
}
|
|
200
|
+
function orderedParamNames(tool) {
|
|
201
|
+
const required = tool.inputSchema.required ?? [];
|
|
202
|
+
const allProps = Object.keys(tool.inputSchema.properties ?? {});
|
|
203
|
+
const seen = /* @__PURE__ */ new Set();
|
|
204
|
+
const ordered = [];
|
|
205
|
+
for (const name of required) {
|
|
206
|
+
if (!seen.has(name)) {
|
|
207
|
+
seen.add(name);
|
|
208
|
+
ordered.push(name);
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
for (const name of allProps) {
|
|
212
|
+
if (!seen.has(name)) {
|
|
213
|
+
seen.add(name);
|
|
214
|
+
ordered.push(name);
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
return ordered;
|
|
218
|
+
}
|
|
219
|
+
async function dispatchTool(tool, params, ctx, overrides, customExecutor, brainExecutor) {
|
|
220
|
+
const override = overrides.get(tool.name);
|
|
221
|
+
if (override) return override(params, ctx);
|
|
222
|
+
if (tool.execution.type === "sql") {
|
|
223
|
+
const placeholderCount = maxPlaceholderIndex(tool.execution.query);
|
|
224
|
+
const paramNames = orderedParamNames(tool);
|
|
225
|
+
const valuesBySchemaOrder = paramNames.map((name) => params[name]);
|
|
226
|
+
const sqlParams = valuesBySchemaOrder.length > 0 ? valuesBySchemaOrder : Object.values(params);
|
|
227
|
+
const missingInRequiredPositions = sqlParams.slice(0, placeholderCount).filter((value) => value === void 0).length;
|
|
228
|
+
if (placeholderCount > 0 && (sqlParams.length < placeholderCount || missingInRequiredPositions > 0)) {
|
|
229
|
+
const providedCount = Math.min(
|
|
230
|
+
sqlParams.length,
|
|
231
|
+
placeholderCount
|
|
232
|
+
) - missingInRequiredPositions;
|
|
233
|
+
throw new Error(
|
|
234
|
+
`Tool '${tool.name}' requires ${placeholderCount} SQL parameter(s) ($1..$${placeholderCount}) but received ${Math.max(providedCount, 0)}. Provide required tool arguments.`
|
|
235
|
+
);
|
|
236
|
+
}
|
|
237
|
+
return ctx.sql.query(tool.execution.query, sqlParams);
|
|
238
|
+
}
|
|
239
|
+
if (tool.execution.type === "brain") {
|
|
240
|
+
if (!brainExecutor) {
|
|
241
|
+
throw new Error(
|
|
242
|
+
`Tool '${tool.name}' is a brain tool but no brain executor is configured. Ensure BRAINBOX_API_KEY and BRAINBOX_API_URL are set.`
|
|
243
|
+
);
|
|
244
|
+
}
|
|
245
|
+
if (tool.sourceProject !== void 0) {
|
|
246
|
+
return brainExecutor(tool.execution.toolName, params, { projectId: tool.sourceProject.projectId });
|
|
247
|
+
}
|
|
248
|
+
if ("projectId" in params) {
|
|
249
|
+
const { projectId, ...rest } = params;
|
|
250
|
+
return brainExecutor(
|
|
251
|
+
tool.execution.toolName,
|
|
252
|
+
rest,
|
|
253
|
+
typeof projectId === "string" ? { projectId } : void 0
|
|
254
|
+
);
|
|
255
|
+
}
|
|
256
|
+
return brainExecutor(tool.execution.toolName, params);
|
|
257
|
+
}
|
|
258
|
+
if (customExecutor) {
|
|
259
|
+
return customExecutor(tool.name, params);
|
|
260
|
+
}
|
|
261
|
+
if (tool.execution.type === "retrieval") {
|
|
262
|
+
throw new Error(
|
|
263
|
+
`Tool '${tool.name}' is a retrieval tool and requires a custom implementation. Register it with mcp.tool('${tool.name}', handler).`
|
|
264
|
+
);
|
|
265
|
+
}
|
|
266
|
+
throw new Error(
|
|
267
|
+
`Tool '${tool.name}' requires a custom implementation. Register it with mcp.tool('${tool.name}', handler).`
|
|
268
|
+
);
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
// src/serve/server.ts
|
|
272
|
+
function buildMcpServer(opts) {
|
|
273
|
+
const { tools, middlewares, overrides, sqlClient, customExecutor, brainExecutor, requestStore: requestStore2 } = opts;
|
|
274
|
+
const server = new Server(
|
|
275
|
+
{ name: "brainbox-mcp", version: "1.0.0" },
|
|
276
|
+
{ capabilities: { tools: {} } }
|
|
277
|
+
);
|
|
278
|
+
server.setRequestHandler(ListToolsRequestSchema, () => ({
|
|
279
|
+
tools: tools.map((t) => ({
|
|
280
|
+
name: t.name,
|
|
281
|
+
description: t.description,
|
|
282
|
+
inputSchema: t.inputSchema
|
|
283
|
+
}))
|
|
284
|
+
}));
|
|
285
|
+
server.setRequestHandler(CallToolRequestSchema, async (req) => {
|
|
286
|
+
const toolName = req.params.name;
|
|
287
|
+
const params = req.params.arguments ?? {};
|
|
288
|
+
const tool = tools.find((t) => t.name === toolName);
|
|
289
|
+
if (!tool) {
|
|
290
|
+
return { content: [{ type: "text", text: `Unknown tool: ${toolName}` }], isError: true };
|
|
291
|
+
}
|
|
292
|
+
const headers = requestStore2.getStore()?.headers ?? {};
|
|
293
|
+
const ctx = {
|
|
294
|
+
sql: sqlClient,
|
|
295
|
+
toolName: tool.name,
|
|
296
|
+
headers,
|
|
297
|
+
defaultQuery: tool.execution.type === "sql" ? tool.execution.query : void 0
|
|
298
|
+
};
|
|
299
|
+
try {
|
|
300
|
+
await runMiddlewareChain(middlewares, ctx);
|
|
301
|
+
const result = await dispatchTool(tool, params, ctx, overrides, customExecutor, brainExecutor);
|
|
302
|
+
return { content: [{ type: "text", text: JSON.stringify(result) }] };
|
|
303
|
+
} catch (err) {
|
|
304
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
305
|
+
return { content: [{ type: "text", text: message }], isError: true };
|
|
306
|
+
}
|
|
307
|
+
});
|
|
308
|
+
return server;
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
// src/client.ts
|
|
312
|
+
import { BrainBoxApiClient } from "@brainbox-labs/api";
|
|
313
|
+
var noopLogger = {
|
|
314
|
+
isVerbose: false,
|
|
315
|
+
debug: () => {
|
|
316
|
+
},
|
|
317
|
+
info: () => {
|
|
318
|
+
},
|
|
319
|
+
warn: () => {
|
|
320
|
+
},
|
|
321
|
+
error: () => {
|
|
322
|
+
}
|
|
323
|
+
};
|
|
324
|
+
var BrainBoxClient = class {
|
|
325
|
+
api;
|
|
326
|
+
constructor(options) {
|
|
327
|
+
this.api = new BrainBoxApiClient(options.apiUrl, options.apiKey, noopLogger);
|
|
328
|
+
}
|
|
329
|
+
/** Health-check: resolves if the API is reachable. */
|
|
330
|
+
async ping() {
|
|
331
|
+
await this.api.ping();
|
|
332
|
+
}
|
|
333
|
+
/**
|
|
334
|
+
* Resolve a project name/slug to its internal cuid2 project ID.
|
|
335
|
+
* The API key is org-scoped, so the org is derived automatically.
|
|
336
|
+
*/
|
|
337
|
+
async resolveProjectId(projectName, org) {
|
|
338
|
+
return this.api.resolveProjectId(projectName, org);
|
|
339
|
+
}
|
|
340
|
+
/** Create a project in the key's org. Requires a write-scoped org/project key. */
|
|
341
|
+
async createProject(name, org) {
|
|
342
|
+
const resolved = await this.api.resolveOrg(org);
|
|
343
|
+
try {
|
|
344
|
+
return await this.api.createProject(resolved.id, name);
|
|
345
|
+
} catch (err) {
|
|
346
|
+
const msg = err instanceof Error ? err.message : "";
|
|
347
|
+
if (/\bAPI 409\b/.test(msg)) {
|
|
348
|
+
const id = /"conflictingId"\s*:\s*"([^"]+)"/.exec(msg)?.[1];
|
|
349
|
+
throw new Error(`[BrainBox] Cannot create project "${name}": it conflicts with an existing project${id ? ` (${id})` : ""}.`);
|
|
350
|
+
}
|
|
351
|
+
throw err;
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
};
|
|
355
|
+
|
|
356
|
+
// src/tenant.ts
|
|
357
|
+
var TENANT_KEY_PREFIX = "bb_tenant_";
|
|
358
|
+
function isTenantKey(apiKey) {
|
|
359
|
+
return apiKey.startsWith(TENANT_KEY_PREFIX);
|
|
360
|
+
}
|
|
361
|
+
async function discoverProjectsView(apiUrl, apiKey) {
|
|
362
|
+
const url = `${apiUrl.replace(/\/+$/, "")}/api/projects`;
|
|
363
|
+
const res = await globalThis.fetch(url, {
|
|
364
|
+
headers: { Authorization: `Bearer ${apiKey}` }
|
|
365
|
+
});
|
|
366
|
+
if (!res.ok) {
|
|
367
|
+
throw new Error(`[BrainBox] Project discovery ${res.status}: ${await res.text()}`);
|
|
368
|
+
}
|
|
369
|
+
const contentType = res.headers.get("content-type") ?? "";
|
|
370
|
+
if (!contentType.includes("application/json")) {
|
|
371
|
+
throw new Error(`[BrainBox] Project discovery returned non-JSON response (${contentType}) from ${url}`);
|
|
372
|
+
}
|
|
373
|
+
const body = await res.json();
|
|
374
|
+
if (!Array.isArray(body.projects)) {
|
|
375
|
+
throw new Error(`[BrainBox] Project discovery response from ${url} has no \`projects\` array`);
|
|
376
|
+
}
|
|
377
|
+
return { projects: body.projects, disabledTools: body.disabledTools ?? [] };
|
|
378
|
+
}
|
|
379
|
+
async function discoverProjects(apiUrl, apiKey) {
|
|
380
|
+
return (await discoverProjectsView(apiUrl, apiKey)).projects;
|
|
381
|
+
}
|
|
382
|
+
async function discoverTenantView(apiUrl, apiKey) {
|
|
383
|
+
return tenantViewFrom(await discoverProjects(apiUrl, apiKey));
|
|
384
|
+
}
|
|
385
|
+
function tenantViewFrom(projects) {
|
|
386
|
+
const overlay = projects.find((p) => p.role === "overlay");
|
|
387
|
+
if (!overlay) {
|
|
388
|
+
throw new Error(
|
|
389
|
+
"[BrainBox] Tenant key resolved to no overlay project. This should not happen for a valid bb_tenant_ key."
|
|
390
|
+
);
|
|
391
|
+
}
|
|
392
|
+
const bases = projects.filter((p) => p.role === "base");
|
|
393
|
+
return { overlay, bases };
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
// src/serve/mcp.ts
|
|
397
|
+
var requestStore = new AsyncLocalStorage();
|
|
398
|
+
var MCP = class {
|
|
399
|
+
middlewares = [];
|
|
400
|
+
overrides = /* @__PURE__ */ new Map();
|
|
401
|
+
disabled = /* @__PURE__ */ new Set();
|
|
402
|
+
syncCallbacks = [];
|
|
403
|
+
sqlClient;
|
|
404
|
+
customExecutor;
|
|
405
|
+
opts;
|
|
406
|
+
// Set in start() after project slug is resolved to a cuid2 ID.
|
|
407
|
+
sync;
|
|
408
|
+
brainExecutor;
|
|
409
|
+
constructor(options) {
|
|
410
|
+
this.opts = {
|
|
411
|
+
apiUrl: "https://ctx.brainbox-ai.app",
|
|
412
|
+
serveUnimplementedTools: false,
|
|
413
|
+
brain: true,
|
|
414
|
+
...options
|
|
415
|
+
};
|
|
416
|
+
this.sqlClient = this.opts.connectors?.sql?.url ? new SqlExecutor(this.opts.connectors.sql.url) : new NoopSqlClient();
|
|
417
|
+
this.customExecutor = this.opts.connectors?.custom?.execute;
|
|
418
|
+
}
|
|
419
|
+
/** Register middleware that runs before every tool call. */
|
|
420
|
+
use(fn) {
|
|
421
|
+
this.middlewares.push(fn);
|
|
422
|
+
return this;
|
|
423
|
+
}
|
|
424
|
+
/** Register a custom or enhanced tool handler. */
|
|
425
|
+
tool(name, fn) {
|
|
426
|
+
this.overrides.set(name, fn);
|
|
427
|
+
return this;
|
|
428
|
+
}
|
|
429
|
+
/** Explicitly exclude a tool from the MCP server (won't appear in tools/list). */
|
|
430
|
+
disable(name) {
|
|
431
|
+
this.disabled.add(name);
|
|
432
|
+
return this;
|
|
433
|
+
}
|
|
434
|
+
/** Register a callback fired when tool definitions are refreshed. */
|
|
435
|
+
onSync(fn) {
|
|
436
|
+
this.syncCallbacks.push(fn);
|
|
437
|
+
return this;
|
|
438
|
+
}
|
|
439
|
+
/** Fetch tool definitions and start the MCP server. */
|
|
440
|
+
async start(opts = {}) {
|
|
441
|
+
const port = opts.port ?? 3100;
|
|
442
|
+
const baseUrl = this.opts.apiUrl.replace(/\/+$/, "");
|
|
443
|
+
if (isTenantKey(this.opts.apiKey)) {
|
|
444
|
+
const view = await discoverTenantView(baseUrl, this.opts.apiKey);
|
|
445
|
+
this.sync = new SyncEngine({
|
|
446
|
+
apiUrl: this.opts.apiUrl,
|
|
447
|
+
apiKey: this.opts.apiKey,
|
|
448
|
+
projects: [view.overlay, ...view.bases],
|
|
449
|
+
pollIntervalMs: this.opts.pollIntervalMs
|
|
450
|
+
});
|
|
451
|
+
this.brainExecutor = createTenantBrainExecutor(this.opts.apiUrl, this.opts.apiKey, view);
|
|
452
|
+
} else {
|
|
453
|
+
if (!this.opts.project) {
|
|
454
|
+
throw new Error("[BrainBox] MCP requires `project` unless using a tenant key.");
|
|
455
|
+
}
|
|
456
|
+
const client = new BrainBoxClient({ apiUrl: baseUrl, apiKey: this.opts.apiKey });
|
|
457
|
+
const isCuid2 = /^[a-z][a-z0-9]{23}$/.test(this.opts.project);
|
|
458
|
+
const projectId = isCuid2 ? this.opts.project : await client.resolveProjectId(this.opts.project);
|
|
459
|
+
this.sync = new SyncEngine({
|
|
460
|
+
apiUrl: this.opts.apiUrl,
|
|
461
|
+
apiKey: this.opts.apiKey,
|
|
462
|
+
projectId,
|
|
463
|
+
pollIntervalMs: this.opts.pollIntervalMs
|
|
464
|
+
});
|
|
465
|
+
this.brainExecutor = createBrainExecutor(this.opts.apiUrl, this.opts.apiKey, projectId);
|
|
466
|
+
}
|
|
467
|
+
this.sync.onUpdate((tools) => {
|
|
468
|
+
this.syncCallbacks.forEach((fn) => fn(tools));
|
|
469
|
+
this.logStartupTable();
|
|
470
|
+
});
|
|
471
|
+
await this.sync.start();
|
|
472
|
+
this.logStartupTable();
|
|
473
|
+
const app = express();
|
|
474
|
+
app.use(express.json());
|
|
475
|
+
app.all("/mcp", async (req, res, next) => {
|
|
476
|
+
try {
|
|
477
|
+
await requestStore.run({ headers: req.headers }, async () => {
|
|
478
|
+
const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: void 0 });
|
|
479
|
+
const server = buildMcpServer({
|
|
480
|
+
tools: this.activeTools(),
|
|
481
|
+
middlewares: this.middlewares,
|
|
482
|
+
overrides: this.overrides,
|
|
483
|
+
sqlClient: this.sqlClient,
|
|
484
|
+
customExecutor: this.customExecutor,
|
|
485
|
+
brainExecutor: this.brainExecutor,
|
|
486
|
+
requestStore
|
|
487
|
+
});
|
|
488
|
+
await server.connect(transport);
|
|
489
|
+
await transport.handleRequest(req, res, req.body);
|
|
490
|
+
});
|
|
491
|
+
} catch (err) {
|
|
492
|
+
next(err);
|
|
493
|
+
}
|
|
494
|
+
});
|
|
495
|
+
await new Promise((resolve) => {
|
|
496
|
+
app.listen(port, () => {
|
|
497
|
+
console.log(`[BrainBox] MCP server ready \u2192 http://localhost:${port}/mcp`);
|
|
498
|
+
resolve();
|
|
499
|
+
});
|
|
500
|
+
});
|
|
501
|
+
}
|
|
502
|
+
activeTools() {
|
|
503
|
+
return this.sync.getTools().filter((tool) => {
|
|
504
|
+
if (this.disabled.has(tool.name)) return false;
|
|
505
|
+
if (tool.execution.type === "brain" && !this.opts.brain) return false;
|
|
506
|
+
if (tool.implementationType === "custom" && !this.overrides.has(tool.name)) {
|
|
507
|
+
return this.opts.serveUnimplementedTools;
|
|
508
|
+
}
|
|
509
|
+
return true;
|
|
510
|
+
});
|
|
511
|
+
}
|
|
512
|
+
logStartupTable() {
|
|
513
|
+
const tools = this.sync.getTools();
|
|
514
|
+
const lines = [`
|
|
515
|
+
[BrainBox] ${tools.length} tools synced
|
|
516
|
+
`];
|
|
517
|
+
for (const tool of tools) {
|
|
518
|
+
if (this.disabled.has(tool.name)) {
|
|
519
|
+
lines.push(` o ${tool.name.padEnd(40)} disabled`);
|
|
520
|
+
} else if (tool.execution.type === "brain" && !this.opts.brain) {
|
|
521
|
+
lines.push(` o ${tool.name.padEnd(40)} brain (excluded -- --no-brain)`);
|
|
522
|
+
} else if (tool.implementationType === "auto") {
|
|
523
|
+
const tier = this.overrides.has(tool.name) ? "enhanced" : `auto (${tool.execution.type})`;
|
|
524
|
+
lines.push(` + ${tool.name.padEnd(40)} ${tier}`);
|
|
525
|
+
} else if (this.overrides.has(tool.name)) {
|
|
526
|
+
lines.push(` + ${tool.name.padEnd(40)} custom (override registered)`);
|
|
527
|
+
} else if (this.opts.serveUnimplementedTools) {
|
|
528
|
+
lines.push(` ! ${tool.name.padEnd(40)} custom (no override -- will error on call)`);
|
|
529
|
+
} else {
|
|
530
|
+
lines.push(` - ${tool.name.padEnd(40)} custom (no override -- NOT serving)`);
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
console.log(lines.join("\n"));
|
|
534
|
+
}
|
|
535
|
+
};
|
|
536
|
+
|
|
537
|
+
export {
|
|
538
|
+
BrainBoxClient,
|
|
539
|
+
isTenantKey,
|
|
540
|
+
discoverProjectsView,
|
|
541
|
+
tenantViewFrom,
|
|
542
|
+
MCP,
|
|
543
|
+
serve_exports
|
|
544
|
+
};
|