Unified IDE context engine that merges semantic codebase search with episodic project memory into a single MCP server.
Every time you start a new AI coding session, your agent starts from zero. It doesn't remember the bug you fixed yesterday, the architectural decision you made last week, or even what files exist in your project. You end up re-explaining context, watching it hallucinate stale assumptions, and losing momentum to the "goldfish memory" problem.
Krusch Context MCP fixes this. It gives your AI coding agent persistent, searchable memory across every session — paired with semantic search over your entire codebase — so your agent always knows what your code does, why you built it that way, and what went wrong last time.
A single Model Context Protocol server exposing 44 tools to any MCP-compatible IDE agent (Cursor, Claude Code, Windsurf, Gemini CLI, etc.):
| Capability | What It Provides |
|---|---|
| ⚡ Unified Hybrid Retrieval | Polygres-inspired single-call retrieval combining vector search, multi-hop graph walks (graph_hops), server-side token packing (limit_tokens), and optional Rubric4Setwise minimal cover reranking. |
| 🔍 Semantic Codebase Search | Search the meaning of your code, not just filenames. "How do we handle auth?" returns the actual implementation. |
| 🧠 Episodic Memory | Bugs, decisions, and lessons persist across sessions, retrieved by semantic relevance with temporal decay. See Episodic Memory Guide. |
| 💎 Steering Nudges | Lightweight key-value facts (preferences, conventions) give the agent behavioral continuity without re-prompting. |
| 🔄 Agentic Context Management (ACM) | Structured context lifecycle staging, compaction, eviction retention policies, and context window token budget auditing (ArXiv: 2607.21503). |
| 🐞 AgentDebugX Error Hub | Failure observability, trajectory root-cause attribution, and execution recovery pattern retrieval for SRE queue healing. |
| ⚙️ DataFlow-Harness Grounded Codegen | Grounded MCP operator registry and schema-validated pipeline DAG mutations (AddNode, WireEdge, UpdateNodeConfig). |
| 📊 Rubric4Setwise Reranking | Document-set selection evaluating Redundancy, Conflict, and Complementarity rubrics to filter candidate sets down to minimal covering sets. |
| 🔬 AREX Deep Research Engine | Recursively self-improving inner research evidence tracking paired with outer self-improvement constraint audits. |
| 📖 Documentation Search | Ingested external docs are searchable locally — your agent references your versions, not its training data. |
| 🛡️ Proactive Auditor (Memory Agent) | Trajectory auditing that learns from feedback (Direct-OPD) to verify trajectories and log alignment signals. |
| 🌍 Zero-Trust Deep Search | One tool call cross-references codebase reality with historical memory to verify understanding before acting. |
🛡️ Everything stays on your hardware — All embeddings via local Ollama (bge-large + llama3.2). Storage is PostgreSQL + pgvector + SQLite. Zero API costs, full data sovereignty.
🔄 Switch models without losing context — Memory is decoupled from the reasoning engine. Swap between Gemini, Claude, GPT-4o, or local models mid-project — every model inherits the same context.
🔌 Model-Provider & Cloud Agnostic (OpenRouter & Polygres.com) — While local Ollama and local Postgres are supported out-of-the-box, krusch-context-mcp is fully provider-agnostic. You can host your database on Polygres.com (DATABASE_URL) and generate cloud bge-large embeddings via OpenRouter (EMBEDDING_URL="https://openrouter.ai/api/v1/embeddings", EMBED_MODEL="baai/bge-large-en-v1.5"), or use any OpenAI-compatible endpoint (LM Studio, llama-server, vLLM).
⚡ One server, not three — Codebase search, episodic memory, and steering nuggets in a single process with shared connection pool and embedding pipeline.
Prerequisites: Node.js 22+ · Ollama with bge-large and llama3.2 · PostgreSQL with pgvector
# 1. Install [PG-Git-MCP](https://github.com/kruschdev/pg-git-mcp) (codebase ingestion engine)
npm install -g pg-git-mcp
# 2. Clone and install
git clone https://github.com/kruschdev/krusch-context-mcp.git
cd krusch-context-mcp
npm install
cp .env.example .env # Configure your database connection
# 3. Start
npm startAdd to your IDE MCP settings (e.g., .cursor/mcp.json, claude_desktop_config.json):
{
"mcpServers": {
"krusch-context-mcp": {
"command": "node",
"args": ["/path/to/krusch-context-mcp/src/index.js"]
}
}
}Restart your IDE — your agent now has access to all 32 tools.
Upgrading?
git pull origin main && npm install && npm start— idempotent migrations run on startup.
graph TD;
A[Agent Tool Call] --> B{Krusch Context MCP};
B -- Semantic Code Search --> C[(PG-Git: blobs)];
B -- Read/Write --> D[(SQLite Compute Cache)];
B -- Read/Write --> E[(Postgres Object Storage)];
D -. Async Pull/Push .-> E;
B -- Deep Search --> C;
B -- Deep Search --> D;
B -- Deep Search --> E;
%% Proactive Auditor & Direct-OPD Alignment Loop
B -- Trajectory Audit --> G[Proactive Auditor];
G -- Warning Nudge --> A;
A -- Feedback / Corrected Diff --> H[nudge_feedback];
H -- write_state --> I[(interaction_memory)];
I -- Reusable Guidance --> G;
F[Ollama Fleet] -. embeddings .-> B;
| Component | Details |
|---|---|
| Storage | Hybrid: Local SQLite (per-project) + PostgreSQL (global & codebase) |
| Embeddings | Ollama bge-large @ 1024 dims, fleet load-balanced |
| Tagging | Ollama llama3.2 for automatic keyword extraction |
| Temporal Decay | score = similarity × e^(-0.01 × age_days) — relevance drops ~26% after 30 days |
- Lakebase Architecture — Local SQLite for zero-latency reads, async write-behind to durable PostgreSQL. A
+0.3local scoring bias mitigates Ebbinghaus forgetting as the global corpus grows. Inspired by Neon. - pgContext Vector Engine — Native PostgreSQL 17 page-native HNSW index access method (
pgcontext_hnsw) with single-pass JSON metadata filtering and exact MVCC/RLS re-checking, preventing vector recall collapse under selective filters. Inspired by Evokoa pgContext. - AgentDebugX Error Hub — Failure observability, trajectory root-cause attribution, and execution recovery pattern retrieval for automated error healing. Inspired by AgentDebugX.
- Hybrid Retrieval — Auto-tagged via
llama3.2to address pure-cosine failure modes (negation, numeric, role-swap). Per Sentra. - Consolidation — Semantic dedup via L2-normalized centroid averaging without re-embedding. From Geometry of Consolidation.
- Holographic Nuggets — Lightweight steering facts adapted from NeoVertex1/nuggets.
- Proactive Context Agent — Trajectory auditor (OPD/PUST) that checks active logs against rules, records feedback alignment traces, and improves over time.
Implements the three-layer organizational memory model from the Sentra "Company Brain" research:
- Factual Memory — Raw codebase state + episodic events → "what happened"
- Interaction Memory — Parent-child UUID lineage, attribution, conflict resolution → "why it happened"
- Action Memory — Autonomous state compilation and graph traversal → "what to do next"
For a detailed technical guide on categories, architecture, sync mechanics, and agent lifecycle patterns, see the Episodic Memory Guide.
You: "That fixed the port conflict! Save this."
Agent: [add_memory] Saved to 'bugs': port 5441 conflicts with legacy DB, use 5442.
You: "How did we structure the auth system?"
Agent: [search_memory] From 'lessons': chose singleton JWT factory to avoid circular dependencies.
search_memory supports deterministic GRASP parameters to dynamically adjust context depth and retrieval strategy:
- Keyword/Tag Matches: Bypass dense vector search to retrieve exact terms or tags:
search_memory({ category: "lessons", query: "JWT", search_type: "keyword" }) - Version Provenance Lineage: Automatically retrieve and append the parent revision chain of the memory:
search_memory({ category: "priorities", query: "database", include_history: true }) - Codebase Edge Resolution: Fetch and append linked git blob references (
memory_to_blob_edges):search_memory({ category: "bugs", query: "VRAM leak", include_linked_blobs: true })
You: "How does our auth middleware work?"
Agent: [search_code] Found 3 files — here's the implementation inlib/auth.js...
You: "Before we start, verify what you know about the DB schema."
Agent: [deep_search] Cross-referencing codebase + memory — schema uses pgvector 1024 dims, last session added thetagscolumn.
You: "Always use
constoverletin this project."
Agent: [nugget_remember] Saved:coding-style:const-over-let.
You: "The previous agent was wrong about the database port."
Agent: [resolve_conflict] Merged conflicting states. Deprecated old branches, created unified resolution.
You: "Let's index the daily research papers using qwen2.5-coder:1.5b embeddings."
Agent: [proactive_nudge] Warning: The postgreside_agent_memorytable embedding column is constrained to 1024 dimensions.qwen2.5-coder:1.5bembeddings have 1536 dimensions and will fail. Always usebge-largeembeddings.Agent: [
nudge_feedback] Logs feedback indicating the warning was accepted and the trajectory was corrected. This alignment signal (Direct-OPD) is retrieved in future sessions as reusable guidance.
1. deep_search({ query: "<topic>", project: "<project>" })
→ Verify codebase + memory in one call
2. nugget_nudges({ query: "<task>", active_project: "<project>" })
→ Load conventions and preferences
1. search_memory({ category: "bugs", query: "<symptoms>" }) → Check history
2. search_code({ query: "<error>", project: "<project>" }) → Find implementation
3. [Fix the bug]
4. add_memory({ category: "bugs", content: "<root cause + fix>" }) → Document
1. add_memory({ category: "outcomes", content: "<decisions and results>" })
2. nugget_remember({ key: "<project>:last-session", value: "<in-progress work>" })
3. consolidate({ category: "activity", project: "<project>", dry_run: true })
1. proactive_nudge({ history: "<conversation history window>", project: "<project>" })
→ Background threat-audit of agent trajectory against historical lessons, bugs, and rules before executing code changes
Full parameter details, defaults, and examples → Tool Reference
| Tool | Description |
|---|---|
| Episodic Memory | |
add_memory |
Store a memory (bug, lesson, priority, outcome, activity) |
search_memory |
Semantic search with temporal decay |
list_memories |
List recent memories by category |
delete_memory / update_memory |
CRUD by ID |
consolidate |
Merge semantically duplicate memories |
compile_state |
Contextmaxxing — compile full project state |
| Company Brain v2 | |
write_state |
Stateful write with concurrency control and attribution |
resolve_conflict |
Merge conflicting sibling states |
get_provenance |
Trace version history and lineage |
search_lens |
Role-filtered semantic retrieval |
traverse_graph |
Navigate parent/child lineage and linked blobs |
update_ontology / link_blob |
Tag management and codebase linking |
| Codebase Search | |
search_code |
Semantic search over indexed files |
deep_search |
Composite zero-trust search (memory + codebase) |
list_repos / read_tree / read_blob |
Browse indexed repositories |
| Nuggets | |
nugget_remember / nugget_nudges / nugget_forget / nugget_list |
Steering fact CRUD |
| System, Auditing, & Skills | |
manage_lifecycle |
Agentic Context Management (ACM) fragment lifecycle (stage, compact, evict, get, list) |
audit_budget |
Agentic Context Management (ACM) token budget and context pressure auditing |
proactive_nudge |
Trajectory auditing — warn on rule/lesson violations |
nudge_feedback |
Log developer/agent feedback to record alignment signals |
analyze_trajectory |
Trajectory auditing — analyze execution path using STRACE and isolate faults |
think |
Perform context synthesis, conflict detection, and gap analysis |
list_skills / get_skill |
Browse and read specialized agent skills Registry |
docs_list / docs_search |
External documentation search |
health_check |
Server status verification |
krusch-context-mcp/
├── src/
│ ├── index.js # MCP server entry — tool registration & dispatch
│ ├── memory-engine.js # Episodic memory CRUD + consolidation
│ ├── v2-engine.js # Company Brain v2 substrate
│ ├── nuggets-engine.js # Holographic Nuggets CRUD
│ ├── unified-retrieval.js # Unified Hybrid Retrieval engine
│ ├── acm-engine.js # Agentic Context Management (ACM) engine & token cost auditing
│ ├── agentdebugx-engine.js # AgentDebugX Error Hub & failure observability
│ ├── dataflow-engine.js # DataFlow-Harness grounded pipeline registry & DAG mutations
│ ├── setwise-engine.js # Rubric4Setwise minimal cover document-set selection
│ ├── arex-engine.js # AREX deep research state engine & constraint audit
│ ├── sqlite-engine.js # Lakebase SQLite layer (pull/push sync)
│ ├── pgcontext-helper.js # pgContext extension detection & HNSW index setup
│ ├── proactive-engine.js # Proactive trajectory auditor
│ └── llm-tags.js # Shared LLM tag generation
├── scripts/ # Benchmarking, evaluation, and maintenance
├── tests/ # *.test.js = automated, test_*.js = smoke
├── docs/
│ ├── TOOL_REFERENCE.md # Full parameter reference for all 44 tools
│ ├── SETUP.md # Configuration, storage routing, troubleshooting
│ └── research/ # Sentra Company Brain research essays
└── package.json
npm test # Automated (node:test, *.test.js)
npm run test:smoke # JSON-RPC stdio smoke tests
node tests/test_client.js # All 44 tools against live DB
node tests/test_ai_watch_integrations.js # AI Watch paper integration suite
node scripts/benchmark_latency.js # End-to-end latency
node scripts/eval_accuracy.js # Precision/recallConvention:
*.test.js= automated tests ·test_*.js= stdio smoke tests
| Project / Service | Role |
|---|---|
| PG-Git-MCP | Semantic codebase search engine (sibling dependency) |
| Polygres.com | AI-native PostgreSQL cloud platform by Evokoa (pgContext & pgGraph native) |
| OpenRouter.ai | Unified cloud LLM & embedding API (baai/bge-large-en-v1.5) |
| AgentDebugX | Open-source failure observability, attribution, and recovery toolkit |
| Krusch Memory MCP | Legacy standalone memory (superseded) |
| Krusch Sequential MCP | Sequential thinking with PG persistence |
| Krusch Cascade Router | Automated LLM inference routing |
| NeoVertex Nuggets | Original Holographic Nuggets architecture |
This project is built upon and inspired by the following foundational research papers, architectural frameworks, and open-source projects:
- Polygres AI-Native Database: Postgres for the Agent Era by Evokoa combining relational, graph, and vector capabilities (Polygres.com).
- OpenRouter Embeddings Engine: Unified cloud embeddings API for
baai/bge-large-en-v1.5vector generation (OpenRouter.ai). - Company Brain Substrate (v2): Core concept and multi-layered organizational memory model inspired by the Sentra "Company Brain" Essay Series.
- Holographic Nuggets: Lightweight key-value steering facts adapted from the original NeoVertex Nuggets design.
- AgentDebugX Error Hub: Failure observability, trajectory root-cause attribution, and Error Hub recovery patch bundles powered by AgentDebugX.
- Lakebase Compute/Storage Decoupling: Storage routing and local-first compute cache separation inspired by the Neon Serverless Postgres Architecture.
- Tool Tracing & Optimization: Automated optimization of agent execution paths powered by the HALO RLM Engine.
- pgContext Vector Acceleration: Native PostgreSQL 17 HNSW index access method and single-pass metadata filtering powered by Evokoa pgContext.
- Agentic Context Management (ACM): Context lifecycle staging, compaction, eviction retention, and token budget auditing based on Gaurav Dadhich, Agentic Context Management: Solving Agent Memory and Cost by Treating Them as Lifecycle and Architecture Problems (ArXiv: 2607.21503).
- AgentDebugX (Failure Observability & Error Hub): Open-source toolkit for failure observability, trajectory root-cause attribution, and recovery patch bundles based on Wang et al., AgentDebugX: An Open-Source Toolkit for Failure Observability, Attribution, and Recovery in LLM Agents (AgentDebugX GitHub · ArXiv: 2607.18754).
- DataFlow-Harness (Grounded Code-Agent Platform): Grounded MCP operator registry and typed, schema-validated DAG mutations based on Zhang et al., DataFlow-Harness: A Grounded Code-Agent Platform for Constructing Editable LLM Data Pipelines (ArXiv: 2607.16617).
- Rubric4Setwise (Beyond Relevance-Centered Retrieval): Rubric-oriented document-set selection evaluating Redundancy, Conflict, and Complementarity into minimal covering sets based on Liu et al., Beyond Relevance-Centered Retrieval: Rubric-Oriented Document-Set Selection and Ranking (ArXiv: 2607.19238).
- AREX (Recursively Self-Improving Deep Research): Inner research evidence state paired with outer self-improvement constraint audits based on Lu et al., AREX: Towards a Recursively Self-Improving Agent for Deep Research (ArXiv: 2607.21461).
- Semantic Consolidation: Centroid-based semantic memory compression without re-embedding based on the Geometry of Consolidation repository.
- Proactive Memory Agent: Long-horizon execution warnings and memory-guided auditing based on Wu et al., Remember When It Matters: Proactive Memory Agent for Long-Horizon Agents (ArXiv: 2607.08716).
- Direct On-Policy Distillation (Direct-OPD): Weak-to-strong feedback distillation for proactive context rules based on Feng et al., Weak-to-Strong Generalization via Direct On-Policy Distillation (ArXiv: 2607.05394).
- Proxy Exploration and Reusable Guidance (PUST): Modular guidance paradigm using feedback traces based on Fu et al., Proxy Exploration and Reusable Guidance: A Modular LLM Post-Training Paradigm via Proxy-Guided Update Signals (ArXiv: 2607.11505).
- Granularity-Aware Search Policy (GRASP): Dynamic context depth expansion for search queries based on Gandhi et al., GRASP: GRanularity-Aware Search Policy for Agentic RAG (ArXiv: 2607.10463).
We welcome contributions! Please ensure tests pass and adhere to the project formatting standards.
MIT License © 2026 kruschdev
