# AGENTS.md — using Brain as your memory over MCP This guide is for AI agents (Claude Code, Cursor, openclaw, custom MCP clients) consuming **INITE Brain** — a bitemporal, per-tenant knowledge-graph memory service on SurrealDB. Humans: start at [docs/getting-started.md](getting-started.md) instead. ## Connect Brain speaks MCP over **Streamable HTTP**, one endpoint per tenant: ``` POST https://brain.inite.ai/mcp # tenant from the credential POST https://brain.inite.ai/mcp/ # explicit; must match the credential Authorization: Bearer brain_ ``` Reach for the tenant-less form when all you have is a URL — an OAuth-discovered connector learns its tenant from the token's `org` claim, not from the path. `GET /mcp/health` answers unauthenticated. Harnesses with native remote-MCP support connect by URL + header. Harnesses that can only spawn stdio servers use the first-party shim [`@inite/brain-mcp`](../clients/brain-mcp/README.md): ```json { "command": "npx", "args": ["-y", "@inite/brain-mcp"], "env": { "BRAIN_API_KEY": "brain_…", "BRAIN_COMPANY_ID": "…" } } ``` Self-hosted: add `BRAIN_BASE_URL` (or `BRAIN_MCP_URL`). The shim (v0.2) is a transparent passthrough for tools AND resources (`resources/list`, `resources/templates/list`, `resources/read`), and bridges sampling in reverse — brain's `sampling/createMessage` reaches YOUR model, falling back to a server-side template when your harness doesn't advertise sampling. Auth, tenancy, scopes, and PII fencing are enforced server-side from the key. Key scopes decide what `tools/list` returns: `brain:read` → read surface; `brain:write` adds mutations; `brain:admin` adds GDPR forget. Two further scopes exist but are hosting-operator-only (granted via env-key config, never mintable through tokens): `brain:read_media` (media/biometric evidence — stricter than `brain:read_pii`, not implied by it) and `brain:platform_admin` (cross-tenant operator authority). ## Tool surface Read (with `brain:read`): | Tool | One-line semantics | | ------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `search_knowledge` | Semantic search over the graph; by default (`focus`) a few lines — only the facts the query is about, or the turn they came from when that is shorter, plus the links between them; `compact` (JSON, every fact, entity ids), `full` (ids, scores, trust keys); `asOf` for "what was TRUE on X" (valid time — a fact learned later still shows) | | `search_multi_hop` | Planner-LLM decomposes into ≤5 anchored hops; by default each hop's sub-query and the focus view of the evidence (`detail: "full"` for `finalEntityIds` + `supportingFactIds`); `synthesize=true` for a grounded answer | | `graph_retrieve` | Graph-first retrieval around named entities (1-hop neighbourhood); use when you already know WHICH entities | | `synthesize` | Hybrid search → citation-bearing answer (each claim ends `[factId]`) → verifier LLM; guardrails `strict`/`lenient`/`off`. By default the answer and its citations, or — with no answer — the focus view of the evidence as `evidence`; `detail: "full"` adds every retrieved hit | | `memory_diff` | Everything learned / retracted / superseded / forgotten between two ISO cursors `[from, to)` — "what changed since last conversation?" | | `get_entity_profile` | One entity at the gist level: with `userId`, its current state as beliefs (each attribute's value and what it replaced), the facts in dispute, and an index of every attribute with recorded facts. `compact` lists every current fact, one line per attribute (also the default when there is no belief about it); `full` is JSON with fact ids and externalRefs | | `get_entity_timeline` | The entity's history at the gist level: the scenes its facts were read from, oldest first, each with its gist and the entity's state changes in it, then one line per fact from no conversation (direct writes, documents). Without scenes, one line per recorded fact. `compact` (JSON with fact ids), `full` (sources, confidence) | | `summarize_entity` | One-line briefing; `styleHint='client_llm'` delegates wording to YOUR model via MCP sampling | | `get_competing_facts` | Unresolved same-predicate disagreements (COMPETING status) for an entity | | `detect_contradiction` | Dry-run the conflict resolver: "if I recorded this fact, what would happen?" (`INSERTED`/`SUPERSEDED`/`COMPETING`/`REJECTED`) | | `find_related_entities` | Entities connected via graph edges; here `asOf` cuts EDGES on knowledge time (as they were believed at T) — the one read surface where it is not valid time | | `match_procedure`, `list_procedures` | Procedural memory: reusable how-to recipes | | `search_communities`, `list_communities`, `find_entity_communities` | Graph community summaries (thematic clusters) | | `why`, `recall_decisions` | Code-memory: why code is the way it is; past recorded decisions | | `get_source_reputation` | Learned trust profile of a source vertical | | `read_media` | A stored image (image block, ≤1568 px) or recording (audio block, ≤10 MB) by the evidence asset or fragment id a fact cites; a fragment id returns only its part (the image region or the recording span). Listed only to a key holding `brain:read_media`; runs the raw-evidence checks of the REST raw route (a pack's consent to serve raw evidence; every read audited) | | `workspace_status` | Which tenant this connection writes to, what is already in its memory, and `nextSteps` — the setup actions that would change something. First call after connecting | | `rename_workspace` | Name the workspace (`brain:write`). Offered only while it has none, and gone once it does | | `get_fact` | One fact as stored: statement, validity, source attribution, lifecycle (`retracted: true` still resolves), `groundingStatus` (`grounded`/`ungrounded`; absent = legacy row) and `assertion` (`stated`/`inferred`/`hypothesis`/`confirmed`). Registered when the server runs `FACTS_API_ENABLED` | | `get_fact_provenance` | Why a fact is remembered: the verbatim grounding turns (with char-span quotes when stamped); plus `derivedFacts`/`closure`/`supportEdges` on servers running the closure/support-graph read flags. Same `FACTS_API_ENABLED` gate | | `relationship_context` | Before speaking to a person: their boundaries, tone, open threads, commitments made to them (overdue first), their state as they last said it (`known: false` once past its span) and what helped — from their own memory, each with a factId. With `brain:read_pii` and the person's consent to inference, `affectSignals`: how they have seemed to feel, read from their words — recent signals with the words, their own baseline, last week against it, a weekly trend; signals, never their state. Under a pack's `safetyMonitoring`, `safety`: risk of suicide or self-harm read from their words (concern / urgent, with the words, `lastUrgentAt`) for your crisis protocol — record what you show them with `POST /v1/users/:userId/safety-events`. Listed only for a tenant with the `relationship` pack | MCP resources (droppable into context without a tool call): `brain://entity/` (profile) and `brain://entity//timeline`; with the `relationship` pack, `brain://relationship/`. Write (adds with `brain:write`): `record_fact` (accepts `conversationId` + `evidence[]` — see grounding below), `link_entities`, `retract_fact`, `record_procedure`, `retire_procedure`, `record_feedback`, `ingest_document` (Source→Indexer→Candidates pipeline; prefer over `record_fact` for anything longer than one claim; accepts `toolObservationRef: tool_observation:` to close the tool result → document → fact provenance loop under `TOOL_OBSERVATIONS_ENABLED`), `record_decision`, and `upload_media` (an image, recording or document as base64 into the evidence plane: kept, scanned, read by the processors the workspace consented to, and remembered with the file as provenance; on a server running `EVIDENCE_BLOB_UPLOAD_ENABLED`; the JSON body cap, 1 MB by default, bounds the file, so larger ones go over `POST /v1/ingest/evidence-blob`). Admin (adds with `brain:admin`): `forget_entity` — GDPR hard-delete with a synchronous cascade and tombstones. Harness work (adds with `brain:write`, on a server running `EXTRACTION_SOURCE=harness`, for a workspace set to harness, or for a workspace whose plan does not include server-side models): `take_memory_work`, `submit_memory_work` — see [Harness mode](#harness-mode). ## Harness mode **On a free plan.** Server-side models are part of paid plans. When your workspace's plan does not include them, `workspace_status` shows `serverModels.source: "not_included"` and `synthesize` answers `reason: "model_unavailable"` with `notice.code: "platform_models_not_included"` and the evidence in `results`. Nothing is lost: the reading the server would have done waits for you. Work it the same way as below with `take_memory_work` / `submit_memory_work`, and answer questions yourself from `search_knowledge` results. A workspace running `EXTRACTION_SOURCE=harness` spends no model key of its own, anywhere. Everything its server would have asked a model, it leaves for you, and you answer with your own model. The server can run with no `OPENAI_API_KEY` at all, on the local `bge-m3` embedder. Writes work as usual. `ingest_document`, the mention routes and the plugin's capture store text raw, and it is searchable at once through the episode lanes. The rest comes in batches: | `kind` | What you read | What the server does with your reply | | --------------------- | ------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------- | | `predicate_semantics` | new attributes: can a subject hold one value or several | sets the attribute's policy, so the next value supersedes or adds | | `media_reading` | images (sent as image blocks): their text and what they show | stores the reading with the image and reads it into facts that cite the image | | `extraction` | stored turns and documents, with the memory context | grounds every value against the text, resolves entities, commits | | `fact_resolution` | each new fact beside the memory facts most like it | same → corroborates; replaces → closes the value that holds from the earlier time (whichever arrived first); contradicts → both competing | | `entity_match` | pairs of entities whose names are close, with their facts | links the same thing (`identity_of`), or remembers "different" | | `fact_conflict` | pairs of competing facts, with the subject's other facts | supersedes the loser and makes the winner the current value | | `fact_corroboration` | pairs of facts that may state one thing in two wordings | records the second as corroborating the first | | `scene_summary` | conversation scenes as transcripts | stores the gist, memory value, state changes and entity mentions | | `belief_statement` | remembered states (subject, attribute, value) | replaces the template sentence with yours | | `kind` | What you read | What the server does with your reply | | --------------------- | --------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------- | | `predicate_semantics` | new attributes: can a subject hold one value or several | sets the attribute's policy, so the next value supersedes or adds | | `extraction` | stored turns and documents, with the memory context | grounds every value against the text, resolves entities, commits | | `fact_resolution` | each new fact beside the memory facts most like it | same → corroborates; replaces → closes the value that holds from the earlier time (whichever arrived first); contradicts → both competing | | `entity_match` | pairs of entities whose names are close, with their facts | links the same thing (`identity_of`), or remembers "different" | | `fact_conflict` | pairs of competing facts, with the subject's other facts | supersedes the loser and makes the winner the current value | | `fact_corroboration` | pairs of facts that may state one thing in two wordings | records the second as corroborating the first | | `scene_summary` | conversation scenes as transcripts | stores the gist, memory value, state changes and entity mentions | | `safety_reading` | a person's own turns, with context | keeps each risk signal (concern / urgent) whose quote is the person's exact words; marks the turns read | | `affect_reading` | a consenting person's own turns, with context | keeps each reading whose quote is the person's exact words, unless they contested it; marks the turns read | | `belief_statement` | remembered states (subject, attribute, value) | replaces the template sentence with yours | 1. When you are idle (between tasks, at the end of a session), call `take_memory_work`. `{work: null}` means nothing is waiting, so stop. Kinds come in the order above: attributes, then facts and how each new fact relates to memory, because the judgements and summaries read them. `kinds` limits a call to some of them. 2. Otherwise `work` holds `kind`, `systemPrompt`, `userContent`, `schema` (the JSON schema of the reply), `items` (how many turns, pairs, scenes, attributes or beliefs the batch covers), `token` and `expiresAt`. Answer it with your model: `systemPrompt` as the system message, `userContent` as the user message, and a JSON object matching `schema` as the reply. A `media_reading` batch's images arrive as image blocks after the JSON text of the result, in item order (`i1` is the first); give them to your model with the user message. An image is offered only when a pack's current modality consent covers reading images into text. Batches number their items (`p1`, `s1`, `q1`, `b1`, …). Answer each item once, by its number. For extraction, copy values verbatim where the prompt says so: the server drops anything the text does not hold, exactly as it does for its own model. 3. Call `submit_memory_work({token, result})` before `expiresAt`. It returns counts for the batch. - An item whose evidence changed since you took it is counted `stale` and comes back later. Submitting a batch twice changes nothing the second time. - An extraction token claims its documents. If you never submit it, they return to the queue on their own after the claim window (`INDEXER_RUN_STALE_MINUTES`, 30 min). - A `409` on extraction means the predicate vocabulary moved since you took the work; take it again. 4. Repeat until `work` is null. Pass the same `userId` you write with. A tenant-global call sees only tenant-global memory, and a user's call sees only that user's. To answer a question, use `search_knowledge` (facts with their relations, so one call usually covers a two-hop question), `get_entity_timeline` (what held before: superseded values with their dates) and `get_fact_provenance`. Then answer from that evidence yourself. In this mode `synthesize` makes no model call: it returns no answer, with `reason: harness_mode` and the evidence in `evidence` (search_knowledge's focus view). A workspace that has spent its daily model budget (`LLM_TENANT_DAILY_TOKEN_BUDGET`) gets the same shape with `reason: model_budget` until the next UTC day. ## When the server's models are unavailable If the server's model provider refuses a call (no credit, a revoked key, a rate limit or an outage), `synthesize` answers `reason: model_unavailable` with `degraded` (`generator` or `verifier`) and a `notice` whose `code` is `server_models_unavailable`. This is not "the memory does not know": - Do not tell the user the memory has nothing on the subject. - With `degraded: ["generator"]` there is no answer. Answer from the evidence yourself (`evidence` in the default view, or call `search_knowledge`), as in harness mode. - With `degraded: ["verifier"]` and an answer (lenient mode), the answer is unchecked. Check it against its citations, or say it is unverified, before you rely on it. - `search_knowledge` may carry the same `notice` beside `degraded: ["vector_leg"]`: the results are keyword matches only, and retrying will not bring semantic matches back until the provider is fixed. - `about_brain` and `workspace_status` report `serverModels.state` (`ok` or `degraded`), per capability (`embed`, `chat`), and `since`. - The fix is on the operator's side: a topped-up or new provider key, the tenant's own provider key (BYOK, planned in #945 phase 3), or connecting your agent in harness mode, which needs no server model at all. ## Memory semantics you must know - **Facts vs episodes.** Brain ingests raw conversation/document _episodes_ and derives typed _facts_ (entity, predicate, object, confidence) from them. Reads serve facts; provenance points back at the raw source. - **Bitemporal by default.** Every fact carries valid time (`validFrom`/`validUntil` — when it held in reality) and knowledge time (`recordedAt`/`retractedAt` — when brain learned/retracted it). Default reads = "actual now". `asOf` on search/synthesize/`get_entity_profile` asks "what was TRUE at T" — VALID time: `validFrom <= T < validUntil`, a retraction dated before T hides the fact, and a fact brain learned after T still shows (a backdated fact is not disappeared by a late ingest). It is NOT a knowledge-time snapshot; that exists only on `GET /v1/entities/:id?recordedAt=` and the entity timeline. See [docs/bitemporal-semantics.md](bitemporal-semantics.md) for the per-surface table. - **Conflicts are explicit.** A new fact meeting an overlapping same-predicate prior is auto-superseded, or parked as COMPETING when too close to call — never silently last-write-wins. Preflight contested writes with `detect_contradiction`; inspect stalemates with `get_competing_facts`. - **Per-user scope is fail-closed.** Read/write tools accept `userId`. Omitting it returns tenant-global facts ONLY — a user's personal memory is never mixed in unless you ask for that user. Always pass `userId` when acting for a specific person. - **Retraction ≠ forgetting.** `retract_fact` closes a fact in knowledge time — auditable, history kept, visible in timelines and `memory_diff`. `forget_entity` (admin, reasons incl. `gdpr_request`) is a hard delete; only tombstones remain. Do not use forget for "this fact is now wrong" — record the new fact or retract. - **Provenance is first-class.** Every fact is attributable: `get_fact` / `get_fact_provenance` (and their REST twins) return the source chain ([docs/fact-provenance-api.md](fact-provenance-api.md)); `search_multi_hop` returns supporting fact ids (`detail: "full"`); `synthesize` cites `[factId]` per claim and a verifier judges support. - **Ground your writes.** `record_fact` accepts `conversationId` (the conversation the fact was observed in) and `evidence[]` (≤10 typed pointers: event/message/conversation/url/document/commit/other). Naming the observation marks the fact **grounded** — servers stamping `groundingStatus` (EVIDENCE_GROUNDING_STAMP) can exclude ungrounded claims from consolidation and from strict serving. A bare `record_fact` is permanently observation-free; always pass what you have. - **`evidenceCitations` is a SEPARATE array from `citations`.** `synthesize` answers carry fact citations in `citations[]` (`c.factId`); episode- or fragment-grounded claims arrive in `evidenceCitations[]` (episode arm: `episodeId` + optional verified `span`; fragment arm: `fragmentId` + `assetId` + `capability` + rendered `excerpt`). Never flatten the two — consumers reading `factId` off an evidence citation (or vice versa) will corrupt their provenance handling. - **Abstention is a feature.** `synthesize` in `strict` mode returns `null` rather than an unsupported answer. Treat `null` as "brain does not know", not as an error to retry around. Beyond the classic reasons (`no_results`, `low_coverage`, verifier verdicts) there are two evidence-plane reasons with DIFFERENT remedies: `ungrounded_evidence` (every cited fact is `groundingStatus='ungrounded'` — remedy: ground the claims, not "the memory doesn't know") and `evidence_capability_unmet` (a claim's predicate requires non-text evidence — visual/audio/document — and no cited evidence of that capability exists; remedy: attach/verify the media). - **Cached answers are legitimate.** A `synthesize` response with `cached: true` was served from the fact-lifecycle-gated answer cache: citations were re-validated against live fact rows at serve time, and `results` is EMPTY because retrieval never ran. Do not treat the empty `results[]` as "no evidence". - **Your tool calls may be observed — content-free.** Under `TOOL_OBSERVATIONS_ENABLED` the server records per-call observation rows (tool name, argument/result DIGESTS, ok flag, duration — no content unless the operator additionally opts into a sanitized 512-char excerpt). Denied calls record nothing. Reference an observation from `ingest_document.toolObservationRef` to link derived documents back to the tool result they came from. ## Common mistakes 1. Omitting `userId` and concluding a user's memory is empty (fail-closed scope, see above). 2. Passing `asOf` expecting a knowledge-time snapshot ("what did we know at T") — on search it is VALID time; knowledge time is `recordedAt` on the entity profile and timeline. (On `find_related_entities` alone, `asOf` is knowledge time for edges.) 3. Re-deriving "what changed" by diffing two full dumps — use `memory_diff`; windows are half-open, adjacent windows never double-count. 4. Recording multi-claim prose via `record_fact` — use `ingest_document` and let extraction + conflict resolution do the work. 5. Treating COMPETING facts as noise — they are unresolved disagreements awaiting adjudication; surface them to the user when relevant. ## Honesty note on eval claims When you cite brain's memory-accuracy numbers, cite them with the protocol: strict binary judge, own full-context baseline, paired stats, held-out split ([docs/eval-protocol.md](eval-protocol.md)). Do not quote numbers from other systems' self-reported benchmarks as comparable — most published memory scores use lenient judges and are inflated; ours are deliberately hard to inflate. The in-repo memory-fitness numbers come from the mechanical, judge-free battery (`pnpm eval:memory-fitness`, `pnpm eval:state-transitions` — see [docs/eval-methodology.md](eval-methodology.md)). ## More - API reference: [docs/api.md](api.md) · data model: [docs/data-model.md](data-model.md) - Domain packs (tenant ontology extensions, pack-declared MCP tools): [docs/domain-packs.md](domain-packs.md), [docs/mcp-pack-tools.md](mcp-pack-tools.md) - Per-user rolling profile: [docs/user-profile-api.md](user-profile-api.md) - Operations & self-hosting: [docs/operations.md](operations.md) License: AGPL-3.0-or-later.