MegaBrain
MegaBrain is a local MCP memory server for AI coding assistants that enforces rules and shares lessons across agents.
brain_consult— pre-flight lookup of project rules, mandatory specs, known blind spots, and golden patterns before coding.brain_record_experience— save mistakes and fixes as vaccines, optionally including verified code snippets.brain_record_rule— store strict constraints by category, severity, and project.brain_require_spec— bind spec files to trigger keywords so agents must read them before matching work.brain_record_golden_pattern— save verified reusable code snippets agents should adopt.brain_list_rules— list active project and global rules.brain_stats— display knowledge base statistics.
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@MegaBrain consult the brain before I write the PHP MySQL signup query"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
🧠 MegaBrain (MCP)
Persistent Cross-Agent Memory, Rule Enforcer, and Blindspot Vaccine for AI Coding Assistants.
Compatible with Claude Desktop, VS Code (Cline, Roo Code, Continue), Antigravity IDE, and Local AI (llama.cpp).
🎯 The Problem
When vibecoding with AI coding agents (Claude, Antigravity, or local LLMs via llama.cpp), developers face two relentless frustrations:
Relentless Repetitive Errors (AI Blind Spots):
The AI writes a PHP/MySQL script and fails on the first try every single time, blindly retrying until it works. In the next session, it resets its memory and makes the exact same mistake again.Context & Spec Amnesia:
The AI ignores project rules (e.g., answering in Portuguese when English is strictly required) or writes UI components without reading the project's design specifications.
Related MCP server: Sugar
💡 The Solution: MegaBrain
MegaBrain is an autonomous memory engine running locally via the Model Context Protocol (MCP). It stores rules, mandatory specifications, and battle-tested code snippets in a high-speed SQLite database with FTS5 full-text search.
Because MegaBrain uses a single local database (~/.megabrain/megabrain.db), any lesson learned by Claude or Antigravity is instantly available to your local llama.cpp model in VS Code, and vice-versa.
┌───────────────────────────────────┐
│ MegaBrain SQLite DB │
│ (~/.megabrain/megabrain.db) │
└─────────────────┬─────────────────┘
│ (MCP / CLI)
┌────────────────────────┼────────────────────────┐
│ │ │
▼ ▼ ▼
┌──────────────────┐ ┌──────────────────┐ ┌──────────────────┐
│ Claude Desktop │ │ VS Code (Cline) │ │ Antigravity IDE │
│ & Claude Code │ │ & llama.cpp │ │ │
└──────────────────┘ └──────────────────┘ └──────────────────┘⚡ The 3 Pillars
1. Mandatory Pre-Flight Check (brain_consult)
Before the AI generates code, designs layout, or queries databases, it queries MegaBrain with its task context. MegaBrain immediately surfaces:
Strict Constraints: E.g.,
STRICT_LANGUAGE: English.Prerequisite Specs: Traps the agent: "You are FORBIDDEN from generating layout code before reading
specs/design-tokens.md".Known Blind Spots: E.g., "You repeatedly fail PDO connection syntax. Do NOT use X; use Y."
Golden Patterns: Verified, working code snippets.
2. Autonomous Post-Mortem Vaccine (brain_record_experience)
Whenever the agent takes $\ge 2$ attempts to fix an error, or when the user says "Grava isso no cérebro" ("Remember this"), the agent records what failed and what worked.
MegaBrain tracks a recurrence counter and vaccinates the entire environment against that mistake.
3. Golden Patterns (Verified Code Snippets)
Instead of letting the AI hallucinate boilerplates from average internet tokens, MegaBrain stores validated implementations that the AI must adopt directly.
🚀 Quickstart
Prerequisites
Python 3.10 or higher
uv (recommended) or standard
pip
Installation
# 1. Clone the repository
git clone https://github.com/dougrn/MCP-MegaBrain.git
cd MCP-MegaBrain
# 2. Sync dependencies with uv
uv syncTry the CLI
# View knowledge base stats
uv run megabrain stats
# Add a strict rule
uv run megabrain record-rule "All code comments and docs must be in English" --category language --project my-app
# Require a spec before touching design
uv run megabrain record-spec "specs/design-tokens.md" --trigger "design,ui,layout" --project my-app
# Record an anti-pattern vaccine
uv run megabrain record-experience --context "php mysql" --failed "Called set_charset on uninitialized PDO" --fix "Pass charset=utf8mb4 inside DSN string"
# Save a verified Golden Pattern
uv run megabrain golden-pattern --title "PHP PDO UTF8MB4" --context "php mysql pdo" --code "$pdo = new PDO('mysql:host=localhost;dbname=test;charset=utf8mb4', $user, $pass, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);"
# Consult MegaBrain (see what the AI receives!)
uv run megabrain consult "php mysql query" --project my-app
# List and delete obsolete records
uv run megabrain list rules
uv run megabrain delete rules 1🔌 Connecting to Your AI Clients
1. Claude Desktop
Add to your claude_desktop_config.json:
Windows:
%APPDATA%\Claude\claude_desktop_config.jsonmacOS:
~/Library/Application Support/Claude/claude_desktop_config.json
{
"mcpServers": {
"megabrain": {
"command": "uv",
"args": [
"run",
"--directory",
"C:\\Users\\dougl\\Desktop\\Serviços\\_Pessoais\\MCP-MegaBrain",
"megabrain-server"
]
}
}
}2. VS Code (Cline / Roo Code)
Add to your Cline MCP settings:
{
"mcpServers": {
"megabrain": {
"command": "uv",
"args": [
"run",
"--directory",
"C:\\Users\\dougl\\Desktop\\Serviços\\_Pessoais\\MCP-MegaBrain",
"megabrain-server"
],
"disabled": false,
"autoApprove": [
"brain_consult",
"brain_record_experience",
"brain_stats"
]
}
}
}3. Antigravity IDE
Add to your MCP server configuration:
{
"mcpServers": {
"megabrain": {
"command": "uv",
"args": [
"run",
"--directory",
"C:\\Users\\dougl\\Desktop\\Serviços\\_Pessoais\\MCP-MegaBrain",
"megabrain-server"
]
}
}
}4. Local AI (llama.cpp)
Run the prompt enricher before passing prompts to llama-server or CLI:
uv run python examples/llama-cpp-wrapper/query_megabrain.py📜 The Agent Behavioral Contract
To guarantee that your AI assistant actively consults MegaBrain and records mistakes autonomously, add the following prompt rule to your agent's instructions (e.g. .cursorrules, .agents/rules/megabrain.md, or Claude project instructions):
# MegaBrain Protocol (Persistent Knowledge & Vaccine)
You are equipped with MegaBrain via MCP tools. You MUST follow these mandatory protocols:
## 1. MANDATORY PRE-FLIGHT CONSULTATION
BEFORE generating code, proposing architecture, querying databases, or touching UI design:
- Call `brain_consult(context="<stack/keywords>", project="<project_id_or_global>")`.
- **Prerequisite Specs**: If any mandatory specs are returned, you are strictly FORBIDDEN from writing code or plans until you inspect the spec file using your file reading tool.
- **Golden Patterns**: If a verified snippet is provided, you MUST adopt it instead of inventing your own implementation.
- **AI Blind Spots / Traps**: Carefully avoid the listed anti-patterns and apply the proven fixes.
## 2. AUTONOMOUS SELF-IMPROVEMENT (POST-MORTEM VACCINE)
Whenever you:
- Spend 2 or more attempts trying to fix an error in a terminal/script, OR
- Discover a non-obvious bug or runtime pitfall:
- IMMEDIATELY call `brain_record_experience(context="...", what_failed="...", fix_applied="...", project="...")`.
- If a clean, reusable code snippet solved the issue, pass it to `verified_snippet`.
## 3. HUMAN TRIGGERS
If the user says:
- "Grava isso no cérebro" / "Aprende isso" / "Vacina contra esse erro" / "Remember this":
- Immediately extract the context keywords, what failed, and the working fix.
- Call `brain_record_experience`.🛠️ CLI Reference
Command | Description | Example |
| Query active rules, specs, and vaccines |
|
| Enforce a strict constraint |
|
| Bind a spec file to topic triggers |
|
| Vaccinate against a repeated error |
|
| Save a battle-tested code snippet |
|
| List stored memory by type |
|
| Delete stored item by type and ID |
|
| Display memory overview & item counts |
|
| Output the agent system instructions |
|
| Launch MCP server over stdio |
|
🧪 Running Tests
uv run pytestAll 15 test suites validate schema migrations, FTS5 full-text search, recurrence increments, deletion operations, and MCP tool executions.
🇧🇷 Resumo em Português
O MCP-MegaBrain é um cérebro persistente para desenvolvedores que trabalham com múltiplos agentes (Antigravity, Claude, VS Code/Cline, llama.cpp). Ele resolve de forma definitiva:
Erros repetitivos e teimosia da IA: Transforma bugs corrigidos em "vacinas" com contador de recorrência.
Amnésia de especificações: Obriga a IA a ler suas specs de design/arquitetura antes de emitir código.
Desobediência de regras: Garante conformidade com idioma, padrões de commit e restrições de arquitetura.
100% Local e Gratuito: Armazenado em SQLite local com busca instantânea (FTS5), sem mensalidades ou nuvem.
📄 License
This project is licensed under the MIT License.
Available Tools
7 toolsbrain_consultA
MANDATORY PRE-FLIGHT CHECK: Call this before writing, designing, or refactoring code. Returns:
Active project rules & hard constraints
Prerequisite specifications you MUST inspect before coding
Known AI blind spots (previous traps & working vaccines)
Golden Patterns (verified working code snippets to use directly)
Args: context: The topic, stack, or task description (e.g., 'php mysql pdo', 'react button design', 'authentication') project: Project name/slug or 'global'
Inputs: context (required), project. Returns: result
brain_list_rulesB
List all active rules for the given project including global rules.
Inputs: project. Returns: result
brain_record_experienceA
VACCINATE AGAINST MISTAKES: Call this whenever you spent >= 2 attempts fixing an error, encountered an unexpected runtime pitfall, or when the user says 'grava isso' / 'aprende isso'.
Args: context: Stack/domain keywords (e.g., 'php mysql utf8mb4', 'docker windows networking') what_failed: The anti-pattern or rookie mistake the AI made fix_applied: The exact working solution or insight that solved it project: Project identifier or 'global' verified_snippet: (Optional) The working code block to also save as a Golden Pattern
Inputs: context (required), fix_applied (required), what_failed (required), project, +1 more. Returns: result
brain_record_golden_patternB
Save a battle-tested code snippet that agents must copy/adopt instead of reinventing boilerplate.
Args: title: Short descriptive title context: Stack/domain keywords (e.g., 'php mysql pdo') code_snippet: The exact verified working code explanation: Explanation of why this pattern is preferred project: Project identifier or 'global'
Inputs: title (required), context (required), code_snippet (required), project, +1 more. Returns: result
brain_record_ruleB
Enforce a strict constraint that agents must always obey.
Args: rule: The constraint statement (e.g., 'All code comments and docs must be in English') category: Category like 'language', 'architecture', 'security', 'git', 'style', 'general' project: Project identifier or 'global' severity: 'CRITICAL', 'HIGH', 'MEDIUM', or 'LOW'
Inputs: rule (required), project, category, severity. Returns: result
brain_require_specA
Register a specification file that the agent MUST read before working on matching topics.
Args: spec_path: Path to spec file (e.g., 'specs/design-tokens.md', 'docs/api.md') trigger_pattern: Comma-separated keywords triggering this requirement (e.g., 'design, ui, layout, componentes') instruction: Directive for the agent (e.g., 'Read design tokens before generating CSS') project: Project identifier or 'global'
Inputs: spec_path (required), trigger_pattern (required), project, instruction. Returns: result
brain_statsB
Get current knowledge base statistics.
Inputs: no named parameters. Returns: result
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 7 tools
Most tools are clearly distinct (record_rule vs record_experience vs record_golden_pattern vs require_spec). However, brain_consult overlaps with brain_list_rules since consult already returns active rules, and record_experience with a verified_snippet partially duplicates record_golden_pattern, creating mild selection ambiguity.
All tools share a consistent brain_ prefix and snake_case verb_noun style (brain_record_rule, brain_list_rules, brain_require_spec). Minor deviations are brain_consult and brain_stats, which lack a noun object but remain readable and unambiguous.
Seven tools is well-scoped for a knowledge-base server covering retrieval, rule/spec/experience/pattern recording, and stats. Each tool maps to a distinct operation and none feels redundant or missing.
Write and read paths are covered (record rules/specs/experiences/patterns, consult, list_rules, stats), but there is no update or delete/retire operation for any stored artifact. Without lifecycle management, stale or wrong rules and vaccines cannot be corrected, which is a notable gap for a long-lived knowledge base.
Maintenance
Related MCP Connectors
Persistent cross-session memory shared by Codex, Claude Code, ChatGPT, and other AI agents.
Shared memory for coding agents. Stop re-explaining your codebase every session.
Private memory for AI agents: save and recall facts across Claude Code, Codex, Cursor and ChatGPT.
Persistent engineering memory designed to follow developers across coding agents.
Related MCP Servers
- FlicenseNot gradedqualityAmaintenanceProvides AI coding agents with a local-first, persistent memory layer so they can store and semantically recall project-specific and cross-project knowledge, conventions, and error patterns during sessions. It also optionally enables autonomous task queue execution and issue resolution driven by that same memory.-
- FlicenseNot gradedqualityAmaintenanceGives AI coding agents persistent, local-first memory so they can store decisions, preferences, error patterns, and cross-project guidelines and semantically recall the relevant context across sessions and projects, with no API keys required. Optionally also enables queued autonomous task execution that draws on that same stored context.-
- FlicenseNot gradedqualityAmaintenanceGives AI coding agents persistent, local-first memory so they can store, semantically search, and recall decisions, preferences, error patterns, and cross-project guidelines directly during a session. It also optionally queues tasks for autonomous execution against that same memory.-
- FlicenseNot gradedqualityAmaintenanceProvides AI coding agents with a local-first persistent memory layer they can read and write during sessions, storing decisions, preferences, error patterns, and research per project or globally. Enables semantic and keyword search, formatted context recall, and cross-project guideline surfacing without API keys or cloud storage.-