DB Mcp (SQLite MCP Server) README

The full upstream README, mirrored for reference. Install config, tool schemas, adoption signals and our own overview live on the DB Mcp (SQLite MCP Server) listing page.

db-mcp (SQLite MCP Server)

SQLite MCP Server with a comprehensive suite of specialized tools, data resources, help resources, and prompts, audit logging with DDL backup snapshots, Streamable HTTP 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.

GitHub Release npm Docker Pulls License: MIT MCP CI E2E Coverage

Wiki β€’ Changelog


🎯 What Sets Us Apart

FeatureDescription
Specialized ToolsThe most comprehensive SQLite MCP server available β€” core CRUD, JSON/JSONB, FTS5 full-text search, statistical analysis, vector search, geospatial/SpatiaLite, introspection, migration, and admin
Deep ObservabilityBuilt-in Prometheus /metrics export, real-time sqlite://metrics MCP resource, historical persistence to a SystemDb sidecar, and a granular sqlite_audit_search tool for compliance and investigation
Dynamic ConfigurationFull YAML/JSON config file support (--config) with precedence rules, plus a sqlite_server_config tool for live runtime config updates (e.g., log levels) without server restarts
Advanced Query & SearchOffset-encoded cursor pagination (cursor / nextCursor), faceted search aggregation, and sqlite_hybrid_search orchestrating FTS5 + Vector similarity with Reciprocal Rank Fusion (RRF) in a single tool call
AI Index Recommendationssqlite_index_audit automatically analyzes EXPLAIN QUERY PLAN responses to suggest optimized composite and partial indexes based on workload patterns
Real-time SubscriptionsNative resources/subscribe support pushing event-driven notifications for sqlite://schema DDL changes and periodic sqlite://health updates directly to clients
25 Resources11 data resources (schema, tables, table_schema, indexes, views, health, meta, audit, metrics, compile_options, pragma) + 14 help resources (sqlite://help + per-group reference) β€” filtered by --tool-filter
10 AI-Powered PromptsGuided workflows for schema exploration, query building, data analysis, optimization, migration, debugging, and hybrid FTS5 + vector search
Code ModeMassive 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 177 group capabilities locally, reducing token overhead by 70–90% and supercharging AI agent reasoning
Token-Optimized PayloadsTool responses are designed for minimal token footprint, with _meta.tokenEstimate embedded on adapter tool, resource, and audit list/search responses so agents know their token cost. Tools include compact, nodesOnly, maxOutliers, minSeverity, and maxInvalid parameters where applicable β€” letting agents control response size without losing data access
Dual SQLite BackendsWASM (sql.js) for zero-compilation portability, Native (better-sqlite3) for high-performance concurrent execution with full features including transactions, FTS5, and SpatiaLite GIS (window functions work on both backends)
OAuth 2.1 + Access ControlEnterprise-ready security with RFC 9728/8414 compliance, granular scopes (full, read, write, admin), and Keycloak integration
Smart Tool Filtering14 tool groups (13 domain groups + Code Mode) + 7 shortcuts let you stay within IDE limits while exposing exactly what you need
HTTP Streaming TransportStreamable HTTP (/mcp) with security headers, rate limiting, health check, and stateless mode for serverless
Production-Ready SecuritySQL injection protection (parameterized queries + Unicode-normalized WHERE clause validation), sandboxed code execution (isolated V8 heaps, Acorn AST & 31 blocked-pattern validation, Proxy nullified, RPC allowlist), CORS deny-all default, fail-closed scope enforcement, JWT claims sanitization, 7 security headers, maxBodyBytes body limits (HttpTransportConfig), rate limiting with Retry-After, slowloris timeouts, trustedProxyIps (HttpTransportConfig), opt-in HSTS, non-root Docker, and build provenance
Encryption at RestNative SQLCipher support via --encryption-key or DB_ENCRYPTION_KEY (required as an env var to also encrypt the sidecar SystemDb audit log). Dynamically loads better-sqlite3-multiple-ciphers to protect sensitive queries from leaking
Strict TypeScript100% type-safe codebase with strict mode, no any types, automated Vitest unit/integration suites, and a comprehensive Playwright E2E suite
Deterministic Error HandlingEvery tool returns structured {success, error, code, category, suggestion, recoverable} responses β€” no raw exceptions, no silent failures. Agents get enriched error context with actionable suggestions instead of cryptic SQLite codes
MCP 2025-11-25 CompliantFull protocol support with tool safety hints (sensitiveHint, readOnlyHint), resource priorities, and progress notifications

πŸ—οΈ Architecture

mermaid
flowchart LR
    Client["MCP Client (stdio / Streamable HTTP)"] --> Auth["Auth & Security (OAuth 2.1 / Bearer / Headers)"]
    Auth --> Filter["Tool Filtering & Code Mode (isolated-vm V8 Sandbox)"]
    Filter --> Native["Native SQLite (better-sqlite3 + SQLCipher / FTS5 / SpatiaLite)"]
    Filter --> WASM["WASM SQLite (sql.js, zero native deps)"]
    Filter --> Sidecar["SystemDb Sidecar (Audit Log, Snapshots & Metrics)"]

πŸš€ Quick Start

Option 1: Docker (Recommended)

Pull and run instantly:

Terminal
docker pull writenotenow/db-mcp:latest

Run with volume mount:

Terminal
docker run -i --rm \
  -e FORCE_IN_MEMORY_RATE_LIMIT=true \
  -v ./data:/app/data \
  writenotenow/db-mcp:latest \
  --sqlite-native /app/data/database.db

Option 2: Node.js Installation

Clone the repository:

bash
git clone https://github.com/neverinfamous/db-mcp.git

Navigate to directory:

bash
cd db-mcp

Install dependencies:

bash
pnpm install

Build the project:

bash
pnpm run build

Run the server with Native backend (better-sqlite3 β€” full features, requires Node.js native build):

bash
node dist/cli.js --transport stdio --sqlite-native ./database.db

Or with WASM backend (sql.js β€” cross-platform, no compilation required):

bash
node dist/cli.js --transport stdio --sqlite ./database.db

Backend Choice: Use --sqlite-native for full native features (transactions, FTS5, SpatiaLite, native SQL window functions). Use --sqlite for WASM mode (no native dependencies; includes SQLite OVER (...) window functions via sqlite_stats_window*).

Verify It Works

bash
node dist/cli.js --transport stdio --sqlite-native :memory:

Expected output:

Code
[<timestamp>] [INFO] [SERVER] MCP Server initialized
...
[<timestamp>] [INFO] [SERVER] Registered adapter: Native SQLite Adapter (better-sqlite3) (sqlite::memory:)
[<timestamp>] [INFO] [SERVER] db-mcp server started (stdio transport)

Run the test suite:

bash
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 native V8 isolate sandbox (isolated-vm) with its own isolated heap. All sqlite.* API calls cross the isolate boundary via C++ ivm.Reference closure wrappers into the host adapter. This provides:

  • Process-level V8 isolation β€” user code runs in a dedicated native V8 isolate with enforced heap limits
  • Readonly enforcement β€” when readonly: true, mutating methods and aliases return structured CODEMODE_READONLY_VIOLATION responses ({ success: false, code: "CODEMODE_READONLY_VIOLATION" }) without executing mutations
  • Hard timeouts β€” C++ isolate synchronous CPU timeout plus host wall-clock promise guard (timeoutMs)
  • Zero host global leakage β€” native Node.js globals (process, require, filesystem/network APIs) do not exist inside the isolate, and dynamic code evaluation (eval/Function) is blocked by Acorn AST + static pattern checks
  • RPC allowlist β€” host-side validation prevents sandboxed scripts from invoking unauthorized API methods
  • Full API access β€” all enabled tool groups are available via sqlite.* (e.g., sqlite.core.readQuery(), sqlite.json.extract())

⚑ 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 its full capability through the sqlite.* API:

config.json
{
  "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 13 domain 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 an extensive toolset 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 + schema + json)

If you prefer individual tool calls, starter provides Core, Schema, and JSON:

config.json
{
  "args": ["--tool-filter", "starter"]
}

Custom Groups

Specify exactly the groups you need:

config.json
{
  "args": ["--tool-filter", "core,json,stats"]
}

Shortcuts (Predefined Bundles)

Note: Native includes FTS5 (5), transactions (8), and SpatiaLite (7) not available in WASM. Window functions (6) work on both backends (sqlite_window_* on Native; sqlite_stats_window* on WASM).

ShortcutWASMNative+ Built-inWhat's Included
starter5454+4Core, Schema, JSON
analytics3333+4Core, Stats
search3944+4Core, Text, Vector
spatial2835+4Core, Geo, Vector
dev-schema4545+4Core, Schema, Introspection, Migration
minimal1313+4Core only
full157177+4 (+7*)Everything enabled (*7 server/audit tools: sqlite_server_config with admin, sqlite_audit_search with --audit-log, 5 backup tools with --audit-log --audit-backup)

Tool Groups (14 Available: 13 Domain + Code Mode)

Note: +4 built-in tools (server_info, server_health, list_adapters, sqlite_execute_code) are injected into every group.

GroupWASMNative+ Built-inDescription
core1313+4Basic CRUD, datetime, OCC versioning
schema1616+4Tables, indexes, triggers, views, DDL
json2525+4JSON/JSONB operations, analysis
text1520+4Text processing + FTS5 + advanced search
stats2020+4Descriptive, inference, window functions
performance66+4Query plans, bloat, anomaly & schema risks
monitoring55+4Locks, WAL size, memory, compile options
vector1111+4Vector storage, similarity search
admin2626+4 (+7*)DB maintenance, backup, virtual tables (*7 audit/admin)
transactions08+4Commit, rollback, savepoints (Native only)
geo411+4Geospatial + SpatiaLite (Native only)
introspection1010+4Schema mapping, FK graph, analysis
migration66+4Schema migration tracking (opt-in)
codemode11+3Sandboxed V8 sqlite.* JS execution

Syntax Reference

PrefixTargetExampleEffect
(none)ShortcutstarterWhitelist Mode: Enable ONLY this shortcut
(none)GroupcoreWhitelist Mode: Enable ONLY this group
(none)Toolread_queryWhitelist Mode: Enable only this tool (+ codemode & 3 built-ins)
+Group+vectorAdd tools from this group to current set
-Group-adminRemove tools in this group from current set
+Tool+fuzzy_matchAdd one specific tool
-Tool-drop_tableRemove one specific tool

Custom Tool Selection

You can list individual tool names (without + prefix) to create a custom whitelist β€” note that sqlite_execute_code (codemode group) remains enabled implicitly unless excluded with -codemode, and the 3 built-in tools (server_info, server_health, list_adapters) are always registered:

Enable 3 selected tools (plus implicit codemode and 3 built-ins; add ,-codemode to exclude Code Mode):

bash
--tool-filter "read_query,write_query,list_tables"

Mix tools from different groups:

bash
--tool-filter "read_query,fuzzy_match,vector_search"

Combine with a shortcut or group:

bash
--tool-filter "starter,+vector_search,+fuzzy_match"

This is useful for scripted or automated clients that need a minimal, precise set of capabilities.

Examples:

bash
--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.

bash
--tool-filter "-stats,-vector,-geo,-admin,-monitoring,-transactions"

πŸ”Œ 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)

ExtensionPurposeStatus
FTS5Full-text search with BM25 rankingβœ… Loaded (Native only)
JSON1JSON functions (json_extract, etc.)βœ… Always loaded
R-TreeSpatial indexing for bounding boxesβœ… Loaded (Native only)

Loadable Extensions (require installation)

ExtensionPurposeToolsCLI Flag
CSVCSV virtual tables2--csv
SpatiaLiteAdvanced GIS capabilities7--spatialite

Installing Extensions

CSV Extension:

Download a precompiled binary or compile from source: https://www.sqlite.org/csv.html

Set the environment variable (Linux/macOS):

server.ts
export CSV_EXTENSION_PATH=/path/to/csv.so

On Windows, use .dll:

server.ts
export CSV_EXTENSION_PATH=/path/to/csv.dll

Or use the CLI flag:

bash
db-mcp --sqlite-native ./data.db --csv

SpatiaLite Extension:

Install the library for your platform:

Set the environment variable:

server.ts
export SPATIALITE_PATH=/path/to/mod_spatialite.so

Or use the CLI flag:

bash
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_PATH environment variables for custom locations.

πŸ“ Resources

Data Resources (11)

MCP resources provide read-only access to database metadata:

ResourceURIDescriptionMin Config
sqlite_schemasqlite://schemaFull database schemaminimal
sqlite_tablessqlite://tablesList all tablesminimal
sqlite_table_schemasqlite://table/{tableName}/schemaSchema for a specific tableminimal
sqlite_indexessqlite://indexesAll indexes in the databaseminimal
sqlite_viewssqlite://viewsAll views in the databasecore,schema
sqlite_healthsqlite://healthDatabase health and status(read-only)
sqlite_metasqlite://metaDatabase metadata and PRAGMAscore,admin
sqlite_compile_optionssqlite://compile_optionsSQLite compile-time build options(read-only)
sqlite_pragmasqlite://pragmaRuntime PRAGMA config snapshot(read-only)
sqlite_auditsqlite://auditRecent audit log + backup stats--audit-log
sqlite_metricssqlite://metricsInternal server metrics(read-only)

Help Resources (1 + up to 13)

On-demand tool reference documentation, filtered by --tool-filter:

ResourceURIDescriptionWhen Registered
sqlite_helpsqlite://helpGotchas, WASM vs Native, Code Mode APIAlways
sqlite_help_coresqlite://help/coreCore CRUD and table operations referenceWhen core group on
sqlite_help_jsonsqlite://help/jsonJSON/JSONB operations referenceWhen json group on
sqlite_help_textsqlite://help/textText processing + FTS5 referenceWhen text group on
sqlite_help_statssqlite://help/statsStatistical analysis + window functions referenceWhen stats group on
sqlite_help_vectorsqlite://help/vectorVector/semantic search referenceWhen vector group on
sqlite_help_geosqlite://help/geoGeospatial + SpatiaLite referenceWhen geo group on
sqlite_help_adminsqlite://help/adminAdmin, backup, virtual tables referenceWhen admin group on
sqlite_help_transactionssqlite://help/transactionsTransaction control referenceWhen transactions group on
sqlite_help_introspectionsqlite://help/introspectionSchema introspection, FK graph, diagnostics referenceWhen introspection group on
sqlite_help_migrationsqlite://help/migrationMigration tracking, apply, rollback referenceWhen migration group on
sqlite_help_schemasqlite://help/schemaSchema inspection and DDL referenceWhen schema group on
sqlite_help_performancesqlite://help/performanceQuery plans, indexing, and tuning referenceWhen performance group on
sqlite_help_monitoringsqlite://help/monitoringHealth, locks, and runtime metrics referenceWhen monitoring 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:

PromptDescription
sqlite_explain_schemaExplain database structure and relationships
sqlite_query_builderHelp construct SQL queries for common operations
sqlite_data_analysisAnalyze data patterns and provide insights
sqlite_optimizationAnalyze and suggest database optimizations
sqlite_migrationHelp create database migration scripts
sqlite_debug_queryDebug SQL queries that aren't working
sqlite_documentationGenerate documentation for the database schema
sqlite_summarize_tableIntelligent table analysis and summary
sqlite_hybrid_search_workflowHybrid FTS5 + vector search workflow
sqlite_demoInteractive demo of MCP capabilities

πŸ“š Agent Skills (SEP-2640)

db-mcp bundles three skills in skills/ (sqlite, opentelemetry, and datadog) and serves them read-only over the MCP skills protocol (SEP-2640): compatible clients can call skills/list / skills/get or read skill://<name>/SKILL.md resources directly. Over HTTP, skill requests require standard authentication plus read scope under OAuth. See skills/README.md for manual installation instructions.

πŸ”§ Configuration

Environment Variables

VariableDefaultDescription
MCP_HOST127.0.0.1Host/IP to bind to (0.0.0.0 in Docker) (CLI: --server-host)
SQLITE_DATABASEβ€”SQLite database path β€” WASM backend by default (CLI: --sqlite; use --sqlite-native or config file for native)
DB_ENCRYPTION_KEYβ€”SQLCipher encryption key (Native only) (CLI: --encryption-key)
DB_MCP_TOOL_FILTERβ€”Tool filter string (CLI: --tool-filter)
METRICS_EXPORTβ€”Export Prometheus /metrics on HTTP or stdio --port (CLI: --metrics-export)
OAUTH_ENABLEDfalseEnable OAuth 2.1 (CLI: --oauth-enabled)
OAUTH_ISSUERβ€”Authorization server URL (CLI: --oauth-issuer)
OAUTH_AUDIENCEβ€”Expected token audience (CLI: --oauth-audience)
OAUTH_JWKS_URIβ€”JWKS URI, auto-discovered if omitted (CLI: --oauth-jwks-uri)
OAUTH_CLOCK_TOLERANCE30Clock tolerance in seconds (CLI: --oauth-clock-tolerance)
MCP_ENABLE_HSTSfalseEnable HSTS header (CLI: --enable-hsts)
NO_AUTH_ENFORCEMENTfalseExplicitly bypass auth enforcement for HTTP (CLI: --no-auth-enforcement)
MCP_ALLOW_INSECURE_NON_LOOPBACKfalseDev-only opt-in to bind unauthenticated HTTP to non-loopback hosts (e.g., 0.0.0.0)
MCP_ALLOW_UNAUTHENTICATED_METRICSfalseOpt-in required to bind unauthenticated stdio /metrics listener to non-loopback hosts
LOG_LEVELinfoLog verbosity: debug, info, notice, warning, error, critical, alert, emergency
METADATA_CACHE_TTL_MS30000Schema cache TTL in ms (auto-invalidated on DDL operations)
MCP_RATE_LIMIT_MAX100Max requests/minute per IP (HTTP transport)
MCP_CODEMODE_RATE_LIMIT60Max sqlite_execute_code executions per minute per client
REDIS_URLβ€”Redis connection URL for distributed HTTP & Code Mode rate limiting in production
FORCE_IN_MEMORY_RATE_LIMITfalseExplicitly allow in-memory HTTP & Code Mode rate limiting in production when REDIS_URL is unset
ALLOWED_HOSTSβ€”Comma-separated additional Host headers allowed for HTTP & stdio /metrics
CSV_EXTENSION_PATHβ€”Custom path to CSV extension binary (native only)
SPATIALITE_PATHβ€”Custom path to SpatiaLite extension binary (native only)
ALLOWED_IO_ROOTSβ€”JSON array or comma-separated list of absolute paths allowed for IO operations
MCP_AUTH_TOKENβ€”Static bearer token for HTTP /mcp & /metrics auth (keeps /health public)
ALLOW_HTTP_JWKSfalseAllow plain HTTP for non-loopback OAuth JWKS URIs (testing only)
ALLOW_HTTP_DISCOVERYfalseAllow plain HTTP for non-loopback OAuth issuer discovery (testing only)
AUDIT_LOGβ€”SQLite SystemDb file path, or stderr for JSONL (CLI: --audit-log)
AUDIT_REDACTtrueRedact tool arguments from audit entries (CLI: --audit-no-redact to disable)
AUDIT_READSfalseAlso log read-scoped tool invocations (CLI: --audit-reads)
AUDIT_BACKUPfalseEnable pre-mutation DDL snapshots (CLI: --audit-backup)
AUDIT_BACKUP_DATAfalseInclude sample data rows in snapshots (CLI: --audit-backup-data)

Tip: Lower METADATA_CACHE_TTL_MS for 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

server.ts
db-mcp <command> [options]

Commands:
  start [options]      Start the db-mcp server (default command)
  init [options]       Interactive wizard to initialize db-mcp.config.json
  doctor [options]     Validate current configuration and environment
  auth                 Authentication utilities
  config               Configuration management utilities

start command options:
  Transport:    -t, --transport <stdio|http>  -p, --port <N>  --server-host <host>  --stateless
  Auth:         -o, --oauth-enabled --oauth-issuer <url> --oauth-audience <aud> --oauth-jwks-uri <url> --oauth-clock-tolerance <sec> --enable-hsts --no-auth-enforcement
  Database:     --sqlite <path>  |  --sqlite-native <path>  [--encryption-key <key>]  -c, --config <path>
  Extensions:   --csv  --spatialite                         (native only)
  Security:     --allowed-io-roots <paths>
  Audit:        --audit-log <path>  --audit-redact  --audit-no-redact  --audit-reads  --audit-backup  --audit-backup-data
  Server:       --server-name <name>  --server-version <ver>  --metrics-export <prometheus>  --tool-filter <filter>  --dry-run
  Global/Util:  --debug  --verbose  -q, --quiet  --log-level <level>  --json  (subcommands: init, doctor|check, auth generate|status, config dump|validate|set|init)

CLI flags override environment variables. Run node dist/cli.js --help for full details.

πŸ“š MCP Client Configuration

Add to your ~/.cursor/mcp.json, Claude Desktop config, or equivalent:

config.json
{
  "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, 188 MCP tools / 177 group tools). To use the WASM backend (sql.js, 168 MCP tools / 157 group tools, zero native dependencies), change --sqlite-native to --sqlite in the args array. See the Backend Options table in DOCKER_README for feature differences.

Variants (modify the args array above):

VariantChange
WASM backendReplace --sqlite-native with --sqlite
In-memory databaseReplace the database path with :memory:
Starter presetReplace "codemode" with "starter" for individual tool calls
CSV extensionAdd "--csv" before "--tool-filter" (native only)
SpatiaLiteAdd "--spatialite" and set env: { "SPATIALITE_PATH": "/path/to/mod_spatialite" } (native only)
Linux/macOSUse forward-slash Unix paths (e.g., /path/to/db-mcp/dist/cli.js)
DockerReplace "command": "node" with "command": "docker", replace "C:/path/to/db-mcp/dist/cli.js" with "run", "-i", "--rm", "-e", "FORCE_IN_MEMORY_RATE_LIMIT=true", "-v", "./data:/app/data", "writenotenow/db-mcp:latest", and change "C:/path/to/your/database.db" to "/app/data/database.db"

See Tool Filtering to customize which tools are exposed.

🌐 Streamable HTTP Transport (Remote Access)

For remote access, web-based clients, or HTTP-compatible MCP hosts, use the HTTP transport (pass --oauth-enabled, MCP_AUTH_TOKEN, or --no-auth-enforcement for local dev):

bash
node dist/cli.js \
  --transport http \
  --port 3000 \
  --no-auth-enforcement \
  --sqlite-native ./database.db \
  --allowed-io-roots $(pwd)

Docker:

Terminal
docker run --rm -p 3000:3000 \
  -e MCP_AUTH_TOKEN=replace-me \
  -e FORCE_IN_MEMORY_RATE_LIMIT=true \
  -v ./data:/app/data \
  writenotenow/db-mcp:latest \
  --transport http --port 3000 --server-host 0.0.0.0 \
  --sqlite-native /app/data/database.db \
  --allowed-io-roots /app/data

Streamable HTTP (Recommended)

Modern protocol (MCP 2025-03-26) β€” single endpoint, session-based:

MethodEndpointPurpose
POST/mcpJSON-RPC requests (initialize, tools/list, etc.)
GET/mcpSSE stream for server notifications
DELETE/mcpSession termination

Sessions are managed via the Mcp-Session-Id header.

Stateless Mode

For serverless/stateless deployments where sessions are not needed:

bash
node dist/cli.js --transport http --port 3000 --stateless --no-auth-enforcement --sqlite-native ./database.db --allowed-io-roots $(pwd)

In stateless mode: GET /mcp returns 405, DELETE /mcp returns 204. Each POST /mcp creates a fresh transport.

Utility Endpoints

MethodEndpointPurpose
GET/healthHealth check (bypasses rate limiting, always available for monitoring)
GET/metricsPrometheus exposition endpoint (bypasses rate limiting; requires --metrics-export prometheus and read scope when auth is active)
GET/Server metadata and available endpoint index

πŸ” 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:

bash
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: 30).

OAuth Scopes

Access control is managed through OAuth scopes:

ScopeDescription
fullUnrestricted access to all operations
readRead-only access to all databases
writeRead and write access to all databases
adminFull administrative access

RFC Compliance

This implementation follows:

  • RFC 9728 β€” OAuth 2.1 Protected Resource Metadata
  • RFC 8414 β€” OAuth 2.1 Authorization Server Metadata
  • RFC 7591 β€” Authorization server registration_endpoint metadata discovery and TypeScript types (no client registration endpoint or flow is implemented)

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 aud claim in tokens. Reviewed against Keycloak 26.x; in dev mode on Keycloak 26.6+ set Keycloak's http-host option to 0.0.0.0 if running in a container.

  • Per-tool scope enforcement: Scopes are enforced at the tool level β€” each tool group maps to a required scope (read, write, or admin). Unknown or unmapped tools default to admin (fail-closed). When OAuth is enabled, every tool invocation checks the calling token's scopes before execution; when MCP_AUTH_TOKEN is used without OAuth, authenticated requests receive ["admin"] scope. When neither OAuth nor MCP_AUTH_TOKEN is configured (--no-auth-enforcement), scope checks are skipped.
  • 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/[].

[!WARNING] HTTP without authentication: HTTP transport fails closed (AUTH_REQUIRED) unless --oauth-enabled, MCP_AUTH_TOKEN, or --no-auth-enforcement is configured. When --no-auth-enforcement is set without OAuth or MCP_AUTH_TOKEN, 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. Pass --encryption-key or DB_ENCRYPTION_KEY to encrypt the target database (if newly created); set the DB_ENCRYPTION_KEY environment variable to also encrypt 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 SQLCipher encryption. Passing --encryption-key or setting the DB_ENCRYPTION_KEY environment variable when configuring a WASM (--sqlite) database fails startup (FATAL). In dual-backend setups (running both Native and WASM instances), keep DB_ENCRYPTION_KEY unset for the WASM instance and assign a separate audit log (e.g., --audit-log mcp-audit-wasm.db) so it never reads a SQLCipher-encrypted audit database written by the Native instance.

Configuring the Key: Provide either a strong passphrase (derived via KDF using PRAGMA key) or a raw 256-bit hex key literal (x'<64-hex>' or X'<64-hex>', applied directly via PRAGMA hexkey) through the --encryption-key CLI flag (target DB only) or the DB_ENCRYPTION_KEY environment variable (target DB and sidecar SystemDb):

bash
# Passphrase (KDF-derived via PRAGMA key)
DB_ENCRYPTION_KEY="your-strong-passphrase-here"

# Raw 256-bit hex key (64 hex chars, applied via PRAGMA hexkey)
DB_ENCRYPTION_KEY="x'0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef'"

[!WARNING] Audit Log Compatibility: The DB_ENCRYPTION_KEY environment variable applies globally and will cause the internal SystemDb to attempt to decrypt your audit log (--audit-log). If you have an existing unencrypted audit log, the server will fail to start with file is not a database. To encrypt ONLY your target database (leaving the audit log unencrypted), use the --encryption-key CLI 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: ~4.51–8.07M ops/sec for Map-based catalog lookup (~0.2–0.3 Β΅s); ~6.78–8.16K ops/sec end-to-end with handler execution and audit bypass (~244–259 Β΅s)
  • Auth scope checks: ~2.32–5.88M ops/sec β€” OAuth scope evaluation adds negligible latency (~0.2–1.1 Β΅s)
  • Identifier validation: ~2.28–6.91M ops/sec β€” SQL identifier sanitization and quoting (~0.2–0.6 Β΅s)
  • Schema cache hits: ~594–649K ops/sec (~2.5–5.5 Β΅s) for SchemaManager cached metadata lookups vs ~4.53K ops/sec on cache miss
  • Debug log (filtered): ~3.08M ops/sec β€” disabled log levels are fast no-ops (~0.7 Β΅s)
  • Code Mode security: ~98.1K validations/sec uncached (~14.8 Β΅s), ~1.10–1.17M ops/sec on cached valid / early-rejected blocked code (~1.5–1.6 Β΅s)
  • Sandbox execution: ~68–216 executions/sec β€” isolated V8 (isolated-vm) round-trips in ~10.3–13.7 ms (~15.7–17.3 ms with real SqliteApi bindings)
bash
pnpm run bench            # Run all benchmarks
pnpm run bench:verbose    # Verbose mode with detailed timings
BenchmarkWhat It Measures
Handler DispatchTool lookup, error construction, SQL validation, audit-intercepted dispatch
UtilitiesIdentifier sanitization, WHERE clause validation, SQL validation
Tool FilteringFilter parsing, group lookups, meta-group catalog generation
Schema ParsingZod schema validation for simple/complex/large payloads + failure paths
Logger & SanitizationLog call overhead, message sanitization, sensitive data redaction
Transport & AuthToken extraction, scope checking, error formatting, rate limiting
Code ModeSandbox creation, pool lifecycle, security validation, execution
Database OperationsNative vs WASM queries, JSON queries, table/index metadata, schema caching
Resource & PromptsResource handler YAML assembly, prompt generation, cached tool catalog

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.