Install
$ agentstack add mcp-sandeep84397-agent-brain ✓ scanned · ✓ verified, works with Claude Code, Cursor, and more.
Security review
✓ PassedNo issues found. Passed automated security review. · v0.1.0 How review works →
- ✓ Prompt-injection patterns
- ✓ Secret / credential exfiltration
- ✓ Dangerous shell & filesystem operations
- ✓ Untrusted network calls
- ✓ Known-malicious package signatures
What it can access
- ✓ Network access No
- ● Filesystem access Used
- ✓ Shell / process execution No
- ✓ Environment & secrets No
- ✓ Dynamic code execution No
From automated source analysis of v0.1.0. “Used” means the capability is present in the source — more access means more to trust, not that it’s unsafe.
Verified badge
Passed review? Show it. Paste this badge into your README, it links to the public security report.
Reliability & compatibility
Declared compatibility
Compatibility is declared by the source manifest. End-to-end runtime verification is coming, see below.
We're building live execution health for every listing: tool-call success rate, median latency, uptime, and last-checked timestamps, measured, not self-reported. It isn't live yet, so we don't show numbers we can't stand behind.
How agent discovery & health will work →About
Agent Brain
Enforced, persistent decision memory for AI code agent teams — that survives context compaction. Agents log decisions and outcomes, learn from past rejections, and resume their pending roadmap after a /compact instead of re-researching it. Hooks make it mandatory (not "stored and hoped for"). And code reads route through SAN compression (~80% fewer tokens, tokenizer-measured) so the context window fills slower in the first place.
Works with any MCP (Model Context Protocol)-compatible agent: Claude Code, Cursor, Windsurf, Cline, Continue, etc. Agent templates (.md files) are Claude Code specific — the MCP server itself is universal.
Contents
- [What This Does](#what-this-does) · [Features](#features)
- [Quick Start](#quick-start) — install in 2 minutes
- [How To Use It](#how-to-use-it) — the agent loop, a worked example, what you get
- [Architecture](#architecture) — what lives where, [performance & internals](#performance--internals)
- [MCP Tools (21)](#mcp-tools-21) — the agent-facing API
- [Agent Team](#agent-team) — bundled role templates
- [Model Routing](#model-routing-quality-per-cost) — right model per phase, two-strikes escalation, plan handoff
- [Brain Protocol](#brain-protocol) — the enforced decision loop
- [SAN Protocol](#san-protocol) — code compression: is it worth it, measuring savings (
token_savings) - [SAN Setup](#san-setup) — turning SAN on, model choice, other platforms
- [Adaptive Warnings](#adaptive-warnings) · [Web Dashboard](#web-dashboard-live-visualization) — 3D office, decisions browser (live feed), SAN search trace
- [Verification](#verification) · [Requirements](#requirements) · [Configuration](#configuration) · [Customization](#customization)
What This Does
AI coding agents start fresh every session: no memory of past decisions, no learning from rejections, no cross-agent knowledge sharing — and they burn tokens re-reading the same source files task after task. Agent Brain fixes both:
- Memory — decisions, outcomes, and review feedback persist across sessions and agents:
Agent → pre_check() → "WARNING: similar approach was rejected last week"
Agent → log_decision() → records what you decided and why
Agent → does work → PR created
Reviewer → log_outcome() → "rejected: violates DIP (dependency inversion)"
Next time, any agent → pre_check() → sees that rejection → avoids the mistake
- Cheap code reading — the optional [SAN protocol](#san-protocol) compresses source files to ~17-27% of their original tokens (81% saved, tokenizer-measured), and [
token_savings](#measuring-your-savings-token_savings) shows you exactly how much it saved, per session, in numbers and %.
Features
| Feature | What it does | |---------|-------------| | Decision Memory | Log decisions, outcomes, feedback. Persists across sessions. | | Pre-Check Warnings | Before starting work, see past failures in the same area. | | Fuzzy Matching | "Rate limiting on signup" finds "rate limiting on login" rejection. | | Code Bridge | Link decisions to code symbols: "Show me all decisions that touched AuthService." (Richer with the optional code-review-graph MCP server; works standalone too.) | | Agent Scorecards | Acceptance rate, trends, top rejection categories per agent. | | Adaptive Warnings | Agents with high rejection rates get stricter pre-check warnings. | | Team Dashboard | All agents at a glance — for project managers. | | SAN Protocol | Compress code to ~20% of original tokens (81% saved, measured). Full codebase fits in context. | | Token Savings Tracker | [token_savings](#measuring-your-savings-token_savings) reports tokens saved this session / today / all-time, with %. | | Enforcement Hook | Code edits are blocked until the agent logs a decision — memory actually gets populated. | | Survives compaction | SessionStart hook re-injects the pending roadmap after /compact so the agent resumes instead of re-researching. [Details](#surviving-compaction-the-amnesia-fix) | | Relevance search | query_decisions(query="…") ranks by topic relevance, not just recency; get_roadmap returns open work in one call. | | SAN as default read path | Hooks on both Read and Bash route raw code reads/dumps to get_san (per-file nudge, optional hard-block), so agents actually use SAN instead of cat/Read. A tool ladder (find→read→grep-literal→edit) is auto-installed to CLAUDE.md. [Details](#making-san-the-default-read-path) | | Records & pruning | Browse every decision as dated markdown; prune old/resolved ones (dry-run first, archived not deleted). Keeps the brain lean without losing the lessons. [Details](#managing-what-the-brain-remembers) | | Live decisions web view | A /decisions browser that streams decisions in real time as agents log them — filter by repo/area/agent/outcome, search, color-coded. [Details](#decisions-view-decisions) | | SAN search trace | A /san view that shows how a query finds code through SAN — index → content → block → src: line range, live. [Details](#san-search-trace-san) |
Quick Start
git clone https://github.com/sandeep84397/agent-brain.git
cd agent-brain
chmod +x setup.sh
./setup.sh
The setup wizard will:
- Create a Python venv and install dependencies
- Prompt for your repo paths (or use the template config)
- Register the MCP server globally with Claude Code
- Install the brain hooks (decision-gate, amnesia re-inject, Read/Bash→SAN routing)
- Add the SAN tool-ladder to
~/.claude/CLAUDE.mdso agents read code the cheap way by default — no manual edit needed (idempotent; safe to re-run) - Offer to customize agent names interactively
- Run verification checks
> No setup.sh? The server works standalone. Just pip install mcp networkx and register manually: > ``bash > claude mcp add --transport stdio --scope user agent-brain -- python3 /path/to/server.py > ` > The server gracefully handles a missing config.json` — it starts with an empty brain.
Where things land: setup.sh installs a copy of the server to ~/.agent-brain/ with its own venv — that copy is what Claude Code runs. The repo checkout keeps the source. CLI examples in this README use python3 brain/server.py from the repo root; against the installed copy, the equivalent is ~/.agent-brain/.venv/bin/python ~/.agent-brain/server.py . If you edit the repo copy, re-copy it to ~/.agent-brain/server.py (or re-run setup.sh) and restart Claude Code.
Linking a project (so subagents can use brain)
./setup.sh registers brain at the user level. That's enough for the main Claude Code session, but subagents spawned inside a project read MCP config from project-scoped files. Run:
./setup.sh --link-project=/absolute/path/to/your/project
This is idempotent and writes/merges:
/.mcp.json— adds theagent-brainserver entry alongside any existing entries/.claude/settings.local.json— setsenableAllProjectMcpServers: trueand addsagent-braintoenabledMcpjsonServers/.gitignore— appends.mcp.json,.san/.san_hashes.json,.san/_cache/
After running it, restart Claude Code in the project (/exit then claude), then verify:
~/.agent-brain/.venv/bin/python ~/.agent-brain/server.py diagnose --project=/absolute/path/to/your/project
> Subagents not seeing brain tools? See [the 4-layer model](#how-brain-mcp-reaches-claude-code-subagents-4-layer-model) under Verification.
How To Use It
Once set up, you don't call brain tools yourself — your agents do, automatically, as part of their normal work. Your job is just to give agents tasks and (optionally) review the memory that builds up.
The loop every agent runs
For any non-trivial task, an agent follows this cycle (enforced by the hook — see [Enforcement Hook](#enforcement-hook)):
1. pre_check(agent, area, action) ← "has anyone tried this before? did it fail?"
2. log_decision(agent, repo, area, ← records the plan; unlocks code edits
action, reasoning)
3. … writes the code …
4. log_outcome(decision_id, outcome, ← records accepted / rejected / failed + why
outcome_by, reason)
You just say "add rate limiting to the signup endpoint". The agent does the rest.
Worked example — across two sessions
Monday — a decision gets rejected:
You: "Add rate limiting to /login"
Agent: pre_check(agent="karan", area="auth", action="rate limit login")
→ "No past failures in 'auth'. Proceed."
Agent: log_decision(... action="in-memory counter per IP", reasoning="simplest")
→ dec_20260609_..._a1b2c3
Agent: …writes code, opens PR…
PE: log_outcome(dec_..._a1b2c3, outcome="rejected", outcome_by="marcus",
reason="in-memory won't survive multi-instance deploy; use Redis")
Friday — a different agent, a related task, a different machine/session:
You: "Add rate limiting to the signup endpoint"
Agent: pre_check(agent="dev", area="auth", action="rate limit signup")
→ "SIMILAR REJECTIONS (1, 78% match):
[2026-06-09] karan tried: in-memory counter per IP
REJECTED by marcus: in-memory won't survive multi-instance deploy; use Redis"
Agent: …goes straight to a Redis-backed limiter, skips the mistake…
No human re-explained the Redis constraint. The brain carried it forward.
How it behaves
| When an agent calls… | What happens | What you see | |----------------------|--------------|--------------| | pre_check | Searches past decisions in the same area + fuzzy-matches similar actions across all areas | Agent mentions relevant past rejections before coding | | log_decision | Appends the decision to the journal + drops a marker file | Code edits are now unblocked for ~30 min | | Edit/Write without a recent log_decision | PreToolUse hook blocks the edit (exit 2) | Agent is forced to log a decision first, then retries | | log_outcome (rejected) | Records the rejection; raises that agent's rejection rate | Future pre_checks surface it; repeat offenders get stricter warnings | | Any tool with a repo/status | Updates the live office dashboard | Agent appears working/reviewing/blocked at localhost:3333 |
What you get out of it (outcomes)
| Outcome | How it helps | |---------|--------------| | Mistakes aren't repeated | A rejection logged once warns every agent, every future session — even on a different machine. | | No re-explaining context | Constraints ("use Redis", "don't bypass the auth middleware") live in the brain, not in your head. | | Cross-agent learning | What backend-engineer learns, frontend-engineer and QA see. Knowledge is team-wide, not per-agent. | | Accountability & trends | Scorecards show each agent's acceptance rate and recurring failure patterns — agent_scorecard("karan", detail=True). | | Auditable history | "Why did we build it this way?" → decisions_for("AuthService.login") returns every decision that touched it, with reasoning and outcome. | | Enforced discipline | The hook means the memory actually gets populated — agents can't silently skip logging and edit code anyway. |
Inspecting the memory yourself
You rarely need to, but from the repo root (where you cloned agent-brain):
python3 brain/server.py stats # overall health: how many decisions/agents/repos
python3 brain/server.py office # who's working on what right now
python3 brain/server.py savings # tokens SAN saved (last session / today / all-time)
From any agent/MCP client you can also ask in plain language — "show me the team dashboard", "what decisions touched the payment service?", "what's karan's scorecard?", "how many tokens did SAN save this session?" — and the agent picks the right tool (team_dashboard, decisions_for, agent_scorecard, token_savings).
Architecture
┌─────────────────────────────────────────────────┐
│ Your Machine (global) │
│ │
│ ~/.agent-brain/ │
│ ├── server.py ← MCP server (17 tools) │
│ ├── config.json ← your repos + team │
│ ├── decisions.json ← memory snapshot │
│ └── decisions.journal← append-only deltas │
│ │
│ ~/.claude/agents/ │
│ ├── project-manager.md │
│ ├── product-owner.md │
│ ├── principal-engineer.md │
│ ├── backend-engineer.md │
│ ├── frontend-engineer.md │
│ └── qa-engineer.md │
│ │
│ project-repo/.san/ ← SAN-compressed code │
│ ├── _index.json │
│ └── src/**/*.san │
│ │
│ dashboard/ ← 3D office + decisions │
│ ├── server.py (python, zero deps) │ + SAN search (web)
│ └── static/ (Three.js + SSE) │
└─────────────────────────────────────────────────┘
Performance & internals
The brain is built to stay fast as the decision history grows into thousands of entries:
| Concern | How it's handled | |---------|------------------| | Reading the graph | decisions.json is parsed once and held in an in-memory cache keyed on file mtime+size — repeat tool calls in a session reuse it (~0.03ms vs ~140ms re-parse). The cache self-invalidates if another session writes the file. | | Writing a decision | Writes are O(delta), not O(graph). decisions.json is a periodic full snapshot; decisions.journal is an append-only log of mutations. Logging an outcome on a ~4MB brain appends ~800 bytes instead of rewriting 4MB. The journal auto-compacts back into the snapshot once it passes 256KB. | | SAN freshness | The freshness sweep (stat every indexed file + scan the .san/ tree) is debounced to once per 60s per repo, so bursts of get_san/query_san calls don't each pay for it. | | Bounded responses | Every list/detail tool caps its output (row limits, per-field truncation) so one giant decision can't blow up a response. Stored text fields are capped at write time too. | | Multi-session safety | Each Claude Code session runs its own server process sharing ~/.agent-brain/. Writes use os.replace with pid-unique temp files to avoid cross-process rename collisions. |
> Files in ~/.agent-brain/: decisions.json (snapshot) + decisions.journal (deltas) are the decision memory — both are needed; don't delete one without the other. office-state.json is live dashboard state (self-pruning), san_savings.jsonl is the token-savings log. All are per-machine and git-ignored.
MCP Tools (21)
Core (every agent uses these)
| Tool | Purpose | |------|---------| | pre_check | Past failures before starting work + plan pointers, escalation hints, model routing, SAN coverage (pass repo=) | | log_decision | Record what you decided and why; optional plan_file links a written plan | | log_outcome | Record accepted/rejected/failed after review | | log_feedback | Reviewers log feedback on decisions |
Query
| Tool | Purpose | |------|---------| | query_decisions | Filter by area/agent/repo/outcome and rank by free-text relevance (query="...") — finds decisions about a topic without knowing the exact area | | get_decision | Full detail + feedback for one decision | | get_roadmap | What's left to do — pending + roadmap/blocker-tagged work, ranked. One call to resume context after a fresh session or compaction |
Records & pruning (keep the brain lean)
| Tool | Purpose | |------|---------| | export_records | Write a
…
Source & license
This open-source MCP server is cataloged on AgentStack and links to its original source — we do not rehost the code.
- Author: sandeep84397
- Source: sandeep84397/agent-brain
- License: MIT
Install and usage instructions live in the source repository linked above.
Reviews
No reviews yet, be the first.
Write a review
Versions
- v0.1.0 Imported from the upstream source.