--- name: BrainstormRouter bootstrap: POST https://api.brainstormrouter.com/v1/register self: GET https://api.brainstormrouter.com/v1/self mcp: POST https://api.brainstormrouter.com/v1/mcp/connect mcp-bootstrap: POST https://api.brainstormrouter.com/v1/mcp/bootstrap openapi: https://api.brainstormrouter.com/openapi.json --- # BrainstormRouter > The governed control plane for AI agents — routing, identity, budget, and evidence as one platform. Run multi-turn AI agent sessions with per-turn model selection (capability-matched: required-tier floor + shrinkage-blended learned reward, cost-aware, with epsilon-greedy exploration), governed tool execution (121 MCP tools), real-time budget enforcement, and memory injection across a curated catalog of 55 models from 9 providers (Anthropic, OpenAI, Google, DeepSeek, xAI, Groq, Perplexity, Moonshot, Z.ai) — counts are the registered catalog; live availability is `GET /v1/models` (circuit breakers may hide temporarily-unhealthy models). Also a drop-in OpenAI & Anthropic-compatible proxy with intelligent routing, graduated trust, agent identity, guardrails, and governance. ## Agent Quick Start (2 calls, no human required) ### Path A: Instant Sandbox Registration (recommended for agents — no invite, no email, no browser) **Call 1 — Register:** ``` POST https://api.brainstormrouter.com/v1/register {"tenant_name": "My Agent", "accept_tos": true} → { "tenant": { "id": "uuid", "slug": "my-agent", "plan": "sandbox" }, "api_key": { "key": "br_live_...", "scopes": ["admin"], "tier": "community" }, "limits": { "requests_per_day": 100, "tokens_per_day": 100000, "budget_usd_per_day": 2, "max_concurrent": 2, "routing": "auto", "byok_required": false }, "claim": { "url": "https://brainstormrouter.com/dashboard/?claim=...", "expires_at": "..." }, "next_steps": { "first_completion": {...}, "upgrade_paths": {...} } } ``` Save the `api_key.key` — it is shown once. `admin_email` is optional. TOS: `GET /v1/tos`. **Call 2 — First completion (works immediately; simulated until you add a provider key):** ``` POST /v1/chat/completions (Authorization: Bearer br_live_...) {"model": "auto", "messages": [{"role": "user", "content": "Hello"}]} ``` **Sandbox limits & upgrades:** the sandbox tier is capped (100 req/day, 100K tokens/day, $2/day, cost-first routing). Upgrade paths, in increasing capability: 1. **BYOK graduation** (recommended for agents — no email, no browser) → standard tier, $5/day: register a provider key (`POST /v1/providers`), check `GET /v1/account/graduation`, then `POST /v1/account/graduate`. A live-validated provider key is the trust anchor. 2. **Email verify** → standard tier, $5/day: `POST /v1/account/verify-email {"email": "..."}` then `POST /v1/account/verify-email/confirm {"code": "..."}` (requires inbox access) 3. **Invite code** → full tier at registration: include `invite_code` in `/v1/register` 4. **Claim dashboard** (human path, optional) → full account: open `claim.url` in a browser ### Path B: Email Signup (for humans without a browser — requires inbox access) ``` POST https://api.brainstormrouter.com/v1/signup {"email": "you@example.com", "tenant_name": "My AI Lab"} → { "message": "Verification code sent. Check your email.", "expires_in_seconds": 600 } POST https://api.brainstormrouter.com/v1/signup/verify {"email": "you@example.com", "code": "123456"} → { "tenant": {...}, "api_key": { "key": "br_live_..." }, "claim": { "url": "..." } } ``` Creates a full (non-sandbox) tenant. If email delivery is unavailable, the API returns a typed 503 (`code: "email_delivery_unavailable"`, `recovery.action: "use_alternate_endpoint"`) pointing back to Path A. ### Path C: CLI (one shot) ``` npx @brainstormrouter/cli go ``` `br go` registers (if needed), auto-detects provider keys in your environment (ANTHROPIC_API_KEY, OPENAI_API_KEY, ...), live-validates and stores them, graduates you out of the sandbox caps, and fires a test completion — non-interactive when stdin is not a TTY. (`br init` remains as the interactive wizard.) ### Add Provider Keys (BYOK — required for real inference; unkeyed sandbox calls return a simulated response) ``` POST /v1/providers (Authorization: Bearer br_live_...) {"provider": "anthropic", "api_key": "sk-ant-..."} ``` ## Agent Orchestration (Session Loop) The primary verb: `POST /v1/agents/:agentId/run` — creates a session, runs a multi-turn execution loop, and streams events as SSE. Each turn: capability-matched selection picks the model (required-tier floor + shrinkage-blended learned reward, cost-aware, with epsilon-greedy exploration) → context injection refreshes (SOUL, MEMORY, SKILL, HEARTBEAT, WORKSPACE, REFERENCE) → guardrails scan the response → tool calls execute via governed MCP → budget checks enforce per-agent limits. | Method | Endpoint | Description | |--------|----------|-------------| | `POST` | `/v1/agents/:agentId/run` | Run agent loop with SSE streaming (multi-turn, per-turn model selection) | | `POST` | `/v1/agents/:agentId/sessions` | Create session without running | | `GET` | `/v1/agents/:agentId/sessions/:sid` | Session status and metadata | | `POST` | `/v1/agents/:agentId/sessions/:sid/events` | Mid-run steering (user.message, user.interrupt via PG NOTIFY) | | `DELETE` | `/v1/agents/:agentId/sessions/:sid` | Terminate session | | `GET` | `/v1/agents/:agentId/runs` | Run history with aggregate cost/turns/duration | ### SSE Event Types `session.status_running`, `session.status_idle`, `session.status_ended`, `agent.message`, `agent.tool_use`, `agent.tool_result`, `br.model_selected`, `br.guardrail_intervention`, `br.budget_warning`, `br.routing_savings` ### Context Injection (per turn) Six attribute types injected into every turn's system prompt (4000 token budget): 1. **SOUL** — identity, personality, directives (from SOUL.md or HR record) 2. **MEMORY** — governance rules, user facts, archival context (from RMM) 3. **SKILL** — domain knowledge, learned patterns (accumulated from prior completions) 4. **HEARTBEAT** — health warning (only when degraded: anomaly score, budget, reputation) 5. **WORKSPACE** — active working context files 6. **REFERENCE** — design specs, style guides (metadata always, content on-demand) ## Key Endpoints for Agents - `GET /v1/self` — Full self-awareness: identity, health, budget, config, suggestions - `GET /v1/capabilities` — Self-describing, trust-scored capability graph of BR's own subsystems (identity, mesh, grants, credential custody, routing, governance); typed contracts + capability vector, scores flagged measured|declared|unknown. Query instead of grepping. Filter ?query= ?tier= ?status= - `GET /v1/discovery` — Capability discovery: routing strategies, health, budget, model stats - `GET /v1/catalog/runnable` — Models that will actually work right now - `GET /v1/health/providers` — Per-provider health with circuit breaker states - `GET /deploy.json` — Deploy manifest (commit_sha, previous_commit_sha, deployed_at, version) — no auth, rate limited - `POST /v1/chat/completions` — Route completions (streaming + non-streaming) - `POST /v1/messages` — Anthropic Messages API (same pipeline, Anthropic format) - `GET /v1/models` — All discovered models - `POST /v1/agent/bootstrap` — Create agent identity with budget + JWT - `POST /v1/mcp/connect` — MCP server (Streamable HTTP) - `POST /v1/mcp/bootstrap` — Pre-auth MCP bootstrap (no key needed): br_register + br_bootstrap_info, so pure-MCP agents onboard in-band - `GET /v1/account/graduation` → `POST /v1/account/graduate` — BYOK graduation out of the sandbox tier (no email, no browser) ## Intelligent Auto-Routing (model="auto") Set `model: "auto"` to activate BrainstormRouter's per-request selection engine. The always-on method is **capability-matched** (this is what `X-BR-Selection-Method` reports): 1. **Required-tier floor**: The request's complexity (0–10 from message count, tools, images, tokens, content analysis, and memory signals) classifies a required capability tier. Only models at or above that tier are eligible — the floor guarantees a hard prompt is never served by an under-powered model. 2. **Shrinkage-blended learned reward**: Each eligible model is scored `qEst = (n·measured + k·prior)/(n+k)` — real measured success blended toward a static quality prior, so cold-start models fall back to the prior and warm up toward observed performance. 3. **Cost-aware**: A log-normalized cost penalty and a tier-distance penalty are subtracted from `qEst`, so the cheapest capable model wins at the floor and easy prompts stay cheap. 4. **Epsilon-greedy exploration**: With a small decaying probability the selector tries a non-top candidate so a mis-estimated prior can be corrected by real outcomes. Model performance ranking (the `br_get_leaderboard` leaderboard) and multi-response consensus voting are learned separately via Thompson sampling; that is distinct from the per-request selection method above. ### Auto Variants - `auto` — Best overall (capability-matched: required-tier floor + shrinkage-blended learned reward, cost-aware, with epsilon-greedy exploration) - `auto:fast` — Fastest model (latency-optimized) - `auto:floor` — Cheapest model (cost-optimized) - `auto:best` — Most capable model (quality-only, ignores cost) Response headers expose the decision: `X-BR-Selection-Method`, `X-BR-Complexity-Level`, `X-BR-Complexity-Score`, `X-BR-Selection-Confidence`, `X-BR-Models-Considered`, `X-BR-Routed-Model`, `X-BR-Route-Reason`, `X-BR-Cache`, `X-BR-Total-Latency-Ms`, `X-BR-Provider-Latency-Ms`, `X-BR-Routing-Overhead-Ms`, and — only when a budget is configured — `X-BR-Budget-Remaining`. `X-BR-Budget-Remaining` is emitted when a budget is configured (a tenant-level limit or a per-key `budget_limit_usd`); requests on an unmetered default plan with no budget cap omit it, since remaining spend is undefined. There is no `X-BR-Memory-Facts-Injected` response header — the count of memory facts injected is reported inside the `x-br-context` JSON header instead. Every error response includes a `recovery` field with machine-actionable next steps. ## CLI (`@brainstormrouter/cli`) ``` npm install -g @brainstormrouter/cli ``` ### Getting Started ``` br init # Guided onboarding (signup or login, add provider, first completion) br auth signup # Create account via email verification br auth login-email # Log in with existing account br auth login # Direct API key login br auth status # Show current auth, tenant, key ``` ### Daily Use ``` br chat "prompt" # Send completion (model=auto by default) br models # List available models br providers add # Add provider API key interactively br health # Provider health + circuit breaker states br webhooks list # List configured webhooks br account # Tenant profile + user count ``` ## Account & Tenant Management All endpoints require `Authorization: Bearer br_live_...` (API key with `config.read` or `config.write` scope). | Method | Endpoint | Description | |--------|----------|-------------| | `GET` | `/v1/account` | Tenant profile (name, plan, status, user count) | | `PATCH` | `/v1/account` | Update tenant name | | `GET` | `/v1/account/users` | List users in tenant | | `POST` | `/v1/account/users/invite` | Invite user by email (generates claim URL) | | `DELETE` | `/v1/account/users/:id` | Remove user from tenant | ### Example: Get tenant profile ``` GET /v1/account → { "tenant": { "id": "uuid", "slug": "my-lab", "name": "My AI Lab", "plan": "free", "user_count": 3 } } ``` ### Example: Invite a user ``` POST /v1/account/users/invite {"email": "teammate@example.com", "role": "member"} → { "invitation": { "email": "...", "role": "member", "claim_url": "https://brainstormrouter.com/dashboard/?claim=..." } } ``` ## Webhooks Event-driven notifications for completions, provider health, budget, keys, and anomalies. All endpoints require `Authorization: Bearer br_live_...`. | Method | Endpoint | Description | |--------|----------|-------------| | `POST` | `/v1/webhooks` | Create webhook | | `GET` | `/v1/webhooks` | List webhooks | | `PATCH` | `/v1/webhooks/:id` | Update webhook (url, events, is_active) | | `DELETE` | `/v1/webhooks/:id` | Delete webhook | | `POST` | `/v1/webhooks/:id/test` | Send test event | | `GET` | `/v1/webhooks/:id/deliveries` | Delivery history | ### Valid event types `completion.created`, `completion.error`, `provider.down`, `provider.recovered`, `budget.threshold`, `budget.exceeded`, `key.created`, `key.revoked`, `anomaly.detected` ### Example: Create a webhook ``` POST /v1/webhooks {"url": "https://example.com/hook", "events": ["completion.error", "provider.down"]} → { "webhook": { "id": "uuid", "url": "...", "events": [...], "is_active": true, "secret": "hex...", "note": "Save this secret — it won't be shown again. Use it to verify webhook signatures." } } ``` Deliveries include an `X-BR-Signature` header = HMAC-SHA256 of the JSON payload using your webhook secret. ## Terms of Service ``` GET /v1/tos (no auth required) → { "version": "1.0", "summary": "...", "url": "https://brainstormrouter.com/legal/terms" } ``` Call before signup to display terms to the user. ## SDKs - [TypeScript SDK](https://www.npmjs.com/package/brainstormrouter) — `npm install brainstormrouter` - [Python SDK](https://pypi.org/project/brainstormrouter/) — `pip install brainstormrouter` - [CLI](https://www.npmjs.com/package/@brainstormrouter/cli) — `npm install -g @brainstormrouter/cli` ## Agent Playbook (Full 12-Phase Guide) - [Agent Playbook](https://brainstormrouter.com/llms-agent-playbook.txt) — step-by-step setup from zero to production ## API Reference - [OpenAPI Spec](https://api.brainstormrouter.com/openapi.json) - [Full API Reference (llms-full.txt)](https://brainstormrouter.com/llms-full.txt) - [Completions](https://docs.brainstormrouter.com/api-reference/completions) - [Models](https://docs.brainstormrouter.com/api-reference/models) - [Memory](https://docs.brainstormrouter.com/api-reference/memory) - [Security](https://docs.brainstormrouter.com/api-reference/security) - [Guardrails](https://docs.brainstormrouter.com/api-reference/guardrails) - [Observability](https://docs.brainstormrouter.com/api-reference/observability) - [Governance](https://docs.brainstormrouter.com/api-reference/governance) ## Core Concepts - [Trust Envelope (signed-JWT decision contract)](https://docs.brainstormrouter.com/concepts/trust-envelope) - [Agent Reputation (5-tier system)](https://docs.brainstormrouter.com/concepts/agent-reputation) - [XDR Pipeline (OCSF + 5 SIEM connectors + bidirectional risk push)](https://docs.brainstormrouter.com/concepts/xdr-pipeline) - [Intelligent Routing (Capability-Matched Selection)](https://docs.brainstormrouter.com/concepts/routing) - [Agent Memory (4-Block RMM)](https://docs.brainstormrouter.com/concepts/memory) - [Graduated Trust Degradation](https://docs.brainstormrouter.com/concepts/graduated-trust) - [Guardrails](https://docs.brainstormrouter.com/concepts/guardrails) - [Observability](https://docs.brainstormrouter.com/concepts/observability) ## Identity Bridge (Machine-to-Dashboard Linking) - After registration, open the claim URL to link your dashboard account - Generate additional claim links: `POST /v1/tenant/claim-link` (API key, admin scope) - Device flow for terminal-to-browser linking: `POST /v1/auth/device/authorize` → display `user_code` → user enters at dashboard → poll `POST /v1/auth/device/token` ## MCP Control Plane - BrainstormRouter operates as both MCP server (121 tools) and MCP gateway (register, govern, proxy external MCP servers) - Secretless access: upstream credentials stored on server registrations, never exposed to agents - Endpoint: `POST https://api.brainstormrouter.com/v1/mcp/connect` - Transport: Streamable HTTP (per MCP spec) ### MCP Server Tools (121) Routing & Models: br_route_completion, br_list_models, br_get_usage, br_set_alias, br_list_aliases, br_patch_aliases, br_get_health Memory: br_memory_list, br_memory_store, br_memory_query, br_memory_delete, br_memory_update, br_memory_shared_store, br_memory_shared_list Config: br_list_prompts, br_list_presets, br_list_config, br_get_config, br_set_config Ops & Insights: br_get_ops_status, br_diagnose_providers, br_get_insights, br_get_governance, br_get_insights_daily, br_get_insights_forecast Agents: br_list_agents, br_get_leaderboard, br_bootstrap_agent, br_agent_status, br_agent_limits, br_agent_anomaly Delegation: br_delegate_agent, br_list_sub_agents, br_terminate_sub_agent Agent Runs: br_agent_run_start, br_agent_run_status, br_agent_run_cancel Capacity: br_get_capacity Security: br_get_security_status, br_get_policies, br_test_policy, br_get_siem_config, br_update_siem_config Guardrails: br_get_guardrail_config, br_update_guardrail_config, br_test_guardrails, br_guardrail_metrics Budget: br_get_budget_status, br_get_budget_forecast Kill Switch: br_activate_killswitch, br_deactivate_killswitch, br_get_killswitch_status, br_killswitch_scope, br_list_killswitch_scopes, br_deactivate_killswitch_scope Governance: br_policy_dry_run, br_replay_decisions, br_session_timeline, br_forensic_snapshots Approvals: br_list_pending_approvals, br_approve_request, br_reject_request Platform Admin: br_list_tenants, br_approve_tenant, br_reject_tenant, br_get_business_digest, br_create_invite_code MCP Gateway: br_mcp_server_health RBAC: br_my_permissions ## Integration Guides - [LangChain](https://docs.brainstormrouter.com/guides/langchain) - [LlamaIndex](https://docs.brainstormrouter.com/guides/llamaindex) - [CrewAI](https://docs.brainstormrouter.com/guides/crewai) - [Vercel AI SDK](https://docs.brainstormrouter.com/guides/vercel-ai) - [Grok Bot harness](https://docs.brainstormrouter.com/guides/grok-bot) — plugin at `plugins/grok-bot`, MCP `POST /v1/mcp/connect`