Control agent access

How to stop an AI agent from running destructive SQL

Give an agent a database MCP server and it can send any SQL the connection allows. Most of the protection belongs in the database, before any tool sees a query.

By
Dan Flanagan
Updated
November 18, 2026
Tested with
PostgreSQL 18.7 and MySQL 8.4.13 in Docker, November 2026. SQL examples parsed with pg_query_go 6.2.5 and the TiDB parser, as Statio's gateway runs them
Reading time
7 min

New to MCP? What is an MCP server? covers the basics first.

An agent with a database MCP server can run whatever SQL its connection allows. If the connection can drop a table, so can the agent, and so can anyone who gets text in front of it. A support ticket that says "clean up the test orders" might become a DELETE with no WHERE.

The fix is mostly in the database. Start with a user that can't write, and add the rest when an agent has to.

Prerequisites

  • PostgreSQL 14 or later, or MySQL 8.0 or later, and an admin login to create a user. The commands were run on PostgreSQL 18.7 and MySQL 8.4.13.
  • A database MCP server and a client to connect it to, such as Claude Code or Cursor.

Step 1: Give the agent its own read-only user

Make a database user for the agent and grant it SELECT and nothing else. Don't reuse the application's user, and don't use your own.

In Postgres:

sql
CREATE ROLE agent_ro LOGIN PASSWORD '<a long random password>';
GRANT CONNECT ON DATABASE shop TO agent_ro;
GRANT USAGE ON SCHEMA public TO agent_ro;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO agent_ro;
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO agent_ro;

The last line covers tables created later. Run it as the role that creates your tables, because default privileges only apply to objects that role creates. On PostgreSQL 14 and later you can grant the predefined role pg_read_all_data instead, which reads every table, view and sequence. It doesn't bypass row-level security.

In MySQL:

sql
CREATE USER 'agent_ro'@'%' IDENTIFIED BY '<a long random password>';
GRANT SELECT ON shop.* TO 'agent_ro'@'%';

Connect as the new user and try a write. Postgres answers ERROR: permission denied for table orders. MySQL answers ERROR 1142 (42000): DELETE command denied to user 'agent_ro'. Put this user's credentials in the MCP server's config and nowhere else.

This is the control that matters most. An agent can't grant itself privileges, whatever SQL it sends.

Step 2: Make its sessions read-only and time-limited

In Postgres you can attach settings to the role, so every session it opens starts with them:

sql
ALTER ROLE agent_ro SET default_transaction_read_only = on;
ALTER ROLE agent_ro SET statement_timeout = '30s';

A read-only transaction refuses INSERT, UPDATE, DELETE, MERGE, TRUNCATE and every CREATE, ALTER and DROP. statement_timeout cancels any statement that runs longer than the limit, so a SELECT across a huge join doesn't hold locks and connections all afternoon.

Both are defaults. They don't lock anything. When I connected as agent_ro, SET default_transaction_read_only = off and SET statement_timeout = 0 both worked. The next DELETE still failed, and that was the grant from Step 1 refusing it.

MySQL has no per-user equivalent. max_execution_time caps statement time, but only for read-only SELECTs, and a session can change it. SET PERSIST sets the server-wide default and keeps it across restarts:

sql
SET PERSIST max_execution_time = 30000;

Step 3: Point the agent at a replica

If the agent only reads, connect it to a replica. A Postgres hot standby is strictly read-only: transaction_read_only is always true there and can't be changed. Heavy agent queries also stay off your primary.

On a MySQL replica, turn on super_read_only. Plain read_only still lets users with CONNECTION_ADMIN or the old SUPER privilege write.

Two caveats. Replicas lag, so the agent may see data a few seconds old. And on a Postgres standby, a long query can be cancelled when it conflicts with changes being replayed from the primary. The agent sees an error and can retry.

Step 4: Check what your MCP server does on its own

Many database MCP servers say they're read-only. How they do it varies, and one well-known case got it wrong.

ServerWhat it does
Reference Postgres server (@modelcontextprotocol/server-postgres)Wraps each query in a READ ONLY transaction. Archived in May 2025
Postgres MCP Pro (crystaldba/postgres-mcp)Restricted mode uses read-only transactions, rejects SQL containing COMMIT or ROLLBACK, and limits execution time
MySQL MCP server (benborla/mcp-server-mysql)Writes are off until you set ALLOW_INSERT_OPERATION, ALLOW_UPDATE_OPERATION or ALLOW_DELETE_OPERATION
Supabaseread_only=true on the server URL runs every query as a read-only Postgres user

The reference server is the cautionary one. Datadog Security Labs showed that it passed the agent's string straight to the database, semicolons and all. Sending COMMIT; DROP SCHEMA public CASCADE; ended the read-only transaction and ran the drop outside it. The npm package was deprecated in July 2025, and it was still getting about 20,000 downloads a week when Datadog wrote it up. If you're running it, move off it.

Supabase's switch is the strongest of these because it changes the database user. The others are enforced by the server's own code, which is fine as long as that code is right. A read-only user from Step 1 holds even when it isn't.

Why filtering the SQL text doesn't work

When an agent needs some writes, the tempting fix is a check in front of the tool: refuse anything that starts with DELETE, DROP or UPDATE. I ran these through a pattern like that, and through the real Postgres and MySQL parsers:

SQLStarts with DELETE, DROP or UPDATEWhat the parser finds
WITH gone AS (DELETE FROM orders RETURNING *) SELECT count(*) FROM goneNoA delete on orders, with no WHERE
/* read-only report */ DELETE FROM ordersNoA delete on orders
SELECT 1; COMMIT; DROP SCHEMA public CASCADENoThree statements, one of them a schema drop
EXPLAIN ANALYZE DELETE FROM ordersNoAn explain and a delete. ANALYZE executes the delete
/*!50000 DROP TABLE orders */ (MySQL)NoA table drop. MySQL runs code inside /*! */ comments, and I checked that it does
DELETE o FROM orders o JOIN customers c ON c.id = o.customer_id WHERE c.banned = 1 (MySQL)YesA delete that writes to orders, with the alias o resolved

Loosen the pattern to match those words anywhere and you start blocking SELECT * FROM orders WHERE note = 'please delete me'. The MySQL multi-table delete shows the other problem. Even when a pattern catches the delete, it can't tell you which table is written, because the target is an alias. A rule like "never write to payments" needs the real table name.

You need a parser that reads the whole statement.

Step 5: Withhold write tools from the agent

Some database servers put certain writes in their own tools. Supabase keeps schema changes in apply_migration, separate from execute_sql, so an agent can query without being able to migrate. Its execute_sql still takes any SQL, and so do execute_sql in Postgres MCP Pro and mysql_query in the MySQL server above.

When a write is its own tool, keep it off the agent's tool list. In Claude Code, a deny rule for mcp__<server>__<tool> does this for one person's machine. In a gateway like Statio, each agent gets per-tool grants, nothing is granted by default, and a refused call is logged with who made it.

That works when the tool name tells you what the call does. A single SQL tool needs the next step.

Step 6: Add SQL policies in a gateway

Statio's gateway can parse the SQL in a tool call before it reaches the server and hand the result to Cedar policies. Postgres goes through pg_query_go, which wraps Postgres's own parser, and MySQL through the TiDB parser. The table in the previous section is their output. Policies only take access away: Statio saves forbid policies and refuses a permit.

A policy can read the statement kinds, the tables read and written, what gets dropped, the functions called, the number of statements, and whether an UPDATE or DELETE has a WHERE. This is the Read-only database template with its defaults:

cedar
forbid (principal, action == Action::"call", resource)
when { context has sql && (!context.sql.parsed || !["select", "explain", "show"].containsAll(context.sql.kinds)) };

It refuses any SQL that contains anything other than a select, explain or show, so the CTE delete and EXPLAIN ANALYZE DELETE above are both refused. The !context.sql.parsed part refuses SQL the parser can't read. A typo gets refused along with any trick that relies on confusing the parser.

Usually you want people to keep write access while agents read. Cedar can check who is calling:

cedar
forbid (principal, action == Action::"call", resource)
when { principal.kind == "agent" && context has sql &&
  (!context.sql.parsed || !["select", "explain", "show"].containsAll(context.sql.kinds)) };

When an agent does need to write, the SQL guardrails template refuses the shapes that cause the worst accidents. With its defaults it refuses an UPDATE or DELETE with no WHERE, more than one statement in a call, and functions like pg_sleep and lo_import:

cedar
forbid (principal, action == Action::"call", resource)
when { context has sql && (!context.sql.parsed || context.sql.unfiltered_writes || context.sql.statements > 1 || context.sql.functions.containsAny(["pg_sleep", "pg_read_file", "pg_read_binary_file", "pg_ls_dir", "lo_import", "lo_export", "dblink", "sleep", "benchmark", "load_file"])) };

One limit worth knowing: unfiltered_writes means no WHERE clause at all. UPDATE orders SET status = 'refunded' WHERE true has one, so this rule lets it through. Pair it with Protected tables on the tables you can't afford to lose, which refuses any write to them however the WHERE reads. Deletion protection and Block DROP TABLE apply in one click, and Approval required can hold every SQL write for a person to approve in Slack or in Statio.

Two things to know before you plan around this:

  • The gateway parses SQL only for servers whose catalog entry declares which tool argument holds the query. Statio's Postgres and MySQL entries are being added to the catalog now. Until a server you use has that declaration, the SQL policies have nothing to read, and Steps 1 to 5 carry the load.
  • statio-sql, the server behind those entries, runs query in a read-only transaction, offers execute only when writes are turned on, caps rows and sets a statement timeout in the database. A policy mistake still meets the database's refusal.

Every template is Cedar you can read and edit. A policy you write yourself starts in dry run, which logs what it would have refused and lets the call through.

Conclusion

The read-only user from Step 1 is the one to set up today. It holds whatever the agent sends and whatever the MCP server gets wrong. A replica and session defaults add a little on top. When an agent has to write, withhold the write tools you can, and use a parser-backed policy for the rest.

Related tutorials: