database-mcp
database-mcp
Servidor MCP de base de datos SQL con paginación real de resultados en el lado del servidor — la característica que ningún servidor MCP de base de datos establecido tiene (DBHub limita filas, Google's MCP Toolbox devuelve todo, mcp-alchemy trunca a 4000 caracteres).
Implementación de referencia en PostgreSQL.
Por qué
Cada servidor MCP SQL existente o trunca resultados grandes o los vuelca completos en el contexto del modelo. La especificación MCP solo pagina operaciones de lista (tools/list), no resultados de herramientas. database-mcp cierra esa brecha:
Una consulta se ejecuta una vez como un cursor del lado del servidor de PostgreSQL (
DECLARE/FETCH FORWARD) dentro de una transacción mantenida.Cada
fetch(cursor)continúa exactamente donde terminó la última página — sin re-ejecución, sin re-escaneo deOFFSET, y la instantánea MVCC mantiene el resultado estable incluso bajo escrituras concurrentes.Las páginas están limitadas por filas (
page_size) y por bytes renderizados (max_page_bytes); las celdas sobredimensionadas se truncan con un marcador explícito.Los cursores mantenidos están limitados: máximo N concurrentes (evicción LRU), evicción por inactividad TTL, además de
idle_in_transaction_session_timeoutcomo respaldo del lado del servidor. Los cursores agotados se cierran automáticamente.
Related MCP server: pgsql-mcp
Perfiles de conexión — gestionados por la IA en tiempo de ejecución
Las conexiones son perfiles con nombre, persistidos en ~/.config/database-mcp/profiles.json (chmod 600). La IA puede añadir, cambiar, probar y eliminarlos sobre la marcha mediante herramientas — sin reiniciar el servidor:
profile_add(name, dsn, allow_writes=false, description, make_default, test=true)profile_remove(name)·profile_test(name)·profiles()cada herramienta de consulta acepta un parámetro opcional
profile; se usa el perfil predeterminado cuando se omite.
Los perfiles son de solo lectura por defecto (default_transaction_read_only a nivel de sesión); las escrituras requieren un perfil con allow_writes=true explícito.
Puente SSH
Un perfil puede alcanzar una base de datos que solo es accesible vía SSH (el clásico escenario "Postgres escucha en localhost de un host remoto"):
profile_add(name="prod", dsn="postgresql://app@dbhost:5432/app",
ssh_host="dbhost")El túnel es un subproceso de
sshdel sistema (-N -L, BatchMode, keepalives) — tu~/.ssh/config, claves y agente se aplican sin cambios. La autenticación debe funcionar de forma no interactiva.ssh_remote_host/ssh_remote_portpor defecto toman el host/puerto del DSN tal como se ve desde el host SSH; si el host del DSN es igual al host SSH, por defecto es127.0.0.1(el caso habitual).Los túneles se inician de forma perezosa, se comprueba su salud en cada uso y se reconstruyen automáticamente. Si un túnel muere a mitad de paginación, sus cursores se invalidan con un error claro y la siguiente consulta se reconecta.
La multiplexación (
ControlMaster) está explícitamente deshabilitada para conexiones de túnel, de modo que la vida del túnel sea exactamente la vida del subproceso.
Herramientas
Herramienta | Propósito |
| Ejecutar SQL, obtener la primera página + |
| Siguiente página de un cursor mantenido — sin re-ejecución |
| Cerrar uno/todos los cursores antes de tiempo |
| Listar tablas/vistas con estimaciones de filas y tamaños |
| Columnas, restricciones, índices de una tabla |
| Plan de consulta (opcionalmente |
| Tarjeta de orientación: cada tabla + estimación de filas + nombres de columnas en una llamada |
| Encontrar tablas/columnas/funciones por nombre o comentario |
| Estadísticas de columnas de |
| Claves foráneas de una tabla, en ambas direcciones |
| Ruta FK más corta entre dos tablas como una cadena JOIN lista |
| Estimación instantánea del planificador (opcional |
| Filas genuinamente aleatorias vía |
| Gestión de conexiones en tiempo de ejecución |
| Perfiles, pools, cursores abiertos, límites |
Los resultados son JSON compacto — columnas una vez, filas como arrays — aproximadamente la mitad de los tokens del formato de diccionario por fila que emiten otros servidores. query también devuelve estimated_rows (estimación del planificador vía EXPLAIN) para que el modelo sepa en qué está paginando.
Instalación y ejecución
uv pip install -e .
database-mcp --dsn postgresql://user@host:5432/db # registers profile "default"
database-mcp # start empty, add profiles at runtimeRegistro en Claude Code:
claude mcp add database -- database-mcp --dsn postgresql://user@host:5432/dbOpciones: --profiles FILE, --allow-writes, --page-size 50, --max-page-size 500, --max-page-bytes 32000, --max-cell 400, --cursor-ttl 300, --max-cursors 4, --statement-timeout 30, --keepalive 120, --connect-timeout 5.
Entorno: DATABASE_MCP_DSN / DATABASE_URL, DATABASE_MCP_PROFILES.
Manejo de conexiones obsoletas
Las conexiones muertas se detectan rápidamente en cada capa en lugar de colgarse:
Túneles SSH:
ServerAliveInterval=--keepalive(por defecto 2 min) conServerAliveCountMax=1— una sonda perdida termina el proceso del túnel, que el gestor del motor detecta en el siguiente uso y reconstruye de forma perezosa.Conexiones de base de datos: keepalives TCP (
keepalives_idle=--keepalive, sondas cada 10 s, 3 fallos) detectan pares muertos en ~30 s — incluyendo conexiones de cursor fijadas fuera del pool.Comprobación de checkout del pool: cada conexión entregada se valida con un viaje de ida y vuelta barato; una obsoleta se descarta y se reemplaza de forma transparente — el llamador nunca ve el error. Las conexiones inactivas del pool se reciclan después de
--keepalivesegundos; los intentos de conexión fallan después de--connect-timeout(por defecto 5 s) en lugar del ~2 min por defecto de TCP.
Pruebas
uv pip install -e '.[dev]'
pytest # needs a local PostgreSQL (DBMCP_TEST_DSN to override)Licencia
MIT
Available Tools
18 toolscloseA
Close an open cursor (or all cursors when no token is given) to free its connection early.
Inputs: cursor. Returns: result
countA
Row count, estimate-first: instant planner estimate (no scan), optionally with a WHERE clause; exact=true runs a real count(*) under the statement timeout. Prefer the estimate.
Inputs: table (required), exact, where, profile. Returns: result
describeA
Describe one table: columns with types/nullability/defaults, constraints (PK/FK/unique/check), and indexes.
Inputs: table (required), profile. Returns: result
explainA
Show the query plan (EXPLAIN). Set analyze=true to actually run the statement and get real timings.
Inputs: sql (required), params, analyze, profile. Returns: result
fetchA
Fetch the next page from an open cursor returned by query. No re-execution: rows continue exactly where the last page ended. The cursor auto-closes when exhausted (has_more=false).
Inputs: cursor (required), page_size. Returns: result
join_pathB
Shortest foreign-key path between two tables, rendered as a ready-to-use JOIN chain (up to 3 equally short paths). Use this instead of guessing joins on unfamiliar schemas.
Inputs: to_table (required), from_table (required), profile, max_hops. Returns: result
overviewA
Orientation card for an unknown database: every table with row estimate and its column names in ONE compact call — use this before tables/describe round-trips. Optional table-name filter.
Inputs: filter, profile. Returns: result
profileA
Column statistics from pg_stats WITHOUT touching the table: null fraction, distinct count (negative = fraction of rows, -1 = unique), most common values with frequencies, histogram bounds, physical correlation. Replaces exploratory SELECT DISTINCT / GROUP BY scans.
Inputs: table (required), profile. Returns: result
profile_addA
Add or update a named connection profile at runtime and persist it. Tests the connection first (set test=false to skip). Profiles are read-only unless allow_writes=true. make_default=true switches the default profile. For a database only reachable via SSH, set ssh_host (an ssh destination or ~/.ssh/config alias; BatchMode, so keys/agent must work non-interactively) — a tunnel is opened automatically and kept alive; ssh_remote_host/ssh_remote_port default to the DSN's host/port as seen FROM the ssh host (usually 127.0.0.1:5432).
Inputs: dsn (required), name (required), test, ssh_host, +5 more. Returns: result
profile_removeB
Remove a connection profile (open cursors on it are closed).
Inputs: name (required). Returns: result
profilesA
List all connection profiles (DSNs password-redacted) and which one is the default.
Inputs: no named parameters. Returns: result
profile_testA
Test connectivity of a profile (default profile when omitted): server version and connect latency.
Inputs: name. Returns: result
queryA
Execute SQL on a profile (default profile when omitted). Returns the first page as compact {"columns":[...],"rows":[[...],...],"page":{"returned","has_more","estimated_rows","cursor"}}. When has_more is true, pass page.cursor to the fetch tool — the query is NOT re-executed; a server-side cursor is held open (stable snapshot). Placeholders: %s positional with the params array.
Inputs: sql (required), params, profile, page_size. Returns: result
relationsA
Foreign keys of one table, both directions: what it references and what references it.
Inputs: table (required), profile. Returns: result
sampleA
A few genuinely random rows from a table (TABLESAMPLE on big tables — no scan, no physically-adjacent LIMIT bias).
Inputs: table (required), n, profile. Returns: result
search_objectsB
Find tables, columns, and functions by name OR by comment (pg_description — often the only documentation a schema has). Answers 'where is the customer email?' in one call.
Inputs: term (required), limit, profile. Returns: result
statusA
Server status: profiles with pool statistics, open cursors, configured limits, profiles file location.
Inputs: no named parameters. Returns: result
tablesA
List tables/views/matviews with estimated row counts and sizes (system schemas excluded). Optional name filter.
Inputs: filter, profile. Returns: result
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 18 tools
Each tool targets a distinct concern: cursor-paginated queries (query/fetch/close), schema exploration (tables/describe/overview/search_objects), statistical analysis (profile/count/sample/relations/join_path), explain plans, and connection profile management (profiles/profile_add/profile_remove/profile_test). No overlapping responsibilities that would cause an agent to misselect.
Tool names are mostly snake_case verbs or nouns that clearly map to actions (query, fetch, describe, count) or objects (tables, profiles). The profile_add/profile_remove/profile_test trio uses a consistent prefix. The only minor inconsistency is mixing singular nouns like 'profile' with plural 'profiles' and standalone verbs, but this does not impair predictability.
At 18 tools, the set is slightly heavy but each tool earns its place—covering query execution, pagination, schema discovery, row sampling, join pathing, explain, column statistics, and connection management. It leans toward the upper bound of reasonable scope for a database MCP server, but avoids bloat.
The tool surface covers the full read-side lifecycle: discover schema (overview, tables, describe, search_objects), analyze data (profile, count, sample, relations, join_path), execute and paginate queries (query, fetch, close), inspect performance (explain), and manage connections (profiles, profile_add/remove/test, status). No critical operations are missing for the intended read/diagnostics purpose.
Related MCP Connectors
Query Postgres, MySQL, SQL Server, Oracle, BigQuery, ClickHouse and Redshift from your AI client.
Query PostgreSQL databases in plain English — LLM-generated, safety-validated SQL.
Connect to PlanetScale databases, branches, schema, query insights, and execute SQL
Managed Postgres MCP: projects, SQL, docs search, and storage buckets via OAuth.
Related MCP Servers
- AlicenseBqualityDmaintenanceEnables comprehensive PostgreSQL database management including index tuning, query plan analysis, health monitoring, schema-aware SQL generation, and safe SQL execution with configurable access control for both development and production environments.9MIT
- AlicenseBqualityDmaintenanceEnables interaction with PostgreSQL databases through comprehensive database management tools including index tuning, query execution plans, health checks, schema intelligence, and safe SQL execution with configurable read-only mode for production use.35MIT
- FlicenseNot gradedqualityDmaintenanceEnables querying PostgreSQL databases via MCP, with multi-database routing, credential isolation, and truncated results plus full CSV export.-
- FlicenseNot gradedqualityDmaintenanceEnables secure, direct access to PostgreSQL databases for queries, modifications, and schema exploration.-