07 — Logging & Retention
Two distinct streams. Don't confuse them.
| Stream | Where | Purpose |
|---|---|---|
| Audit log | State Postgres: audit_calls (one row per call) and audit_call_intents (one row per target call, written first) | Forensic record. Synchronous, mandatory, append-only. |
| Stdout log | Process stdout, one JSON object per line | Operational observability. Ingested by Loki / Splunk / etc. via Alloy. |
The audit log is the system of record. The stdout log is a sidecar for operators; it MUST NOT be the only place a tool call leaves a trace.
What "audit log" means here
Append-only record of every tool invocation, written synchronously before results return to the agent. If the audit write fails, the request fails. There is no "best effort" audit.
Every tools/call gets one audit_calls row — including calls rejected before a tool ran (unknown tool, arguments that do not parse: outcome = invalid_arguments, server_name/database_name NULL). The one carve-out: a request shed at the concurrency caps (429 rate_limited, 503 service_overloaded) is a log line and a metric only, so overload never adds a state-DB write per rejected request (spec 03 §Errors).
Intent and completion (two-phase)
A call that reaches a target database is written twice:
- Intent — after authz, before the gateway opens the target pool, it commits an
audit_call_intentsrow:request_id,occurred_at,user_sub,user_email,tool,server_name,database_name,db_type,access(readorwrite), the caller's claimedupstream_actor/upstream_run_id(migration 0014), and thesql(capped like the completion row's,sql_truncatedwhen cut) andreasonthe completion row would carry (migration 0018), and the boundparamscapped as the completion row caps them (migration 0025). The reaper copies all of them into theabandonedrow, so a write that may have committed is still recorded with what it was. If that write fails, the call is refused withaudit_unavailableand the target is never reached. - Completion — after the tool's work, the
audit_callsrow with the outcome, under the samerequest_id. If that write fails, the client getsaudit_unavailable; a drop guard retries the row with outcomeaudit_unavailableand the tool's own outcome inerror_message.
Every target call writes an intent — reads and writes alike (owner decision, plan 101). Revisit writes-only if the benchmark shows the extra insert matters; production volume today is tens of calls a day.
Reaper. An intent with no audit_calls row of the same request_id means the gateway stopped between the two writes (crash, OOM kill, a shutdown drain that ran out of time). Every replica runs a sweep each minute under a transaction-scoped advisory lock (one sweep at a time across replicas); it writes an audit_calls row with outcome = abandoned, occurred_at from the intent, and error_message naming the access (access: write means the statement may have committed). A sweep only considers intents older than the grace — target open allowance (60 s) + statement ceiling (30 s) + two audit-write deadlines (2 × 15 s) + shutdown drain (20 s) = 140 s — so a call still running is never reaped. A sweep walks aged intents oldest first, (occurred_at, request_id) order, in batches of 10,000 from a per-process cursor, so each statement stays bounded however much retention holds and an intent already settled is never re-examined. The cursor advances only past committed batches — a failed sweep resumes where the last good one stopped, so no intent is skipped — and lives in process memory: a restarted replica catches up from the oldest intent, batch by batch.
Indeterminate writes. A write-access call that ends timeout or cancelled may have been cut off mid-commit, so its rows_affected is NULL but the change may be durable. Its error_message (and, for timeout / cancel_query, the client's message) ends with (access: write; the statement may have committed) — unless the call ran under dry_run, which rolls the transaction back and cannot commit, so its outcome is never indeterminate. A write whose COMMIT fails without a definitive answer from the server (connection lost, unreadable reply) is answered unavailable with the message connection lost during commit; the write may or may not have been applied, carrying the same note; a commit the server refused rolled back and keeps its ordinary code. A client disconnect drops the tool before it can say so; the drop guard reads the intent's access and adds the same note to the cancelled row.
Shutdown drain. The drop guard's retry, stream-sink deliveries and the exec layer's cancels run on a tracked task set, not bare tokio::spawn. After the server stops accepting work, main waits for that set for up to 20 s; anything still running past it is left to the reaper.
Client disconnect. The dispatch future is dropped; the guard writes outcome = cancelled with error_message = "client disconnected before completion".
Fields
audit_calls columns:
| Column | Source |
|---|---|
id | Gateway-minted UUID per row |
request_id | Gateway-minted UUID per request (also the x-request-id header and the dispatch log line's request_id) |
occurred_at | Server-side now() at insert |
user_sub, user_email, groups | From the session (see 04-auth-sso); groups is a JSONB snapshot at request time |
agent_client | Self-reported MCP client banner: User-Agent, else x-mcp-client, cut to the 128-byte upstream-header cap on a character boundary — one oversized banner must not make a huge row in the store or the SIEM export |
ip | Request socket, as text |
server_name, database_name | Logical names; NULL for tools that address neither, or when the arguments never parsed |
db_type | postgres / mongo / redis (the configured server.kind, so a YugabyteDB target records postgres); NULL when no backend kind was resolved: tools that take no server, and a run_scoped: true refusal (03), which comes before the server is looked up |
tool | run_query, describe_schema, …; unknown for an unknown or missing tool name |
sql | What the call read: the agent's sql argument for run_query / explain — a SQL statement on Postgres, the JSON command document on Mongo, the JSON argv array on Redis (e.g. ["HGETALL","user:1"]), as sent; schema.table for sample_table / table_stats (on Mongo, sample_table stores the find it runs, e.g. {"find":"events","filter":{}}); schema or schema.table for describe_schema (database[.collection] on Mongo); the target request_id for cancel_query; NULL for tools that read no table |
sql_truncated | sql was cut at the 64 KiB stored-SQL cap (on a character boundary) — one huge statement must not make a huge row in the store or the SIEM export |
sql_sha256 | SHA-256 of the stored sql (NULL without sql), set by a BEFORE INSERT trigger in the state DB whatever the writer sent, so every insert path — completion row, reaper, an older release mid-rollout — carries a digest that matches; get_query_history's hash filter seeks it through audit_calls_history_sha_idx. Migrations 0026 (column, trigger, backfill) / 0027 (index) |
params | The positional params of a run_query / explain call (spec 03), as the caller sent them: a JSONB array. A different shape on an admin read: an admin.audit_calls row holds the export's filters as a JSON object (user, server, db, tool, outcome, since, until, limit, include_sql), never positional params — a consumer keys on tool before reading params as an array. Under the same 64 KiB cap as sql: when the array's JSON is longer, the column holds that JSON text's prefix (cut on a character boundary) as a JSONB string — a string here is a cut array. NULL for a call without params and a call refused at the argument edge. The intent row carries them too, capped the same way (migration 0025), and the reaper copies them into the abandoned row and its stream event, so a parameterized write that may have committed keeps its values; an intent written by a release before 0025 has none. Migration 0024 |
reason | User-provided reason string, if any |
row_count | Final row count returned (after truncation) |
rows_affected | Rows a write changed (rolled back again under dry_run); NULL for reads |
upstream_actor, upstream_run_id | x-dbmcp-on-behalf-of / x-dbmcp-run-id a service-token caller claimed (14-service-tokens). Unverified — stored for attribution, never used for authz; user_sub stays service:<name>. NULL for SSO sessions |
truncated | Whether the row cap cut the result |
elapsed_ms | Wall-clock of the tool's work |
outcome | One of the closed set in Outcomes |
error_message | The sanitized message the client got — no credentials or raw connection details |
sql and params are stored verbatim up to the cap, literals included, and every stream sink carries them the same way (stdout as the JSON text, "" without params; syslog in the JSON body). The sql_capture policy (redacted / metadata-only per database) proposed with the stream sinks (#218) was never built: there is no setting that keeps literals out of audit_calls or the export. A database whose literals must not be stored should not be reachable through run_query.
Outcomes
audit_calls.outcome holds exactly one of these 16 values (src/audit/outcome.rs; spec 03 §Errors for the client-facing ones):
| Outcome | Written by | Meaning |
|---|---|---|
success | tool | The call did its work |
dry_run | tool | A write ran and was rolled back on request |
forbidden | tool | No grant allows the call |
forbidden_sql | tool | The statement guard refused the SQL |
permission_denied | tool | The target role lacks a privilege the statement needs |
undefined_object | tool | The statement names a table or column that does not exist |
invalid_arguments | tool / dispatch | Arguments failed validation, or the tool name is unknown |
reason_required | tool | The grant requires a reason and none was given |
timeout | tool | Statement timeout or wall-clock budget hit |
syntax_error | tool | The target rejected the statement |
unavailable | tool | Target unreachable, credentials rejected, or no pooled connection in time |
unsupported_backend | tool | The tool does not support that server kind |
internal | tool | Gateway bug; details in the operational log only |
cancelled | drop guard / tool | Client disconnected, or another call's cancel_query stopped it |
audit_unavailable | dispatch | The audit store refused a write; the drop-guard retry records it |
abandoned | reaper | An intent never got a completion row |
rate_limited and service_overloaded are HTTP rejections before dispatch and never reach this column (see the carve-out above).
Storage
| Tier | Where | TTL | Purpose | Status |
|---|---|---|---|---|
| Hot | Gateway's state Postgres | 90 days (configurable) | Fast operator queries, dashboards | Shipped |
| Archive | S3 / GCS / Azure Blob, optional | 1y / 7y / forever | Compliance retention | Not shipped — roadmap Phase 4 |
| Stream | Optional sink: stdout, syslog (config: logging.stream: [{kind: stdout}, {kind: syslog, host: ..., port: ..., transport: udp|tcp|tls, ca_file: ...}]), OTLP, Kafka | live | Plug into existing SIEM/Splunk/Datadog | stdout + syslog shipped (#218); OTLP/Kafka not shipped |
Hot and stream are independent — you can send everything to Splunk and keep 90 days in Postgres. A row is streamed only after its durable write commits. Every audit_calls row is streamed: tool completions, fallback rows, and the reaper's abandoned rows (sent once their batch commits). Every sink carries every audit_calls field (pinned by a parity test against the row type).
Sinks are best-effort copies. The state-DB row is the authority; a sink that cannot keep up drops rows and counts them, and never slows or fails the request. Both sinks drop rather than apply backpressure, because backpressure would put a slow log consumer on the request path.
Stdout sink. One target: "audit_stream" event per row on the gateway's JSON-per-line stdout, every row field top-level (id as audit_id, groups as a JSON array string, absent optionals as "" / 0 / false — except rows_affected, which is left out for a read because 0 is a real write count). Lines pass through the same bounded non-blocking queue as every log line; a full queue drops the line and counts it in log_lines_dropped_total (the queue cannot tell an audit line from another, so it is not in audit_stream_dropped_total).
Syslog sink. RFC 5424, MSG body = the row as JSON. transport picks the wire (default udp):
transport | Wire | Framing | Notes |
|---|---|---|---|
udp | RFC 5426 datagram | one row per datagram | Loss on a down receiver is silent |
tcp | RFC 6587 | octet counting (LEN SP MSG) | A refused or reset connection is a counted drop |
tls | RFC 5425 | octet counting | Receiver verified against ca_file (PEM, required); system roots are not trusted; the receiver's certificate must name host |
Octet counting, not newline framing: sql can carry a newline. The connection is opened once and reused; a failed send forgets it, and a stream transport reconnects and resends once. Delivery is at-most-twice, not exactly-once: a row written into a stream the receiver half-closed can be lost with no failed send, and a resend can duplicate a row the receiver already took. Consumers dedupe on the row id — id in a syslog message (the identity-only fallback below keeps it), audit_id on the stdout stream; the durable audit_calls row is the authority. A message is at most 8 KiB on every transport (rsyslog's default maxMessageSize): an oversized row has its free text cut, field by field until it fits, in the order sql, params (their JSON text's prefix, as a string), agent_client, upstream_run_id, upstream_actor, reason, error_message. Every cut field is a prefix suffixed ...[truncated]. The first pass leaves each field at least 512 bytes of JSON, so a long error_message beside a long sql loses neither; a second pass, for a row whose other fields leave no room for that, may cut a field to the suffix alone. A row still oversized (its groups or email alone pass the cap) is sent as {id, request_id, tool, outcome, error_message, message_truncated: true}, with error_message cut the same way to 512 bytes, or null. The body is a valid JSON object in every case. DNS resolution and each send have a 5 s ceiling; connecting shares one 5 s budget across the resolved addresses in order, and over TLS an address counts only once its verified handshake completes (one that accepts TCP but fails the handshake falls through to the next); a row waits at most 10 s for the connection a previous row holds, and at most 1,024 rows per sink are queued or in delivery — past that, new rows are dropped. A CA file that cannot be read or holds no certificate fails boot (or the reload). A row a sink cannot deliver increments audit_stream_dropped_total{sink="syslog"}; the error log is rate-limited to one line a minute carrying the count dropped since the last one and the transport.
Retention pruning
A background task runs hourly and deletes audit_call_intents rows, then audit_calls rows, then permissions_audit rows (the admin API's change trail, 12) older than the hot TTL — AUDIT_RETENTION_DAYS, default 90. One cutoff, read from the state DB's clock once per run, applies to every batch of every table (occurred_at for the call tables, ts for permissions_audit), so no row inside the window is ever deleted. Every expired intent is deleted before any completion: a completion is never older than its intent, so an intent that survives always keeps its completion and the reaper never records a finished call as abandoned. A run that loses the lock stops there — it never touches a later table — and the replica holding the lock finishes the job. TTL is floored at one day. Deletes run in batches of 5,000 rows, oldest first, each in its own transaction under a transaction-scoped advisory lock — a large backlog never becomes one long transaction, and a replica that finds the lock held leaves the pruning to the replica holding it. No archive tier is shipped, so nothing is exported before the delete. Pruning is logged.
The same run then hard-deletes dead permissions rows on the same cutoff: grants whose revoked_at is past it, then databases and users whose deleted_at is past it — children before parents, so the foreign keys hold. Live (not revoked, not soft-deleted) rows are never touched. A soft-deleted user or database that a grant still references is skipped and the run logs a WARN with the count; the admin API revokes a parent's grants in the transaction that soft-deletes it, so such a row can only come from a write outside the gateway. The deletion itself was already recorded in permissions_audit, which ages out on the same horizon. The batches walk partial indexes on the dead rows (migration 0020).
The MySQL permissions store is not pruned — neither its permissions_audit table (migrations-mysql/0002) nor its soft-deleted rows. The gateway never writes that store (boot rejects driver: mysql with admin.enabled); the operator's own tooling fills it and owns its retention.
What bounds every table the gateway writes
| Data | Bound | Max age |
|---|---|---|
audit_calls, audit_call_intents, permissions_audit (state DB) | hourly pruner | AUDIT_RETENTION_DAYS (default 90) + ≤ 1 h tick (+ ≤ 5 min first-tick jitter) |
sessions (incl. revoked rows — the session denylist) | auth GC, every 5 min | expires_at + 1 h grace; SESSION_TTL_HOURS ≤ 168 |
oauth_refresh_tokens, oauth_refresh_rotated | auth GC, every 5 min | chain birth + REFRESH_TTL_DAYS (default 1, ≤ 366) |
oauth_clients | auth GC, every 5 min | 90 days after last use (1 h if never authorised) |
permissions_grants (revoked), permissions_users / permissions_databases (soft-deleted) | hourly pruner, after permissions_audit | revoked_at / deleted_at + AUDIT_RETENTION_DAYS; live rows are never touched |
| Pending OAuth flows, auth codes, session cache | process memory, TTL-swept | minutes; gone on restart |
Retention surfaces outside the gateway
AUDIT_RETENTION_DAYS bounds only the live state DB. The operator must set each of these to match, or audit data outlives the window there:
- State-DB backups / snapshots / PITR WAL archives — a 1-year backup retention keeps 1 year of audit rows, however short the hot TTL.
- Stdout log stores (Loki, Splunk, CloudWatch, …) — every dispatch line and every
stdoutstream-sink row lands there under that store's own retention. - Syslog receivers / SIEM fed by the
syslogstream sink. - Error tracking (GlitchTip / Sentry) event retention.
Operator queries
Common questions, runnable directly against the state DB:
-- Who ran what against prod in the last hour?
select occurred_at, user_email, database_name, sql, row_count, outcome
from audit_calls
where server_name = 'prod' and occurred_at > now() - interval '1 hour'
order by occurred_at desc;
-- Top callers for the week
select user_email, count(*) from audit_calls
where occurred_at > now() - interval '7 days'
group by user_email order by 2 desc;
-- Find every query that touched a sensitive table
select * from audit_calls
where sql ilike '%customer_pii%'
and occurred_at > now() - interval '30 days';
-- Calls the gateway never finished recording (crash between target and audit)
select occurred_at, user_email, server_name, database_name, error_message
from audit_calls
where outcome = 'abandoned'
order by occurred_at desc;
What is not in the audit log
- The DB password / connection string. Never.
- Result row contents. Counts only.
- Anything that would re-identify a user beyond what's already in the session.
Stdout log — dispatch line contract
Every tool dispatch emits exactly one JSON-per-line record on stdout, in addition to (not in place of) the audit row. Loki / Alloy ingest this without per-line parsing; the keys are top-level and the types are stable. Operator-facing detail lives in docs/deployment/logging.md; this section is the canonical field contract.
Baseline keys on every log line:
| Field | Type | Notes |
|---|---|---|
timestamp | RFC 3339 string | Subscriber default |
level | string | INFO / WARN / ERROR / DEBUG |
message | string | Static log-line string |
The dispatch line (message = "tool dispatched") carries additionally:
| Field | Type | When set |
|---|---|---|
request_id | string | JSON-RPC request id |
user_sub | string | OIDC sub of the caller; "anonymous" on unauthenticated paths |
tool | string | Tool name (run_query, explain, …) |
server | string | Logical server name from call args, empty for tools that aren't server-scoped |
db | string | Logical database name from call args, empty for tools that aren't database-scoped |
outcome | string | The spec 03 code the client saw (success / forbidden / forbidden_sql / invalid_arguments / timeout / syntax_error / unavailable / audit_unavailable / internal / …). Emitted after the audit write, so an audit failure logs audit_unavailable |
duration_ms | integer | Wall-clock the tool itself took. 0 for outcomes where no tool work ran (e.g. forbidden before dispatch). |
access | string | write when the call ran with write access (a data write, or EXPLAIN of one, under query_write), else read |
upstream_run_id, upstream_actor | string | Only on a service-token call that claimed them; unverified |
The audit-write-failure line adds:
| Field | Type | Notes |
|---|---|---|
audit_write_duration_ms | integer | Wall-clock the failed audit insert took. duration_ms on the same line keeps the contract above — tool execution time, not audit latency. |
class | string | Credential-free cause (pool_timed_out, database/<sqlstate>, timeout, …) — never the driver error's text |
tool_outcome | string | The outcome the tool produced before the audit write failed |
Audit metrics: tool_calls{tool,outcome,access} (outcome as above; access is read, write, or unknown for a call dropped before its tool decided), audit_write_duration_seconds, audit_fallback_failures_total (a drop-guard retry that also failed — that call's row exists only if its intent is reaped), audit_stream_dropped_total{sink}.
Renames or removals of any field above are contract breaks. Additions are fine.
Error reporting (GlitchTip)
Unhandled panics and unexpected errors are shipped to a GlitchTip instance (self-hosted Sentry-compatible) for error tracking. This is a third stream, distinct from the audit log and the stdout log, and it carries no DB credentials — see the scrubber contract below.
Initialization order
Sentry inits first in fn main, before the tokio runtime is built. The init returns a guard (ClientInitGuard) bound to a variable that lives for the whole process; dropping it early stops event delivery, so it is held until main returns. Only then is the multi-thread runtime constructed and the async entry (run()) block_on'd. This guarantees a panic during runtime setup is still captured.
Configuration
| Knob | Source | Notes |
|---|---|---|
dsn | SENTRY_DSN env var | Unset / empty → client initializes disabled; the app runs normally and ships nothing. The DSN is never hardcoded. |
environment | SENTRY_ENVIRONMENT env var | Falls back to development. |
release | CARGO_PKG_VERSION | Pinned to the crate version at build time. |
send_default_pii | — | Hard-coded false. The gateway never sends PII. |
Error tracking only. GlitchTip supports neither performance tracing nor profiling nor replay. traces_sample_rate is pinned to 0.0; no spans or transactions are created. Adding tracing/profiling/replay options is a contract break against this section.
before_send scrubber (mandatory)
Every outbound event passes through a before_send hook that redacts secrets. This is defense-in-depth on top of the typed-error discipline in the stdout contract — GlitchTip payloads cross the process boundary and must never carry a credential. The hook scrubs, replacing the secret portion with ***REDACTED***:
- URL userinfo —
scheme://user:pass@host, password-onlyscheme://:pass@host, passwords containing/or@(the last@before whitespace,?or#delimits the host), and username-onlyscheme://token@host; - bare service tokens (
dbmcp_svc_…, truncated ones included), JWTs (eyJ…), andBearer …/Basic …credentials; key=value,key: valueand JSON"key":"value"assignments for the keywordspassword,passwd,pwd,secret,token,dsn,api_key/apikey,authorization,cookie,credential,private_key(plurals included, case-insensitive), with quoted values containing spaces;- by key: every value under a JSON object key that names a credential (same keyword list, matched on the key lowercased with
-/_dropped, soX-Api-Key,access_token,Set-Cookiecount), whatever its shape.
The hook serialises the whole event to JSON, walks it once, and deserialises it, so every protocol field is covered — message, logentry.message/params, culprit, transaction, fingerprint, exception type/value/module/mechanism.data, stack-frame vars, breadcrumbs, tags, user, request (headers, cookies, env), extra, contexts — including fields a future SDK adds. An event that cannot round-trip is dropped, never shipped unscrubbed.
Env keys whose values must never leak (the scrubber targets their shapes, not the values themselves):
STATE_DB_URL TARGET_DB_URL PERMISSIONS_DB_DSN OIDC_CLIENT_SECRET SESSION_SIGNING_KEY
Scrubber contract:
| Rule | Detail |
|---|---|
| Replace only the secret portion | The match is rewritten; the rest of the string is untouched. |
| Non-matching text is preserved byte-for-byte | An event that carries no secret ships exactly as the SDK built it. |
A whole field collapsing to ***REDACTED*** is a failure, not a scrub | It destroys the event and fingerprints every distinct error into one issue. |
| Patterns compile once, at boot | A pattern that does not compile aborts the process — a scrubber that cannot scrub is a build defect, and the gateway must not open an event stream it cannot clean. |
The regex features the patterns use are named explicitly | unicode-case for (?i), unicode-perl for \w / \s / \b. |
bin/check-scrub-features asserts those features in the no-dev-dependency graph | That is the graph the release image builds; dev-dependencies mask a missing feature from cargo test. |
Runtime injection
The DSN is injected at runtime via a Kubernetes sealed-secret (not baked into the image). Operator setup lives in deployment/logging. With no secret mounted, SENTRY_DSN is absent and the client is a no-op — a missing GlitchTip config must never prevent the gateway from serving traffic.