@cocaxcode/database-mcp
Allows interacting with MySQL databases by running SQL queries, exploring schemas and tables, and managing named connections within groups, including connection switching, rollback, and dump/restore.
Allows interacting with PostgreSQL databases by running SQL queries, exploring schemas and tables, and managing named connections within groups, including connection switching, rollback, and dump/restore.
Allows interacting with SQLite databases by running SQL queries, exploring schemas and tables, and managing named connections within groups, including connection switching and rollback.
Click on "Deploy 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., "@@cocaxcode/database-mcp Show me the last 10 orders with customer names"
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.
Quick Overview
The most complete MCP server for databases. 33 tools across 3 engines (PostgreSQL, MySQL, SQLite), with connection groups, named connection management, automatic rollback, dump/restore, schema auto-discovery via MCP Resources, and full query history — all from natural language.
This is not just a query runner. It is a full database workbench: organize connections into groups scoped to your project directories, set defaults that persist between sessions, introspect schemas at three levels of detail, get pre-mutation snapshots on every write, undo mistakes with reverse SQL, dump and restore entire databases, and track every query you run — per project, per connection.
Every connection belongs to a group. Groups have scopes (directories), a default connection, and an active connection. When you work inside a scoped directory, you only see that group's connections — no clutter, no confusion.
You describe what you need. The AI reads your schema, writes the SQL, and executes it safely — with automatic LIMIT injection, pre-mutation snapshots, and confirmation before destructive operations. No cloud accounts, no ORMs, no config files. Credentials never leave your machine. Everything runs locally.
Works with Claude Code, Claude Desktop, Cursor, Windsurf, VS Code, Codex CLI, Gemini CLI, and any MCP-compatible client.
Related MCP server: Database MCP Server
Just Talk to It
You don't need to memorize tool names or SQL syntax. Just say what you want.
> "Connect to my local PostgreSQL on port 5432, database myapp, user admin"
> "Create a group called backend and add this directory"
> "Connect to my PostgreSQL on localhost, put it in the backend group"
> "Set local-pg as the default connection"
> "Show me all tables"
> "What columns does the users table have?"
> "Show me the last 10 orders with the customer name"
-> AI reads FKs from schema, builds the JOIN, applies LIMIT 10
> "Insert a test user called Alice"
-> Snapshot captured for rollback
> "Oops, undo that"
-> Rows restored via reverse SQL
> "Switch to the production database for this session"
-> Instant context change, all queries now go to prod
> "Delete all inactive users"
-> "This will affect N rows. Call again with confirm=true to proceed."
> "What did I run today?"
-> Full query history with timestamps and execution times
> "Dump the database — structure and data"
-> SQL file generated, ready for restoreThe AI already knows your schema through MCP Resources. It reads db://schema to discover tables and db://tables/{name}/schema for columns, foreign keys, and indexes. When you ask for data across tables, it builds correct JOINs automatically.
Connection Groups
Every connection belongs to a group. Groups are the organizing unit for your database connections — they keep things scoped, clean, and automatic.
A group has three key concepts:
Scopes: directories that share the group's connections. When you work inside a scoped directory, you only see that group's connections. No global clutter.
Default: the connection that activates automatically when you enter a scoped directory. Persists between sessions.
Active: the connection being used right now. Session only — resets to the default on restart.
Here is a practical workflow:
"Create a group called backend"
"Add this directory as scope"
"Create a PostgreSQL connection called local-dev in the backend group" <- auto-default (first connection)
"Create another called production in backend"
"List connections" <- shows local-dev (active, default)
"Switch to production" <- session only
"Set production as default" <- persists between sessionsThe first connection added to a group becomes the default automatically. Switching connections only changes the active for the current session — restart and you are back to the default. If you want the change to stick, set a new default explicitly.
This means you can safely switch to production for a quick query and know that next time you open the project, you will be back on your development database.
Installation
Claude Code
claude mcp add --scope user database -- npx -y @cocaxcode/database-mcp@latestClaude Desktop
Add to your config file (~/Library/Application Support/Claude/claude_desktop_config.json on macOS, %APPDATA%\Claude\claude_desktop_config.json on Windows):
{
"mcpServers": {
"database": {
"command": "npx",
"args": ["-y", "@cocaxcode/database-mcp@latest"]
}
}
}Add to .cursor/mcp.json or .windsurf/mcp.json in your project root:
{
"mcpServers": {
"database": {
"command": "npx",
"args": ["-y", "@cocaxcode/database-mcp@latest"]
}
}
}Add to .vscode/mcp.json:
{
"servers": {
"database": {
"type": "stdio",
"command": "npx",
"args": ["-y", "@cocaxcode/database-mcp@latest"]
}
}
}codex mcp add database -- npx -y @cocaxcode/database-mcp@latestOr add to ~/.codex/config.toml:
[mcp_servers.database]
command = "npx"
args = ["-y", "@cocaxcode/database-mcp@latest"]Add to ~/.gemini/settings.json:
{
"mcpServers": {
"database": {
"command": "npx",
"args": ["-y", "@cocaxcode/database-mcp@latest"]
}
}
}Driver installation
Install only the driver(s) you need — they load dynamically at runtime:
npm install -g postgres # PostgreSQL (postgres.js)
npm install -g mysql2 # MySQL
npm install -g sql.js # SQLite (runs in-process, no native bindings)Note: When using
npx, drivers must be installed globally. If you install the server globally (npm install -g @cocaxcode/database-mcp), drivers can be local or global.
Features
Multi-database, one interface
Most database MCP servers make you reconfigure credentials every session. This one does not. Named connections persist inside groups — create them once, use them forever.
Named connections work like git branches. You create dev, staging, prod once inside a group and they are always there. Switching is instant — one command, zero reconfiguration:
"Create a group called my-project and add this directory as scope"
"Create a connection called dev with host localhost, database myapp, user admin in my-project"
"Create a read-only connection called analytics pointing to ./data/metrics.db in my-project"
"Switch to dev" -> queries go to PostgreSQL
"Switch to analytics" -> queries go to SQLite
"Duplicate dev as dev-readonly with read-only mode"Group-scoped connections mean different projects see different databases automatically. Working on project A? You see project A's group and connections. Switch to project B's directory and it picks up project B's group with its own default. No manual switching, no interference between projects:
"Create a group called frontend with scope /home/user/frontend"
"Create a group called backend with scope /home/user/backend"Now each directory has its own isolated set of connections.
100% local credentials. Every connection is stored as a JSON file in ~/.database-mcp/connections/. Passwords never leave your machine. Nothing is sent to the cloud. Nothing is committed to git. Your credentials are yours.
Live management. Create, duplicate, rename, test, export, and switch connections mid-conversation. No restart needed, no config file editing, no context loss.
Safety built in
Protection | How it works |
Read-only mode | Connection-level enforcement — blocks all mutations |
Confirmation required | Destructive ops require explicit |
Auto LIMIT | Read queries get |
Password masking | Credentials shown as |
Pre-mutation snapshots | Every INSERT/UPDATE/DELETE captures row state for rollback |
Auto gitignore |
|
Rollback snapshots
Every mutation captures a pre-state snapshot. Undo anything.
"Show me available rollbacks"
"Rollback the last delete"
-> "This will INSERT 47 rows back into orders. Confirm?"
-> Rows restored via reverse SQLOriginal operation | Rollback generates |
|
|
|
|
|
|
DDL (CREATE, ALTER, DROP) | Logged but not reversible |
Schema introspection
Three levels of detail, with pattern filtering:
"List all tables" -> names only (fast)
"Show me the users table with columns" -> columns + types + nullable
"Full schema for orders including FKs" -> columns + foreign keys + indexes
"Tables starting with user" -> pattern: 'user%'MCP Resources (db://schema and db://tables/{name}/schema) give AI agents automatic access to your schema — no manual SQL needed for multi-table queries.
Query execution with EXPLAIN
"Show me all users"
-> SELECT * FROM users LIMIT 100 <- auto LIMIT
"Show the execution plan for this query"
-> EXPLAIN ANALYZE with dialect-specific syntax (PostgreSQL/MySQL/SQLite)Compression modes (v0.3+)
SQL results often carry TEXT / JSON / HTML columns that can be kilobytes per row. AI agents pay for every byte that reaches the context window. execute_query, execute_mutation and explain_query accept four optional parameters that cut 60-95% of those tokens while keeping rows and structure intact.
Param | Values | What it does |
|
| Controls detail level |
|
| Returns only these columns (client-side projection) |
| number (default | Per-cell byte cap for |
| number | Row cap beyond SQL LIMIT |
Modes:
minimal— onlyrowCount,executionTimeMs,affectedRows, and a preview of the first row. Ideal for INSERT/UPDATE/DELETE confirmation, COUNT queries, polling. Saves ~90-95% tokens.normal(default) — full rows, but each cell truncated tomax_cell_byteswith a…(+NB)marker. Preserves table structure. Saves ~60-80% tokens on wide rows.full— entire result untouched. Use when you need the complete value of every cell.
Typical savings on SELECT * FROM blog_posts LIMIT 100 where content is ~2KB HTML per row (~200KB total):
Mode | Tokens consumed | Savings |
| ~50,000 | 0% (baseline) |
| ~12,500 | ~75% |
| ~2,500 | ~95% |
| ~300 | ~99% |
For a head-to-head comparison against raw
psqlwith measured numbers, see Native alternatives below.
Recovering the full result: every compressed response includes a call_id. If you need the complete cells later, call inspect_last_query({ call_id }) — without re-executing the SQL, preserving DB load and any side-effects. Results are kept in a 20-slot ring buffer and persisted to ~/.database-mcp/last-queries/ with a 1-hour TTL.
// Example: normal (default) response
{
"call_id": "k3m9a2xp",
"columns": ["id", "title", "content"],
"rows": [
{ "id": 1, "title": "Hello", "content": "<h1>Long HTML…(+1847B)" }
],
"rowCount": 1,
"executionTimeMs": 12,
"cells_truncated": 1,
"hint": "1 cell(s) truncated to 500 bytes. Use inspect_last_query({ call_id: \"k3m9a2xp\" }) for full values.",
"tokens_saved_estimate": 462
}Native alternatives: real token cost
How this MCP compares against the native options Claude Code has when database is not available (Bash + psql, sqlite3, mysql CLI, etc.).
TL;DR: compared to raw psql, execute_query saves between 78% and 96% of context tokens depending on the mode, with no loss of debugging information. Measured on a real call to SELECT * FROM blog_posts LIMIT 5 on a PostgreSQL table with a content column of ~1 KB of HTML per row:
How the agent calls it | Uses MCP? | Tokens consumed | Delta vs psql |
| ❌ native | ~1,800 | baseline |
| ❌ native | fragile, agent-assembled | hard to measure |
| ✅ MCP | ~1,500 | −17% (less formatting overhead) |
| ✅ MCP | ~400 | −78% |
| ✅ MCP | ~80 | −96% |
| ✅ MCP | ~130 | −93% |
Why this table's numbers differ from the "Compression modes" section above: these come from a 5-row real-world query, while the previous table extrapolates to a 100-row result with heavier content. Trend and order of magnitude are the same.
Notes:
Raw
psqloutput gets worse as rows grow — JSONB and long TEXT columns have no native filter. The MCP cell-truncation preserves structure (row count + column list) while collapsing heavy cells with a…(+NB)marker.inspect_last_queryrecovers the complete result without re-running the SQL. Withpsqlyou would have to re-execute, paying DB CPU again and risking re-triggering side-effects onRETURNINGclauses.The MCP also adds features that have no direct native equivalent: connection groups scoped to project directories, automatic rollback snapshots on mutations, query history, schema introspection via MCP Resources, and dump/restore.
Schema context is added at the end of the response when relevant (default
truefornormal/full). Disable withinclude_schema_context: falseif the agent already knows the schema.Every registered MCP adds a fixed overhead of ~300-600 tokens per session (its instructions block + tool names). Typical break-even: 1 real query per session.
Dump and restore
Full database backup in SQL format — structure only or structure + data.
"Dump the database"
-> Choose: structure only or full
-> Choose: all tables or specific ones
-> SQL file saved to .database-mcp/dumps/
"Restore from the last dump"
-> Lists available dumps, asks for confirmation, executesGenerated SQL handles DROP TABLE IF EXISTS, FK disable/enable, and dialect-aware DDL.
Query history
Every query logged per-project with timestamp, connection, execution time, and result type.
"What queries did I run today?"
"Show me only mutations"
"History for the prod connection"Export and import connections
"Export all connections" -> JSON with masked passwords
"Export with secrets included" -> JSON with real credentials
"Import these connections: { ... }" -> creates missing connectionsTool Reference
33 tools in 8 categories, plus 2 MCP Resources:
Category | Tools | Count |
Connections |
| 11 |
Groups |
| 7 |
Schema |
| 1 |
Queries |
| 3 |
Dump |
| 3 |
Rollback |
| 2 |
History |
| 2 |
Config |
| 2 |
Resources: db://schema · db://tables/{tableName}/schema
Tip: You never need to call these tools directly. Just describe what you want and the AI picks the right one.
Storage
Storage is split into two locations by design. This separation is intentional and solves a real problem: your credentials belong to you, your project history belongs to the project.
Global: ~/.database-mcp/ — groups, connections, credentials, and settings. Lives in your home directory. Never inside a project. Never in git. Never shared with anyone unless you explicitly export them.
Per-project: {project}/.database-mcp/ — query history, rollback snapshots, and database dumps. Lives inside the project directory and is automatically added to .gitignore on first write.
~/.database-mcp/ # Global (configurable via DATABASE_MCP_DIR)
├── groups/ # Connection groups with scopes and defaults
├── connections/ # Connection configs (credentials, chmod 600)
├── project-conns.json # Session-only active connections (cleared on restart)
└── config.json # Server config (limits)
{your-project}/.database-mcp/ # Per-project (auto-gitignored)
├── history.json # Query history (max 5000)
├── rollbacks.json # Pre-mutation snapshots (max 1000)
└── dumps/
└── {conn}-{timestamp}-{mode}.sql # Database dumpsThe result: you can share a project repo freely — collaborators get the history and rollback structure, but zero credentials. They create their own connections and groups locally.
Configuration
Configurable from the conversation or via environment variables:
Variable | Description | Default |
| Global storage directory |
|
| Max rollback snapshots per project |
|
| Max history entries per project |
|
"Set max rollbacks to 2000"
"Set max history to 10000"Priority: env var > saved config > default.
Warning: If you override
DATABASE_MCP_DIRto a path inside a git repository, add.database-mcp/to your.gitignoreto avoid pushing credentials.
Architecture
src/
├── index.ts # Entry point (StdioServerTransport)
├── server.ts # createServer() factory
├── tools/ # 33 tool handlers (one file per category)
├── resources/ # MCP Resources (schema auto-discovery)
├── services/ # Business logic
│ ├── connection-manager # Lazy connect, driver caching
│ ├── schema-introspector # Multi-dialect introspection (3 detail levels)
│ ├── query-executor # Read/mutation/explain with safety
│ ├── rollback-manager # Snapshot capture + reverse SQL
│ ├── history-logger # Per-project query log
│ └── dump-manager # Dump/restore (SQL generation)
├── drivers/ # Database adapters (postgres, mysql, sqlite)
├── lib/ # Types, storage, sanitization
└── utils/ # SQL classifier, parser, formatterZero runtime deps beyond
@modelcontextprotocol/sdkandzodStrict TypeScript — no
anyDynamic driver loading —
import('postgres')/import('mysql2/promise')/import('sql.js')at runtime< 60KB bundled via tsup
Factory pattern —
createServer(storageDir?, projectDir?)for isolated test instances
Available Tools
34 toolsconfig_getA
Muestra la configuracion actual del servidor (limites de rollback e historial).
Inputs: no named parameters.
config_setB
Modifica la configuracion del servidor. Los cambios se guardan permanentemente.
Inputs: max_history, max_rollbacks.
conn_createA
Crea una nueva conexion a base de datos (PostgreSQL, MySQL o SQLite). SIEMPRE pregunta al usuario a que grupo pertenece.
Inputs: name (required), type (required), group (required), dsn, +7 more.
conn_deleteA
Elimina una conexion. IMPORTANTE: pide confirmacion al usuario antes de llamar esta tool con confirm=true.
Inputs: name (required), confirm.
conn_duplicateA
Duplica una conexion existente con un nuevo nombre.
Inputs: name (required), new_name (required).
conn_exportA
Exporta conexiones a JSON. Por defecto enmascara passwords — usa include_secrets=true para incluirlos.
Inputs: name, include_secrets.
conn_getA
Obtiene los detalles de una conexion. El password se muestra enmascarado.
Inputs: name (required).
conn_group_add_scopeA
Añade un directorio (scope) a un grupo. Las conexiones del grupo seran accesibles desde ese directorio.
Inputs: group (required), scope.
conn_group_createA
Crea un nuevo grupo de conexiones. Luego añade scopes (directorios) con conn_group_add_scope.
Inputs: name (required).
conn_group_deleteA
Elimina un grupo. Las conexiones del grupo NO se eliminan pero quedaran huerfanas.
Inputs: name (required).
conn_group_listA
Lista todos los grupos con sus scopes, default y conexiones.
Inputs: no named parameters.
conn_group_remove_scopeB
Quita un directorio (scope) de un grupo.
Inputs: group (required), scope.
conn_importA
Importa conexiones desde un JSON exportado. Omite conexiones que ya existen (usa overwrite=true para reemplazar).
Inputs: json (required), overwrite.
conn_listA
Lista todas las conexiones disponibles e indica cual esta activa.
Inputs: no named parameters.
conn_project_clearB
Elimina la asociacion de conexion especifica de un proyecto.
Inputs: project (required).
conn_project_listB
Lista todos los proyectos con conexiones especificas asignadas.
Inputs: no named parameters.
conn_renameB
Renombra una conexion existente.
Inputs: name (required), new_name (required).
conn_setA
Actualiza un campo de una conexion existente.
Inputs: key (required), name (required), value (required).
conn_set_defaultA
Marca una conexion como el default de su grupo. El default se activa automaticamente al entrar al proyecto.
Inputs: name (required).
conn_set_groupB
Asigna o cambia el grupo de una conexion existente.
Inputs: group (required), connection (required).
conn_switchA
Cambia la conexion activa (de sesion). Para cambiar el default permanente usa conn_set_default.
Inputs: name (required), project.
conn_testA
Prueba la conexion a una base de datos. Ejecuta SELECT 1 y mide la latencia.
Inputs: name (required).
db_dumpB
Exporta la base de datos a un archivo SQL. Flujo conversacional: primero pregunta si exportar todas las tablas o personalizar, luego que contenido incluir (estructura, datos o todo).
Inputs: scope, schema, tables, content.
db_dump_listB
Lista los dumps disponibles en el proyecto actual.
Inputs: no named parameters.
db_restoreA
Restaura un dump SQL en la base de datos activa. IMPORTANTE: esta operacion es destructiva (DROP TABLE + CREATE TABLE). Pide confirmacion al usuario antes de ejecutar con confirm=true.
Inputs: confirm, filename.
execute_mutationA
Ejecuta una mutacion (INSERT, UPDATE, DELETE, DDL). Pide confirmacion y crea snapshot para rollback. El result se comprime por defecto — para mutations usa verbosity=minimal si solo te interesa affectedRows.
Inputs: sql (required), params, verbosity, only_columns, +2 more.
execute_queryA
Ejecuta una consulta de lectura (SELECT, SHOW, etc.). Inyecta LIMIT automaticamente. El result se comprime por defecto (verbosity=normal, celdas truncadas a 500 bytes) para ahorrar tokens; usa inspect_last_query con el call_id para recuperar el result completo sin re-ejecutar.
Inputs: sql (required), limit, params, verbosity, +4 more.
explain_queryB
Muestra el plan de ejecucion de una consulta (EXPLAIN). Sin ANALYZE por defecto.
Inputs: sql (required), params, analyze, verbosity, +3 more.
history_clearA
Limpia el historial de consultas. Opcionalmente solo las anteriores a una fecha.
Inputs: before.
history_listB
Lista el historial de consultas ejecutadas. Filtrable por tipo, conexion y estado.
Inputs: type, limit, success, connection.
inspect_last_queryA
Recupera el result completo (sin celdas truncadas, sin row cap) de un execute_query / execute_mutation / explain_query previo. Usa el call_id que aparece en la response comprimida. Sin call_id devuelve el más reciente. NO re-ejecuta el SQL.
Inputs: call_id.
rollback_applyA
Revierte una mutacion usando un rollback snapshot. IMPORTANTE: confirma con el usuario antes de ejecutar con confirm=true.
Inputs: id (required), confirm.
rollback_listA
Lista los rollback snapshots disponibles. Muestra las mutaciones recientes que se pueden revertir.
Inputs: limit, connection.
search_schemaA
Busca tablas/vistas en el schema de la base de datos. Soporta 3 niveles de detalle: names (solo nombres), summary (nombres + columnas), full (todo + FK + indices).
Inputs: schema, pattern, object_type, detail_level.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 34 tools
Most tools have a single clear responsibility, and the conn_* prefix cleanly separates connection management from querying, rollback, history, config, and dump operations. Some overlap remains around conn_set versus conn_set_group/conn_set_default, but descriptions are explicit enough to guide selection.
The dominant pattern is resource_action in snake_case (conn_create, conn_list, rollback_apply, config_set), which is predictable and readable. A minority of tools invert the order (execute_query, search_schema, inspect_last_query), creating a minor but noticeable inconsistency.
At 34 tools this server is heavy, exceeding the 25+ threshold where selection overhead becomes a real problem. The broad database domain justifies many operations, but several could be consolidated (e.g., conn_set variants, group/project management) to reduce cognitive load.
The tool surface covers the main database workflows: connection CRUD, grouping and scopes, query execution with rollback, history, config, schema search, and dump/restore. Minor gaps exist, such as no explicit group rename or direct project-assignment tool, but agents can work around them.
Maintenance
Related MCP Connectors
PostgreSQL, MySQL, and SQL Server in one session. 26 read-only MCP tools for AI agents.
Hosted PostgreSQL MCP server for Claude, ChatGPT and Cursor, with each action switched per account.
Text-to-SQL MCP server: read-only queries on PostgreSQL, MySQL and SQL Server with your real schema
Related MCP Servers
- AlicenseNot gradedqualityDmaintenanceA modular MCP server that enables interaction with multiple database types including PostgreSQL, MySQL, SQLite, Redis, MongoDB, and LDAP. It provides tools for executing queries, managing SQL commands, and exploring database schemas with configurable read-only security.13 npmMIT
- AlicenseNot gradedqualityDmaintenanceAn extensible MCP server for database operations that supports PostgreSQL for managing schemas, tables, data, and user permissions. It features automatic migration recording for DDL changes and integrates with various AI-powered editors like Cursor, Zed, and Claude Code.24 npm2MIT
- FlicenseNot gradedqualityDmaintenanceA secure multi-database MCP server supporting MySQL, PostgreSQL, and SQLite with read-only enforcement, SQL injection prevention, and tools for schema analysis, performance optimization, and visualization.4-
- AlicenseAqualityDmaintenanceA multi-database MCP server supporting MySQL, PostgreSQL, MongoDB, and SQLite with read-only and read-write query capabilities, schema inspection, and SSH tunneling, all without Docker.557 PyPI1MIT