local-brain-mcp
π§ local-brain-mcp
Local-first, Git-aware persistent memory for AI coding assistants.
Local Brain is a lightweight Model Context Protocol (MCP) server that indexes your repository's Git history and manual engineering decisions into an embedded SQLite vector database. It equips AI coding assistants (Claude Code, Cursor, GitHub Copilot, Windsurf, Zed) with long-term codebase memoryβ100% offline, zero egress, and zero cloud API keys.
π Table of Contents
Problem with cloud AI memory tools | How local-brain solves it |
π 150β800ms network latency per recall | β‘ < 5ms β local SQLite vector search |
βοΈ Your code sent to foreign servers | π 100% on-device, zero egress |
πΈ Token bloat on every session | π¦ Hard 250-token budget cap per recall |
ποΈ Stale outdated context from old decisions | π Git-diff invalidation marks old memories STALE |
π WIP/typo commits pollute the brain | π― Quality filter keeps only high-signal lessons |
ποΈ Monorepo noise across packages | π― Path-scoped queries, per-package namespacing |
π Duplicate memories waste tokens | 𧬠Smart deduplication + merge on ingest |
π€· No record of how a decision evolved | π Full memory lineage with |
Quick Start
# 1. Navigate to your Git repository
cd /path/to/your-project
# 2. Auto-detect installed AI editors and link MCP configuration
npx local-brain init
# 3. Ingest your Git history into the local brain database
npx local-brain ingest
# 4. Check memory database statistics
npx local-brain status
# 5. Restart your AI editor (Claude Code, Cursor, Copilot, Windsurf, Zed)Editor / MCP Setup
All tools carry MCP 1.5 annotations (readOnlyHint, destructiveHint, idempotentHint) so hosts can show confirmation dialogs before destructive operations.
brain_recall
Semantic search your codebase memory. Results ranked by a composite score (similarity 45%, scope 20%, recency 10%, confidence 10%, importance 10%, quality 5%) and capped to 250 tokens.
{
"mcpServers": {
"local-brain": {
"command": "node",
"args": ["/absolute/path/to/local-brain-mcp/dist/mcp-server.js"],
"env": {}
}
}
}What is MCP? (For Beginners)
The Model Context Protocol (MCP) is an open standard created by Anthropic that allows AI applications (like Claude or Cursor) to securely interact with local tools and data sources.
βββββββββββββββββββββββββββ
β AI Coding Assistant β
βββββββββββββ¬ββββββββββββββ
β Tool Invocation (JSON-RPC over stdio)
βΌ
βββββββββββββββββββββββββββ
β Local Brain MCP β
βββββββββββββ¬ββββββββββββββ
β Parameterized SQL
βΌ
βββββββββββββββββββββββββββ
β Embedded SQLite DB β
βββββββββββββββββββββββββββLocal Brain runs locally as a background process over standard input/output (stdio). The AI invokes Local Brain tools whenever it needs to recall past lessons or remember new rules.
MCP Tools Reference
1. brain_recall
Semantically searches codebase memories relevant to the query and optional file scope.
Type: Read-only
When to use: Before refactoring, fixing bugs, or implementing features to check if relevant lessons or constraints exist.
Parameters:
Parameter | Type | Required | Description |
|
| Yes | What to search for (max 1000 characters). |
|
| No | Repo-relative file path to scope the query (e.g. |
|
| No | Maximum memories to return (1β20, default: 5). |
|
| No | Filter by category: |
Example Input:
{
"query": "JWT token expiration bug",
"file_path": "src/auth/jwt.ts",
"max_items": 3
}Example Output:
## Brain Recall: "JWT token expiration bug"
β’ [src/auth/jwt.ts @ 8a4f12] (fix): JWT refresh race condition β RS256 cert rotates every 24h. Cache public keys with 1h TTL.
β’ [src/auth/session.ts @ c31d04] (bug): Sessions expire silently on Tuesday UTC maintenance window.brain_learn
Manually store a lesson or team convention with quality assessment. Low-signal content (shell noise, one-liners) is automatically filtered.
Type: Write
When to use: When you or the AI discover a crucial rule, edge case, or convention that is not documented in git commits.
Parameters:
Parameter | Type | Required | Description |
|
| Yes | Actionable lesson or decision (max 10000 characters). |
|
| No | Category: |
|
| No | Associated file path (e.g. |
|
| No | Importance multiplier between 0.5 and 2.0 (default: 1.0). |
Example Input:
{
"lesson": "Always use parameterized prepared statements in better-sqlite3 to prevent injection.",
"category": "convention",
"file_path": "src/db/queries.ts",
"importance": 1.5
}brain_trace
Full chronological history of all memories for a specific file, including superseded and deprecated entries.
Type: Read-only
When to use: When investigating the maintenance history or past regressions of a specific source file.
Parameters:
Parameter | Type | Required | Description |
|
| Yes | Repo-relative file path (e.g. |
Example Input:
{
"file_path": "src/db.ts"
}brain_forget
Permanently remove or deprecate a specific memory by ID (idempotent).
{
"id": 42,
"hard_delete": false
}brain_prune
Remove stale/deprecated memories in bulk. Optionally triggers a full git-diff invalidation pass.
Type: Destructive Write
When to use: After major refactors or codebase rewrites to purge outdated knowledge.
Parameters:
Parameter | Type | Required | Description |
|
| No |
|
|
| No | If true, runs a git invalidation pass first (default: |
Example Input:
{
"status": "stale",
"run_invalidation": true
}brain_status
Returns health diagnostics: memory counts by status, DB size, schema version, oldest/newest entries.
{}CLI Commands
local-brain init # setup wizard β writes MCP config for all detected editors
local-brain ingest # scan git history and build the brain DB
local-brain ingest --since "6 months ago" --verbose
local-brain status # show DB memory counts and diagnostics
local-brain prune --invalidate # detect + remove stale memories
local-brain learn "lesson text" --category convention --file src/db/client.ts
local-brain trace --file src/db/client.ts
local-brain forget --id 42Real-World Usage Example
git history
β
[git-ingest.ts] β filters WIP/typo/format commits + quality assessment
β duplicate?
[db.ts] β findDuplicateMemory β smart merge (preserves richest summary)
β
[embeddings.ts] β pure-JS TF-IDF feature hashing (384-dim, sub-1ms, zero network)
β
[db.ts] β stores in .git/brain.db (provenance: author, branch, confidence, importance)
β (on file change)
[invalidation.ts] β marks stale if file changed > 30% (multi-file array support)
β (on MCP tool call)
[recall.ts] β cosine similarity + multi-factor ranking, scoped to package, capped to 250 tokens
β
Claude Code / Cursor / Copilot / Windsurf / ZedRanking Formula
rank_score = (similarity Γ 0.45)
+ (scope_boost Γ 0.20)
+ (recency Γ 0.10)
+ (confidence Γ 0.10)
+ (importance Γ 0.10)
+ (quality Γ 0.05)
Γ status_multiplier (active=1.0, stale=0.25, deprecated=0.05)Memory Lifecycle
inserted (active)
β stale (git-diff invalidation if file changed > 30%)
β deprecated (superseded by newer memory or manual forget)
β deleted (hard prune)Schema & Provenance
Each memory stores:
Field | Description |
| Raw commit message or lesson text |
| Distilled one-liner (merged on dedup) |
| Canonical file(s) this memory belongs to |
| Git commit author |
| Branch at ingest time |
| SHA of the commit |
| Float 0β1, updated on merge |
| Float, boosted by quality signals |
|
|
| FK to the memory that replaced this one |
| Float output of quality assessment |
Project Structure
local-brain-mcp/
βββ src/
β βββ cli.ts # Command-line interface and setup wizard
β βββ db.ts # SQLite database management and migrations
β βββ embeddings.ts # Code-aware TF-IDF feature hashing vectorizer
β βββ git-ingest.ts # Commit filtering and git ingestion pipeline
β βββ invalidation.ts # Git-diff staleness detection engine
β βββ mcp-server.ts # MCP server definition and tool handlers
β βββ recall.ts # Multi-factor ranking and token-capped search
β βββ schema.sql # Core SQLite table schemas and triggers
β βββ scoping.ts # Monorepo package scope and path sanitization
βββ tests/
β βββ mcp-tools.test.js # MCP protocol and tool integration tests
β βββ embeddings.test.js # Vectorizer and cosine math unit tests
β βββ recall-ranking.test.js # Multi-factor ranking algorithm tests
β βββ scoping.test.js # Monorepo scope and path security tests
β βββ security.test.js # SQL injection and path traversal tests
β βββ invalidation.test.js # Diff parsing and threshold tests
β βββ git-ingest.test.js # Commit filter regex and classifier tests
βββ scripts/
β βββ benchmark.mjs # Performance benchmark runner
β βββ copy-schema.mjs # Build step copying SQL schema to dist
β βββ evaluate-retrieval.mjs # Information Retrieval evaluation runner
βββ .github/workflows/ci.yml # Multi-version Node.js CI workflow
βββ package.json
βββ tsconfig.json
βββ README.mdTroubleshooting
1. MCP Server Not Appearing in AI Assistant
Run
npx local-brain initto re-apply editor configurations.Verify that your editor was completely restarted.
Check that
nodeis available in your systemPATH.
2. No Memories Returned on Recall
Ensure git history has been ingested:
npx local-brain ingest.Check database status:
npx local-brain status.If working in a subdirectory, check monorepo package scoping.
3. Memories Flagged as Stale
If a file had substantial changes (>30% lines), its memories are automatically marked
stale.Run
npx local-brain prune --invalidateto clean outdated records and re-runnpx local-brain ingest.
Development & Testing
# Clone the repository
git clone https://github.com/cosmiccoder200x-sys/local-brain-mcp.git
cd local-brain-mcp
# Install dependencies
npm install
# Type check
npm run typecheck
# Build TypeScript to dist/
npm run build
# Run unit and integration tests
npm test
# Run performance benchmarks
npm run benchmark
# Run retrieval quality evaluation
npm run evalFAQ
Q: Does Local Brain send code to the cloud?
A: No. Local Brain is 100% offline and makes zero external network requests.
Q: Do I need an OpenAI or Anthropic API key to run it?
A: No. Local Brain uses a built-in pure-JavaScript feature-hashing embedding engine.
Q: Where is the memory database saved?
A: In <your-repo>/.git/brain.db (or ~/.config/local-brain/brain.db outside git repos).
Q: Does it work with monorepos?
A: Yes. Local Brain auto-detects package boundaries (e.g. packages/auth, apps/web) and scopes recalls accordingly.
Tech Stack
Protocol:
@modelcontextprotocol/sdk(StdioServerTransport)Storage:
better-sqlite3(SQLite WAL mode, BLOB float32 vectors)Embeddings: Pure-JS TF-IDF feature hashing (384-dim, sub-1ms, 100% offline)
Git Engine:
simple-gitCLI Engine:
commander
Test Coverage
Suite | Tests | Status |
MCP Tool Annotations | 8 | β pass |
Database & Migrations | 4 | β pass |
Deduplication & Smart Merge | 4 | β pass |
Quality Assessment | 3 | β pass |
Memory Supersession | 2 | β pass |
MCP Server Lifecycle (integration) | 7 | β pass |
Adversarial Retrieval (18 cases AβR) | 18 | β pass |
npm test # runs all suitesLicense
MIT β build freely.
Latest Blog Posts
- Who's Calling? MCP Hosts Are an Identity Blind Spot (And the Spec Knows It)By Om-Shree-0709 on .mcpAgent IdentityOAuth 2.1
- Your AI Chatbot Just Exposed Your CEO's Salary to an InternBy Om-Shree-0709 on .Agent IdentityMCP SecurityOAuth Delegation
- Why MCP Servers Need Execution Sandboxing (And Why Your Current Stack Isn't Enough)By Om-Shree-0709 on .Agentic AiPrompt InjectionWebAssembly
MCP directory API
We provide all the information about MCP servers via our MCP API.
curl -X GET 'https://glama.ai/api/mcp/v1/servers/cosmiccoder200x-sys/local-brain-mcp'
If you have feedback or need assistance with the MCP directory API, please join our Discord server