safe-db-mcp
You can safely explore and query SQLite databases read-only through four tools, with every query parsed, capped, timed, and audited.
Discover databases —
list_databasesreturns each available database with a short description and table count.Inspect schemas —
describe_schemareturns tables, columns, types, primary keys, foreign keys, row counts, and sample rows (optionally scoped to one table, or withsample_rows=0to skip samples).Run read-only queries —
run_queryexecutes a single SELECT/WITH statement and returns columns, rows, row count, timing, and truncation status, withmax_rowscontrol.Explain query plans —
explain_queryshows SQLite's plan for a SELECT without executing it, useful for debugging slow queries.Stay safe — only read-only statements are allowed (no writes, ATTACH, pragmas, or multi-statement chains); a LIMIT is injected (default 100, hard cap 1000), queries time out, oversized cells are truncated, and every call—allowed or blocked—is audit-logged.
Recover from errors — malformed queries or unknown columns return "did you mean" hints via edit-distance matching.
Enables safe querying of SQLite databases, with every query validated, forced read-only, row-capped, time-limited, and logged.
Click on "Deploy Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@safe-db-mcp show me the top 10 customers by total sales"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
safe-db-mcp
A read-only MCP server that lets an AI client query SQLite databases safely — every query parsed, forced read-only, row-capped, time-limited, and logged — plus an eval harness that measures how accurately a model answers benchmark questions through that server, and a dashboard to explore it all.
Live demo: coming soon · Demo:
docs/demo.gif(added at deploy)
Why
Giving a model raw database access is risky: it can write, drop, exfiltrate whole tables, or
hang the database with a runaway query. safe-db-mcp is the narrow waist in between. The model
only ever sees four read-only tools — list_databases, describe_schema, run_query, and
explain_query — and every call goes through a safety layer before it touches SQLite:
Read-only. Statements are parsed with
sqlglot; onlySELECT/WITH(and set operations) are allowed. Anything that writes, attaches, pragmas, or chains multiple statements is rejected before execution.Bounded. A
LIMITis injected if missing (default 100, hard cap 1000), queries run under a wall-clock timeout, and oversized cells are truncated.Observable. Every query — allowed or blocked — is written to an append-only audit log with the SQL, status, row count, and timing.
Helpful. On a malformed query or unknown column the server returns a "did you mean" hint (closest table/column by edit distance) so the model can recover instead of guessing.
Related MCP server: sqlite-mcp
The eval — does safe querying still work?
A safety layer is only worth it if a model can still get the right answer through it. The harness measures that on a reproducible slice of the Spider text-to-SQL benchmark (seed 42; 30 tune / 20 holdout questions across several databases).
For each question the agent is given only the MCP tools and the plain-English question. It explores the schema, writes SQL, runs it, recovers from errors, and returns an answer. We compare the result set (not the SQL string) against the gold query's result — order-insensitive unless the question implies ordering.
Baseline (tune split, Claude Sonnet)
Metric | Value |
Execution accuracy | 42.3% (11 / 26 scored) |
First-try-valid rate | 92.3% |
Recovery rate (after a bad first query) | 50% |
Blocked-query rate | 0% |
Mean tool calls / question | 3.2 |
4 of the 30 questions are excluded as unscorable (their gold query returns an empty result on
the shipped database — a known Spider flight_2 whitespace quirk — so there is nothing to match
against). Accuracy is computed over the 26 scorable questions. Accuracy by difficulty:
easy 62.5%, medium 50%, hard 0%, extra 28.6%. The remaining misses are genuine (e.g. mis-reading
"on average", returning ties without a LIMIT); see docs/PROBLEMS_LOG.md.
Reproduce it — no API key, no tokens
The baseline run is committed along with its LLM cache, so CI (and you) can replay it exactly with no model call and no key:
make eval # replays the committed cache, recomputes 42.3%, fails on >3pt regressionlive mode calls the model and record writes the cache; replay (above) is deterministic.
See docs/USAGE.md for running your own experiments and the holdout split.
Dashboard
A Next.js app (in web/) over the FastAPI backend (src/safedb/api.py):
Try it — ask a plain-English question and watch each tool call stream back live (SSE), ending in the answer, the SQL, and the result table. Capped at 10/visitor and 150/day.
Eval — browse runs, metric cards, and every question that passed or failed with the model's SQL next to the gold SQL.
Audit log — every query the server saw, including blocked ones, with status and timing.
Architecture
Next.js dashboard ──HTTP/SSE──▶ FastAPI (api.py) ──▶ agent loop ──MCP/stdio──▶ safedb server
web/ read + /ask eval/ + agent.py safety + audit + SQLitesrc/safedb/— the MCP server (server.py), safety validator (safety.py), audit log (audit.py), the per-turn agent loop (agent.py), the neutral LLM client with Claude↔Gemini fallback (llm_client.py), and the HTTP backend (api.py).eval/— slice builder, scorer, orchestrator, and the Claude Agent SDK runner.web/— the dashboard.
LLM backends (bring your own key). The MCP server needs no model; only the agent/eval/demo
layer calls one. Pick a backend in .env (see .env.example):
anthropic_api— your own Anthropic API key (ANTHROPIC_API_KEY). Recommended for anything hosted. Falls back to Gemini if the Anthropic call fails or is over budget.gemini— your own Gemini API key (GEMINI_API_KEY).claude_sdk— a localclaude loginsession, no key. Local dev only.
The key is yours and lives only in the gitignored .env; nothing is committed. See
DECISIONS.md.
Quick start
make setup # create the virtualenv, install the package, download Chinook
make run # start the MCP server over stdio
make api # start the FastAPI backend on :8000
make test # run the test suite
make lint # ruff lint + format check
make eval # replay the committed baseline eval + regression gate
cd web && npm ci && npm run dev # dashboard on :3000Docs
docs/USAGE.md— install and usagedocs/PROJECT_A.md— full specificationdocs/VERIFY.md— per-phase verification checklistdocs/PROBLEMS_LOG.md— problems hit per phase and how they were solveddocs/related-work.md— how this compares to prior text-to-SQL workdeploy/README.md— self-hosted Ubuntu + nginx bring-up
Licence
MIT. See LICENSE. Bundled data (Chinook, Spider) is downloaded locally and never
committed; see DATA_SOURCES.md.
Available Tools
4 toolsdescribe_schemaA
Return the tables, columns, keys, and a few sample rows for a database. Call this before writing SQL so you use real table and column names. Pass a table to inspect just one, or sample_rows=0 to omit the samples.
Inputs: database (required), table, sample_rows. Returns: tables, database
explain_queryA
Return SQLite's query plan for a SELECT without executing it. Use it to check how a query will run or to debug a slow one. The same validation as run_query applies.
Inputs: sql (required), database (required). Returns: ok, hint, plan, message, +1 more
list_databasesA
List the databases available to query, with a short description and table count for each. Call this first to discover what you can query.
Inputs: no named parameters. Returns: databases
run_queryA
Run a single read-only SELECT against a database and get the rows back. The query is rejected if it is not one read-only statement, and results are capped and may be truncated. Call describe_schema first to get exact table and column names.
Inputs: sql (required), database (required), max_rows. Returns: ok, hint, rows, columns, +5 more
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
TDQS
Scored across 4 tools
Each tool has a clearly distinct role: discovery, schema inspection, query execution, and query-plan explanation. The boundaries between describe_schema and explain_query are especially clear because one describes table structure while the other reports SQLite's execution plan.
All four tools follow a consistent snake_case verb_noun pattern: list_databases, describe_schema, run_query, explain_query. There are no mixed conventions or vague names.
Four tools is well-scoped for a read-only database exploration server. Each tool earns its place by covering a distinct step in the workflow without adding redundant operations.
The surface fully covers the intended read-only workflow: discover databases, inspect schemas, run SELECT queries, and explain query plans. Write operations are intentionally absent, consistent with the safe-db-mcp purpose.
Maintenance
Related MCP Connectors
Text-to-SQL MCP server: read-only queries on PostgreSQL, MySQL and SQL Server with your real schema
Hosted SQL Server MCP server for Claude, ChatGPT and Cursor, with each action switched per account.
Query, join, profile, clean and convert CSV/JSON/Parquet with server-side DuckDB over MCP.
Query your warehouse or a CSV with Claude/ChatGPT over MCP, governed by table-level ACL + audit.
Related MCP Servers
- FlicenseNot gradedqualityDmaintenanceAn MCP server that provides safe, read-only access to SQLite databases through MCP. This server is built with the FastMCP framework, which enables LLMs to explore and query SQLite databases with built-in safety features and query validation.108-
- AlicenseNot gradedqualityDmaintenanceAn MCP server that enables AI agents to interact with SQLite databases by querying schemas, executing SQL, and inspecting table metadata. It supports safe database access through configurable read-only modes, query timeouts, and dry-run execution plans.MIT
- AlicenseAqualityBmaintenanceRead-only MCP server for querying PostgreSQL, MySQL, and SQLite from AI agents — multi-database, safe by default.4268 npm1ISC
- AlicenseNot gradedqualityDmaintenanceA read-only MCP server that enables LLMs to safely explore and query any SQLite database via natural language. It exposes tools for listing tables, describing schemas, and executing SELECT/WITH queries with built-in safety guards like write prevention and row limits.MIT