MongoDB Integration Guide
What is MongoDB?
mongodb 7.7 + one module-scoped MongoClient, registered with attachDatabasePool on Vercel.
Driver 7.x and Mongoose 9 need Node 20.19+. On Vercel, install Atlas from the Marketplace (it injects MONGODB_URI), create the client once at module scope with maxIdleTimeMS: 5000, and call attachDatabasePool(client) from @vercel/functions so Fluid compute closes idle sockets before suspending. The Data API is end-of-life, so Edge code has no HTTP escape hatch. For RAG, an autoEmbed vector index has Atlas embed text with Voyage AI (voyage-4, $0.06 per 1M tokens). For codeAmani it's a client-driven choice: Neon Postgres stays the default, and Kenya-targeted builds use Atlas AF_SOUTH_1 (Cape Town) next to Vercel cpt1.
Five MongoDB primitives
A document store you reach for only when Postgres jsonb won't do.
███╗ ███╗ ██████╗ ███╗ ██╗ ██████╗ ██████╗ ██████╗ ██████╗
████╗ ████║██╔═══██╗████╗ ██║██╔════╝ ██╔═══██╗██╔══██╗██╔══██╗
██╔████╔██║██║ ██║██╔██╗ ██║██║ ███╗██║ ██║██║ ██║██████╔╝
██║╚██╔╝██║██║ ██║██║╚██╗██║██║ ██║██║ ██║██║ ██║██╔══██╗
██║ ╚═╝ ██║╚██████╔╝██║ ╚████║╚██████╔╝╚██████╔╝██████╔╝██████╔╝
╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═════╝ ╚═════╝ ╚═════╝ ╚═════╝MongoDB Integration Guide
Focus: When and how codeAmani uses MongoDB for client projects that require a document database. Covers picking an Atlas tier (Free / Flex / Dedicated), provisioning through the Vercel Marketplace, connection reuse on Vercel Fluid compute with
attachDatabasePool, Mongoose with Zod at the boundary, the aggregation pipeline, transactions, MongoDB Vector Search with Voyage AI embeddings, region choice for Kenya-targeted builds, and setting up (and un-sticking) the MongoDB MCP server in Claude Code.
Overview
MongoDB is a document database advertised as an option on motionstackstudios.com. It stores BSON documents in collections rather than rows in tables. That flexibility (nested objects, arrays, a different shape per document) is the whole point, and it's also why MongoDB is not the house default.
The house default for almost everything is Neon Postgres + Drizzle ORM, with Supabase as the second relational option. Postgres jsonb columns cover a lot of "document-ish" needs while keeping strong typing, joins, transactions and per-PR branching. MongoDB earns a place only when a client build specifically needs a document model: a schema that keeps changing, deeply nested data that would be painful to normalize, or per-tenant documents whose fields differ per customer.
Check first. Before adding MongoDB to a build, query the
codeAmani-tech-stackMCP (search_guides/get_guide) and confirm the Neon/Postgres default (includingjsonb) won't meet the requirement. MongoDB adds a second database paradigm, its own ODM, and its own connection-pool pitfalls on serverless.
Official Documentation
| Resource | URL |
|---|---|
MongoDB Docs (root; append .md to any page for Markdown) | https://www.mongodb.com/docs/ |
| MongoDB Atlas (managed) | https://www.mongodb.com/docs/atlas/ |
| Node.js Driver (v7, current) | https://www.mongodb.com/docs/drivers/node/current/ |
| Node.js Driver release notes | https://www.mongodb.com/docs/drivers/node/current/reference/release-notes/ |
| Mongoose ODM (v9, current) | https://mongoosejs.com/docs/ |
| MongoDB Vector Search | https://www.mongodb.com/docs/vector-search/ |
| Voyage AI by MongoDB (Embedding & Reranking API) | https://www.mongodb.com/docs/voyageai/ |
| Atlas + Vercel native integration | https://www.mongodb.com/docs/atlas/reference/partner-integrations/vercel/ |
@vercel/functions attachDatabasePool | https://vercel.com/docs/functions/functions-api-reference/vercel-functions-package#database-connection-pool-management |
| MongoDB MCP Server | https://www.mongodb.com/docs/mcp-server/ |
| Pricing | https://www.mongodb.com/pricing |
Versions (verified on npm 2026-10-20)
| Package | Version | Notes |
|---|---|---|
mongodb (Node driver) | 7.7.0 (2026-09-28) | Node >= 20.19.0. v6 line still published as 6.21.0. |
mongoose | 9.11.2 (2026-10-12) | Node >= 20.19.0. v8 maintained as 8.24.5. |
@vercel/functions | 3.10.1 | Provides attachDatabasePool and waitUntil. |
mongodb-mcp-server | 3.1.0 (2026-10-15) | Node ^20.19.0 || ^22.13.0 || >=24.0.0. |
mongodb-client-encryption | 7.2.1 | Only for Queryable Encryption / CSFLE. |
| MongoDB Server | 9.0 current stable | Atlas Flex runs at least 8.0. |
Driver 7.x highlights since 7.0 (2025-11): 7.1 built-in MONGODB-AWS auth (no aws4) and exponential backoff in withTransaction(); 7.2 experimental runtimeAdapters and Web-standard Uint8Array / globalThis.crypto instead of Buffer / crypto; 7.3 deprecated MongoDB Server 4.2 and fixed SCRAM auth in Deno; 7.4 made Symbol.asyncDispose (await using) stable; 7.5 made Queryable Encryption prefix/suffix/substring queries GA (Server 9.0); 7.6 dropped Server 4.2, added baseBackoffMS, faster insertMany / bulkWrite, and an ESM-bundling fix; 7.7 fixed an OIDC bug where one failed token fetch poisoned the whole client.
Atlas tiers after the Serverless / Shared retirement
Atlas Serverless instances and the old M2/M5 Shared tiers are gone. You couldn't create them after February 2025, and Atlas stopped supporting them on 2026-01-22. M2/M5 clusters were migrated to Flex; Serverless instances were migrated to Free, Flex or Dedicated depending on usage. Update any Terraform/CLI/API code that still names the old types. Provision only these:
| Tier | Price (Oct 2026) | Storage | Limits that matter | Use for |
|---|---|---|---|---|
| Free (M0) | $0 | 512 MB | 100 ops/s, 500 connections, 10 GB in + 10 GB out per 7 days, no backups, auto-pauses after 30 idle days | Learning, demos |
| Flex | $0.011/hr, capped at $30/month | up to 5 GB | 500 ops/s, 500 connections, max 50 aggregation stages, no allowDiskUse, one daily snapshot, no private endpoints, no Performance Advisor | Dev, staging, low-traffic client apps |
| Dedicated (M10+) | from $0.08/hr (about $56.94/month for M10) | 10 GB → 4 TB/node | Full feature set; auto-scaling; 99.995% SLA | Production, regulated data |
| Atlas Infinite (public preview) | from $0.09/hr (about $65/month) | up to 128 TB per HA shard | M10+ only; decoupled compute and storage | Spiky AI-scale workloads (not yet for client prod) |
Search and Vector Search run on the cluster by default. Dedicated Search Nodes (S20 at $0.12/hr and up, us-east-1 prices) are an M10+ add-on. Re-check https://www.mongodb.com/pricing before quoting a client.
Choosing a region (Kenya-targeted projects)
There's no Atlas region in East Africa. The nearest are in South Africa, and only one supports the cheap tiers:
| Atlas region | Provider / location | Free | Flex | M10+ |
|---|---|---|---|---|
AF_SOUTH_1 | AWS af-south-1, Cape Town | ✅ | ✅ | ✅ |
SOUTH_AFRICA_NORTH | Azure southafricanorth, Johannesburg | — | — | ✅ |
AFRICA_SOUTH_1 | Google Cloud africa-south1, Johannesburg | — | — | ✅ (no Search Nodes) |
SOUTH_AFRICA_WEST | Azure southafricawest, Cape Town | — | — | ✅ |
- Default for Kenya-targeted builds:
AF_SOUTH_1(AWS Cape Town), paired with Vercel regioncpt1, which is also AWSaf-south-1. Function and database sit in the same AWS region, and you can start on Free or Flex. - Johannesburg is dedicated-only (M10+ on Azure or Google Cloud). Pick it only when a client contract names Johannesburg, and budget at least M10.
- Atlas Infinite isn't offered in
af-south-1. - US-first projects (the default) stay in the Vercel project's region, usually
iad1with AtlasUS_EAST_1.
Provisioning
Option A — Vercel Marketplace native integration (preferred on Vercel)
Vercel Marketplace → Storage → MongoDB Atlas → Install. You pick a tier (Free, Flex or Dedicated), a Vercel region (mapped to the closest Atlas region), and an installation plan:
- Free plan: no card, Free clusters only.
- Paid plan: card required; Flex and Dedicated are billed through your Vercel invoice. Creating one Flex or Dedicated cluster switches the whole installation to Paid. Going back to Free means uninstalling and reinstalling.
What it does for you:
- Creates a Vercel-managed Atlas organization + project and injects
MONGODB_URIinto the linked Vercel project's environments (vercel env pullto get it locally). - Adds
0.0.0.0/0to the Atlas IP access list (Vercel egress IPs are dynamic) and creates a DB user namedVercel-Admin-<resource>withreadWriteAnyDatabase. For client data, create a narrower user (readWriteon one database) and swap the URI. - Installs MongoDB's agent skills (
mongodb-schema-design,mongodb-query-optimizer,mongodb-search-and-ai). - Signs you into Atlas through Vercel SSO. Vercel "Admin"/"User" map to Atlas Organization Owner/Read Only.
Starter: npx create-next-app --example with-mongodb my-mongodb-app, then vercel link and vercel env pull.
Option B — Atlas directly (non-Vercel hosts, or client-owned Atlas orgs)
- Create a project and a cluster (Free, Flex or M10+) in the region chosen above.
- Database Access: create a user scoped to the app's database.
- Network Access: allow the platform's egress. Serverless hosts have dynamic IPs, so you typically need
0.0.0.0/0and rely on TLS + SCRAM + a strong password. Use private endpoints (M10+) when the host supports them. - Connect → Drivers: copy the SRV string.
mongodb+srv://<user>:<urlEncodedPassword>@cluster0.xxxxx.mongodb.net/<dbName>?retryWrites=true&w=majority&appName=acme-appGotcha: URL-encode the password. A literal
@,:,/or#breaks parsing, soP@ss:w0rdbecomesP%40ss%3Aw0rd.
Connection reuse on Vercel Fluid compute
Fluid compute is the default for new Vercel projects. Concurrent requests share one function instance and its globals, so one module-scoped MongoClient per instance is the right model. The remaining problem is suspension: idle sockets don't time out while an instance is frozen, so they pile up as "phantom" connections against the Atlas limit (500 on Free/Flex). attachDatabasePool from @vercel/functions fixes that. It uses waitUntil to keep the instance alive just long enough to close idle connections before suspending. Vercel lists MongoDB among the supported pool types.
// lib/mongodb.ts (full file: examples/lib-mongodb.ts)
import { MongoClient, type Db, type MongoClientOptions } from "mongodb";
import { attachDatabasePool } from "@vercel/functions";
const uri = process.env.MONGODB_URI;
if (!uri) throw new Error("Missing MONGODB_URI environment variable");
const mongoUri: string = uri;
const options: MongoClientOptions = {
appName: "codeamani-app",
maxIdleTimeMS: 5000, // Vercel recommends a short idle timeout
maxPoolSize: 10,
};
function createClient(): MongoClient {
const client = new MongoClient(mongoUri, options);
attachDatabasePool(client); // close idle connections before suspension
return client;
}
const globalForMongo = globalThis as typeof globalThis & { _mongoClient?: MongoClient };
export const client: MongoClient = globalForMongo._mongoClient ?? createClient();
globalForMongo._mongoClient = client;
export function getDb(name: string = process.env.MONGODB_DB ?? "app"): Db {
return client.db(name);
}Rules:
- Create the client once, at module scope. Don't create a
new MongoClient()per request, and neverclient.close()in a handler. - No explicit
connect()needed. The driver connects lazily on the first operation, which is how Vercel's own snippet works. - Don't wrap the shared client in
await using. Driver 7.4 madeSymbol.asyncDisposestable, soawait usingwould close the client when the scope exits. Use it only in scripts and tests. - Don't set
maxPoolSize: 1. Vercel warns it hurts concurrency on Fluid without reducing total connections. - Use rolling releases on big deploys so a fleet of fresh instances doesn't open connections all at once.
- Node.js runtime only. The driver doesn't run on the Edge runtime. Keep
export const runtime = "nodejs"(the Next.js default) on routes that touch MongoDB.
Netlify / other serverless hosts: there's no attachDatabasePool. Keep the same module-scoped client and set maxIdleTimeMS. The rest of the pattern is identical.
Mongoose — cached connection
// lib/dbConnect.ts (full file: examples/lib-dbConnect.ts)
import mongoose from "mongoose";
import { attachDatabasePool } from "@vercel/functions";
const uri = process.env.MONGODB_URI;
if (!uri) throw new Error("Missing MONGODB_URI environment variable");
const mongoUri: string = uri;
interface MongooseCache { conn: typeof mongoose | null; promise: Promise<typeof mongoose> | null }
const globalForMongoose = globalThis as typeof globalThis & { _mongoose?: MongooseCache };
const cached: MongooseCache = globalForMongoose._mongoose ?? { conn: null, promise: null };
globalForMongoose._mongoose = cached;
export async function dbConnect(): Promise<typeof mongoose> {
if (cached.conn) return cached.conn;
if (!cached.promise) {
cached.promise = mongoose
.connect(mongoUri, { bufferCommands: false, maxPoolSize: 10, maxIdleTimeMS: 5000 })
.then((m) => {
attachDatabasePool(m.connection.getClient()); // the underlying MongoClient
return m;
});
}
try {
cached.conn = await cached.promise;
} catch (err) {
cached.promise = null; // don't cache a failed connect
throw err;
}
return cached.conn;
}Mongoose schema + Zod at the boundary
Validate untrusted input with Zod first, then persist with a typed Mongoose model. Zod guards request bodies and webhooks; the Mongoose schema is the persistence contract. Full file: examples/provider-model.ts.
import { Schema, model, models, type InferSchemaType, type Model } from "mongoose";
import { z } from "zod";
import { dbConnect } from "@/lib/dbConnect";
export const ProviderInput = z.object({
name: z.string().min(1),
licenseType: z.enum(["APD", "AHCA", "DCF"]),
email: z.email(), // Zod 4; z.string().email() is deprecated
services: z.array(z.string()).default([]),
metadata: z.record(z.string(), z.unknown()).optional(),
});
const providerSchema = new Schema(
{
name: { type: String, required: true, trim: true },
licenseType: { type: String, required: true, enum: ["APD", "AHCA", "DCF"] },
email: { type: String, required: true, lowercase: true, index: true },
services: { type: [String], default: [] },
metadata: { type: Schema.Types.Mixed },
},
{ timestamps: true, strict: true },
);
export type Provider = InferSchemaType<typeof providerSchema>;
// Reuse the compiled model across hot reloads / warm invocations (avoids OverwriteModelError).
export const ProviderModel: Model<Provider> =
(models.Provider as Model<Provider> | undefined) ?? model<Provider>("Provider", providerSchema);
export const runtime = "nodejs";
export async function POST(req: Request): Promise<Response> {
const parsed = ProviderInput.safeParse(await req.json());
if (!parsed.success) return Response.json({ error: z.flattenError(parsed.error) }, { status: 400 });
await dbConnect();
const provider = await ProviderModel.create(parsed.data);
return Response.json({ id: provider._id.toString() }, { status: 201 });
}Mongoose 9 changes that bite: pre middleware no longer receives
next()(return or throw instead), and UUIDs come back asbson.UUID. Also add a collection-level$jsonSchemavalidator as a backstop for writes that bypass Mongoose (scripts, the MCP server, other services).
Aggregation pipeline
Stages run in order, and each stage's output feeds the next. Full file: examples/queries.ts.
export async function providerIntakeSummary(licenseType: "APD" | "AHCA" | "DCF") {
return getDb()
.collection<ProviderDoc>("providers")
.aggregate<{ name: string; email: string; openIntakes: number }>([
{ $match: { licenseType } },
{ $lookup: { from: "intakes", localField: "_id", foreignField: "providerId", as: "intakes" } },
{
$project: {
_id: 0, name: 1, email: 1,
openIntakes: { $size: { $filter: { input: "$intakes", as: "i", cond: { $eq: ["$$i.status", "open"] } } } },
},
},
{ $sort: { openIntakes: -1 } },
{ $limit: 50 },
])
.toArray();
}Index the early
$match/$sortfields and confirmIXSCAN(notCOLLSCAN) withexplainor the MCPexplaintool. Flex caps pipelines at 50 stages and doesn't supportallowDiskUse.
Transactions
Every Atlas cluster is a replica set, so multi-document ACID transactions work everywhere. withTransaction() handles commit/abort and retries transient errors. Since driver 7.1, it also backs off exponentially between retries.
export async function recordIntake(providerId: string, notes?: string): Promise<void> {
const db = getDb();
const id = new ObjectId(providerId);
const session = client.startSession();
try {
await session.withTransaction(async () => {
await db.collection<IntakeDoc>("intakes").insertOne({ providerId: id, status: "open", notes }, { session });
await db.collection<ProviderDoc>("providers").updateOne({ _id: id }, { $inc: { openCount: 1 } }, { session });
});
} finally {
await session.endSession();
}
}Transactions hold locks and add latency (60-second default limit). Embedding related data in one document often removes the need for one.
MongoDB Vector Search with Voyage AI
MongoDB owns Voyage AI. Its embedding models are served by Atlas, and Vector Search can call them for you. There are two ways to use it (full file: examples/vector-search-voyage.ts):
A. Automated Embedding (autoEmbed), the least code
You index a text field with type autoEmbed. Atlas embeds existing and new documents with the chosen Voyage model, keeps the embeddings in sync, and embeds your query text at search time.
await knowledge().createSearchIndex({
name: "knowledge_auto",
type: "vectorSearch",
definition: {
fields: [
{ type: "autoEmbed", modality: "text", path: "text", model: "voyage-4" },
{ type: "filter", path: "tenantId" },
],
},
});
const hits = await knowledge().aggregate([
{
$vectorSearch: {
index: "knowledge_auto",
path: "text",
query: { text: "how do I reset my M-Pesa PIN?" },
model: "voyage-4",
numCandidates: 100,
limit: 5,
filter: { tenantId },
},
},
{ $project: { _id: 0, text: 1, source: 1, score: { $meta: "vectorSearchScore" } } },
]).toArray();| Model | $ / 1M tokens | Use |
|---|---|---|
voyage-4-lite | $0.02 | High volume, cost-sensitive |
voyage-4 | $0.06 | Recommended general text |
voyage-4-large | $0.12 | Max accuracy |
voyage-code-4 | $0.12 | Code / technical docs (Atlas only) |
- 200 million free tokens per model, once per Atlas organization. They don't refresh.
- Query rate limits: an M0 cluster with no payment method gets 3 RPM / 2,000 TPM, which is demo-only. Paid clusters (M0 with a card, Flex, Dedicated) get 2,000 RPM, with TPM depending on the model.
- M10+ needs storage auto-scaling enabled. If the disk fills, embedding pauses and the index goes Stale.
- Generated vectors are stored on your cluster, in an internal database, and count toward storage (5 GB on Flex).
- Changing
model,numDimensionsorquantizationre-embeds everything (and bills again). - Create the index after bulk-loading. The first build uses a separate high-throughput path that isn't bound by rate limits.
B. Bring your own vectors (Embedding API)
Use this when you need the vectors elsewhere too (a cache, another store), or need explicit control. Create a model API key in Atlas (Voyage AI → API keys) and call https://ai.mongodb.com/v1/embeddings. Keys issued directly by Voyage AI use https://api.voyageai.com/v1/embeddings instead.
const res = await fetch("https://ai.mongodb.com/v1/embeddings", {
method: "POST",
headers: { Authorization: `Bearer ${process.env.VOYAGE_API_KEY}`, "Content-Type": "application/json" },
body: JSON.stringify({ input: texts, model: "voyage-4", input_type: "document", output_dimension: 1024 }),
});Index it as { "type": "vector", "path": "embedding", "numDimensions": 1024, "similarity": "dotProduct" } and query with queryVector. Use input_type: "document" for stored text and "query" for search text; Voyage says this markedly improves retrieval. Voyage 4-series embeddings (-lite, base, -large) are compatible with each other, so you can index with voyage-4-large and query with voyage-4-lite. Dimensions are 1024 by default, or 256/512/2048. The TypeScript SDK is voyageai (0.4.0); point it at Atlas with environment: "https://ai.mongodb.com/v1".
Which RAG store?
| RAG store | When to choose |
|---|---|
| Neon + pgvector (house default for Postgres builds) | Already on Postgres; vectors next to relational data; SQL filtering |
| Pinecone (house dedicated option) | Large-scale, vector-first workloads; multi-tenant namespaces |
| MongoDB Vector Search | Already on MongoDB; embeddings beside the source documents; Automated Embedding removes the embedding pipeline |
Multi-tenant safety: always pass a
filter(for exampletenantId) in$vectorSearch, and index that path as afilterfield. It's the same discipline asWHERE tenant_id = ….
MongoDB Search (formerly Atlas Search) adds full-text $search and hybrid search on the same cluster. It isn't compatible with Queryable Encryption.
Queryable Encryption (sensitive fields)
For fields the server must never see in plaintext (IDs, health data), Queryable Encryption encrypts on the client. The data stays encrypted at rest, in use, in logs and in backups, and still supports equality, range, prefix, suffix and substring queries. Prefix/suffix/substring need driver >= 7.5.0, mongodb-client-encryption >= 7.2.0 and MongoDB Server 9.0. Keys live in a KMS (AWS/Azure/GCP/KMIP). Driver 7.6 can route KMS calls through an HTTP proxy (kmsConnectCallback). It works on Atlas but not with MongoDB Search. Treat it as a design decision: decide at schema time, not after launch.
Atlas Data API and App Services are gone
The Data API and custom HTTPS Endpoints reached end of life on 2025-09-30, and Atlas App Services as a whole is EOL (only Triggers remain in the Atlas UI). There's no HTTP escape hatch for Edge or Workers. Call the database from a Node.js function, or use a Postgres/Neon path for edge-native code.
MongoDB MCP server in Claude Code
There are two servers. Pick one:
| Atlas Managed MCP Server (remote) | Local MCP (mongodb-mcp-server) | |
|---|---|---|
| Claude Code plugin | /plugin install mongodb-atlas@claude-plugins-official | /plugin install mongodb@claude-plugins-official |
| Auth | Atlas OAuth through /mcp → Authenticate (an org owner must enable AI Clients first) | Connection string, Atlas service account, or Atlas Local (Docker) |
| Runs | Hosted by MongoDB; no local Node | npx on your machine (Node ^20.19 || ^22.13 || >=24) |
| Best for | Atlas clusters, team use | Self-managed / local dev, connection-string access |
Useful tools (local server 3.1.0): find, aggregate, count, collection-schema, collection-indexes, explain, create-index, list-databases, export, atlas-list-clusters, atlas-get-performance-advisor, atlas-get-regions, atlas-local-create-deployment, search-knowledge.
Local server: safe manual setup
Run the interactive setup once. It writes a config file and asks about read-only mode, so answer Y:
npx mongodb-mcp-server@latest setupOr register it yourself at user scope, after a global install (see fix 1 below; on native Windows use node + the package path as the command). Keep the connection string in your shell environment (from Hazina), not in the command line, and reference it with ${VAR} expansion in ~/.claude.json:
{
"mcpServers": {
"mongodb": {
"type": "stdio",
"command": "mongodb-mcp-server",
"args": ["--readOnly"],
"env": { "MDB_MCP_CONNECTION_STRING": "${MDB_MCP_CONNECTION_STRING}" }
}
}
}Useful flags (or MDB_MCP_* env vars): --readOnly (only read/connect/metadata tools are registered), --indexCheck (rejects queries that would COLLSCAN), --disabledTools atlas or --disabledTools create update delete, --transport http --httpHost=0.0.0.0 (then connect to http://host:3000/mcp).
"connection timed out after 30000ms" — what's going on and how to fix it
On 2026-10-20, plugin:mongodb:mongodb timed out in the codeAmani Claude Code session. Here's the cause:
- The
mongodbplugin (1.2.1) starts the server withnpx -y mongodb-mcp-server@<3. That resolves to 2.1.2, not 3.x, andnpxhas to download about 390 packages on a cold cache. - Measured on this Windows machine, installing 3.1.0 took 73 s, and a cold
npx -yrun passed 120 s. Claude Code's default MCP startup timeout is 30 s, so the first start always times out. - Once installed, the server answers the MCP
initializehandshake almost instantly, even without a connection string (you can connect later with theconnecttool). Missing credentials aren't the cause.
Fixes, in order of preference:
- Install the server once and point Claude Code at it (no
npxon each start):npm install -g mongodb-mcp-server@3.1.0 # macOS / Linux / WSL claude mcp add mongodb --scope user -- mongodb-mcp-server --readOnly # Native Windows: run the package entry with node (avoids .cmd shim resolution) claude mcp add mongodb --scope user -- node "C:/Users/<you>/AppData/Roaming/npm/node_modules/mongodb-mcp-server/dist/esm/index.js" --readOnlynpm root -gprints the globalnode_modulespath if yours differs. Then turn off the plugin's own server (plugin:mongodb:mongodb) in/mcp, or disable the plugin in/plugin, so the slownpxcopy doesn't keep timing out next to yours. Disabling the whole plugin also removes itsmongodb-*skills. - Or warm the npx cache so later cold starts are fast:
npx -y "mongodb-mcp-server@<3" --version. - Or raise the startup timeout for the session:
export MCP_TIMEOUT=180000(bash) or$env:MCP_TIMEOUT = "180000"(PowerShell) before startingclaude. - Or switch to the Atlas Managed MCP Server (
mongodb-atlasplugin). It's remote, so there's nothing to download.
If it still fails: check node --version against the engines range, then read the logs at %LOCALAPPDATA%\mongodb\mongodb-mcp\.app-logs (Windows) or ~/.mongodb/mongodb-mcp/.app-logs. For HTTP transport, make sure the URL ends in /mcp. Atlas tools return "Atlas API credentials not configured" without MDB_MCP_API_CLIENT_ID / MDB_MCP_API_CLIENT_SECRET, and 403 if the service account's role is too low.
Safety: keep MCP sessions read-only against anything with client data. Writes through the MCP bypass Mongoose validation, so the collection
$jsonSchemavalidator is your backstop. Never paste a connection string into chat; the docs warn specifically against runtimeconnectwith production URIs.
Environment Variables
Only real secrets go below. The Vercel Marketplace integration injects MONGODB_URI for you.
# Atlas SRV connection string — server-only secret (contains the DB password, URL-encoded).
MONGODB_URI=mongodb+srv://app_user:URL%2DENCODED%2DPASS@cluster0.xxxxx.mongodb.net/app?retryWrites=true&w=majority&appName=acme-app
# Atlas model API key for the Voyage AI Embedding API (option B only; autoEmbed needs none).
VOYAGE_API_KEY=your-atlas-model-api-key
# MongoDB MCP server (local dev only) — never a production URI.
MDB_MCP_CONNECTION_STRING=mongodb+srv://readonly_user:...@cluster0.xxxxx.mongodb.net/
MDB_MCP_API_CLIENT_SECRET=your-atlas-service-account-secretNon-secret settings:
| Variable | Example | Purpose |
|---|---|---|
MONGODB_DB | app | Database name when it isn't in the URI path |
MDB_MCP_API_CLIENT_ID | <service-account-client-id> | Atlas service-account ID (pairs with the secret above) |
MDB_MCP_READ_ONLY | true | Force the MCP server into read-only mode |
MCP_TIMEOUT | 180000 | Claude Code MCP startup timeout in ms (shell, not app) |
MONGODB_URI,VOYAGE_API_KEYand the MCP secrets are server-only. Never use aNEXT_PUBLIC_*name for them, and store them in Hazina / Vercel env vars, not committed files.
Common Use Cases
| Use Case | Approach |
|---|---|
| Default relational database | Neon Postgres + Drizzle (house default). Use MongoDB only for true document needs |
| Semi-structured / occasional nesting | Postgres jsonb on Neon before reaching for MongoDB |
| Flexible / evolving / per-tenant schema | MongoDB Atlas + Mongoose Schema.Types.Mixed |
| New project on Vercel | Marketplace native integration → MONGODB_URI injected |
| Connection on Vercel Fluid | Module-scoped client + attachDatabasePool + maxIdleTimeMS: 5000 |
| Prototype / staging | Flex ($30/month cap). Free M0 only for demos |
| Kenya-targeted build | Atlas AF_SOUTH_1 + Vercel cpt1. Johannesburg is M10+ only |
| Input validation | Zod at the boundary + Mongoose schema + collection $jsonSchema |
| Analytics / joins / rollups | Aggregation pipeline ($match → $lookup → $group → $project) |
| Atomic multi-document writes | session.withTransaction(...) |
| Semantic search / RAG on Mongo data | Vector Search with autoEmbed (voyage-4), or BYO Voyage vectors |
| Sensitive fields that must stay encrypted | Queryable Encryption (driver 7.5+, Server 9.0 for string queries) |
| Inspect schema / indexes / run read queries | MongoDB MCP (--readOnly) |
Troubleshooting
| Issue | Fix |
|---|---|
| Atlas connection count climbs on Vercel | Module-scoped client + attachDatabasePool(client) + maxIdleTimeMS: 5000; never new MongoClient() per request |
MongoParseError / auth fails | URL-encode the password; check the DB user and its role |
MongoServerSelectionError / timeout | Atlas IP access list must allow the host's egress (0.0.0.0/0 for Vercel; the Marketplace adds it) |
OverwriteModelError | models.X ?? model("X", schema) |
MongooseError: Operation buffering timed out | bufferCommands: false and await dbConnect() before queries |
| Fails on Edge / Workers | Driver and Mongoose need Node.js; the Data API is EOL, so there's no HTTP fallback |
| Free cluster "throttled" | M0 is 100 ops/s and 10 GB/7-day transfer. Move to Flex |
$vectorSearch returns nothing | Index still building, or numDimensions doesn't match the model; for autoEmbed, check that the index isn't Stale (disk full) |
context-limit-exceeded on $vectorSearch | Query text exceeds the model's 32K-token window |
| Automated Embedding queries rate-limited | M0 with no card gets 3 RPM; add a payment method or use Flex |
Aggregation slow (COLLSCAN) | Index the $match/$sort fields; confirm IXSCAN via explain |
| MCP "connection timed out after 30000ms" | Cold npx download; install mongodb-mcp-server globally or raise MCP_TIMEOUT (see the MCP section) |
TS error Cannot find module 'ws' from @vercel/functions | ws is an optional peer; keep skipLibCheck: true (Next.js default) or add @types/ws |
codeAmani notes
- Database choice. MongoDB is a client-driven option, not a house default. Neon (then Supabase) wins unless the client needs a real document model. Record the reason in the project's README.
- Keep the stack's defaults. Auth stays Clerk; payments stay Stripe. Store Stripe customer/subscription IDs on the user document, and verify Stripe webhook signatures before writing anything.
- Secrets server-side only.
MONGODB_URI,VOYAGE_API_KEYandMDB_MCP_*secrets live in Hazina / Vercel env vars. Replace the Marketplace'sreadWriteAnyDatabaseuser with a per-appreadWriteuser for client data. - AI routing. Claude stays primary for generation. Voyage (via Atlas) is the embedding provider when the data is in MongoDB, because it's billed on the same Atlas invoice and
autoEmbedremoves the embedding job. Start onvoyage-4; drop tovoyage-4-litefor high-volume indexing. - Kenya-targeted projects. Atlas
AF_SOUTH_1(Cape Town) + Vercelcpt1is the default pair, and it works on Free/Flex. Johannesburg needs M10+. M-Pesa callback handlers: validate the callback, storeCheckoutRequestIDwith a unique index right after the STK Push response, and deduplicate the callback with an upsert on that key. Amounts are integer KES. Mobile-first, low-bandwidth: project only the fields a screen needs. - Tier policy. Free M0 for demos only (it auto-pauses and has no backups). Flex for staging and small client apps. M10+ with backups for anything holding PHI/PII or payments.
- MCP is for dev/test. Read-only against anything real. Prefer the Atlas Managed MCP Server for Atlas clusters, and install the local server globally instead of relying on
npxcold starts.