db-mcp (SQLite MCP Server)
SQLite MCP Server with 170+ specialized tools, 11 data resources + 11 help resources, and 10 prompts, audit logging with DDL backup snapshots, HTTP/SSE Transport, OAuth 2.1 authentication, tool filtering, granular access control, and structured error handling with categorized, actionable responses. Available in WASM and better-sqlite3 variants.
🎯 What Sets Us Apart
🚀 Quick Start
Option 1: Docker (Recommended)
Pull and run instantly:
docker pull writenotenow/db-mcp:latest
Run with volume mount:
docker run -i --rm \
-v $(pwd):/workspace \
writenotenow/db-mcp:latest \
--sqlite-native /workspace/database.db
Option 2: Node.js Installation
Clone the repository:
git clone https://github.com/neverinfamous/db-mcp.git
Navigate to directory:
cd db-mcp
Install dependencies:
pnpm install
Build the project:
pnpm run build
Run the server with Native backend (better-sqlite3 — full features, requires Node.js native build):
node dist/cli.js --transport stdio --sqlite-native ./database.db
Or with WASM backend (sql.js — cross-platform, no compilation required):
node dist/cli.js --transport stdio --sqlite ./database.db
Backend Choice: Use
--sqlite-nativefor full features (181 MCP tools / 170 group tools, transactions, window functions, SpatiaLite). Use--sqlitefor WASM mode (154 MCP tools / 143 group tools, no native dependencies).
Verify It Works
node dist/cli.js --transport stdio --sqlite-native :memory:
Expected output:
[db-mcp] Starting MCP server...
[db-mcp] Registered adapter: Native SQLite Adapter (better-sqlite3) (sqlite:default)
[db-mcp] Server started successfully
Run the test suite:
pnpm run test
Prerequisites
- ✅ Docker installed and running (for Docker method)
- ✅ Node.js 24+ (LTS) (for local installation)
Code Mode: Maximum Efficiency
Code Mode (sqlite_execute_code) dramatically reduces token usage (70–90%) and is included by default in all presets.
Code executes in a worker-thread sandbox — a separate V8 isolate with its own memory space. All sqlite.* API calls are forwarded to the main thread via a MessagePort-based RPC bridge, where the actual database operations execute. This provides:
- Process-level isolation — user code runs in a separate V8 instance with enforced heap limits
- Readonly enforcement — when
readonly: true, stripped methods throw clear error messages listing available methods via Proxy traps - Hard timeouts — worker termination if execution exceeds the configured limit
- V8 code generation restrictions —
eval()andFunction()construction from strings disabled at the V8 engine level viacodeGeneration: { strings: false, wasm: false } - RPC allowlist — host-side validation prevents workers from invoking unauthorized API methods
- Full API access — all 10 tool groups are available via
sqlite.*(e.g.,sqlite.core.readQuery(),sqlite.json.extract())
Set CODEMODE_ISOLATION=vm with CODEMODE_ISOLATION_INSECURE=1 to fall back to the in-process vm module sandbox if needed.
⚡ Code Mode Only (Maximum Token Savings)
If you control your own setup, you can run with only Code Mode enabled — a single tool that provides access to all 180+ tools' worth of capability through the sqlite.* API:
{
"mcpServers": {
"db-mcp-sqlite": {
"command": "node",
"args": [
"/path/to/db-mcp/dist/cli.js",
"--transport",
"stdio",
"--sqlite-native",
"/path/to/database.db",
"--tool-filter",
"codemode"
]
}
}
}
This exposes just sqlite_execute_code plus built-in tools. The agent writes JavaScript against the typed sqlite.* SDK — composing queries, chaining operations across all 10 tool groups, and returning exactly the data it needs — in one execution. This mirrors the Code Mode pattern pioneered by Cloudflare for their entire API: fixed token cost regardless of how many capabilities exist.
[!TIP] Maximize Token Savings: Instruct your AI agent to prefer Code Mode over individual tool calls:
"When using db-mcp, prefer
sqlite_execute_code(Code Mode) for multi-step database operations to minimize token usage."
🎛️ Tool Filtering
[!IMPORTANT] AI-enabled IDEs like Cursor have tool limits. With 180+ tools in the native backend, you must use tool filtering to stay within limits. Use shortcuts or specify groups to enable only what you need.
Quick Start: Recommended Configurations
Starter (core + json + text)
If you prefer individual tool calls, starter provides Core + JSON + Text:
{
"args": ["--tool-filter", "starter"]
}
Custom Groups
Specify exactly the groups you need:
{
"args": ["--tool-filter", "core,json,stats"]
}
Shortcuts (Predefined Bundles)
Note: Native includes FTS5 (5), window functions (6), transactions (8), and SpatiaLite (7) not available in WASM.
Tool Groups (10 Available)
Note: +4 built-in tools (server_info, server_health, list_adapters, sqlite_execute_code) are injected into every group.
Syntax Reference
Custom Tool Selection
You can list individual tool names (without + prefix) to create a fully custom whitelist — only the tools you specify will be enabled:
Enable exactly 3 tools (whitelist mode):
--tool-filter "read_query,write_query,list_tables"
Mix tools from different groups:
--tool-filter "read_query,fuzzy_search,vector_search"
Combine with a shortcut or group:
--tool-filter "starter,+vector_search,+fuzzy_search"
This is useful for scripted or automated clients that need a minimal, precise set of capabilities.
Examples:
--tool-filter "starter"
--tool-filter "core,json,text,stats"
--tool-filter "starter,+stats"
--tool-filter "starter,-vector"
Legacy Syntax (still supported):
If you start with a negative filter (e.g., -vector,-geo), it assumes you want to start with all tools enabled and then subtract.
--tool-filter "-stats,-vector,-geo,-backup,-monitoring,-transactions,-window"
🔌 SQLite Extensions
SQLite supports both built-in extensions (compiled into better-sqlite3) and loadable extensions (require separate binaries).
Built-in Extensions (work out of box)
Loadable Extensions (require installation)
Installing Extensions
CSV Extension:
Download a precompiled binary or compile from source: https://www.sqlite.org/csv.html
Set the environment variable (Linux/macOS):
export CSV_EXTENSION_PATH=/path/to/csv.so
On Windows, use .dll:
export CSV_EXTENSION_PATH=/path/to/csv.dll
Or use the CLI flag:
db-mcp --sqlite-native ./data.db --csv
SpatiaLite Extension:
Install the library for your platform:
- Linux (apt):
sudo apt install libspatialite-dev - macOS (Homebrew):
brew install libspatialite - Windows: Download from https://www.gaia-gis.it/gaia-sins/
Set the environment variable:
export SPATIALITE_PATH=/path/to/mod_spatialite.so
Or use the CLI flag:
db-mcp --sqlite-native ./data.db --spatialite
Note: Extension binaries must match your platform and architecture. The server searches common paths automatically, or use the
CSV_EXTENSION_PATH/SPATIALITE_PATHenvironment variables for custom locations.
📁 Resources
Data Resources (11)
MCP resources provide read-only access to database metadata:
Help Resources (1 + up to 10)
On-demand tool reference documentation, filtered by --tool-filter:
Efficiency Tip: Data resources are always readable regardless of tool configuration. The "Min Config" column shows the smallest configuration that provides tools to act on what the resource exposes. Help resources are served on-demand — agents read them only when working with a specific tool group.
💬 Prompts (10)
MCP prompts provide AI-assisted database workflows:
🔧 Configuration
Environment Variables
Tip: Lower
METADATA_CACHE_TTL_MSfor development (e.g.,1000), or increase it for production with stable schemas (e.g.,60000= 1 min). Schema cache is automatically invalidated on DDL operations (CREATE/ALTER/DROP).
CLI Reference
db-mcp [options]
Transport: --transport <stdio|http|sse> --port <N> --server-host <host> --stateless
Auth: --oauth-enabled --oauth-issuer <url> --oauth-audience <aud>
Database: --sqlite <path> | --sqlite-native <path> [--encryption-key <key>]
Extensions: --csv --spatialite (native only)
Security: --allowed-io-roots <paths>
Audit: --audit-log <path> --audit-no-redact --audit-reads --audit-backup --audit-backup-data
Server: --name <name> --version <ver> --metrics-export <type> --tool-filter <filter>
CLI flags override environment variables. Run
node dist/cli.js --helpfor full details.
📚 MCP Client Configuration
Add to your ~/.cursor/mcp.json, Claude Desktop config, or equivalent:
{
"mcpServers": {
"db-mcp-sqlite": {
"command": "node",
"args": [
"C:/path/to/db-mcp/dist/cli.js",
"--transport",
"stdio",
"--sqlite-native",
"C:/path/to/your/database.db",
"--tool-filter",
"codemode"
]
}
}
}
[!TIP] Switching backends: The config above uses the Native backend (better-sqlite3, 181 MCP tools). To use the WASM backend (sql.js, 154 MCP tools, zero native dependencies), change
--sqlite-nativeto--sqlitein the args array. See the Backend Options table in DOCKER_README for feature differences.
Variants (modify the args array above):
See Tool Filtering to customize which tools are exposed.
🌐 HTTP/SSE Transport (Remote Access)
For remote access, web-based clients, or HTTP-compatible MCP hosts, use the HTTP transport:
node dist/cli.js \
--transport http \
--port 3000 \
--sqlite-native ./database.db \
--allowed-io-roots $(pwd)
Docker:
docker run --rm -p 3000:3000 \
-v ./data:/app/data \
writenotenow/db-mcp:latest \
--transport http --port 3000 \
--sqlite-native /app/data/database.db \
--allowed-io-roots /app/data
The server supports two MCP transport protocols simultaneously, enabling both modern and legacy clients to connect:
Streamable HTTP (Recommended)
Modern protocol (MCP 2025-03-26) — single endpoint, session-based:
Sessions are managed via the Mcp-Session-Id header.
Stateless Mode
For serverless/stateless deployments where sessions are not needed:
node dist/cli.js --transport http --port 3000 --stateless --sqlite-native ./database.db --allowed-io-roots $(pwd)
In stateless mode: GET /mcp returns 405, DELETE /mcp returns 204, /sse and /messages return 404. Each POST /mcp creates a fresh transport.
Legacy SSE (Backward Compatibility)
Legacy protocol (MCP 2024-11-05) — for clients like Python mcp.client.sse:
Utility Endpoints
🔐 Authentication
db-mcp secures the HTTP transport using strict OAuth 2.1 authentication:
OAuth 2.1 (Enterprise)
Full OAuth 2.1 with RFC 9728/8414 compliance for production multi-tenant deployments:
node dist/cli.js \
--transport http \
--port 3000 \
--sqlite-native ./database.db \
--allowed-io-roots $(pwd) \
--oauth-enabled \
--oauth-issuer http://localhost:8080/realms/db-mcp \
--oauth-audience db-mcp-server
Additional flags:
--oauth-jwks-uri <url>(auto-discovered if omitted),--oauth-clock-tolerance <seconds>(default: 60).
OAuth Scopes
Access control is managed through OAuth scopes:
RFC Compliance
This implementation follows:
- RFC 9728 — OAuth 2.1 Protected Resource Metadata
- RFC 8414 — OAuth 2.1 Authorization Server Metadata
- RFC 7591 — OAuth 2.1 Dynamic Client Registration
The server exposes metadata at /.well-known/oauth-protected-resource.
Note for Keycloak users: Add an Audience mapper to your client (Client → Client scopes → dedicated scope → Add mapper → Audience) to include the correct
audclaim in tokens.
[!NOTE] Per-tool scope enforcement: Scopes are enforced at the tool level — each tool group maps to a required scope (
read,write, oradmin). Unknown or unmapped tools default toadmin(fail-closed). When OAuth is enabled, every tool invocation checks the calling token's scopes before execution. When OAuth is not configured, scope checks are skipped entirely.
[!TIP] Audit identity integration: When OAuth is enabled alongside audit logging (
--audit-log), audit entries for write/admin tools automatically capture the authenticated user (claims.sub) and granted scopes. This provides a complete forensic trail linking every mutation to a specific identity. Without OAuth, these fields arenull/[].
[!WARNING] HTTP without authentication: When using
--transport httpwithout enabling OAuth, all clients have full unrestricted access. Always enable authentication for production HTTP deployments. See SECURITY.md for details.
🔐 Encryption at Rest (Native Only)
db-mcp supports transparent database encryption using SQLCipher via the better-sqlite3-multiple-ciphers driver. When encryption is enabled, the server automatically encrypts both your target database (if newly created) and the sidecar SystemDb audit log, ensuring your schema, queries, and results are protected at rest.
Important WASM Limitation: The WASM backend (sql.js) does not support encryption. If you supply an encryption key to the WASM backend, it will gracefully ignore it for the target database. However, this can cause conflicts if both a Native and WASM backend share the same --audit-log file (since the Native backend will encrypt the shared audit log, causing the WASM backend to crash when reading it). To avoid this in dual-backend setups, assign a separate audit log (e.g., --audit-log mcp-audit-wasm.db) for your WASM instance.
Configuring the Key:
You can provide the key via the --encryption-key CLI flag or the DB_ENCRYPTION_KEY environment variable.
- Strong Passphrase: A standard string. SQLCipher will automatically use PBKDF2 key derivation.
DB_ENCRYPTION_KEY="your-strong-passphrase-here" - Raw Hex Key (Best Performance): To skip PBKDF2 derivation overhead, provide an exact 256-bit raw hex key prefixed with
xand wrapped in single quotes:DB_ENCRYPTION_KEY="x'2DD29CA851E7B56E4697B0E1F08507293D761A05CE4D1B628663F411A8086D99'"
[!WARNING] Audit Log Compatibility: The
DB_ENCRYPTION_KEYenvironment variable applies globally and will cause the internalSystemDbto attempt to decrypt your audit log (--audit-log). If you have an existing unencrypted audit log, the server will fail to start withfile is not a database. To encrypt ONLY your target database (leaving the audit log unencrypted), use the--encryption-keyCLI flag instead of the global environment variable.
📊 Benchmarks
Performance benchmarks measure framework overhead on critical hot paths using Vitest bench (tinybench). The suite validates that framework plumbing stays negligible relative to actual database I/O:
- Tool dispatch: 6–14M ops/sec — Map-based lookup is effectively zero-cost
- Auth scope checks: 4–8M ops/sec — OAuth middleware adds no measurable latency
- Identifier validation: 4–7M ops/sec — SQL sanitization is near-instant
- Schema cache hits: 3–6M ops/sec — metadata lookups avoid redundant queries
- Debug log (filtered): 5–11M ops/sec — disabled log levels are true no-ops
- Code Mode security: ~0.2–1.3M validations/sec for typical code, blocked patterns rejected in 1-2 µs
- Sandbox execution: ~0.5–4.9K executions/sec — trivial code round-trips through V8 isolate in 0.2-1.5 ms
pnpm run bench # Run all benchmarks
pnpm run bench:verbose # Verbose mode with detailed timings
Contributing
Contributions are welcome! Please read our Contributing Guidelines before submitting a pull request.
Security
For security concerns, please see our Security Policy.
⚠️ Never commit credentials - Store secrets in
.env(gitignored)
License
This project is licensed under the MIT License - see the LICENSE file for details.
Code of Conduct
Please read our Code of Conduct before participating in this project.