MCP HubMCP Hub
1RB

mongo-mcp

by: 1RB

MCP server that provide tools to LLMs such as claude in cursor to interact with MongoDB

7created 05/03/2025
Visit
MongoDB
LLM

πŸ“ŒOverview

Purpose: The MongoDB MCP Server enables Large Language Models (LLMs) to interact seamlessly with MongoDB databases using natural language queries.

Overview: This server utilizes the Model Context Protocol (MCP), an open standard that allows AI systems to connect with external data sources and tools. It acts as a bridge between MCP clients (like AI assistants) and MongoDB databases, facilitating enhanced data manipulation and retrieval in a user-friendly manner.

Key Features:

  • Collection Schema Inspection: Enables users to view and understand the structure of database collections for improved navigation and data handling.

  • Document Querying and Filtering: Allows users to perform specific queries and apply filters to retrieve only relevant documents based on criteria.

  • Index Management: Facilitates the creation and management of indexes to optimize query performance and database efficiency.

  • Document Operations: Supports essential operations such as inserting, updating, and deleting documents within collections.

  • Secure Database Access: Ensures connection security via connection strings, safeguarding the database against unauthorized access.

  • Comprehensive Error Handling: Implements robust validation and error handling measures to enhance user experience and maintain integrity.


πŸ—„οΈ MongoDB MCP Server for LLMS

A Model Context Protocol (MCP) server that enables LLMs to interact directly with MongoDB databases. Query collections, inspect schemas, and manage data seamlessly through natural language.

πŸ“š What is Model Context Protocol (MCP)?

The Model Context Protocol (MCP) is an open standard developed by Anthropic that creates a universal way for AI systems to connect with external data sources and tools. MCP establishes a standardized communication channel between:

  • MCP Clients: AI assistants like Claude that consume data (e.g., Claude Desktop, Cursor.ai)
  • MCP Servers: Services that expose data and functionality (like this MongoDB server)

Key benefits of MCP:

  • Universal Access: Provides a single protocol for AI assistants to query data from various sources
  • Standardized Connections: Handles authentication, usage policies, and data formats consistently
  • Sustainable Ecosystem: Promotes reusable connectors that work across multiple LLM clients

✨ Features

  • Collection schema inspection
  • Document querying and filtering
  • Index management
  • Document operations (insert, update, delete)
  • Secure database access through connection strings
  • Comprehensive error handling and validation

πŸ“‹ Prerequisites

Before you begin, ensure you have:

  • Node.js (v18 or higher)
  • MongoDB instance (local or remote)
  • An MCP client like Claude Desktop or Cursor.ai

Verify your Node.js installation by running:

node --version  # Should show v18.0.0 or higher

πŸš€ Quick Start

Find your MongoDB connection URL and add this configuration to your Claude Desktop config file:

MacOS: ~/Library/Application\ Support/Claude/claude_desktop_config.json
Windows: %APPDATA%/Claude/claude_desktop_config.json

{
  "mcpServers": {
    "mongodb": {
      "command": "npx",
      "args": [
        "mongo-mcp",
        "mongodb://<username>:<password>@<host>:<port>/<database>?authSource=admin"
      ]
    }
  }
}

Installing via Smithery

Smithery.ai is a registry platform for MCP servers that simplifies discovery and installation. To install MongoDB MCP Server for Claude Desktop automatically via Smithery:

npx -y @smithery/cli install mongo-mcp --client claude

Cursor.ai Integration

To use MongoDB MCP with Cursor.ai:

  1. Open Cursor.ai and navigate to Settings > Features
  2. Look for "MCP Servers" in the features panel
  3. Add a new MCP server with the following configuration:
    • Name: mongodb
    • Command: npx
    • Args: mongo-mcp mongodb://<username>:<password>@<host>:<port>/<database>?authSource=admin

Note: Cursor currently supports MCP tools only in the Agent in Composer feature.

Test Sandbox Setup

If you don't have a MongoDB server and want to create a sample sandbox:

  1. Start MongoDB using Docker Compose:
docker-compose up -d
  1. Seed the database with test data:
npm run seed

Configure Claude Desktop

Add this configuration to your Claude Desktop config file for local development:

{
  "mcpServers": {
    "mongodb": {
      "command": "node",
      "args": [
        "dist/index.js",
        "mongodb://root:example@localhost:27017/test?authSource=admin"
      ]
    }
  }
}

Test Sandbox Data Structure

The seed script creates three collections with sample data:

Users

  • Personal info (name, email, age)
  • Nested address with coordinates
  • Arrays of interests
  • Membership dates

Products

  • Product details (name, SKU, category)
  • Nested specifications
  • Price and inventory info
  • Tags and ratings

Orders

  • Order details with items
  • User references
  • Shipping and payment info
  • Status tracking

🎯 Example Prompts

Try these prompts with Claude to explore functionality:

Basic Operations

"What collections are available in the database?"
"Show me the schema for the users collection"
"Find all users in San Francisco"

Advanced Queries

"Find all electronics products that are in stock and cost less than $1000"
"Show me all orders from the user john@example.com"
"List the products with ratings above 4.5"

Index Management

"What indexes exist on the users collection?"
"Create an index on the products collection for the 'category' field"
"List all indexes across all collections"

Document Operations

"Insert a new product with name 'Gaming Laptop' in the products collection"
"Update the status of order with ID X to 'shipped'"
"Find and delete all products that are out of stock"

πŸ“ Available Tools

Query Tools

  • listCollections: Lists available collections
  • find: Queries documents with filtering and projection
  • insertOne: Inserts a single document
  • updateOne: Updates a single document
  • deleteOne: Deletes a single document

Index Tools

  • createIndex: Creates a new index
  • dropIndex: Removes an index
  • indexes: Lists indexes for a collection

πŸ› οΈ Development

This project uses:

  • TypeScript
  • MongoDB Node.js driver
  • Zod for schema validation
  • Model Context Protocol SDK

Set up the development environment:

npm install
npm run build
npm run dev
npm test

πŸ”’ Security Considerations

When using this MCP server with your MongoDB database:

  • Create a dedicated MongoDB user with minimal permissions
  • Never use admin credentials in production
  • Enable access logging for auditing
  • Set appropriate read/write permissions
  • Use connection string parameters to restrict access (e.g., readPreference=secondary)
  • Consider IP allow-listing

⚠️ Always follow the principle of least privilege.

🌐 How It Works

The MongoDB MCP server:

  1. Connects to your MongoDB database using the connection string
  2. Exposes MongoDB operations as tools following the MCP specification
  3. Validates inputs using Zod for safety and security
  4. Executes queries and returns structured data to the LLM client
  5. Manages connection pooling and error handling

All operations include validation to prevent injection and security issues.

πŸ“¦ Deployment

Deploy the MCP server:

  • Locally via npx
  • Globally via npm: npm install -g @coderay/mongo-mcp-server
  • In a Docker container
  • As a service on platforms like Heroku, Vercel, or AWS

❓ Troubleshooting

Common Issues

  • Connection Errors: Check connection string, server availability, network permissions
  • Authentication Issues: Verify credentials, auth database, TLS/SSL requirements
  • Tool Execution Problems: Restart client, check logs (e.g., on macOS: tail -n 20 -f ~/Library/Logs/Claude/mcp*.log)
  • Performance Issues: Add indexes, use projection and pagination

Getting Help

🀝 Contributing

Contributions are welcome! Submit a Pull Request:

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

πŸ“œ License

This project is licensed under the MIT License.