🎩 You're Invited:Meet the Socket team at Black Hat in Las Vegas, August 3-6.RSVP
Sign In

@cocaxcode/database-mcp

Package Overview
Dependencies
Maintainers
1
Versions
30
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@cocaxcode/database-mcp

MCP server for database connectivity. Multi-DB (PostgreSQL, MySQL, SQLite), connection management, schema introspection, query execution with rollback, history, elicitation for destructive ops, and prepared statements. Zero config.

Source
npmnpm
Version
0.2.4
Version published
Weekly downloads
60
-48.28%
Maintainers
1
Weekly downloads
 
Created
Source

@cocaxcode/database-mcp

Your databases, one conversation away.
33 tools · PostgreSQL · MySQL · SQLite · Connection Groups · Rollback · Dump/Restore · Schema auto-discovery

npm version npm downloads License Node 33 tools

Overview · Just Talk to It · Connection Groups · Installation · Features · Tool Reference · Storage · Architecture

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.

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 restore

The 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 sessions

The 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@latest

Claude 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"]
    }
  }
}
Cursor / Windsurf

Add to .cursor/mcp.json or .windsurf/mcp.json in your project root:

{
  "mcpServers": {
    "database": {
      "command": "npx",
      "args": ["-y", "@cocaxcode/database-mcp@latest"]
    }
  }
}
VS Code

Add to .vscode/mcp.json:

{
  "servers": {
    "database": {
      "type": "stdio",
      "command": "npx",
      "args": ["-y", "@cocaxcode/database-mcp@latest"]
    }
  }
}
Codex CLI (OpenAI)
codex mcp add database -- npx -y @cocaxcode/database-mcp@latest

Or add to ~/.codex/config.toml:

[mcp_servers.database]
command = "npx"
args = ["-y", "@cocaxcode/database-mcp@latest"]
Gemini CLI (Google)

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

ProtectionHow it works
Read-only modeConnection-level enforcement — blocks all mutations
Confirmation requiredDestructive ops require explicit confirm: true
Auto LIMITRead queries get LIMIT 100 by default (respects existing LIMIT)
Password maskingCredentials shown as *** in conn_get output
Pre-mutation snapshotsEvery INSERT/UPDATE/DELETE captures row state for rollback
Auto gitignore.database-mcp/ added to .gitignore on first write

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 SQL
Original operationRollback generates
DELETE WHERE id = 5INSERT INTO ... VALUES (...)
UPDATE SET name = 'Bob'UPDATE SET name = 'Alice' (pre-update values)
INSERT INTO ...DELETE WHERE id = {new_id}
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)

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, executes

Generated 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 connections

Tool Reference

33 tools in 8 categories, plus 2 MCP Resources:

CategoryToolsCount
Connectionsconn_create conn_list conn_get conn_set conn_switch conn_rename conn_delete conn_duplicate conn_test conn_export conn_import11
Groupsconn_group_create conn_group_list conn_group_delete conn_group_add_scope conn_group_remove_scope conn_set_default conn_set_group7
Schemasearch_schema1
Queriesexecute_query execute_mutation explain_query3
Dumpdb_dump db_restore db_dump_list3
Rollbackrollback_list rollback_apply2
Historyhistory_list history_clear2
Configconfig_get config_set2

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 dumps

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

VariableDescriptionDefault
DATABASE_MCP_DIRGlobal storage directory~/.database-mcp/
DATABASE_MCP_MAX_ROLLBACKSMax rollback snapshots per project1000
DATABASE_MCP_MAX_HISTORYMax history entries per project5000
"Set max rollbacks to 2000"
"Set max history to 10000"

Priority: env var > saved config > default.

Warning: If you override DATABASE_MCP_DIR to a path inside a git repository, add .database-mcp/ to your .gitignore to 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, formatter
  • Zero runtime deps beyond @modelcontextprotocol/sdk and zod
  • Strict TypeScript — no any
  • Dynamic driver loadingimport('postgres') / import('mysql2/promise') / import('sql.js') at runtime
  • < 60KB bundled via tsup
  • Factory patterncreateServer(storageDir?, projectDir?) for isolated test instances

MIT · Built by cocaxcode

Keywords

mcp

FAQs

Package last updated on 29 Mar 2026

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts