db-mcp
db-mcp is a comprehensive SQLite server for AI-driven database interactions, offering 122 specialized tools across analytics, search, and administration with dual backends and enterprise-grade security.
Database Operations: CRUD operations, schema management, indexing, views, and constraints with 8 core tools
Transaction Support: Full ACID compliance with begin, commit, rollback, and savepoints (7 tools, native backend)
JSON Processing: Full JSON/JSONB manipulation, schema analysis, and operations (23 tools)
Text Processing: Regex, fuzzy matching, phonetic search, and similarity analysis (17 tools)
Full-Text Search: FTS5 with BM25 ranking, search optimization, and index management (4 tools)
Statistical Analysis: Descriptive statistics, percentiles, regression, outlier detection (13-19 tools)
Window Functions: ROW_NUMBER, RANK, LAG/LEAD, running totals, moving averages (6 tools, native only)
Vector/Semantic Search: AI embeddings, cosine similarity, hybrid search (11 tools)
Geospatial Operations: Distance calculations, bounding boxes, SpatiaLite GIS capabilities (4-11 tools, native backend)
Virtual Tables: CSV, R-Tree, series, views, vacuum, and dbstat support (13 tools)
Administration: Backup, restore, PRAGMA operations, transaction management, health monitoring (33 tools)
Security: OAuth 2.1 authentication (RFC 9728/8414 compliant) with granular scope-based authorization (read, write, admin, database-specific, table-specific) and SQL injection prevention
Multiple Backends: WASM (102 tools, cross-platform) or Native (122 tools, full features) SQLite implementations
Tool Filtering: Configure tool sets with presets (starter, analytics, search, spatial, minimal, full) or custom groups to manage AI IDE limits
Resources: Read database metadata through 8 resources (schema, tables, indexes, views, health, configuration, insights)
AI Assistance: 10 prompts for schema explanation, query building, data analysis, optimization, migration scripts, debugging, and documentation
Flexible Deployment: Supports STDIO, HTTP/SSE (stateful/stateless), Docker, Node.js, and direct IDE integration (Cursor)
Extensions: Built-in FTS5, JSON1, R-Tree, plus loadable CSV and SpatiaLite extensions
Performance: Configurable metadata caching with automatic invalidation on DDL operations
Provides database operation tools for connecting to and managing MongoDB databases with support for OAuth 2.0 authentication and granular access control
Provides database operation tools for connecting to and managing MySQL databases with support for OAuth 2.0 authentication and granular access control
Provides database operation tools for connecting to and managing PostgreSQL databases with support for OAuth 2.0 authentication and granular access control
Provides database operation tools for connecting to and managing Redis databases with support for OAuth 2.0 authentication and granular access control
Provides database operation tools for connecting to and managing SQLite databases with support for OAuth 2.0 authentication and granular access control
Click on "Install 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., "@db-mcpshow me the top 10 customers by total orders from the PostgreSQL sales database"
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.
db-mcp (SQLite MCP Server)
SQLite MCP Server with 151 specialized tools, 11 data resources + 9 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
Feature | Description |
151 Specialized Tools | The most comprehensive SQLite MCP server available โ core CRUD, JSON/JSONB, FTS5 full-text search, statistical analysis, vector search, geospatial/SpatiaLite, introspection, migration, and admin |
20 Resources | 11 data resources (schema, tables, indexes, views, health, metadata, insights, audit, compile_options, pragma) + 9 help resources ( |
10 AI-Powered Prompts | Guided workflows for schema exploration, query building, data analysis, optimization, migration, debugging, and hybrid FTS5 + vector search |
Code Mode | Massive Token Savings: Execute complex, multi-step operations inside a V8 isolate sandbox with process-level isolation and hard timeouts. Instead of spending thousands of tokens on back-and-forth tool calls, Code Mode exposes all 151 capabilities locally, reducing token overhead by 70โ90% and supercharging AI agent reasoning |
Token-Optimized Payloads | Every tool response is designed for minimal token footprint with |
Dual SQLite Backends | WASM (sql.js) for zero-compilation portability, Native (better-sqlite3) for high-performance concurrent execution with full features including transactions, window functions, and SpatiaLite GIS |
OAuth 2.1 + Access Control | Enterprise-ready security with RFC 9728/8414 compliance, granular scopes ( |
Smart Tool Filtering | 10 tool groups + 7 shortcuts let you stay within IDE limits while exposing exactly what you need |
HTTP Streaming Transport | Streamable HTTP ( |
Production-Ready Security | SQL injection protection, parameterized queries, input validation, sandboxed code execution, HTTP body size enforcement, 7 security headers, server timeouts (slowloris protection), Retry-After rate limiting, |
Strict TypeScript | 100% type-safe codebase with strict mode, no |
Deterministic Error Handling | Every tool returns structured |
MCP 2025-03-26 Compliant | Full protocol support with tool safety hints, resource priorities, and progress notifications |
๐ Quick Start
Option 1: Docker (Recommended)
Pull and run instantly:
docker pull writenotenow/db-mcp:latestRun with volume mount:
docker run -i --rm \
-v $(pwd):/workspace \
writenotenow/db-mcp:latest \
--sqlite-native /workspace/database.dbOption 2: Node.js Installation
Clone the repository:
git clone https://github.com/neverinfamous/db-mcp.gitNavigate to directory:
cd db-mcpInstall dependencies:
npm installBuild the project:
npm run buildRun the server with Native backend (better-sqlite3 โ full features, requires Node.js native build):
node dist/cli.js --transport stdio --sqlite-native ./database.dbOr with WASM backend (sql.js โ cross-platform, no compilation required):
node dist/cli.js --transport stdio --sqlite ./database.dbBackend Choice: Use
--sqlite-nativefor full features (151 tools, transactions, window functions, SpatiaLite). Use--sqlitefor WASM mode (125 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 successfullyRun the test suite:
npm run testPrerequisites
โ 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, write methods return structured errors instead of executingHard timeouts โ worker termination if execution exceeds the configured limit
Full API access โ all 11 tool groups are available via
sqlite.*(e.g.,sqlite.core.readQuery(),sqlite.json.extract())
Set CODEMODE_ISOLATION=vm 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 151 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 11 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.
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
AI-enabled IDEs like Cursor have tool limits. With 151 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 (50 tools)
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.
Shortcut | WASM | Native | + Built-in | What's Included |
| 53 | 58 | +3 | Core, JSON, Text |
| 55 | 61 | +3 | Core, JSON, Stats |
| 40 | 45 | +3 | Core, Text, Vector |
| 30 | 37 | +3 | Core, Geo, Vector |
| 30 | 30 | +3 | Core, Introspection, Migration |
| 15 | 15 | +3 | Core only |
| 125 | 151 | +3 | Everything enabled |
Tool Groups (10 Available)
Note: +3 built-in tools (server_info, server_health, list_adapters) and +1 code mode are always included.
Group | WASM | Native | + Built-in | Description |
| 1 | 1 | +3 | Code Mode (sandboxed code execution) ๐ |
| 14 | 14 | +3 | Basic CRUD, schema, tables |
| 24 | 24 | +3 | JSON/JSONB operations, analysis |
| 14 | 19 | +3 | Text processing + FTS5 + advanced search |
| 16 | 22 | +3 | Statistical analysis (+ window funcs) |
| 11 | 11 | +3 | Embeddings, similarity search |
| 26 | 26 | +3 | Backup, restore, virtual tables, pragma |
| 0 | 8 | +3 | Transaction control and atomic execution |
| 4 | 11 | +3 | Geospatial + SpatiaLite (Native only) |
| 9 | 9 | +3 | FK graph, cascade sim, storage/index audit |
| 6 | 6 | +3 | Migration tracking, apply, rollback (opt-in) |
Syntax Reference
Prefix | Target | Example | Effect |
(none) | Shortcut |
| Whitelist Mode: Enable ONLY this shortcut |
(none) | Group |
| Whitelist Mode: Enable ONLY this group |
(none) | Tool |
| Whitelist Mode: Enable ONLY this tool |
| Group |
| Add tools from this group to current set |
| Group |
| Remove tools in this group from current set |
| Tool |
| Add one specific tool |
| Tool |
| Remove one specific tool |
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,fts5"
--tool-filter "starter,+stats"
--tool-filter "starter,-fts5"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)
Extension | Purpose | Status |
FTS5 | Full-text search with BM25 ranking | โ Always loaded |
JSON1 | JSON functions (json_extract, etc.) | โ Always loaded |
R-Tree | Spatial indexing for bounding boxes | โ Always loaded |
Loadable Extensions (require installation)
Extension | Purpose | Tools | CLI Flag |
CSV | CSV virtual tables | 2 |
|
SpatiaLite | Advanced GIS capabilities | 7 |
|
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.soOn Windows, use .dll:
export CSV_EXTENSION_PATH=/path/to/csv.dllOr use the CLI flag:
db-mcp --sqlite-native ./data.db --csvSpatiaLite Extension:
Install the library for your platform:
Linux (apt):
sudo apt install libspatialite-devmacOS (Homebrew):
brew install libspatialiteWindows: Download from https://www.gaia-gis.it/gaia-sins/
Set the environment variable:
export SPATIALITE_PATH=/path/to/mod_spatialite.soOr use the CLI flag:
db-mcp --sqlite-native ./data.db --spatialiteNote: 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:
Resource | URI | Description | Min Config |
|
| Full database schema |
|
|
| List all tables |
|
|
| Schema for a specific table |
|
|
| All indexes in the database |
|
|
| All views in the database |
|
|
| Database health and status | (read-only) |
|
| Database metadata and PRAGMAs |
|
|
| SQLite compile-time build options | (read-only) |
|
| Runtime PRAGMA config snapshot | (read-only) |
|
| Business insights memo (analysis) |
|
|
| Recent audit log + backup stats |
|
Help Resources (1 + up to 8)
On-demand tool reference documentation, filtered by --tool-filter:
Resource | URI | Description | When Registered |
|
| Gotchas, WASM vs Native, Code Mode API | Always |
|
| JSON/JSONB operations reference | When json group on |
|
| Text processing + FTS5 reference | When text group on |
|
| Statistical analysis + window functions reference | When stats group on |
|
| Vector/semantic search reference | When vector group on |
|
| Geospatial + SpatiaLite reference | When geo group on |
|
| Admin, backup, virtual tables reference | When admin group on |
|
| Transaction control reference | When transactions group on |
|
| Schema introspection, FK graph, diagnostics reference | When introspection group on |
|
| Migration tracking, apply, rollback reference | When migration group on |
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:
Prompt | Description |
| Explain database structure and relationships |
| Help construct SQL queries for common operations |
| Analyze data patterns and provide insights |
| Analyze and suggest database optimizations |
| Help create database migration scripts |
| Debug SQL queries that aren't working |
| Generate documentation for the database schema |
| Intelligent table analysis and summary |
| Hybrid FTS5 + vector search workflow |
| Interactive demo of MCP capabilities |
๐ง Configuration
Environment Variables
Variable | Default | Description |
|
| Host/IP to bind to (CLI: |
| โ | SQLite database path (CLI: |
| โ | Tool filter string (CLI: |
| โ | Simple bearer token for HTTP auth (CLI: |
|
| Enable OAuth 2.1 (CLI: |
| โ | Authorization server URL (CLI: |
| โ | Expected token audience (CLI: |
| โ | JWKS URI, auto-discovered if omitted (CLI: |
|
| Clock tolerance in seconds (CLI: |
|
| Log verbosity: |
|
| Schema cache TTL in ms (auto-invalidated on DDL operations) |
|
| Code Mode sandbox: |
|
| Max requests/minute per IP (HTTP transport) |
| โ | Custom path to CSV extension binary (native only) |
| โ | Custom path to SpatiaLite extension binary (native only) |
| โ | Audit log file path, or |
|
| Redact tool arguments from audit entries (CLI: |
|
| Also log read-scoped tool invocations (CLI: |
|
| Enable pre-mutation DDL snapshots (CLI: |
|
| Include sample data rows in snapshots (CLI: |
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: --auth-token <token> | --oauth-enabled --oauth-issuer <url> --oauth-audience <aud>
Database: --sqlite <path> | --sqlite-native <path>
Extensions: --csv --spatialite (native only)
Audit: --audit-log <path> --audit-redact --audit-reads --audit-backup --audit-backup-data
Server: --name <name> --version <ver> --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"
]
}
}
}Variants (modify the args array above):
Variant | Change |
WASM backend | Replace |
In-memory database | Replace the database path with |
Starter preset | Replace |
CSV extension | Add |
SpatiaLite | Add |
Linux/macOS | Use forward-slash Unix paths (e.g., |
Docker | Replace |
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.dbDocker:
docker run --rm -p 3000:3000 \
-v ./data:/app/data \
writenotenow/db-mcp:latest \
--transport http --port 3000 \
--sqlite-native /app/data/database.dbThe 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:
Method | Endpoint | Purpose |
|
| JSON-RPC requests (initialize, tools/list, etc.) |
|
| SSE stream for server notifications |
|
| Session termination |
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.dbIn 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:
Method | Endpoint | Purpose |
|
| Opens SSE stream, returns |
|
| Send JSON-RPC messages to the session |
Utility Endpoints
Method | Endpoint | Purpose |
|
| Health check (bypasses rate limiting, always available for monitoring) |
๐ Authentication
db-mcp supports two authentication mechanisms for HTTP transport:
Simple Bearer Token (--auth-token)
Lightweight authentication for development or single-tenant deployments:
node dist/cli.js --transport http --port 3000 --auth-token my-secret --sqlite-native ./database.db
# Or via environment variable
export MCP_AUTH_TOKEN=my-secret
node dist/cli.js --transport http --port 3000 --sqlite-native ./database.dbClients must include Authorization: Bearer my-secret on all requests. /health and / are exempt. Unauthenticated requests receive 401 with WWW-Authenticate: Bearer headers per RFC 6750.
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 \
--oauth-enabled \
--oauth-issuer http://localhost:8080/realms/db-mcp \
--oauth-audience db-mcp-serverAdditional flags:
--oauth-jwks-uri <url>(auto-discovered if omitted),--oauth-clock-tolerance <seconds>(default: 60).
OAuth Scopes
Access control is managed through OAuth scopes:
Scope | Description |
| Read-only access to all databases |
| Read and write access to all databases |
| Full administrative access |
| Access to specific database only |
| Access to specific table only |
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.
Per-tool scope enforcement: Scopes are enforced at the tool level โ each tool group maps to a required scope (read, write, or admin). 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.
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 are null/[].
HTTP without authentication: When using --transport http without enabling OAuth or --auth-token, all clients have full unrestricted access. Always enable authentication for production HTTP deployments. See SECURITY.md for details.
๐ 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: 11โ14M ops/sec โ Map-based lookup is effectively zero-cost
Auth scope checks: 6โ8M ops/sec โ OAuth middleware adds no measurable latency
Identifier validation: 6โ7M ops/sec โ SQL sanitization is near-instant
Schema cache hits: 4โ6M ops/sec โ metadata lookups avoid redundant queries
Debug log (filtered): 10โ11M ops/sec โ disabled log levels are true no-ops
Code Mode security: 1โ1.3M validations/sec for typical code, blocked patterns rejected in <1 ยตs
Sandbox execution: ~4.4โ4.9K executions/sec โ trivial code round-trips through V8 isolate in ~0.2 ms
npm run bench # Run all benchmarks
npm run bench:verbose # Verbose mode with detailed timingsBenchmark | What It Measures |
Handler Dispatch | Tool lookup, error construction, progress notification overhead |
Utilities | Identifier sanitization, WHERE clause validation, SQL validation |
Tool Filtering | Filter parsing, group lookups, meta-group catalog generation |
Schema Parsing | Zod schema validation for simple/complex/large payloads + failure paths |
Logger & Sanitization | Log call overhead, message sanitization, sensitive data redaction |
Transport & Auth | Token extraction, scope checking, error formatting, rate limiting |
Code Mode | Sandbox creation, pool lifecycle, security validation, execution |
Database Operations | PRAGMA ops, table metadata, query result processing, schema caching |
Resource & Prompts | URI matching, content assembly, prompt generation, tool indexing |
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.
Maintenance
Resources
Unclaimed servers have limited discoverability.
Looking for Admin?
If you are the server author, to access and configure the admin panel.
Latest Blog Posts
MCP directory API
We provide all the information about MCP servers via our MCP API.
curl -X GET 'https://glama.ai/api/mcp/v1/servers/neverinfamous/db-mcp'
If you have feedback or need assistance with the MCP directory API, please join our Discord server