Skip to main content
Glama
Sahilkr02

MongoDB Memory MCP Server

by Sahilkr02
README.md
# MongoDB Memory MCP Server

[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
[![Node.js Version](https://img.shields.io/badge/node-%3E%3D20.0.0-brightgreen.svg)](https://nodejs.org/)
[![MCP Spec Compliance](https://img.shields.io/badge/MCP_Spec-2026--07--28-blue.svg)](https://modelcontextprotocol.io/)
[![Tests](https://img.shields.io/badge/tests-99%20passed-success.svg)](tests/)

A production-grade, collaborative **MongoDB Memory Model Context Protocol (MCP) Server** built using Node.js (ES Modules), MongoDB 7.0, and the official `@modelcontextprotocol/sdk`.

Acts as a persistent long-term memory engine for AI agents (Claude Desktop, Cursor, Antigravity, Gemini CLI, or custom AI agents), enabling them to store, search, update, delete, retrieve, and summarize structured project memories across developer workflows.

---

## šŸ“‹ Table of Contents

- [Features](#-features)
- [Tech Stack](#-tech-stack)
- [Folder Structure](#-folder-structure)
- [Prerequisites](#-prerequisites)
- [Installation](#-installation)
- [Environment Variables](#-environment-variables)
- [Running Locally](#-running-locally)
- [Production Build & Docker](#-production-build--docker)
- [Package Scripts](#-package-scripts)
- [API Reference](#-api-reference)
- [Client Configuration](#-client-configuration)
- [Troubleshooting](#-troubleshooting)
- [Security](#-security)
- [Roadmap](#-roadmap)
- [Contributing](#-contributing)
- [Code Style](#-code-style)
- [License](#-license)
- [Acknowledgements](#-acknowledgements)

---

## ✨ Features

- **2026-07-28 MCP Specification Compliant**: Mandatory `server/discover` RPC, stateless `_meta` parsing, `"resultType": "complete"`, `ttlMs` / `cacheScope` indicators, Streamable HTTP headers (`Mcp-Method`, `Mcp-Name`), and deterministic tool sorting.
- **15 Modular MCP Tools**: Standardized CRUD operations, score-weighted full-text search, tag filtering, type filtering, recency listing, project context summarization, and Atlas Vector Search readiness.
- **6 Dynamic Context Resources (`memory://`)**: Exposes live readable project context URIs (`memory://project/{projectId}`, `memory://decision/{projectId}`, `memory://bugs/{projectId}`, etc.).
- **6 Reusable AI Prompt Templates**: Automated prompt generators for architecture reviews, code reviews, documentation generation, and sprint summaries.
- **Developer Onboarding REST APIs**: Management endpoints for projects (`/api/projects`), developers (`/api/developers`), project-bound API keys (`/api/keys`), and signed JWT tokens (`/api/tokens`).
- **Dynamic Scope Isolation**: Automatically binds `req.auth.projectId` via MongoDB API key lookup to enforce tenant memory isolation.
- **Dual Transport Modes**: Local desktop IDEs via Stdio (`npm start`) and remote network agents via Streamable HTTP (`npm run start:http`) at `http://localhost:3000/messages`.
- **Auto-Generated Postman Collection**: Live downloadable Postman collection v2.1.0 available at `GET /postman.json`.
- **Case-Insensitive Searching**: Case-insensitive regex matching ensuring `TodoNative`, `todonative`, and `TODONATIVE` match 100% reliably.
- **Comprehensive Test Suite**: **99 unit & integration tests passing** across 21 test suites (`vitest` + `mongodb-memory-server`).

---

## šŸ› ļø Tech Stack

- **Runtime**: Node.js 20+ LTS (ES Modules)
- **MCP SDK**: `@modelcontextprotocol/sdk` (v1.5.0+)
- **Database**: MongoDB 7.0+ (`mongodb` Native Node Driver)
- **Web Server**: Express v4.21.2 & Cors v2.8.5
- **Schema Validation**: `zod` v3.24.1
- **Security & Auth**: `jsonwebtoken` v9.0.2
- **Logger**: `winston` v3.17.0 (Stderr-safe structured JSON logger)
- **Testing**: `vitest` v3.0.4 & `mongodb-memory-server` v10.1.3
- **Containerization**: Docker & Docker Compose

---

## šŸ“‚ Folder Structure

```text
mongodb-mcp/
ā”œā”€ā”€ docs/                              # Comprehensive documentation suite (11 guides)
ā”œā”€ā”€ src/                               # Application source code
│   ā”œā”€ā”€ config/                        # Environment & config validation
│   ā”œā”€ā”€ database/                      # MongoDB connection pool & indexing
│   ā”œā”€ā”€ mcp/                           # MCP 2026-07-28 protocol handlers
│   ā”œā”€ā”€ middleware/                    # Express auth & protocol middleware
│   ā”œā”€ā”€ models/                        # Protocol constants & error hierarchy
│   ā”œā”€ā”€ prompts/                       # MCP Prompt Templates Engine
│   ā”œā”€ā”€ repositories/                  # MongoDB Data Access Repositories
│   ā”œā”€ā”€ resources/                     # MCP Dynamic Resources (`memory://`)
│   ā”œā”€ā”€ schemas/                       # Zod validation schemas
│   ā”œā”€ā”€ services/                      # Core Business Logic Services
│   ā”œā”€ā”€ tools/                         # Modular MCP Tools Registry (15 tools)
│   ā”œā”€ā”€ transports/                    # Transport layer (Express HTTP / SSE)
│   ā”œā”€ā”€ utils/                         # Logger, errors, Postman generator
│   └── server.js                      # Main server entrypoint & bootstrap
ā”œā”€ā”€ tests/                             # Vitest Test Suite (99 tests)
│   ā”œā”€ā”€ unit/                          # Unit test files
│   └── integration/                   # Integration test files
ā”œā”€ā”€ Dockerfile                         # Multi-stage production Dockerfile
ā”œā”€ā”€ docker-compose.yml                 # Docker Compose deployment stack
ā”œā”€ā”€ package.json                       # Dependencies & npm scripts
└── README.md                          # Master GitHub README
```

---

## āš™ļø Prerequisites

- **Node.js**: `>=20.0.0 LTS`
- **npm**: `>=10.0.0`
- **MongoDB**: `7.0+` (Local instance or Docker container)

---

## šŸ“„ Installation

```bash
# 1. Clone repository
git clone https://github.com/your-username/mongodb-memory-mcp.git
cd mongodb-memory-mcp

# 2. Install dependencies
npm install

# 3. Create environment configuration
cp .env.example .env
```

---

## šŸ”‘ Environment Variables

| Variable | Default Value | Description |
|---|---|---|
| `NODE_ENV` | `development` | Environment mode (`development`, `production`, `test`) |
| `TRANSPORT` | `stdio` | MCP Transport mode (`stdio` or `http`) |
| `PORT` | `3000` | HTTP port when `TRANSPORT=http` |
| `MONGODB_URI` | `mongodb://localhost:27017/agent_memory` | MongoDB connection URI |
| `LOG_LEVEL` | `info` | Logging verbosity (`error`, `warn`, `info`, `debug`) |
| `ENABLE_AUTH` | `false` | Enable/disable authentication middleware |
| `API_KEY` | `your_admin_api_key_here` | Master Admin API key |
| `JWT_SECRET` | `your_jwt_secret_here` | Secret for signing JWT tokens (min 32 chars) |

---

## šŸš€ Running Locally

```bash
# Start MongoDB via Docker Compose
docker-compose up -d mongodb

# Launch in Stdio Mode (Default for local desktop IDEs)
npm start

# Launch in HTTP Network Mode (Port 3000)
npm run start:http
```

---

## 🐳 Production Build & Docker

```bash
# Build & run entire container stack
docker-compose up -d --build

# View container logs
docker-compose logs -f mcp-server
```

---

## šŸ“œ Package Scripts

| Script | Command | Purpose |
|---|---|---|
| `npm start` | `node src/server.js` | Launch server in Stdio mode |
| `npm run start:http` | `TRANSPORT=http node src/server.js` | Launch server in HTTP network mode |
| `npm test` | `vitest run` | Execute 99 unit & integration tests |
| `npm run lint` | `eslint .` | Execute ESLint code quality checks |
| `npm run format` | `prettier --write .` | Format codebase with Prettier |
| `npm run check-connection` | `node src/utils/testConnection.js` | Execute connection diagnostics |
| `npm run generate-auth` | `node src/utils/generateAuth.js` | CLI helper to generate API keys & JWTs |

---

## šŸ”Œ Client Configuration

### Streamable HTTP Mode (Antigravity, Cursor, VS Code, Gemini CLI)
```json
{
  "mcpServers": {
    "mongodb-memory": {
      "url": "http://localhost:3000/messages",
      "type": "streamable-http",
      "headers": {
        "X-API-Key": "mcp-memory-api-key"
      }
    }
  }
}
```

### Stdio Subprocess Mode (Claude Desktop)
```json
{
  "mcpServers": {
    "mongodb-memory": {
      "command": "node",
      "args": ["/Users/sahil/Projects/mongodb-mcp/src/server.js"],
      "env": {
        "TRANSPORT": "stdio",
        "MONGODB_URI": "mongodb://localhost:27017/agent_memory"
      }
    }
  }
}
```

---

## šŸ“– API Documentation

Complete API documentation for REST endpoints, MCP tools, resources, and prompt templates is available in [docs/API_REFERENCE.md](docs/API_REFERENCE.md) and [docs/USER_GUIDE.md](docs/USER_GUIDE.md).

---

## šŸ›”ļø Security Policy

Please review our [SECURITY.md](SECURITY.md) for vulnerability reporting guidelines.

---

## šŸ¤ Contributing

We welcome contributions! Please see [CONTRIBUTING.md](CONTRIBUTING.md) and our [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md) for guidance.

---

## šŸ“„ License

Distributed under the MIT License. See [LICENSE](LICENSE) for details.

---

## šŸ™ Acknowledgements

- [Model Context Protocol (MCP)](https://modelcontextprotocol.io/) by Anthropic
- [MongoDB Native Node Driver](https://github.com/mongodb/node-mongodb-native)
- [Express Framework](https://expressjs.com/)