MO

MongoDB MCP Server: Mongoose Schema and Validation

Secure MCP server data by implementing MongoDB with Mongoose schemas and validation to ensure robust, consistent, and scalable models.

Quick Install
npx -y @nabid-pf/mongo-mongoose-mcp

Overview

This repository implements an MCP (Model Context Protocol) server backed by MongoDB and Mongoose. It provides a structured way to persist model context and related data with well-defined schemas, validation rules, and optional indexes so stored entries remain consistent, secure, and scalable. By using Mongoose schemas, the server enforces shape and types for documents before they reach the database, reducing runtime errors and making downstream model behavior more predictable.

For developers building LLM integrations, chat systems, or any service that needs to store contextual model state, this MCP server supplies a practical starting point: connection management, schema examples, validation handling, and simple API endpoints to create, read, and manage model context entries. The project is lightweight and meant to be extended into production-ready services with additional auth, rate-limits, and monitoring.

Features

  • Mongoose-based schemas enforcing types, required fields, and custom validation
  • Central MongoDB connection logic with environment configuration
  • Example schemas for model context entries (timestamps, indexes)
  • Validation error handling that maps Mongoose errors to HTTP responses
  • Simple REST-style examples (create / read) ready to extend
  • Clear examples showing how to add custom pre-save hooks and virtuals

Installation / Configuration

Clone and install dependencies:

git clone https://github.com/nabid-pf/mongo-mongoose-mcp.git
cd mongo-mongoose-mcp
npm install

Create a .env file (example variables):

MONGO_URI=mongodb://localhost:27017
MONGO_DBNAME=mcp_db
PORT=4000

Common environment variables:

VariableDescriptionExample
MONGO_URIMongoDB connection stringmongodb://localhost:27017
MONGO_DBNAMEDatabase name to usemcp_db
PORTPort for the HTTP server4000

Start the server:

npm start
# or for development
npm run dev

Example minimal server connection (Node/Express + Mongoose):

const express = require('express');
const mongoose = require('mongoose');

const app = express();
app.use(express.json());

const uri = process.env.MONGO_URI;
const dbName = process.env.MONGO_DBNAME;
mongoose.connect(uri, { dbName, useNewUrlParser: true, useUnifiedTopology: true });

app.listen(process.env.PORT || 4000, () => {
  console.log('MCP server running');
});

Schema and Validation Examples

A representative Mongoose schema for a model context entry:

const mongoose = require('mongoose');

const ContextSchema = new mongoose.Schema({
  modelId: { type: String, required: true, index: true },
  userId: { type: String, required: true },
  context: { type: Array, required: true, default: [] },
  intent: { type: String, enum: ['qa', 'dialog', 'retrieval'], default: 'dialog' },
  metadata: { type: Object, default: {} },
}, {
  timestamps: true
});

// Example pre-save hook
ContextSchema.pre('save', function(next) {
  if (this.context.length > 5000) {
    return next(new Error('Context length exceeds allowed limit'));
  }
  next();
});

module.exports = mongoose.model('ModelContext', ContextSchema);

Validation is enforced by Mongoose: missing required fields or invalid enums cause a ValidationError. Handle those errors and return clear API responses:

app.post('/contexts', async (req, res) => {
  try {
    const ctx = new ModelContext(req.body);
    const saved = await ctx.save();
    res.status(201).json(saved);
  } catch (err) {
    if (err.name === 'ValidationError') {
      return res.status(400).json({ error: 'validation_error', details: err.errors });
    }
    res.status(500).json({ error: 'server_error' });
  }
});

Available Resources

  • GitHub repository: https://github.com/nabid-pf/mongo-mongoose-mcp
  • Mongoose docs: https://mongoosejs.com/docs/guide.html
  • MongoDB docs: https://docs.mongodb.com/manual/

Use these resources to customize schema design, add compound indexes, and tune connection options for production.

Use Cases

  • Chatbot persistent memory: store per-user or per-session message contexts so a model can resume conversations with relevant history.
    • Example: store last N turns, enrich with metadata like sentiment or topic for retrieval.
  • Retrieval-augmented generation (RAG): persist embedding references or vector IDs in metadata and use them to fetch supporting passages.
  • Long-term analytics and auditing: validated schemas make it straightforward to run analytics queries on structured fields (intent, userId, timestamps).
  • Orchestration and state machines: track model-driven state transitions with schema-enforced enums and timestamps for reliable replay/debugging.

With the provided schema patterns and validation handling, you can extend the MCP server to support authentication, versioned contexts, TTL indexes for expiry, or integration with vector stores — all while keeping stored data consistent and predictable.