
How to Build a Secure Database MCP Server for PostgreSQL and SQLite in Python
Building a scoped database MCP service without granting raw SQL access
A local AI coding assistant does not need arbitrary database credentials to answer a schema question. Treat an MCP tool as a narrow capability: for example, list a small set of approved tables in a fixed database, rather than accepting a model-supplied filesystem path or arbitrary SQL statement.
Revised November 12, 2026: The earlier code interpolated model-controlled SQLite paths into a URI, had a PostgreSQL DSN disconnected from the advertised environment variable, and described read-only mode as equivalent to immutable storage and full information isolation. Those protections were overstated. The following examples are design fragments for a controlled deployment, not a production-ready exposed MCP server.
1. Pick the capability and data boundary first
| Requirement | Safer design | Do not assume |
|---|---|---|
| Inspect approved SQLite schema | Configure the exact database file outside model-controlled input | Any readable file on the host is authorized |
| PostgreSQL schema lookup | Use a dedicated account with verified minimum privileges | A role name or read-only transaction prevents all data disclosure |
| User-supplied table name | Map to an administrator-owned allowlist | Arbitrary quoted identifiers are harmless |
| Agent response | Bound row counts, bytes and operation duration | LIMIT alone bounds execution time or size of values |
| Tool transport | Local stdio for a trusted client with no public port | Local execution automatically isolates OS permissions |
The SQLite URI filename documentation explicitly distinguishes mode=ro (open for read-only access) from the separate immutable=1 parameter. A read-only SQLite connection does not stop another program from writing the same database file, and an immutable flag must not be set on a database that can change.
2. A bounded SQLite diagnostic fragment
The Python sqlite3 reference documents opening URI filenames with the uri=True option. The following code operates on an administrator-selected local database only; it does not accept a path or SQL text from the agent:
from pathlib import Path
from urllib.parse import quote
import sqlite3
# Edit this fixed, operator-approved location to match your deployment.
DB_FILE = Path("/srv/approved-data/catalog.sqlite3")
resolved = DB_FILE.resolve(strict=True)
if not resolved.is_file():
raise ValueError("Approved database must be a regular file")
# URI-encode the fixed filesystem path; never concatenate model input.
uri = "file:" + quote(str(resolved), safe="/") + "?mode=ro"
with sqlite3.connect(uri, uri=True, timeout=2.0) as conn:
conn.execute("PRAGMA query_only=ON")
rows = conn.execute(
"SELECT name FROM sqlite_schema WHERE type=? ORDER BY name LIMIT 25",
("table",),
).fetchall()
print([name for (name,) in rows])
This is an unexecuted illustrative query requiring an existing authorized database file. It does not bound all resource consumption, hide sensitive schema names, or prevent a privileged external process from changing the file. Apply filesystem permissions, access approval and a task-specific output policy separately.
The official SQLite query_only pragma describes a per-connection guard on write statements. Do not describe it as an access-control boundary for arbitrary files, virtual tables, ATTACH, extensions or external operating-system writes. The service process should not have filesystem access to unrelated secrets.
3. PostgreSQL needs enforced role privileges
If PostgreSQL is the backend, have an operator verify that the configured connection string really comes from the intended secret manager or environment variable. Do not hardcode a fallback DSN or embed working credentials in a published MCP example.
The PostgreSQL GRANT reference documents privilege grants on databases, schemas and objects. A read-only transaction setting alone is not a substitute for a least-privilege account, correctly scoped grants, no elevated role inheritance and an output policy. Confirm that future object permissions reflect the schema owners, and test with the actual configured role in a disposable database.
For a safe MCP interface, make tools fixed operations such as an operator-approved table-list or a narrow, parameterized lookup. Explicitly deny unapproved table identifiers, exports, INSERT/UPDATE/DELETE and model-provided general SQL. Do not claim arbitrary SQL is secure simply because the connection says read-only.
4. Review and verification checklist
- Identify exactly which tables and columns may be disclosed to the AI caller; a read-only database can still contain private data.
- Verify database selection comes from operator configuration, not a tool argument.
- Verify the effective database role or OS account, including indirect permissions and extension access.
- Test read-only versus write attempts in an isolated copy, not the production database. Test error behavior without logging credentials.
- Bound result size and time using the specific database’s supported mechanisms, not an untested universal timeout.
- Log only approved operational metadata and errors; never print secrets, full DSNs, or sensitive query results.
The MCP specification documents stdio and Streamable HTTP transports. Choose transport, authentication and network controls separately from database privilege controls.
Limitations: No PostgreSQL instance, SQLite production file, MCP client, network connection or privilege configuration was tested for this article. It documents the intended boundary and a fixed read-only query fragment, not the deployment of a verified secure database server.
Primary references
- SQLite file URI access modes
- Python sqlite3 URI connections
- SQLite query_only pragma
- PostgreSQL privilege GRANT
- MCP transport specification
Reviewed against current cited source documents on November 12, 2026. Original publication date preserved.