Home/Content/Local MCP Memory Server: Building a Persistent Multi-Agent Memory System with Node.js & MongoDB

Local MCP Memory Server: Building a Persistent Multi-Agent Memory System with Node.js & MongoDB

Ranit Saha
March 25, 2026
5 min read

Explore a real MCP memory server built with Node.js and MongoDB enabling persistent AI memory, multi-agent collaboration, and intelligent context retrieval.

AI systems today break down when multiple agents or users interact with the same project. They overwrite each other, lose context, and operate without coordination. This project addresses that gap by building a persistent, collaboration-safe memory and coordination layer using MCP, Node.js, and MongoDB.

Instead of isolated agents, this system enables stateful, multi-agent collaboration with shared memory, task orchestration, and conflict-aware updates.


Overview

This system extends MCP beyond memory into a full coordination backend for AI agents and humans.

Core architecture:

  • mcp-server.js → MCP stdio interface (JSON-RPC)

  • server.js → Express API + MongoDB persistence

  • MongoDB → stores memory, tasks, locks, activity, issues, and metrics

The system transforms the traditional flow:

Agent executes → user waits

into:

Agents + users collaborate → shared state → conflict-aware updates

Key Features

1. Project Descriptor System

Defines baseline identity and rules of a project.

This becomes the entry point for any agent, ensuring:

  • consistent understanding of the system

  • reduced ambiguity


2. Persistent Memory with Lifecycle + Ranking

Memory is not flat storage. It includes:

  • ranking

  • lifecycle states

  • version tracking

From the underlying implementation:

score += matches * 2;
score += (item.importance || 3) * 2;
score += Math.max(0, 5 - ageHours / 24);
score += Math.log((item.accessCount || 0) + 1);

This ensures retrieval is context-aware and relevance-driven.


3. Context Graph Retrieval

Unlike simple search, this system can connect:

  • memory

  • tasks

  • issues

  • actions

  • agents

This enables graph-like contextual reasoning, not isolated lookups.


4. Task Orchestration Engine

Supports:

  • task creation

  • priority scoring

  • scheduling

  • capability-aware assignment

This moves agents from execution units to workflow participants.


5. Soft Locking System

acquire_resource_lock → work → release_resource_lock

Used for:

  • files

  • modules

  • tasks

This prevents conflicts without blocking humans.

Key design principle:

warn and coordinate, not hard-block


6. Activity Stream (Real-Time Awareness)

Agents publish activity events:

  • what they are doing

  • what changed

  • what is in progress

This creates observability for collaboration.


7. Agent Registry + Heartbeats

Tracks:

  • active agents

  • health status

Allows the system to understand who is working on what in real time.


8. Error + Action Logging

From implementation (logger.js):

await dbInstance.collection(\"logs\").insertOne({
  type: \"error\",
  message: error.message
});

Errors are also converted into memory entries:

const memory = new ContextModel({
  type: \"error\",
  content: error.message
});

This creates self-improving behavior over time.


How It Works

End-to-End Flow

Agent (Codex / Roo)
 → MCP (stdio JSON-RPC)
 → mcp-server.js
 → HTTP API (server.js)
 → MongoDB
 → Response back to agent

Example: Context Storage

await callMemoryApi(\"/context\", {
  method: \"POST\",
  headers: { \"Content-Type\": \"application/json\" },
  body: JSON.stringify({
    agent: CONFIG.agent,
    project: CONFIG.project,
    scope: CONFIG.scope,
    content: args.content
  })
});

Example: Query Builder Logic

MemoryQueryBuilder.build({
  agent,
  project,
  query,
  scope,
  includeGlobal
});

This dynamically composes:

  • $or conditions for scope

  • $text search


Example: Safe Startup Pattern

let startupPromise = null;

if (!startupPromise) {
startupPromise = startServer({ silent: true });
}

Prevents duplicate server instances in MCP runtime.


System Mode Workflow

Derived from project docs:

  1. Read project descriptor

  2. Search memory

  3. Fetch tasks + messages

  4. Check activity + locks

  5. Claim work

  6. Execute

  7. Store memory + log action


Tech Stack

  • Node.js (ESM)

  • Express.js

  • MongoDB

  • MCP (stdio JSON-RPC)

Core files:

  • mcp-server.js → protocol layer

  • server.js → API + DB

  • mcp.model.js → models + query builder

  • logger.js → logging + memory conversion

  • mcp-shim.js → auto project detection


Implementation Highlights

database.collection(\"contexts\").createIndex({
  content: \"text\",
  summary: \"text\",
  tags: \"text\"
});

Without this, /context/search breaks.


2. Memory Normalization

export function normalizeMemory(memory) {
  return {
    ...memory,
    importance: memory.importance ?? 3,
    accessCount: memory.accessCount || 0
  };
}

Ensures consistency across all stored entities.


3. MCP Protocol Safety

  • stdout → JSON-RPC only

  • logs → DB or stderr

Critical to prevent protocol corruption.


4. Project Auto-Detection

const projectRoot = findProjectRoot(process.cwd());

Removes need for manual configuration.


5. Collaboration-Safe Updates

From docs behavior:

  • version checks

  • timestamp validation

  • conflict warnings

I’m not certain about the exact implementation of version conflict resolution in code, but the system clearly enforces overlap detection instead of silent overwrites.


Use Cases

1. Multi-Agent Development Systems

Agents collaborate on:

  • codebases

  • features

  • debugging


2. AI Project Managers

With tasks, issues, and activity tracking:

  • planning becomes automated

  • execution becomes coordinated


3. Long-Term AI Memory Systems

Agents retain:

  • architecture decisions

  • patterns

  • fixes


4. Human + AI Collaboration Platforms

Humans and agents work together with:

  • visibility

  • coordination

  • reduced conflicts


Future Improvements

Based on current structure:

  • vector embeddings (embedding field already exists)

  • automated task prioritization tuning

  • stronger conflict resolution strategies

  • distributed deployment (multi-node MCP servers)

  • real-time streaming instead of polling


  • MCP architecture deep dive → /blogs/model-context-protocol-architecture

  • Designing AI collaboration systems → /blogs/multi-agent-ai-system-design


Conclusion

This project moves MCP from a memory tool into a full collaboration infrastructure layer.

Key shift:

  • from isolated agents

  • to coordinated, stateful systems

The combination of:

  • memory

  • tasks

  • locks

  • activity

  • agents

creates a system where AI is no longer just reactive — it becomes participatory and coordinated.

For advanced AI systems, this is the foundation for:

  • scalability

  • reliability

  • real collaboration


📎 Reference docs and implementation: https://coderooz.github.io/Local-MCP-Memory-Server/

Comments(0)

Local MCP Memory Server: Building a Persistent Multi-Agent Memory System with Node.js & MongoDB | Coderooz