@thebaascompany/brain-sdk
v0.1.2
Published
Typed TypeScript SDK for external apps using The Brain API.
Readme
The Brain SDK
Typed TypeScript SDK for building external apps on top of The Brain.
Package: @thebaascompany/brain-sdk
The SDK handles:
- OAuth login with a registered Brain app.
- Server API keys for unattended, read-only integrations.
- PKCE helpers for browser-friendly public clients.
- Typed calls to the curated
/sdk/v1API. - Convenience methods for common Brain, Brain Area, document, search, task, and report operations.
External app tokens only work on /sdk/v1. They do not grant access to internal admin routes.
Install
npm install @thebaascompany/brain-sdkThe SDK requires Node 20 or newer.
Create An External App In The Brain
Before an external website or tool can use the SDK, a Brain admin must register it in The Brain.
In The Brain:
- Open
Settings. - Open the
Integrationstab. - Create a new OAuth app.
- Copy the generated
client_id. - If the app is confidential, copy the
client_secretonce and store it securely.
The Integrations tab is only visible to admins.
App Fields
App name
Human-readable name shown to admins and users during authorization.
Description
Short explanation of what the app does. This helps users understand what they are authorizing.
Website URL
Optional public homepage for the app.
Redirect URIs
Exact OAuth callback URLs where The Brain may send users after login. Include the full scheme and path.
Examples:
https://tracker.example.com/auth/brain/callback
http://localhost:3003/callbackAllowed browser origins
Exact browser origins allowed to call the SDK API from a frontend app. Include the scheme, but no path.
Examples:
https://tracker.example.com
http://localhost:3003SDK scope
Choose what the app may request:
brain:read: read Brains, Brain Areas, documents, search/graph data, stats, tasks, and reports.brain:write: includesbrain:readand allows trusted document writes exposed by the SDK, such as create, upload, update, edit, extract, and rollback.
Confidential client with secret
Use this for server-side apps that can safely store a secret. Leave it off for browser-only apps, local tools, or prototypes that cannot protect a secret.
Access Model
The app does not get global access by default.
Each user logs in with their Brain account. The app can only see and do what that user is already allowed to see and do in The Brain.
For example, if a Mapp user can only access one Brain Area, the external app will only receive data for that user's accessible Brain/Brain Area scope.
OAuth Login
For browser and public-client flows, use PKCE:
import {
buildAuthorizeUrl,
createCodeChallenge,
exchangeCodeForToken,
generateCodeVerifier,
generateState
} from "@thebaascompany/brain-sdk";
const baseUrl = "https://brain.thebaascompany.com";
const clientId = "app_xxx";
const redirectUri = "https://your-app.example.com/callback";
const codeVerifier = generateCodeVerifier();
const codeChallenge = await createCodeChallenge(codeVerifier);
const state = generateState();
const authorizeUrl = buildAuthorizeUrl({
baseUrl,
clientId,
redirectUri,
scope: ["brain:read"],
state,
codeChallenge
});
// Store codeVerifier and state in your app session, then redirect the user:
// window.location.href = authorizeUrl;In your callback route, validate state, then exchange the code:
const token = await exchangeCodeForToken({
baseUrl,
clientId,
code,
redirectUri,
codeVerifier
});For confidential server-side apps, also pass clientSecret.
const token = await exchangeCodeForToken({
baseUrl,
clientId,
clientSecret: process.env.BRAIN_CLIENT_SECRET,
code,
redirectUri,
codeVerifier
});Use The Client
import { createClientFromToken } from "@thebaascompany/brain-sdk";
const brain = createClientFromToken({
baseUrl: "https://brain.thebaascompany.com",
tokenResponse: token
});
const me = await brain.me();
const brains = await brain.listBrains();
const brainAreas = await brain.listBrainAreas({ include_spaces: true });For local direct-backend testing, override the data API base because production serves the API under /api:
const brain = createClientFromToken({
baseUrl: "http://127.0.0.1:8000",
apiBaseUrl: "http://127.0.0.1:8000",
tokenResponse: token
});Read documents from a Brain Area:
const documents = await brain.listDocuments("proj_xxx", {
layers: ["knowledge"],
needs_review: false,
order_by: "updated_desc"
});Read extracted text content:
const content = await brain.getDocumentContent("proj_xxx", "doc_xxx", {
limit: 5000
});Download or attach the original uploaded file:
// Good for Notion-style integrations that need a temporary URL to attach/link.
const file = await brain.getDocumentFileLink("proj_xxx", "doc_xxx", {
expiresInSeconds: 900
});
console.log(file.filename, file.mime_type, file.download_url);For server-side code that can send Brain auth headers, download the file directly:
const response = await brain.downloadDocument("proj_xxx", "doc_xxx");
const filename = response.headers.get("content-disposition");
const bytes = await response.arrayBuffer();getDocumentContent returns extracted markdown/text. getDocumentFileLink and downloadDocument return the original stored file bytes, so PDFs/DOCX files keep their original formatting/layout.
Create a document when the app has brain:write:
const document = await brain.createTextDocument("proj_xxx", {
title: "Meeting Notes",
text: "Notes from the customer call...",
document_type: "notes",
layers: ["knowledge"]
});Refresh a token when you store refresh tokens:
import { refreshAccessToken } from "@thebaascompany/brain-sdk";
const token = await refreshAccessToken({
baseUrl: "https://brain.thebaascompany.com",
clientId: "app_xxx",
refreshToken: storedRefreshToken
});Unattended Server API Key Flow
Use this for server-side jobs that need read-only access to specific Brains or Brain Areas without a user login.
In The Brain:
- Open
Settings. - Open
Integrations. - In
Server API keys, create a key. - Select one or more Brains or Brain Areas.
- Copy the key once and store it in server-side secrets.
Brain-scoped keys are dynamic: they can read all current and future Brain Areas inside that Brain. Brain Area-scoped keys only read selected Brain Areas.
Never put a server API key in browser/frontend code.
import { createClientFromApiKey } from "@thebaascompany/brain-sdk";
const brain = createClientFromApiKey({
baseUrl: "https://brain.thebaascompany.com",
apiKey: process.env.BRAIN_API_KEY!
});
const documents = await brain.listDocuments("proj_xxx");Server API keys are read-only. Write helpers such as createTextDocument, updateDocument, and extractDocument require OAuth with brain:write.
Low-Level Typed API
Every current /sdk/v1 route is available through the typed low-level API:
const result = await brain.api.GET("/sdk/v1/brain-areas/{project_id}/documents", {
path: { project_id: "proj_xxx" },
query: { layers: ["knowledge"], order_by: "updated_desc" }
});Form-data routes use formData:
const file = new File(["hello"], "hello.txt", { type: "text/plain" });
await brain.api.POST("/sdk/v1/brain-areas/{project_id}/documents/upload", {
path: { project_id: "proj_xxx" },
formData: {
file,
title: "Hello",
document_type: "notes",
layers: ["knowledge"]
}
});For AI agents building integrations: start with the named helpers for common reads and writes. If no helper exists, use brain.api.GET, brain.api.POST, brain.api.PUT, or brain.api.DELETE with the exact /sdk/v1 route. Route strings, path params, query params, and bodies are typed from OpenAPI.
Local OAuth Example
This repository includes a small local OAuth app for validating a registered external app.
Register an external app in The Brain with:
- Redirect URI:
http://localhost:3002/callback - Allowed browser origin:
http://localhost:3002 - Scope:
brain:read - Public client unless you specifically want to test a confidential client
Run:
cd brain-sdk
BRAIN_CLIENT_ID=app_xxx bun run example:oauthOpen:
http://localhost:3002To test writes, register or update the app with brain:write, then run:
BRAIN_CLIENT_ID=app_xxx BRAIN_SCOPE=brain:write bun run example:oauthOptional environment variables:
BRAIN_BASE_URL, defaulthttp://127.0.0.1:8000BRAIN_REDIRECT_URI, defaulthttp://localhost:3002/callbackBRAIN_SCOPE, defaultbrain:readBRAIN_CLIENT_SECRET, only for confidential appsPORT, default3002BRAIN_TEST_PROJECT_ID, project used by/test-write
Local Development
Inside this repository:
cd brain-sdk
bun install
bun run check
bun run buildRegenerate SDK types when the backend /sdk/v1 OpenAPI contract changes:
bun run types:generateThe backend must be running locally at http://127.0.0.1:8000 for type generation.
