safesql-mcp
Connects to a PostgreSQL database via a postgres:// URL and exposes the same exploration and query tools — schema overview, table descriptions, sampling, capped read-only queries with bind parameters, EXPLAIN plans with index hints, table profiling, relationship diagrams, exports and audit logging — with reads executed inside a READ ONLY transaction with statement_timeout and a SQL guard blocking dangerous statements.
Connects to a SQLite database file (opened read-only with query_only enforced by default) and lets the assistant explore and query it: list tables, describe columns/keys/indexes, get a compact schema overview, search the schema, sample rows, run read queries with row/byte/time caps, explain query plans with tuning hints, profile tables for data quality, show foreign-key relationships, export results, and keep a saved-query library plus audit log. Writes/DDL are opt-in admin mode with dry run and confirm token.
This server does not currently have a deployable release on Glama. Follow the repository's setup instructions to install and configure it for your MCP client, including any required credentials and local dependencies.
safesql-mcp
Safe SQL for AI assistants. SQLite and PostgreSQL in one zero-config MCP server, read-only by default.
An MCP server that lets Claude, Cursor, VS Code, Windsurf and other AI
tools explore and query your databases without being able to damage them. Point it at a SQLite file or a
postgres:// URL and you are done.
You: Which countries bring in the most revenue from delivered orders?
Claude: (calls query)
5 rows in 3 ms
country | customers | revenue
FR | 19 | 32265.61
DE | 17 | 30375.97
BR | 19 | 26634.39
...Why this one
The official Postgres and SQLite reference servers were archived in 2025, and most replacements either
handle a single engine, dump large JSON blobs into the context window, or trust the model not to run
UPDATE without a WHERE. safesql-mcp is built around three ideas:
Safety is enforced by the database, not by hope. Reads run on a SQLite connection opened read-only with
query_only, or inside a PostgreSQLREAD ONLYtransaction withstatement_timeout. A SQL guard on top blocks multi-statement smuggling,SET,COPY,DO,ATTACH, file and network functions and more. Writes are opt-in, previewed in a rolled-back transaction, and need a confirm token.Token-efficient output. The whole schema of the demo database (6 tables, keys, types, nullability, foreign keys and row counts) is 701 characters. The same schema as
information_schema.columnsJSON is 31,695 characters (45x more). Results are compact pipe tables with row, byte and cell caps.One drop-in server for several databases.
npx -y safesql-mcp ./app.db postgres://...connects both at once. No config file, no API keys, no native build step (SQLite uses Node's built-innode:sqlite).
Related MCP server: sql-explorer
Quickstart (1 minute)
You need Node.js 22.16 or newer.
npx -y safesql-mcp demo # creates ./safesql-demo.db (a small online shop)
npx -y safesql-mcp init claude ./safesql-demo.db # or: cursor, vscode, windsurf, claude-code, allRestart the app and ask: "Give me a tour of this database" or "Which products sell best in Germany?"
Use your own database instead:
npx -y safesql-mcp init cursor ./data/app.sqlite
npx -y safesql-mcp init claude "postgres://reader:secret@localhost:5432/app"
npx -y safesql-mcp init all main=./app.db analytics=postgres://reader@db/warehouseCheck everything is wired up correctly (connection, read-only enforcement, role privileges):
npx -y safesql-mcp doctor ./app.dbNot on npm yet? Run from source:
git clone https://github.com/cryptodeta/safesql-mcp && cd safesql-mcp && npm install && npm run build, then usenode /path/to/safesql-mcp/packages/server/dist/cli.jswherever this README saysnpx -y safesql-mcp.
Client configuration
init writes these for you (and keeps a .bak of the old file). On Windows it uses "command": "cmd"
with "args": ["/c", "npx", "-y", "safesql-mcp", ...].
claude_desktop_config.json (macOS: ~/Library/Application Support/Claude/, Windows: %APPDATA%\Claude\):
{
"mcpServers": {
"safesql": { "command": "npx", "args": ["-y", "safesql-mcp", "/absolute/path/to/app.db"] }
}
}claude mcp add safesql -- npx -y safesql-mcp /absolute/path/to/app.db~/.cursor/mcp.json (global) or .cursor/mcp.json (project):
{
"mcpServers": {
"safesql": {
"command": "npx",
"args": ["-y", "safesql-mcp"],
"env": { "DATABASE_URL": "postgres://reader:secret@localhost:5432/app" }
}
}
}.vscode/mcp.json:
{
"servers": {
"safesql": { "type": "stdio", "command": "npx", "args": ["-y", "safesql-mcp", "${workspaceFolder}/app.db"] }
}
}~/.codeium/windsurf/mcp_config.json:
{
"mcpServers": {
"safesql": { "command": "npx", "args": ["-y", "safesql-mcp", "/absolute/path/to/app.db"] }
}
}Tip: keep passwords out of config files by using env with DATABASE_URL or SAFESQL_DB_<NAME>.
Tools
Tool | What it does |
| Connected databases, engine, mode, limits and policy (credentials hidden) |
| Tables and views with row counts, filter by schema or pattern |
| Columns, types, PK, FKs, defaults, indexes, "referenced by"; several tables per call |
| Entire schema in one compact block within a character budget |
| Find tables/columns by name or comment, with did-you-mean |
| A few (or random) rows, optional columns and filter |
| One read statement with bind params, row/byte/time caps, |
| Query plan plus plain-language hints (full scans, missing indexes, sorts, bad estimates); |
| Per-column nulls, distinct, min/max/avg, top values and data-quality notes |
| Foreign keys as a Mermaid |
| Save full results to CSV, JSON, JSONL or Markdown inside the export directory |
| List, save and delete named read queries |
| Recent statements, row counts, timings, errors and blocked attempts |
| Only in write/admin mode: INSERT/UPDATE/DELETE (and DDL in admin mode) with dry run and confirm token |
Also: MCP resources safesql://databases, safesql://{db}/schema, safesql://{db}/table/{table}, and
prompts explore_database, optimize_query, data_quality_check, safe_change.
Sample outputs
schema_overview on the demo database:
shop (sqlite, read mode): 6 tables/views. Legend: * = primary key, → = foreign key, ? = nullable, ~n = rows
api_keys ~40: id* int, customer_id int→customers, label text, token text, created_at text
customer_revenue (view): id int?, name text?, country char(2)?, orders any?, revenue any?
customers ~200: id* int, name text, email text, country char(2), created_at text, password_hash text
order_items ~2540: order_id* int→orders, product_id* int→products, quantity int, unit_price real
orders ~1000: id* int, customer_id int→customers, status text, created_at text, total real
products ~28: id* int, name text, category text, price real, in_stock boolSecrets are masked automatically, even when aliased:
2 rows in 0 ms
name | email | password_hash
Lucas Silva | lucas.silva1@example.com | [redacted]
Arjun Kim | arjun.kim2@example.com | [redacted]
Redacted: password_hashexplain with hints:
SCAN order_items
USE TEMP B-TREE FOR ORDER BY
Hints:
- Full scan of order_items (~2540 rows). If the query filters or joins on a column of order_items, an index on that column avoids reading every row.
- Sorting in a temporary B-tree for ORDER BY. An index whose columns match the ORDER BY order removes this step.A write in --write mode (step 1, dry run):
DRY RUN (rolled back, nothing changed): UPDATE would affect 5 rows in shop.
Preview of affected rows (after the change):
id | name | category | price | in_stock
9 | SQL Basics | Books | 102.98 | 1
10 | Data Modeling Patterns | Books | 139.48 | 1
11 | The Query Optimizer | Books | 91.23 | 1
…
To apply it, show this preview to the user and, if they agree, call execute again with the same SQL and confirm="BAowmRSn" (valid 10 min, single use).Errors say what to do next:
Error [BLOCKED]: DELETE without a WHERE clause would change every row of orders.
Hint: Add a WHERE clause. If changing every row is really intended, pass allow_full_table=true (a dry run is still required).
Error [SQL_ERROR]: no such table: ordrs
Hint: Did you mean "orders"?Safety model
Every statement passes through these layers. Each one alone blocks the common accidents; together they make the read path safe even if one layer had a bug.
SQL guard (tokenizer that understands comments, strings, quoted identifiers and dollar quoting): exactly one statement per call; classifies it as read, write or DDL; always blocks
SET/RESET, transaction control,COPY,DO,CALL,LOCK,ATTACH/DETACH,VACUUM,GRANT/REVOKE,PREPARE/EXECUTE, PRAGMA assignments,SELECT ... FOR UPDATE,SELECT ... INTO, roles, databases, extensions andALTER SYSTEM; blocks functions with side effects or hidden SQL (pg_read_file,lo_export,dblink,set_config,query_to_xml,pg_terminate_backend,load_extension,writefile, ...). Data-modifying CTEs andEXPLAIN ANALYZE <write>are treated as writes.Engine-level read-only. SQLite reads use a separate connection opened with
readOnly: trueplusPRAGMA query_only = ONandtrusted_schema = OFF. PostgreSQL reads run inBEGIN TRANSACTION READ ONLYwithSET LOCAL statement_timeout,lock_timeoutandidle_in_transaction_session_timeout, and take a snapshot before your SQL runs so the transaction cannot be switched back to read-write. Every read transaction is rolled back.doctorproves this by attempting a write on the read path and checking that the database refuses it.Hard limits. Rows per page (default 100,
offsetto continue), bytes per response (60 KB), cell length (300 chars), and a timeout (15 s). PostgreSQL cancels withstatement_timeout; SQLite runs in a worker thread that is terminated on timeout, so even a runaway recursive CTE stops on time.Policies.
--allow-tables,--deny-tablesand--deny-columns(globs likeaudit_*,*.ssn) are checked against the query plan, not just the text: SQLite bytecode (EXPLAIN) and PostgreSQLEXPLAIN (VERBOSE)reveal every table and column a query touches, including through views,SELECT *, CTEs and subqueries. Denied tables and columns are hidden from all schema tools.Redaction. Columns that look like secrets (
password,token,secret,api_key,ssn,card_number,cvv,salt, ...) are replaced with[redacted], matched by the result column's source column, soSELECT password_hash AS xis masked too. Add your own with--redact-columns, mask e-mails with--mask-emails, or turn auto-redaction off with--no-redact.Writes are opt-in and two-step. Start with
--write(data) or--admin(data and schema). Theexecutetool first runs the statement in a transaction, reports affected rows and a preview of the changed rows (viaRETURNING), rolls back and returns a single-use token bound to that exact SQL and parameters. Only a second call with the token commits.UPDATE/DELETEneed a realWHERE(1=1,TRUE,x = xand... OR 1=1do not count); changes above--max-affected(default 1000) are rolled back. Theexecutetool is not even registered while every database is read-only.Audit log. Every statement, including blocked ones, is appended to
~/.safesql-mcp/audit.jsonl(tool, SQL, row count, affected rows, duration, error). Bind parameter values are never logged.No credential leaks. Connection URLs are shown with
***for the password, and every tool response is scrubbed of known passwords.
Hardening PostgreSQL (recommended)
The server already enforces read-only access, but a dedicated role adds a second, independent layer:
CREATE ROLE ai_reader LOGIN PASSWORD 'change-me';
GRANT pg_read_all_data TO ai_reader; -- PostgreSQL 14+; otherwise GRANT SELECT per schema
ALTER ROLE ai_reader SET statement_timeout = '15s';doctor warns when the configured role is a superuser or can write to tables.
Configuration
Databases come from (in order) a config file, command-line arguments, SAFESQL_DB_<NAME> variables and
finally DATABASE_URL. Names default to the file name or database name; use name=<url> to choose.
Option | Env | Default | Meaning |
|
| read | Allow data changes / also schema changes |
|
| 100 | Rows per query page (max 10,000) |
|
| 15000 | Statement timeout |
|
| 1000 | Larger writes are rolled back |
| 60000 | Approximate bytes of rows per response | |
| Only these tables are visible | ||
| Hide these tables | ||
| Hide these columns ( | ||
| Mask these columns in results | ||
| auto | Turn off automatic secret masking | |
|
| off |
|
|
|
| Where |
|
|
| JSONL audit log |
|
|
| JSON config file |
|
| 3000, 127.0.0.1 | Streamable HTTP transport |
|
| Require |
A config file gives per-database settings, ${ENV} interpolation and saved queries
(see examples/safesql.config.json):
{
"databases": {
"shop": { "url": "./shop.db", "denyColumns": ["customers.password_hash"] },
"warehouse": { "url": "${WAREHOUSE_URL}", "allowTables": ["reporting.*"], "timeoutMs": 30000 },
"staging": { "url": "postgres://app@localhost/staging", "mode": "write", "maxAffectedRows": 100 }
},
"queries": {
"daily_signups": {
"db": "warehouse",
"sql": "SELECT date_trunc('day', created_at) d, count(*) FROM reporting.users GROUP BY 1 ORDER BY 1 DESC LIMIT 30"
}
}
}HTTP and Docker
npx -y safesql-mcp --http ./app.db --port 3000 # MCP endpoint: http://127.0.0.1:3000/mcp, health: /health
docker build -t safesql-mcp .
docker run -p 3000:3000 -e SAFESQL_HTTP_TOKEN=change-me -e DATABASE_URL=postgres://reader:pw@host/db safesql-mcp
docker run -p 3000:3000 -e SAFESQL_HTTP_TOKEN=change-me safesql-mcp --http examples/shop.db # bundled demo dataThe HTTP transport is stateless and shares one connection pool and schema cache across requests. Set a token whenever the port is reachable by anyone but you.
CLI
safesql-mcp demo [file] # sample SQLite shop database
safesql-mcp demo --sql postgres | psql "$URL" # the same data for PostgreSQL
safesql-mcp schema ./app.db # compact schema overview
safesql-mcp query ./app.db "SELECT count(*) FROM users" --format csv
safesql-mcp doctor ./app.db postgres://... # diagnose setup
safesql-mcp tools # list MCP toolsPerformance
Measured on a laptop-class Linux box with Node 24 (node:sqlite, SQLite 3.53) and PostgreSQL 17 on localhost:
Operation | Time |
Indexed point query, SQLite, through the full guard + worker path | ~0.1 ms |
Indexed point query, PostgreSQL (read-only transaction per query) | ~0.4 ms |
| ~110 ms |
| ~1 ms |
The published package is about 165 KB of JavaScript with four small runtime dependencies (@modelcontextprotocol/sdk,
zod, pg and pg-cursor), all pure JavaScript.
Limitations
Engines: SQLite and PostgreSQL only. MySQL/MariaDB are not supported yet.
Node.js 22.16+ is required because SQLite uses the built-in
node:sqlitemodule (no native compile). On Node 22 it may be marked experimental; the server silences that warning.Policies on PostgreSQL are checked with
EXPLAIN (VERBOSE). Functions that read tables internally (for example user-definedSECURITY DEFINERfunctions) are not visible in the plan. If you need hard guarantees for sensitive tables, also restrict the database role.Redaction works on result columns that come straight from a table column (aliases included). An expression such as
upper(password)is not masked; use--deny-columnsfor columns that must never be read.SELECT *on a table with a denied column is refused (with the list of allowed columns), not rewritten.SQLite timeouts terminate the worker thread, so the first query after a timeout reopens the file (a few milliseconds).
offsetpaging re-runs the query and skips rows; for deep pagination prefer keyset filters (WHERE id > ...).Not published to npm yet; use the from-source instructions above until it is.
Development
git clone https://github.com/cryptodeta/safesql-mcp && cd safesql-mcp
npm install
npm run check # lint + typecheck + tests + build + stdio/HTTP smoke test
SAFESQL_TEST_PG_URL=postgres://postgres:postgres@localhost:5432/postgres npm test # include PostgreSQL testsSee CONTRIBUTING.md for the layout and guidelines.
License
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
This server cannot be deployed
Maintenance
Related MCP Connectors
Safe, read-only Postgres and MySQL access for AI agents. Audit log + column-level controls.
Query 40 databases from Claude, ChatGPT, or Cursor — on any device. Read-only, encrypted, audited.
Query PostgreSQL databases in plain English — LLM-generated, safety-validated SQL.
Query Postgres, MySQL, SQL Server, Oracle, BigQuery, ClickHouse and Redshift from your AI client.
Related MCP Servers
- AlicenseNot gradedqualityNot gradedmaintenanceProvides AI assistants with safe, controlled access to PostgreSQL databases with read-only defaults, granular permissions, query safety features, and schema introspection capabilities.1-
- FlicenseAqualityDmaintenanceEnables AI assistants to query SQLite databases using plain language, with strict read-only enforcement and column-level access control to prevent damage or unauthorized data reads.4-
- AlicenseAqualityBmaintenanceEnables AI agents to inspect database schemas and run strictly read-only SQL queries with guardrails against destructive statements, multi-statement chaining, and unbounded scans. Supports SQLite natively and PostgreSQL optionally.4137 PyPIMIT
- AlicenseNot gradedqualityBmaintenanceEnables AI assistants to explore and query PostgreSQL or SQLite databases read-only, with SQL allow-listing, automatic row limits, statement timeouts, column masking, per-tool rate limits and JSONL audit logging.MIT