Brain Docs

Reference

Integrations

Frameworks

Next.jsFastAPILangChainOpenAI

Protocol

Brain over MCP
Brain/Docs
✦ ASKBrain on GitHubDashboard
IntegrationsBrain over MCP

Brain over MCP

@brain-db/mcp exposes Brain's tenant surface as 49 Model Context Protocol tools over stdio or remote Streamable HTTP — the transports, the tool surface, the four-line error contract, and the identity model that makes one public deployment safe.

PURPOSE

@brain-db/mcp is a first-party MCP server for Brain. It exposes the tenant surface as 49 tools over stdio or remote Streamable HTTP, so any MCP client — Claude, Cursor, Copilot — can give its agent durable memory in one connection. This page covers running it, every tool and its limits, how a failed tool call reads, and the identity model that lets a single public deployment serve every user as themselves.

◇Prerequisites

Node 20 or newer — the package declares "node": ">=20". A Brain API key and the base URL of a backend — the Arc gateway, or your own brain-edge. An MCP client, if you are connecting one. If encode and recall are new, read Your first memory first: the tools below are those verbs with agent-facing names.

What it is

A thin, stateless front for Brain's REST surface. Every tool is one /v1/* call, the JSON contract is identical, and the server holds no state between requests — so it scales horizontally and any instance can serve any request.

That thinness is the point. The server adds exactly three things the REST API does not have:

01

Tool descriptions a model reads

Each tool carries guidance written for an agent rather than a developer — when to reach for recall over list_memories, why resolve_entity comes before create_entity.

02

A failure an agent can act on

Every error renders as four labelled lines including an explicit retry verdict. An agent left to infer that either loops on a terminal failure or abandons a transient one.

03

A surface with the sharp edges removed

Eight tenant routes have no tool at all, and one destructive flag cannot be set. See Deliberately not exposed.

You do not need to write one

Earlier revisions of this page said Brain ships no MCP server and showed how to build a wrapper yourself. That has not been true since 0.2.0.

Install

npm install -g @brain-db/mcp

There is no public hosted endpoint to point this at yet

Every example below uses http://127.0.0.1:8080 for a local brain-edge, or a placeholder host like https://brain-edge.internal where the backend is remote. Substitute your own deployment's URL in either case — a host copied verbatim from this page will not resolve.

Two transports, one rule

The credential comes from the transport. That single rule explains every configuration difference below, and it is worth holding onto — most confusion with this server is a credential arriving by the wrong route.

stdio — the client owns the process

The usual local setup for Claude Desktop and Cursor. The client starts the server and holds the key in its own config:

claude_desktop_config.json
{
  "mcpServers": {
    "brain": {
      "command": "npx",
      "args": ["-y", "@brain-db/mcp", "--stdio"],
      "env": {
        "BRAIN_MCP_BACKEND_URL": "http://127.0.0.1:8080",
        "BRAIN_MCP_API_KEY": "brain_…"
      }
    }
  }
}
`--stdio` is not optional, and leaving it off hangs the client

The package ships a bin, which is the conventional signal for a stdio server — so the obvious config omits the flag. Without --stdio (or BRAIN_MCP_STDIO=1) the binary starts an HTTP listener instead, never reads the initialize frame on stdin, and the client waits forever with no error to show you. If a client reports the server as "connecting" and never resolves, this is the first thing to check.

On stdio the server writes only protocol frames to stdout. Every log, including the startup line, goes to stderr, which clients surface as server logs. Anything else on stdout is a parse error at the client.

Remote HTTP — one deployment, many users

brain-mcp            # listens on :3333, MCP endpoint at POST /mcp
claude mcp add --transport http brain https://mcp.example.com/mcp \
  --header "Authorization: Bearer brain_…"
{
  "mcpServers": {
    "brain": {
      "url": "https://mcp.example.com/mcp",
      "headers": { "Authorization": "Bearer brain_…" }
    }
  }
}

Over HTTP every request brings its own key and BRAIN_MCP_API_KEY is not consulted at all. A request without a bearer is refused with a 401 carrying WWW-Authenticate: Bearer realm="brain-mcp" and a JSON-RPC envelope whose message names the fix — it never reaches the backend.

Only the Bearer scheme

The gateway also accepts x-api-key. This server does not, deliberately: one documented place to put the credential is one place to get it wrong, and one place an intermediary can log it. Authorization: Bearer <key> is the whole contract.

Configuration

ParameterTypeRequired
BRAIN_MCP_BACKEND_URLurlrequired

Brain's REST base URL — the hosted gateway, or your own brain-edge. A trailing slash is stripped. Missing or empty is a startup failure, not a per-request one.

BRAIN_MCP_API_KEYstringoptional

The caller's Brain key. Required with --stdio, ignored over HTTP.

BRAIN_MCP_STDIObooleanoptional

Serve over stdin/stdout instead of HTTP — the same as --stdio. Accepts 1, true, yes, on. Defaults to false; port and host are unused in that mode.

BRAIN_MCP_PORTintegeroptional

Listen port, HTTP only. Defaults to 3333. Anything outside 1..65535 fails at startup.

BRAIN_MCP_HOSTstringoptional

Bind interface. Defaults to 0.0.0.0.

BRAIN_MCP_REQUEST_TIMEOUT_MSintegeroptional

Per-request backend timeout. Defaults to 30000. Exceeding it surfaces to the agent as a retryable 504.

Every one of these is validated once, at startup, so a misconfigured deployment fails to boot rather than failing one tool call at a time in production.

`BRAIN_MCP_OAUTH_ENABLED` now refuses to start

An earlier version had an OAuth mode: the caller presented a JWT, and the server called the backend with its own shared service key, selecting a namespace from a token claim. That selection never worked — the gateway ignores the namespace header for key callers — so every OAuth tenant landed in the service key's own workspace. An OAuth mode that authenticates the caller and then serves them someone else's data is worse than none.

It is gone, and the flag is a startup failure rather than a warning: a deployment that sets it believes it is isolating tenants, and has to find out from its own logs rather than from a tenant. Unset BRAIN_MCP_OAUTH_ENABLED and every BRAIN_MCP_OAUTH_* to start.

There is no OAuth handshake today. A client that expects one must be configured with a static header instead.

Deploying one

The container is published to GHCR on every version tag, multi-arch (linux/amd64, linux/arm64):

docker run -p 3333:3333 \
  -e BRAIN_MCP_BACKEND_URL=https://brain-edge.internal \
  ghcr.io/arc-labs-ai/brain-mcp:latest

That is the whole configuration. The image holds no credential and has no default for one, so the same container serves every user at their own identity. Pin a digest rather than a tag in a deploy manifest; each release prints one.

Two things the image commits to, because deployments depend on them:

  • curl is installed, and the image's own HEALTHCHECK uses it — so an image missing it fails at build time rather than in a deploy loop.
  • The health path is /healthz, and it is unauthenticated: a load balancer has no bearer to send. A target group pointed anywhere else never sees a healthy target.
curl -fsS localhost:3333/healthz
# {"status":"ok","service":"brain-mcp"}

What the stateless design buys you

Each POST /mcp builds a fresh server, transport and backend bound to that caller's credential, then tears them down when the response closes. There is no session id and no cross-request state, so there is nothing for one caller's identity to leak into another's — and any instance behind a load balancer can serve any request without sticky routing.

The 49 tools

No tool takes a customer or tenant id. The identity is the caller's credential, resolved server-side, so there is nothing for an agent to set — or to get wrong. ? marks an optional argument.

Memory — the core loop

Most agents only ever call the first three.

ToolArgsWhat it does
remembercontentStore a fact, event or turn. Brain extracts typed facts and supersedes stale ones. Returns the memory id.
recallquery, max_results? (1–1000)Retrieve the current, consistent truth. Returns an answer shape — single / many / none — with evidence and confidence; contradicted facts are already resolved server-side.
forgetmemory_id, hard?Delete one memory. Soft by default (tombstone with a grace window); hard zeroes it immediately. Cascades to dependent facts.
list_memorieslimit? (1–100), cursor?Page through what is stored, newest first. Inventory, not questions.
inspect_memorymemory_idEverything behind one memory — the facts extracted from it, its provenance, how it scored. The verb for "why was this not used".
materialize_directivescategories?, top_k? (1–200), min_confidence? (0–1)The workspace's standing instructions, rendered as a block to drop into a system prompt. Call it once at session start rather than recalling for it each turn.

inspect_memory does not return the raw embedding

It summarises it — shape and magnitude — instead. Measured against a live server the raw vector was 4,716 of 8,701 characters: 54% of the response, spent on 384 floats an agent can do nothing with. "Is there an embedding and is it sane" is the only question those numbers could answer, and the summary answers it.

Reasoning

ToolArgsWhat it does
planstart, goal, max_steps? (1–10)A route from a start state to a goal across what is known. Reasons over stored facts rather than inventing steps.
reasonobservationWhat follows from an observation, given what is already known. Use to check an implication before acting on it.

The max_steps ceiling is not arbitrary: Brain's planner refuses anything above its own max_traversal_depth, which defaults to 10. The schema used to advertise 50, so an agent reading it would pick a value in 11–50, pass validation at the tool, and be refused by the server with 50 exceeds max_traversal_depth = 10. A deployment that raises the limit makes this conservative rather than wrong.

Entities

entity_type_id comes from get_schema.

ToolArgsWhat it does
create_entityentity_type_id, canonical_nameDeclare an entity. Creating one that already exists under the same name is a conflict, not a silent no-op — resolve first if unsure.
list_entitiesentity_type_id, limit? (1–200), cursor?Entities of one type. The type is required — listing across every type is refused rather than silently paged.
resolve_entitycandidate_nameMap a surface form to the entity it refers to, or report no match. Use before creating, and before assuming two mentions are the same thing.
get_entityentity_idOne entity, with its canonical name, type and attributes.
traverse_entityentity_id, depth? (1–5), limit? (1–200)Walk outward along relations without pulling the whole graph.
entity_relationsentity_id, limit? (1–200), cursor?The relations attached to one entity, without walking further.
update_entityentity_id, canonical_name, aliases, attributes?Replace name, aliases and attributes wholesale — a replace, not a patch. Omitting aliases clears them, so get_entity first and send the full list back with your change.
rename_entityentity_id, new_canonical_name, move_to_alias?New canonical name, old one kept as an alias. Prefer this over update_entity for a rename: the old name is how a mention in older text still resolves.
merge_entitiessurvivor_entity_id, merged_entity_id, confidence?, reason?Fold a duplicate into the entity that remains. survivor_entity_id is the one that stays.
unmerge_entityentity_idThe undo for merge_entities. Pass the id of the entity that was absorbed, not the survivor.
delete_entityentity_id, reason?Tombstone it, so it stops appearing in listings and traversals. Soft — rows that referenced it still refer to something that exists.

Graph

ToolArgsWhat it does
linksource, target, kindA typed edge between two memories — caused, followed_by, derived_from, similar_to, contradicts, supports, references, part_of.
unlinksource, target, kindRemove one. Idempotent.
graphlimit? (1–200), cursor?A page of the workspace's graph. Use to see structure; use recall to answer a question.

Knowledge

ToolArgsWhat it does
list_statementslimit? (1–200), cursor?The subject–predicate–object facts extracted from this workspace. Use to audit what Brain believes, not to answer a question.
get_statementstatement_idOne statement, with the memory it came from.
get_relationrelation_idOne relation, with its endpoints and type.
statement_historystatement_idThe full supersession chain, oldest to newest. Reach for it when a recall and a statement disagree.
create_statement—Assert a claim directly rather than waiting for extraction to infer one. Use when the user states a fact outright.
supersede_statementstatement_idReplace a claim with a corrected one, keeping both and the link between them. The right tool when something changed or was wrong.
delete_statementstatement_id, message?Soft-tombstone. The row survives for audit and stops being returned.
retract_statementstatement_id, message?The stronger form — the content does not survive. For something that should never have been recorded.
create_relation—Assert a typed edge. The type is namespace:name (a bare name is rejected) and must already be declared.
supersede_relationrelation_idReplace an edge, keeping the chain. Send every field: the replacement is whole and its properties blob replaces rather than merges.
delete_relationrelation_id, reason?Tombstone an edge; traversals stop crossing it. If it is merely out of date, supersede_relation keeps the history.

Schema

ToolArgsWhat it does
get_schema—The entity and relation types declared here. Read before creating entities.
validate_schemaschema_documentCheck a document without storing it.
upload_schemaschema_documentMerge new declarations. Additive: it cannot drop a declaration, and changing an existing one is a conflict.
list_schema_versionslimit? (1–200), cursor?The schema's version history. Distinct from get_schema, which returns the one current document.
list_extractors—What will read a new memory and what it may produce. Read-only — extraction is always on and cannot be turned off from here.
drop_schema_typekind, name, force?Remove one declared predicate or relation type. Entity types are not droppable: they are shared across workspaces.

Identity

ToolArgsWhat it does
whoami—The namespace and space the caller's key resolves to on the server. Call it first when anything looks like it is reading the wrong workspace.
capabilities—What this deployment supports — limits, enabled extractor tiers, protocol version. Use to check a limit before hitting it.
llm_credential_status—Whether this workspace has a provider key, and for which provider and model. Returns a display fingerprint, never the key.
verify_llm_credential—Re-check the registered key by asking the provider. Takes nothing and sends no secret anywhere — a key that worked at registration can be revoked later.

Workspace

ToolArgsWhat it does
create_sessionsession_id, title?Provision a session so one conversation's memories can be told apart from another's. The id is yours to choose — use the conversation id you already have.
list_sessionslimit? (1–200)Sessions in this workspace, newest activity first.
delete_sessionsession_id, hard?Retire a session. Soft by default — its memories stay and it stops being listed. hard erases it, and has to be asked for by name.
list_spaceslimit? (1–200)The spaces this credential can see, with last-active times. whoami says which one you are writing to.

Query introspection

ToolArgsWhat it does
explain_querytextThe plan Brain would use, and what it expects to cost — without running it.
trace_querytextWhat each stage actually cost. Note this runs the query; it is not the free counterpart to explain_query.

The schema document is a DSL, not JSON

The commonest wasted turn against this server is an agent handing upload_schema a JSON object, because every other argument on every other tool is JSON-shaped. It is rejected with:

syntax error at 1:1: expected schema

What it wants is Brain's schema DSL:

namespace acme
define entity_type Person { attributes {} }
define entity_type Org { attributes {} }
define predicate works_at { kind: Fact subject: Entity<Person> object: Entity<Org> }

The namespace line must name this workspace's own namespace — which whoami reports. Call get_schema first to see what is already declared: upload_schema is additive, so redeclaring an existing type differently is a conflict rather than an update.

Size limits

Three caps, at three layers, and the first two are set so that the inner one fires first.

OptionTypeDefault / Env
remember(content)~256 KB · 262,144 chars

Enforced by the tool's own schema, so going over is an ordinary validation error naming the offending argument.

POST /mcp body1 MB

The HTTP backstop, for anything that slips past a schema. Answered as a JSON-RPC 413 whose message says to split the content.

JSON-RPC batch100 messages

A batch longer than this is refused by the transport with a 400 and Invalid Request: Batch must not exceed 100 messages. Nothing in the batch runs, so split a long batch rather than retrying it.

Why the inner cap exists at all

Over the body limit, Express's default handler answers with an HTML error page. An MCP client cannot parse that, so it raises a transport error — the agent sees the connection break rather than a tool result it can read, and one oversized remember looks like the server fell over. Both layers now answer in JSON-RPC, and the schema cap sits below the transport cap so the common case never reaches it.

Reading a tool failure

Every tool funnels failures through one renderer, so a condition reads the same whichever tool hit it — and comes back as an isError result, never a thrown exception, which an MCP client would report as a transport fault.

error: namespace acme has no LLM credential registered
code: llm_credential.missing http 409
retry: no — this call will fail identically until the cause below is fixed
fix: this workspace has no LLM provider key configured. Brain extracts typed
     facts and generates retrieval questions on every write, both of which
     need a provider key … a workspace admin needs to add an OpenAI or
     Anthropic key in the Arc Labs dashboard under Settings → Providers.
trace_id: 01JD…
ParameterTypeRequired
errorstringrequired

What happened, in the backend's own words.

codestringrequired

The stable handle plus the HTTP status. A code this server has not been taught is rendered (unrecognised) rather than passed through silently.

retry"never" | "soon" | "once"required

The line that changes agent behaviour. A server-sent retry_after overrides the generic wording with the delay actually asked for.

fixstringrequired

Who resolves it — the agent, the caller, or an operator.

trace_idstringoptional

Present when the backend sent one. The gateway withholds 5xx detail from the response on purpose and logs it under this id, so quoting it is the difference between "something broke" and a line an operator can find.

The retry verdict is the part worth caring about. Left to infer it, an agent either retries a terminal failure until it gives up and tells the user their data was lost, or abandons a transient one that would have succeeded a second later.

The two credential failures are not the same failure

They are one character apart and opposite in every way that matters:

CodeStatusRetryWho fixes it
llm_credential.missing409neverA workspace admin registers a provider key
llm_credential.unavailable503soonNobody — the broker was briefly unreachable

An agent that confuses them tells the user to go configure a key that is already configured, or silently retries a condition that will never clear. See Errors for the full taxonomy.

It understands both backends

brain-edge and the Arc gateway do not share an error shape — the edge sends {"error": {"code", "message"}}, the gateway an RFC 7807 problem document — and they barely share a vocabulary: twelve codes against eighteen, with three in common. The renderer parses both, so a failure is described the same way whichever you are pointed at.

Identity

Every request runs as the caller, and nothing about that is this server's decision. The caller's brain_… key goes to the backend verbatim as Authorization: Bearer; the backend resolves it to the (namespace, space) the key is bound to and runs the operation as that tenant — the same path the SDK and plain curl take. Rate limiting, metering and billing key off the same resolved scope, so a hosted deployment accounts per user without being told who anyone is.

Why there is no customer_id argument

Both backends scope by the key alone. The hosted gateway reads the x-brain-namespace / x-brain-space headers only for console JWTs and ignores them for API keys; self-hosted brain-edge ignores them too. A tool argument claiming to select a customer would be accepted, sent, ignored, and reported as success — a wrong answer that looks exactly like a right one.

Earlier versions of this server did exactly that, and held one shared service key — so every caller of a hosted deployment landed in that key's workspace while the surface read as if it isolated them. Per-caller credentials are what make the one-URL deployment correct; dropping the id argument is what stops it claiming to be correct in a second, contradictory way.

To check which identity a connection has, call whoami. It reports what the backend resolved, not what this server was configured with, so it cannot agree with a mistake.

Running one publicly

No shared secret and no network boundary required:

BRAIN_MCP_BACKEND_URL=https://brain-edge.internal brain-mcp

The server has no credential to fall back to, which is what makes it safe to expose directly: there is no ambient authority to reach. There is deliberately no env-var fallback on the HTTP path — a server-held key would make a client that forgot its header succeed as somebody, which is the one failure mode that is invisible in production, because it looks exactly like working.

Deliberately not exposed

Eight tenant routes have no tool, because an agent holding them is a worse deal than an agent without them. The line is not "is it a write" — entity merges, statement supersessions and schema drops are all writes and all tools, because each is recoverable, scoped to one record, or both. What stays out is what a confused or steered agent could use to leak a secret or lose something unrecoverably.

OptionTypeDefault / Env
PUT /v1/llm-credentialno tool

A tool that accepts a raw provider key invites a model to put one in a tool call, where it lands in transcripts and logs. llm_credential_status covers the read side; keys are managed in the dashboard.

DELETE /v1/llm-credentialno tool

Same reasoning, in reverse — an agent that can silently remove a tenant's key can stop extraction without anyone noticing, and that stops every write in the workspace.

POST /v1/llm-credential/testno tool

Also carries a raw key in the body. verify_llm_credential re-checks the key already registered, and sends no secret anywhere.

PUT /v1/schemano tool

Destructive whole-document replacement. upload_schema merges, so the worst an agent can do to a schema is additive.

POST / DELETE /v1/spacesno tool

No space verb takes a path parameter — all of them act on the caller's own space. So a delete is not "remove a space" but "erase this workspace", from one tool call, with no id to get wrong.

POST /v1/memories/vectorno tool

Takes a caller-computed embedding. An agent has none to supply.

GET /v1/subscribeno tool

Server-Sent Events. MCP tools are request/response, and no tool shape would honestly describe a stream.

force_drop_existingnot settable

Wholesale destructive schema replacement discards declarations and the rows bound to them. upload_schema cannot set it, so there is no tool that replaces a schema destructively.

None of these is reachable from the server's backend client either: a method with no caller is a destructive surface with no purpose.

`drop_schema_type` is the one destructive schema path that exists

It removes a single declared predicate or relation type, and its force flag is not a confirmation prompt: a type nothing uses drops without it, so passing force specifically consents to orphaning live rows. Those rows survive as plain memories that are no longer enriched from the typed graph — nothing is deleted, but the claims stop being queryable as claims.

Entity types are deliberately not droppable here at all: they are shared across workspaces, so there is no safe way to drop one from a single tenant's connection.

What the protocol does not give you here

RequestBehaviour
GET /mcp, DELETE /mcp405. Stateless mode has no server-initiated stream and no session to tear down. Tool-only clients never need either; a client that insists on the notification stream will not work.
Server-initiated notificationsNot available, for the same reason.
OAuthRemoved. See the warning above — the flag is now a startup failure.
x-api-keyNot read. Authorization: Bearer only.

MCP or the SDK?

Both speak the same surface, so this is not a capability question. It is a question of who decides when memory is touched.

MCP
SDK at a call site
Who calls
The model decides, from the tool descriptions
You decide, in code you wrote
Best for
Agentic clients whose loop you do not control
Application code where the loop is yours
Context cost
Tool definitions and results consume the agent's context
None — results are yours to trim
Failure mode
The model does not call the tool, and nobody notices
Your code did not call it, and a test can catch that

The last row is the one worth sitting with: a memory that never gets written looks identical to a conversation where there was nothing to write. A common production shape is MCP for reads and explicit SDK calls for writes — the model can ask what is known whenever it likes, and your code decides what is worth remembering. Nothing stops you doing both against the same workspace.

01
What to write

The decision MCP hands to the model, and the one worth taking back.

02
Identity by key

Why there is no scope argument on any surface, not just this one.

03
Every error code

The full taxonomy the four-line renderer draws from.

See also
The REST surface it frontsEvery route, with request and response shapes.LangChain insteadWhen the loop is a framework's rather than a model's.Multi-tenancyThe same per-key isolation, from your own code.

Was this page helpful?

OpenAI

Brain as the long-term memory layer behind the Responses API — the flat tool shape, the dispatch loop, where Conversations end and memory begins, and why identity must never come from a tool argument.

Switching to Brain

Moving from another memory layer — what ports mechanically, the four concepts that have no equivalent elsewhere, how Brain actually differs from mem0, Zep and supermemory, and a cutover plan that does not require trusting it on day one.

On this page

What it isInstallTwo transports, one rulestdio — the client owns the processRemote HTTP — one deployment, many usersConfigurationDeploying oneThe 49 toolsMemory — the core loopReasoningEntitiesGraphKnowledgeSchemaIdentityWorkspaceQuery introspectionThe schema document is a DSL, not JSONSize limitsReading a tool failureIdentityRunning one publiclyDeliberately not exposedWhat the protocol does not give you hereMCP or the SDK?
Suggest an editOpen in Playground