MongoDB Storage for MCP Servers

Learn how to implement MongoDB storage integration for Model Context Protocol servers

MongoDB Storage Integration for MCP

Overview

MongoDB provides a flexible document-based storage solution for MCP servers, particularly well-suited for storing model contexts and related metadata. This guide covers implementing MongoDB as a storage provider for your MCP server.

Prerequisites

  • MongoDB 6.0 or higher
  • Node.js 18 or higher
  • MCP server base implementation
  • MongoDB Compass (optional, for visualization)

Implementation

// filepath: /path/to/MongoDBStorage.ts
import { MongoClient, Collection } from 'mongodb';

interface ContextDocument {
  _id: string;
  data: Buffer;
  metadata?: Record<string, any>;
  createdAt: Date;
  updatedAt: Date;
}

class MongoDBStorage implements MCPStorageProvider {
  private collection: Collection<ContextDocument>;

  constructor(uri: string, dbName: string) {
    const client = new MongoClient(uri);
    this.collection = client.db(dbName).collection('contexts');
  }

  async initialize(): Promise<void> {
    await this.collection.createIndex({ _id: 1 });
    await this.collection.createIndex({ updatedAt: 1 });
  }

  async storeContext(contextId: string, data: Buffer): Promise<void> {
    await this.collection.updateOne(
      { _id: contextId },
      {
        $set: {
          data,
          updatedAt: new Date()
        },
        $setOnInsert: {
          createdAt: new Date()
        }
      },
      { upsert: true }
    );
  }

  async retrieveContext(contextId: string): Promise<Buffer> {
    const doc = await this.collection.findOne({ _id: contextId });
    if (!doc) {
      throw new Error('Context not found');
    }
    return doc.data;
  }
}