@brainbox-labs/sdk 0.0.0-stage → 0.22.1
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 +56 -0
- package/dist/chunk-43LDD7YT.js +139 -0
- package/dist/chunk-AJR44IFE.js +47 -0
- package/dist/chunk-ANGBZHCB.js +120 -0
- package/dist/chunk-MLKGABMK.js +9 -0
- package/dist/chunk-OOHPBQXX.js +152 -0
- package/dist/chunk-VEXUCOXR.js +387 -0
- package/dist/chunk-YRH35U57.js +178 -0
- package/dist/chunk-YWH6IOQG.js +650 -0
- package/dist/column-profiler-FJCAQQAS.js +23 -0
- package/dist/docs-loader-VMBVV44Y.js +9 -0
- package/dist/index-qV0gq2eJ.d.ts +148 -0
- package/dist/index.d.ts +387 -0
- package/dist/index.js +507 -0
- package/dist/ingest/public.d.ts +182 -0
- package/dist/ingest/public.js +63 -0
- package/dist/ingest-OA6KWJNR.js +9 -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 +7 -0
- package/dist/sql-parser-TB26PFXS.js +198 -0
- package/dist/trino-TUQ7CIRM.js +13 -0
- package/package.json +79 -4
package/README.md
CHANGED
|
@@ -1,3 +1,347 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @brainbox-labs/sdk
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
BrainBox JavaScript/TypeScript SDK — ingest data into your brain, query it programmatically, and serve it as a local MCP server.
|
|
4
|
+
|
|
5
|
+
## Quick start
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install @brainbox-labs/sdk
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## The `BrainBox` root
|
|
12
|
+
|
|
13
|
+
Everything starts from a `BrainBox` handle:
|
|
14
|
+
|
|
15
|
+
```typescript
|
|
16
|
+
import { BrainBox } from '@brainbox-labs/sdk';
|
|
17
|
+
|
|
18
|
+
const brain = new BrainBox({
|
|
19
|
+
apiKey: process.env.BRAINBOX_API_KEY!,
|
|
20
|
+
org: 'my-org',
|
|
21
|
+
project: 'my-project', // slug or cuid2 ID
|
|
22
|
+
});
|
|
23
|
+
```
|
|
24
|
+
|
|
25
|
+
The handle exposes three verb namespaces — `brain.ingest`, `brain.recall`, `brain.update` — plus a server builder at `brain.serve`.
|
|
26
|
+
|
|
27
|
+
---
|
|
28
|
+
|
|
29
|
+
## `brain.ingest` — ingest sources
|
|
30
|
+
|
|
31
|
+
One call to ingest a Postgres schema, SQL files, docs, and free-form text. Blocks until each stage is activated and a new version is published.
|
|
32
|
+
|
|
33
|
+
```typescript
|
|
34
|
+
const result = await brain.ingest({
|
|
35
|
+
postgres: { connectionString: process.env.DATABASE_URL! },
|
|
36
|
+
sql: ['./sql/reports'], // SQL files or directories
|
|
37
|
+
docs: ['./docs/**/*.md'], // glob patterns
|
|
38
|
+
text: 'ARR excludes professional services fees.',
|
|
39
|
+
message: 'Q2 reports + finance docs',
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
console.log(result.stages); // [{ kind: 'sql', version: 4 }, { kind: 'docs', version: 5 }]
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
### `IngestOptions`
|
|
46
|
+
|
|
47
|
+
| Option | Type | Description |
|
|
48
|
+
| --- | --- | --- |
|
|
49
|
+
| `postgres` | `{ connectionString, tables?, dialect? }` | Postgres schema to introspect. `tables` restricts to named tables; `dialect` overrides the SQL dialect tag sent to the server (default: `'postgres'`). |
|
|
50
|
+
| `trino` | `{ connectionString, tables?, dialect? }` | Trino schema to introspect (`trino://user[:password]@host[:port]/catalog[/schema]`). Mutually exclusive with `postgres` and `athena`; no enforced PKs/FKs/indexes. Requires the optional `trino-client` dependency. |
|
|
51
|
+
| `athena` | `{ connectionString, tables?, dialect? }` | AWS Athena schema to introspect (`athena://region/database[?catalog=&workgroup=&output=&pollTimeoutMs=]`). AWS credentials come from the standard AWS SDK credential chain, not the URL. `pollTimeoutMs` (default 300 000) bounds how long a query is polled before failing with a clear error, instead of hanging indefinitely. Mutually exclusive with `postgres` and `trino`; no enforced PKs/FKs/indexes. Requires the optional `@aws-sdk/client-athena` dependency. |
|
|
52
|
+
| `sql` | `string[]` | SQL file paths / directories (requires `postgres`, `trino`, or `athena`) |
|
|
53
|
+
| `docs` | `string[]` | Glob patterns matching `.md`, `.txt`, `.html` files. `.pdf` and `.docx` are auto-converted to markdown (requires `mammoth` and `pdf-parse` optional deps). |
|
|
54
|
+
| `text` | `string` | Inline text snippet attached as a document |
|
|
55
|
+
| `profile` | `{ mode, sampleRows?, skipColumns? }` | Profile column data from the database. `mode: 'cardinality'` collects distinctCount, nullRate, numeric/string stats. `mode: 'full'` also collects enum values and JSON key shapes. Supports Postgres, MySQL, SQLite, DuckDB, Trino, and Athena. |
|
|
56
|
+
| `message` | `string` | Description of the ingest (reserved for future use) |
|
|
57
|
+
| `timeoutMs` | `number` | Per-stage poll timeout (default: 300 000 ms) |
|
|
58
|
+
| `reviewOnly` | `boolean` | Stop after context is ready — skip activation for curation |
|
|
59
|
+
| `force` | `boolean` | Re-process the last connector draft instead of uploading sources again |
|
|
60
|
+
|
|
61
|
+
### Partial failures
|
|
62
|
+
|
|
63
|
+
If a later stage fails after an earlier one has already activated, an `IngestPartialFailureError` is thrown carrying the completed stages:
|
|
64
|
+
|
|
65
|
+
```typescript
|
|
66
|
+
import { IngestPartialFailureError } from '@brainbox-labs/sdk';
|
|
67
|
+
|
|
68
|
+
try {
|
|
69
|
+
await brain.ingest({ postgres: { connectionString }, docs: ['./docs'] });
|
|
70
|
+
} catch (err) {
|
|
71
|
+
if (err instanceof IngestPartialFailureError) {
|
|
72
|
+
console.log('completed:', err.completed); // stages that already shipped
|
|
73
|
+
console.log('failed stage:', err.failedKind);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
---
|
|
79
|
+
|
|
80
|
+
## `brain.recall` — read the brain
|
|
81
|
+
|
|
82
|
+
Read verbs that map 1:1 to the hosted BrainBox MCP tools:
|
|
83
|
+
|
|
84
|
+
```typescript
|
|
85
|
+
const index = await brain.recall.get_index();
|
|
86
|
+
const recent = await brain.recall.get_recent_changes();
|
|
87
|
+
const learn = await brain.recall.list_learnings();
|
|
88
|
+
|
|
89
|
+
const domain = await brain.recall.recall_domain({ query: 'orders' });
|
|
90
|
+
const traces = await brain.recall.recall_traces({ entity: 'order', limit: 5 });
|
|
91
|
+
const wiki = await brain.recall.recall_wiki({ q: 'returns policy' }); // each hit carries matchedPassage
|
|
92
|
+
|
|
93
|
+
const trace = await brain.recall.get_trace({ id: 'trc_abc' });
|
|
94
|
+
const page = await brain.recall.get_wiki_page({ id: 'wiki_xyz' });
|
|
95
|
+
|
|
96
|
+
const brief = await brain.recall.research_task({
|
|
97
|
+
question: 'Why did returns spike last week?',
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
// Enumerate without searching — list_* return summaries, get_* fetch one item
|
|
101
|
+
const pages = await brain.recall.list_wiki_pages({ namespace: 'acme', kind: 'runbook', limit: 50 });
|
|
102
|
+
const recentT = await brain.recall.list_traces({ team: 'support', since: '2026-10-01' });
|
|
103
|
+
const hits = await brain.recall.grep_wiki({ pattern: 'refund window', contextLines: 2 });
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
`grep_wiki` runs **client-side**: the SDK pages through `list_wiki_pages` (cursor + `includeBody`, 20 pages per call, one kind at a time) and matches each body locally. It works for every org and does not use the server's opt-in `grep_wiki` tool. The server's list cursor goes about 1000 pages deep per kind; the result carries `pagesTruncated: true` if a kind reaches that — narrow with `tag`, `namespace` or `kind`.
|
|
107
|
+
|
|
108
|
+
### Agent loop
|
|
109
|
+
|
|
110
|
+
`.asTools()` returns an array of `VerbTool` objects — each has a standard MCP-format `inputSchema` plus a bound `execute` method — so the array drops straight into any agent framework:
|
|
111
|
+
|
|
112
|
+
```typescript
|
|
113
|
+
const tools = [...brain.recall.asTools(), ...brain.update.asTools()];
|
|
114
|
+
|
|
115
|
+
// Or hide tools this org has switched off (e.g. save_domain), so the model never picks one that would 403:
|
|
116
|
+
const enabled = [...await brain.recall.asEnabledTools(), ...await brain.update.asEnabledTools()];
|
|
117
|
+
|
|
118
|
+
// With the Anthropic SDK:
|
|
119
|
+
const response = await anthropic.messages.create({ tools, ... });
|
|
120
|
+
for (const block of response.content) {
|
|
121
|
+
if (block.type === 'tool_use') {
|
|
122
|
+
const tool = tools.find(t => t.name === block.name)!;
|
|
123
|
+
const result = await tool.execute(block.input);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
---
|
|
129
|
+
|
|
130
|
+
## `brain.update` — write to the brain
|
|
131
|
+
|
|
132
|
+
Write verbs for saving learnings and processing events (plus skills, wiki pages, and personal pages — see `brain.ts`'s `BrainUpdate` type for the full list):
|
|
133
|
+
|
|
134
|
+
```typescript
|
|
135
|
+
await brain.update.create_learning({
|
|
136
|
+
rule: 'Returns over 30 days are written off, not refunded.',
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
await brain.update.process_event({
|
|
140
|
+
text: '...',
|
|
141
|
+
eventType: 'meeting',
|
|
142
|
+
source: { externalId: 'granola:abc123' },
|
|
143
|
+
});
|
|
144
|
+
// source.externalId is the idempotency key. A concurrent duplicate gets a 409, thrown as
|
|
145
|
+
// BrainDispatchError { code: 'CONFLICT', retryable: true }: back off and retry.
|
|
146
|
+
|
|
147
|
+
// Create a skill, or replace an existing one's body as the next version
|
|
148
|
+
const skill = await brain.update.create_skill({
|
|
149
|
+
name: 'reconcile-invoices',
|
|
150
|
+
description: 'How to reconcile invoices',
|
|
151
|
+
sources: [{ name: 'steps', content: '...' }],
|
|
152
|
+
onConflict: 'update', // default 'error'
|
|
153
|
+
});
|
|
154
|
+
// skill.outcome is 'created' | 'updated'; skill.version is the new version
|
|
155
|
+
|
|
156
|
+
// Retire a learning that is no longer true, append to a wiki page without
|
|
157
|
+
// rewriting it, and tell the brain what it was missing
|
|
158
|
+
await brain.update.retire_learning({ learningId: 'lrn_abc', reason: 'Policy changed Q3' });
|
|
159
|
+
await brain.update.save_wiki_page({ mode: 'append', id: 'wiki_xyz', body: '- 2026-10-20: ...' });
|
|
160
|
+
await brain.update.report_context_gap({ need: 'EU refund policy', kind: 'missing' });
|
|
161
|
+
|
|
162
|
+
// Flag a personal page for admin review without changing its content
|
|
163
|
+
await brain.update.save_personal_page({ id: 'pp_abc', flagForReview: true, userId: 'u_123' });
|
|
164
|
+
|
|
165
|
+
// Delete a synthesis wiki page or a trace. Soft: hidden from every read at once,
|
|
166
|
+
// purged after 7 days unless a person restores it from the dashboard
|
|
167
|
+
const res = await brain.update.archive_wiki_page({ pageId: 'wp_abc', reason: 'Duplicate of wp_def' });
|
|
168
|
+
await brain.update.archive_trace({ traceId: 'tr_abc', reason: 'Recorded in error' });
|
|
169
|
+
// res.status is 'pending_deletion'; res.purgeAfter is the ISO purge time
|
|
170
|
+
```
|
|
171
|
+
|
|
172
|
+
The archive tools are off unless an org admin turns on **Agent deletion tools** (`agentArchiveTools`); until then the server refuses them and `asEnabledTools()` leaves them out. Only `kind: 'synthesis'` pages can be archived this way.
|
|
173
|
+
|
|
174
|
+
`append_wiki_page` and `flag_personal_page_for_review` still work but are deprecated: the SDK rewrites them to the two calls above, and `asTools()` no longer lists them.
|
|
175
|
+
|
|
176
|
+
Every non-2xx response throws `BrainDispatchError` with `status`, `code` (the server's code when it sends one, e.g. `VERSION_CONFLICT`), `details` (the parsed JSON body), `retryable` and `retryAfter` (seconds, from the Retry-After header). `retryable` is true for 429, 502, 503, 504 and the `process_event` in-flight 409. Other 409s are not retryable as-is: a `VERSION_CONFLICT` from `save_wiki_page` means re-read the page and retry with `baseVersion: err.details.currentVersion`.
|
|
177
|
+
|
|
178
|
+
```typescript
|
|
179
|
+
import { BrainDispatchError } from '@brainbox-labs/sdk';
|
|
180
|
+
|
|
181
|
+
try {
|
|
182
|
+
await brain.update.process_event({ text: '...', source: { externalId: 'granola:abc123' } });
|
|
183
|
+
} catch (err) {
|
|
184
|
+
if (err instanceof BrainDispatchError && err.retryable) { /* wait err.retryAfter ?? a backoff, then retry */ }
|
|
185
|
+
else throw err;
|
|
186
|
+
}
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
`save_domain` is available over the SDK too (`brain.update.save_domain`), not just MCP.
|
|
190
|
+
|
|
191
|
+
---
|
|
192
|
+
|
|
193
|
+
## `brain.projects` — list and create projects
|
|
194
|
+
|
|
195
|
+
Org-level, so no `project` is needed on the handle. `list()` works for every key type and returns role-tagged `{ projectId, name, role, description?, aliases? }`. `create()` needs a write-scoped org or project key; tenant keys are refused (the server answers 409), and a name clash gives a readable error with the conflicting id.
|
|
196
|
+
|
|
197
|
+
```typescript
|
|
198
|
+
const brain = new BrainBox({ apiKey: process.env.BRAINBOX_API_KEY!, org: 'acme' });
|
|
199
|
+
|
|
200
|
+
const projects = await brain.projects.list();
|
|
201
|
+
const created = await brain.projects.create('support-brain');
|
|
202
|
+
```
|
|
203
|
+
|
|
204
|
+
Renaming/deleting projects and all tenant management (create, list, keys, suspend) are admin-tier on the server and not reachable with an API key.
|
|
205
|
+
|
|
206
|
+
---
|
|
207
|
+
|
|
208
|
+
## `brain.serve` — MCP server builder
|
|
209
|
+
|
|
210
|
+
Build and start a local MCP server (Streamable HTTP) serving your approved tools:
|
|
211
|
+
|
|
212
|
+
```typescript
|
|
213
|
+
const mcp = brain.serve.mcp({
|
|
214
|
+
connectors: { sql: { url: process.env.DATABASE_URL! } },
|
|
215
|
+
});
|
|
216
|
+
|
|
217
|
+
// Middleware: runs before every tool call
|
|
218
|
+
mcp.use(async (ctx, next) => {
|
|
219
|
+
const user = await verifyToken(ctx.headers['authorization']);
|
|
220
|
+
ctx.tenantId = user.tenantId;
|
|
221
|
+
await next();
|
|
222
|
+
});
|
|
223
|
+
|
|
224
|
+
// Enhanced tier: wrap the approved SQL with a tenant filter
|
|
225
|
+
mcp.tool('get_overdue_invoices', async (params, ctx) => {
|
|
226
|
+
return ctx.sql.query(
|
|
227
|
+
`${ctx.defaultQuery} AND tenant_id = $1`,
|
|
228
|
+
[...Object.values(params), ctx.tenantId],
|
|
229
|
+
);
|
|
230
|
+
});
|
|
231
|
+
|
|
232
|
+
// Custom tier: full implementation (tool shape defined in BrainBox UI)
|
|
233
|
+
mcp.tool('create_reconciliation_exception', async (params, ctx) => {
|
|
234
|
+
const [row] = await ctx.sql.query(
|
|
235
|
+
'INSERT INTO recon_exceptions (amount, tenant_id) VALUES ($1, $2) RETURNING id',
|
|
236
|
+
[params.amount, ctx.tenantId],
|
|
237
|
+
);
|
|
238
|
+
return row;
|
|
239
|
+
});
|
|
240
|
+
|
|
241
|
+
await mcp.start({ port: 3100 });
|
|
242
|
+
// → MCP server ready at http://localhost:3100/mcp
|
|
243
|
+
```
|
|
244
|
+
|
|
245
|
+
### Tool execution tiers
|
|
246
|
+
|
|
247
|
+
| Tier | Developer effort | Behavior |
|
|
248
|
+
| --- | --- | --- |
|
|
249
|
+
| **Auto** | Nothing | SDK runs the approved SQL via the `sql` connector |
|
|
250
|
+
| **Enhanced** | `mcp.tool('name', fn)` on an auto tool | `ctx.defaultQuery` holds the approved SQL; developer wraps it |
|
|
251
|
+
| **Custom** | `mcp.tool('name', fn)` on a custom tool | Full implementation — tool shape is defined in BrainBox UI |
|
|
252
|
+
| **Disabled** | `mcp.disable('name')` | Tool excluded from MCP server entirely |
|
|
253
|
+
|
|
254
|
+
Custom tools without an override are silently excluded by default. Set `serveUnimplementedTools: true` to register them with a clear error on call.
|
|
255
|
+
|
|
256
|
+
### `ToolContext`
|
|
257
|
+
|
|
258
|
+
Every middleware and tool handler receives a `ToolContext`:
|
|
259
|
+
|
|
260
|
+
```typescript
|
|
261
|
+
interface ToolContext {
|
|
262
|
+
sql: SqlClient; // ctx.sql.query(sql, params)
|
|
263
|
+
defaultQuery?: string; // Approved SQL — available on auto-tier tools
|
|
264
|
+
toolName: string;
|
|
265
|
+
headers: Record<string, string | string[] | undefined>;
|
|
266
|
+
[key: string]: unknown; // Middleware can attach arbitrary fields (ctx.user, ctx.tenantId, …)
|
|
267
|
+
}
|
|
268
|
+
```
|
|
269
|
+
|
|
270
|
+
### Zero-code MCP server
|
|
271
|
+
|
|
272
|
+
No custom logic? Run the binary directly:
|
|
273
|
+
|
|
274
|
+
```bash
|
|
275
|
+
BRAINBOX_API_KEY=bb_xxx \
|
|
276
|
+
BRAINBOX_PROJECT=my-project \
|
|
277
|
+
DATABASE_URL=postgres://localhost:5432/mydb \
|
|
278
|
+
npx -y -p @brainbox-labs/sdk brainbox-mcp
|
|
279
|
+
# → MCP server ready at http://localhost:3100/mcp
|
|
280
|
+
```
|
|
281
|
+
|
|
282
|
+
### Claude Desktop config
|
|
283
|
+
|
|
284
|
+
```json
|
|
285
|
+
{
|
|
286
|
+
"mcpServers": {
|
|
287
|
+
"my-project": {
|
|
288
|
+
"command": "npx",
|
|
289
|
+
"args": ["brainbox-mcp"],
|
|
290
|
+
"env": {
|
|
291
|
+
"BRAINBOX_API_KEY": "bb_xxx",
|
|
292
|
+
"BRAINBOX_PROJECT": "my-project",
|
|
293
|
+
"DATABASE_URL": "postgres://localhost:5432/mydb"
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
```
|
|
299
|
+
|
|
300
|
+
---
|
|
301
|
+
|
|
302
|
+
## `BrainBox` options
|
|
303
|
+
|
|
304
|
+
```typescript
|
|
305
|
+
new BrainBox({
|
|
306
|
+
apiKey: string; // BrainBox API key (bb_...)
|
|
307
|
+
org: string; // Organisation slug
|
|
308
|
+
project?: string; // Project (brain) slug or cuid2 ID — required for ingest/recall/update/serve
|
|
309
|
+
apiUrl?: string; // Defaults to https://ctx.brainbox-ai.app
|
|
310
|
+
})
|
|
311
|
+
```
|
|
312
|
+
|
|
313
|
+
---
|
|
314
|
+
|
|
315
|
+
## Architecture
|
|
316
|
+
|
|
317
|
+
```text
|
|
318
|
+
src/
|
|
319
|
+
brain.ts — BrainBox root: ingest, recall, update, serve namespaces
|
|
320
|
+
verb-namespace.ts — buildVerbNamespace(): VerbHandler + asTools()
|
|
321
|
+
client.ts — BrainBoxClient (REST API access)
|
|
322
|
+
index.ts — public exports
|
|
323
|
+
ingest/
|
|
324
|
+
index.ts — performIngest(): stages pipeline
|
|
325
|
+
introspect.ts — schema-introspection dispatcher (routes by URL scheme / explicit dialect)
|
|
326
|
+
schema-reader.ts — Postgres introspection (pg)
|
|
327
|
+
trino.ts — Trino introspection + connection (trino-client — optional dep)
|
|
328
|
+
athena.ts — Athena introspection + connection (@aws-sdk/client-athena — optional dep)
|
|
329
|
+
sql-parser.ts — SQL file parsing (pgsql-ast-parser)
|
|
330
|
+
docs-loader.ts — glob + inline text expansion; routes pdf/docx through doc-converter
|
|
331
|
+
column-profiler.ts — column statistics engine (Postgres, MySQL, SQLite, DuckDB, Trino, Athena)
|
|
332
|
+
doc-converter.ts — PDF/DOCX/HTML → markdown (mammoth, pdf-parse, turndown — optional deps)
|
|
333
|
+
public.ts — @brainbox-labs/sdk/ingest subpath re-exports
|
|
334
|
+
serve/
|
|
335
|
+
mcp.ts — MCP public class (use(), tool(), disable(), start())
|
|
336
|
+
sync.ts — SyncEngine: fetches tool definitions from BrainBox API
|
|
337
|
+
server.ts — MCP Server builder (@modelcontextprotocol/sdk)
|
|
338
|
+
dispatch.ts — Tool dispatcher: override > auto-sql > error
|
|
339
|
+
middleware.ts — runMiddlewareChain() (Koa-style next())
|
|
340
|
+
connectors/
|
|
341
|
+
sql.ts — SqlExecutor (pg.Pool) + NoopSqlClient
|
|
342
|
+
brain.ts — BrainExecutor (dispatch endpoint)
|
|
343
|
+
types.ts — ContextTool, SqlClient, ToolContext, MiddlewareFn, ToolHandlerFn
|
|
344
|
+
bin.ts — CLI entrypoint (brainbox-mcp binary)
|
|
345
|
+
```
|
|
346
|
+
|
|
347
|
+
The MCP server runs entirely in the developer's infrastructure. BrainBox never receives database credentials or query results.
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import {
|
|
2
|
+
introspectAthenaSchema,
|
|
3
|
+
introspectAthenaSchemaWithConnection,
|
|
4
|
+
openAthenaConnection,
|
|
5
|
+
parseAthenaUrl
|
|
6
|
+
} from "./chunk-YRH35U57.js";
|
|
7
|
+
import "./chunk-MLKGABMK.js";
|
|
8
|
+
export {
|
|
9
|
+
introspectAthenaSchema,
|
|
10
|
+
introspectAthenaSchemaWithConnection,
|
|
11
|
+
openAthenaConnection,
|
|
12
|
+
parseAthenaUrl
|
|
13
|
+
};
|
package/dist/bin.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
package/dist/bin.js
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {
|
|
3
|
+
MCP
|
|
4
|
+
} from "./chunk-YWH6IOQG.js";
|
|
5
|
+
import "./chunk-MLKGABMK.js";
|
|
6
|
+
|
|
7
|
+
// src/bin.ts
|
|
8
|
+
import { parse } from "dotenv";
|
|
9
|
+
import { readFileSync } from "fs";
|
|
10
|
+
function loadEnvFiles() {
|
|
11
|
+
const load = (path) => {
|
|
12
|
+
try {
|
|
13
|
+
return parse(readFileSync(path, "utf-8"));
|
|
14
|
+
} catch {
|
|
15
|
+
return {};
|
|
16
|
+
}
|
|
17
|
+
};
|
|
18
|
+
const merged = { ...load(".env"), ...load(".env.local") };
|
|
19
|
+
for (const [k, v] of Object.entries(merged)) {
|
|
20
|
+
if (!(k in process.env)) process.env[k] = v;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
loadEnvFiles();
|
|
24
|
+
function env(name, required = false) {
|
|
25
|
+
const val = process.env[name];
|
|
26
|
+
if (required && !val) {
|
|
27
|
+
console.error(`[BrainBox] Error: ${name} environment variable is required.`);
|
|
28
|
+
process.exit(1);
|
|
29
|
+
}
|
|
30
|
+
return val;
|
|
31
|
+
}
|
|
32
|
+
var apiKey = env("BRAINBOX_API_KEY", true);
|
|
33
|
+
var project = env("BRAINBOX_PROJECT", true);
|
|
34
|
+
var apiUrl = env("BRAINBOX_API_URL") ?? "https://ctx.brainbox-ai.app";
|
|
35
|
+
var sqlUrl = env("DATABASE_URL");
|
|
36
|
+
var noBrain = env("BRAINBOX_NO_BRAIN") === "true";
|
|
37
|
+
var port = process.env["PORT"] ? parseInt(process.env["PORT"], 10) : 3100;
|
|
38
|
+
var keyPreview = `${apiKey.slice(0, 10)}...${apiKey.slice(-4)}`;
|
|
39
|
+
console.log("[BrainBox] Starting with config:");
|
|
40
|
+
console.log(` api url : ${apiUrl}`);
|
|
41
|
+
console.log(` project : ${project}`);
|
|
42
|
+
console.log(` api key : ${keyPreview}`);
|
|
43
|
+
console.log(` sql : ${sqlUrl ? "configured" : "none"}`);
|
|
44
|
+
console.log(` brain : ${noBrain ? "off" : "on"}`);
|
|
45
|
+
console.log(` port : ${port}`);
|
|
46
|
+
var mcp = new MCP({
|
|
47
|
+
apiKey,
|
|
48
|
+
project,
|
|
49
|
+
apiUrl,
|
|
50
|
+
connectors: sqlUrl ? { sql: { url: sqlUrl } } : void 0,
|
|
51
|
+
brain: !noBrain
|
|
52
|
+
});
|
|
53
|
+
mcp.start({ port }).catch((err) => {
|
|
54
|
+
console.error("[BrainBox] Failed to start:", err);
|
|
55
|
+
process.exit(1);
|
|
56
|
+
});
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
// src/ingest/trino.ts
|
|
2
|
+
function parseTrinoUrl(url) {
|
|
3
|
+
let u;
|
|
4
|
+
try {
|
|
5
|
+
u = new URL(url);
|
|
6
|
+
} catch {
|
|
7
|
+
throw new Error("[BrainBox] Invalid Trino connection URL \u2014 expected trino://user[:password]@host[:port]/catalog[/schema].");
|
|
8
|
+
}
|
|
9
|
+
const scheme = u.protocol.replace(/:$/, "").toLowerCase();
|
|
10
|
+
if (scheme !== "trino" && scheme !== "trino+https" && scheme !== "trino+http") {
|
|
11
|
+
throw new Error(`[BrainBox] Not a Trino connection URL (scheme "${scheme}") \u2014 expected trino://, trino+https://, or trino+http://.`);
|
|
12
|
+
}
|
|
13
|
+
const password = u.password !== "" ? decodeURIComponent(u.password) : void 0;
|
|
14
|
+
const ssl = u.searchParams.get("ssl");
|
|
15
|
+
const https = scheme === "trino+https" || ssl === "true" || scheme === "trino" && ssl !== "false" && password !== void 0;
|
|
16
|
+
const segments = u.pathname.split("/").filter((s) => s.length > 0);
|
|
17
|
+
const catalog = segments[0];
|
|
18
|
+
if (catalog === void 0) {
|
|
19
|
+
throw new Error("[BrainBox] Trino connection URL must include a catalog: trino://user@host:8080/catalog[/schema].");
|
|
20
|
+
}
|
|
21
|
+
const target = {
|
|
22
|
+
server: `${https ? "https" : "http"}://${u.hostname}:${u.port !== "" ? u.port : https ? "443" : "8080"}`,
|
|
23
|
+
catalog: decodeURIComponent(catalog),
|
|
24
|
+
user: u.username !== "" ? decodeURIComponent(u.username) : "brainbox"
|
|
25
|
+
};
|
|
26
|
+
const schema = segments[1];
|
|
27
|
+
if (schema !== void 0) target.schema = decodeURIComponent(schema);
|
|
28
|
+
if (password !== void 0) target.password = password;
|
|
29
|
+
return target;
|
|
30
|
+
}
|
|
31
|
+
async function openTrinoConnection(url) {
|
|
32
|
+
const target = parseTrinoUrl(url);
|
|
33
|
+
let mod;
|
|
34
|
+
try {
|
|
35
|
+
mod = await import("trino-client");
|
|
36
|
+
} catch {
|
|
37
|
+
throw new Error(
|
|
38
|
+
'[BrainBox] Trino support requires the optional dependency "trino-client". Install it with: npm install trino-client'
|
|
39
|
+
);
|
|
40
|
+
}
|
|
41
|
+
const client = mod.Trino.create({
|
|
42
|
+
server: target.server,
|
|
43
|
+
catalog: target.catalog,
|
|
44
|
+
...target.schema !== void 0 ? { schema: target.schema } : {},
|
|
45
|
+
auth: new mod.BasicAuth(target.user, target.password)
|
|
46
|
+
});
|
|
47
|
+
return {
|
|
48
|
+
queryRows: async (sql) => {
|
|
49
|
+
const iter = await client.query(sql);
|
|
50
|
+
const rows = [];
|
|
51
|
+
let names;
|
|
52
|
+
for await (const page of iter) {
|
|
53
|
+
if (page.error !== void 0) {
|
|
54
|
+
throw new Error(`[BrainBox] Trino query failed: ${page.error.message ?? "unknown error"}`);
|
|
55
|
+
}
|
|
56
|
+
if (names === void 0 && page.columns !== void 0) {
|
|
57
|
+
names = page.columns.map((c) => c.name);
|
|
58
|
+
}
|
|
59
|
+
if (page.data !== void 0 && names !== void 0) {
|
|
60
|
+
const colNames = names;
|
|
61
|
+
for (const values of page.data) {
|
|
62
|
+
const row = {};
|
|
63
|
+
colNames.forEach((name, i) => {
|
|
64
|
+
row[name] = values[i];
|
|
65
|
+
});
|
|
66
|
+
rows.push(row);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
return rows;
|
|
71
|
+
},
|
|
72
|
+
// trino-client is stateless HTTP — nothing to close.
|
|
73
|
+
close: async () => {
|
|
74
|
+
}
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
function escapeLiteral(value) {
|
|
78
|
+
return `'${value.replace(/'/g, "''")}'`;
|
|
79
|
+
}
|
|
80
|
+
async function introspectTrinoSchemaWithConnection(conn, schemaFilter) {
|
|
81
|
+
const schemaCond = schemaFilter !== void 0 ? ` AND table_schema = ${escapeLiteral(schemaFilter)}` : "";
|
|
82
|
+
const tableRows = await conn.queryRows(
|
|
83
|
+
`SELECT table_schema, table_name
|
|
84
|
+
FROM information_schema.tables
|
|
85
|
+
WHERE table_type = 'BASE TABLE'
|
|
86
|
+
AND table_schema <> 'information_schema'${schemaCond}
|
|
87
|
+
ORDER BY table_schema, table_name`
|
|
88
|
+
);
|
|
89
|
+
const columnRows = await conn.queryRows(
|
|
90
|
+
`SELECT table_schema, table_name, column_name, data_type, is_nullable, column_default
|
|
91
|
+
FROM information_schema.columns
|
|
92
|
+
WHERE table_schema <> 'information_schema'${schemaCond}
|
|
93
|
+
ORDER BY table_schema, table_name, ordinal_position`
|
|
94
|
+
);
|
|
95
|
+
const columnsByTable = /* @__PURE__ */ new Map();
|
|
96
|
+
for (const col of columnRows) {
|
|
97
|
+
const key = `${col.table_schema}.${col.table_name}`;
|
|
98
|
+
const column = {
|
|
99
|
+
name: col.column_name,
|
|
100
|
+
type: col.data_type,
|
|
101
|
+
nullable: col.is_nullable === "YES",
|
|
102
|
+
isPrimaryKey: false,
|
|
103
|
+
isForeignKey: false
|
|
104
|
+
};
|
|
105
|
+
if (col.column_default !== null && col.column_default !== void 0) {
|
|
106
|
+
column.defaultValue = col.column_default;
|
|
107
|
+
}
|
|
108
|
+
const existing = columnsByTable.get(key);
|
|
109
|
+
if (existing !== void 0) {
|
|
110
|
+
existing.push(column);
|
|
111
|
+
} else {
|
|
112
|
+
columnsByTable.set(key, [column]);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
const tables = tableRows.map((t) => ({
|
|
116
|
+
name: t.table_name,
|
|
117
|
+
schema: t.table_schema,
|
|
118
|
+
columns: columnsByTable.get(`${t.table_schema}.${t.table_name}`) ?? [],
|
|
119
|
+
indexes: [],
|
|
120
|
+
constraints: []
|
|
121
|
+
}));
|
|
122
|
+
return { tables, extractedAt: (/* @__PURE__ */ new Date()).toISOString() };
|
|
123
|
+
}
|
|
124
|
+
async function introspectTrinoSchema(connectionString) {
|
|
125
|
+
const target = parseTrinoUrl(connectionString);
|
|
126
|
+
const conn = await openTrinoConnection(connectionString);
|
|
127
|
+
try {
|
|
128
|
+
return await introspectTrinoSchemaWithConnection(conn, target.schema);
|
|
129
|
+
} finally {
|
|
130
|
+
await conn.close();
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
export {
|
|
135
|
+
parseTrinoUrl,
|
|
136
|
+
openTrinoConnection,
|
|
137
|
+
introspectTrinoSchemaWithConnection,
|
|
138
|
+
introspectTrinoSchema
|
|
139
|
+
};
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
// src/ingest/introspect.ts
|
|
2
|
+
var SUPPORTED_INTROSPECTION_DIALECTS = ["postgres", "trino", "athena"];
|
|
3
|
+
var INTROSPECTORS = {
|
|
4
|
+
postgres: async () => (await import("./schema-reader-4ZVTUZIX.js")).introspectSchema,
|
|
5
|
+
trino: async () => (await import("./trino-TUQ7CIRM.js")).introspectTrinoSchema,
|
|
6
|
+
athena: async () => (await import("./athena-R67AV2DO.js")).introspectAthenaSchema
|
|
7
|
+
};
|
|
8
|
+
function detectIntrospectionDialect(url) {
|
|
9
|
+
const lower = url.toLowerCase();
|
|
10
|
+
if (lower.startsWith("postgres://") || lower.startsWith("postgresql://")) return "postgres";
|
|
11
|
+
if (lower.startsWith("trino://") || lower.startsWith("trino+http")) return "trino";
|
|
12
|
+
if (lower.startsWith("athena://") || lower.startsWith("awsathena://")) return "athena";
|
|
13
|
+
return void 0;
|
|
14
|
+
}
|
|
15
|
+
var KNOWN_UNSUPPORTED = [
|
|
16
|
+
[["mysql://", "mysql2://"], "MySQL"],
|
|
17
|
+
[["sqlite:", "sqlite3:"], "SQLite"],
|
|
18
|
+
[["duckdb:", "md:"], "DuckDB"],
|
|
19
|
+
[["bigquery://"], "BigQuery"],
|
|
20
|
+
[["snowflake://"], "Snowflake"],
|
|
21
|
+
[["jdbc:awsathena"], "Athena (JDBC connection strings \u2014 use athena://region/database instead)"],
|
|
22
|
+
[["presto://"], "Presto"]
|
|
23
|
+
];
|
|
24
|
+
function unsupportedMessage(url) {
|
|
25
|
+
const supported = SUPPORTED_INTROSPECTION_DIALECTS.join(", ");
|
|
26
|
+
const lower = url.toLowerCase();
|
|
27
|
+
for (const [prefixes, label] of KNOWN_UNSUPPORTED) {
|
|
28
|
+
if (prefixes.some((p) => lower.startsWith(p))) {
|
|
29
|
+
return `[BrainBox] ${label} schema introspection is not yet supported (supported: ${supported}).`;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
return `[BrainBox] Cannot detect the database engine from the connection string (supported: ${supported}). For connection strings without a URL scheme (e.g. keyword/value Postgres format), pass the dialect explicitly.`;
|
|
33
|
+
}
|
|
34
|
+
async function introspectDatabaseSchema(connectionString, dialect) {
|
|
35
|
+
const resolved = dialect ?? detectIntrospectionDialect(connectionString);
|
|
36
|
+
if (resolved === void 0) {
|
|
37
|
+
throw new Error(unsupportedMessage(connectionString));
|
|
38
|
+
}
|
|
39
|
+
const introspect = await INTROSPECTORS[resolved]();
|
|
40
|
+
return introspect(connectionString);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export {
|
|
44
|
+
SUPPORTED_INTROSPECTION_DIALECTS,
|
|
45
|
+
detectIntrospectionDialect,
|
|
46
|
+
introspectDatabaseSchema
|
|
47
|
+
};
|