MongoDB MCP Server: Build an AI Agent for Natural-Language Mongo Queries
Nikhil Tiwari
MCP Playground
Updated: May 18, 2026 โ added the hosted MongoDB MCP option (one-click cloud deploy, live URL + bearer token).
๐ MCP Recipe
- What you'll build: An AI agent that talks to MongoDB in natural language โ queries, aggregations, schema inspection, and Atlas cluster management
- MCP server:
mongodb-mcp-server(official, maintained by mongodb-js) - Fast path: Deploy hosted MongoDB MCP โ live HTTPS URL + token in ~30 seconds, no install
- Local path: 10โ15 minutes (Node.js + connection string)
- Difficulty: Beginner-friendly
โก Skip the install โ spin up a hosted MongoDB MCP server in seconds
If you don't want to keep npx mongodb-mcp-server running on a laptop or pay for a long-lived VM, deploy the hosted MongoDB MCP server on MCP Playground. Same official mongodb-mcp-server, managed for you.
- Live HTTPS URL + bearer token in ~30 seconds โ paste your Mongo connection string into a form, click Deploy
- Runs in an isolated cloud sandbox โ your connection string never leaves the deployment, the URL is gated by the bearer token
- Works with Claude Desktop, Cursor, Claude Code, MCP Agent Studio and any MCP-compatible agent
- Free tier: 1 active server, 10 min/month. Pro tiers add more slots and runtime
- Same tool surface (
find,aggregate,countDocuments,$indexStats, Atlas Admin) โ your prompts port 1:1
The MongoDB MCP server turns any Claude, GPT-5, Gemini, DeepSeek or Grok client into a Mongo-fluent analyst. It exposes your collections, the aggregation framework, indexes, the slow-query profiler and Atlas cluster controls as MCP tools โ so you can ask "show me daily signups for the last 30 days, broken down by source" and get an actual aggregate() pipeline run against your data.
This recipe covers both paths: the hosted route (~30 seconds, no install) for anyone who wants to get started immediately, and the self-hosted route for teams that need to run the server on their own network or against a database that's only reachable from a private VPC. The walkthrough then covers five queries that show off analytics, debugging and ops tasks, and explains connection-string mode (any Mongo) vs Atlas service-account mode (cluster management).
What the MongoDB MCP Server Provides
The server is maintained by the official mongodb-js org and ships as the mongodb-mcp-server npm package. It exposes two distinct toolsets, depending on which credentials you pass at startup:
| Toolset | How to enable | What you can do |
|---|---|---|
| Database tools | Pass --connectionString "mongodb+srv://โฆ" |
List databases and collections, run find, aggregate, countDocuments, inspect indexes, profile slow queries, infer schemas from samples |
| Atlas tools | Pass --apiClientId + --apiClientSecret |
List clusters, check replica-set status, view metrics, manage database users, inspect Atlas Search indexes |
You can pass both at once for a fully-armed agent. The --readOnly flag locks the server to non-mutating commands โ strongly recommended until you trust write operations.
Prerequisites
For npx โ no global install needed
Local, Atlas, or self-hosted โ anything reachable via a connection string
Strongly recommended โ create a user with read-only roles for the DBs you want to expose
Step 1: Start the Server with HTTP Transport
The default transport is stdio (good for Claude Desktop / Cursor). For browser-based clients like MCP Agent Studio you need HTTP โ pass --transport http:
npx -y mongodb-mcp-server@latest \
--transport http \
--connectionString "mongodb+srv://USER:PASS@your-cluster.mongodb.net/your-db" \
--readOnly
The server listens on http://127.0.0.1:3000 by default. Override with --httpHost and --httpPort if needed. Keep the process running โ in production you'll want it under pm2, systemd, or in a container.
Security
The HTTP transport has no built-in auth. Run it on localhost only, or front it with a reverse proxy that adds an auth header before exposing it publicly. Never put a connection string with write privileges on a public endpoint.
Step 2: Connect from MCP Agent Studio (Browser, No Install)
Easiest way to drive the server: MCP Agent Studio. Pick the pre-built MongoDB Agent template โ it ships with a system prompt tuned for analytics, schema work and aggregation pipelines.
- Open /templates/mongodb-agent and click Open in Studio.
- Paste
http://localhost:3000/mcpinto the MCP server URL field. - Pick a model โ Claude Sonnet 4.5 is the default; Opus 4.7 is the strongest for complex aggregation pipelines.
- Send a first message: "List all databases on this cluster."
If you'd rather use Claude Desktop or Cursor, skip the --transport http flag โ those clients speak stdio natively.
Step 3: Five Queries That Show What the Agent Can Do
1. Schema discovery
Prompt
"Sample 100 documents from the users collection and tell me the field types โ flag any field that's sometimes missing or has inconsistent types."
The agent uses the mongodb-aggregate tool with a $sample stage, then infers the schema. Useful when joining a project with no schema docs, or when you suspect a producer is writing the wrong shape.
2. Natural-language analytics
Prompt
"Daily signups for the last 30 days, grouped by signup source. Sort newest first."
The model writes a pipeline with $match on createdAt, $group by date and source, $sort descending. You see the pipeline before it runs โ copy it into your code if you want to reuse it.
3. Index audit
Prompt
"Which indexes on the events collection have not been used in the last 24 hours? Show me which ones I can safely drop."
Calls $indexStats and filters by accesses.ops and accesses.since. Surfaces dead indexes that are wasting RAM. Pair with the "recommend an index for this slow query" prompt for a full index review.
4. Slow-query triage
Prompt
"Look at system.profile from the last hour. Group slow queries by ns and tell me which collections are getting hammered, with the worst offending shape for each."
Requires the profiler to be enabled (db.setProfilingLevel(1, { slowms: 100 })). The agent groups queries by namespace, surfaces the worst command shape, and suggests an index when the answer is obvious.
5. Atlas cluster snapshot
Prompt
"Give me a one-paragraph status of every cluster in this Atlas project โ name, region, tier, and any node that's lagging in replica set sync."
Only works when you start the server with --apiClientId + --apiClientSecret. The Atlas toolset uses the public Atlas Admin API under the hood.
Picking the Right Model
Mongo aggregation pipelines are non-trivial to write, so model choice matters more here than for, say, a Slack-message agent.
| Model | When to pick it |
|---|---|
| Claude Opus 4.7 | Complex multi-stage pipelines, schema inference across heterogeneous documents, when correctness > cost |
| Claude Sonnet 4.5 | Default. Handles 95% of analytics queries, much cheaper |
| GPT-5.4 | Strong on Atlas-side ops (cluster status, user management); slightly weaker than Claude on aggregation pipeline composition |
| DeepSeek V4 Pro | Cheapest competent option โ good for batch jobs that run the same prompt against many collections |
Use Compare mode in Agent Studio to send the same Mongo prompt to two models side-by-side โ you'll see whose pipeline is correct in seconds.
Connection String vs Atlas Service Account
Two auth modes, two different sets of tools โ easy to confuse:
- Connection string (
--connectionString): Standard MongoDB URI. The agent can read/write data and inspect schemas. Works with any Mongo (local, Atlas, RDS-style hosted Mongo, self-hosted). This is what you want for analytics. - Atlas service account (
--apiClientId+--apiClientSecret): Atlas Admin API credentials. The agent can manage clusters, users, network access lists, and Search indexes โ but cannot read your data. This is what you want for ops.
Pass both for the full picture. Create the service account at cloud.mongodb.com โ Access Manager โ Service Accounts.
Production Notes
- Always pair
--readOnlywith prod connection strings until you've verified the system prompt prevents accidental writes. - Use a dedicated read-only DB user. Don't reuse the user your app writes with. Grant only the databases the agent should see.
- The HTTP transport has no auth. Bind to
127.0.0.1, or front with an auth proxy. Never expose0.0.0.0:3000to the public internet. - Profiler queries can be heavy. If you enable the slow-query profiler, scope it to a database (not all of them) and use
slowms: 100or higher. - Aggregation result sizes can blow up the model's context window. The default system prompt in the MongoDB Agent template caps results at 50 documents โ keep that in your own prompts.
Skip the install โ get a hosted MongoDB MCP in 30 seconds
Live HTTPS URL + bearer token, managed cloud sandbox. Works with Claude Desktop, Cursor, MCP Agent Studio and any MCP-compatible agent. Free tier available.
Deploy hosted MongoDB MCP โ Open MongoDB Agent templateRelated Recipes
- PostgreSQL MCP: Build a Claude Analytics Agent
- Build an AI Database Query Assistant (Supabase MCP)
- Best AI Model for MCP Tool Calling
Frequently Asked Questions
Hosted vs self-hosted MongoDB MCP โ which should I use?
mongodb-mcp-server tool surface โ your prompts and pipelines port 1:1.Does the official MongoDB MCP server support write operations?
insert, update, delete and DDL commands. Pass --readOnly to lock it to non-mutating commands. Until you trust the system prompt, always pair production credentials with --readOnly.Is there a hosted MongoDB MCP server I can use without running anything myself?
mongodb-mcp-server. Click MongoDB on /mcp-hosted, paste your connection string, click Deploy โ you get a live HTTPS URL and bearer token in ~30 seconds. There's still no first-party endpoint at a URL like mcp.mongodb.com from MongoDB Inc., so for now the hosted option is either MCP Playground's managed deployment or self-hosting on your own infrastructure.Can I use this with MongoDB Atlas?
--connectionString for data tools, and an Atlas service-account client ID + secret to --apiClientId / --apiClientSecret for cluster-management tools. You can pass both at the same time.Why does the agent need to see my schema first?
$sample stage) to learn field names and types. This is normal โ once it has the schema for a collection it caches it for the rest of the conversation.Which AI model is best for MongoDB aggregation pipelines?
Written by Nikhil Tiwari
15+ years in product development. AI enthusiast building developer tools that make complex technologies accessible to everyone.
Free MCP Tools (no install)
Test any MCP server with 30+ AI models โ free
Connect any MCP endpoint and chat with Claude, GPT-5, Gemini, DeepSeek and more. Watch every tool call live.
โฆ Free credits on sign-up ยท no credit card needed