MongoDB MCP Server

MongoDB MCP Server

A secure, read-only MCP server that enables AI agents to connect to MongoDB, perform queries and aggregations, and manage connections.

Category
Visit Server

README

MongoDB MCP Server

English · Español

English

A secure, read-only 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 0600 permissions.
  • Lists configured connections, databases, and collections.
  • Runs bounded find queries and read-only aggregation pipelines.
  • 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.

The server intentionally does not expose insert, update, delete, $out, $merge, or server-side JavaScript operations.

Requirements

  • Bun 1.3 or newer.
  • A reachable MongoDB deployment and a connection URI.
  • A MongoDB user with only the permissions the agents should have. A read-only database user is strongly recommended.

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:source

The default endpoints are:

  • MCP: http://127.0.0.1:3000/mcp
  • Health check: http://127.0.0.1:3000/health

For a built server:

bun run build
bun start

Configuration

Bun loads .env automatically. All settings are optional when running only on loopback.

Variable Default Description
MCP_HOST 127.0.0.1 HTTP bind address.
MCP_PORT 3000 HTTP port.
MCP_API_KEY unset Bearer token for /mcp; required outside loopback.
MCP_ALLOWED_HOSTS loopback hosts Comma-separated exact Host values; required outside loopback. Include the port when clients send one.
MCP_ALLOWED_ORIGINS empty Comma-separated browser origins. Requests containing an unlisted Origin are rejected.
MCP_MONGODB_STORE_PATH .data/connections.json Persistent connection-profile file.
MCP_MAX_QUERY_LIMIT 100 Maximum documents/items per tool call.
MCP_QUERY_TIMEOUT_MS 10000 Maximum query and connection timeout accepted by tools.
MCP_MAX_RESPONSE_CHARS 50000 Maximum serialized document payload before truncation.
MCP_TLS_CERT_PATH unset PEM certificate path; must be used with MCP_TLS_KEY_PATH.
MCP_TLS_KEY_PATH unset PEM private-key path; must be used with MCP_TLS_CERT_PATH.

Generate a token for remote access and configure the public hostname:

openssl rand -hex 32
MCP_HOST=0.0.0.0
MCP_PORT=3000
MCP_API_KEY=replace-with-the-generated-value
MCP_ALLOWED_HOSTS=mcp.example.com

Use 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.pem

Install 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 list

If 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 = 30

Restart 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 list

For 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
mongodb_connect Validate, ping, and optionally persist a named MongoDB URI. Updates the local connection store.
mongodb_list_connections List profiles with redacted endpoints and live status. None.
mongodb_disconnect Close a live client without deleting its profile. Runtime-only.
mongodb_remove_connection Delete a saved/transient profile and close its client. Deletes the local profile only.
mongodb_list_databases List visible databases with pagination. None.
mongodb_list_collections List/filter collections with pagination. None.
mongodb_find Run a bounded read-only find query. None.
mongodb_aggregate Run a bounded read-only aggregation. None.

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.

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 mode 0600. 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.
  • Binding outside loopback fails at startup unless both Bearer authentication and explicit allowed hosts are configured.
  • Requests with a browser Origin are 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 check

Local MongoDB integration test

With an unauthenticated MongoDB server listening on 127.0.0.1:27017, run:

bun run test:integration

To use another test deployment:

MONGODB_TEST_URI='mongodb://127.0.0.1:27018' bun run test:integration

bun 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 tests

Español

Servidor seguro y de solo lectura 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 find acotadas y pipelines de agregación de solo lectura.
  • 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 servidor no expone inserciones, actualizaciones, borrados, $out, $merge ni JavaScript ejecutado por MongoDB.

Requisitos

  • Bun 1.3 o superior.
  • Un despliegue MongoDB accesible y su URI de conexión.
  • Un usuario MongoDB con únicamente los permisos que deben tener los agentes. Se recomienda fuertemente un usuario de solo lectura.

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:source

Endpoints predeterminados:

  • MCP: http://127.0.0.1:3000/mcp
  • Salud: http://127.0.0.1:3000/health

Para ejecutar el artefacto compilado:

bun run build
bun start

Configuración

Bun carga .env automáticamente. Todas las variables son opcionales si el servidor escucha únicamente en loopback.

Variable Predeterminado Descripción
MCP_HOST 127.0.0.1 Dirección donde escucha HTTP.
MCP_PORT 3000 Puerto HTTP.
MCP_API_KEY sin definir Token Bearer para /mcp; obligatorio fuera de loopback.
MCP_ALLOWED_HOSTS hosts de loopback Valores Host exactos separados por comas; obligatorio fuera de loopback. Incluir puerto cuando el cliente lo envíe.
MCP_ALLOWED_ORIGINS vacío Orígenes de navegador separados por comas. Se rechaza todo Origin no listado.
MCP_MONGODB_STORE_PATH .data/connections.json Archivo de perfiles persistentes.
MCP_MAX_QUERY_LIMIT 100 Máximo de documentos/elementos por tool.
MCP_QUERY_TIMEOUT_MS 10000 Timeout máximo de conexión y consulta aceptado por las tools.
MCP_MAX_RESPONSE_CHARS 50000 Máximo del payload serializado antes de truncarlo.
MCP_TLS_CERT_PATH sin definir Certificado PEM; debe acompañarse de MCP_TLS_KEY_PATH.
MCP_TLS_KEY_PATH sin definir Clave privada PEM; debe acompañarse de MCP_TLS_CERT_PATH.

Para acceso remoto, generar un token y declarar el hostname público:

openssl rand -hex 32
MCP_HOST=0.0.0.0
MCP_PORT=3000
MCP_API_KEY=reemplazar-con-el-valor-generado
MCP_ALLOWED_HOSTS=mcp.example.com

En 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.pem

Instalar 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 list

Si 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 = 30

Reiniciar 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 list

Para 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
mongodb_connect Validar, comprobar y opcionalmente persistir una URI con nombre. Actualiza el almacén local.
mongodb_list_connections Listar perfiles con endpoints redactados y estado actual. Ninguno.
mongodb_disconnect Cerrar el cliente sin borrar el perfil. Solo en el proceso actual.
mongodb_remove_connection Borrar un perfil y cerrar su cliente. Borra únicamente el perfil local.
mongodb_list_databases Listar bases visibles con paginación. Ninguno.
mongodb_list_collections Listar/filtrar colecciones con paginación. Ninguno.
mongodb_find Ejecutar una consulta de lectura acotada. Ninguno.
mongodb_aggregate Ejecutar una agregación de solo lectura acotada. Ninguno.

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.

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 modo 0600. 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_KEY fuerte e independiente.
  • El inicio falla fuera de loopback si no se configuraron autenticación Bearer y hosts permitidos.
  • Todo request con Origin de 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 check

Prueba de integración con MongoDB local

Con MongoDB sin autenticación escuchando en 127.0.0.1:27017, ejecutar:

bun run test:integration

Para usar otro despliegue de prueba:

MONGODB_TEST_URI='mongodb://127.0.0.1:27018' bun run test:integration

bun 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 MCP

Recommended Servers

playwright-mcp

playwright-mcp

A Model Context Protocol server that enables LLMs to interact with web pages through structured accessibility snapshots without requiring vision models or screenshots.

Official
Featured
TypeScript
Magic Component Platform (MCP)

Magic Component Platform (MCP)

An AI-powered tool that generates modern UI components from natural language descriptions, integrating with popular IDEs to streamline UI development workflow.

Official
Featured
Local
TypeScript
Audiense Insights MCP Server

Audiense Insights MCP Server

Enables interaction with Audiense Insights accounts via the Model Context Protocol, facilitating the extraction and analysis of marketing insights and audience data including demographics, behavior, and influencer engagement.

Official
Featured
Local
TypeScript
VeyraX MCP

VeyraX MCP

Single MCP tool to connect all your favorite tools: Gmail, Calendar and 40 more.

Official
Featured
Local
Kagi MCP Server

Kagi MCP Server

An MCP server that integrates Kagi search capabilities with Claude AI, enabling Claude to perform real-time web searches when answering questions that require up-to-date information.

Official
Featured
Python
graphlit-mcp-server

graphlit-mcp-server

The Model Context Protocol (MCP) Server enables integration between MCP clients and the Graphlit service. Ingest anything from Slack to Gmail to podcast feeds, in addition to web crawling, into a Graphlit project - and then retrieve relevant contents from the MCP client.

Official
Featured
TypeScript
Neon Database

Neon Database

MCP server for interacting with Neon Management API and databases

Official
Featured
Exa Search

Exa Search

A Model Context Protocol (MCP) server lets AI assistants like Claude use the Exa AI Search API for web searches. This setup allows AI models to get real-time web information in a safe and controlled way.

Official
Featured
Qdrant Server

Qdrant Server

This repository is an example of how to create a MCP server for Qdrant, a vector search engine.

Official
Featured
E2B

E2B

Using MCP to run code via e2b.

Official
Featured