MongoDB MCP Server
Click on "Install Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@MongoDB MCP Serverlist collections in database 'mydb'"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
MongoDB MCP Server
English
A secure read/write Model Context Protocol server that lets Codex, Claude Code, OpenCode, and other MCP clients connect to MongoDB over Streamable HTTP/HTTPS.
Features
Validates and names MongoDB connections for reuse.
Persists connection profiles across restarts in a local file with
0600permissions.Lists configured connections, databases, and collections.
Runs bounded
findqueries and read-only aggregation pipelines.Inserts, updates, replaces, and deletes documents with explicit per-call limits.
Runs bounded
$merge/$outpipelines and can drop an exactly confirmed collection or database.Accepts MongoDB Extended JSON in query inputs and returns BSON values as Extended JSON.
Supports JSON and Markdown tool responses plus MCP structured content.
Applies query limits, operation timeouts, response-size limits, URI redaction, Host/Origin validation, and optional Bearer authentication.
Serves stateless MCP over HTTP or direct TLS with Bun.
Write access is explicit and follows the connected MongoDB user's permissions. The server does not expose arbitrary database commands and continues to block server-side JavaScript operators such as $where, $function, and $accumulator.
Requirements
Bun 1.3 or newer.
A reachable MongoDB deployment and a connection URI.
A MongoDB user with exactly the permissions the agents should have. Use
readWriteonly for databases the MCP may modify; drop operations require the corresponding MongoDB privileges.
Install and run
git clone https://github.com/stock42/mcp-mongodb.git
cd mcp-mongodb
bun install
cp .env.example .env
bun run check
bun run start:sourceThe default endpoints are:
MCP:
http://127.0.0.1:3000/mcpHealth check:
http://127.0.0.1:3000/health
For a built server:
bun run build
bun startConfiguration
Bun loads .env automatically. All settings are optional when running only on loopback.
Variable | Default | Description |
|
| HTTP bind address. |
|
| HTTP port. |
| unset | Bearer token for |
| loopback hosts | Comma-separated exact |
| empty | Comma-separated browser origins. Requests containing an unlisted |
|
| Persistent connection-profile file. |
|
| Maximum documents/items returned, inserted, or selected by a bounded multi-write call. |
|
| Maximum query and connection timeout accepted by tools. |
|
| Maximum serialized document payload before truncation. |
| unset | PEM certificate path; must be used with |
| unset | PEM private-key path; must be used with |
Generate a token for remote access and configure the public hostname:
openssl rand -hex 32MCP_HOST=0.0.0.0
MCP_PORT=3000
MCP_API_KEY=replace-with-the-generated-value
MCP_ALLOWED_HOSTS=mcp.example.comUse HTTPS in production, either through a trusted reverse proxy or directly:
MCP_TLS_CERT_PATH=/absolute/path/to/fullchain.pem
MCP_TLS_KEY_PATH=/absolute/path/to/privkey.pemInstall in Codex
Codex CLI, the Codex IDE extension, and the ChatGPT desktop app share MCP configuration. Export the same token configured in the server and add its Streamable HTTP URL:
export MONGODB_MCP_TOKEN='replace-with-your-MCP_API_KEY'
codex mcp add mongodb \
--url http://127.0.0.1:3000/mcp \
--bearer-token-env-var MONGODB_MCP_TOKEN
codex mcp listIf MCP_API_KEY is unset for a loopback-only server, omit --bearer-token-env-var.
Manual ~/.codex/config.toml equivalent:
[mcp_servers.mongodb]
url = "http://127.0.0.1:3000/mcp"
bearer_token_env_var = "MONGODB_MCP_TOKEN"
required = true
tool_timeout_sec = 30Restart the Codex client after editing its configuration, then use /mcp to inspect the connection. See the official Codex MCP documentation.
Install in Claude Code
Add the remote server at user scope. The following command resolves the token from your current shell:
export MONGODB_MCP_TOKEN='replace-with-your-MCP_API_KEY'
claude mcp add --transport http --scope user \
--header "Authorization: Bearer ${MONGODB_MCP_TOKEN}" \
mongodb http://127.0.0.1:3000/mcp
claude mcp listFor a project-scoped configuration that expands the token at runtime, add .mcp.json without committing the secret itself:
{
"mcpServers": {
"mongodb": {
"type": "http",
"url": "http://127.0.0.1:3000/mcp",
"headers": {
"Authorization": "Bearer ${MONGODB_MCP_TOKEN}"
}
}
}
}Run /mcp inside Claude Code to inspect server status. See the official Claude Code MCP documentation.
Install in OpenCode
Export the token and add this entry to opencode.json or opencode.jsonc:
export MONGODB_MCP_TOKEN='replace-with-your-MCP_API_KEY'{
"$schema": "https://opencode.ai/config.json",
"mcp": {
"mongodb": {
"type": "remote",
"url": "http://127.0.0.1:3000/mcp",
"enabled": true,
"oauth": false,
"headers": {
"Authorization": "Bearer {env:MONGODB_MCP_TOKEN}"
}
}
}
}Verify it with opencode mcp list. See the official OpenCode MCP documentation.
Available tools
Tool | Purpose | Side effects |
| Validate, ping, and optionally persist a named MongoDB URI. | Updates the local connection store. |
| List profiles with redacted endpoints and live status. | None. |
| Close a live client without deleting its profile. | Runtime-only. |
| Delete a saved/transient profile and close its client. | Deletes the local profile only. |
| List visible databases with pagination. | None. |
| List/filter collections with pagination. | None. |
| Run a bounded read-only find query. | None. |
| Run a bounded read-only aggregation. | None. |
| Insert one Extended JSON document. | Adds one document. |
| Insert a bounded ordered/unordered batch. | Adds documents. |
| Update or upsert at most one matching document. | Modifies or creates a document. |
| Update a bounded set of matching documents. | Modifies up to the requested limit. |
| Replace or upsert one complete document. | Replaces or creates a document. |
| Delete at most one matching document. | Permanently deletes a document. |
| Delete a bounded set of matching documents. | Permanently deletes up to the requested limit. |
| Run a bounded pipeline ending in | Writes to or replaces the exact output collection. |
| Drop one exactly confirmed collection. | Permanently deletes its documents and indexes. |
| Drop one exactly confirmed database. | Permanently deletes the full database. |
mongodb_update_many scans matching documents in _id order. When has_more is true, pass its next_after_id value back as after_id to continue without selecting the same batch again. mongodb_delete_many naturally advances because each selected batch is removed.
Example prompts:
Connect as "analytics" using mongodb+srv://... and persist the profile.
List the databases available through analytics.
Find 20 active users in app.users, sorted by createdAt descending.
Group paid orders by currency and calculate total revenue.
Insert a new order into shop.orders using Extended JSON.
Mark at most 50 pending jobs as queued and tell me if more remain.
Merge daily revenue totals into analytics.daily_revenue.
Drop the staging.tmp_import collection after confirming its exact name.For BSON values in filters, use Extended JSON, for example:
{
"_id": { "$oid": "507f1f77bcf86cd799439011" },
"createdAt": { "$gte": { "$date": "2026-01-01T00:00:00.000Z" } }
}Security notes
A persisted MongoDB URI is stored unencrypted in the file configured by
MCP_MONGODB_STORE_PATH, protected with filesystem mode0600. Protect the host and backups accordingly.The server never returns stored URIs or credentials; profile listings contain only scheme, host, and database path.
Use a dedicated least-privilege MongoDB account and a separate strong
MCP_API_KEY.Treat access to this MCP as write access to every namespace granted to that MongoDB account. Prefer separate credentials and deployments for production and development.
Binding outside loopback fails at startup unless both Bearer authentication and explicit allowed hosts are configured.
Requests with a browser
Originare rejected unless it is explicitly listed.Tool annotations help clients understand side effects, but MongoDB permissions remain the security boundary.
Development
bun run typecheck
bun test
bun run build
bun run checkLocal MongoDB integration test
With an unauthenticated MongoDB server listening on 127.0.0.1:27017, run:
bun run test:integrationTo use another test deployment:
MONGODB_TEST_URI='mongodb://127.0.0.1:27018' bun run test:integrationbun run check:all runs the regular quality checks followed by this integration. The test creates a uniquely named mcp_mongodb_test_<uuid> database, seeds it, exercises the real MCP HTTP endpoint, and removes both the database and temporary connection store in finally. Never point MONGODB_TEST_URI at a deployment where that reserved test prefix is used for real data.
Project layout:
src/
connections/ Persistent profiles and MongoClient lifecycle
tools/ MCP tool registration
utils/ Query, pagination, redaction, and request safety
config.ts Environment parsing and deployment invariants
http-server.ts Bun HTTP/HTTPS adapter for Streamable HTTP
mcp-server.ts MCP server factory and instructions
index.ts Process entry point and graceful shutdown
test/ Unit and MCP protocol testsRelated MCP server: MongoDB MCP Server
Español
Servidor seguro de lectura y escritura para Model Context Protocol que permite a Codex, Claude Code, OpenCode y otros clientes MCP conectarse a MongoDB mediante Streamable HTTP/HTTPS.
Funcionalidades
Valida y asigna nombres reutilizables a conexiones MongoDB.
Persiste perfiles entre reinicios en un archivo local con permisos
0600.Lista conexiones configuradas, bases de datos y colecciones.
Ejecuta consultas
findacotadas y pipelines de agregación de solo lectura.Inserta, actualiza, reemplaza y borra documentos con límites explícitos por llamada.
Ejecuta pipelines
$merge/$outacotados y puede eliminar una colección o base confirmada por nombre exacto.Acepta Extended JSON de MongoDB y devuelve valores BSON como Extended JSON.
Ofrece respuestas JSON o Markdown, además de contenido estructurado MCP.
Aplica límites de resultados, timeout, tamaño de respuesta, redacción de URIs, validación Host/Origin y autenticación Bearer opcional.
Sirve MCP stateless sobre HTTP o TLS directo usando Bun.
El acceso de escritura es explícito y respeta los permisos del usuario MongoDB conectado. El servidor no expone comandos arbitrarios de base de datos y continúa bloqueando operadores de JavaScript del servidor como $where, $function y $accumulator.
Requisitos
Bun 1.3 o superior.
Un despliegue MongoDB accesible y su URI de conexión.
Un usuario MongoDB con exactamente los permisos que deben tener los agentes. Usar
readWritesolo para las bases que el MCP pueda modificar; los drops requieren los privilegios MongoDB correspondientes.
Instalación y ejecución
git clone https://github.com/stock42/mcp-mongodb.git
cd mcp-mongodb
bun install
cp .env.example .env
bun run check
bun run start:sourceEndpoints predeterminados:
MCP:
http://127.0.0.1:3000/mcpSalud:
http://127.0.0.1:3000/health
Para ejecutar el artefacto compilado:
bun run build
bun startConfiguración
Bun carga .env automáticamente. Todas las variables son opcionales si el servidor escucha únicamente en loopback.
Variable | Predeterminado | Descripción |
|
| Dirección donde escucha HTTP. |
|
| Puerto HTTP. |
| sin definir | Token Bearer para |
| hosts de loopback | Valores |
| vacío | Orígenes de navegador separados por comas. Se rechaza todo |
|
| Archivo de perfiles persistentes. |
|
| Máximo de documentos/elementos devueltos, insertados o seleccionados por una escritura múltiple acotada. |
|
| Timeout máximo de conexión y consulta aceptado por las tools. |
|
| Máximo del payload serializado antes de truncarlo. |
| sin definir | Certificado PEM; debe acompañarse de |
| sin definir | Clave privada PEM; debe acompañarse de |
Para acceso remoto, generar un token y declarar el hostname público:
openssl rand -hex 32MCP_HOST=0.0.0.0
MCP_PORT=3000
MCP_API_KEY=reemplazar-con-el-valor-generado
MCP_ALLOWED_HOSTS=mcp.example.comEn producción usar HTTPS mediante un reverse proxy confiable o TLS directo:
MCP_TLS_CERT_PATH=/ruta/absoluta/fullchain.pem
MCP_TLS_KEY_PATH=/ruta/absoluta/privkey.pemInstalar en Codex
Codex CLI, la extensión de IDE y la app de escritorio de ChatGPT comparten la configuración MCP. Exportar el mismo token del servidor y registrar la URL Streamable HTTP:
export MONGODB_MCP_TOKEN='reemplazar-con-MCP_API_KEY'
codex mcp add mongodb \
--url http://127.0.0.1:3000/mcp \
--bearer-token-env-var MONGODB_MCP_TOKEN
codex mcp listSi el servidor de loopback no usa MCP_API_KEY, omitir --bearer-token-env-var.
Configuración manual equivalente en ~/.codex/config.toml:
[mcp_servers.mongodb]
url = "http://127.0.0.1:3000/mcp"
bearer_token_env_var = "MONGODB_MCP_TOKEN"
required = true
tool_timeout_sec = 30Reiniciar el cliente luego de editar la configuración y usar /mcp para verificar la conexión. Ver la documentación MCP de Codex.
Instalar en Claude Code
Agregar el servidor remoto con alcance de usuario. Este comando toma el token del shell actual:
export MONGODB_MCP_TOKEN='reemplazar-con-MCP_API_KEY'
claude mcp add --transport http --scope user \
--header "Authorization: Bearer ${MONGODB_MCP_TOKEN}" \
mongodb http://127.0.0.1:3000/mcp
claude mcp listPara una configuración de proyecto que expanda el token al ejecutarse, agregar .mcp.json sin guardar el secreto:
{
"mcpServers": {
"mongodb": {
"type": "http",
"url": "http://127.0.0.1:3000/mcp",
"headers": {
"Authorization": "Bearer ${MONGODB_MCP_TOKEN}"
}
}
}
}Usar /mcp dentro de Claude Code para revisar el estado. Ver la documentación MCP de Claude Code.
Instalar en OpenCode
Exportar el token y agregar la configuración en opencode.json u opencode.jsonc:
export MONGODB_MCP_TOKEN='reemplazar-con-MCP_API_KEY'{
"$schema": "https://opencode.ai/config.json",
"mcp": {
"mongodb": {
"type": "remote",
"url": "http://127.0.0.1:3000/mcp",
"enabled": true,
"oauth": false,
"headers": {
"Authorization": "Bearer {env:MONGODB_MCP_TOKEN}"
}
}
}
}Verificar con opencode mcp list. Ver la documentación MCP de OpenCode.
Tools disponibles
Tool | Propósito | Efectos |
| Validar, comprobar y opcionalmente persistir una URI con nombre. | Actualiza el almacén local. |
| Listar perfiles con endpoints redactados y estado actual. | Ninguno. |
| Cerrar el cliente sin borrar el perfil. | Solo en el proceso actual. |
| Borrar un perfil y cerrar su cliente. | Borra únicamente el perfil local. |
| Listar bases visibles con paginación. | Ninguno. |
| Listar/filtrar colecciones con paginación. | Ninguno. |
| Ejecutar una consulta de lectura acotada. | Ninguno. |
| Ejecutar una agregación de solo lectura acotada. | Ninguno. |
| Insertar un documento Extended JSON. | Agrega un documento. |
| Insertar un lote acotado, ordenado o no. | Agrega documentos. |
| Actualizar o hacer upsert de un documento. | Modifica o crea un documento. |
| Actualizar un conjunto acotado de documentos. | Modifica hasta el límite pedido. |
| Reemplazar o hacer upsert de un documento completo. | Reemplaza o crea un documento. |
| Borrar como máximo un documento. | Borra permanentemente un documento. |
| Borrar un conjunto acotado de documentos. | Borra permanentemente hasta el límite pedido. |
| Ejecutar un pipeline acotado terminado en | Escribe o reemplaza la colección de salida exacta. |
| Eliminar una colección confirmada por nombre exacto. | Borra permanentemente documentos e índices. |
| Eliminar una base confirmada por nombre exacto. | Borra permanentemente la base completa. |
mongodb_update_many recorre los documentos coincidentes en orden de _id. Cuando has_more sea verdadero, enviar su next_after_id como after_id en la llamada siguiente para no seleccionar el mismo lote. mongodb_delete_many avanza naturalmente porque elimina cada lote seleccionado.
Prompts de ejemplo:
Conectate como "analytics" usando mongodb+srv://... y persistí el perfil.
Listá las bases disponibles mediante analytics.
Buscá 20 usuarios activos en app.users, ordenados por createdAt descendente.
Agrupá las órdenes pagadas por moneda y calculá el ingreso total.
Insertá una orden nueva en shop.orders usando Extended JSON.
Marcá como queued hasta 50 jobs pendientes e indicá si quedan más.
Fusioná los totales diarios en analytics.daily_revenue.
Eliminá staging.tmp_import después de confirmar el nombre exacto de la colección.Para valores BSON en filtros usar Extended JSON, por ejemplo:
{
"_id": { "$oid": "507f1f77bcf86cd799439011" },
"createdAt": { "$gte": { "$date": "2026-01-01T00:00:00.000Z" } }
}Seguridad
Una URI persistida se guarda sin cifrar en
MCP_MONGODB_STORE_PATH, protegida con modo0600. Proteger también el host y sus backups.El servidor nunca devuelve URIs ni credenciales guardadas; solo muestra esquema, host y ruta de base de datos.
Usar una cuenta MongoDB dedicada con privilegios mínimos y una
MCP_API_KEYfuerte e independiente.Tratar el acceso a este MCP como acceso de escritura a todo namespace permitido para esa cuenta MongoDB. Usar credenciales y despliegues separados para producción y desarrollo.
El inicio falla fuera de loopback si no se configuraron autenticación Bearer y hosts permitidos.
Todo request con
Originde navegador se rechaza salvo que esté permitido explícitamente.Las anotaciones de tools orientan al cliente, pero los permisos MongoDB siguen siendo la frontera de seguridad real.
Desarrollo
bun run typecheck
bun test
bun run build
bun run checkPrueba de integración con MongoDB local
Con MongoDB sin autenticación escuchando en 127.0.0.1:27017, ejecutar:
bun run test:integrationPara usar otro despliegue de prueba:
MONGODB_TEST_URI='mongodb://127.0.0.1:27018' bun run test:integrationbun run check:all ejecuta primero las validaciones normales y luego esta integración. La prueba crea una base única mcp_mongodb_test_<uuid>, carga fixtures, recorre el endpoint MCP HTTP real y elimina en finally tanto la base como el almacén temporal de conexiones. Nunca apuntar MONGODB_TEST_URI a un despliegue donde ese prefijo reservado contenga datos reales.
Estructura principal:
src/
connections/ Persistencia de perfiles y ciclo de vida de MongoClient
tools/ Declaración de tools MCP
utils/ Seguridad de consultas, paginación y redacción
config.ts Variables de entorno e invariantes de despliegue
http-server.ts Adaptador HTTP/HTTPS de Bun para Streamable HTTP
mcp-server.ts Factory e instrucciones del servidor MCP
index.ts Entrada del proceso y apagado ordenado
test/ Pruebas unitarias y de protocolo MCPThis server cannot be installed
Maintenance
Resources
Unclaimed servers have limited discoverability.
Looking for Admin?
If you are the server author, to access and configure the admin panel.
Related MCP Servers
- AlicenseAqualityDmaintenanceA Model Context Protocol server that provides read-only access to MongoDB databases, enabling AI assistants to directly query and analyze MongoDB data while maintaining data safety.14289MIT
- Alicense-qualityDmaintenanceEnables AI agents to securely connect to MongoDB databases via MCP, with deployment modes from basic to RBAC-gated with Keycloak authentication.282MIT
- FlicenseBqualityCmaintenanceA MongoDB MCP Server that allows AI agents and MCP clients to interact with MongoDB databases through standardized tools for CRUD operations, schema discovery, and collection management.8
- Flicense-qualityDmaintenanceA read-only MongoDB MCP server designed for serverless deployment on Vercel, providing secure, limited access to MongoDB databases for AI assistants.
Related MCP Connectors
MCP server connecting AI agents to non-custodial staking data across 130+ networks.
Managed LinkedIn MCP server for AI agents: search, connect, message and enrich on accounts you own.
Self-hosted MCP gateway: turn any API, database or MCP server into AI connectors — no code.
Latest Blog Posts
- Who's Calling? MCP Hosts Are an Identity Blind Spot (And the Spec Knows It)By Om-Shree-0709 on .mcpAgent IdentityOAuth 2.1
- Your AI Chatbot Just Exposed Your CEO's Salary to an InternBy Om-Shree-0709 on .Agent IdentityMCP SecurityOAuth Delegation
- Why MCP Servers Need Execution Sandboxing (And Why Your Current Stack Isn't Enough)By Om-Shree-0709 on .Agentic AiPrompt InjectionWebAssembly
MCP directory API
We provide all the information about MCP servers via our MCP API.
curl -X GET 'https://glama.ai/api/mcp/v1/servers/stock42/mcp-mongodb'
If you have feedback or need assistance with the MCP directory API, please join our Discord server