03 — MCP Tool Surface
The set of tools the gateway exposes to agents. This is the agent-facing contract. Keep it small and boring.
Design rules
- Read-only by default. A write-capable tool exists only if 06-permissions explicitly enables it for the calling identity.
- Every tool accepts
server+database(exceptlist_servers/list_databases/whoami). The pair fully scopes the call. reasonis optional in the protocol but may be required by policy. If policy requires it and it's absent, the gateway returns a structured error telling the agent to ask the user for one.- Results are size-capped.
run_queryandsample_tableaccept a caller-suppliedlimit; most-restrictive-wins: the effective row limit ismin(caller.limit, grant.row_limit, gateway-ceiling). The gateway-wide ceiling is 100,000 rows and applies regardless of what the caller asks for or whether the grant setsrow_limit— an absent or oversized grant still clamps to the ceiling, never "unbounded". A grant may only tighten below the ceiling; it may not loosen past it. When neither the caller nor the grant names a limit,run_querydefaults to 1,000 rows andsample_tabledefaults to 10 rows. Results are also capped at 32 MiB of decoded values per call (exec::MAX_RESULT_BYTES), whatever the row limit: past it the gateway stops collecting and setstruncated: true, exactly as for the row cap. The cap weighs what the gateway holds in memory, not the wire form: every JSON node of a decoded row counts as one whole value (32 bytes) plus the bytes of its strings and keys, so an array of a million small integers weighs 32 MB, not 4. On Postgres a row whose wire form alone is past what is left of the budget is refused before it is decoded (see Resource safety §Memory). Mongo commands get the same row and byte budget;findandaggregatealso carry a server-side limit ofrow_limit + 1. Redis replies get the same row and byte budget; theSCANfamily also carries aCOUNTof at most 1,000. Other result-returning tools (list_servers,list_databases,describe_schema,explain) do not accept a callerlimit; they enforce internal caps sized to their output shape. - No tool exposes credentials, connection strings, or hostnames. Servers and databases are referenced by their config-defined logical name.
Handshake and tool metadata
Protocol revision 2025-06-18 only. initialize answers protocolVersion, capabilities: {"tools": {}}, serverInfo and instructions: under 2 KiB of plain text a client may put in the agent's system prompt — the call order (list_servers → list_databases → describe_schema → sample_table / run_query, explain first for a costly query, whoami for one's own grants), the sql shape per server kind (SQL / Mongo JSON command document / Redis JSON argv), which tools each kind offers, the row default and ceiling, the byte cap and the statement-timeout ceiling, when to pass reason, the error body and write field, one line of advice per actionable error code, and the overload answer below. Every number in it, and in the tool descriptions, is rendered from the constant that enforces it (src/mcp/limits.rs), never typed twice.
tools/list gives each tool a name, a human title, a description (payload shape, defaults and ceilings, the engines that offer it, the action it needs), an inputSchema (additionalProperties: false, so every accepted argument is advertised) and annotations. The hints describe what the gateway enforces; clients must not rely on them for safety:
| Tools | readOnlyHint | destructiveHint | openWorldHint |
|---|---|---|---|
list_servers, list_databases, describe_schema, sample_table, get_query_history, table_stats, db_activity, whoami | true | — | false |
explain (analyze executes the statement), cancel_query (stops a running statement) | false | false | false |
run_query (a query_write grant lets UPDATE / DELETE through) | false | true | false |
The committed snapshot tests/data/mcp/{initialize,tools_list}.json is the reviewed form of both payloads; tests/it_offline/mcp_surface.rs fails on any drift (UPDATE_MCP_FIXTURES=1 regenerates it).
Tools
list_servers
Returns the servers the caller can see — logical name, kind (postgres, mongo, redis), human description, and databases: that server's databases exactly as list_databases reports them, so one call answers where the caller can go and what it may do there. No connection info. The kind is the configured server.kind, so a YugabyteDB (YSQL) target, declared kind: postgres, reports postgres; a Dragonfly, Valkey or KeyDB target reports redis. mysql / mssql never appear: boot refuses them (08-config). A server is listed when any grant names it and an existing database (any action); its databases holds only those the caller has schema_read on (query_read / query_write imply it), so a server reached only through history_read lists an empty databases.
list_databases
Args: optional server. With server: the databases on that server the caller holds schema_read on (query_* imply it); an unknown server and one the caller has no such grant on both answer forbidden with the same message, never an empty list, so server names cannot be probed. Without server (or with no arguments at all): every such database across every server, possibly empty. Pure config and authz: no target call. Returns { "databases": [ … ] }, each entry:
| Field | Meaning |
|---|---|
server, name, description | Logical names and the configured description |
kind | The server's kind, as in list_servers |
actions | Every action the caller holds here: schema_read, query_read, query_write, history_read (an action implied by a held one is listed too) |
writes | true when a data write can succeed: a query_write grant on a Postgres database configured with a write_role |
tools | Every tool the caller can use on this database on this engine (sorted) |
limits | One entry per held action except query_write (a write runs under query_read's limits): { "action", "tools", "require_reason", "row_limit"?, "statement_timeout_ms"? }. The values are the ones the gateway enforces for a call needing that action: the most-restrictive merge of every grant that applies to that action (06-permissions), clamped like the tools clamp them. row_limit (on query_read only) is the most rows one run_query / sample_table call can return, min(grant.row_limit, 100,000); a call that names no limit still gets the tool's default (1,000 / 10). statement_timeout_ms (absent on history_read, which never reaches a target) is min(grant.statement_timeout_ms, 30,000) |
Which action each tool needs: schema_read — describe_schema, table_stats, db_activity; query_read — run_query, sample_table, explain, cancel_query; history_read — get_query_history. A tool the engine answers unsupported_backend is left out of tools (see Errors). No engine version is reported: the gateway holds none without a target call.
describe_schema
Args: server, database, optional schema (default public), optional table, optional detail (names | columns | full, default columns), optional search, optional reason. Honours the grant's require_reason constraint like every tool that reaches the target: without a non-blank reason the call gets reason_required (audited) and the catalog is never read. Schema, table and search term reach the catalog as bound values only.
detail: columns(the default, and the shape this tool always had):{ "tables": [{ "schema", "name", "columns": [{ "name", "data_type", "nullable" }] }], "truncated": bool },data_typefrominformation_schema(character varying,ARRAY,USER-DEFINED). The scan is capped at 50,000 columns; when the cap is hittruncatedistrue, tables past the cut are missing, and the table the cut fell in is dropped rather than returned with only some of its columns — every table returned is complete. Narrow withtableto see one table past the cap.detail: names:{ "tables": [{ "schema", "name", "kind" }], "truncated" },kindone oftable,partitioned_table,view,materialized_view,foreign_table; capped at 50,000 tables.detail: full: one entry per table,{ "schema", "name", "kind", "comment"?, "row_estimate", "columns": [{ "name", "data_type", "nullable", "default"?, "comment"?, "element_type"?, "enum_values"? }], "primary_key", "foreign_keys": [{ "name", "columns", "references": { "schema", "table", "columns" } }], "indexes": [{ "name", "columns", "unique", "primary", "definition" }] }.data_typeis the real type (format_type:character varying(64),integer[],myschema.mood);element_typeis set for an array,enum_values(in sort order) for an enum or an array of one.row_estimateispg_class.reltuples— the planner's estimate,nullfor a view or a table never analysed.primary_keyis the column list ornull; an index column that is an expression isnull(itsdefinitionsays what it is). Keys and indexes follow the column rule below: a primary key, index or foreign key is listed only when the read role sees every column it touches — for an index its key andINCLUDEcolumns and every column its expressions or partial predicate read, for a foreign key the columns on both sides, andUSAGEon the referenced table's schema — and is left out whole otherwise (primary_keyis thennull), never listed with a column dropped and never with adefinitionquoting a hidden column. A column'sdefault— for a generated column, its generation expression — is omitted when it reads a column the role cannot see. Capped at 2,000 tables.search: case-insensitive substring; only tables whose name, or one of whose column names the read role can see (the column rule below), contains it are listed, each whole. Blank isinvalid_arguments. Withsearchand noschema, every schema is searched.- No
schemagiven: the payload addsschemas, the schemas the read role may use (USAGE), system schemas aside.
Visibility follows information_schema: a table is listed when the read role owns it or holds a privilege on one of its columns, a column when the role owns its table or holds a privilege on it. Materialized views appear at names and full only (information_schema omits them). The audit row's sql records the scope read: schema, schema.table, or * for a search across every schema.
Mongo: schema is ignored (the database is the namespace) and table names one collection. Returns { "collections": [{ "database", "name", "type", "indexes": [{ "name", "key", "unique" }] }], "truncated": bool } from listCollections + listIndexes; type is collection, view, …, and a view has no indexes. names drops indexes; search matches collection names (and, at full, sampled field names). full adds sample: { "sampled", "fields": [{ "name", "types", "count" }], "truncated" } per collection: field paths (nested to three levels, a.b.c, at most 200) and the BSON types seen (string, int, double, objectId, date, null, …) in a bounded sample — at most 100 documents per collection, fewer under a tighter grant row_limit — with count the sampled documents in which the field was read: when the sample is truncated it is a lower bound, so a low count does not mean a sparse field. Names and type names only, never a value. Sampling reads documents, so it runs under the caller's query_read grant (its require_reason and statement_timeout_ms apply); a caller without one gets the columns shape plus note saying why the fields are missing. The types are the stored BSON element types, read from the stored BSON: an Int64 is a long, a BinData binary, and a subdocument shaped like an ObjectId's extended JSON ({"$oid": "…"}) an object. Each sample is a find through the read-only rejector, like any the caller could run; the gateway reads field names and types from the raw BSON and drops the values. What one document contributes is bounded: the first 201 fields of each nesting level, in stored order, and field names of at most 1 KiB. A document past either bound, or a sample the result budget cut short, leaves the sample truncated — never an error for the listing. A system.* collection is listed but never sampled: its sample is { "sampled": 0, "fields": [], "truncated": false, "withheld": "system collection" }. A collection the role may list but not read is listed too, its sample withheld the same way with "withheld": "not readable by the database role" — one unreadable collection never fails the call. The assembled listing is held to the 32 MiB result budget as a whole, besides each command's own cap: collections past it are left out and truncated is true. A call that samples says so in its audit row's sql: <database> [detail=full, sampled ≤ <k> docs per collection] (<database>.<collection> […] with table), k the per-collection cap that applied; the row's row_count is the collections listed. A full call answered without sampling records the plain read.
Redis: not offered — unsupported_backend. A keyspace has no catalog to describe; list keys with SCAN (MATCH, TYPE) and inspect one with TYPE through run_query.
sample_table
Args: server, database, table, optional schema, optional limit (default 10, capped; at least 1 — 0 is invalid_arguments), optional columns, optional max_bytes, optional max_cell_bytes, optional reason. Returns a small sample as a sized row result. columns keeps only the named columns, in the order named: a non-empty list of identifiers, none twice (else invalid_arguments); a name the table has no column for is undefined_object (column does not exist: <names>, after the read). On Mongo columns picks top-level fields of each document instead, and a document without a field simply omits it. The projection is applied to the sampled rows, so the gateway's 32 MiB budget still weighs every column. Useful for "what does this data look like" without writing SQL. On Mongo, table names a collection and the sample is a limited find, one document column per row; a collection name may also hold - and . after its first character (order-items, events.2024), never a trailing .. Which name rule applies depends on the server's kind, so it is checked in two steps that keep the kind from an ungranted caller: before authz every table is held to the collection rule, whatever server it names (a table breaking it is invalid_arguments naming that rule, for a configured server and an unknown one alike); after authz a Postgres table must also be an identifier (invalid_arguments naming the identifier rule), and a Mongo system.* collection is forbidden (system collections are not readable through the gateway) — server state such as system.profile (other sessions' queries) or system.js, not application data. Not offered on Redis (unsupported_backend): there is no table to sample.
Requires query_read, not schema_read. This tool returns row data, so it is authorized exactly like run_query and honours the same require_reason constraint. A schema_read grant covers metadata only (describe_schema, list_databases).
run_query
Args: server, database, sql, optional params, optional limit (at least 1 — 0 is invalid_arguments), optional dry_run, optional max_bytes, optional max_cell_bytes, optional reason. Executes under the caller's grant with statement timeout. Returns a sized row result, and rows_affected for a write (plus "dry_run": true under dry_run). The primary tool.
params binds values to $1..$n (Postgres only). A JSON array, bound in order over the extended protocol: a param is always a value, never SQL text — the guard reads sql alone, so a denied statement is forbidden_sql whatever its params, and a param holding '; DROP … is just that string. Each JSON type binds as one SQL type: null → an untyped NULL whose type the server infers from where $n stands ($1::int IS NULL), boolean → bool, integer → int8, any other number → float8, string → text, array or object → jsonb. Values travel in binary, so a string is never re-read as another type: cast in the SQL for anything else ($1::date, $1::uuid, $1::numeric). At most 100 params, each at most 64 KiB of JSON (every string inside params, object keys included, is free text up to 64 KiB at the argument edge); an integer past int8 is refused, not rounded — pass it as a string and cast it; so is any number of magnitude 2^63 or more, which the JSON parser can only hold as a rounded float (18446744073709551617, 1e19). A bound past these, or any params on a Mongo or Redis target (`params` is not supported for mongo), is invalid_arguments, after authz. A read run through the text cast is described and run with the caller's own params, never with made-up ones. The audit row stores the params beside sql (07-logging-retention).
sql carries the target's own query language. One argument, three shapes, picked by the server's kind:
kind | sql carries | Example |
|---|---|---|
postgres (PostgreSQL, YugabyteDB YSQL) | one SQL statement | SELECT count(*) FROM users |
mongo | a JSON-encoded command document | {"find":"users","filter":{"active":true}} |
redis (Redis, Dragonfly, Valkey, KeyDB) | a JSON array: the command and its arguments | ["HGETALL","user:1"] |
The rest of this section describes the SQL path; the Mongo rules are in 12-dynamic-permissions §"Mongo adapter", the Redis rules under Redis payload below.
Read vs. write is per-grant. With a query_read grant the sql guard accepts only read-only statements (SELECT / EXPLAIN). A query_write grant on the target (server, database) additionally lets a single top-level INSERT / UPDATE / DELETE through — data writes only. Schema modification (CREATE / ALTER / DROP / TRUNCATE), GRANT / REVOKE, COPY, transaction control, and multi-statement bodies are rejected in both modes; the gateway never issues DDL. Writes also require the target-DB role to actually hold write privileges — the gateway does not provision them (see 06-permissions and CLAUDE.md non-negotiable #3).
Two roles per database, one per tier. A database that accepts writes names a write_role (+ write_password) next to its read role; a query_write grant on a database without one fails boot. The access a call runs with is decided per statement: a write-tier caller's SELECT still runs as the read role inside a read-only transaction, and only a data write runs as write_role. The read tier can therefore never reach a write-capable role — the separation is role-level, not parser-level.
dry_run: true (write tier only) executes the write, reports rows_affected, and rolls the transaction back: no row change persists. It is a real execution, not a simulation: triggers fire (a side effect outside the transaction, such as a dblink call, stays done) and sequences advance (nextval is never rolled back). The response carries "dry_run": true and the audit row records outcome dry_run with rows_affected. dry_run on a read statement is invalid_arguments; on a write without a query_write grant the guard answers forbidden_sql first. Writes commit synchronously before the response returns, and every write is audited exactly like a read. Mongo and Redis targets remain read-only regardless of grant.
Read access is enforced by the database too. A query_read call runs in a READ ONLY transaction, so even a write-capable target role cannot write through it; the sql guard is the second layer, not the only one. A write is never cut short: when a RETURNING write produces more rows than the limit (or the byte cap), the gateway stops collecting, drains the rest, commits, and returns the capped rows with truncated: true and rows_affected — the number of rows the statement actually changed. A write's result always carries rows_affected; a read's never does. A read past the cap is cancelled and rolled back (nothing to lose).
Statement-timeout ceiling: every query is subject to a hard 30 s ceiling regardless of the per-grant statement_timeout_ms value. A grant may set a shorter timeout; it may not exceed 30 s — the gateway clamps it. The timeout is enforced both DB-side (SET LOCAL statement_timeout) and by a Tokio guard as belt-and-suspenders. A query that exceeds it returns timeout.
EXPLAIN ANALYZE inside sql is rejected. It executes the statement, and through run_query it would bypass the per-statement access decision. The sql guard rejects it before the query reaches the DB; the caller receives forbidden_sql. Use explain with analyze: true instead.
The guard refuses what it cannot read the way Postgres does. It decides on its own parse of sql; the target runs Postgres's. So the text is tokenized twice — by the guard's parser and by a scanner following Postgres's lexical rules — and both must put every word, quoted identifier, literal and parameter at the same bytes and agree on which bytes are comments. Anything else is forbidden_sql, with a message naming the rewrite: a comment opening directly after an operator character (1 >-- … — Postgres ends the operator at --; put a space before the comment), string literals separated only by a line break (Postgres joins them, and the continuation keeps the first part's escape rules; join with ||), Unicode-escaped identifiers (U&"…"), and any other disagreement (a backslash in X'…', 1L, b"…", a $1$ dollar tag). The statement must be read to its end: after it come only ; and comments, and a label that is a keyword is written with AS (SELECT a AS end). The price is deliberate: a few legal spellings are refused (a =-- note, 'a'⏎'b').
A call needs no parentheses, so names are checked wherever Postgres can resolve one to a call. Postgres reads (x).f and row.f as f(x) / f(row) when no such column exists. The denylist therefore applies to every name in a field-access chain and to the last part of a qualified column reference, not only to f(…). A two-part reference (t.f) can only pass t's whole row, so it is held against the families and the exact names whose function takes one row (http); an exact name no row can be passed to (t.pg_notify, r.invoke, t.setseed) is an ordinary column there. Three or more parts (t.col.f = f(t.col)) can pass any value and meet the whole list. Side effect: a qualified column whose name falls under a denied family (l.lo_revenue) is refused — a family also stands for names not listed, whose signatures are unknown; unqualified (lo_revenue) it can only be a column and passes.
Other sessions' statements are not readable. Every identity on a (server, database) shares one role, so Postgres would show each caller the others' live and recorded SQL. pg_stat_activity, pg_stat_statements, pg_prepared_statements, pg_stat_monitor, yb_terminated_queries, and the extensions' equivalents (citus_stat_activity, citus_dist_stat_activity, citus_lock_waits, citus_stat_statements, aurora_stat_activity, pg_show_plans, pg_store_plans, pg_qualstats*) are refused wherever the name is written (table, function or alias), as are the functions beneath them (pg_stat_get_activity, pg_stat_get_backend_*, pg_prepared_statement) and every relation and function in pg_cron's cron schema (cron.*), plus pg_cron's run log by its bare name (job_run_details). A bare job is not refused — the name is too common — so operator requirement: the target read role has no USAGE on schema cron (or any other extension schema storing SQL text) and none on its search_path; the REVOKEs are in target roles. pg_stat_statements_info (eviction count, last reset) shows no statement and stays readable. db_activity answers "what is running" for the caller's own requests, without query text. The gateway's own db_activity / cancel_query statements are fixed text and do not pass through the guard.
Denied functions (matched on the last name component, case-insensitively, whatever the role may execute): filesystem (pg_read_file, pg_read_binary_file, pg_stat_file, pg_ls_*, pg_current_logfile, pg_file_*, pg_logdir_ls, lo_*, loread, lowrite); session and shared state (set_config, setseed, pg_advisory_*, pg_try_advisory_*, pg_stat_reset*, pg_stat_statements_reset); other backends (pg_cancel_backend, pg_terminate_backend); messages (pg_notify, pg_logical_emit_message); SQL-text executors (query_to_xml*, cursor_to_xml*, table_to_xml*, schema_to_xml*, database_to_xml*, ts_stat, ts_rewrite, crosstab*, connectby, xpath_table, pgr_*, dblink*, treat); background and scheduled SQL (pg_background_*, schedule, schedule_in_database, alter_job, unschedule, cron.*); network (http, http_get, http_post, http_put, http_patch, http_delete, http_head, http_set_curlopt, http_reset_curlopt — the http extension and pg_net —, invoke (aws_lambda), query_export_to_s3, table_import_from_s3); replication (pg_logical_slot_*, pg_replication_slot_advance, pg_drop_replication_slot, pg_create_*, pg_copy_*, pg_replication_origin_*). With a write grant, an UPDATE of pg_settings is refused as set_config: its rule calls that function. The target relation decides, not its alias (UPDATE orders AS pg_settings passes). SELECT … INTO is refused in every spelling, the empty target list (SELECT INTO t FROM x) included.
null means SQL NULL — always. A value the gateway cannot render as JSON is never returned as null, because an agent acting on the result cannot tell a fabricated null from a real one. Such a cell comes back as {"unsupported_type": "<pg type>"} instead, naming the type so the caller can cast it (SELECT my_col::text).
Zero-row results still name their columns. A successful query that matches no rows returns rows: [], truncated: false, and columns populated with the selected column names in their left-to-right order — same shape as a non-empty result. This lets the caller distinguish "your filter matched nothing" from "that table has no such columns" without a second round-trip. The names come from the read's description, which is made before it runs (next paragraph). Reads only: a write that returns no rows (no RETURNING, or a RETURNING that matched nothing) answers columns: []. Nothing runs inside a write's transaction after the statement itself, because a failure there would abort the transaction and the commit would then silently roll the write back.
A read is described, then run, once. A Postgres read is prepared (Parse/Describe, which executes nothing) with the types its params bind with, inside its own read-only transaction, tag and statement_timeout; the same text is then parsed again, bound and executed. The description costs a warm read one round trip and one more Parse, and one catalog lookup the first time a connection returns a given table's columns. Every statement on a target connection, described or not, is the protocol's unnamed one, inside the call's transaction (what runs outside one — connect, reset, cancel — is a simple query): a name outlives its transaction behind a pooler that tracks prepared statements by their text, and the next caller of that text would be handed the old one — refused by the server after DDL (0A000 "cached plan must not change result type"). So no call ever reuses a plan the gateway made for another call. Its own can still go stale between its Parse and its Bind, which is unavailable (nothing ran), and a schema change the statement itself cannot survive (a dropped column it names) still fails it, as undefined_object. That is why the description is unconditional and nothing is cached per statement: a cache would go stale on DDL, and a first run, or "describe only after a failure", would still risk running a read twice. A column type the gateway cannot render costs one more catalog query, which says whether it needs the text cast. Before it is nested in the cast the caller's text is proven a single statement by an unnamed Parse of its own, as a cursor's query, never by an SQL PREPARE: that one would outlive a call abandoned before its DEALLOCATE on a backend a transaction-mode pooler hands to the next caller (42P05). A category-Z type (pg_node_tree) fails the driver's own description; its columns are then read from a cursor over the statement under LIMIT 0, declared with the caller's own params, which plans the statement and fetches no row; planning may still evaluate an immutable expression. A timeout, cancel, lost connection or refusal met there is the call's answer, as it would be in the read itself. Nothing is left prepared for the next caller to read in pg_prepared_statements (see 05-credentials). Writes are not described.
Rendering rules for the non-obvious types:
| Postgres type | JSON |
|---|---|
numeric / decimal | string with exactly the value's display scale, plain digits, never scientific notation: "1.50", "1.5000" for numeric(10,4), "0.00000000000000000001" — never a float, so money keeps full precision. NaN, Infinity, -Infinity as those strings |
money | string like numeric, no currency symbol or grouping: "-1234.50". The fraction digits are the session's lc_monetary (asked of the server with each transaction), so ¥ amounts have none |
timestamptz | RFC 3339 string, normalised to UTC |
timestamp / date / time | ISO-8601 string, no zone invented |
timetz | the time, then the zone it was stored with: "12:34:56.500+05:30" |
timestamptz / timestamp / date infinity, -infinity | "infinity", "-infinity" |
a date or timestamp outside years 0000–9999 | same shape with a signed year: "+294276-12-31T23:59:59.999999", "-4712-01-01" (astronomical year numbering: 1 BC is 0000) |
time 24:00:00 | "24:00:00" |
uuid | string |
bytea | Postgres' own \x-prefixed hex string |
json / jsonb | inlined as JSON. A number keeps its value: one a 64-bit float cannot hold exactly (12345678901234567890.123, 18446744073709551616) comes back as its numeral, a JSON string — the numeric rule — and so does one past the float range (1e400), in json and jsonb alike |
float4 / float8 NaN, ±infinity | "NaN", "Infinity", "-Infinity" — JSON numbers cannot hold them, and null would read as SQL NULL |
oid, xid, cid, xid8 and the reg* aliases (regclass, regtype, regproc, …) | the number: 'pg_class'::regclass is 1259 — the alias' binary form is the OID, not the name; cast to text for the name |
"char" | one-character string (relkind "r"); a byte outside ASCII as Postgres' octal escape |
name, xml, citext and other text-like types | string (YugabyteDB is built without xml: any xml value is refused there, 0A000) |
tsvector | Postgres' text form: "'it''s':1A,7 'plain'" |
pg_lsn | "16/B374D848" |
a one-dimensional array of any type above (name[], bool[], float8[], numeric[], timestamptz[], money[] …) | JSON array, each element rendered as above (elements may be null) |
interval | ISO-8601 duration, e.g. "P1Y2M3DT4H5M6.5S" |
inet / cidr | Postgres text form, e.g. "10.0.0.1", "10.0.0.0/8" |
| enums | the label, as a string |
a type with no binary output (an extension type that never wrote one) or an internal one (pg_node_tree — so pg_class.relpartbound —, pg_ndistinct, …) | its text form, as a string. Such a column would make the driver refuse the whole read, so the read runs with those columns, and only those, cast to text; SELECT * FROM pg_class works. Reads only. The cast is decided before anything runs (below), so a read runs once and a volatile function's effect never repeats |
multi-dimensional arrays, arrays of json/jsonb, ranges, composites, other user-defined types | {"unsupported_type": "…"} |
Sized row results
run_query and sample_table answer { "columns", "rows", "truncated", "row_limit", "elapsed_ms" }, plus, only when they apply:
| Field | Meaning |
|---|---|
column_types | Postgres: each column's type as the server names it on the wire (INT4, TEXT, TIMESTAMPTZ, INT8[], an enum's own name), in columns order — also for a result with no rows. Absent on Mongo and Redis |
row_limit | The effective row limit the call ran under (always present) |
truncated_by | When truncated: "limit" — the caller's limit (or the tool default) was reached, a larger limit returns more; "grant_row_limit" — the grant's row_limit or the 100,000 ceiling clipped the limit below what was asked, a larger limit will not help; "byte_cap" — the caller's max_bytes or the gateway's 32 MiB budget stopped the rows first |
hint | When truncated: how to get the rest — keyset paging (ORDER BY a unique key, then WHERE key > the last row's key; on Mongo sort and filter on _id; on Redis the reply's cursor or a narrower range) |
cells_truncated | How many cells of the returned rows max_cell_bytes replaced by the marker |
max_bytes (at least 2, the size of an empty rows array []; 0 or 1 is invalid_arguments, refused before the target is read) caps the compact JSON size of the rows array the caller receives: the leading rows that fit are kept, the rest dropped, truncated_by: "byte_cap". It weighs the JSON text, not the decoded size the gateway's own 32 MiB budget weighs, and applies after that budget, so the stricter of the two wins; a value above 33,554,432 is treated as 33,554,432. max_cell_bytes (at least 1) replaces every cell whose compact JSON is longer with {"$dbmcp_truncated": {"bytes": <the cell's JSON size>, "preview": "<at most max_cell_bytes bytes, cut on a character boundary>"}} — a string previews its own text, any other value its JSON text — row by row, each row before max_bytes weighs it; a row past the byte cut is dropped unshaped, its cells not counted. Capping a cell does not by itself set truncated, but a marker can outweigh the cell it replaces, so the byte cap applies after replacement — max_bytes, or without it the 32 MiB ceiling — and can still drop trailing rows, truncated_by: "byte_cap". Neither has a default: without them a result is exactly as before, save that the shaped rows never exceed 33,554,432 bytes of compact JSON — shaping can grow a result (a marker outweighs a short cell, JSON escaping), so that ceiling applies with or without max_bytes, truncated_by: "byte_cap".
Redis payload
sql is a JSON array — the argv a Redis client would send — e.g. ["HGETALL","user:1"] or ["SCAN","0","MATCH","app:user:*","COUNT","200"]. Elements are strings; a JSON number is accepted and sent as its decimal string.
Malformed argv is invalid_arguments. A sql that is not a JSON array, is empty, or holds an element that is not a string or number (object, array, boolean, null) — and a SCAN-family call missing its cursor or an option's value, or carrying a COUNT that is not a positive integer — is refused at the argument edge with invalid_arguments and the message "`sql`: <reason>", before the intent row and before any network call.
Deny by default. The command name (first element, case-insensitive) must be on a read-only allowlist:
| Type | Allowed |
|---|---|
| Strings / keys | GET MGET STRLEN GETRANGE SUBSTR GETBIT BITCOUNT BITPOS EXISTS TYPE TTL PTTL EXPIRETIME PEXPIRETIME DBSIZE |
| Hashes | HGET HMGET HGETALL HKEYS HVALS HLEN HEXISTS HSTRLEN HRANDFIELD HSCAN |
| Lists | LRANGE LLEN LINDEX LPOS |
| Sets | SMEMBERS SISMEMBER SMISMEMBER SCARD SRANDMEMBER SSCAN SINTER SUNION SDIFF SINTERCARD |
| Sorted sets | ZRANGE ZRANGEBYSCORE ZRANGEBYLEX ZREVRANGE ZREVRANGEBYSCORE ZREVRANGEBYLEX ZSCORE ZMSCORE ZCARD ZCOUNT ZLEXCOUNT ZRANK ZREVRANK ZRANDMEMBER ZSCAN |
| Streams | XRANGE XREVRANGE XLEN |
| Keyspace | SCAN |
Everything else is forbidden_sql before any network call — command rejected by gateway: redis command `<NAME>` is not in the read-only allowlist. That covers every write, and on purpose also KEYS (unbounded, blocks the server), SORT (can STORE), EVAL* / FCALL* / FUNCTION (scripts can write), MONITOR and (P)SUBSCRIBE (unbounded streams), CLIENT / CONFIG / DEBUG / INFO / OBJECT / MEMORY (server administration and introspection), the blocking commands (BLPOP / BRPOP / BLMOVE / BZPOPMIN / …, WAIT*), connection state (SELECT, AUTH, HELLO, MULTI / EXEC) and module commands (JSON.*, FT.*, …). ZRANGESTORE is not on the list, so no allowed command can write. Rejection messages name the command or option, never an argument value.
Every command is bounded before it is sent. With cap = row_limit + 1 (the extra one is how truncated is detected), the gateway rewrites or prechecks each command that could return an unbounded reply:
| Commands | Bound |
|---|---|
LRANGE, ZRANGE index form (incl. REV), ZREVRANGE | stop clamped to start + cap - 1; negative indices are first resolved with LLEN / ZCARD |
ZRANGE … BYSCORE / BYLEX, ZRANGEBYSCORE, ZREVRANGEBYSCORE, ZRANGEBYLEX, ZREVRANGEBYLEX | a LIMIT count that is negative or above cap becomes cap; no LIMIT → LIMIT 0 cap appended; a smaller count is kept |
XRANGE, XREVRANGE | COUNT clamped to cap, or appended |
LPOS | COUNT 0 or above cap → cap; MAXLEN held to 100,000 (injected when absent or 0) |
HRANDFIELD, SRANDMEMBER, ZRANDMEMBER | the count's magnitude clamped to cap, sign kept; a non-integer count is invalid_arguments |
HGETALL, HKEYS, HVALS, SMEMBERS | served by an internal HSCAN / SSCAN loop (COUNT 1000) that stops at cap items or the 32 MiB byte budget; duplicates dropped; same output shape. HGETALL order is scan order (Redis guarantees none anyway). The ACL user needs HSCAN / SSCAN (in +@read) |
SUNION, SINTER, SDIFF | SCARD precheck (sum / smallest / first set); a possible result above row_limit is forbidden_sql — query rejected by gateway: `SUNION` could return up to N members, past this call's row limit of R; read the sets with SSCAN, or count with SINTERCARD. SINTERCARD returns one integer and is not prechecked (bounded only by the timeout) |
GET, HGET, GETRANGE, SUBSTR | STRLEN / HSTRLEN precheck; a value over 32 MiB is never fetched — zero rows, truncated: true |
MGET, HMGET | at most cap keys, then only the prefix whose summed length fits 32 MiB; truncated: true when anything was dropped |
A precheck and the read are two commands, so a key can grow in between; the client-side timeout is the backstop for that race.
SCAN family options are checked and COUNT is clamped. MATCH and COUNT are accepted on SCAN / HSCAN / SSCAN / ZSCAN; TYPE on SCAN only. Any other option is forbidden_sql (e.g. redis command `HSCAN` does not allow option `NOVALUES` — NOVALUES would drop the values the result shape promises). Every COUNT is lowered to at most 1,000, and COUNT 1000 is appended when absent. Page with the returned next_cursor (start at "0"; "0" again means done).
Keys are scoped by the target ACL, not a grant — same rule as tables on Postgres (06-permissions). The ACL user the gateway logs in as should hold only +@read on the key patterns the agent may see. ACL key patterns do not filter SCAN or DBSIZE: a user limited to ~app:* still sees other key names through SCAN. The recipe, including -scan -dbsize for when key names are sensitive, is in config-reference §Redis.
Result shapes. Every reply becomes the shared columns / rows shape (the gateway speaks RESP2):
| Reply | columns | rows |
|---|---|---|
| Scalar (string, integer, nil) | ["value"] | one row |
Array (MGET, LRANGE, SMEMBERS, ZRANGE without scores, …) | ["value"] | one row per element; a nested array is one JSON value |
HGETALL, HRANDFIELD … WITHVALUES | ["field","value"] | one row per pair |
ZRANGE* / ZRANDMEMBER … WITHSCORES | ["member","score"] | one row per pair |
SCAN | ["next_cursor","key"] | one row per key |
SSCAN | ["next_cursor","member"] | one row per member |
HSCAN | ["next_cursor","field","value"] | one row per field |
ZSCAN | ["next_cursor","member","score"] | one row per member |
XRANGE / XREVRANGE | ["id","fields"] | one row per entry; fields is a JSON object |
A sorted-set score is the server's decimal text ("2.5", "inf"), not a JSON number — the same no-precision-loss rule as Postgres numeric. The SCAN family repeats next_cursor on every row; an empty page is one row with next_cursor set and the item column(s) null, so the cursor is never lost. When row_limit or the byte budget cuts a SCAN-family page, the items past the cap are dropped (truncated: true) while next_cursor still points past the whole page — narrow MATCH or lower COUNT rather than relying on the next page to return them. Outside the empty-page row, null is Redis' nil reply — a missing key or field. A bulk string that is not valid UTF-8 comes back as {"base64": "…"}, never a lossy string; a non-UTF-8 stream field name becomes the object key base64:<encoded>. row_limit and the 32 MiB byte budget apply as on every target, with truncated: true when they cut the reply.
Errors. A command the server refuses maps to the shared codes: NOPERM (the ACL user lacks the command or key) → permission_denied; any other error reply (WRONGTYPE, ERR …) → syntax_error carrying the server's code and message with the ACL username replaced by <role>; a connection or I/O failure → unavailable; a reply the gateway cannot parse → internal. Exception: a reply about the server's state (MOVED, ASK, TRYAGAIN, CLUSTERDOWN, MASTERDOWN, LOADING — the dataset is still loading, BUSY — a script holds the server) is about where the data lives or whether the server can serve, not about the command — nothing the agent can fix by rewriting it, and MOVED / ASK carry another node's address. It is unavailable, with the server's text dropped; retry later. A pooled connection the server (or a proxy) closed while it sat idle is replaced once and the command run again on the new one — every command the gateway sends is a read; only when the new connection fails too is the call unavailable. A connect-time rejection (WRONGPASS / NOAUTH) is unavailable and marks the adapter stale so the next call reconnects with a freshly resolved password (05-credentials); connect-time server messages are never passed through.
Timeouts are client-side only. Redis has no per-command server timeout, so statement_timeout_ms (clamped to the 30 s ceiling) is enforced by the gateway's Tokio deadline alone, at exactly the effective timeout. A connection goes back to the pool only after a complete reply or a server error reply; one whose command was cut off by the deadline or a client disconnect, or that hit an I/O error, is closed, never reused. The server finishes the command on its own — Redis cannot cancel one in flight — which the allowlist keeps short: no blocking commands, no scripts, no KEYS, clamped SCAN counts.
explain
Args: server, database, sql, optional params (as in run_query, bound to the explained statement), optional analyze (default false), optional reason. Returns { "plan", "summary", "elapsed_ms" } from EXPLAIN (FORMAT JSON). Lets the agent estimate cost before running expensive queries. Honours the same require_reason constraint as run_query.
summary is read off plan so the agent need not walk the tree: { "total_cost", "plan_rows", "seq_scans", "node_count" } — the root node's Total Cost and Plan Rows, the Relation Name of every Seq Scan node (plan order, each relation once), and the number of plan nodes, the root and everything under Plans (init- and sub-plans included). Omitted when the plan has no root node; plan is unchanged.
The statement passes the same guard as run_query at the caller's grant: a read needs query_read, an INSERT / UPDATE / DELETE needs query_write and is planned as the database's write_role. Plain EXPLAIN never executes the statement, so planning a write changes nothing.
Not offered on Mongo or Redis: unsupported_backend, answered before any parsing or target call.
analyze: true executes the statement for real row counts and timings, so it is accepted for read statements only — DML with analyze is forbidden_sql, whatever the grant. The read runs as the read role inside the read-only transaction and under the statement timeout, which is what makes executing it safe.
get_query_history
Args: server, database, optional since (RFC 3339), optional limit, optional cursor, optional sql_sha256, optional reason. Returns the caller's own recent queries (request id, SQL and its SHA-256, reason, timestamp, duration, row count, rows affected, outcome) for that (server, database), ordered newest-first, one page at a time. Lets the agent recover context across sessions without exposing other users' queries.
Scoping is the security-critical contract. The filter is on the SSO-verified identity (identity.user_sub) from the session middleware — NEVER on a client-supplied user field. The arguments struct uses #[serde(deny_unknown_fields)]; any attempt to pass user (or any other unknown key) is rejected with JSON-RPC invalid_params before any history is read — and the attempt itself is audited as invalid_arguments. The WHERE clause is user_sub = $1 AND server_name = $2 AND database_name = $3, ordered by (occurred_at, id) descending; the composite index audit_calls_history_idx (migration 0011) covers both.
limit defaults to 100 and is clamped to a page ceiling of 1,000; a hostile u32::MAX request is clamped, not honoured. The truncated flag reports exactly that clamp: it is true when the caller's limit exceeded the ceiling and was lowered. It does not mean "more entries exist" — that is next_cursor.
Pagination is keyset on (occurred_at, id). The response carries next_cursor — an opaque string, null on the last page. Pass it back as cursor (with the same server, database, since) for the next older page; pages never overlap, however many new calls land in between. A cursor the gateway did not mint is rejected with invalid_params (audited invalid_arguments).
Service identities see one run at a time. When a service-token call carries x-dbmcp-run-id (14-service-tokens §Upstream attribution), only rows recorded with that same run id are returned, so agents sharing one token do not read each other's history by default. Without the header a service identity sees all of its rows; the header is ignored for SSO sessions.
Each entry's sql is capped at 4,096 bytes (cut on a character boundary); sql_truncated: true marks an entry whose statement was cut — here, or at the 64 KiB stored-SQL cap when the row was written (07-logging-retention).
Each entry's sql_sha256 is the lowercase hex SHA-256 of its sql as audit_calls stores it — before the 4,096-byte cut above, after the 64 KiB store-time one (null without sql). sql_sha256 as an argument (64 hex digits, either case) narrows the page to the entries with that hash: every run of one statement, within the caller's own history and run scope as above. Stored as audit_calls.sql_sha256 by a state-DB trigger (07-logging-retention) and indexed, so a lookup seeks its matches.
since and sql_sha256 are parsed at the edge; a malformed value is rejected with invalid_params rather than silently dropping the filter.
Response shape: { "entries": [{ "request_id", "sql", "sql_truncated", "sql_sha256", "reason", "occurred_at", "elapsed_ms", "row_count", "rows_affected", "outcome" }], "truncated": bool, "next_cursor": string | null }.
Requires the history_read grant, which is standalone (per #170 — query_read does not imply it). A caller without an explicit history_read grant for (server, database) gets forbidden. The merged constraints of the matching grants apply as for every other tool: when require_reason is set, a call without a non-empty reason gets reason_required (audited), and the reason given is recorded in the audit row. The call itself is audited like any other tool dispatch (tool = "get_query_history", sql = NULL).
Implemented with #169.
table_stats
Args: server, database, optional schema (default public), optional table, optional reason. Requires schema_read (statistics are metadata, never row data). Returns { "columns", "rows", "truncated", "elapsed_ms" }, one row per table the read role may SELECT: schema, table, total_bytes, table_bytes, index_bytes, row_estimate, live_rows, dead_rows, seq_scans, index_scans, last_vacuum, last_autovacuum, last_analyze, last_autoanalyze, indexes — indexes a JSON array of { name, bytes, scans }. From pg_stat_user_tables, pg_stat_user_indexes and pg_total_relation_size, read as the read role inside a read-only transaction and the statement timeout; capped at 10,000 tables (truncated).
db_activity
Args: server, database, optional reason, optional run_scoped (boolean, default false — see run_scoped). Requires schema_read. Returns { "columns", "rows", "truncated", "elapsed_ms" } with pid, request_id, pool, state, wait_event_type, wait_event, running_ms for each statement the gateway is running on that database for the caller — request_id is the gateway request the backend serves (the gateway tags its backends via application_name), pool is read / write. The adapter only sees the gateway's own roles; the tool then keeps only requests whose intent row (07-logging-retention) carries the caller's identity, so one identity never sees another's activity; a service-token call with x-dbmcp-run-id sees only requests whose intent recorded that run id (14-service-tokens). No query text: the caller's statements are in get_query_history. Each tier is listed over its own query pool, under the caller's share of it — never over the cancel pool, which stays reserved so a cancel always gets a connection; while writes hold every write-tier connection, the write tier's listing waits up to the acquire timeout and the read tier's rows are the answer, with truncated: true — as whenever the write tier could not be listed (its pool full, its credential unresolved or refused), since writes may still be running there.
cancel_query
Args: server, database, request_id, optional reason, optional run_scoped (boolean, default false — see run_scoped). Requires query_read on that database. Cancels the statement the gateway is running for request_id — the id from an error body, the x-request-id header, or db_activity. Own identity only: a request_id that is not one of the caller's own on that (server, database) answers forbidden, exactly like an unknown one, so ids cannot be probed. A service-token call with x-dbmcp-run-id owns only that run's requests: another run's request_id gets the same forbidden answer (14-service-tokens). A running statement's own request_id reaches its client only after the call returns (the x-request-id header, an error body), so a run that cancels its own in-flight statement reads the id from db_activity. Returns { "cancelled": bool } — false when the request had already finished. The cancelled call answers cancelled and writes its own audit row with that outcome; the cancel_query call's row records the target request_id in sql. A malformed request_id is invalid_arguments. Not offered on Mongo or Redis (unsupported_backend). On Redis the answer comes after authz and the require_reason check but before the ownership lookup, so it is the same for any request_id; a Redis command is bounded by its client-side timeout instead (see Redis payload).
YugabyteDB. cancel_query uses pg_cancel_backend like any Postgres target, and works when host names a single tserver. Backend pids and pg_stat_activity are node-local and the cancel pool connects to the same host as the query pool, so behind a load balancer across tservers the cancel can land on another node: it finds no backend ({ "cancelled": false }), the statement runs on until its statement timeout, and a client-disconnect cancel still records cancelled in the audit row. The statement timeout is the bound that always holds; point host at one tserver.
run_scoped
An optional boolean on db_activity and cancel_query. true is a precondition: answer only if this call is narrowed to the caller's run — a service-token call that carries x-dbmcp-run-id. Otherwise the call is refused invalid_arguments naming run_scoped, and nothing is listed or cancelled. An SSO session has no run (its header is ignored), so true is always refused there. The refusal comes before grants, the ownership lookup, the intent row and any target call, so it is the same for a server that does not exist; it writes one audit row, with the server and database the caller named and no db_type. false and absent are the same: the behaviour above, unchanged. Any other type, null included, is invalid_arguments. The argument never widens an answer, and with a run id present it changes nothing: the header already scopes the call. Under require_upstream a call missing either header is refused by that rule first, whatever run_scoped says. The run id is not verified: this is a filter, not isolation. Use across gateway versions: 14-service-tokens §Upstream attribution.
whoami
No args (an unknown key is invalid_arguments). The caller's own identity — never another's: { "sub", "email", "auth", "service_account"?, "groups", "session_expires_at"?, "grants" }. auth is sso or service; a service account (14-service-tokens) adds service_account, its configured name, and has no session_expires_at (no session backs it). An SSO caller's session_expires_at (RFC 3339) is its gateway session's expiry, read from the state DB; the access token in hand may expire sooner and is refreshed as usual. groups is the snapshot taken at login. grants lists every (server, database) the caller holds any action on — history_read-only ones included — with the same fields as a list_databases entry. No target call. Audited like every tool: one whoami row, no server/database, row_count = the number of grants.
Errors
Errors are structured JSON, not free-text strings. A tool error is a tool result with isError: true whose text is { "request_id", "code", "message" } — code from the table below. The body also carries retryable (bool: true only for unavailable, audit_unavailable and cancelled — the same call, unchanged, may succeed again — and never when write is unknown or applied) and hint (a short next step for the code: forbidden → see list_servers / list_databases, timeout → narrow the query or check its plan with explain, undefined_object / syntax_error → describe_schema, reason_required → ask the user and resend with reason, …; whatever the code, when write is unknown or applied the hint says to check the target state before resending instead of to call again); elapsed_ms when the call reached the point of timing a target call; and limit, { "name", "value" }, when a gateway cap stopped the call — today {"name": "statement_timeout_ms", "value": <the effective budget>} on timeout, whose message also names that budget: query exceeded the configured statement_timeout (200 ms); check the plan with explain, or narrow the query. A refusal by the target database (syntax_error, undefined_object, permission_denied) adds, when the database gave them: position, the 1-based character offset in the caller's statement where Postgres located the error; db_hint, the server's own hint — only a parser or catalog hint (SQLSTATE class 42), never a column diagnostic's (42702 / 42703), role redacted, never DETAIL — next to the gateway's hint, which is unchanged; and near_misses, up to five existing table or column names the read role can see closest to an undefined one, closest first (omitted when empty). An unparseable statement's forbidden_sql adds location, { "line", "column" } (1-based), where the parser stopped. The forbidden message is the same for a server or database that does not exist and one the caller has no grant on (no grants for this server/database), so a caller cannot probe for names. A call that ran with write access (run_query or explain as the write_role under a query_write grant) adds write, whether its change is in the target: "not_applied" (refused, failed before the commit, rolled back, a dry_run, or a plain EXPLAIN), "unknown" (cut off where the commit may have landed: timeout, cancelled, a lost commit reply, a panic), or "applied" (committed — only an error raised after the commit, audit_unavailable, carries it). A read's body has no write. unknown and applied mean a retry may write twice. The invalid_arguments refusal and the shed answers below have their own envelopes.
| Code | HTTP | When |
|---|---|---|
unauthenticated | 401 | Token missing/expired — agent triggers re-login |
expired_session | 401 | Session outlived its TTL (distinct from revoked_session: routine, not a sign-out). Agent triggers re-login |
forbidden | 403 | Authenticated but permission denied for this server/db/action |
forbidden_sql | 403 | SQL rejected before reaching the DB: statement not covered by the grant (a write without query_write, or a schema mod / COPY / multi-statement in any mode), EXPLAIN ANALYZE in sql (either spelling, ANALYZE/ANALYSE, keyword or option form), explain with analyze: true on a write, text Postgres tokenizes differently from the guard (Unicode-escaped identifiers U&"…", a comment opening inside an operator, string literals split by a line break), a statement over a structural limit (512 JOINs, 1024 SELECTs, 128 levels of parentheses, or the parser work budget: 25,000 steps plus 24 for each token, comments and whitespace not counted, and one for each byte of the text, comments and whitespace included, several times what a statement of its length takes; the message names the limit), a relation showing other sessions' statements (pg_stat_activity, pg_stat_statements, pg_prepared_statements, …), or a denied function, called with parentheses or in attribute notation (filesystem, session state, cross-session messages, SQL-text executors, network, replication — the list is under run_query). An unparseable statement's message names where the parser stopped — could not parse SQL at line 2, column 25 — coordinates only, never the parser's text, which quotes the statement. On Mongo: a command or top-level field outside the read-only allowlist, a denied operator ($out, $merge, $function, $where, $accumulator), or a find / aggregate / count / distinct on a system.* collection — the command's own, or one a pipeline stage reads at any depth ($lookup / $graphLookup from, $unionWith, nested pipelines and $facet branches included) — (listIndexes on one stays allowed: it is metadata), or a stage naming a collection in another database (from: {db, coll}); a $lookup-shaped document inside $literal is data, not a stage. On Redis: a command outside the read-only allowlist, a SCAN-family option it does not allow, or a SUNION / SINTER / SDIFF whose SCARD precheck exceeds the row limit (Redis payload) |
invalid_arguments | 400 | Arguments rejected: they do not deserialise (missing or mistyped field, unknown key), break the argument edge (any string argument or argument name carrying NUL or another control character — identifiers take none, free text keeps tab/newline/carriage return; an identifier — server, database, schema, table, a sample_table columns entry, request_id — over 128 bytes, reason over 1,024, sql over 64 KiB (the audit cap, so every statement that runs is stored whole), a string inside params over 64 KiB, any other string over 1,024; checked before the intent row, so nothing refused here reaches the target and the audit row stores no part of the refused value), fail a per-tool bound (limit: 0, malformed since or cursor, a sample_table name that is not an identifier (on Mongo, a table that is not a collection name — the message names that rule), dry_run on a read, a params past its bounds or on a Mongo or Redis target, a malformed get_query_history sql_sha256, a non-UUID cancel_query request_id, a run_scoped: true on a call no run narrows, a run_query Mongo command that is not a JSON object naming a command — `sql`: mongo command is not valid JSON at line 2, column 20, coordinates only, never the parser's text —, a malformed Redis argv or a non-integer *RANDMEMBER / HRANDFIELD count — see Redis payload), the tool name contains a control character, the tool name is unknown, name is missing, or a service-token call's upstream headers are malformed or missing under require_upstream (14-service-tokens). JSON-RPC envelope carries invalid_params (-32602); the audit row records invalid_arguments — with server/database NULL when the arguments never parsed, and tool = "unknown" for an unknown or missing name (the caller's name, capped at 64 bytes, is in error_message) — so every boundary rejection is accountable. |
reason_required | 400 | Policy requires a reason for this call; none provided, or only whitespace |
timeout | 408 | Statement timeout fired (30 s ceiling). On Redis the gateway's client-side deadline fired (it also covers any precheck) and the connection was closed |
syntax_error | 400 | DB rejected the SQL. When the DB gave a SQLSTATE the message carries it, so the agent can fix the query. The same message is what the audit row and its sinks keep, so it must not carry row data — and Postgres puts row data in a primary message in any position: quoted (relation "alice@example.com" does not exist, from a column cast to regclass; likewise regtype, regrole, regproc, regnamespace, to_tsquery(col), current_setting(col)), unquoted (the bytes of an encoding error, the text of a RAISE EXCEPTION). So on Postgres the server's sentence is never passed on: the wording is the gateway's, keyed by SQLSTATE (42P01 → relation does not exist; an unlisted code gets its class's wording, an unlisted class statement rejected by the database), and the server's text is not read at all — keeping even the server words the submitted SQL also spells would confirm that a row holds that word. One name may follow, taken from the submitted SQL, by position: for a parse or analysis diagnostic (SQLSTATE class 42) that carries an error position into the caller's statement, the identifier the statement holds at that offset, verbatim — the caller's own casing and quoting, qualified name included: 42P01 relation does not exist: Usres, 42883 function or operator does not exist: nope, 42601 syntax error: FORM. Nothing is named when the position is on anything but an identifier (a literal, an operator, a number), when the identifier is longer than 128 characters, or when it is the operand of a cast (email::regclass, CAST(…); a column diagnostic, 42702 / 42703, is exempt) — a cast to a reg* type looks its object up from row data. Every other class is raised while the statement runs over data and gets the wording alone: 22P02 invalid input syntax for the target type, 42P01 relation does not exist for col::regclass, 42501 permission denied (raised at execution, with no position). A typo'd name is still named; a value read from a row never is, whatever the caller typed. The configured role name is still replaced by "<role>". DETAIL and CONTEXT are never read. The server's HINT is kept — exposed beside the message, never inside it — only under the rule that lets a name through: SQLSTATE class 42, an error position in the caller's statement, not on a cast operand; such hints name statement objects and fixed advice (No function matches the given name and argument types. You might need to add explicit type casts.), and a hint raised at run time over data has no position and is dropped. A column diagnostic's hint (42702 / 42703) is dropped too: Postgres picks the column it suggests (Perhaps you meant to reference the column "t.email".) from the whole relation, column grants aside, so it can name a column the read role cannot see; near_misses, filtered by the role's column privileges, carries that suggestion instead. The error position itself — a 1-based character offset into the caller's statement, counted from the caller's text even under explain's wrapper; none for a sample_table statement, which is the gateway's — is exposed beside the message too. On Mongo the server's errmsg echoes the command, filter values included, and for a run-time error values from documents: the message is the code and the gateway's wording keyed by it (168 unrecognized expression operator, 2 bad value in the command, an unlisted code command rejected by the database), plus — for a code raised while the command is parsed, before any document is read — the one key of the caller's own command the server's message names last: the target DB rejected the SQL: 31325 unrecognized expression operator: $fooo. Never a value. A SQLSTATE of class 28 (a refused login) is never a syntax_error: it is unavailable, with no server text. On Redis: any server error reply other than NOPERM and the cluster replies below (WRONGTYPE, ERR …), with its code and message and the ACL username replaced by <role> |
permission_denied | 403 | The target role lacks a privilege the statement needs (SQLSTATE 42501), or a write was attempted inside the read tier's read-only transaction (25006), or a Redis ACL refusal (NOPERM), or a Mongo Unauthorized reply (code 13, the role lacks the action on that collection: 13 not authorized — gateway wording only, as the server's message echoes the command); message carries the SQLSTATE and, on Postgres, the gateway's wording under the syntax_error redaction rule: the wording alone, 42501 permission denied — Postgres reports no statement position for a privilege check, so the object is not named |
undefined_object | 400 | The statement names a table or column that does not exist (SQLSTATE 42P01 / 42703); message carries the SQLSTATE and the gateway's wording under the syntax_error redaction rule (42703 column does not exist: nope). Beside it, up to five near-miss names, closest first (edit distance, a swap of two neighbours counting one): existing relations (qualified when the search path does not find them, quoted where Postgres needs it) or column names close to the one the statement holds at the error position. Only names the read role could already read through describe_schema — looked up as the read role, in a read-only transaction, the typed name's length bound, never its text — and the lookup is best-effort: 200 ms, and a slow or failed one answers no names, never an error. An error raised over row data (col::regclass) has no position, so no lookup runs |
unavailable | 503 | DB unreachable, its credentials rejected (on any connection the gateway opens — the query pools and the one cancel_query uses alike; the server's refusal text names the role and can name the client address, and is never passed on), no pooled connection free within 5 s, or the caller already holding its whole share of the pool for 5 s (see Resource safety). Waiting for a connection is not counted against the statement timeout, so a saturated pool is unavailable, never timeout. On Postgres also a transaction the target rolled back for a reason a retry clears — SQLSTATE 40001 (serialization failure; routine on YugabyteDB, reads included), 40P01 (deadlock victim), 25P03 / 25P04 (idle-in-transaction or transaction timeout), and the one 0A000 that means the statement's own plan went stale under DDL before anything ran (told by the server function that raised it and the absence of an error context, never by its localised message; the same error from inside a function the statement called came after it started, so it keeps syntax_error like every other 0A000) — and the 08 / 53 / 57P classes (connection, resources, operator intervention), any error of severity FATAL (it ends the session, it does not judge a statement), and a class 58 (system error) the server did not raise for the statement: nothing in the SQL is there to fix, so it is never syntax_error; retry. That is what a pooler answers with for a target it cannot reach — pgcat a FATAL 58000, PgBouncer a FATAL 08P01 or the server's own refusal of its login — and its text, which can name a host or a user, is dropped. When a write's COMMIT gets such an answer — a refused login (class 28) the server did not raise for the statement and a FATAL 40001 without a source location included — write is unknown; the server's own refusal of a COMMIT (a deferred constraint, 40001) rolled it back and is not_applied. A 08P01 or a class 58 the server raised for the statement keeps syntax_error and its SQLSTATE: a function can raise either, a missing file is 58P01, and a $n without a param is 08P01. The two are told apart by severity and by the source location Postgres puts in every error and a pooler in none, never by the text. Every target-error log line carries request_id, server and db as event fields, never the role. On Redis also a reply about the server's state rather than the command (MOVED, ASK, TRYAGAIN, CLUSTERDOWN, MASTERDOWN, LOADING, BUSY): the gateway does not follow redirects, and the reply's text — another node's address — is dropped. Redis alike, plus a refused TLS handshake (wrong CA, hostname mismatch — refused before AUTH is sent), a pooled connection closed while idle that cannot be reopened, and any I/O error. On Mongo the pool wait is the gateway's own (one permit per connection of the driver's pool), so a saturated Mongo pool is unavailable after 5 s like the others |
rate_limited | 429 | Calling identity has too many concurrent in-flight requests (per-identity cap). Retry-After: 1 header is set; body code concurrency_limit_exceeded (see Resource safety for the /mcp JSON-RPC shape). |
service_overloaded | 503 | Gateway-wide concurrency ceiling reached. Retry-After: 1 header is set; body code service_overloaded. |
audit_unavailable | 503 | The audit store refused a write — the intent row before a target call, or the completion row after the tool ran — or the gateway has no audit store. The request is refused; nothing is returned unaudited. The audit row (if the store recovers for the drop-guard retry) records audit_unavailable with the tool's own outcome in error_message. When the completion row fails after a write that committed or may have, the request was still answered audit_unavailable, but the change may be in the target: the body's write is applied or unknown, the message — still starting audit write failed; request rejected — adds the write may already be in the target: check before retrying (access: write; the statement may have committed), and the drop-guard row's error_message carries the same note. If that row fails too, the intent is reaped as abandoned with access: write. |
unsupported_backend | 501 | The tool is not offered on the target's engine, answered (and audited) before any parsing or target call: explain, table_stats, db_activity and cancel_query on Mongo; on Redis those four plus describe_schema and sample_table |
internal | 500 | Bug. Has a request ID that matches a server-side log line. A tool that panics answers internal and its audit row completes as internal, not cancelled; a panic anywhere else in a request answers HTTP 500 with the JSON-RPC internal-error envelope (-32603, data: {"code": "internal", "request_id"}). The panic message is never sent to the client |
cancelled is answered to a call whose statement cancel_query stopped. dry_run is the audit outcome of a successful run_query with dry_run: true (the response is a normal result with "dry_run": true). Two codes appear only in audit_calls.outcome, never in a response: cancelled when the client disconnected before the tool finished, and abandoned (the gateway stopped between reaching the target and recording the outcome — see 07-logging-retention §"Intent and completion").
Shed requests are not audit rows. A 429 rate_limited or 503 service_overloaded answer is a log line and a metric only: under overload the gateway does not add a state-DB write per rejected request. No tool ran and no target was reached, so MUST #2 (every DB call → audit row) is not in play.
Every error includes a request_id the user can paste back to ops: the gateway-minted UUID that is also the response's x-request-id header, the request_id on the server-side log line, and audit_calls.request_id — never the client's JSON-RPC id.
Resource safety
Two concurrency budgets protect the gateway. The bearer-gated budget covers /mcp, POST /auth/logout and the admin API (/admin/v1/*):
| Limit | Default | Response when exceeded |
|---|---|---|
| Global (process-wide) | 512 concurrent requests | 503 service_overloaded |
Per-identity (per SSO sub / service account) | 16 concurrent requests; a service account may set its own max_concurrent_requests | 429 rate_limited |
Both caps are checked after authentication. A per-identity permit is held for the full lifetime of the request. The global cap is checked first to keep the per-identity map lookup cheap on a saturated gateway. A cap of 0 is refused at boot.
The unauthenticated OAuth flow routes — POST /auth/login, GET /auth/callback, GET /authorize, POST /token, POST /revoke, POST /register — have their own, smaller budget: one eighth of the global cap (64 by default, never below 1). Each of them writes into a size-capped store or drives IdP/DB work, so a flood must be bounded; none carries an identity, and sharing the gated budget would let anonymous traffic (stalled bodies, an /authorize flood) take /mcp down. Exhausted, these routes answer 503 service_overloaded. GET on mcp_path (a constant 405), the discovery metadata, /healthz and /readyz are not gated — probes are trusted infra traffic and discovery documents are static (/metrics is on its own listener). /readyz answers from a one-second cache and never queues for a state-DB connection: at most one probe runs at a time (concurrent callers get the last result), it takes an idle connection or opens one only when the pool has room, and a pool saturated with request traffic counts as ready.
Every shed response keeps its HTTP status (429 / 503), carries Retry-After: 1, a warn log line with the request id and budget, and increments requests_shed_total{scope="global"|"identity"|"oauth"}. On mcp_path the body is a JSON-RPC error, so an MCP client can parse it: {"jsonrpc": "2.0", "id": null, "error": {"code": -32000, "message", "data": {"code", "category", "retry_after_s": 1, "request_id"}}} — id is null because the request body was never read; data.code is concurrency_limit_exceeded (category rate_limited) or service_overloaded (category overloaded). Every other route (POST /auth/logout, the admin API, the OAuth flow routes) answers {"error": {"category", "code"}, "request_id"}.
Budget headers. Every mcp_path answer that passed the per-identity check carries x-dbmcp-concurrency-limit (the caller's cap: the per-identity default or its service account's own) and x-dbmcp-concurrency-remaining (permits left when this request was admitted); a 429 carries both, with remaining 0. A global 503 carries neither — the identity was never checked.
Time and size bounds. Every request is bounded end to end; past the timeout the request is dropped (for a tool call: the same path as a client disconnect — query cancelled, audit row cancelled) and answered 504.
| Routes | Timeout | Body limit |
|---|---|---|
/mcp, /auth/logout | 75 s — the 30 s statement ceiling + pool acquire + both audit writes + slack | 1 MiB |
| OAuth flow routes | 60 s — covers the 45 s IdP code exchange | 16 KiB |
| Admin API | 30 s | 64 KiB (1 MiB for POST /admin/v1/grants/batch, 16 MiB for POST /admin/v1/permissions/diff) |
| Probes + discovery | 5 s | 1 KiB |
A request body must arrive in full within 10 s, so a slow-loris sender cannot pin a concurrency permit. The OAuth flow routes go further: the body is read in full (≤16 KiB, within 5 s) before their concurrency permit is taken, so slow senders cannot hold the OAuth budget at all; a body still incomplete after 5 s is answered 408, an oversized one 413, both in the RFC 6749 {"error": "invalid_request", "error_description"} shape.
The 30 s statement-timeout ceiling (see run_query above) is the complementary per-query bound: it limits how long one request can hold its permits. On Postgres it is enforced DB-side and by the gateway; on Mongo by maxTimeMS and the gateway; on Redis by the gateway alone, which closes the connection of any command it cuts off (see Redis payload).
Per-caller share of a pool. The per-identity request cap (16) is larger than a database's pool (4 connections by default), so on its own it would let one caller pin every connection of a database with slow queries until the statement timeout. Each adapter therefore also shares its pool out: one caller — SSO sub or service account — holds at most max(1, max_connections − 1) connections of a pool at a time (per tier on Postgres: the read pool and the write pool are shared out separately). The share is taken before the connection and held as long as it is; a caller at its share waits on itself, for at most 5 s, then gets unavailable — it never takes the connection someone else is waiting for. A pool of one connection cannot be shared out and is left whole. On Postgres a cancel uses its own pool and is not counted. On Mongo it has no pool of its own: the cancel of a stopped call keeps that call's connection and its caller's share until it ends, for at most 3 s (12), so a call waiting for either can wait that much longer — counted against its 5 s wait, never against its statement timeout. A Redis cancel only closes the connection. Applies to Postgres, Mongo and Redis.
Memory. One call's result is bounded by the byte cap above: 32 MiB of decoded values, weighed node by node. What that cap cannot bound is the one row the driver is receiving: the Postgres driver buffers a row whole before the gateway can look at it, and Postgres allows a row of up to 1 GiB (SELECT repeat('x', 1000000000)). The gateway never decodes or returns such a row — it is refused from its wire length, the result is truncated: true, a read is cancelled — and the buffer is given back when the connection returns to the pool, but for that moment the bytes are held. Rows of 1 MiB or more on the wire are decoded at most two at a time per database, so the copy decoding makes is bounded as well. The limit to size a container for is therefore, per Postgres database, in-flight queries × (32 MiB + the largest row the role can produce), where in-flight queries is at most pool.max_connections (twice that with a write_role) and no single caller holds more than its share. Keep max_connections small on databases whose roles can read very wide rows.
What we don't expose
- No DDL tools (
create_table,drop_table, …) — those don't belong in a debugging gateway. - No DML tools (
insert,update,delete) at the protocol layer. If writes are enabled by policy, they go throughrun_querywith the role having write grants; the audit log captures the SQL. - No raw
pg_dump/mysqldumpstyle export. Bulk export is a different product. - No "run on all databases" — every call is scoped to one DB.