05 — Credentials
The promise
No DB credential ever leaves the gateway. Not in responses, not in logs, not in errors. The agent — and the developer — has no way to obtain a connection string from this system.
What the gateway holds
For every (server, database) pair declared in config, the gateway needs:
- host, port, db name
- a Postgres (or MySQL/MSSQL) role
- the password / cert / IAM-token-issuer for that role
These come from one of four sources, resolved at config load. Unresolved references abort boot — the gateway never serves a request it can't authenticate to.
- Inline literal in
config.yaml(dev only —gateway.env: productionrejects it at boot, naming the field, never the value; applies to service-account tokens too). - Environment variable reference —
${ENV:DB_PROD_RO_PASSWORD}— resolved from the process env at startup. - File reference —
${FILE:/run/secrets/db-prod-ro-password}— read from disk at startup. Pairs with k8s sealed-secrets / external-secrets-operator / Vault Agent sidecar (all of which materialise secrets as files). Re-read on pool open so file rotation works without a restart. - Secret manager reference —
vault:secret/prod/db/ro_password,aws-sm:arn:...,gcp-sm:projects/.../secrets/.... Recognised today; backend integrations land later. Until then, the gateway refuses to start rather than failing on first DB connect.
Per-database role design
Every database gets its own Postgres role. Not one role per server. Not one role for everything.
| Aspect | Choice |
|---|---|
| Privilege | SELECT on intended schemas; nothing else by default |
statement_timeout | Set on the role (ALTER ROLE … SET statement_timeout) — defense in depth on top of the gateway's own timeout |
idle_in_transaction_session_timeout | Short — read-only debugging doesn't need long transactions |
| Row cap | Enforced gateway-side by streaming the cursor, breaking at N, and cancelling the backend so it stops generating rows nobody asked for (see below) |
| Naming | mcp_gateway_<env>_<db>_ro — boring, traceable in DB-side logs |
The repo will ship example SQL for provisioning these roles (see 09-deployment).
Row cap: cancel on truncate
row_limit must bound server-side work, not just the client-visible row count. sqlx always issues the extended-protocol portal Execute with limit: 0 (no server-side row cap — deliberate, to avoid parallel-worker pessimization), so breaking the Rust-side read loop at N does NOT stop Postgres from generating and queueing the rest of the result. The pooled connection cannot accept the next command (COMMIT included) until that queued traffic is fully read — wait_until_ready drains it silently on the next .await. That defeats the row cap on exactly the queries where it matters.
Contract:
- Applies to reads. A truncated write is drained and committed instead — rolling it back would report rows as written that were not (see 03-mcp-tools §
run_query). The byte cap (32 MiB of decoded values) truncates the same way as the row cap. - On truncation, the exec layer fires an identity-checked
pg_cancel_backendthrough the dedicated cancel pool — same mechanism used for a client disconnect, invoked inline. The backend then aborts server-side rather than continuing to produce rows nobody asked for. - The now-aborted transaction only accepts
ROLLBACK, so the exec layer follows the cancel withtx.rollback()instead oftx.commit(). It first reads the cancelled statement to its end: the driver would otherwise answer the rollback with that statement's57014and not send it until the connection is released. The rollback is attempted, and its answer waited for, before the rows are returned; it is confirmed only when that cleanup succeeds (next bullet). - Cleanup failures do not fail the request. The truncated rows already collected are the result.
pg_cancel_backendreturningfalsemeans the backend is already gone (equivalent to success) and is not logged. Neither is the cancelled statement's own57014. Cancellation execution errors, any other error the statement ends with, androllbackerrors are logged atwarnlevel for observability, never surfaced to the client — a valid truncated read must not be turned into a failure by cleanup noise. - The non-truncated path is unchanged: plain
tx.commit(), errors propagated as typedExecErrors. - A cancel only hits the query it was meant for. A PID is reused across pooled callers, so a late cancel could land on the next caller's statement. Each transaction sets
SET LOCAL application_name = 'dbmcp-<uuid>', and the cancel isSELECT pg_cancel_backend(pid) FROM pg_stat_activity WHERE pid = $1 AND application_name = $2— it fires only while that transaction is still running.
No session state survives a pooled connection
Two separate mechanisms, with different reach:
- Transaction-local pins — what a call depends on.
SET TRANSACTION READ ONLY,SET LOCAL statement_timeout,SET LOCAL application_nameandSET LOCAL standard_conforming_strings = onare issued inside each call's own transaction, so they hold on whichever backend runs the statement and end with it.standard_conforming_stringsis pinned because the SQL guard lexes string literals the way Postgres does only with it on. - Session cleanup — what a caller could leave behind for the next. Every connection returned to the gateway's pool runs
RESET ALL; RESET SESSION AUTHORIZATION; RESET ROLE; DEALLOCATE ALL; DISCARD SEQUENCES; DISCARD TEMP; SET standard_conforming_strings = on; SELECT pg_advisory_unlock_all()before the next caller gets it; a connection whose reset fails is closed, not reused.RESET ALLleavesroleandsession_authorizationalone, so both are reset by name;DEALLOCATE ALLdrops anything still prepared (the gateway's own statements are unnamed, see 03-mcp-tools), so one caller's SQL never shows up in the next caller'spg_prepared_statements;DISCARD SEQUENCESforgetslastval()/currval(), so a key one write-tier caller generated is not readable by the next;DISCARD TEMPdrops temporary tables, rows included.DISCARD ALLis not used: it cannot run inside the multi-statement batch.standard_conforming_stringsis also set at connect and at the end of this batch, as a second layer under the transaction-local pin.
Session cleanup is a guarantee only when the gateway's connection is one backend for its whole life: a direct connection, or a pooler in session mode. Behind a transaction-mode pooler the server connection goes back to the pooler's pool at COMMIT / ROLLBACK, so the cleanup batch — sent afterwards, outside a transaction — may run on a different backend from the one the caller used, and the backend the caller dirtied may next serve anyone, including a client that is not the gateway. There the gateway cannot provide session isolation; the pooler must: a server reset of DISCARD ALL applied after every transaction (PgBouncer: server_reset_query = DISCARD ALL with server_reset_query_always = 1). A transaction-mode pooler with no such reset policy is unsupported for isolation — the transaction-local pins still hold, the session cleanup does not. Operator-facing form: pooler contract.
Cost of DISCARD SEQUENCES. It also drops the sequence values a backend preallocated: a sequence declared with CACHE n (n > 1) hands each session n values at a time, and the unused remainder is thrown away at every return to the pool instead of at disconnect. A write-tier call that draws from such a sequence therefore burns up to n − 1 values, and reaches the sequence itself (a WAL-logged update) on its next nextval instead of the session cache. Sequences with the default CACHE 1, and every call that draws no sequence value, are unaffected; gaps are already permitted by sequence semantics. Isolation wins: the cache lives in the same per-session state that holds currval() / lastval(), and Postgres offers no way to forget one without the other. On YugabyteDB, where a larger cache (ysql_sequence_cache_minval, default 100) saves a round trip to the master, prefer server-side caching (ysql_sequence_cache_method=server) for sequences a write_role draws from.
Cancellation safety (src/CLAUDE.md §Cancellation safety) still holds: if the request future is dropped mid-query (agent disconnect / outer tokio::time::timeout), the CancelOnDrop guard fires pg_cancel_backend from a detached task. Disarming happens only after the inline cleanup returns, so a hang during rollback still hands the cancel off to the guard on outer-timeout kick-in.
Why not IAM auth alone?
IAM auth (AWS RDS IAM, GCP Cloud SQL IAM) is supported as a credential source — the gateway swaps in a short-lived token instead of a password — but the role concept stays. IAM auth + a role with SELECT is the recommended setup on managed Postgres.
Write access
Off by default. To enable:
- The role granted to the gateway must have the write grants — gateway will not provision them for you.
- Config must mark the
(server, database)permission entry asmode: read-write. - The permission must be scoped to a specific group, with
require_reason: truerecommended. - Audit log captures the full SQL of every write.
This is intentionally several steps so it can't be enabled by accident.
Connection pool
Per (server, database):
- Max connections in config (default 4, sized from the 2026-11-12 production baseline: per-database concurrency 0–1)
- Min connections 0 and idle timeout 5 min: the pool opens on first use and an idle gateway holds no target connection
- Acquire timeout 5 s — fail fast so the agent gets
unavailable. It is spent before the statement timeout starts, never counted against it - A separate cancel pool (
PG_CANCEL_POOL_SIZEconnections, default 2, lazy) carriespg_cancel_backend, so cancels never queue behind the queries they are cancelling - Mongo: the same sizing, plus a 5 s server-selection and connect timeout
- Redis:
max_connectionsandidle_timeout_sas above;min_connectionsis ignored (nothing is opened ahead of use). One connection per in-flight command (no shared multiplexed connection). A connection returns to the pool only after a complete reply or a server error reply; one hit by a timeout, a client disconnect or an I/O error is closed, never reused — its reply may still be in flight. A connection the server closed while idle fails that one call withunavailable; there is no retry - YugabyteDB (as
kind: postgres): the Postgres pool unchanged. On release a connection gets the same reset as Postgres; a server without advisory locks rejects the unlock asfeature_not_supported, and the gateway then repeats the resets without the unlock and keeps the connection (since 2.0.1) - TLS required by default; reject non-TLS unless explicitly opted out for local dev
Rotation
A rotated password needs no restart. When the target rejects the credentials (SQLSTATE class 28 on Postgres and YugabyteDB, an authentication error on Mongo, WRONGPASS / NOAUTH at connect on Redis), the adapter for that (server, database) is marked stale and the registry replaces it on the next call, resolving the password reference again — so a rewritten ${FILE:…} mount takes effect on its own. The call that hit the rejection fails unavailable; the next one uses the new password. On Postgres the two tiers of a database with a write_role go stale apart: the write tier resolves write_password when the first call needs it (a write, or a db_activity / cancel_query reaching another replica's writes) and is replaced on its own when the target refuses it, so a write credential that does not resolve or is rejected fails writes only — reads, and the read tier's pool, are untouched.
Credentials are re-read from their source on SIGHUP (config reload). Live connections aren't killed — new connections will use the new credential, old ones drain naturally. For forced rotation, restart the gateway; with two replicas, this is zero-downtime.
What this rules out
- No "share my session credential with my coworker" — there's nothing to share.
- No connection-string export tool. Ever.
- No "let me see what credential you're using" admin endpoint. Logs show role name (not password) and only to operators.
- No DSN in a boot failure. A driver connect error can quote the URL it was handed (and thus the password); the gateway logs the error type only and exits with a credential-free message. Same discipline as the admin handlers.