@brainbox-labs/sdk
v0.26.1
Published
BrainBox JavaScript/TypeScript SDK — MCP server + API client
Maintainers
Readme
@brainbox-labs/sdk
BrainBox JavaScript/TypeScript SDK — ingest data into your brain, query it programmatically, and serve it as a local MCP server.
Quick start
npm install @brainbox-labs/sdkThe BrainBox root
Everything starts from a BrainBox handle:
import { BrainBox } from '@brainbox-labs/sdk';
const brain = new BrainBox({
apiKey: process.env.BRAINBOX_API_KEY!,
org: 'my-org',
project: 'my-project', // slug or cuid2 ID
});The handle exposes three verb namespaces — brain.ingest, brain.recall, brain.update — plus brain.sync / brain.prune for keeping a folder of docs mirrored, and a server builder at brain.serve.
brain.ingest — ingest sources
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.
const result = await brain.ingest({
postgres: { connectionString: process.env.DATABASE_URL! },
sql: ['./sql/reports'], // SQL files or directories
docs: ['./docs/**/*.md'], // glob patterns
text: 'ARR excludes professional services fees.',
message: 'Q2 reports + finance docs',
});
console.log(result.stages); // [{ kind: 'sql', version: 4 }, { kind: 'docs', version: 5 }]IngestOptions
| Option | Type | Description |
| --- | --- | --- |
| 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'). |
| 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. |
| 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. |
| sql | string[] | SQL file paths / directories (requires postgres, trino, or athena) |
| docs | string[] | Glob patterns matching .md, .txt, .html files. .pdf and .docx are auto-converted to markdown (requires mammoth and pdf-parse optional deps). |
| text | string | Inline text snippet attached as a document |
| 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. |
| message | string | Description of the ingest (reserved for future use) |
| timeoutMs | number | Per-stage poll timeout (default: 300 000 ms) |
| reviewOnly | boolean | Stop after context is ready — skip activation for curation |
| force | boolean | Re-process the last connector draft instead of uploading sources again |
Partial failures
If a later stage fails after an earlier one has already activated, an IngestPartialFailureError is thrown carrying the completed stages:
import { IngestPartialFailureError } from '@brainbox-labs/sdk';
try {
await brain.ingest({ postgres: { connectionString }, docs: ['./docs'] });
} catch (err) {
if (err instanceof IngestPartialFailureError) {
console.log('completed:', err.completed); // stages that already shipped
console.log('failed stage:', err.failedKind);
}
}brain.sync and brain.prune — mirror a folder of docs
brain.sync keeps a folder (or an explicit list of docs) in step with the brain by stable sourceKey: it lists what the brain holds, uploads only new and changed docs, and reports docs that no longer exist locally. Needs project on the handle and an org or project key (tenant keys are refused).
const brain = new BrainBox({ apiKey: process.env.BRAINBOX_API_KEY!, org: 'acme', project: 'support-brain' });
// Preview first: nothing is sent or created.
const plan = await brain.sync({ dir: './docs/kb', dryRun: true });
console.log(plan.added.length, plan.changed.length, plan.unchanged.length, plan.pendingDeletes);
// Then sync for real. Docs deleted locally come back as `pendingDeletes`; nothing is archived.
const result = await brain.sync({ dir: './docs/kb' });
// Apply a decision about those deletes later.
if (result.pendingDeletes.length) {
await brain.prune(result.pendingDeletes.map((d) => d.sourceKey));
}SyncOptions
| Option | Meaning |
|---|---|
| dir | Folder of docs (md, txt, html, pdf, docx). Dot-directories and node_modules are skipped. |
| sources | In-memory DocEntry[], alone or on top of dir. Without a sourceKey the key is derived from name. |
| namespace | Where the pages live; part of every derived key. Defaults to the basename of dir; required with sources and no dir. |
| flat | Put every page in namespace itself. Default: subfolders map to nested namespaces (kb + eng/x.md → kb/eng). Keys are the same either way. |
| transform | A script under .brainbox/transforms/ (or a path relative to the working directory) applied to each doc; its content hash is part of the version. |
| prune | Pre-approve archiving docs that no longer exist locally. Default false. |
| force | Send every doc and tell the server not to skip unchanged ones. |
| dryRun | Diff only: no ingest, no archive, nothing created (a missing project reports every doc as added). |
| maxBatchBytes, maxBatchDocs | Upload batch limits (default 700 000 bytes, 50 docs). |
| onProgress | Called as each batch starts and finishes. |
| analysisDepth, timeoutMs, reviewOnly | As for brain.ingest. |
A sync root owns its namespace. Deletes are computed against every keyed raw-source page in the namespace and everything under it (exactly the namespace with flat). Pages written there by anything else, or by another folder synced to a nested namespace such as kb/eng, show up as pending deletes. Don't sync kb and kb/eng from two roots.
SyncResult
| Field | Meaning |
|---|---|
| dryRun, namespace | Whether anything was sent, and the namespace this sync owns. |
| added | Docs not in the brain yet. |
| changed | Docs whose content, namespace or analysis depth differ from the brain. |
| unchanged | Same key, version and namespace as the brain. Not sent unless force. |
| deleted | In the brain, no longer present locally. |
| pendingDeletes | deleted minus what was archived. Without prune: true this equals deleted: nothing is archived without a decision. |
| archived | Source keys archived by this call (only with prune: true). |
| listingTruncated, listingTruncatedReason | Set when the brain's listing may be incomplete. Deletes are then not computed: deleted and pendingDeletes are empty and nothing is archived, so treat an empty list as "unknown", not "none". |
| projectMissing | Dry run only: the project doesn't exist yet, so everything is reported as added. |
| skippedByServer, skippedByTransform | Keys the server reported unchanged; files a transform dropped (returned null). |
| ingest, batches | The stages and per-batch outcome (landed, failed, notAttempted). Absent for a dry run or when nothing needed sending. |
Entries in added, changed and unchanged are { sourceKey, name }; in deleted and pendingDeletes, { sourceKey, title }.
If a batch fails, sync throws SyncPartialFailureError with the result attached. Everything that landed stays landed, and a rerun resumes because landed keys come back as unchanged. Deletes are still computed but nothing is archived.
brain.prune(sourceKeys)
Archives the synced pages for these sourceKeys, to apply a decision about pendingDeletes.
const { archived, notFound } = await brain.prune(['kb%2Fold.md']);- Soft: pages are archived, not hard-deleted, and can be restored server-side. Archived pages drop out of recall and out of the next sync's listing.
- Unknown keys are not an error: they come back in
notFound, so a repeated prune is safe. - All keys are validated first. One malformed key throws before anything is archived.
- It never creates anything: a missing project throws.
- It archives exactly the keys you pass, whatever namespace they are in. Pass keys from
pendingDeletes, not a guess.
brain.recall — read the brain
Read verbs that map 1:1 to the hosted BrainBox MCP tools:
const index = await brain.recall.get_index();
const recent = await brain.recall.get_recent_changes();
const learn = await brain.recall.list_learnings();
const domain = await brain.recall.recall_domain({ query: 'orders' });
const traces = await brain.recall.recall_traces({ entity: 'order', limit: 5 });
const wiki = await brain.recall.recall_wiki({ q: 'returns policy' }); // each hit carries matchedPassage
const trace = await brain.recall.get_trace({ id: 'trc_abc' });
const page = await brain.recall.get_wiki_page({ id: 'wiki_xyz' });
const brief = await brain.recall.research_task({
question: 'Why did returns spike last week?',
});
// Enumerate without searching — list_* return summaries, get_* fetch one item
const pages = await brain.recall.list_wiki_pages({ namespace: 'acme', kind: 'runbook', limit: 50 });
const recentT = await brain.recall.list_traces({ team: 'support', since: '2026-10-01' });
const hits = await brain.recall.grep_wiki({ pattern: 'refund window', contextLines: 2 });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.
Agent loop
.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:
const tools = [...brain.recall.asTools(), ...brain.update.asTools()];
// Or hide tools this org has switched off (e.g. save_domain), so the model never picks one that would 403:
const enabled = [...await brain.recall.asEnabledTools(), ...await brain.update.asEnabledTools()];
// With the Anthropic SDK:
const response = await anthropic.messages.create({ tools, ... });
for (const block of response.content) {
if (block.type === 'tool_use') {
const tool = tools.find(t => t.name === block.name)!;
const result = await tool.execute(block.input);
}
}brain.update — write to the brain
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):
await brain.update.create_learning({
rule: 'Returns over 30 days are written off, not refunded.',
});
await brain.update.process_event({
text: '...',
eventType: 'meeting',
source: { externalId: 'granola:abc123' },
});
// source.externalId is the idempotency key. A concurrent duplicate gets a 409, thrown as
// BrainDispatchError { code: 'CONFLICT', retryable: true }: back off and retry.
// Create a skill, or replace an existing one's body as the next version
const skill = await brain.update.create_skill({
name: 'reconcile-invoices',
description: 'How to reconcile invoices',
sources: [{ name: 'steps', content: '...' }],
onConflict: 'update', // default 'error'
});
// skill.outcome is 'created' | 'updated'; skill.version is the new version
// Retire a learning that is no longer true, append to a wiki page without
// rewriting it, and tell the brain what it was missing
await brain.update.retire_learning({ learningId: 'lrn_abc', reason: 'Policy changed Q3' });
await brain.update.save_wiki_page({ mode: 'append', id: 'wiki_xyz', body: '- 2026-10-20: ...' });
await brain.update.report_context_gap({ need: 'EU refund policy', kind: 'missing' });
// Flag a personal page for admin review without changing its content
await brain.update.save_personal_page({ id: 'pp_abc', flagForReview: true, userId: 'u_123' });
// Delete a synthesis wiki page or a trace. Soft: hidden from every read at once,
// purged after 7 days unless a person restores it from the dashboard
const res = await brain.update.archive_wiki_page({ pageId: 'wp_abc', reason: 'Duplicate of wp_def' });
await brain.update.archive_trace({ traceId: 'tr_abc', reason: 'Recorded in error' });
// res.status is 'pending_deletion'; res.purgeAfter is the ISO purge timeThe 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.
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.
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.
import { BrainDispatchError } from '@brainbox-labs/sdk';
try {
await brain.update.process_event({ text: '...', source: { externalId: 'granola:abc123' } });
} catch (err) {
if (err instanceof BrainDispatchError && err.retryable) { /* wait err.retryAfter ?? a backoff, then retry */ }
else throw err;
}save_domain is available over the SDK too (brain.update.save_domain), not just MCP.
brain.projects — list and create projects
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.
const brain = new BrainBox({ apiKey: process.env.BRAINBOX_API_KEY!, org: 'acme' });
const projects = await brain.projects.list();
const created = await brain.projects.create('support-brain');Renaming/deleting projects and all tenant management (create, list, keys, suspend) are admin-tier on the server and not reachable with an API key.
brain.serve — MCP server builder
Build and start a local MCP server (Streamable HTTP) serving your approved tools:
const mcp = brain.serve.mcp({
connectors: { sql: { url: process.env.DATABASE_URL! } },
});
// Middleware: runs before every tool call
mcp.use(async (ctx, next) => {
const user = await verifyToken(ctx.headers['authorization']);
ctx.tenantId = user.tenantId;
await next();
});
// Enhanced tier: wrap the approved SQL with a tenant filter
mcp.tool('get_overdue_invoices', async (params, ctx) => {
return ctx.sql.query(
`${ctx.defaultQuery} AND tenant_id = $1`,
[...Object.values(params), ctx.tenantId],
);
});
// Custom tier: full implementation (tool shape defined in BrainBox UI)
mcp.tool('create_reconciliation_exception', async (params, ctx) => {
const [row] = await ctx.sql.query(
'INSERT INTO recon_exceptions (amount, tenant_id) VALUES ($1, $2) RETURNING id',
[params.amount, ctx.tenantId],
);
return row;
});
await mcp.start({ port: 3100 });
// → MCP server ready at http://localhost:3100/mcpTool execution tiers
| Tier | Developer effort | Behavior |
| --- | --- | --- |
| Auto | Nothing | SDK runs the approved SQL via the sql connector |
| Enhanced | mcp.tool('name', fn) on an auto tool | ctx.defaultQuery holds the approved SQL; developer wraps it |
| Custom | mcp.tool('name', fn) on a custom tool | Full implementation — tool shape is defined in BrainBox UI |
| Disabled | mcp.disable('name') | Tool excluded from MCP server entirely |
Custom tools without an override are silently excluded by default. Set serveUnimplementedTools: true to register them with a clear error on call.
ToolContext
Every middleware and tool handler receives a ToolContext:
interface ToolContext {
sql: SqlClient; // ctx.sql.query(sql, params)
defaultQuery?: string; // Approved SQL — available on auto-tier tools
toolName: string;
headers: Record<string, string | string[] | undefined>;
[key: string]: unknown; // Middleware can attach arbitrary fields (ctx.user, ctx.tenantId, …)
}Zero-code MCP server
No custom logic? Run the binary directly:
BRAINBOX_API_KEY=bb_xxx \
BRAINBOX_PROJECT=my-project \
DATABASE_URL=postgres://localhost:5432/mydb \
npx -y -p @brainbox-labs/sdk brainbox-mcp
# → MCP server ready at http://localhost:3100/mcpClaude Desktop config
{
"mcpServers": {
"my-project": {
"command": "npx",
"args": ["brainbox-mcp"],
"env": {
"BRAINBOX_API_KEY": "bb_xxx",
"BRAINBOX_PROJECT": "my-project",
"DATABASE_URL": "postgres://localhost:5432/mydb"
}
}
}
}BrainBox options
new BrainBox({
apiKey: string; // BrainBox API key (bb_...)
org: string; // Organisation slug
project?: string; // Project (brain) slug or cuid2 ID — required for ingest/recall/update/serve
apiUrl?: string; // Defaults to https://ctx.brainbox-ai.app
})Architecture
src/
brain.ts — BrainBox root: ingest, recall, update, serve namespaces
verb-namespace.ts — buildVerbNamespace(): VerbHandler + asTools()
client.ts — BrainBoxClient (REST API access)
index.ts — public exports
ingest/
index.ts — performIngest(): stages pipeline
introspect.ts — schema-introspection dispatcher (routes by URL scheme / explicit dialect)
schema-reader.ts — Postgres introspection (pg)
trino.ts — Trino introspection + connection (trino-client — optional dep)
athena.ts — Athena introspection + connection (@aws-sdk/client-athena — optional dep)
sql-parser.ts — SQL file parsing (pgsql-ast-parser)
docs-loader.ts — glob + inline text expansion; routes pdf/docx through doc-converter
column-profiler.ts — column statistics engine (Postgres, MySQL, SQLite, DuckDB, Trino, Athena)
doc-converter.ts — PDF/DOCX/HTML → markdown (mammoth, pdf-parse, turndown — optional deps)
public.ts — @brainbox-labs/sdk/ingest subpath re-exports
serve/
mcp.ts — MCP public class (use(), tool(), disable(), start())
sync.ts — SyncEngine: fetches tool definitions from BrainBox API
server.ts — MCP Server builder (@modelcontextprotocol/sdk)
dispatch.ts — Tool dispatcher: override > auto-sql > error
middleware.ts — runMiddlewareChain() (Koa-style next())
connectors/
sql.ts — SqlExecutor (pg.Pool) + NoopSqlClient
brain.ts — BrainExecutor (dispatch endpoint)
types.ts — ContextTool, SqlClient, ToolContext, MiddlewareFn, ToolHandlerFn
bin.ts — CLI entrypoint (brainbox-mcp binary)The MCP server runs entirely in the developer's infrastructure. BrainBox never receives database credentials or query results.
