# @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

You need Node 24+ and an API key. An org admin creates keys in the [BrainBox app](https://ctx.brainbox-ai.app/orgs): the org's API keys page has org keys (`bb_...`), and a project's page has project keys (`bb_proj_...`). The quickstart creates a project, so use an org key. Then:

```bash
mkdir brainbox-hello && cd brainbox-hello
npm init -y && npm install @brainbox-labs/sdk
export BRAINBOX_API_KEY=bb_...      # your key
```

Prefer a `.env` file? Put `BRAINBOX_API_KEY=bb_...` in it and run `node --env-file=.env hello.mjs`.

Save as `hello.mjs` and run `node hello.mjs`. It creates a project, ingests one sentence, and asks a question about it. Re-running is safe.

```javascript
import { BrainBox } from '@brainbox-labs/sdk';

const apiKey = process.env.BRAINBOX_API_KEY;

// 1. Find or create a project. No `org` needed: a key belongs to exactly one org, and the SDK uses it.
const root = new BrainBox({ apiKey });
const name = 'hello-world';
if (!(await root.projects.list()).some((p) => p.name === name)) await root.projects.create(name);

// 2. Ingest some text. Resolves once the new version is live.
const brain = new BrainBox({ apiKey, project: name });
await brain.ingest({ text: 'Orders older than 30 days are written off and not refunded.' });

// 3. Ask a question. `intent` is the question in plain words.
const brief = await brain.recall.research_task({ intent: 'What is the returns policy for old orders?' });
console.log(brief);
```

`project` takes a slug or the project's ID. `org` is optional; see [Which org?](#which-org) below.

## The `BrainBox` root

Everything starts from a `BrainBox` handle:

```typescript
import { BrainBox } from '@brainbox-labs/sdk';

const brain = new BrainBox({
  apiKey: process.env.BRAINBOX_API_KEY!,
  project: 'my-project',   // slug or cuid2 ID
});
```

### Which org?

An API key belongs to exactly one organization, so `org` is optional and defaults to the key's org. If you pass it, it is checked against the key: a mismatch throws `OrgMismatchError` (`status: 403`, `code: 'ORG_MISMATCH'`, `keyOrg`, `requestedOrg`) instead of acting on the wrong org.

```typescript
import { OrgMismatchError } from '@brainbox-labs/sdk';

try {
  await new BrainBox({ apiKey, org: 'wrong-org', project: 'my-project' }).recall.get_index();
} catch (err) {
  if (err instanceof OrgMismatchError) console.log(`this key is for "${err.keyOrg}"`);
}
```

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.

```typescript
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 `npm install trino-client` (an optional peer dependency, not installed by default). |
| `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 dependencies that npm installs by default; see [Optional dependencies](#optional-dependencies)). |
| `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:

```typescript
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).

```typescript
const brain = new BrainBox({ apiKey: process.env.BRAINBOX_API_KEY!, 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 `sourceKey`s, to apply a decision about `pendingDeletes`.

```typescript
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:

```typescript
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({
  intent: '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 });
```

In a `research_task` brief, an entity with `"type": "llm_proposed"` was proposed by the model rather than read from a schema or document, so it has lower confidence than a schema-grounded one (which is `1.0`). Treat it as a lead to check, not a fact.

`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:

```typescript
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):

```typescript
await brain.update.create_learning({
  rule: 'Orders over 30 days old are written off, not refunded.',
});
// For a richer record, pass queryContext, priorAnswer, correctAnswer and learningContext instead of `rule`.

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 time
```

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.

`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`.

```typescript
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.

```typescript
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:

```typescript
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/mcp
```

### Tool 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`:

```typescript
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:

```bash
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/mcp
```

### Claude Desktop config

```json
{
  "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

```typescript
new BrainBox({
  apiKey: string;     // BrainBox API key (bb_...)
  org?: string;       // Organisation slug. Optional: defaults to the key's org
  project?: string;   // Project (brain) slug or cuid2 ID — required for ingest/recall/update/serve
  apiUrl?: string;    // Defaults to https://ctx.brainbox-ai.app
})
```

---

## Optional dependencies

These are `optionalDependencies`: npm installs them by default, and they are loaded only when needed. The exception is `trino-client`, an optional peer dependency: for Trino, run `npm install trino-client` yourself.

| Package | Needed for |
|---------|-----------|
| `pdf-parse` | `.pdf` docs |
| `mammoth` | `.docx` docs |
| `turndown` | `.html` docs (and the `.docx` conversion) |
| `mysql2`, `better-sqlite3`, `@duckdb/node-api` | MySQL, SQLite and DuckDB column profiling |
| `@aws-sdk/client-athena` | Athena introspection |

If an install omitted them (`--omit=optional`, or a native build failed), a missing package surfaces only when you use
it, as a module-not-found error naming the package. `brain.ingest` and `brain.sync` reject with that error when they
reach a PDF or DOCX file (the CLI, by contrast, skips the file with a warning). Fix it with
`npm install pdf-parse mammoth turndown`.

---

## Architecture

```text
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.
