Blog

Give AI coding agents safe database access: a tested Postgres setup

Give a coding agent its own Postgres login that owns nothing, sees only the views you made for it, and runs every query in a read-only transaction. For anything that writes, hand it a throwaway copy of the database. Keep production owner credentials off the machine it works on.

Most setups stop at a weaker guard: a line in CLAUDE.md, a filter that only lets SELECT through, or a read-only flag. We tried 12 ways of deleting every row in a table against six technical guards on PostgreSQL 18.7, and five of the six lost the table. This post has the results, then the SQL, query script and migration check we'd use instead.

Why instructions aren't enough

Two incidents show how it goes wrong, both as told by the founders who lost the data. In July 2025, Replit's agent deleted a live database with records on more than 1,200 executives during a declared code freeze. In 2026, a Cursor agent working in PocketOS's staging environment deleted a Railway volume, which took production and the backups stored on that volume with it. Railway recovered the data two days later. The agent's explanation was that it "guessed that deleting a staging volume via the API would be scoped to staging only".

Neither agent had to defeat anything, because the credential allowed the call. So the question to ask of any setup is what happens if the agent runs the worst statement it can think of.

Six read-only guards against 12 write attempts

Each test started from a fresh database with 100 rows in customers. The agent connected as the table owner, except in the last column. "Lost" means the table was empty afterwards.

Attempt SELECT only filter SELECT, WITH, EXPLAIN filter default_transaction_read_only BEGIN READ ONLY wrapper Wrapper, one statement per call Login with SELECT grants only
DELETE Safe Safe Safe Safe Safe Safe
WITH d AS (DELETE ...) SELECT Safe Lost Safe Safe Safe Safe
SELECT purge(), normal function Lost Lost Safe Safe Safe Safe
SELECT purge(), SECURITY DEFINER Lost Lost Safe Safe Safe Lost
EXPLAIN ANALYZE DELETE Safe Lost Safe Safe Safe Safe
COMMIT; DELETE Safe Safe Safe Lost Safe Safe
SELECT 1; COMMIT; DELETE Lost Lost Safe Lost Safe Safe
SET TRANSACTION READ WRITE; DELETE; COMMIT Safe Safe Lost Lost Safe Safe
SET default_transaction_read_only = off, then DELETE Safe Safe Lost Safe Safe Safe
SELECT set_config(...) for the same setting, then DELETE Safe Safe Lost Safe Safe Safe

The two attempts not shown are COMMIT and DELETE as separate calls, which no guard let through, and set_config('transaction_read_only', ...) followed by DELETE and COMMIT in one string. The last one got past both filters and nothing else.

What each column teaches:

  • Text filters lose. SQL has too many ways to write from something that starts with SELECT. Parsing the query properly helps, but that's a list to maintain too. AWS's own Postgres MCP server needed a fix in September 2026 (CVE-2026-85787) for "an incomplete list of disallowed inputs" in its read-only check.
  • default_transaction_read_only is a default. Any session can turn it off with one SET.
  • A read-only transaction holds only if the agent can't end it. In the plain wrapper, the driver accepts several statements in one string, so COMMIT closes your transaction and the rest runs outside it. Datadog found exactly this in Anthropic's reference Postgres MCP server, now archived. Sending the query with the extended protocol, which refuses more than one statement, closed the hole in our test.
  • A restricted login has one gap. Postgres lets every role execute new functions by default, and a SECURITY DEFINER function runs with its owner's rights.

That leaves two guards worth combining. The login stops everything except the function call, and a one-statement read-only transaction stops that. Together they blocked all 12. The next section is why we wouldn't use the transaction on its own, even though it had no losses in the table.

What a read-only transaction still allows

Don't use the wrapper with an owner or superuser login. The Postgres manual calls it "a high-level notion of read-only that does not prevent all writes to disk". Inside BEGIN READ ONLY, with one statement per call, these all succeeded:

  • As a superuser, COPY (SELECT 1) TO PROGRAM '...' ran a shell command on the database host. It created a file in our test.
  • As the owner, LOCK TABLE orders IN ACCESS EXCLUSIVE MODE, which blocks even reads on that table until the transaction ends.
  • As the owner, SELECT pg_terminate_backend(...) disconnected another of the owner's sessions, which in production would be your app.
  • Any query on any column the login can read, including password hashes.

Create the agent's login

This script assumes a database called app whose tables are owned by app_owner. Run it on a development copy first, as an admin connected to app:

BEGIN;
CREATE ROLE agent_ro LOGIN PASSWORD 'change-me' CONNECTION LIMIT 3
  NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS;

REVOKE ALL ON DATABASE app FROM PUBLIC;
GRANT CONNECT ON DATABASE app TO app_owner, agent_ro;

REVOKE EXECUTE ON ALL FUNCTIONS IN SCHEMA public FROM PUBLIC;
GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA public TO app_owner;
ALTER DEFAULT PRIVILEGES FOR ROLE app_owner REVOKE EXECUTE ON FUNCTIONS FROM PUBLIC;

CREATE SCHEMA agent;
CREATE VIEW agent.customers AS
  SELECT id, created_at, 'user' || id || '@example.invalid' AS email FROM public.customers;
CREATE VIEW agent.orders AS
  SELECT id, customer_id, total, created_at FROM public.orders;

GRANT USAGE ON SCHEMA agent TO agent_ro;
GRANT SELECT ON ALL TABLES IN SCHEMA agent TO agent_ro;

ALTER ROLE agent_ro SET search_path = agent;
ALTER ROLE agent_ro SET default_transaction_read_only = on;
ALTER ROLE agent_ro SET statement_timeout = '15s';
ALTER ROLE agent_ro SET idle_in_transaction_session_timeout = '30s';
COMMIT;

The agent reads views in its own schema and has no rights on public. That handles personal data in the same step: email is replaced with a fake address and password_hash isn't there at all. Everything the agent reads goes to a model provider, so choose columns with that in mind. In our test a select on public.customers was denied, and pg_stats, which can reveal common values from a column, returned no rows for it.

Things to check before you run it on anything shared:

  • Other logins. REVOKE ALL ON DATABASE ... FROM PUBLIC removes the connect right that every other role had by default. Grant it back to each one you use: backups, analytics, monitoring.
  • Functions. The EXECUTE revoke also hits extension functions installed in public. Grant them back to roles that need them.
  • Row-level security. A view reads its tables with the view owner's rights. Ours returned all 100 orders despite a policy that should have shown one, and changing the view's owner to the table owner didn't help until we ran ALTER TABLE ... FORCE ROW LEVEL SECURITY. If your policies matter here, put the filter in the view.
  • New tables. They're invisible to the agent until you add a view. That's deliberate.
  • pg_read_all_data. It's a tempting shortcut, but it grants read access to every table and view in the database.

The ALTER ROLE lines set useful defaults, and a session can override them. Our agent login ran SET statement_timeout = 0 without complaint. The connection limit did hold: the fourth connection was refused. If a slow query would hurt, point the agent at a replica or a copy.

Audit what the login can do

Grants pile up. Run this while connected as the agent's login; it changes nothing and lists everything that should worry you:

SELECT 'role attribute' AS kind, a.attr AS finding
FROM pg_roles r
CROSS JOIN LATERAL (VALUES
  ('SUPERUSER', r.rolsuper), ('CREATEDB', r.rolcreatedb), ('CREATEROLE', r.rolcreaterole),
  ('REPLICATION', r.rolreplication), ('BYPASSRLS', r.rolbypassrls)) AS a(attr, on_)
WHERE r.rolname = current_user AND a.on_
UNION ALL
SELECT 'member of', g.rolname
FROM pg_roles g
WHERE g.rolname <> current_user AND pg_has_role(current_user, g.oid, 'MEMBER')
UNION ALL
SELECT 'can write', c.oid::regclass || ' (' || p || ')'
FROM pg_class c
JOIN pg_namespace n ON n.oid = c.relnamespace
CROSS JOIN unnest(ARRAY['INSERT','UPDATE','DELETE','TRUNCATE']) AS p
WHERE c.relkind IN ('r','p','v','f') AND n.nspname NOT LIKE 'pg\_%' AND n.nspname <> 'information_schema'
  AND has_table_privilege(c.oid, p)
UNION ALL
SELECT 'can write column', a.attrelid::regclass || '.' || a.attname
FROM pg_attribute a
JOIN pg_class c ON c.oid = a.attrelid
JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE c.relkind IN ('r','p','v','f') AND a.attnum > 0 AND NOT a.attisdropped
  AND n.nspname NOT LIKE 'pg\_%' AND n.nspname <> 'information_schema'
  AND NOT has_table_privilege(c.oid, 'UPDATE') AND NOT has_table_privilege(c.oid, 'INSERT')
  AND (has_column_privilege(c.oid, a.attnum, 'UPDATE') OR has_column_privilege(c.oid, a.attnum, 'INSERT'))
UNION ALL
SELECT 'can advance sequence', c.oid::regclass::text
FROM pg_class c
WHERE c.relkind = 'S' AND (has_sequence_privilege(c.oid, 'USAGE') OR has_sequence_privilege(c.oid, 'UPDATE'))
UNION ALL
SELECT 'can create in schema', n.nspname
FROM pg_namespace n
WHERE n.nspname NOT LIKE 'pg\_%' AND has_schema_privilege(n.oid, 'CREATE')
UNION ALL
SELECT 'can call SECURITY DEFINER', p.oid::regprocedure::text
FROM pg_proc p
JOIN pg_namespace n ON n.oid = p.pronamespace
WHERE p.prosecdef AND n.nspname NOT LIKE 'pg\_%' AND has_function_privilege(p.oid, 'EXECUTE')
  AND has_schema_privilege(n.oid, 'USAGE')
UNION ALL
SELECT 'can connect to', d.datname
FROM pg_database d
WHERE d.datallowconn AND d.datname <> current_database() AND has_database_privilege(d.oid, 'CONNECT')
UNION ALL
SELECT 'database privilege', current_database() || ' (' || p || ')'
FROM unnest(ARRAY['CREATE','TEMPORARY']) AS p
WHERE has_database_privilege(current_database(), p)
ORDER BY 1, 2;

An empty result is the goal. On the usual "grant select on all tables" login, it reported the SECURITY DEFINER function, temporary tables and two other databases the login could connect to. With our script, only the databases were left:

can connect to | postgres
can connect to | template1

REVOKE CONNECT ON DATABASE postgres, template1 FROM PUBLIC cleared both. Check first that nothing else relies on them. Put the query in CI against staging and fail when it returns rows. It doesn't judge which data the login can read, so review the views yourself.

Let the agent query through a small script

You don't need an MCP server for this. Any agent that can run a shell command can use this Node script, which needs only npm i pg:

// usage: node q.mjs "SELECT ..."   (needs AGENT_DATABASE_URL)
import pg from 'pg'

const sql = process.argv[2]
const explain = /^\s*explain\b/i.test(sql)
const client = new pg.Client(process.env.AGENT_DATABASE_URL)
await client.connect()
const run = (text) => client.query({ text, queryMode: 'extended' })
try {
  await run('BEGIN READ ONLY')
  if (!explain) await run(`DECLARE agent_cursor NO SCROLL CURSOR FOR ${sql}`)
  const { rows } = await run(explain ? sql : 'FETCH 201 FROM agent_cursor')
  console.log(JSON.stringify(rows.slice(0, 200), null, 1))
  if (rows.length > 200) console.log('-- stopped at 200 rows; add a filter or aggregate')
} catch (error) {
  console.error(error.message)
  process.exitCode = 1
} finally {
  await client.query('ROLLBACK').catch(() => {})
  await client.end()
}

The extended protocol rejects a second statement. DECLARE CURSOR accepts only queries and stops one SELECT from pouring a million rows into the context window: SELECT generate_series(1, 100000000) came back with 200 rows. As an extra check we ran ten write or escape attempts through the script as the table owner, and no rows were lost. Use the restricted login anyway.

Then tell the agent about it in AGENTS.md or CLAUDE.md:

## Database
- Query with `node scripts/q.mjs "SELECT ..."`. It's read-only and returns at most 200 rows.
- Only the `agent` schema is visible. If you need another table, ask; don't look for other credentials.
- Never apply a migration. Write the file, run `node scripts/rehearse.mjs <file>`, and paste the output.

Those lines tell the agent how to work. The login enforces the limits, provided no better credential is within reach. An agent with a shell can read .env, ~/.pgpass, your cloud CLI's login and your shell history, so the owner's connection string for production shouldn't be on that machine. Hosting tokens count too, since PocketOS lost its data to an API call and not to SQL.

If you use a hosted MCP server

Check what its read-only switch does and what it leaves open. From the docs, read on 25 November 2026:

Server Read-only switch What the docs say
Supabase read_only=true Runs queries "as a read-only Postgres user". Add project_ref=<id> to limit it to one project, and features= to cut the tool list
Neon readonly=true Disables write tools. SQL tools otherwise connect "as the database owner" unless you set roleName

Neon's docs also say "Never connect MCP agents to production databases", and Supabase recommends non-production data and keeping manual approval on. For a self-hosted server, give it the restricted login's connection string and run the 12 attempts on a scratch database before you trust its flag.

Give it a throwaway copy for writes

Agents are useful for writing migrations and seed scripts, and those have to run somewhere. Postgres can clone a database in one statement:

CREATE DATABASE app_try TEMPLATE app_template STRATEGY FILE_COPY;

Keep app_template as a local restore with personal data removed, and leave it idle, because cloning fails while something else is connected to it. For an 811 MB database on our Windows laptop, FILE_COPY took 2.0 to 5.1 seconds over three runs. The default WAL_LOG strategy took 6.9 to 8.1. That's cheap enough to give each git worktree its own database.

Rehearse every migration before review

An agent's migration can look fine and destroy data. This script clones the template, counts rows and filled values per column, runs the migration, counts again and drops the clone:

// usage: node rehearse.mjs migrations/0042_change.sql [template_db]
import fs from 'node:fs'
import pg from 'pg'

const [file, template = 'app_template'] = process.argv.slice(2)
const admin = new URL(process.env.REHEARSE_URL ?? 'postgres://rehearser:[email protected]:5432/postgres')
if (!['127.0.0.1', 'localhost', '[::1]'].includes(admin.hostname)) throw new Error(`refusing non-local host ${admin.hostname}`)
const sql = fs.readFileSync(file, 'utf8')
const copy = `rehearse_${process.pid}_${Date.now()}`
const at = (db) => Object.assign(new URL(admin), { pathname: `/${db}` }).href
const id = pg.escapeIdentifier

async function withClient(url, fn) {
  const client = new pg.Client(url)
  await client.connect()
  try { return await fn(client) } finally { await client.end() }
}

async function profile(client) {
  const { rows } = await client.query(`
    SELECT n.nspname, c.relname, c.relfilenode, array_agg(a.attname::text ORDER BY a.attnum) AS cols
    FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
    JOIN pg_attribute a ON a.attrelid = c.oid AND a.attnum > 0 AND NOT a.attisdropped
    WHERE c.relkind IN ('r', 'p') AND n.nspname !~ '^pg_' AND n.nspname <> 'information_schema'
    GROUP BY 1, 2, 3`)
  const out = new Map()
  for (const t of rows) {
    const name = `${t.nspname}.${t.relname}`
    const counts = t.cols.map((c, i) => `count(${id(c)}) AS c${i}`).join(', ')
    const { rows: [r] } = await client.query(`SELECT count(*) AS n, ${counts} FROM ${id(t.nspname)}.${id(t.relname)}`)
    out.set(name, { rows: +r.n, file: t.relfilenode, cols: new Map(t.cols.map((c, i) => [c, +r[`c${i}`]])) })
  }
  return out
}

const problems = []
const notes = []
await withClient(at('postgres'), (c) => c.query(`CREATE DATABASE ${id(copy)} TEMPLATE ${id(template)}`))
try {
  await withClient(at(copy), async (client) => {
    const before = await profile(client)
    const started = performance.now()
    await client.query('BEGIN')
    await client.query(sql)
    const ms = Math.round(performance.now() - started)
    const { rows: locks } = await client.query(`
      SELECT n.nspname || '.' || c.relname AS t, bool_or(l.mode = 'AccessExclusiveLock') AS reads
      FROM pg_locks l JOIN pg_class c ON c.oid = l.relation JOIN pg_namespace n ON n.oid = c.relnamespace
      WHERE l.pid = pg_backend_pid() AND c.relkind IN ('r', 'p')
        AND l.mode IN ('AccessExclusiveLock', 'ExclusiveLock', 'ShareRowExclusiveLock', 'ShareLock')
      GROUP BY 1`)
    await client.query('COMMIT')
    const after = await profile(client)
    notes.push(`ran in ${ms} ms`)
    for (const l of locks) {
      if (before.has(l.t)) notes.push(`${l.t}: ${l.reads ? 'reads and writes' : 'writes'} blocked until commit`)
    }
    for (const [name, b] of before) {
      const a = after.get(name)
      if (!a) { problems.push(`${name}: table gone (${b.rows} rows)`); continue }
      if (a.rows < b.rows) problems.push(`${name}: ${b.rows - a.rows} of ${b.rows} rows gone`)
      if (a.file !== b.file) notes.push(`${name}: whole table rewritten`)
      for (const [col, filled] of b.cols) {
        if (!a.cols.has(col)) problems.push(`${name}.${col}: column gone (${filled} values)`)
        else if (a.rows >= b.rows && a.cols.get(col) < filled) problems.push(`${name}.${col}: ${filled - a.cols.get(col)} values became NULL`)
      }
    }
  })
} catch (error) {
  problems.push(`migration failed: ${error.message}`)
} finally {
  await withClient(at('postgres'), (c) => c.query(`DROP DATABASE ${id(copy)} WITH (FORCE)`))
}
for (const n of notes) console.log(`note  ${n}`)
for (const p of problems) console.log(`LOSS  ${p}`)
process.exit(problems.length ? 1 : 0)

Set it up with a login that can create databases and nothing more, and restore the template as that login:

CREATE ROLE rehearser LOGIN CREATEDB PASSWORD 'rehearser';

Don't use a superuser. A migration that tried ALTER ROLE and one that tried COPY ... TO PROGRAM were both refused when we ran them as rehearser.

Here's one it catches, on a 100,000-row orders table. Read it before looking at the output:

DELETE FROM orders
WHERE customer_id IN (
  SELECT customer_id FROM customers WHERE email LIKE '%@test.example' OR id < 10
);
note  ran in 56 ms
LOSS  public.orders: 100000 of 100000 rows gone

customers has no customer_id column; its key is id. Postgres doesn't raise an error, because the inner customer_id then refers to the outer orders row. The condition becomes true for every order as soon as one customer matches. It's valid SQL that reads like the right thing, and reviewers miss it for the same reason the agent did.

Other results, with 2 million rows in orders and 200,000 in customers (the renames are on customers):

Migration Result
Add a nullable column No loss, 4 ms
Add a NOT NULL column with a constant default No loss, 16 ms
Add a uuid column with DEFAULT gen_random_uuid() Whole table rewritten, 16.3 s with reads and writes blocked
Change id from integer to bigint Whole table rewritten, 14.8 s with reads and writes blocked
CREATE INDEX No loss, 0.7 s with writes blocked
Rename done as drop column plus add column Column gone, 100,000 values
RENAME COLUMN Also flagged as "column gone"

The last row is a false alarm by design: the data survives, but any code using the old name breaks, so a person should look at it. Exit code 1 means there's something to approve, which makes the script usable as a CI step.

It has limits. Values overwritten with other values aren't noticed, and a migration that adds rows can hide ones it deleted. Lock notes cover one transaction, so they're wrong for a file with its own COMMIT, though the loss check still worked on one. CREATE INDEX CONCURRENTLY can't run inside a transaction and gets reported as a failure. Durations on a laptop won't match production, but a rewrite there will be a rewrite here.

Before you connect anything

  • The agent's login owns nothing, and the audit query returns no rows.
  • It reads views with personal data and secrets left out.
  • Queries run one at a time in a read-only transaction, with a row cap.
  • No owner credential or hosting token is readable from the agent's machine.
  • Writes go to a clone, and migrations are rehearsed and then applied by a person or CI.
  • Backups live outside the account or volume the agent could reach, and you've restored one.

Questions people ask

Is a read-only Postgres user enough for Claude Code or Cursor?

It stops direct writes. It doesn't stop SECURITY DEFINER functions, slow queries or reading data you didn't mean to share. Add the function revoke, the views and a replica or copy if load matters.

Can a read-only agent still leak data?

Yes. Rows it reads can contain text written by an attacker, such as a support ticket telling the agent to post other rows somewhere. Read-only access doesn't prevent that. Leave sensitive columns out, and don't pair the database with a tool that can send data out without approval.

Should an agent ever connect to production?

We'd keep it on a sanitized copy. If you need production evidence for one bug, use a replica, the restricted login and manual approval for each query, then disable the login with ALTER ROLE agent_ro NOLOGIN.

The agent already deleted something. What now?

Stop it, then restore from a backup or your host's point-in-time recovery into a new database, and compare before you switch. If it removed files as well, see how to undo agent changes with git. The security checklist covers row-level security and leaked keys.

We ran the scripts and tests here on PostgreSQL 18.7, Node 22 and pg 8.23 on Windows, against generated data. The hosted MCP servers weren't tested; that table comes from their docs. Other sources, read on the same day: Postgres docs on predefined roles, client settings and read-only transactions.