SurajAiri/mcp_mongodb
If you are the rightful owner of mcp_mongodb and would like to certify it and/or have it hosted online, please leave a comment on the right or send an email to henry@mcphub.com.
A Model Context Protocol (MCP) server for MongoDB operations, providing a seamless interface for database interactions through async operations.
MCP MongoDB
A Model Context Protocol (MCP) server for MongoDB operations, providing a seamless interface for database interactions through async operations.
Author: Suraj Airi ()
Overview
MCP MongoDB is a FastMCP-based server that enables MongoDB database operations through a standardized protocol. It provides tools for document management, querying, and collection operations with full async support using Motor (the async Python driver for MongoDB).
Features
- Async MongoDB Operations: Full async support using Motor
- Document Management: Create, read, update, delete operations
- Flexible Querying: Support for complex MongoDB queries with pagination
- Environment Configuration: Easy setup through environment variables
- Error Handling: Comprehensive error handling and logging
- MCP Protocol: Standardized interface through Model Context Protocol
Installation
Prerequisites
- Python 3.8+
- MongoDB instance (local or remote)
- uv package manager (recommended)
Using uv (Recommended)
Install uv if you haven't already:
# On macOS and Linux
curl -LsSf https://astral.sh/uv/install.sh | sh
# On Windows
powershell -c "irm https://astral.sh/uv/install.ps1 | iex"
Install dependencies:
uv sync
Or install specific packages:
uv add motor fastmcp python-dotenv pymongo
Using pip (Alternative)
pip install motor fastmcp python-dotenv pymongo
Installation for Claude Desktop
To use this MCP server with Claude Desktop, follow these steps:
-
Clone the repository:
git clone <repository-url> cd mcp_mongodb
-
Install dependencies:
uv sync
-
Configure Claude Desktop:
Add the following configuration to your Claude Desktop settings file:
On macOS:
~/Library/Application Support/Claude/claude_desktop_config.json
On Windows:
%APPDATA%\Claude\claude_desktop_config.json
mcp install mcp_mongodb/server.py
{ "mcpServers": { "mcp-mongodb": { "command": "uv", "args": ["run", "python", "/path/to/your/mcp_mongodb/server.py"], "env": { "MONGODB_URI": "mongodb://localhost:27017", "MONGODB_DB_NAME": "your_database_name", "MONGODB_COLLECTION_NAME": "your_collection_name" } } } }
Replace
/path/to/your/mcp_mongodb/main.py
with the actual path to your project. -
Restart Claude Desktop to load the new MCP server.
-
Verify Installation:
In Claude Desktop, you should now be able to use MongoDB operations. Try asking Claude to "list all available tools" to see the MongoDB tools.
Configuration
Environment Variables
Create a .env
file in your project root:
MONGODB_URI=mongodb://localhost:27017
MONGODB_DB_NAME=your_database_name
MONGODB_COLLECTION_NAME=your_collection_name
Default Values
If environment variables are not set, the following defaults are used:
MONGODB_URI
:mongodb://localhost:27017
MONGODB_DB_NAME
:default_db
MONGODB_COLLECTION_NAME
:default_collection
Project Structure
mcp_mongodb/
āāā mongo_db.py # MongoDB operations class
āāā main.py # MCP server implementation
āāā .env # Environment configuration
āāā pyproject.toml # uv project configuration
āāā uv.lock # uv lock file
āāā README.md # This file
Usage
Starting the Server
from main import mcp
# The server will automatically start with the configured lifespan
# MongoDB connection is established on startup and closed on shutdown
Available Tools
1. Setup MongoDB Connection
setup_mongodb(
db_uri="mongodb://localhost:27017",
db_name="my_database",
collection_name="my_collection"
)
2. Add Document
add_document({
"name": "John Doe",
"age": 30,
"email": "john@example.com"
})
# Returns: {"inserted_id": "document_id"}
3. Get Document by ID
get_document("document_id")
# Returns: The document or {"error": "Document not found"}
4. Update Document
update_document(
document_id="document_id",
update_fields={"age": 31, "status": "active"}
)
# Returns: {"modified_count": 1}
5. Delete Document
delete_document("document_id")
# Returns: {"deleted_count": 1}
6. Find Documents
find_documents(
query={"age": {"$gte": 18}},
limit=10,
offset=0
)
# Returns: {"documents": [...]}
7. Get All Documents
get_all_documents(limit=100, offset=0)
# Returns: {"documents": [...]}
8. Count Documents
count_documents(
query={"status": "active"},
limit=0,
offset=0
)
# Returns: {"count": 42}
Available Resources
MongoDB Configuration
# Resource URI: mongodb://config
get_mongodb_config()
# Returns current MongoDB configuration
MongoDB Operations Class
The MongoDbOperations
class provides low-level MongoDB operations:
Methods
insert_document(collection, document)
: Insert a single documentfind_document(collection, query)
: Find a single documentupdate_document(collection, query, update)
: Update documents matching queryupdate_document_by_id(collection, document_id, update)
: Update by document IDdelete_document(collection, query)
: Delete documents matching querydelete_document_by_id(collection, document_id)
: Delete by document IDfind_all_documents(collection, query, limit, offset)
: Find multiple documents with paginationcount_documents(collection, query, limit, offset)
: Count documents with optional constraintsget_document_by_id(collection, document_id)
: Get document by ID
Error Handling
The server includes comprehensive error handling:
- Connection Errors: Handled during MongoDB client initialization
- Document Not Found: Returns appropriate error messages
- Invalid ObjectId: Handled in ID-based operations
- Insert/Update/Delete Failures: Proper error responses
Logging
Logging is configured but commented out by default. To enable logging, uncomment the logging configuration in main.py
:
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
filename='mcp_mongodb.log'
)
Example Usage
Basic Document Operations
import asyncio
from main import mcp
async def example_usage():
# Add a document
result = await add_document({
"name": "Alice Smith",
"age": 28,
"department": "Engineering"
})
document_id = result["inserted_id"]
# Get the document
document = await get_document(document_id)
print(f"Retrieved: {document}")
# Update the document
await update_document(document_id, {"age": 29})
# Find documents
engineers = await find_documents({"department": "Engineering"})
print(f"Engineers: {engineers['documents']}")
# Count documents
count = await count_documents({"age": {"$gte": 25}})
print(f"Adults: {count['count']}")
# Run the example
asyncio.run(example_usage())
Contributing
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature
) - Install development dependencies:
uv sync --dev
- Make your changes
- Add tests if applicable
- Commit your changes (
git commit -m 'Add some amazing feature'
) - Push to the branch (
git push origin feature/amazing-feature
) - Open a Pull Request
Development Setup
# Clone the repository
git clone <repository-url>
cd mcp_mongodb
# Install dependencies with uv
uv sync --dev
# Run tests (if available)
uv run pytest
# Run the server locally
uv run python main.py
Support
For issues and questions:
- Email:
- Create an issue in the repository
- Check the MongoDB Motor documentation for database-specific questions
- Review the FastMCP documentation for MCP-related questions
Author
Suraj Airi
Email:
Changelog
Version 1.0.0
- Initial release
- Basic CRUD operations
- MCP protocol support
- Async MongoDB operations
- Environment-based configuration
Note:
This is my first open-source shareable project so i might lack standards of maintaining the code. You are always welcome to help setup properly.