Explore a real MCP memory server built with Node.js and MongoDB enabling persistent AI memory, multi-agent collaboration, and intelligent context retrieval.
Modern AI agents are powerful, but they suffer from one fundamental limitation: they forget everything between sessions. This project solves that problem by introducing a persistent, structured memory layer using the Model Context Protocol (MCP), backed by a real Node.js + MongoDB implementation.
Instead of treating AI as stateless responders, this system turns them into long-term collaborators that learn, remember, and evolve across projects.
Overview
This project implements a fully functional MCP memory server that enables:
Persistent memory across sessions
Shared memory across multiple agents
Project-aware context isolation
Searchable and ranked knowledge retrieval
At its core, this is not just an API — it is memory infrastructure for AI systems.
The system is split into two layers:
MCP Protocol Layer (
mcp-server.js) → Handles agent communication via JSON-RPC over stdioPersistence Layer (
server.js) → Handles storage, querying, and ranking using MongoDB
Key Features
1. Persistent Memory (Context Model)
Memory is stored using ContextModel, which includes:
content,summaryimportance,accessCounttags,metadata
This allows the system to store structured, reusable knowledge, not just raw text.
2. Multi-Agent Memory Isolation
Memory is scoped using:
agentprojectscope(private,project,global)
This prevents cross-contamination while still allowing shared knowledge.
3. Intelligent Search + Ranking
Search is not just MongoDB text search — it’s enhanced with custom ranking logic:
score += matches * 2;
score += (item.importance || 3) * 2;
score += Math.max(0, 5 - ageHours / 24);
score += Math.log((item.accessCount || 0) + 1);This means results are ranked by:
keyword relevance
importance
recency
usage frequency
4. Action Tracking System
Every meaningful change is logged using ActionModel:
actionTypetargetsummarycontextRefs
This creates a traceable history of work, not just static memory.
5. Automatic Project Detection (mcp-shim.js)
The shim dynamically detects project context:
const projectRoot = findProjectRoot(process.cwd());
const derivedProject = slugifyProjectName(path.basename(projectRoot));This removes the need for manual configuration and ensures clean project-level memory separation.
6. Logging as Memory
Errors are not just logged — they are converted into memory entries:
const memory = new ContextModel({
type: \"error\",
content: error.message,
tags: [\"error\", \"debug\"]
});This enables the system to learn from failures automatically.
How It Works
Full Flow (Agent → Memory)
Agent sends MCP request via stdio
mcp-server.jsparses JSON-RPCTool call maps to HTTP request
server.jsprocesses requestMongoDB stores/retrieves data
Response flows back to agent
Architecture:
Agent
→ MCP Server (stdio JSON-RPC)
→ HTTP API (Express)
→ MongoDBExample: Store Memory Flow
await callMemoryApi(\"/context\", {
method: \"POST\",
body: JSON.stringify({
agent: CONFIG.agent,
project: CONFIG.project,
scope: CONFIG.scope,
content: args.content
})
});Example: Search Flow
const baseQuery = MemoryQueryBuilder.build({
agent,
project,
query,
scope,
includeGlobal
});The query builder dynamically composes MongoDB filters using:
$orfor scope logic$textfor search
Tech Stack
Node.js (ES Modules)
Express.js for HTTP API
MongoDB for persistence
MCP (Model Context Protocol) via stdio JSON-RPC
UUID for identity generation
Key modules:
server.js→ API + DBmcp-server.js→ protocol layermcp.model.js→ schema + query builderlogger.js→ logging + error-to-memorymcp-shim.js→ project auto-detection
Implementation Highlights
1. Startup Safety (Singleton Server)
let startupPromise = null;
if (!startupPromise) {
startupPromise = startServer({ silent: true });
}
Prevents multiple server instances inside MCP runtime.
2. Indexing Strategy
database.collection(\"contexts\").createIndex({
content: \"text\",
summary: \"text\",
tags: \"text\"
});Search depends on this index — without it, queries will fail.
3. Memory Normalization
export function normalizeMemory(memory) {
return {
...memory,
importance: memory.importance ?? 3,
accessCount: memory.accessCount || 0,
updatedAt: new Date()
};
}Ensures consistent structure across all memory types.
4. MCP Protocol Safety Rule
stdout → JSON-RPC only
logs → DB or stderr
Breaking this will corrupt protocol communication.
5. Resilient API Calls
await waitForServer(CONFIG.serverUrl);Ensures MCP server does not call API before it's ready.
Use Cases
This system enables entirely new classes of AI systems:
1. Long-Term AI Assistants
Agents remember:
past decisions
architecture constraints
recurring bugs
2. Multi-Agent Collaboration
Different agents share:
patterns
fixes
project knowledge
3. Self-Improving Systems
Because errors are stored as memory:
system learns automatically
repeated failures reduce over time
4. Debugging Systems with Memory
Agents can recall:
past bugs
root causes
previous fixes
Future Improvements
Based on current architecture, these upgrades are realistic:
Vector embeddings (replace text search)
Auto importance scoring
Conflict resolution between memory entries
Health monitoring + auto-restart
The current schema already supports embedding, but it is not used yet — suggesting planned semantic search.
Links
Github Repostiory : https://github.com/coderooz/Local-MCP-Memory-Server
Conclusion
This project transforms AI systems from:
stateless responders
into:
persistent, learning collaborators
What makes it powerful is not just storage — but structure + workflow + integration with MCP.
The combination of:
scoped memory
ranked retrieval
action tracking
error learning
creates a foundation for self-evolving AI systems.
If you're building advanced AI tooling, this is not optional infrastructure — it's the missing layer.