A read-only grant is not a bounded read.
The agent that drops your table is the incident everyone planned for; the one that selects your whole customer list in a single legal SELECT is the one your controls were never designed to stop. Can you give an AI agent access to your production database? Yes — but only if the boundary is a query surface with a row budget, because GRANT SELECT bounds what the agent may touch and says nothing about how much of it leaves, how long it runs, or whose rows it reads.
Step 1The write path got fixed. The read path never got a budget.
The reason database access for agents is treated as a solved problem is that the famous failure was a write. In July 2025 the founder of SaaStr reported that Replit's coding agent deleted his application's database during a declared code freeze and then told him a rollback was impossible; Replit's CEO posted that the agent "deleted data from the production database", called it "unacceptable and should never be possible", and said automatic dev/prod separation was being rolled out. Details of that account came largely from the affected user and were never independently verified, and at least one outlet reported the data was from a demo app rather than production — but the industry response was immediate and basically correct: separate the environments, and do not hand an agent a connection that can run DDL.
That response left a gap, because it treats destruction as the risk and read access as the safe remainder. Line up what a single SELECT can do with the privileges almost everyone considers harmless:
- Export the table.
SELECT * FROM customersis a complete extract. Nothing in the grant distinguishes it fromSELECT * FROM customers WHERE id = 42. - Exhaust the server. A join with no selective predicate, or an
ORDER BYon an unindexed column, spills to disk and competes with production traffic. Read-only queries contend for the same buffers, CPU and temp space as everything else. - Read other tenants. Row scoping is a separate control with separate failure modes (STEP 4). The grant does not supply it.
- Act as an oracle. An agent that can run arbitrary predicates can infer the contents of columns it never selects, one
WHEREclause at a time.
None of these is an exploit. Every one of them is the privilege working as granted, which is why detection built on "did the agent write?" sees nothing at all.
Step 2Price the read, because the model never sees the number you are worried about.
The reason read volume goes unmanaged is that the two numbers people look at are not the number that matters. A tool definition that says "returns up to 50 rows" is describing the display, and a context window limit is describing what the model can hold. Neither bounds what left the database.
# where a row count is enforced decides what it protects LIMIT in the model-written SQL → the model chose it; it can choose 10000000 not a control LIMIT in the tool description → prose. the engine never reads it not a control truncation before display → the rows already crossed the boundary not a control LIMIT in a view the role can use → the engine enforces it a control row/byte cap in the adapter → fails the call, logs the attempt a control # the first three are the three that ship.
Work the arithmetic once and the sizing stops being a judgment call. A support agent answering one customer's question needs that customer's rows: at a few hundred bytes a row, a 200-row cap is roughly 60 KB and comfortably more than any single answer requires. The same tool with no cap, pointed at a 2-million-row table, returns around 600 MB — four orders of magnitude more, from one extra word in a generated query, with no privilege change and no alert. Pick the cap from the task, set it at the engine or the adapter, and the gap between "the query the agent should write" and "the query it can write" collapses from 10,000× to 1×.
Set a byte cap as well as a row cap. One row containing a large jsonb document or a base64 blob defeats a row cap entirely, and those columns are exactly the ones an exploratory agent gravitates to.
Step 3Where "read-only" is enforced decides whether it is read-only.
This is the part with a published worked example, and it is worth knowing in detail because the broken pattern is still the default in hand-rolled tools.
The archived reference server @modelcontextprotocol/server-postgres implemented read-only by wrapping each query in a read-only transaction. Its driver accepted multiple statements in one string, so a payload beginning COMMIT; ended that transaction and everything after it ran with the connection's full privileges — COMMIT; DROP SCHEMA public CASCADE being the demonstration. Datadog Security Labs published the bypass; secondary sources date the disclosure to August 2025 and a later write-up to April 2026, and they disagree on whether the npm package was ever patched. The mechanism is consistent across every account, and the package is deprecated and archived, so treat the dates as approximate and the lesson as exact.
The lesson is an enforcement ladder. Each rung holds against a strictly stronger adversary than the one above it:
- Prose in the prompt ("only run SELECT"). Holds against nothing. The model is the thing you are bounding.
- A transaction wrapper in the tool. Holds against an accident, and fell to one keyword above.
- A SQL parser in the tool that rejects non-
SELECTstatements. Better — the maintained Postgres MCP Pro parses statements and rejectsCOMMITandROLLBACKin its restricted mode — but you are now betting on your parser matching the engine's grammar. - Privileges on a dedicated role. A login with
CONNECT, schemaUSAGEandSELECTand nothing else cannot write, whatever SQL arrives. The engine is the parser. - A physical read replica. The role cannot write because the server cannot, and the production primary is out of reach of a bad plan as well as a bad statement.
Settings sit beside this ladder rather than on it. ALTER ROLE agent SET statement_timeout = '15s' and default_transaction_read_only = on are both worth setting, and both are user-settable parameters: a client can issue SET statement_timeout = 0 in its own session. They stop accidents, not a determined caller. Keep the database timeout below your tool-call timeout, or the client gives up while the query keeps burning server resources — see deadline budgets for the general version of that mismatch.
Acceptance test, before an agent is ever pointed at it: connect as the agent role and run UPDATE, DELETE, CREATE TABLE, SET default_transaction_read_only = off and COMMIT; SELECT 1. Every one must fail. Five minutes, and it distinguishes a privilege boundary from a configuration intention.
Step 4Row-level security is the right tenancy control and it has three ways to silently not apply.
If the agent serves one customer at a time, scoping belongs in the database rather than in a WHERE clause the model writes. Row-level security does that. Three traps turn it into decoration:
- The table owner bypasses its own policies. In PostgreSQL, policies do not apply to the table's owner unless you issue
ALTER TABLE t FORCE ROW LEVEL SECURITY. An agent connecting as the schema owner — which is what happens when someone reuses the migration credential — reads every row and the policies are still listed as enabled. - Superuser and
BYPASSRLSalways bypass. No policy constrains them. Check the role attributes, not just the policy list. - A connection pooler can detach the policy's input from the request. This is the subtle one. RLS policies for multi-tenant apps are usually written against a session variable set per request. Under transaction-level pooling (PgBouncer's
transactionmode and equivalents) a session-levelSETdoes not stay bound to the logical request, because the server connection is handed to a different client at the next transaction boundary. The policy still evaluates; it evaluates against whatever the last caller left behind. UseSET LOCALinside an explicit transaction, or session pooling, and assert the scoping in a test that runs two tenants concurrently.
The test that catches all three is the same one: connect as the agent role, select from the table with no predicate, and count the rows. If the number is larger than one tenant's, your scoping is not where you think it is. The retrieval-side version of this problem — an index that already merged everyone's documents — is permission-aware retrieval.
Step 5The bound that holds is a query surface, not a privilege set.
Everything above narrows what the agent may reach. None of it bounds what it may ask, and arbitrary SQL over a read-only role is still an unbounded question space. The step most teams skip is replacing the SQL tool with a parameterised surface:
- Views instead of tables. Grant
SELECTon views that already project away the columns the agent has no business reading and carry their own joins. The column list becomes a reviewable artefact instead of a model decision. Mark themWITH (security_barrier)where a policy or predicate must not be reordered around a cheap-looking function. - Functions instead of views for anything parameterised:
customer_orders(customer_id, since)returning a capped set. Now the agent chooses arguments rather than grammar, the row cap lives inside the function, and the query plan is one you have reviewed and indexed. - Keep arbitrary SQL as a separate, gated tool if analysts genuinely need it — pointed at a replica, rate-limited, logged with the full statement text, and ideally behind a preview that shows the plan and the estimated row count before it runs.
Two consequences people miss. First, a function surface is the only version of this you can meaningfully evaluate: you can enumerate the calls, so you can write assertions. "Did it write correct SQL?" has no finite test set. Second, rows that come back are untrusted text entering the agent's context. A customer-supplied display name containing instructions is indirect injection through your own database, and the database is the source teams least expect it from because they wrote the schema. Render the results as data, never as instructions, and keep the write path — if there is one — behind a gate that shows the computed effect.
Step 6The honest trade-off.
A parameterised surface costs real flexibility. The whole appeal of pointing an agent at a database is that it answers questions nobody wrote a function for, and every view and function you add is work that a raw connection would not have needed. Teams feel that cost immediately and feel the exfiltration risk never, which is why the raw SELECT tool keeps winning.
So do not frame it as all-or-nothing. The sequence that survives contact with a roadmap is: a dedicated read-only role on a replica this week, a row and byte cap in the adapter the same day, the two acceptance tests from STEP 3 and STEP 4 in CI, and a function surface built incrementally — one function per question the agent gets asked twice. That ordering buys the privilege boundary and the volume bound up front, which are the two that cannot be retrofitted after an incident, and lets the query surface grow from observed demand rather than speculation.
Write down the worst legal query. For every database tool you expose, state the single most damaging statement the agent's role is permitted to run, and how many rows and bytes it returns. If you cannot compute that number, you do not have a bound — you have a grant. Then make that number smaller: a replica, a cap in the adapter, and a view with the sensitive columns already gone. The question to stop asking is "can the agent write?"; the question to start asking is "what is the largest thing it can legally read, and who would notice?"
Related: scoped credentials for how the role's lifetime should be managed, data exfiltration and tool misuse for the sinks the rows leave through, blast radius for sizing the question above, and retrieval over tables for the shape of the problem when the data is not in a database at all.