Guide · TypeScript agent

Build a TypeScript agent on BrainBox

For developers and coding agents wiring agent code to a Brain with the SDK or MCP.

Updated

This guide takes you from an empty folder to a TypeScript agent that answers from a BrainBox Brain and saves a correction back to it. The agent is a short Vercel AI SDK loop with Claude, and the Brain is wired in with brain.recall.asEnabledTools() and brain.update.asEnabledTools() from @brainbox-labs/sdk. Every step ends with a check, so a coding agent can run the whole page unattended. The finished code is in the examples/agent-sdk-anthropic folder of the client-setup-v1 repo.

  • One file, about 150 lines: the SDK hands you tool objects, and you pass them to the model as they are.
  • The agent can read everything and write only `create_learning` and `save_wiki_page`.
  • Each step has a command and the output that means it worked.

For coding agents

Run these steps in order in an empty folder. A step passes when its check prints what is described under that step below. If a check fails, stop and read Troubleshooting. Step 5 holds secrets: use the values the person gave you and never print them or commit .env.

Prereq. node -v                              -> v24 or later
Step 1. npx -y @brainbox-labs/cli@latest login, then whoami   -> whoami prints the email and organization
Step 2. npx -y @brainbox-labs/cli@latest demo olist           -> prints: "Olist sample" is ready
        then tool get_index --project "Olist sample"  -> JSON starting with an "entities" array
Step 3. ask the person for a bb_ API key with write scope (an org admin creates it in the app)
Steps 4-6. write package.json, .env and index.ts exactly as shown below
Check the install. npm install, then npm ls --depth=0  -> @brainbox-labs/sdk@0.26.1 and ai@6.x
Step 7. npx tsx --env-file=.env index.ts "<question>"  -> "Using 18 brain tools", a [tool] line, "=== Answer ==="
Step 8. npx tsx --env-file=.env index.ts "Remember this: <fact>", then
        npx -y @brainbox-labs/cli@latest tool list_learnings --project "Olist sample"  -> the fact is under "corrections"

What you need

Node 24 or later (the CLI needs 24; the example's package.json declares 20 or later and was checked on Node 24), an Anthropic API key for the model, and a BrainBox account. Signing in below creates the account if you do not have one. The code uses @brainbox-labs/sdk 0.26.1 from public npm, so there is no registry or token to set up.

node -v
# v24.12.0 (any v24 or later)

Step 1: Sign in and check

login opens the browser. Add --no-browser over SSH. whoami is the check: it prints the account you are signed in as and exits 1 if you are not signed in. The CLI also prints the API URL it uses and where that URL came from, which matters if something points at the wrong host (see Troubleshooting).

npx -y @brainbox-labs/cli@latest login
npx -y @brainbox-labs/cli@latest whoami
# you@example.com — org: Your Org

Step 2: Put data in a Brain

The fastest route is the Olist sample, a small e-commerce Brain the CLI copies into your organization in seconds. It becomes a project named Olist sample. To use your own data instead, run ingest on a Postgres URL, a folder of docs or SQL files; see the CLI reference. The check reads the Brain back with get_index, the first call an agent makes.

npx -y @brainbox-labs/cli@latest demo olist
# ✓ "Olist sample" is ready in Your Org. Try asking:
#   • What is the return process, step by step?
#   • What is a customer entitled to when a delivery arrives after the estimated date?

npx -y @brainbox-labs/cli@latest tool get_index --project "Olist sample"
# {"entities":[{"name":"Customer","fieldCount":5},{"name":"Message","fieldCount":4},{"name":"Seller","fieldCount":4},{"name":"OrderItem","fieldCount":7}, ...
# success: valid JSON starting with an "entities" array, exit code 0

Step 3: Create an API key

The SDK authenticates with a BrainBox API key, not with your brainbox login. An organization admin creates one in the BrainBox app at https://ctx.brainbox-ai.app: open Organization settings, then API Keys (admins only), and create a key. You choose read or write scope when you create it, and write is the default. This agent needs a write key, because a read key cannot call create_learning. The key is shown only once, so copy the bb_ value into .env in the next step. Keys are credentials: keep .env out of git.

Step 4: package.json

Make a new folder and save this as package.json. The SDK is pinned to an exact version. ai is the Vercel AI SDK on its v6 line and @ai-sdk/anthropic is the matching provider.

{
  "name": "@brainbox-labs/example-agent-sdk-anthropic",
  "version": "1.0.0",
  "private": true,
  "type": "module",
  "scripts": {
    "start": "tsx index.ts"
  },
  "dependencies": {
    "@ai-sdk/anthropic": "^3.0.0",
    "@brainbox-labs/sdk": "0.26.1",
    "ai": "^6.0.0"
  },
  "devDependencies": {
    "@types/node": "^22.0.0",
    "tsx": "^4.0.0",
    "typescript": "^5.4.0"
  },
  "engines": {
    "node": ">=20"
  }
}

Step 5: .env

Save this as .env, with your values. BRAINBOX_ORG is the organization name and BRAINBOX_PROJECT is the project name, so for the sample use Olist sample. The SDK and the example do not read .env themselves; the run commands pass it with --env-file.

BRAINBOX_API_KEY=bb_...
BRAINBOX_ORG=my-org
BRAINBOX_PROJECT=my-project
ANTHROPIC_API_KEY=sk-ant-...

Step 6: index.ts and install

Save this as index.ts, then install. The file builds one BrainBox handle, collects the tools, and loops until the model answers. asEnabledTools() drops tools your org has switched off. Of the write tools the file exposes only create_learning and save_wiki_page, so the model cannot archive or retire anything. Each tool is already an MCP-format schema with a bound execute, so it goes straight into jsonSchema(...) and execute; there is no dispatch table. brain.recall.asTools() and brain.update.asTools() return the static list if you want every tool.

/**
 * BrainBox agent — Claude (Anthropic API) + @brainbox-labs/sdk.
 *
 * Uses brain.recall.asEnabledTools() and brain.update.asEnabledTools() instead of a raw
 * MCP client — no MCP connection or schema conversion boilerplate needed.
 *
 * Usage:
 *   npx tsx index.ts "What are the main entities in this domain?"
 *   npx tsx index.ts   # interactive REPL
 *
 * Required env vars:
 *   BRAINBOX_API_KEY        — org-level API key (bb_...)
 *   BRAINBOX_ORG            — org slug
 *   BRAINBOX_PROJECT        — project (brain) slug
 *   ANTHROPIC_API_KEY       — Anthropic API key (sk-ant-...)
 *
 * Optional:
 *   ANTHROPIC_MODEL         — defaults to claude-sonnet-5-5
 */

import { BrainBox } from '@brainbox-labs/sdk';
import { generateText, tool, jsonSchema, stepCountIs } from 'ai';
import { anthropic } from '@ai-sdk/anthropic';
import * as readline from 'readline';

const MAX_STEPS = 20;
const WRITE_TOOLS = new Set(['create_learning', 'save_wiki_page']);

// VerbTool is not exported by the SDK; derive it from asTools().
type VerbTool = ReturnType<BrainBox['recall']['asTools']>[number];

for (const v of ['BRAINBOX_API_KEY', 'BRAINBOX_ORG', 'BRAINBOX_PROJECT', 'ANTHROPIC_API_KEY']) {
  if (!process.env[v]) {
    console.error(`Missing ${v}. Export it before running.`);
    process.exit(1);
  }
}

const brain = new BrainBox({
  apiKey: process.env.BRAINBOX_API_KEY!,
  org: process.env.BRAINBOX_ORG!,
  project: process.env.BRAINBOX_PROJECT!,
});

const MODEL = process.env.ANTHROPIC_MODEL ?? 'claude-sonnet-5-5';

// Adapt VerbTool[] to the AI SDK tool map format.
// - `inputSchema` key (not `parameters`) — required by AI SDK v6
// - `stopWhen` (not `maxSteps`) — required by AI SDK v6
function toAITools(verbTools: VerbTool[]) {
  return Object.fromEntries(
    verbTools.map(t => [
      t.name,
      tool({
        description: t.description,
        inputSchema: jsonSchema(t.inputSchema),
        execute: async (args: unknown) => JSON.stringify(await t.execute(args as Record<string, unknown>)),
      }),
    ]),
  );
}

// --- Agent ---

const SYSTEM_PROMPT = `You are a business intelligence assistant with access to the BrainBox brain — a domain model that captures entities, relationships, business rules, processes, and vocabulary for this organization's data.

Available tools:
- get_index: high-level overview of entities, vocabulary, and recent learnings — start here
- list_learnings: retrieve saved business rules and learnings
- get_recent_changes: what has changed in the domain model recently
- recall_domain: search entities, relationships, metrics, or vocabulary by query
- recall_traces: find workflow/process traces by entity or keyword
- recall_wiki: search wiki pages by query
- get_trace: fetch a specific trace by ID
- get_wiki_page: fetch a specific wiki page by ID
- research_task: pose a free-form question; the brain synthesizes an answer across all sources
- create_learning: save a new business rule or learning to the brain
- save_wiki_page: create or append to a wiki page

When asked a question:
1. Start with get_index to orient yourself (unless you already called it this session).
2. Use recall_domain, recall_traces, recall_wiki, or research_task to drill in.
3. Answer with specific references to what you found.

When asked to learn or record something, use create_learning (needs queryContext, priorAnswer, correctAnswer, learningContext) or save_wiki_page.

Be concise. Cite tool outputs to support your answers.`;

async function runAgent(query: string) {
  // asEnabledTools() drops tools this org has switched off. Least privilege:
  // of the update tools, expose only the two write-backs this agent needs.
  const updateTools = (await brain.update.asEnabledTools()).filter((t) =>
    WRITE_TOOLS.has(t.name),
  );
  const verbTools = [...(await brain.recall.asEnabledTools()), ...updateTools];
  const aiTools = toAITools(verbTools);

  console.log(`\nUsing ${verbTools.length} brain tools: ${verbTools.map((t) => t.name).join(', ')}\n`);
  console.log('---');

  const result = await generateText({
    model: anthropic(MODEL),
    system: SYSTEM_PROMPT,
    messages: [{ role: 'user', content: query }],
    tools: aiTools,
    stopWhen: stepCountIs(MAX_STEPS),
    onStepFinish: (step) => {
      for (const item of step.content ?? []) {
        if (item.type === 'tool-call') {
          console.log(`[tool] ${item.toolName}(${JSON.stringify(item.input).slice(0, 120)})`);
        }
        if (item.type === 'tool-result') {
          const preview = String(item.output).slice(0, 200);
          console.log(`       → ${preview}${String(item.output).length > 200 ? '…' : ''}`);
        }
        if (item.type === 'text' && item.text) {
          console.log(`[step] ${item.text.slice(0, 120)}${item.text.length > 120 ? '…' : ''}`);
        }
      }
    },
  });

  console.log('\n=== Answer ===');
  console.log(result.text);
  console.log(`\n(${result.steps.length} step(s), ${result.usage.totalTokens} tokens)`);
}

// --- Entry point ---

async function main() {
  const queryFromArgs = process.argv.slice(2).join(' ').trim();

  if (queryFromArgs) {
    await runAgent(queryFromArgs);
    return;
  }

  const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
  console.log('BrainBox agent ready. Type a question or "exit" to quit.\n');

  const ask = () =>
    rl.question('> ', async (input) => {
      const q = input.trim();
      if (!q || q === 'exit') {
        rl.close();
        return;
      }
      await runAgent(q);
      ask();
    });

  ask();
}

main().catch((err) => {
  console.error(err);
  process.exit(1);
});

Check the install

Install, then confirm the versions. The check passes when the SDK is exactly 0.26.1 and ai is on 6.x.

npm install
npm ls --depth=0
# @ai-sdk/anthropic@3.x
# @brainbox-labs/sdk@0.26.1
# ai@6.x

Step 7: Ask a question

Run one question. The first line lists the tools the agent was given: 18 with default organization settings, fewer if your org switched some off. Then you see one [tool] line per call with a trimmed result under it, then the answer and the step count. Which tools the model picks varies between runs and models. The check passes when you see the tool list, at least one [tool] line and an === Answer === section. The output below is a real run (@brainbox-labs/sdk 0.26.1, ai 6.0.338, @ai-sdk/anthropic 3.0.145, claude-sonnet-5-5, Node 24.12) against a nearly empty test Brain with one rule, so it says there are no entities. Against the Olist sample the same question returns its entities, such as Customer, Order and Product.

npx tsx --env-file=.env index.ts "What are the main entities in this domain?"

Using 18 brain tools: get_index, list_skills, get_skill, list_learnings, get_recent_changes, list_traces, recall_traces, get_trace, list_wiki_pages, recall_wiki, get_wiki_page, list_personal_pages, recall_domain, research_task, check_context_draft, grep_wiki, create_learning, save_wiki_page

---
[tool] get_index({})
       → {"entities":[],"vocabulary":[],"rules":[{"name":"Refund Policy"}],"processes":[],"relationships":[],"learnings":[],"version":1,"wiki":{"pagesCount":0,…
[tool] recall_domain({"kind":"concept"})
       → {"kind":"concept","items":[]}

=== Answer ===
This domain doesn't have any entities yet. `get_index` returned an empty entity list, and `recall_domain` with `kind=concept` returned no items.
…
(3 step(s), 9425 tokens)

What a tool result looks like

Tool results are objects, not prose, and the model reads them as JSON. get_index returns entities, vocabulary, rules, processes, relationships, learnings, a version and a wiki summary. research_task returns summary, entities, workflows, governingRules, pastActivity, appliedLearnings, gaps, confidence and dataFoundNote. Read gaps and confidence: when the Brain does not hold the answer it says so there, which is the cue to write the missing fact back in the next step.

Step 8: Write back a learning

Tell the agent a fact to keep. It should call create_learning, which needs queryContext, priorAnswer, correctAnswer and learningContext; the file's system prompt lists them. The call returns the new learning's id and "status":"saved". The fact is stored in the Brain for every agent that uses it, so use a scratch copy such as the sample, not a Brain others rely on. The output below is from the same real run as Step 7. Use your own fact.

npx tsx --env-file=.env index.ts "Save a learning: when asked how long credit card refunds take, an earlier answer said 'about two weeks' but the correct answer is 5-10 business days after approval. Context: refund policy FAQ."

[tool] create_learning({"queryContext":"How long do credit card refunds take?","priorAnswer":"Credit card refunds take about two weeks.","corre…)
       → {"learning_id":"me6ujq3xs3a7n86fuxmynjkb","status":"saved","message":"Saved. Every future agent querying this project will see this before answering."}

=== Answer ===
I saved the learning (ID `me6ujq3xs3a7n86fuxmynjkb`). Future agents will now see that credit card refunds take **5-10 business days after approval**, not "about two weeks."
…
(2 step(s), 9445 tokens)

Check that the Brain returns it

Confirm the write by reading the saved learnings, which list_learnings and get_index show straight away. You can do it through the agent, as below, or without the model by running the CLI check, where your fact appears as the insight under corrections. research_task is a research agent that decides for itself which learnings apply, so a new learning may not show up in its appliedLearnings right away; do not use it as the check.

npx tsx --env-file=.env index.ts "List the saved learnings and show the one about credit card refund timing."

[tool] list_learnings({})
       → {"instruction":"Apply these before answering. …

=== Answer ===
There is one saved learning. It's a correction, and it's the one about credit card refund timing.

**Learning `me6ujq3xs3a7n86fuxmynjkb`**
- **Insight:** Credit card refunds take 5-10 business days after approval.
…
(2 step(s), 9369 tokens)

# the same check without the model
npx -y @brainbox-labs/cli@latest tool list_learnings --project "Olist sample"
# {"instruction":"Apply these before answering. …","rules":[],"corrections":[{"id":"…","insight":"…your fact…","context":"…"}]}

Use MCP instead of the SDK

If your framework speaks MCP, connect to the project endpoint with a project key (bb_proj_..., issued from the project sidebar, API Keys) and the Brain tools come from listTools(). This script is the connection check, and it has been run against /api/mcp with a project key: it listed the tools and get_index returned the Brain. It uses top-level await, so the folder needs "type": "module" in its package.json: the folder from Step 4 already has it, and in a fresh folder the commands below add it. Without it Node fails with "Top-level await is currently not supported with the 'cjs' output format". Set BRAINBOX_MCP_KEY and run it. The endpoint rejects an invalid key with a 401, and rejects a credential that is not a project key with a 403 that names the Project API Keys page. The server exposes the Brain tools, including get_index; see the MCP reference for the endpoints and which key each one takes.

# in a fresh folder only: npm init -y && npm pkg set type=module
npm install @modelcontextprotocol/sdk tsx

// mcp-check.ts
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';

const key = process.env.BRAINBOX_MCP_KEY;
if (!key) {
  console.error('Missing BRAINBOX_MCP_KEY (a project key, bb_proj_...). Export it before running.');
  process.exit(1);
}

const client = new Client({ name: 'brainbox-mcp-check', version: '1.0.0' });
await client.connect(
  new StreamableHTTPClientTransport(new URL('https://ctx.brainbox-ai.app/api/mcp'), {
    requestInit: { headers: { Authorization: `Bearer ${key}` } },
  }),
);

const { tools } = await client.listTools();
console.log(`${tools.length} tools: ${tools.map((t) => t.name).join(', ')}`);

const index = await client.callTool({ name: 'get_index', arguments: {} });
console.log(JSON.stringify(index.content).slice(0, 200));

await client.close();

// run it
BRAINBOX_MCP_KEY=bb_proj_... npx tsx mcp-check.ts
// <n> tools: get_index, ...  (then the first 200 characters of get_index)

Other model providers

The Brain side does not change when the model does. Because the loop is the Vercel AI SDK, switching providers means installing that provider's package, importing it, changing the model: line in index.ts, and setting that provider's key. For Gemini on Vertex AI, see the agent-sdk-vertex example in the same repo.

Clone and run it

The same files are in the client-setup-v1 repo, in examples/agent-sdk-anthropic, with a README. Clone it, run npm install in that folder, copy .env.example to .env, and use the same commands as above.

git clone https://github.com/brainbox-labs/client-setup-v1.git
cd client-setup-v1/examples/agent-sdk-anthropic
npm install
cp .env.example .env   # then fill in your values
npx tsx --env-file=.env index.ts "What are the main entities in this domain?"

Next: teach the Brain

The same SDK ingests and corrects from code. The ingest-and-query example ingests a doc and queries it. ingest-correct-query ingests, adds a correction with create_learning, and queries again. See the SDK reference for brain.ingest, brain.sync and the full list of verbs.

Troubleshooting

Match the error text.

invalid x-api-key  (APICallError, from the model call)
  -> ANTHROPIC_API_KEY is wrong. This comes from Anthropic, not BrainBox. The BrainBox key is not
     checked until the first tool call, so the "Using 18 brain tools" line can print with a bad BrainBox key.

[BrainBox] API 401 on /orgs: {"error":"Invalid API key","code":"UNAUTHORIZED"}
  -> BRAINBOX_API_KEY is wrong, revoked or truncated. Use a bb_ key from the app (organization settings,
     API Keys). A brainbox login session is not an API key.

[BrainBox] Project "x" not found. Available: Olist sample, ...
  -> BRAINBOX_PROJECT must be a project name from that list, spelled exactly. Check BRAINBOX_ORG too.

[BrainBox] <tool> is not enabled for this org. Ask an org admin to enable it.
  -> The org switched that tool off. asEnabledTools() already leaves it out; it only appears if you
     call the verb directly.

Missing BRAINBOX_API_KEY. Export it before running.
  -> The variables were not loaded. Run with --env-file=.env or export them. Nothing reads .env on its own.

Project-scoped API keys must use /api/mcp
  -> You sent a project key (bb_proj_...) to /api/org-mcp. A project key goes to /api/mcp and reaches that one
     project. /api/org-mcp takes an organization key or an OAuth sign-in. A key is not accepted on every endpoint.

Reads work but a write is rejected
  -> The key has read scope. Create a key with write scope; create_learning and save_wiki_page need it.

Answers are empty or say the Brain does not know
  -> Run npx -y @brainbox-labs/cli@latest tool get_index --project "<name>". If entities and wiki are empty, nothing is ingested yet:
     run npx -y @brainbox-labs/cli@latest demo olist, or npx -y @brainbox-labs/cli@latest ingest <source> --project "<name>".

Wrong host or wrong account
  -> The SDK uses https://ctx.brainbox-ai.app unless you pass apiUrl. The CLI prints its API URL and where
     it came from (--api-url, BRAINBOX_API_URL, brainbox login, or the default) before each command.
     Since CLI 0.20.1 a .env in the current folder is not loaded; set BRAINBOX_ENV_FILE to load one.
SDK or MCP for a TypeScript agent
SDK (`@brainbox-labs/sdk`)MCP (`/api/mcp`)
CredentialAPI key (`bb_...`) for an organization or project, plus org and project namesProject key (`bb_proj_...`) only
Tools come from`brain.recall.asEnabledTools()` and `brain.update.asEnabledTools()``client.listTools()` on the MCP server
Also doesIngest, sync and prune from codeNothing beyond the Brain tools
ReachesThe project you nameThe one project the key belongs to

FAQ

Do I need to use the Vercel AI SDK?
No. Each tool from `asEnabledTools()` has a name, a description, an MCP-format `inputSchema` and an `execute` method, so any framework that takes JSON-schema tools can use them. The example uses the Vercel AI SDK because it makes switching model providers a one-line change.
What is the difference between asEnabledTools() and asTools()?
`asTools()` returns the static list of every tool. `asEnabledTools()` is the same list without the tools your organization has switched off, so the model never picks one that would fail with a 403. Use `asEnabledTools()` in an agent.
Which key does the SDK need?
A BrainBox API key that starts with `bb_`, passed as `apiKey`. An admin creates it in the app under Organization settings, API Keys, choosing read or write scope when creating it. The SDK does not read your `brainbox login` session.
Does the SDK or the example read a .env file?
No. The example reads `process.env` only. Since CLI 0.20.1 the CLI does not read a `.env` from the current folder either. Pass the file with `--env-file=.env`, as the commands below do, or export the variables.
Should I use the SDK or MCP?
Use the SDK when your agent is TypeScript code you run: it needs an organization or project key plus the org and project names, and it can also ingest and sync. Use MCP when the framework already speaks MCP: it needs a project key and one URL, and it reaches one Brain.

Give your agents a brain.

Sign in and ask your first question.

Book a Demo