Build a MongoDB Atlas MCP Server for Agentic Data Access & Vector Search
MongoDB launched the Atlas Managed MCP Server on August 14, 2026, making live operational data a first-class resource for AI coding agents. This guide builds atlas-mcp, a FastMCP TypeScript gateway that exposes read-only tools for querying Atlas collections and Atlas Vector Search, with inputSchema JSON contracts, result caps, field allowlists, and OAuth 2.0 / API-key security — the governed pattern teams need before agents touch production data.
Deepak Bagada
CEO, SaaSNext
- MongoDB launched the Atlas Managed MCP Server on Aug 14, 2026; atlas-mcp is the self-hosted FastMCP TypeScript counterpart with the same governed-access discipline.
- Expose read-only tools by default — findDocuments, aggregateDocuments, vectorSearch — with inputSchema JSON contracts, result caps, and field allowlists.
- OAuth 2.0 client-credentials with cached, self-refreshing tokens (or an API key for fast starts) keeps agent access authenticated and auditable.
- The agentic recall pattern chains vector search + filtered aggregation into grounded answers where every claim maps to a real document id.
By Deepak Bagada, CEO at SaaSNext & Principal AI Architect.
When MongoDB launched the Atlas Managed MCP Server on August 14, 2026, it made live operational data a first-class resource for AI coding agents — Claude Code, Codex, Grok Build, and Devin can now query Atlas collections and Atlas Vector Search through a hosted MCP endpoint. But for teams that need the data plane under their own control — VPC placement, custom redaction, bespoke tool surfaces — a self-hosted FastMCP gateway is the pattern that fits. This guide builds atlas-mcp: a FastMCP TypeScript server exposing governed, read-only MongoDB Atlas tools with inputSchema JSON contracts, result caps, field allowlists, and OAuth 2.0 security. The MCP directory has tracked the agent-data integration wave all year; this is the production-grade pattern for it.
Why a gateway over the managed server
The managed tier is the right default for most teams — zero ops, MongoDB-hosted auth, auto-scaling. A custom FastMCP gateway is the right call when you need:
- Data-plane control — the server lives in your VPC, egress is your policy.
- Custom tool surfaces — you shape exactly which queries agents may run, with domain-specific tools instead of generic CRUD.
- Redaction and audit — interpose field-level PII stripping and per-call audit logging that the managed endpoint may not offer.
- Least-privilege scoping — per-collection allowlists baked into the gateway, independent of the Atlas user's broader rights.
The gateway discipline is the same one the AI workflows library applies to every agent tool surface: agents are only as trustworthy as the surfaces you give them.
Architecture
flowchart LR
A[Claude / Cursor / Agent] -->|MCP JSON-RPC| B[atlas-mcp FastMCP Server]
B -->|OAuth 2.0 / API key| C[MongoDB Atlas Data API]
B -->|MongoDB driver| D[Atlas cluster]
D --> E[Collections]
D --> F[Atlas Vector Search index]
B --> G[Audit log / redaction hook]
The server sits between the agent and Atlas. Every tool call passes the gateway, which authenticates, authorizes, shapes the query, caps results, redacts fields, and logs the call.
Project setup
mkdir atlas-mcp && cd atlas-mcp
npm init -y
npm install @modelcontextprotocol/sdk fastmcp mongodb dotenv express
# .env
ATLAS_CONNECTION_STRING=mongodb+srv://<user>:<pass>@cluster0.mongodb.net/
ATLAS_DATABASE=support
ATLAS_ALLOWED_COLLECTIONS=tickets,articles,products
ATLAS_READ_ROLE=readOnly
MCP_PORT=3001
AUTH_MODE=apikey # or oauth
MCP_API_KEY=sk-atlas-mcp-local-dev
REDACT_FIELDS=email,phone,ssn
Server implementation
// server.ts — atlas-mcp FastMCP TypeScript gateway
import { FastMCP } from 'fastmcp';
import { MongoClient, Db } from 'mongodb';
import dotenv from 'dotenv';
dotenv.config();
const client = new MongoClient(process.env.ATLAS_CONNECTION_STRING!);
let db: Db;
const allowed = new Set(
(process.env.ATLAS_ALLOWED_COLLECTIONS || '').split(',').map((s) => s.trim())
);
const redactFields = (process.env.REDACT_FIELDS || '').split(',').map((s) => s.trim());
function guardCollection(name: string) {
if (!allowed.has(name)) throw new Error(`collection not allowed: ${name}`);
}
function redact(doc: Record<string, any>) {
const out = { ...doc };
for (const f of redactFields) delete out[f];
return out;
}
const server = new FastMCP({ name: 'atlas-mcp', version: '0.1.0' });
// 1. findDocuments — typed read-only query tool
server.addTool({
name: 'findDocuments',
description: 'Query documents from an allowlisted Atlas collection with optional filter, projection, limit and skip.',
inputSchema: {
type: 'object',
properties: {
collection: { type: 'string', description: 'Collection name (allowlisted)' },
filter: { type: 'object', description: 'MongoDB query filter (JSON)' },
projection: { type: 'object', description: 'Field projection (JSON)' },
limit: { type: 'number', minimum: 1, maximum: 50, default: 10 },
skip: { type: 'number', minimum: 0, default: 0 },
},
required: ['collection'],
},
async execute(args: any) {
guardCollection(args.collection);
const coll = db.collection(args.collection);
const docs = await coll
.find(args.filter || {}, { projection: args.projection })
.skip(args.skip || 0)
.limit(Math.min(args.limit || 10, 50))
.toArray();
return { count: docs.length, documents: docs.map(redact) };
},
});
// 2. aggregateDocuments — bounded aggregation pipeline
server.addTool({
name: 'aggregateDocuments',
description: 'Run a bounded aggregation pipeline on an allowlisted collection (max 3 stages, capped output).',
inputSchema: {
type: 'object',
properties: {
collection: { type: 'string' },
pipeline: { type: 'array', description: 'Aggregation stages (JSON array, max 3)', maxItems: 3 },
limit: { type: 'number', minimum: 1, maximum: 50, default: 10 },
},
required: ['collection', 'pipeline'],
},
async execute(args: any) {
guardCollection(args.collection);
const stages = (args.pipeline || []).slice(0, 3).concat([{ $limit: Math.min(args.limit || 10, 50) }]);
const docs = await db.collection(args.collection).aggregate(stages).toArray();
return { count: docs.length, documents: docs.map(redact) };
},
});
// 3. vectorSearch — Atlas Vector Search with $vectorSearch
server.addTool({
name: 'vectorSearch',
description: 'Semantic search over an Atlas Vector Search index with top-k hits.',
inputSchema: {
type: 'object',
properties: {
collection: { type: 'string' },
indexName: { type: 'string', default: 'default' },
queryVector: { type: 'array', items: { type: 'number' }, description: 'Embedding vector' },
k: { type: 'number', minimum: 1, maximum: 20, default: 5 },
filter: { type: 'object', description: 'Optional pre-filter (JSON)' },
},
required: ['collection', 'queryVector'],
},
async execute(args: any) {
guardCollection(args.collection);
const pipeline = [
{
$vectorSearch: {
index: args.indexName || 'default',
queryVector: args.queryVector,
path: 'embedding',
limit: Math.min(args.k || 5, 20),
filter: args.filter || {},
},
},
{ $project: { _id: 1, title: 1, body: 1, score: { $meta: 'vectorSearchScore' } } },
];
const docs = await db.collection(args.collection).aggregate(pipeline).toArray();
return { hits: docs.map(redact) };
},
});
async function main() {
await client.connect();
db = client.db(process.env.ATLAS_DATABASE || 'support');
await server.start({ transportType: 'http', port: Number(process.env.MCP_PORT || 3001) });
console.log('atlas-mcp listening on', process.env.MCP_PORT || 3001);
}
main().catch((e) => { console.error(e); process.exit(1); });
Client configuration (mcpServers)
{
"mcpServers": {
"atlas-mcp": {
"command": "npx",
"args": ["tsx", "server.ts"],
"env": {
"ATLAS_CONNECTION_STRING": "mongodb+srv://...",
"ATLAS_DATABASE": "support",
"ATLAS_ALLOWED_COLLECTIONS": "tickets,articles",
"REDACT_FIELDS": "email,phone,ssn"
}
}
}
}
OAuth 2.0 & API-key security guide
The gateway supports two auth modes. For production, use OAuth 2.0 client-credentials: the server holds a client id/secret, exchanges them for an Atlas Data API token, caches it, and self-refreshes before expiry — agents never see credentials, and every call carries a scoped, short-lived token. For local development, an API key (MCP_API_KEY) in the Authorization header is fine, with the same read-only Atlas role. Add an auth middleware that rejects unauthenticated requests, and log every tool call (agent, tool, collection, row count) to an append-only audit store — the same access-control discipline the MCP directory applies to every production MCP integration.
The agentic recall workflow
The gateway shines in a recall pattern: an agent answers questions from your own data. Flow: (1) embed the question, (2) vectorSearch for top-k semantically similar documents, (3) aggregateDocuments or findDocuments for fresh metadata, (4) synthesize an answer where every claim carries a document id. Because every tool is read-only, capped, and field-filtered, the agent can answer grounded questions without ever endangering the data. That is the same grounded-recall discipline the AI workflows library documents for production RAG.
Result caps and token efficiency
Two design decisions in this gateway deserve emphasis because they decide whether the deployment stays cheap or burns budget. The first is the hard result cap. Every tool clamps its output — findDocuments to 50 documents, aggregateDocuments to a bounded pipeline, vectorSearch to 20 hits — so no single tool call can return 100K documents and flood the agent's context window. The second is shaped output. Each tool returns only the fields the agent needs, plus a count, rather than entire documents. Together these two rules keep the tool-output token bill flat even as agent usage grows, which is the difference between a gateway you can forget about and a gateway that becomes a line item in your monthly AI spend. When you wire the gateway into an agent like Claude Code or Cursor, tune the caps to your actual task mix and watch the token telemetry for a week before raising anything.
Testing the gateway before agents touch it
Before connecting a real agent, run a dry integration pass: start the server, list the tools with the MCP inspector, invoke findDocuments against a staging collection with a deliberately broad filter, and confirm the cap and redaction behave. Then attempt the operations you want to block — a write, a non-allowlisted collection, a request that exceeds the cap — and confirm each one errors cleanly. This pre-flight pass catches the two most common failure modes: a missing guardCollection check that lets an agent reach a sensitive collection, and a redaction list that does not match the actual field names in your documents. Both are configuration errors, not code errors, and both are cheap to catch before production agents connect.
Deployment and operations
Run the gateway as a managed process with its own service account, restart policy, and health endpoint, and keep the MongoDB driver version pinned. The connection string should reference a read-only Atlas user with a role scoped to the allowed collections — the gateway can enforce collection allowlists, but defense in depth means the database user cannot write even if the gateway logic is bypassed. Set a log level that captures every tool invocation with the agent id, collection, and row count, and ship those logs to your audit pipeline. If you later need write access for agents, add it as a separate, explicitly gated tool behind human approval — never by widening the existing read tools.
The bottom line
MongoDB's Atlas Managed MCP Server made live data a first-class agent resource on August 14, 2026; atlas-mcp is the self-hosted FastMCP TypeScript counterpart for teams that need data-plane control. Read-only tools with inputSchema contracts, collection allowlists, result caps, redaction, and OAuth/API-key auth keep the surface governed. Build the gateway, wire it into your agent config, and give your agents live, governed access to the data that actually matters. More agent-data patterns are in the AI workflows library.
One operational note worth repeating: the gateway's value is proportional to how narrowly you scope it. A gateway that can read three collections with capped, redacted output is a safe tool; a gateway that can read everything is a liability wearing a safety label. Start narrow, measure what agents actually query, and widen only what the evidence justifies.
Frequently Asked Questions
What is atlas-mcp?
A FastMCP TypeScript server that exposes governed, read-only MongoDB Atlas tools — findDocuments, aggregateDocuments, vectorSearch — to AI agents via the Model Context Protocol.
Why build our own if MongoDB launched a managed MCP server?
The managed tier is zero-ops, but self-hosted gives you data-plane control: VPC placement, custom field redaction, and tool surfaces the managed endpoint may not offer yet.
How do agents authenticate?
OAuth 2.0 client-credentials flow with a cached, self-refreshing token, or a static API key for fast starts — both scoped to read-only Atlas permissions.
How do I stop agents from reading sensitive fields?
Field allowlists on every tool, collection allowlists in config, result caps, and a redact hook that strips configured sensitive fields from tool output.
What does the agent workflow look like?
The literature-recall pattern: vectorSearch top-k hits, filtered aggregation for metadata, and a grounded answer where every claim carries a document id.
Closing thoughts
The Atlas Managed MCP Server launch legitimized the agent-data gateway as a product surface. Whether you take the managed tier or build atlas-mcp yourself, the discipline is the same: read-only by default, allowlist everything, redact what matters, cap what returns, and audit every call. Live operational data makes agents dramatically more useful — govern it and it stays that way. The patterns in the AI workflows library will keep your gateway production-safe."
Enjoyed this breakdown? Get our morning dispatch in your inbox.
Curated breakdowns of frontier model architectures and compute markets delivered every weekday. Zero fluff.
Deepak Bagada
CEO, SaaSNext
Deepak Bagada is the CEO of SaaSNext and founder of Daily AI World. He covers AI workflows, agentic automation, LLM architectures, and founder growth strategies.
Related Intelligence Analysis
Vercel AI SDK Tool Calling React: 5 Steps (2026)
Vercel AI SDK tool calling React integration is a programming pattern that executes server-side functions based on large language model decisions and streams the results to a React frontend. By combining streamText with...
Fact-Density vs. Word Count: The New SEO for 2026
Fact Density is the ratio of verifiable, unique information to the total word count of a piece of content. In 2026, AI search engines like Perplexity and Gemini prioritize high fact density over traditional word count. A...
NVIDIA Audex vs Qwen3.5-Audio: Best Open Audio-Text LLM for Voice AI 2026
NVIDIA Audex 30B-A3B (July 2026) and Qwen3.5-35B-A3B are the two leading open audio-text LLMs. Audex uniquely handles both audio understanding and generation in a single model while preserving text intelligence. Qwen3.5-...