PromptHub
Back to Blog
Developer Tools Artificial Intelligence

Stop Building Amnesic AI Agents: Daem0n-MCP Fixes Memory Forever

B

Bright Coding

Author

15 min read 76 views
Stop Building Amnesic AI Agents: Daem0n-MCP Fixes Memory Forever

Stop Building Amnesic AI Agents: Daem0n-MCP Fixes Memory Forever

Every developer who has worked with AI agents knows the gut-punch moment. You spend three hours architecting a complex authentication system with Claude, refining edge cases, documenting critical decisions. The next morning? Gone. The agent greets you with the same cheerful blank slate, ready to reinvent the same broken wheel. You scream into the void. The void doesn't remember either.

This isn't a bug. It's the fundamental amnesia baked into every LLM interaction. Context windows are glorified short-term memory. Markdown↗ Smart Converter files become digital graveyards—technically present, functionally invisible unless the agent decides to read them. And agents, bless their probabilistic hearts, often don't.

What if your AI could actually remember? Not just store text, but understand why decisions were made, when they failed, and how to avoid repeating catastrophes? What if it could dream—yes, dream—about your codebase while you sleep, re-evaluating past failures with fresh evidence?

Enter Daem0n-MCP. This isn't another vector database wrapper with a catchy name. It's a cognitive architecture for AI agents: persistent semantic memory, decision enforcement, autonomous learning loops, and retrieval so intelligent it routes queries by complexity like a neural traffic controller. With 500+ tests, 11 MCP tools, and 59 workflow actions, Daem0n-MCP transforms your agent from goldfish to oracle.

Ready to stop repeating yourself? Let's summon the daemon.


What is Daem0n-MCP?

Daem0n-MCP is an AI Memory & Decision System built on the Model Context Protocol (MCP). Created by 9thLevelSoftware, it gives AI agents something previously impossible: persistent, semantically-aware memory with active enforcement and continuous learning.

The project emerged from a brutal recognition: current AI tooling treats memory as passive storage. You write files. Maybe the agent reads them. Probably not. Daem0n-MCP inverts this paradigm entirely—memory becomes active, participatory, and intelligent.

The latest v6.6.6 release—codenamed ModernBERT Deep Sight—represents a quantum leap. The old all-MiniLM-L6-v2 embedding model is dead. Long live ModernBERT with asymmetric query/document encoding, 256-dimensional Matryoshka truncation, and optional ONNX acceleration. The daemon literally sees deeper now.

But the real magic isn't any single feature. It's the cognitive loop: agents store decisions, receive enforced rules before acting, record outcomes, and learn from failures autonomously. The system even dreams—re-evaluating failed decisions during idle periods with current evidence, persisting insights as tagged learning memories.

This isn't science fiction. It's shipping code with 500+ passing tests, Claude Code native hooks, OpenCode integration, and a workflow so refined that 67 separate tools consolidated into 8 workflow-oriented instruments with zero capability loss.

The developer community is taking notice because Daem0n-MCP solves the number one productivity killer in AI-assisted development: context loss. When your agent remembers that JWT auth failed last quarter, that synchronous database calls crashed production, that specific module patterns cause bugs—you stop being a broken record and start being a conductor.


Key Features That Separate Daem0n-MCP from Everything Else

ModernBERT Deep Sight: Vision Fundamentally Sharpened

The v6.6.6 embedding engine is a breaking change worth the pain. Old 384-dimensional MiniLM embeddings are replaced by ModernBERT's asymmetric architecture: encode_query() and encode_document() with task-specific prefixes (search_query: / search_document: ). The result? Retrieval accuracy that makes previous versions feel like reading through fog.

Capability Before (v5.x) After (v6.6.6)
Model all-MiniLM-L6-v2 nomic-ai/modernbert-embed-base
Dimensions 384 256 (Matryoshka truncation)
Encoding Single encode() Dual: encode_query() / encode_document()
Backend PyTorch only ONNX quantized + torch fallback
Prefixes None Query/document specific

Background Dreaming: Autonomous Nocturnal Learning

When you step away, the daemon doesn't sleep—it dreams. The IdleDreamScheduler monitors tool call activity, and after configurable idle timeout (default 60 seconds), triggers FailedDecisionReview. Past failures are re-evaluated with current evidence, classified as revised, confirmed_failure, or needs_more_data, and persisted as learning memories with dream tags.

This is cooperative scheduling—the moment you return, dreaming yields immediately. No lag. No interruption. Just a daemon that got smarter while you grabbed coffee.

Cognitive Tools: Meta-Reasoning Instruments

Three standalone MCP tools enable agent introspection:

  • simulate_decision: Temporal Scrying—replay past decisions with current knowledge, revealing what changed
  • evolve_rule: Rule Entropy Analysis—detect staleness, code drift, and outcome correlation degradation
  • debate_internal: Adversarial Council—structured evidence-grounded debate with convergence detection

These aren't toys. They're cognitive prosthetics for agents that need to reason about their own reasoning.

Auto-Zoom Retrieval Routing: Query-Aware Intelligence

Simple queries get vector-only search (fast path). Medium complexity triggers hybrid BM25+vector with RRF fusion. Complex queries activate GraphRAG multi-hop traversal with community summaries. Shadow mode logs classifications without behavioral changes, and everything falls back to hybrid on failure.

This is adaptive retrieval—the system recognizes what you're asking and dispatches the right cognitive machinery.

Claude Code Native Hooks: Five Lifecycle Integration Points

Automated installation via python↗ Bright Coding Blog -m daem0nmcp.cli install-claude-hooks registers:

Hook Event Purpose
session_start Session dawn Auto-briefing with context awareness
pre_edit PreToolUse (Edit/Write) Preflight enforcement + file memory recall
pre_bash PreToolUse (Bash) Rule enforcement on commands
post_edit PostToolUse (Edit/Write) Suggest remembrance for significant changes
stop Stop/SubagentStop Auto-capture decisions from conversation

Use Cases Where Daem0n-MCP Transforms Development

1. Long-Running Refactoring Projects

You're migrating a monolith to microservices. Over weeks, decisions accumulate: "Use gRPC for inter-service, REST for external", "Event sourcing for orders, CRUD for inventory". Without Daem0n-MCP, week three's agent contradicts week one's architecture. With it? The daemon surfaces conflicting decisions, enforces established patterns, and tracks which choices actually worked.

2. Onboarding Rotating AI Assistants

Different Claude sessions, same project, same amnesia. Daem0n-MCP's commune(action="briefing") delivers institutional memory on demand—recent decisions, active warnings, failed approaches, git changes, and pre-fetched context for declared focus areas. New session, same daemon. No ramp-up.

3. Safety-Critical Rule Enforcement

Production databases. Financial transactions. Medical data handling. The govern workflow creates decision trees with must_do, must_not, and ask_first constraints. The pre_bash hook intercepts dangerous commands. The preflight action validates changes against stored rules. This is memory as safety system, not suggestion engine.

4. Knowledge Graph Discovery

Legacy codebase, no documentation, original developers departed. The explore workflow with Leiden community detection builds hierarchical knowledge graphs from memory relationships. communities reveals functional clusters. chain traces causal paths between decisions. evolution shows how understanding developed over time. Archaeology accelerated.


Step-by-Step Installation & Setup Guide

Prerequisites

  • Python 3.10+
  • Git
  • Claude Code or OpenCode (optional but recommended)

Clone and Install

# Clone the repository
git clone https://github.com/9thLevelSoftware/Daem0n-MCP.git ~/Daem0nMCP

# Install in editable mode
pip install -e ~/Daem0nMCP

Platform-Specific Server Configuration

Linux/macOS (stdio transport—recommended):

# Find your Python executable path
python3 -c "import sys; print(sys.executable)"
# Example output: /usr/local/bin/python3

# Register with Claude Code (replace with your actual path)
claude mcp add daem0nmcp --scope user -- /usr/local/bin/python3 -m daem0nmcp.server

# Restart Claude Code to load tools
claude

Windows (HTTP transport required—stdio hangs due to known bug):

# Terminal 1: Start the server (keep running)
python ~/Daem0nMCP/start_server.py --port 9876
# Wait for: "Uvicorn running on http://localhost:9876"

# Terminal 2: Add to Claude configuration
# Edit ~/.claude.json manually or use:
claude mcp add daem0nmcp http://localhost:9876/mcp -s user

Manual ~/.claude.json configuration:

{
  "mcpServers": {
    "daem0nmcp": {
      "type": "http",
      "url": "http://localhost:9876/mcp"
    }
  }
}

Claude Code Hook Installation (Critical for Full Power)

# Automated installation—registers all 5 lifecycle hooks
python -m daem0nmcp.cli install-claude-hooks

# Verify in ~/.claude/settings.json, then restart Claude Code

OpenCode Setup

# Automated project-level configuration
python -m daem0nmcp.cli install-opencode

Or manual opencode.json:

{
  "$schema": "https://opencode.ai/config.json",
  "mcp": {
    "daem0nmcp": {
      "type": "local",
      "command": ["python", "-m", "daem0nmcp"],
      "enabled": true,
      "environment": {
        "PYTHONUNBUFFERED": "1"
      }
    }
  }
}

Windows OpenCode (HTTP transport):

{
  "$schema": "https://opencode.ai/config.json",
  "mcp": {
    "daem0nmcp": {
      "type": "remote",
      "url": "http://localhost:9876/mcp",
      "enabled": true
    }
  }
}

Post-Installation: Index Your Codebase

# Build semantic understanding of your code
python -m daem0nmcp.cli index

# Scan for latent technical debt
python -m daem0nmcp.cli scan-todos --auto-remember

Critical: v6.6.6 Embedding Migration

If upgrading from v5.x, existing embeddings must be re-encoded:

python -m daem0nmcp.migrations.migrate_embedding_model --project-path /path/to/.daem0nmcp

Qdrant collections auto-recreate with correct dimensions on first startup.


REAL Code Examples from the Repository

Example 1: The Old vs. New Workflow Paradigm

Daem0n-MCP v5.1 consolidated 67 individual tools into 8 workflow instruments. This transformation isn't cosmetic—it's cognitive ergonomics.

# ============================================================
# OLD WAY: 67 separate tools, massive context overhead
# ============================================================

# Each tool loads its own schema into the agent's context window
mcp__daem0nmcp__get_briefing(project_path="/home/user/myproject")
mcp__daem0nmcp__recall(topic="auth", project_path="/home/user/myproject")
mcp__daem0nmcp__remember(
    category="decision",
    content="Use JWT tokens instead of sessions",
    project_path="/home/user/myproject"
)
mcp__daem0nmcp__record_outcome(
    memory_id=42,
    outcome="JWT auth works great",
    worked=True,
    project_path="/home/user/myproject"
)

# ============================================================
# NEW WAY: 8 workflow tools, 88% fewer definitions
# ============================================================

# Single tool schema, action parameter selects operation
mcp__daem0nmcp__commune(action="briefing", project_path="/home/user/myproject")
mcp__daem0nmcp__consult(action="recall", topic="auth", project_path="/home/user/myproject")
mcp__daem0nmcp__inscribe(
    action="remember",
    category="decision",
    content="Use JWT tokens instead of sessions",
    project_path="/home/user/myproject"
)
mcp__daem0nmcp__reflect(
    action="outcome",
    memory_id=42,
    outcome_text="JWT auth works great",
    worked=True,
    project_path="/home/user/myproject"
)

Why this matters: LLM context windows are finite and expensive. Every tool schema consumes tokens. Reducing 67 schemas to 8 while preserving all 59 actions means more room for actual reasoning, faster tool selection, and lower API costs. The action parameter pattern groups logically related operations—commune for session lifecycle, consult for intelligence gathering, inscribe for memory creation—making the system's mental model intuitive for both humans and agents.


Example 2: Memory Storage with Semantic Richness

This example demonstrates how Daem0n-MCP captures decisions with multi-dimensional context that enables sophisticated retrieval later.

# Store a decision with full provenance for future retrieval
inscribe(
    action="remember",
    category="decision",           # Taxonomy: decision, pattern, warning, learning
    content="Use JWT tokens instead of sessions",
    rationale="Need stateless auth for horizontal scaling",
    tags=["auth", "architecture", "scalability"],
    file_path="src/auth/jwt.py"    # Spatial anchor: where this lives in codebase
)

# The daemon now understands this decision through multiple lenses:
# - Semantic: "authentication", "token", "stateless" will all match
# - Spatial: queries about src/auth/jwt.py surface this
# - Temporal: recency-weighted, with 30-day half-life for decisions
# - Social: tagged for discovery by related queries

The hidden power: Daem0n-MCP doesn't just store text. It indexes through ModernBERT embeddings (256-dim asymmetric), BM25 keyword matching, and entity extraction. A future query about "REST API authentication" will surface this memory even though "REST" and "API" appear nowhere in the original content. The semantic matching bridges conceptual gaps that keyword search cannot.


Example 3: Active Context—MemGPT-Style Working Memory

Some memories deserve always-hot status. The active context system maintains up to 10 pinned items with automatic expiration and duplicate prevention.

# Promote a memory to always-hot working context
inscribe(
    action="activate",
    memory_id=42,
    reason="Working on auth refactor—this decision is load-bearing",
    priority=10,                   # Higher priority = stronger injection
    expires_in_hours=8             # Auto-cleanup prevents stale context
)

# View all currently active memories
commune(action="active_context")
# Returns: list of hot memories with metadata, auto-injected into briefings

# Demote when no longer relevant
inscribe(action="deactivate", memory_id=42)

# Nuclear option: clear entire working memory
inscribe(action="clear_active")

Critical insight: This mirrors human working memory—limited capacity, actively managed, time-bounded. Without it, agents drown in irrelevant historical noise. With it, current priorities dominate without losing access to deeper history. The priority parameter enables nuanced conflict resolution when multiple active memories apply.


Example 4: Cognitive Tools—Agent Introspection in Action

These three tools elevate Daem0n-MCP from memory system to cognitive partner.

# ============================================================
# TEMPORAL SCRYING: Replay past decisions with current knowledge
# ============================================================
simulate_decision(decision_id=42)
# Returns: What would I decide differently today?
#          What evidence has emerged since the original decision?
#          Which assumptions have been validated or falsified?

# ============================================================
# RULE ENTROPY: Detect staleness and drift in enforced rules
# ============================================================
evolve_rule(rule_id=5)           # Deep analysis of single rule
evolve_rule()                     # Batch: all enabled rules
# Returns: Code drift correlation, outcome degradation,
#          recommendation to update, disable, or split rule

# ============================================================
# ADVERSARIAL COUNCIL: Structured debate with convergence detection
# ============================================================
debate_internal(
    topic="Database choice for session storage",
    advocate_position="Use Redis for sub-millisecond latency",
    challenger_position="Use PostgreSQL↗ Bright Coding Blog for ACID guarantees and existing ops expertise"
)
# Returns: Evidence-grounded arguments, identified trade-offs,
#          convergence detection (agreement reached?) or
#          structured disagreement with decision criteria

The paradigm shift: Most memory systems are retrospective—they look backward. Daem0n-MCP's cognitive tools are prospective—they improve future decisions. The debate_internal tool is particularly radical: it implements adversarial reasoning that surfaces hidden assumptions and prevents groupthink... even when the "group" is one agent.


Example 5: The Complete Agent Protocol

This is the recommended workflow that maximizes Daem0n-MCP's value. Copy it. Adapt it. Enforce it.

# ============================================================
# SESSION START: Orient the agent with full context
# ============================================================
commune(action="briefing")
# Auto-delivers: stats, recent decisions, warnings, failed approaches,
# git changes, plus pre-fetched context for declared focus areas

# ============================================================
# BEFORE CHANGES: Intelligence gathering and rule enforcement
# ============================================================
consult(action="preflight", description="Adding OAuth2 provider to auth service")
# Combined recall + rules check: surfaces relevant memories,
# validates against must_do/must_not constraints, generates warnings

consult(action="recall_file", file_path="src/auth/oauth2.py")
# File-specific memory retrieval: all decisions, patterns, warnings
# linked to this exact file

# ============================================================
# AFTER DECISIONS: Capture rationale while fresh
# ============================================================
inscribe(
    action="remember",
    category="decision",
    content="Use PKCE flow for mobile OAuth2 to prevent authorization code interception",
    rationale="Mobile apps cannot keep client secrets confidential per RFC 7636",
    tags=["auth", "oauth2", "mobile", "security"],
    file_path="src/auth/oauth2.py"
)

# ============================================================
# AFTER IMPLEMENTATION: Close the learning loop
# ============================================================
reflect(action="outcome", memory_id=43, outcome_text="PKCE flow implemented, penetration test passed", worked=True)
# Success reinforces: this decision gets normal relevance weighting

reflect(action="outcome", memory_id=44, outcome_text="Token refresh race condition caused logout storms", worked=False)
# Failure amplifies: 1.5x relevance boost in future recalls,
# warning classification, candidate for Background Dreaming re-evaluation

Why this protocol matters: It implements closed-loop learning. Most agents make decisions in open loops—act, forget, repeat. Daem0n-MCP's outcome recording with worked=True/False creates reinforcement signals that reshape future behavior. Failed decisions don't just persist; they're amplified, re-evaluated during idle periods, and surfaced proactively when similar situations arise.


Advanced Usage & Best Practices

Tuning Hybrid Search Weights

The DAEM0NMCP_HYBRID_VECTOR_WEIGHT environment variable (default 0.3) controls BM25 vs. vector balance. Increase for semantic-heavy codebases with consistent vocabulary. Decrease for domains with precise jargon where keyword matching dominates.

Leveraging Condensed Recall

Token-constrained agents should use condensed=True on consult(action="recall")—50-75% reduction with 150-character content truncation. Critical for long sessions near context limits.

Cross-Project Federation

Link related repositories for organizational memory:

maintain(action="link_project", project_path="../shared-lib")
# Memories from shared-lib surface in current project queries
# Break down silos without monorepo migration

Visual Mode for Complex Exploration

Append visual=True to workflow calls for interactive HTML interfaces via MCP Apps—D3.js-powered graph visualization, 10,000+ nodes at 60fps, no CDN dependencies.

Proactive Rule Evolution

Schedule periodic evolve_rule() calls in CI pipelines. Stale rules are more dangerous than no rules—they create false confidence while reality drifts.


Comparison with Alternatives

Capability Daem0n-MCP Plain Markdown Vector DB (Pinecone/Weaviate) MemGPT
Active enforcement ✅ Pre-action rules ❌ Passive only ❌ Retrieval only ⚠️ Limited
Semantic matching ✅ ModernBERT asymmetric ❌ None ✅ Basic embeddings ✅ Basic
Outcome learning ✅ Closed-loop with boosting ❌ None ❌ None ⚠️ Partial
Autonomous dreaming ✅ Idle re-evaluation ❌ None ❌ None ❌ None
Graph reasoning ✅ GraphRAG + Leiden ❌ None ❌ None ❌ None
Cognitive tools ✅ 3 meta-reasoning tools ❌ None ❌ None ❌ None
Bi-temporal queries valid_time vs transaction_time ❌ None ❌ None ❌ None
Context compression ✅ LLMLingua-2 (3x-6x) ❌ N/A ❌ N/A ❌ None
MCP native ✅ FastMCP 3.0 ❌ N/A ❌ Requires wrapper ❌ N/A
Lifecycle hooks ✅ 5 Claude Code hooks ❌ None ❌ None ❌ None
Setup complexity Medium (5 min with hooks) Low High Medium

The verdict: Plain markdown is free and worthless for active memory. Raw vector databases are powerful but passive—expensive infrastructure without cognitive architecture. MemGPT pioneered working memory but lacks enforcement, learning loops, and graph reasoning. Daem0n-MCP is the only system that unifies retrieval, enforcement, learning, and meta-cognition in a production-ready MCP package.


FAQ: What Developers Actually Ask

Is Daem0n-MCP production-ready?

Yes. 500+ tests, semantic versioning, automated migrations, and active development. The v6.6.6 release includes ONNX quantization and graceful fallbacks for reliability.

Does it work with GPT-4, Gemini, or local models?

Any MCP-compatible client. The memory system is client-agnostic. Claude Code and OpenCode have first-class integrations, but the underlying MCP server serves any compliant consumer.

How does it handle sensitive code?

Local by default. All storage is SQLite/Qdrant in .daem0nmcp/storage/daem0nmcp.db within your project. No cloud exfiltration. Optional remote Qdrant via DAEM0NMCP_QDRANT_URL for team scenarios.

What's the performance impact?

Minimal. ModernBERT embeddings run ONNX-quantized with torch fallback. BM25 indexing is incremental. Background dreaming yields cooperatively. Typical tool call latency: <200ms for simple queries, <1s for complex GraphRAG traversals.

Can I migrate from v5.x without losing data?

Yes, with one step. Run the embedding migration command (documented above). Database schema migrations apply automatically. Legacy tools remain registered for backward compatibility during transition.

How does this differ from just using RAG?

RAG is retrieval. Daem0n-MCP is cognition. RAG fetches relevant documents. Daem0n-MCP enforces rules before actions, learns from outcomes, dreams during idle time, debates internally, and evolves its own understanding. It's the difference between a library and a research partner.

What if the daemon makes wrong connections?

Surprise scoring and verification tools. The surprise_score (0.0-1.0) flags novel information. The verify action validates claims against stored knowledge. The debate_internal tool surfaces conflicting interpretations. Nothing is blindly trusted.


Conclusion: Stop Building Amnesic Systems

The most expensive bug in software isn't a null pointer or race condition. It's repeated context loss—the endless re-discovery of decisions already made, failures already experienced, patterns already established.

Daem0n-MCP doesn't just solve this. It inverts the problem. Memory becomes active, participatory, and intelligent. Your agent doesn't read files and hope—it receives enforced briefings, validated preflights, and amplified warnings from past failures. It dreams about your codebase while you sleep. It debates itself when uncertain.

This is what AI-assisted development was supposed to be: continuous, cumulative, compounding intelligence.

The installation takes five minutes. The hooks take two. The first time your agent says "Wait—you tried this approach before and it failed. Here's what happened..."—you'll understand why the daemon's vision is worth summoning.

Install Daem0n-MCP now. Give your agents the memory they deserve. Stop repeating yourself. Start building systems that learn.

"The system learns from YOUR outcomes. Record them faithfully..." — Daem0n

Comments (0)

Comments are moderated before appearing.

No comments yet. Be the first to share your thoughts!