BrainLLM
Give Claude a memory that survives the session.
Self-hosted memory for LLMs in TriliumNext Notes, structured by the server and editable by you, served over the Model Context Protocol.
Site · Connect to Claude · How it works · Docs · Privacy
What is BrainLLM?
LLMs forget. Every session starts from zero: who you are, what you're working on, what was decided yesterday, what went wrong last week. BrainLLM fixes that.
BrainLLM is an MCP server that gives an LLM a real, persistent memory — stored in TriliumNext Notes, a mature open-source knowledge base you self-host and own. The model opens each session by loading who you are and what's live, writes durable facts the moment they surface, wires knowledge together as a typed graph, and closes each session with a log, a diary entry, and a database backup. The next session picks up exactly where the last one ended.
It's a single Bun/TypeScript service with two dependencies (the MCP SDK and Zod), speaking to Trilium exclusively through its public ETAPI. Your memory lives in your Trilium instance — inspectable, editable, and portable, never locked inside a vendor's black box.
Who it's for
Anyone running an LLM as a long-running collaborator, not a one-shot Q&A tool — across coding, research, personal knowledge management, or day-to-day operational tracking — who wants that collaborator to actually remember: who you are, what's in flight, what was decided, without you re-explaining it every session. If you're comfortable self-hosting one small service and a Trilium instance, BrainLLM turns "the model forgot everything again" into a solved problem. It works with any MCP-capable client (Claude Desktop, Claude Code, or anything else speaking MCP), not just one product.
From experiment to open source
BrainLLM began in February 2026 as a personal experiment: could an LLM operate a real, self-hosted memory reliably enough to be trusted as its own memory — orienting, writing, connecting, and closing sessions without a human doing the filing? Through sustained daily, production use the answer held. The design has settled, the failure modes have been found and fixed, and the project has graduated from experiment to something efficient and stable enough to share — so it's now open source. It still runs the author's own sessions every day; what you're reading is the same code, not a demo. It also still carries the shape of one person's daily use — see Adapting to your environment for exactly what that means and what to change.
The core principle
The model supplies content. The server owns form.
Placement, naming, labels, deduplication, relation bookkeeping, lifecycle aging, archival, date stamping, HTML sanitization, backups — and structure itself — are all deterministic server policy, never delegated to the LLM. The model never chooses a parent note, never sets a label, never checks for duplicates, never stamps a date. That division is what makes the memory reliable: every guarantee is enforced at the tool layer, not requested via prompt.
Design highlights
- Structure is enforced, not requested — every content kind has a canonical structure, served by
template()and held on write: a new thread requires its goal, thread/diary/session entries open with an identification line (which LLM, which environment, which session type), threads carry exactly one Resolution (owned byresolve()), duplicate section headings are detected, andLast updatedstamps are server-maintained. - Domains born complete — creating a knowledge domain creates its book and its canonical Sources note (marker legend, stamp, grouped source list, revision table), so every claim has a sourcing home from the first write.
- A visible graph —
graph()renders the whole relation graph (or any note's neighborhood) as a Mermaid flowchart, maintained as a native Trilium note. - Byte-preserving artifacts — text is UTF-8, while binary content uses strict standard base64 in the tool contract and raw bytes on the wire; binary reads return an explicit MIME/base64 envelope instead of replacement characters.
- One-call day orientation —
day()serves the previous session, its change log and everything touched since in a single call. - Two thread shapes — a thread is a dated journal (one child per active day) or a titled collection (one maintained note per item, e.g. an ideas list), chosen once with
shape=at creation. - Timeless notes, dated records — knowledge, information and thread books hold no state or history (only a domain's Current State does);
maintain(deep=true)flags dated prose that creeps in. Every note except a log carries an icon, set by kind and backfilled by the sweep. - Resilient plumbing — every backend call is timeout-bounded with retry on idempotent reads; routine core writes are idempotent or duplicate-guarded, while full-mode raw overwrites remain explicit; content surgery survives the editor's own HTML rewriting; renaming a domain cascades to everything inside it; the maintenance sweep heals drift it finds.
- Multi-agent by default — all write-classified tools serialize behind a process-wide FIFO lock, so two agents (an interactive session and an automated run, say) writing through one hosted instance queue in arrival order instead of racing; reads stay fully parallel. Deletion catch-up in the daily log keeps a note deleted after its day's close from vanishing without a trace — and its window is configurable (
deletionCatchupDaysin the lifecycle policy), defaulting to Trilium's 7-day retention. - Ask in prose, split on a seam —
consistency(subject="…")finds every note asserting about a fact however it is phrased, no regex guessing;consistency(pattern, staleAfterDays=N)surfaces figures held in exactly one untouched note, the ones that rot silently because nothing disagrees with them, and skips sessions and diaries, which are history rather than claims;diff(since="today")reviews every note a session changed in one call;revise(find="Phase 2", within="tr")edits, inserts or removes a table row named by a few words inside it;read(ids=[…])batches a multi-note orientation into one round trip — each note's size up front, or a singlesection=across them; andsplit(noteId, sections=[…], into="…")is the write half of the oversized-note problem — it lifts whole sections into a new note and leaves a pointer back. Information notes can carry a#mandatemarker so a scoped session finds the one note it must obey without reading every note's prose. - A distinct connector identity — hosted instances advertise BrainLLM and their own origin, with same-origin PNG/SVG icons, explicit page favicon links and a real multi-size ICO. The canonical mark is shared across the connector, consent pages and public assets.
- Preview changes and measure coverage —
revise(noteId, edits=[…], dryRun=true)shows sequential match counts and sanitized before/after content with no revision, labels or gate writes. Revision failures stop content overwrites.consistency()reports read failures and scan coverage; case-insensitive comparisons retain spelling variants without false conflicts. Incomplete scans cannot establish absence or unanimity. - Registers close in one call —
revise(find, within="tr", mode="remove", closure={thread, body})removes a register row and records its closure in that thread's entry for the day,closure={note, table?, row?}moves a row into an explicitly selected register table; destination cells must match the table's shape. Destination-first ordering preserves recoverability, andmoves=[{find, row?}]batches closures with preflight and per-row progress, andappend={table, row}adds a row with no anchor to find;within=also accepts a row as a reader sees it ("Phase 2 | Claude | Open"), and a table row whose cells disagree with its header is flagged at write time and bymaintain(deep). - Bulk edits and lighter receipts —
revise(find, within="tr", mode="remove", all=true)removes every row an anchor sits in, in one write and previewable withdryRun=true;remember(kind="sources", revision=[{source, from}])renames a Sources key when a source moves instead of adding a second row; a dated-thread append returnspreviousRun, its author's previous block and run number;read(ids, sizes=true)plans a bulk read from sizes and section sizes alone; anddiff(since="today", summaryOnly=true)lists what changed without the lines. - Records you can prove — sessions, diary entries and dated thread entries are append-only, and now verifiably so: every
close()seals its day's records into a digest chained to the previous day's, andmaintain(deep)reports any sealed record that was rewritten afterwards. Appends stay legal; edits to history do not go unnoticed.
How it works
At bootstrap, BrainLLM builds a five-area tree in Trilium. Every note the tools create is typed, labeled, dated, and placed by server policy:
BrainLLM (#brainLlmRoot)
├── 👤 Master Biography · Goals · Preferences (the user — maintained singletons)
├── 🤖 LLM Responsibilities · Protocols · Self-correction · Diary/ (the assistant's self-model + daily diary)
├── 🗂️ Memory Sessions/ · Threads/ (daily session logs + multi-session work)
├── 📚 Knowledge Master/ · Domains/<domain>/{ Sources, info } (learned facts beyond/contra training)
└── 💡 Insights Logs/ · Graph · Claims (the brain's record of itself)
| Note class | Kinds | Behavior |
|---|---|---|
| Singletons | biography, goals, preferences, responsibilities, protocols, selfcorrection (+ each domain's Sources note) | Exactly one maintained note; edited in place; hold current-state truth |
| Dated records | diary, session, log | One per calendar day; every write lands as a timestamped addendum block — chronology is the point |
| Collections | thread, user, information, domain | Titled notes, deduplicated by normalized title within their scope |
A session follows an enforced protocol: start() orients (who you are, live threads, what changed since last time) → the model works, writing durable facts as they surface → session() → addendum() → maintain() → remarks() → diary() → close() commits the log, regenerates the daily change log, and triggers a DB backup. The pre-close gate is enforced in code: close() refuses until every step actually ran, in order — narrating "I did the steps" doesn't count, only tool calls do. The gate is durable, written to the session note rather than held in memory, so it survives a restart mid-session and behaves the same on stdio and HTTP. A session that wrote no content gets a light close: nothing to fold or sweep, so close() asks only for session(), remarks() and a short diary().
Orientation is deliberately cheap. start() returns your singletons as section headings — enough for the model to know what the brain holds — and it pulls the one section that matters. Serving the entire self-model on every session meant a one-line question cost the same as a day's work; start(depth="full") is still there for the sessions that genuinely need it.
Knowledge is a typed graph: a closed vocabulary of 16 relations (extends, contradicts, supports, partOf, supersedes, corrects, …), wired by connect() or at creation, traversed by explore() (links / backlinks / neighborhood / shortest path), rendered by graph(), and audited by maintain(deep), which heals duplicate edges and flags what a note application would never think to look for: orphaned notes, stale content, duplicate titles, structural drift inside a note, bodies past the read ceiling, stubs that were labelled and never written, titles carrying a date (which defeats dedup-by-title), threads heavy enough to want consolidating, Sources notes whose verification table was never filled in, and bodies carrying doubly-escaped markup. Most of it is computed from note properties server-side rather than by reading bodies, so the report is complete rather than truncated. Findings can be acknowledged (maintain(ack=[…])) so a flag you have judged correct goes quiet until that note's content actually changes — a warning that reappears every run and is correctly ignored every run trains you to skim the list.
Quick start
Prerequisites
- Bun v1.0+
- A running TriliumNext instance (desktop app or server)
1. Install and build
git clone https://github.com/miisodev/BrainLLM
cd BrainLLM
bun install
bun run build
2. Get an ETAPI token
Or skip this step. Set TRILIUM_PASSWORD instead of TRILIUM_ETAPI_TOKEN and BrainLLM mints a token itself on first start, caching it beside brainllm.json so restarts reuse it rather than creating a new one each time. This is the easiest path for a container deploy, where there's no terminal to run a setup command in.
To do it explicitly instead, either let init mint one:
TRILIUM_BASE_URL=http://localhost:8080 TRILIUM_PASSWORD=your-trilium-password bun run init
It caches the token beside brainllm.json with owner-only permissions and does not print the secret. If you explicitly need a copy, run bun run init -- --show-token; the CLI is idempotent and adopts an existing #brainLlmRoot instead of creating a duplicate tree. Or create one by hand in Trilium: Options → ETAPI → Create token.
3. Configure your MCP client
For Claude Desktop, add to claude_desktop_config.json (see config.example.json for a complete example including remote):
| Platform | Path |
|---|---|
| Windows | %APPDATA%\Claude\claude_desktop_config.json |
| macOS | ~/Library/Application Support/Claude/claude_desktop_config.json |
| Linux | ~/.config/Claude/claude_desktop_config.json |
{
"mcpServers": {
"BrainLLM": {
"command": "bun",
"args": ["run", "/absolute/path/to/BrainLLM/dist/index.js"],
"env": {
"TRILIUM_BASE_URL": "http://localhost:8080",
"TRILIUM_ETAPI_TOKEN": "your-etapi-token-here"
}
}
}
}
For Claude Code, the same server block works in .mcp.json. A schema-valid MCPB manifest (manifest.json) is included for hosts that support custom Bun commands, but BrainLLM still requires Bun and this repository does not yet publish a .mcpb one-click artifact.
4. Bootstrap the brain
Restart your client and ask Claude to run bootstrap — it builds the five-area tree (each area engraved with its purpose), writes brainllm.json, and is active immediately. Or from the CLI:
TRILIUM_BASE_URL=http://localhost:8080 TRILIUM_ETAPI_TOKEN=your-token bun run init
5. Teach the model to operate it
Install the operational skill — the document that teaches Claude to treat BrainLLM as its own mind rather than a filing cabinet:
# Claude Code / Cowork skills directory (macOS/Linux)
cp -r skills/brainllm ~/.claude/skills/brainllm
# Windows PowerShell
New-Item -ItemType Directory -Force "$env:USERPROFILE\.agents\skills" | Out-Null
Copy-Item skills\brainllm "$env:USERPROFILE\.agents\skills\brainllm" -Recurse -Force
For clients that take a skill upload (claude.ai), use brainllm.zip from the latest release: it is the same skills/brainllm/ folder, zipped.
Then start a session. The model calls start(), orients, and operates the brain natively from there.
The tool surface
All tool returns are structured JSON. User-input mistakes return informational errors ({error, detail, hint}) the model can read and self-correct from; every read/write/search tool includes a free relations snippet; all writes are retry-safe.
Why the tools are named the way they are
The naming is a readability feature for you, not a style choice. Most MCP clients show you the name of each tool call as it happens. BrainLLM's tools are named as plain-English verbs for what is happening to your memory — remember, recall, revise, resolve, forget, connect, maintain — so that the call log reads as a description of what the model is doing in your brain, without you having to know the schema or open Trilium to find out.
The alternative, which most servers pick, is to name tools after the API underneath: create_note, patch_note, update_attribute. That tells you a row changed. It doesn't tell you the model recorded a decision, corrected something it previously believed, or closed a line of work — and those are the things you actually want to see scroll past.
Read this way, a session is legible at a glance:
| You see | What it means |
|---|---|
start → day |
Orienting: loading who you are, what's open, what changed since last time |
remember · diary |
Writing something down — a durable fact, or the model's own daily record |
recall · domain · outline |
Looking something up before answering, rather than answering from training |
revise · resolve · forget |
Changing, completing, or archiving something that already existed |
connect · graph |
Wiring a relationship between two things it noticed |
maintain · addendum |
Housekeeping — aging, structural drift, folding pending edits in |
remarks → close |
Wrapping up: reflecting, then committing the session log |
Three conventions keep that legible as the surface grows:
- Verbs for actions, nouns for surfaces.
rememberwrites;knowledgereads. If a tool name is a noun, it only ever reads. <surface>/<surface>_recallpairs. The bare name reads a surface in full; the_recallsuffix skims it. Seeingmemory_recallrather thanmemorytells you the model chose the cheap read.- Destructive verbs say so.
forget,detach,delete_*are never spelled as something softer, so an irreversible call is never disguised as a routine one.
The full mode tools deliberately break this convention — they are named after the raw Trilium primitives (create_note, patch_note, delete_attribute) precisely so that a raw, guard-free operation is visibly different in the log from a brain-aware one.
Tool permissions
Every tool declares whether it reads, writes, or destroys, so your client can group them and you can grant permission per group instead of per call. Every tool also carries a human-readable title ("Edit a note", "Search the brain") for permission prompts and directory listings. The current full-mode split is 34 read-only · 31 write · 13 destructive (core mode is 23 read-only · 17 write · 5 destructive); revise, label and connect count as destru
