db-mcp (SQLite MCP Server)

SQLite MCP server with OAuth 2.1, HTTP/SSE, 122 tools, and smart tool filtering

DatabasesTypeScriptv1.0.2

db-mcp (SQLite MCP Server)

SQLite MCP Server with 139 specialized tools, 8 data resources + 9 help resources, and 10 prompts, 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.

GitHub GitHub Release npm Docker Pulls License: MIT Status MCP Registry Security TypeScript E2E Tests E2E Tests Coverage

Wiki โ€ข Changelog


๐ŸŽฏ What Sets Us Apart

FeatureDescription
139 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
17 Resources8 data resources (schema, tables, indexes, views, health, metadata, insights) + 9 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 fast, secure JavaScript sandbox. Instead of spending thousands of tokens on back-and-forth tool calls, Code Mode exposes all 139 capabilities locally, reducing token overhead by up to 90% and supercharging AI agent reasoning
Token-Optimized PayloadsEvery tool response is designed for minimal token footprint. Tools include compact, nodesOnly, maxOutliers, minSeverity, and maxInvalid parameters where applicable โ€” letting agents control response size without losing data access. Large datasets include metadata so agents always know the full picture
Dual SQLite BackendsWASM (sql.js) for zero-compilation portability, Native (better-sqlite3) for full features including transactions, window functions, and SpatiaLite GIS
Performanceโš ๏ธ WASM Caution: Synchronous execution blocks Node Event Loop on heavy workloads. ๐Ÿš€ Native: High-performance concurrent execution.
OAuth 2.1 + Access ControlEnterprise-ready security with RFC 9728/8414 compliance, granular scopes (read, write, admin, db:*, table:*:*), and Keycloak integration
Smart Tool Filtering9 tool groups + 7 shortcuts let you stay within IDE limits while exposing exactly what you need
HTTP Streaming TransportStreamable HTTP (/mcp) for modern clients + legacy SSE (/sse) for backward compatibility โ€” both protocols supported simultaneously with security headers, rate limiting, health check, and stateless mode for serverless
Production-Ready SecuritySQL injection protection, parameterized queries, input validation, sandboxed code execution, HTTP body size enforcement, 7 security headers, server timeouts (slowloris protection), Retry-After rate limiting, trustProxy for reverse proxy deployments, opt-in HSTS, non-root Docker execution, and build provenance
Strict TypeScript100% type-safe codebase with strict mode, no any types, 1911 unit tests + 1136 E2E tests and 90% coverage
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-03-26 CompliantFull protocol support with tool safety hints, resource priorities, and progress notifications

๐Ÿš€ Quick Start

Option 1: Docker (Recommended)

Pull and run instantly:

bash
docker pull writenotenow/db-mcp:latest

Run with volume mount:

bash
docker run -i --rm \
  -v $(pwd):/workspace \
  writenotenow/db-mcp:latest \
  --sqlite-native /workspace/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
npm install

Build the project:

bash
npm run build

Run the server:

bash
# Native backend (better-sqlite3) - Full features, requires Node.js native build
node dist/cli.js --transport stdio --sqlite-native ./database.db

# WASM backend (sql.js) - Cross-platform, no compilation required
node dist/cli.js --transport stdio --sqlite ./database.db

Backend Choice: Use --sqlite-native for full features (139 tools, transactions, window functions, SpatiaLite). Use --sqlite for WASM mode (115 tools, no native dependencies).

Verify It Works

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

Expected output:

text
[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:

bash
npm run test

Prerequisites

  • โœ… Docker installed and running (for Docker method)
  • โœ… Node.js 24+ (LTS) (for local installation)

๐ŸŽ›๏ธ Tool Filtering

[!IMPORTANT] AI-enabled IDEs like Cursor have tool limits. With 139 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

โญ Recommended: Code Mode (Maximum Token Savings)

Code Mode (sqlite_execute_code) provides access to all 139 tools' worth of capability through a single, secure JavaScript sandbox. Instead of spending thousands of tokens on back-and-forth tool calls, Code Mode exposes all capabilities locally โ€” reducing token overhead by up to 90%.

json
{
  "mcpServers": {
    "db-mcp-sqlite": {
      "command": "node",
      "args": [
        "C:/path/to/db-mcp/dist/cli.js",
        "--transport",
        "stdio",
        "--sqlite-native",
        "C:/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 9 tool groups, and returning exactly the data it needs โ€” in one execution.

Starter (50 tools)

If you prefer individual tool calls, starter provides Core + JSON + Text:

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

Custom Groups

Specify exactly the groups you need:

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

Shortcuts (Predefined Bundles)

Note: Native includes FTS5 (4), window functions (6), transactions (7), and SpatiaLite (7) not available in WASM.

ShortcutWASMNative+ Built-inWhat's Included
starter4650+3Core, JSON, Text
analytics4652+3Core, JSON, Stats
search3438+3Core, Text, Vector
spatial2532+3Core, Geo, Vector
dev-schema2525+3Core, Introspection, Migration
minimal1010+3Core only
full115139+3Everything enabled

Tool Groups (10 Available)

Note: +3 built-in tools (server_info, server_health, list_adapters) and +1 code mode are always included.

GroupWASMNative+ Built-inDescription
codemode11+3Code Mode (sandboxed code execution) ๐ŸŒŸ
core1010+3Basic CRUD, schema, tables
json2424+3JSON/JSONB operations, analysis
text1418+3Text processing + FTS5 + advanced search
stats1420+3Statistical analysis (+ window funcs)
vector1212+3Embeddings, similarity search
admin2734+3Backup, restore, virtual tables, pragma
geo512+3Geospatial + SpatiaLite (Native only)
introspection1010+3FK graph, cascade sim, storage/index audit
migration77+3Migration tracking, apply, rollback (opt-in)

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
+Group+vectorAdd tools from this group to current set
-Group-adminRemove tools in this group from current set
+Tool+fuzzy_searchAdd one specific tool
-Tool-drop_tableRemove 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:

bash
# 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:

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

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

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

Loadable Extensions (require installation)

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

Installing Extensions

CSV Extension:

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

# Set environment variable:
export CSV_EXTENSION_PATH=/path/to/csv.so  # Linux
export CSV_EXTENSION_PATH=/path/to/csv.dll # Windows

# Or use CLI flag:
db-mcp --sqlite-native ./data.db --csv

SpatiaLite Extension:

bash
# Linux (apt):
sudo apt install libspatialite-dev

# macOS (Homebrew):
brew install libspatialite

# Windows: Download from https://www.gaia-gis.it/gaia-sins/

# Set environment variable:
export SPATIALITE_PATH=/path/to/mod_spatialite.so

# Or use 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_PATH environment variables for custom locations.

๐Ÿ“ Resources

Data Resources (8)

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,admin
sqlite_healthsqlite://healthDatabase health and status(read-only)
sqlite_metasqlite://metaDatabase metadata and PRAGMAscore,admin
sqlite_insightsmemo://insightsBusiness insights memo (analysis)core,admin

Help Resources (1 + up to 8)

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

ResourceURIDescriptionWhen Registered
sqlite_helpsqlite://helpGotchas, WASM vs Native, Code Mode APIAlways
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, transactions, backup, virtual tables referenceWhen admin 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

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

๐Ÿ”ง Configuration

Environment Variables

VariableDefaultDescription
MCP_HOST0.0.0.0Host/IP to bind to (CLI: --server-host)
SQLITE_DATABASEโ€”SQLite database path (CLI: --sqlite / --sqlite-native)
DB_MCP_TOOL_FILTERโ€”Tool filter string (CLI: --tool-filter)
MCP_AUTH_TOKENโ€”Simple bearer token for HTTP auth (CLI: --auth-token)
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_TOLERANCE60Clock tolerance in seconds (CLI: --oauth-clock-tolerance)
LOG_LEVELinfoLog verbosity: debug, info, warning, error
METADATA_CACHE_TTL_MS5000Schema cache TTL in ms (auto-invalidated on DDL operations)
CODEMODE_ISOLATIONworkerCode Mode sandbox: worker (enhanced isolation) or vm
MCP_RATE_LIMIT_MAX100Max requests/minute per IP (HTTP transport)
CSV_EXTENSION_PATHโ€”Custom path to CSV extension binary (native only)
SPATIALITE_PATHโ€”Custom path to SpatiaLite extension binary (native only)

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

text
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)
Server:       --name <name>  --version <ver>  --tool-filter <filter>

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:

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"
      ]
    }
  }
}

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" and wrap args in run -i --rm -v ./data:/app/data writenotenow/db-mcp:latest

See Tool Filtering to customize which tools are exposed.

HTTP/SSE Transport (Remote Access)

For remote access, web-based clients, or MCP Inspector testing, run the server in HTTP mode:

bash
node dist/cli.js --transport http --port 3000 --server-host 0.0.0.0 --sqlite-native ./database.db

Endpoints:

EndpointDescriptionMode
GET /Server info and available endpointsBoth
POST /mcpJSON-RPC requests (initialize, tools/call, etc.)Both
GET /mcpSSE stream for server-to-client notificationsStateful
DELETE /mcpSession terminationStateful
GET /sseLegacy SSE connection (MCP 2024-11-05)Stateful
POST /messagesLegacy SSE message endpointStateful
GET /healthHealth check (always public)Both

Session Management: The server uses stateful sessions by default. Include the mcp-session-id header (returned from initialization) in subsequent requests for session continuity.

Security Features:

  • 7 Security Headers โ€” X-Content-Type-Options, X-Frame-Options, Content-Security-Policy, Cache-Control, Referrer-Policy (no-referrer), Permissions-Policy + opt-in Strict-Transport-Security via enableHSTS
  • Server Timeouts โ€” Request, keep-alive, and headers timeouts prevent slowloris-style DoS
  • Rate Limiting โ€” 100 requests/minute per IP (429 + Retry-After on excess, health checks exempt)
  • CORS โ€” Configurable via --cors-origins (default: *, supports wildcard subdomains like *.example.com). โš ๏ธ Security Warning: The default * allows requests from any origin. For production HTTP deployments, explicitly configure this to your trusted domains.
  • Trust Proxy โ€” Opt-in trustProxy for X-Forwarded-For IP extraction behind reverse proxies
  • Body Size Limit โ€” Configurable via --max-body-bytes (default: 1 MB)
  • 404 Handler โ€” Unknown paths return { error: "Not found" }
  • Cross-Protocol Guard โ€” SSE session IDs rejected on /mcp and vice versa

Stateless Mode (Serverless)

For serverless deployments (AWS Lambda, Cloudflare Workers, Vercel), use stateless mode:

bash
node dist/cli.js --transport http --port 3000 --server-host 0.0.0.0 --stateless --sqlite-native :memory:
ModeProgress NotificationsLegacy SSEServerless
Stateful (default)โœ… Yesโœ… Yesโš ๏ธ Complex
Stateless (--stateless)โŒ NoโŒ Noโœ… Native

๐Ÿ” Authentication

db-mcp supports two authentication mechanisms for HTTP transport:

Simple Bearer Token (--auth-token)

Lightweight authentication for development or single-tenant deployments:

bash
# CLI
node dist/cli.js --transport http --port 3000 --auth-token my-secret --sqlite-native ./database.db

# Environment variable
export MCP_AUTH_TOKEN=my-secret
node dist/cli.js --transport http --port 3000 --sqlite-native ./database.db

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

ComponentStatusDescription
Protected Resource Metadataโœ…RFC 9728 /.well-known/oauth-protected-resource
Auth Server Discoveryโœ…RFC 8414 metadata discovery with caching
Token Validationโœ…JWT validation with JWKS support
Scope Enforcementโœ…Granular read, write, admin scopes
HTTP Transportโœ…Streamable HTTP with OAuth middleware

Supported Scopes

ScopeDescription
readRead-only access to all databases
writeRead and write access to all databases
adminFull administrative access
db:{name}Access to specific database only
table:{db}:{table}Access to specific table only

Quick Start with OAuth CLI Flags

bash
node dist/cli.js --transport http --port 3000 \
  --oauth-enabled \
  --oauth-issuer http://localhost:8080/realms/db-mcp \
  --oauth-audience db-mcp-server \
  --sqlite-native ./database.db

Additional flags: --oauth-jwks-uri <url> (auto-discovered if omitted), --oauth-clock-tolerance <seconds> (default: 60).

Keycloak Integration

See docs/KEYCLOAK_SETUP.md for setting up Keycloak as your OAuth provider.

Priority: When both --auth-token and --oauth-enabled are set, OAuth 2.1 takes precedence. If neither is configured, the server warns and runs without authentication.

๐Ÿ“Š 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: ~11M ops/sec โ€” Map-based lookup is effectively zero-cost
  • Auth scope checks: 7โ€“9M ops/sec โ€” OAuth middleware adds no measurable latency
  • Identifier validation: 6.4M ops/sec โ€” SQL sanitization is near-instant
  • Schema cache hits: 4.3M ops/sec โ€” metadata lookups avoid redundant queries
  • Debug log (filtered): 9.5M ops/sec โ€” disabled log levels are true no-ops (50ร— faster than actual writes)
  • Code Mode security: 1.2M validations/sec for typical code, blocked patterns rejected in <1 ยตs
bash
npm run bench            # Run all benchmarks
npm run bench:verbose    # Verbose mode with detailed timings
BenchmarkWhat It Measures
Handler DispatchTool lookup, error construction, progress notification overhead
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 OperationsPRAGMA ops, table metadata, query result processing, schema caching
Resource & PromptsURI 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.

Learn More