CAT
/MCP
SkillsMCPMarketplacesDigestToolsAdvertise

This week in Claude

Every Monday: Claude Code, Agent SDK, MCP, and the Anthropic platform moves worth your time.

Skills by Category
Frontend DevelopmentBackend & APIsTesting & QASecurityDevOps & CI/CDGit & Pull RequestsDocumentationCode Review & QualityAI & Agent BuildingSkill Development
MCP Servers by Category
Sales & MarketingWeb & Browser AutomationDatabasesAI & LLM ToolsCloud & InfrastructureCommunication & MessagingDeveloper ToolsDesign & CreativeDocuments & KnowledgeSearch & Web Crawling
Marketplaces by Category
AI Agents & OrchestrationLLM IntegrationDevelopment ToolsFrontend & UIBackend & APIsDatabasesTesting & Code QualityDevOps & CloudSecurity & ComplianceGit & Version Control

Cross AI Tools

Discover Claude Code plugins, extensions, and tools. Automatically updated directory of Anthropic Claude AI marketplaces with development tools, productivity plugins, and integrations.

Resources

  • Browse Skills
  • Browse MCP Servers
  • Browse Marketplaces
  • Plugins Reference

Community

  • About
  • Tools
  • Feedback
  • Privacy Policy
  • Advertise

Built for the Claude Code community with Claude Code by @mertduzgun

Independent project, not affiliated with Anthropic

db-mcp (SQLite MCP Server)

neverinfamous/db-mcp
STDIOregistry active
Summary

A SQLite server that goes well beyond basic CRUD with 170+ tools spanning FTS5 full-text search, JSON operations, statistical analysis, vector search, and SpatiaLite geospatial queries. The standout is Code Mode, which runs multi-step operations in a V8 sandbox to cut token usage by 70-90% instead of chaining dozens of tool calls. Ships with dual backends (WASM for portability, better-sqlite3 for performance), OAuth 2.1 authentication with granular table and operation scopes, and HTTP/SSE transports. Smart tool filtering lets you expose only what you need to stay within IDE limits. Reach for this when you need serious SQLite capabilities with production security, not just a query executor.

CodeRabbit
CodeRabbit
AI writes the code. CodeRabbit catches the slop.
Try For Free →
Keep your Mac awake
Keep your Mac awake
Keep your Mac awake while Claude Code and 40+ AI agents run. Sleeps when they're idle.
One time payment $9 →
Context.devContext.dev
Context.dev
Integrate web data into your AI product. One API to scrape website & brand data.
Get API Key Now →
Make your agent a DeFi expert
Make your agent a DeFi expert
Agent, run crypto. Access onchain data & trade routes via 1inch.
Install now →
Make money from your Skills
Make money from your Skills
On Capafy, your Skill runs online 24/7 as an agent product, and you get paid every time someone uses it.
Start earning →
AppSignal
AppSignal
Monitor with ease. Code with confidence.
Start Free Trial →
CodeRabbit
CodeRabbit
AI writes the code. CodeRabbit catches the slop.
Try For Free →
Keep your Mac awake
Keep your Mac awake
Keep your Mac awake while Claude Code and 40+ AI agents run. Sleeps when they're idle.
One time payment $9 →
Context.devContext.dev
Context.dev
Integrate web data into your AI product. One API to scrape website & brand data.
Get API Key Now →
Make your agent a DeFi expert
Make your agent a DeFi expert
Agent, run crypto. Access onchain data & trade routes via 1inch.
Install now →
Make money from your Skills
Make money from your Skills
On Capafy, your Skill runs online 24/7 as an agent product, and you get paid every time someone uses it.
Start earning →
AppSignal
AppSignal
Monitor with ease. Code with confidence.
Start Free Trial →

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.

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

Wiki • Changelog


🎯 What Sets Us Apart

FeatureDescription
181+ 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 & SearchO(1) cursor-based keyset pagination, 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
22 Resources11 data resources (schema, tables, table_schema, indexes, views, health, meta, audit, metrics, compile_options, pragma) + 11 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 180+ capabilities locally, reducing token overhead by 70–90% and supercharging AI agent reasoning
Token-Optimized PayloadsEvery tool response is designed for minimal token footprint with _meta.tokenEstimate on every response 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, window functions, and SpatiaLite GIS
OAuth 2.1 + Access ControlEnterprise-ready security with RFC 9728/8414 compliance, granular scopes (full, read, write, admin, db:*, table:*:*), and Keycloak integration
Smart Tool Filtering10 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 + Unicode-normalized WHERE clause validation), sandboxed code execution (V8 codeGeneration restrictions, frozen prototypes, 29 blocked patterns, Proxy nullified, RPC allowlist), CORS deny-all default, fail-closed scope enforcement, JWT claims sanitization, 7 security headers, body size limits, rate limiting with Retry-After, slowloris timeouts, trustedProxyIps, opt-in HSTS, non-root Docker, and build provenance
Encryption at RestNative SQLCipher support via --encryption-key or DB_ENCRYPTION_KEY. Dynamically loads better-sqlite3-multiple-ciphers and automatically encrypts the sidecar SystemDb audit logs to prevent sensitive queries from leaking
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 (sensitiveHint, readOnlyHint), resource priorities, and progress notifications

🚀 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-native for full features (181 MCP tools / 170 group tools, transactions, window functions, SpatiaLite). Use --sqlite for 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() and Function() construction from strings disabled at the V8 engine level via codeGeneration: { 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.

ShortcutWASMNative+ Built-inWhat's Included
starter6570+4Core, JSON, Text
analytics6773+4Core, JSON, Stats
search5156+4Core, Text, Vector
spatial4047+4Core, Geo, Vector
dev-schema4141+4Core, Introspection, Migration
minimal2525+4Core only
full143170+4Everything enabled

Tool Groups (10 Available)

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

GroupWASMNative+ Built-inDescription
core2525+4Basic CRUD, schema, tables
json2525+4JSON/JSONB operations, analysis
text1520+4Text processing + FTS5 + advanced search
stats1723+4Descriptive, inference, window functions
vector1111+4Vector storage, similarity search
admin3031+4DB maintenance, backup, virtual tables
transactions08+4Commit, rollback, savepoints (Native only)
geo411+4Geospatial + SpatiaLite (Native only)
introspection1010+4Schema mapping, FK graph, analysis
migration66+4Schema migration tracking (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:

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)

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:

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_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,admin
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 10)

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

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_HOST127.0.0.1Host/IP to bind to (0.0.0.0 in Docker) (CLI: --server-host)
SQLITE_DATABASE—SQLite database path (CLI: --sqlite / --sqlite-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 metrics at HTTP /metrics (e.g., prometheus) (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_TOLERANCE60Clock 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)
LOG_LEVELinfoLog verbosity: debug, info, warning, error
METADATA_CACHE_TTL_MS5000Schema cache TTL in ms (auto-invalidated on DDL operations)
CODEMODE_ISOLATIONisolateCode Mode sandbox: isolate (isolated-vm native) or worker
CODE_MODE_MAX_RESULT_SIZE102400Maximum Code Mode result payload in bytes (default 100KB, cap 50MB)
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)
ALLOWED_IO_ROOTS—JSON array or comma-separated list of absolute paths allowed for IO operations
MCP_AUTH_TOKEN—Simple bearer token for HTTP auth (CLI: --auth-token)
AUDIT_LOG—Audit log file path, or stderr (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

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 --help for 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-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" 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 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:

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:

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:

MethodEndpointPurpose
GET/sseOpens SSE stream, returns /messages?sessionId=<id> endpoint
POST/messages?sessionId=<id>Send JSON-RPC messages to the session

Utility Endpoints

MethodEndpointPurpose
GET/healthHealth check (bypasses rate limiting, always available for monitoring)

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

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 — 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 aud claim in tokens.

[!NOTE] 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 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 are null/[].

[!WARNING] HTTP without authentication: When using --transport http without 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.

  1. Strong Passphrase: A standard string. SQLCipher will automatically use PBKDF2 key derivation.
    DB_ENCRYPTION_KEY="your-strong-passphrase-here"
    
  2. Raw Hex Key (Best Performance): To skip PBKDF2 derivation overhead, provide an exact 256-bit raw hex key prefixed with x and wrapped in single quotes:
    DB_ENCRYPTION_KEY="x'2DD29CA851E7B56E4697B0E1F08507293D761A05CE4D1B628663F411A8086D99'"
    

[!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: 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
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.

Featured
CodeRabbit
CodeRabbit
AI writes the code. CodeRabbit catches the slop.
Try For Free →
Keep your Mac awake
Keep your Mac awake
Keep your Mac awake while Claude Code and 40+ AI agents run. Sleeps when they're idle.
One time payment $9 →
Context.devContext.dev
Context.dev
Integrate web data into your AI product. One API to scrape website & brand data.
Get API Key Now →
Make your agent a DeFi expert
Make your agent a DeFi expert
Agent, run crypto. Access onchain data & trade routes via 1inch.
Install now →
Make money from your Skills
Make money from your Skills
On Capafy, your Skill runs online 24/7 as an agent product, and you get paid every time someone uses it.
Start earning →
AppSignal
AppSignal
Monitor with ease. Code with confidence.
Start Free Trial →
Categories
Databases
Registryactive
Packagedb-mcp
TransportSTDIO
UpdatedFeb 4, 2026
View on GitHub

Related Databases MCP Servers

View all →
Postgres

ai.waystation/postgres

Connect to your PostgreSQL database to query data and schemas.
54
Read Only Local Postgres Mcp Server

hovecapital/read-only-local-postgres-mcp-server

MCP server for read-only PostgreSQL database queries in Claude Desktop
2
Database Mcp

cocaxcode/database-mcp

MCP server for database connectivity. Multi-DB (PostgreSQL, MySQL, SQLite), 19 tools.
1
Mcp Mysql

io.github.infoinlet-marketplace/mcp-mysql

Read-only MySQL/MariaDB for AI agents — query, list/describe tables, health. SQL-guarded.
Database Admin

io.github.cybeleri/database-admin

Database admin MCP: schema inspection, query optimization for PostgreSQL and MySQL
Postgres Secured (Aegis Zero-Trust)

io.github.yash-0620/postgres-mcp-secured

Enterprise PostgreSQL MCP secured by Aegis Zero-Trust to block unauthorized SQL injections.