DB
Model Context Protocol (MCP) server for secure database access. Query SQLite, PostgreSQL, MySQL, and MariaDB databases with AI assistants like Claude and Codex.
Ask AI about DB
Powered by Claude Β· Grounded in docs
I know everything about DB. Ask me about installation, configuration, usage, or troubleshooting.
0/500
Reviews
Documentation
MCP Database Server
A Model Context Protocol (MCP) server that provides secure database access for AI assistants and LLM-based tools. Query SQLite, PostgreSQL, MySQL, and MariaDB databases with built-in safety controls, query validation, and audit logging.
Features
- π Secure by Default: Read-only mode with granular permission controls
- ποΈ Multi-Database: Support for SQLite, PostgreSQL, MySQL, and MariaDB
- π‘οΈ SQL Validation: Automatic query validation and injection prevention
- π Table Allowlisting: Restrict access to specific tables
- β±οΈ Query Timeouts: Prevent long-running queries
- π Audit Logging: JSON-formatted operation logs
- π MCP Protocol: Native stdio transport for AI assistants
- π HTTP Mode: Optional REST API for legacy integrations
Supported MCP Clients
- Codex CLI
- Claude Desktop
- Cline (VS Code Extension)
- Any MCP-compatible client
Quick Start
Installation
The easiest way to use this MCP server is via npx (no installation required):
npx @amusphere/mcp-db
Configuration for MCP Clients
This server is designed to let AI assistants dynamically specify database connections via the db_url parameter. You can start the server without specifying a default database, and the AI will provide the connection string when needed.
Codex CLI
Add to your Codex configuration file (~/.codex/mcp.toml or similar):
[mcp_servers.mcp-db]
command = "npx"
args = ["-y", "@amusphere/mcp-db"]
The AI assistant will then specify the database URL in each tool call:
You: "Show me tables in my SQLite database at ./data/app.db"
AI: Uses db_url = "sqlite:///./data/app.db" in the tool call
Claude Desktop
Add to your Claude Desktop config (~/Library/Application Support/Claude/claude_desktop_config.json on macOS):
{
"mcpServers": {
"mcp-db": {
"command": "npx",
"args": ["-y", "@amusphere/mcp-db"]
}
}
}
Optional: Set a Default Database
If you want to set a default database (can still be overridden by the AI):
[mcp_servers.mcp-db]
command = "npx"
args = ["-y", "@amusphere/mcp-db", "--host", "sqlite:///./dev.db"]
Usage Examples
Recommended: Dynamic Database Selection
Start the server without a default database and let the AI specify the connection:
# Start server (AI will provide db_url in each request)
npx @amusphere/mcp-db
# With security controls
npx @amusphere/mcp-db --allow-writes --allowlist users,posts,comments
# With custom limits
npx @amusphere/mcp-db --max-rows 100 --timeout 30
User conversation examples:
- "Show tables in sqlite:///./dev.db"
- "Query the production database at postgresql://localhost/prod"
- "Compare user counts between ./dev.db and ./prod.db"
Alternative: Default Database
If you work primarily with one database, you can set a default (can still be overridden):
# SQLite default
npx @amusphere/mcp-db --host sqlite:///./dev.db
# PostgreSQL default
npx @amusphere/mcp-db --host postgresql://user:password@localhost:5432/mydb
# With allowlist for default database
npx @amusphere/mcp-db \
--host sqlite:///./dev.db \
--allowlist users,posts,comments
User conversation examples:
- "Show me the tables" (uses default database)
- "Now check the other database at ./other.db" (overrides default)
Local Development
Clone and build from source:
git clone https://github.com/amusphere/mcp-db.git
cd mcp-db
npm install
npm run build
npm start -- --host sqlite:///./dev.db
Development mode with hot-reload:
npm run dev
Testing
Comprehensive tests are available for all supported databases. See tests/README.md for detailed testing documentation.
Quick test commands:
# Run all tests (requires Docker)
npm test
# Run individual database tests
npm run test:sqlite # No Docker required
npm run test:postgres # Requires PostgreSQL container
npm run test:mysql # Requires MySQL container
npm run test:mariadb # Requires MariaDB container
Docker-based testing:
# Run all tests in Docker (recommended - auto cleanup)
npm run test:docker
# Or manually manage containers
docker compose up -d postgres mysql mariadb # Start databases
npm test # Run tests
docker compose down -v # Stop and clean up
HTTP Server Mode (Legacy)
For backwards compatibility with HTTP-based integrations:
npx @amusphere/mcp-db --host sqlite:///./dev.db --http-mode --port 8080
This exposes REST endpoints at http://localhost:8080/tools/* for non-MCP clients.
Configuration Reference
Command Line Arguments
| Argument | Description | Default |
|---|---|---|
--host <url> | Optional default database URL (can be overridden by AI via db_url parameter) | None |
--allow-writes | Enable INSERT/UPDATE/DELETE operations | false |
--allow-ddl | Enable CREATE/ALTER/DROP operations | false |
--allowlist <tables> | Comma-separated list of allowed tables (applies to all databases) | All tables |
--max-rows <number> | Maximum rows to return for SELECT queries | 500 |
--timeout <seconds> | Query timeout in seconds | 20 |
--http-mode | Run as HTTP server instead of MCP stdio | false |
--port <number> | Port for HTTP mode | 8080 |
--require-api-key | Require X-API-Key header (HTTP mode only) | false |
--api-key <value> | Expected API key value | - |
Note: The --host parameter is optional. If not specified, the AI must provide db_url in every tool call. If specified, it serves as a default that can be overridden per-request.
Database URL Formats
SQLite:
sqlite:///./path/to/database.db # Relative path
sqlite:////absolute/path/to/db.db # Absolute path
sqlite:///:memory: # In-memory database
PostgreSQL:
postgresql://username:password@host:port/database
postgresql://localhost/mydb # Local with defaults
MySQL:
mysql://username:password@host:port/database
mysql://root:password@localhost:3306/mydb
MariaDB:
mariadb://username:password@host:port/database
mariadb://root:password@localhost:3306/mydb
Note: MariaDB URLs are automatically converted to MySQL format internally.
Environment Variables
All command-line arguments can also be set via environment variables (command-line args take precedence):
| Environment Variable | Equivalent Argument |
|---|---|
DB_URL | --host |
ALLOW_WRITES | --allow-writes |
ALLOW_DDL | --allow-ddl |
ALLOWLIST_TABLES | --allowlist |
MAX_ROWS | --max-rows |
QUERY_TIMEOUT_SEC | --timeout |
PORT | --port |
REQUIRE_API_KEY | --require-api-key |
API_KEY | --api-key |
Example with environment variables:
export DB_URL="postgresql://user:pass@localhost:5432/mydb"
export ALLOW_WRITES="true"
export ALLOWLIST_TABLES="users,posts,comments"
npx @amusphere/mcp-db
Available MCP Tools
This server provides four MCP tools for database operations:
db_tables
List all tables in the database.
Parameters:
db_url(required/optional): Database URL. Required if no default--hostis set, otherwise optional to overrideschema(optional): Filter by schema (PostgreSQL only)
Example - Dynamic database selection:
{
"db_url": "sqlite:///./data/myapp.db"
}
Example - PostgreSQL with schema:
{
"db_url": "postgresql://user:pass@localhost:5432/mydb",
"schema": "public"
}
db_describe_table
Get column information for a specific table.
Parameters:
table(required): Table name to describedb_url(required/optional): Database URL. Required if no default--hostis set, otherwise optional to overrideschema(optional): Schema name (PostgreSQL only)
Example - Dynamic database selection:
{
"db_url": "sqlite:///./users.db",
"table": "users"
}
Example - With schema (PostgreSQL):
{
"db_url": "postgresql://localhost/mydb",
"table": "users",
"schema": "public"
}
db_execute
Execute a SQL statement with safety controls.
Parameters:
sql(required): SQL statement to executedb_url(required/optional): Database URL. Required if no default--hostis set, otherwise optional to overrideargs(optional): Named parameters (use:paramsyntax in SQL)allow_write(optional): Must betruefor write operationsrow_limit(optional): Override default max rows
Example - Dynamic query with parameters:
{
"db_url": "sqlite:///./data/app.db",
"sql": "SELECT * FROM users WHERE status = :status LIMIT 10",
"args": {
"status": "active"
}
}
Example - Cross-database query:
{
"db_url": "postgresql://user:pass@prod-server:5432/analytics",
"sql": "SELECT COUNT(*) as total FROM events WHERE date >= :start_date",
"args": {
"start_date": "2024-01-01"
}
}
db_explain
Get query execution plan and performance information using EXPLAIN.
Parameters:
sql(required): SQL query to analyze (typically a SELECT statement)db_url(required/optional): Database URL. Required if no default--hostis set, otherwise optional to overrideargs(optional): Named parameters (use:paramsyntax in SQL)analyze(optional): Run EXPLAIN ANALYZE to get actual execution statistics (executes the query)
Example - Basic query plan (SQLite):
{
"db_url": "sqlite:///./data/app.db",
"sql": "SELECT * FROM users WHERE email = :email",
"args": {
"email": "user@example.com"
}
}
Example - Performance analysis (PostgreSQL):
{
"db_url": "postgresql://localhost/mydb",
"sql": "SELECT u.name, COUNT(o.id) FROM users u JOIN orders o ON u.id = o.user_id GROUP BY u.name",
"analyze": true
}
Use cases:
- Identify slow queries and missing indexes
- Analyze JOIN performance and query optimization opportunities
- Compare execution plans between databases
- Verify query efficiency before deploying to production
How AI Assistants Use These Tools
This server is designed for dynamic database connections. AI assistants specify the database URL in each request, allowing you to work with multiple databases seamlessly.
Example Conversations
Working with SQLite:
You: "Connect to my SQLite database at ./data/users.db and show me all tables"
AI: Calls db_tables with db_url="sqlite:///./data/users.db"
Switching between databases:
You: "Now check the production database at /var/lib/app/prod.db"
AI: Calls db_tables with db_url="sqlite:////var/lib/app/prod.db"
You: "And also show me tables in the PostgreSQL analytics database"
AI: Calls db_tables with db_url="postgresql://user:pass@localhost:5432/analytics"
Natural language queries:
You: "How many users are in the SQLite database at ./users.db?"
AI: Calls db_execute with:
- db_url="sqlite:///./users.db"
- sql="SELECT COUNT(*) FROM users"
Supported Operations
When you connect an AI assistant (like Claude or Codex) to this MCP server, it can:
- Connect to any database dynamically: Specify different databases in natural language
- Explore database structure: "What tables are in database X?"
- Understand table schemas: "Show me the columns in the users table from database Y"
- Query data: "How many active users in the production database?"
- Analyze query performance: "Explain the execution plan for this query"
- Compare across databases: "Compare user counts between dev.db and prod.db"
- Optimize queries: "Find slow queries and suggest indexes"
The AI assistant will automatically extract the database path/URL from your request and use the appropriate tool with the correct db_url parameter.
Configuration Reference
- Default is READ-ONLY: Write and DDL operations require explicit enabling
- Use allowlists: Restrict access to specific tables with
--allowlist - Set query limits: Use
--max-rowsand--timeoutto prevent resource exhaustion - Named parameters: Always use
:paramsyntax to avoid SQL injection - Audit logging: All operations are logged to stderr in JSON format
Security Best Practices
- Default is READ-ONLY: Write and DDL operations require explicit enabling
- Use allowlists: Restrict access to specific tables with
--allowlist - Set query limits: Use
--max-rowsand--timeoutto prevent resource exhaustion - Named parameters: Always use
:paramsyntax to avoid SQL injection - Audit logging: All operations are logged to stderr in JSON format
- Separate credentials: Use read-only database users when possible
- Network security: For remote databases, use SSL/TLS connections
Audit Logs
All database operations are logged to stderr in JSON format:
{
"timestamp": "2024-01-17T10:30:45.123Z",
"tool": "db_execute",
"category": "read",
"duration_ms": 42,
"rowcount": 10,
"sql": "SELECT * FROM users LIMIT 10"
}
Troubleshooting
Connection Issues
SQLite file not found:
# Use absolute path
npx @amusphere/mcp-db --host sqlite:////absolute/path/to/db.db
# Or relative from current directory
npx @amusphere/mcp-db --host sqlite:///./relative/path/db.db
PostgreSQL connection refused:
- Verify the database is running:
pg_isready -h localhost - Check connection string format
- Ensure network access (firewall, security groups)
Permission Errors
"Write operations disabled":
# Enable writes (both server AND request must allow)
npx @amusphere/mcp-db --host sqlite:///./dev.db --allow-writes
"Table not allowlisted":
# Add tables to allowlist
npx @amusphere/mcp-db --host sqlite:///./dev.db --allowlist users,posts
Performance Issues
Queries timing out:
# Increase timeout
npx @amusphere/mcp-db --host sqlite:///./dev.db --timeout 60
Too much data returned:
# Reduce row limit
npx @amusphere/mcp-db --host sqlite:///./dev.db --max-rows 100
MCP Client Configuration
Server not appearing in Claude Desktop:
- Check config file location:
~/Library/Application Support/Claude/claude_desktop_config.json(macOS) - Verify JSON syntax is valid
- Restart Claude Desktop completely
Codex not connecting:
- Check
~/.codex/mcp.tomlsyntax - Ensure
npxis in PATH - Try running command manually first
Docker Deployment
Using Docker Compose
# Start the server with PostgreSQL
docker-compose up --build
# Access at http://localhost:8080 (HTTP mode)
Standalone Container
# Build
docker build -t mcp-db:latest .
# Run with SQLite (mount volume for persistence)
docker run --rm \
-v $(pwd)/data:/data \
-e DB_URL='sqlite:////data/mydb.db' \
mcp-db:latest
# Run with PostgreSQL
docker run --rm \
-e DB_URL='postgresql://user:pass@host:5432/db' \
-e ALLOW_WRITES=false \
mcp-db:latest
Contributing
Contributions are welcome! Please:
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
Development Setup
git clone https://github.com/amusphere/mcp-db.git
cd mcp-db
npm install
npm run dev # Start development server with hot-reload
npm run lint # Run ESLint
npm run typecheck # Run TypeScript type checking
npm test # Run all tests (requires Docker)
npm run test:docker # Run tests in Docker (recommended)
CI/CD Pipeline
All pull requests automatically run through our CI/CD pipeline:
- β Security Scanning: Gitleaks (secrets) and Trivy (vulnerabilities)
- β Code Quality: ESLint and TypeScript type checking
- β Build Verification: Transpile TypeScript to JavaScript
- β Comprehensive Testing: All database tests (SQLite, PostgreSQL, MySQL, MariaDB)
No additional setup required - all security scans use GitHub's built-in tokens.
License
MIT License - see LICENSE file for details
Support
- π Documentation
- π Issue Tracker
- π¬ Discussions
Related Projects
- Model Context Protocol - Official MCP documentation
- MCP Servers - Collection of MCP servers
- Claude Desktop - AI assistant with MCP support
Made with β€οΈ for the MCP community
