{"id":35912565,"url":"https://github.com/neverinfamous/db-mcp","last_synced_at":"2026-06-06T11:01:06.400Z","repository":{"id":328254819,"uuid":"1114822935","full_name":"neverinfamous/db-mcp","owner":"neverinfamous","description":"Secure Database Administration \u0026 Observability with Code Mode in V8 Isolate Sandbox Unifying 181+ Tools with Optimized Payloads for 70–90% Token Savings. Includes Dynamic Tool Filtering, Dual-Transport HTTP/SSE, OAuth 2.1 Auth, Granular Access Control, Audit Logging, Deterministic Error Handling, Prometheus Metrics export, \u0026 Encryption at Rest","archived":false,"fork":false,"pushed_at":"2026-06-06T10:02:59.000Z","size":3401,"stargazers_count":8,"open_issues_count":0,"forks_count":1,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-06-06T10:18:40.173Z","etag":null,"topics":["ai-llm","better-sqlite3","csv","database","developer-tools","fts5","http-sse","json","jsonb","mcp","mcp-server","model-context-protocol","oauth","rtree","spatialite","sqlite","sqlite-wasm","typescript","vector-search","wasm"],"latest_commit_sha":null,"homepage":"https://adamic.tech/","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/neverinfamous.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":"SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-12-12T00:01:19.000Z","updated_at":"2026-06-06T10:18:17.000Z","dependencies_parsed_at":null,"dependency_job_id":"85475d03-7648-4c96-846e-a7087b6e587e","html_url":"https://github.com/neverinfamous/db-mcp","commit_stats":null,"previous_names":["neverinfamous/db-mcp"],"tags_count":7,"template":false,"template_full_name":null,"purl":"pkg:github/neverinfamous/db-mcp","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/neverinfamous%2Fdb-mcp","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/neverinfamous%2Fdb-mcp/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/neverinfamous%2Fdb-mcp/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/neverinfamous%2Fdb-mcp/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/neverinfamous","download_url":"https://codeload.github.com/neverinfamous/db-mcp/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/neverinfamous%2Fdb-mcp/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":33979274,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-26T15:22:16.424Z","status":"online","status_checked_at":"2026-06-06T02:00:07.033Z","response_time":107,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["ai-llm","better-sqlite3","csv","database","developer-tools","fts5","http-sse","json","jsonb","mcp","mcp-server","model-context-protocol","oauth","rtree","spatialite","sqlite","sqlite-wasm","typescript","vector-search","wasm"],"created_at":"2026-01-10T03:40:40.079Z","updated_at":"2026-06-06T11:01:06.377Z","avatar_url":"https://github.com/neverinfamous.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# db-mcp (SQLite MCP Server)\n\n\u003c!-- mcp-name: io.github.neverinfamous/db-mcp --\u003e\n\n**SQLite MCP Server** with 170+ 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.\n\n[![GitHub](https://img.shields.io/badge/GitHub-neverinfamous/db--mcp-blue?logo=github)](https://github.com/neverinfamous/db-mcp)\n![GitHub Release](https://img.shields.io/github/v/release/neverinfamous/db-mcp)\n[![npm](https://img.shields.io/npm/v/db-mcp)](https://www.npmjs.com/package/db-mcp)\n[![Docker Pulls](https://img.shields.io/docker/pulls/writenotenow/db-mcp)](https://hub.docker.com/r/writenotenow/db-mcp)\n[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT)\n![Status](https://img.shields.io/badge/status-Production%2FStable-brightgreen)\n[![MCP](https://img.shields.io/badge/MCP-Registry-green.svg)](https://registry.modelcontextprotocol.io/v0/servers?search=io.github.neverinfamous/db-mcp)\n[![Security](https://img.shields.io/badge/Security-Enhanced-green.svg)](SECURITY.md)\n[![TypeScript](https://img.shields.io/badge/TypeScript-Strict-blue.svg)](https://github.com/neverinfamous/db-mcp)\n[![E2E](https://github.com/neverinfamous/db-mcp/actions/workflows/e2e.yml/badge.svg)](https://github.com/neverinfamous/db-mcp/actions/workflows/e2e.yml)\n[![Tests](https://img.shields.io/badge/Tests-1911%20passed-brightgreen.svg)](https://github.com/neverinfamous/db-mcp)\n[![Coverage](https://img.shields.io/badge/Coverage-87.53%25-green.svg)](https://github.com/neverinfamous/db-mcp)\n\n**[Wiki](https://github.com/neverinfamous/db-mcp/wiki)** • **[Changelog](CHANGELOG.md)**\n\n---\n\n## 🎯 What Sets Us Apart\n\n| Feature                          | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |\n| -------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |\n| **170+ 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                                                                                                                                                                                                                                                                            |\n| **20 Resources**                 | 11 data resources (schema, tables, indexes, views, health, metadata, insights, audit, compile_options, pragma) + 9 help resources (`sqlite://help` + per-group reference) — filtered by `--tool-filter`                                                                                                                                                                                                                                                                       |\n| **10 AI-Powered Prompts**        | Guided workflows for schema exploration, query building, data analysis, optimization, migration, debugging, and hybrid FTS5 + vector search                                                                                                                                                                                                                                                                                                                                   |\n| **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 170+ capabilities locally, reducing token overhead by 70–90% and supercharging AI agent reasoning                                                                                                                               |\n| **Token-Optimized Payloads**     | Every 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                                                                                                                                                  |\n| **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                                                                                                                                                                                                                                                                             |\n| **OAuth 2.1 + Access Control**   | Enterprise-ready security with RFC 9728/8414 compliance, granular scopes (`full`, `read`, `write`, `admin`, `db:*`, `table:*:*`), and Keycloak integration                                                                                                                                                                                                                                                                                                                    |\n| **Smart Tool Filtering**         | 10 tool groups + 7 shortcuts let you stay within IDE limits while exposing exactly what you need                                                                                                                                                                                                                                                                                                                                                                              |\n| **HTTP Streaming Transport**     | Streamable 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                                                                                                                                                                                                                                                  |\n| **Production-Ready Security**    | SQL injection protection (parameterized queries + Unicode-normalized WHERE clause validation), sandboxed code execution (V8 `codeGeneration` restrictions, frozen prototypes, 18 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, `trustProxy`, opt-in HSTS, non-root Docker, and build provenance |\n| **Strict TypeScript**            | 100% type-safe codebase with strict mode, no `any` types, 1911 unit tests + 1136 E2E tests and 90% coverage                                                                                                                                                                                                                                                                                                                                                                   |\n| **Deterministic Error Handling** | Every 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                                                                                                                                                                                                                                    |\n| **MCP 2025-03-26 Compliant**     | Full protocol support with tool safety hints (`sensitiveHint`, `readOnlyHint`), resource priorities, and progress notifications                                                                                                                                                                                                                                                                                                                                               |\n\n## 🚀 Quick Start\n\n### Option 1: Docker (Recommended)\n\nPull and run instantly:\n\n```bash\ndocker pull writenotenow/db-mcp:latest\n```\n\nRun with volume mount:\n\n```bash\ndocker run -i --rm \\\n  -v $(pwd):/workspace \\\n  writenotenow/db-mcp:latest \\\n  --sqlite-native /workspace/database.db\n```\n\n### Option 2: Node.js Installation\n\nClone the repository:\n\n```bash\ngit clone https://github.com/neverinfamous/db-mcp.git\n```\n\nNavigate to directory:\n\n```bash\ncd db-mcp\n```\n\nInstall dependencies:\n\n```bash\nnpm install\n```\n\nBuild the project:\n\n```bash\nnpm run build\n```\n\nRun the server with **Native backend** (better-sqlite3 — full features, requires Node.js native build):\n\n```bash\nnode dist/cli.js --transport stdio --sqlite-native ./database.db\n```\n\nOr with **WASM backend** (sql.js — cross-platform, no compilation required):\n\n```bash\nnode dist/cli.js --transport stdio --sqlite ./database.db\n```\n\n\u003e **Backend Choice:** Use `--sqlite-native` for full features (166 group tools, transactions, window functions, SpatiaLite). Use `--sqlite` for WASM mode (139 tools, no native dependencies).\n\n### Verify It Works\n\n```bash\nnode dist/cli.js --transport stdio --sqlite-native :memory:\n```\n\nExpected output:\n\n```\n[db-mcp] Starting MCP server...\n[db-mcp] Registered adapter: Native SQLite Adapter (better-sqlite3) (sqlite:default)\n[db-mcp] Server started successfully\n```\n\nRun the test suite:\n\n```bash\nnpm run test\n```\n\n### Prerequisites\n\n- ✅ Docker installed and running (for Docker method)\n- ✅ Node.js 24+ (LTS) (for local installation)\n\n## Code Mode: Maximum Efficiency\n\nCode Mode (`sqlite_execute_code`) dramatically reduces token usage (70–90%) and is included by default in all presets.\n\nCode 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:\n\n- **Process-level isolation** — user code runs in a separate V8 instance with enforced heap limits\n- **Readonly enforcement** — when `readonly: true`, stripped methods throw clear error messages listing available methods via Proxy traps\n- **Hard timeouts** — worker termination if execution exceeds the configured limit\n- **V8 code generation restrictions** — `eval()` and `Function()` construction from strings disabled at the V8 engine level via `codeGeneration: { strings: false, wasm: false }`\n- **RPC allowlist** — host-side validation prevents workers from invoking unauthorized API methods\n- **Full API access** — all 10 tool groups are available via `sqlite.*` (e.g., `sqlite.core.readQuery()`, `sqlite.json.extract()`)\n\nSet `CODEMODE_ISOLATION=vm` with `CODEMODE_ISOLATION_INSECURE=1` to fall back to the in-process `vm` module sandbox if needed.\n\n### ⚡ Code Mode Only (Maximum Token Savings)\n\nIf you control your own setup, you can run with **only Code Mode enabled** — a single tool that provides access to all 170+ tools' worth of capability through the `sqlite.*` API:\n\n```json\n{\n  \"mcpServers\": {\n    \"db-mcp-sqlite\": {\n      \"command\": \"node\",\n      \"args\": [\n        \"/path/to/db-mcp/dist/cli.js\",\n        \"--transport\",\n        \"stdio\",\n        \"--sqlite-native\",\n        \"/path/to/database.db\",\n        \"--tool-filter\",\n        \"codemode\"\n      ]\n    }\n  }\n}\n```\n\nThis 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](https://blog.cloudflare.com/code-mode-mcp/) pioneered by Cloudflare for their entire API: fixed token cost regardless of how many capabilities exist.\n\n\u003e [!TIP]\n\u003e **Maximize Token Savings:** Instruct your AI agent to prefer Code Mode over individual tool calls:\n\u003e\n\u003e _\"When using db-mcp, prefer `sqlite_execute_code` (Code Mode) for multi-step database operations to minimize token usage.\"_\n\n---\n\n## 🎛️ Tool Filtering\n\n\u003e [!IMPORTANT]\n\u003e **AI-enabled IDEs like Cursor have tool limits.** With 170+ 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.\n\n### Quick Start: Recommended Configurations\n\n#### Starter (core + json + text)\n\nIf you prefer individual tool calls, `starter` provides Core + JSON + Text:\n\n```json\n{\n  \"args\": [\"--tool-filter\", \"starter\"]\n}\n```\n\n#### Custom Groups\n\nSpecify exactly the groups you need:\n\n```json\n{\n  \"args\": [\"--tool-filter\", \"core,json,stats\"]\n}\n```\n\n### Shortcuts (Predefined Bundles)\n\n\u003e **Note:** Native includes FTS5 (5), window functions (6), transactions (8), and SpatiaLite (7) not available in WASM.\n\n| Shortcut     | WASM   | Native | + Built-in | What's Included                |\n| ------------ | ------ | ------ | ---------- | ------------------------------ |\n| `starter`    | **60** | **65** | +4         | Core, JSON, Text               |\n| `analytics`  | 63     | 69     | +4         | Core, JSON, Stats              |\n| `search`     | 46     | 51     | +4         | Core, Text, Vector             |\n| `spatial`    | 36     | 43     | +4         | Core, Geo, Vector              |\n| `dev-schema` | 37     | 37     | +4         | Core, Introspection, Migration |\n| `minimal`    | 21     | 21     | +4         | Core only                      |\n| `full`       | 139    | 166    | +4         | Everything enabled             |\n\n### Tool Groups (10 Available)\n\n\u003e **Note:** +4 built-in tools (server_info, server_health, list_adapters, sqlite_execute_code) are injected into every group.\n\n| Group           | WASM | Native | + Built-in | Description                                |\n| --------------- | ---- | ------ | ---------- | ------------------------------------------ |\n| `codemode`      | 1    | 1      | +4         | Code Mode (sandboxed code execution) 🧠    |\n| `core`          | 21   | 21     | +4         | Basic CRUD, schema, tables                 |\n| `json`          | 25   | 25     | +4         | JSON/JSONB operations, analysis            |\n| `text`          | 14   | 19     | +4         | Text processing + FTS5 + advanced search   |\n| `stats`         | 17   | 23     | +4         | Descriptive, inference, window functions   |\n| `vector`        | 11   | 11     | +4         | Vector storage, similarity search          |\n| `admin`         | 31   | 32     | +4         | DB maintenance, backup, virtual tables     |\n| `transactions`  | 0    | 8      | +4         | Commit, rollback, savepoints (Native only) |\n| `geo`           | 4    | 11     | +4         | Geospatial + SpatiaLite (Native only)      |\n| `introspection` | 10   | 10     | +4         | Schema mapping, FK graph, analysis         |\n| `migration`     | 6    | 6      | +4         | Schema migration tracking (opt-in)         |\n\n### Syntax Reference\n\n| Prefix   | Target   | Example         | Effect                                        |\n| -------- | -------- | --------------- | --------------------------------------------- |\n| _(none)_ | Shortcut | `starter`       | **Whitelist Mode:** Enable ONLY this shortcut |\n| _(none)_ | Group    | `core`          | **Whitelist Mode:** Enable ONLY this group    |\n| _(none)_ | Tool     | `read_query`    | **Whitelist Mode:** Enable ONLY this tool     |\n| `+`      | Group    | `+vector`       | Add tools from this group to current set      |\n| `-`      | Group    | `-admin`        | Remove tools in this group from current set   |\n| `+`      | Tool     | `+fuzzy_search` | Add one specific tool                         |\n| `-`      | Tool     | `-drop_table`   | Remove one specific tool                      |\n\n### Custom Tool Selection\n\nYou can list individual tool names (without `+` prefix) to create a fully custom whitelist — only the tools you specify will be enabled:\n\nEnable exactly 3 tools (whitelist mode):\n\n```bash\n--tool-filter \"read_query,write_query,list_tables\"\n```\n\nMix tools from different groups:\n\n```bash\n--tool-filter \"read_query,fuzzy_search,vector_search\"\n```\n\nCombine with a shortcut or group:\n\n```bash\n--tool-filter \"starter,+vector_search,+fuzzy_search\"\n```\n\nThis is useful for scripted or automated clients that need a minimal, precise set of capabilities.\n\n**Examples:**\n\n```bash\n--tool-filter \"starter\"\n--tool-filter \"core,json,text,fts5\"\n--tool-filter \"starter,+stats\"\n--tool-filter \"starter,-fts5\"\n```\n\n**Legacy Syntax (still supported):**\nIf you start with a negative filter (e.g., `-vector,-geo`), it assumes you want to start with _all_ tools enabled and then subtract.\n\n```bash\n--tool-filter \"-stats,-vector,-geo,-backup,-monitoring,-transactions,-window\"\n```\n\n## 🔌 SQLite Extensions\n\nSQLite supports both **built-in** extensions (compiled into better-sqlite3) and **loadable** extensions (require separate binaries).\n\n#### Built-in Extensions (work out of box)\n\n| Extension  | Purpose                             | Status           |\n| ---------- | ----------------------------------- | ---------------- |\n| **FTS5**   | Full-text search with BM25 ranking  | ✅ Always loaded |\n| **JSON1**  | JSON functions (json_extract, etc.) | ✅ Always loaded |\n| **R-Tree** | Spatial indexing for bounding boxes | ✅ Always loaded |\n\n#### Loadable Extensions (require installation)\n\n| Extension      | Purpose                   | Tools | CLI Flag       |\n| -------------- | ------------------------- | ----- | -------------- |\n| **CSV**        | CSV virtual tables        | 2     | `--csv`        |\n| **SpatiaLite** | Advanced GIS capabilities | 7     | `--spatialite` |\n\n#### Installing Extensions\n\n**CSV Extension:**\n\nDownload a precompiled binary or compile from source: https://www.sqlite.org/csv.html\n\nSet the environment variable (Linux/macOS):\n\n```bash\nexport CSV_EXTENSION_PATH=/path/to/csv.so\n```\n\nOn Windows, use `.dll`:\n\n```bash\nexport CSV_EXTENSION_PATH=/path/to/csv.dll\n```\n\nOr use the CLI flag:\n\n```bash\ndb-mcp --sqlite-native ./data.db --csv\n```\n\n**SpatiaLite Extension:**\n\nInstall the library for your platform:\n\n- **Linux (apt):** `sudo apt install libspatialite-dev`\n- **macOS (Homebrew):** `brew install libspatialite`\n- **Windows:** Download from https://www.gaia-gis.it/gaia-sins/\n\nSet the environment variable:\n\n```bash\nexport SPATIALITE_PATH=/path/to/mod_spatialite.so\n```\n\nOr use the CLI flag:\n\n```bash\ndb-mcp --sqlite-native ./data.db --spatialite\n```\n\n\u003e **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.\n\n## 📁 Resources\n\n### Data Resources (11)\n\nMCP resources provide read-only access to database metadata:\n\n| Resource                 | URI                                 | Description                       | Min Config    |\n| ------------------------ | ----------------------------------- | --------------------------------- | ------------- |\n| `sqlite_schema`          | `sqlite://schema`                   | Full database schema              | `minimal`     |\n| `sqlite_tables`          | `sqlite://tables`                   | List all tables                   | `minimal`     |\n| `sqlite_table_schema`    | `sqlite://table/{tableName}/schema` | Schema for a specific table       | `minimal`     |\n| `sqlite_indexes`         | `sqlite://indexes`                  | All indexes in the database       | `minimal`     |\n| `sqlite_views`           | `sqlite://views`                    | All views in the database         | `core,admin`  |\n| `sqlite_health`          | `sqlite://health`                   | Database health and status        | _(read-only)_ |\n| `sqlite_meta`            | `sqlite://meta`                     | Database metadata and PRAGMAs     | `core,admin`  |\n| `sqlite_compile_options` | `sqlite://compile_options`          | SQLite compile-time build options | _(read-only)_ |\n| `sqlite_pragma`          | `sqlite://pragma`                   | Runtime PRAGMA config snapshot    | _(read-only)_ |\n| `sqlite_insights`        | `memo://insights`                   | Business insights memo (analysis) | `core,admin`  |\n| `sqlite_audit`           | `sqlite://audit`                    | Recent audit log + backup stats   | `--audit-log` |\n\n### Help Resources (1 + up to 8)\n\nOn-demand tool reference documentation, filtered by `--tool-filter`:\n\n| Resource                    | URI                           | Description                                           | When Registered             |\n| --------------------------- | ----------------------------- | ----------------------------------------------------- | --------------------------- |\n| `sqlite_help`               | `sqlite://help`               | Gotchas, WASM vs Native, Code Mode API                | Always                      |\n| `sqlite_help_json`          | `sqlite://help/json`          | JSON/JSONB operations reference                       | When json group on          |\n| `sqlite_help_text`          | `sqlite://help/text`          | Text processing + FTS5 reference                      | When text group on          |\n| `sqlite_help_stats`         | `sqlite://help/stats`         | Statistical analysis + window functions reference     | When stats group on         |\n| `sqlite_help_vector`        | `sqlite://help/vector`        | Vector/semantic search reference                      | When vector group on        |\n| `sqlite_help_geo`           | `sqlite://help/geo`           | Geospatial + SpatiaLite reference                     | When geo group on           |\n| `sqlite_help_admin`         | `sqlite://help/admin`         | Admin, backup, virtual tables reference               | When admin group on         |\n| `sqlite_help_transactions`  | `sqlite://help/transactions`  | Transaction control reference                         | When transactions group on  |\n| `sqlite_help_introspection` | `sqlite://help/introspection` | Schema introspection, FK graph, diagnostics reference | When introspection group on |\n| `sqlite_help_migration`     | `sqlite://help/migration`     | Migration tracking, apply, rollback reference         | When migration group on     |\n\n\u003e **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.\n\n## 💬 Prompts (10)\n\nMCP prompts provide AI-assisted database workflows:\n\n| Prompt                          | Description                                      |\n| ------------------------------- | ------------------------------------------------ |\n| `sqlite_explain_schema`         | Explain database structure and relationships     |\n| `sqlite_query_builder`          | Help construct SQL queries for common operations |\n| `sqlite_data_analysis`          | Analyze data patterns and provide insights       |\n| `sqlite_optimization`           | Analyze and suggest database optimizations       |\n| `sqlite_migration`              | Help create database migration scripts           |\n| `sqlite_debug_query`            | Debug SQL queries that aren't working            |\n| `sqlite_documentation`          | Generate documentation for the database schema   |\n| `sqlite_summarize_table`        | Intelligent table analysis and summary           |\n| `sqlite_hybrid_search_workflow` | Hybrid FTS5 + vector search workflow             |\n| `sqlite_demo`                   | Interactive demo of MCP capabilities             |\n\n## 🔧 Configuration\n\n### Environment Variables\n\n| Variable                    | Default   | Description                                                                    |\n| --------------------------- | --------- | ------------------------------------------------------------------------------ |\n| `MCP_HOST`                  | `0.0.0.0` | Host/IP to bind to (CLI: `--server-host`)                                      |\n| `SQLITE_DATABASE`           | —         | SQLite database path (CLI: `--sqlite` / `--sqlite-native`)                     |\n| `DB_MCP_TOOL_FILTER`        | —         | Tool filter string (CLI: `--tool-filter`)                                      |\n| `MCP_AUTH_TOKEN`            | —         | Simple bearer token for HTTP auth (CLI: `--auth-token`)                        |\n| `OAUTH_ENABLED`             | `false`   | Enable OAuth 2.1 (CLI: `--oauth-enabled`)                                      |\n| `OAUTH_ISSUER`              | —         | Authorization server URL (CLI: `--oauth-issuer`)                               |\n| `OAUTH_AUDIENCE`            | —         | Expected token audience (CLI: `--oauth-audience`)                              |\n| `OAUTH_JWKS_URI`            | —         | JWKS URI, auto-discovered if omitted (CLI: `--oauth-jwks-uri`)                 |\n| `OAUTH_CLOCK_TOLERANCE`     | `60`      | Clock tolerance in seconds (CLI: `--oauth-clock-tolerance`)                    |\n| `LOG_LEVEL`                 | `info`    | Log verbosity: `debug`, `info`, `warning`, `error`                             |\n| `METADATA_CACHE_TTL_MS`     | `5000`    | Schema cache TTL in ms (auto-invalidated on DDL operations)                    |\n| `CODEMODE_ISOLATION`        | `isolate` | Code Mode sandbox: `isolate` (isolated-vm native) or `worker`                  |\n| `CODE_MODE_MAX_RESULT_SIZE` | `102400`  | Maximum Code Mode result payload in bytes (default 100KB, cap 50MB)            |\n| `MCP_RATE_LIMIT_MAX`        | `100`     | Max requests/minute per IP (HTTP transport)                                    |\n| `CSV_EXTENSION_PATH`        | —         | Custom path to CSV extension binary (native only)                              |\n| `SPATIALITE_PATH`           | —         | Custom path to SpatiaLite extension binary (native only)                       |\n| `AUDIT_LOG`                 | —         | Audit log file path, or `stderr` (CLI: `--audit-log`)                          |\n| `AUDIT_REDACT`              | `true`    | Redact tool arguments from audit entries (CLI: `--audit-no-redact` to disable) |\n| `AUDIT_READS`               | `false`   | Also log read-scoped tool invocations (CLI: `--audit-reads`)                   |\n| `AUDIT_BACKUP`              | `false`   | Enable pre-mutation DDL snapshots (CLI: `--audit-backup`)                      |\n| `AUDIT_BACKUP_DATA`         | `false`   | Include sample data rows in snapshots (CLI: `--audit-backup-data`)             |\n\n\u003e **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).\n\n### CLI Reference\n\n```\ndb-mcp [options]\n\nTransport:    --transport \u003cstdio|http|sse\u003e  --port \u003cN\u003e  --server-host \u003chost\u003e  --stateless\nAuth:         --auth-token \u003ctoken\u003e  |  --oauth-enabled --oauth-issuer \u003curl\u003e --oauth-audience \u003caud\u003e\nDatabase:     --sqlite \u003cpath\u003e  |  --sqlite-native \u003cpath\u003e\nExtensions:   --csv  --spatialite                         (native only)\nAudit:        --audit-log \u003cpath\u003e  --audit-no-redact  --audit-reads  --audit-backup  --audit-backup-data\nServer:       --name \u003cname\u003e  --version \u003cver\u003e  --tool-filter \u003cfilter\u003e\n```\n\n\u003e CLI flags override environment variables. Run `node dist/cli.js --help` for full details.\n\n## 📚 MCP Client Configuration\n\nAdd to your `~/.cursor/mcp.json`, Claude Desktop config, or equivalent:\n\n```json\n{\n  \"mcpServers\": {\n    \"db-mcp-sqlite\": {\n      \"command\": \"node\",\n      \"args\": [\n        \"C:/path/to/db-mcp/dist/cli.js\",\n        \"--transport\",\n        \"stdio\",\n        \"--sqlite-native\",\n        \"C:/path/to/your/database.db\",\n        \"--tool-filter\",\n        \"codemode\"\n      ]\n    }\n  }\n}\n```\n\n\u003e [!TIP]\n\u003e **Switching backends:** The config above uses the **Native** backend (better-sqlite3, 166 tools). To use the **WASM** backend (sql.js, 139 tools, zero native dependencies), change `--sqlite-native` to `--sqlite` in the args array. See the [Backend Options table in DOCKER_README](DOCKER_README.md#backend-options) for feature differences.\n\n**Variants** (modify the `args` array above):\n\n| Variant                | Change                                                                                                                               |\n| ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |\n| **WASM backend**       | Replace `--sqlite-native` with `--sqlite`                                                                                            |\n| **In-memory database** | Replace the database path with `:memory:`                                                                                            |\n| **Starter preset**     | Replace `\"codemode\"` with `\"starter\"` for individual tool calls                                                                      |\n| **CSV extension**      | Add `\"--csv\"` before `\"--tool-filter\"` (native only)                                                                                 |\n| **SpatiaLite**         | Add `\"--spatialite\"` and set `env: { \"SPATIALITE_PATH\": \"/path/to/mod_spatialite\" }` (native only)                                   |\n| **Linux/macOS**        | Use forward-slash Unix paths (e.g., `/path/to/db-mcp/dist/cli.js`)                                                                   |\n| **Docker**             | Replace `\"command\": \"node\"` with `\"command\": \"docker\"` and wrap args in `run -i --rm -v ./data:/app/data writenotenow/db-mcp:latest` |\n\n\u003e See [Tool Filtering](#️-tool-filtering) to customize which tools are exposed.\n\n## 🌐 HTTP/SSE Transport (Remote Access)\n\nFor remote access, web-based clients, or HTTP-compatible MCP hosts, use the HTTP transport:\n\n```bash\nnode dist/cli.js \\\n  --transport http \\\n  --port 3000 \\\n  --sqlite-native ./database.db\n```\n\n**Docker:**\n\n```bash\ndocker run --rm -p 3000:3000 \\\n  -v ./data:/app/data \\\n  writenotenow/db-mcp:latest \\\n  --transport http --port 3000 \\\n  --sqlite-native /app/data/database.db\n```\n\nThe server supports **two MCP transport protocols simultaneously**, enabling both modern and legacy clients to connect:\n\n### Streamable HTTP (Recommended)\n\nModern protocol (MCP 2025-03-26) — single endpoint, session-based:\n\n| Method   | Endpoint | Purpose                                          |\n| -------- | -------- | ------------------------------------------------ |\n| `POST`   | `/mcp`   | JSON-RPC requests (initialize, tools/list, etc.) |\n| `GET`    | `/mcp`   | SSE stream for server notifications              |\n| `DELETE` | `/mcp`   | Session termination                              |\n\nSessions are managed via the `Mcp-Session-Id` header.\n\n### Stateless Mode\n\nFor serverless/stateless deployments where sessions are not needed:\n\n```bash\nnode dist/cli.js --transport http --port 3000 --stateless --sqlite-native ./database.db\n```\n\nIn stateless mode: `GET /mcp` returns 405, `DELETE /mcp` returns 204, `/sse` and `/messages` return 404. Each `POST /mcp` creates a fresh transport.\n\n### Legacy SSE (Backward Compatibility)\n\nLegacy protocol (MCP 2024-11-05) — for clients like Python `mcp.client.sse`:\n\n| Method | Endpoint                   | Purpose                                                       |\n| ------ | -------------------------- | ------------------------------------------------------------- |\n| `GET`  | `/sse`                     | Opens SSE stream, returns `/messages?sessionId=\u003cid\u003e` endpoint |\n| `POST` | `/messages?sessionId=\u003cid\u003e` | Send JSON-RPC messages to the session                         |\n\n### Utility Endpoints\n\n| Method | Endpoint  | Purpose                                                                |\n| ------ | --------- | ---------------------------------------------------------------------- |\n| `GET`  | `/health` | Health check (bypasses rate limiting, always available for monitoring) |\n\n## 🔐 Authentication\n\ndb-mcp supports two authentication mechanisms for HTTP transport:\n\n### Simple Bearer Token (`--auth-token`)\n\nLightweight authentication for development or single-tenant deployments:\n\n```bash\nnode dist/cli.js --transport http --port 3000 --auth-token my-secret --sqlite-native ./database.db\n\n# Or via environment variable\nexport MCP_AUTH_TOKEN=my-secret\nnode dist/cli.js --transport http --port 3000 --sqlite-native ./database.db\n```\n\nClients 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.\n\n### OAuth 2.1 (Enterprise)\n\nFull OAuth 2.1 with RFC 9728/8414 compliance for production multi-tenant deployments:\n\n```bash\nnode dist/cli.js \\\n  --transport http \\\n  --port 3000 \\\n  --sqlite-native ./database.db \\\n  --oauth-enabled \\\n  --oauth-issuer http://localhost:8080/realms/db-mcp \\\n  --oauth-audience db-mcp-server\n```\n\n\u003e **Additional flags:** `--oauth-jwks-uri \u003curl\u003e` (auto-discovered if omitted), `--oauth-clock-tolerance \u003cseconds\u003e` (default: 60).\n\n### OAuth Scopes\n\nAccess control is managed through OAuth scopes:\n\n| Scope   | Description                            |\n| ------- | -------------------------------------- |\n| `full`  | Unrestricted access to all operations  |\n| `read`  | Read-only access to all databases      |\n| `write` | Read and write access to all databases |\n| `admin` | Full administrative access             |\n\n### RFC Compliance\n\nThis implementation follows:\n\n- **RFC 9728** — OAuth 2.1 Protected Resource Metadata\n- **RFC 8414** — OAuth 2.1 Authorization Server Metadata\n- **RFC 7591** — OAuth 2.1 Dynamic Client Registration\n\nThe server exposes metadata at `/.well-known/oauth-protected-resource`.\n\n\u003e **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.\n\n\u003e [!NOTE]\n\u003e **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.\n\n\u003e [!TIP]\n\u003e **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`/`[]`.\n\n\u003e [!WARNING]\n\u003e **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](SECURITY.md) for details.\n\n## 📊 Benchmarks\n\nPerformance benchmarks measure framework overhead on critical hot paths using [Vitest bench](https://vitest.dev/guide/features.html#benchmarking) (tinybench). The suite validates that framework plumbing stays negligible relative to actual database I/O:\n\n- **Tool dispatch:** 11–14M ops/sec — Map-based lookup is effectively zero-cost\n- **Auth scope checks:** 6–8M ops/sec — OAuth middleware adds no measurable latency\n- **Identifier validation:** 6–7M ops/sec — SQL sanitization is near-instant\n- **Schema cache hits:** 4–6M ops/sec — metadata lookups avoid redundant queries\n- **Debug log (filtered):** 10–11M ops/sec — disabled log levels are true no-ops\n- **Code Mode security:** 1–1.3M validations/sec for typical code, blocked patterns rejected in \u003c1 µs\n- **Sandbox execution:** ~4.4–4.9K executions/sec — trivial code round-trips through V8 isolate in ~0.2 ms\n\n```bash\nnpm run bench            # Run all benchmarks\nnpm run bench:verbose    # Verbose mode with detailed timings\n```\n\n| Benchmark             | What It Measures                                                        |\n| --------------------- | ----------------------------------------------------------------------- |\n| Handler Dispatch      | Tool lookup, error construction, progress notification overhead         |\n| Utilities             | Identifier sanitization, WHERE clause validation, SQL validation        |\n| Tool Filtering        | Filter parsing, group lookups, meta-group catalog generation            |\n| Schema Parsing        | Zod schema validation for simple/complex/large payloads + failure paths |\n| Logger \u0026 Sanitization | Log call overhead, message sanitization, sensitive data redaction       |\n| Transport \u0026 Auth      | Token extraction, scope checking, error formatting, rate limiting       |\n| Code Mode             | Sandbox creation, pool lifecycle, security validation, execution        |\n| Database Operations   | PRAGMA ops, table metadata, query result processing, schema caching     |\n| Resource \u0026 Prompts    | URI matching, content assembly, prompt generation, tool indexing        |\n\n---\n\n## Contributing\n\nContributions are welcome! Please read our [Contributing Guidelines](CONTRIBUTING.md) before submitting a pull request.\n\n## Security\n\nFor security concerns, please see our [Security Policy](SECURITY.md).\n\n\u003e **⚠️ Never commit credentials** - Store secrets in `.env` (gitignored)\n\n## License\n\nThis project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.\n\n## Code of Conduct\n\nPlease read our [Code of Conduct](CODE_OF_CONDUCT.md) before participating in this project.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fneverinfamous%2Fdb-mcp","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fneverinfamous%2Fdb-mcp","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fneverinfamous%2Fdb-mcp/lists"}