---
title: "Postgres MCP Server Security: Safe AI Agent Access"
description: "How to connect AI agents to Postgres or Oracle through an MCP server safely: read-only roles, row-level security, timeouts, per-user OAuth and audit logs."
url: https://axiointelligence.com/blog/mcp_database_access_postgres_oracle
---

[← Blog](https://axiointelligence.com/blog)

mcp security, postgres mcp server, oracle mcp server, ai agents, postgresql, database security

# Giving AI Agents Your Postgres or Oracle Database Through MCP, Without Handing Them the Keys

Brice Ayres / October 27, 2026

Short answer

A read-only flag in an MCP server is not a security boundary: Datadog showed the archived reference Postgres MCP server could be escaped with a stacked COMMIT, and the MCP Python SDK could accept tokens issued for other services until versions 1.30.0 and 2.2.0 added an opt-in audience check. Put the limits in the database instead: a dedicated read-only role, row-level security or Oracle VPD, a read replica, statement\_timeout and row caps, single-statement execution, per-user OAuth with audience validation, audit logging, and human approval for any write.

Someone in your company has asked to “just plug the agent into the database.” You can do that safely, but not by trusting the MCP server’s read-only switch. We put the limits where the agent can’t talk its way past them: in the database role, in row-level policies, on a replica, and in an OAuth check that ties every query to a real person. Below is the setup we use for a Postgres MCP server, with the Oracle equivalents next to it.

## Why isn’t an MCP server’s “read-only mode” enough?

Because it is usually a wrapper, and wrappers leak. In August 2025 Datadog Security Labs [published a SQL injection](https://securitylabs.datadoghq.com/articles/mcp-vulnerability-case-study-SQL-injection-in-the-postgresql-mcp-server/) in the reference Postgres MCP server. The server ran each query inside `BEGIN TRANSACTION READ ONLY`, but the Node driver accepted several statements in one string. A query like this ended the read-only transaction and ran the rest with full privileges:

```
COMMIT; DROP SCHEMA public CASCADE;
```

Datadog also showed a quieter attack. Because the pool reused connections, `COMMIT; SET statement_timeout TO 1;` broke every later query on that connection, including other users’ queries. That reference server was deprecated and archived in 2025, yet at the time of Datadog’s write-up its npm package was still getting about 21,000 downloads a week. Datadog’s advice, which we agree with, is to use a restricted database role in every case.

Even well-built servers say the same. The [AWS Labs Postgres MCP server](https://awslabs.github.io/mcp/servers/postgres-mcp-server) parses each query with PostgreSQL’s own parser, rejects multiple statements and blocks dangerous functions. Its docs still call that guard “best-effort, defense-in-depth … not a security boundary” and tell you to pair it with a least-privilege role.

## What does a safe Postgres MCP server setup look like?

Here are the controls, in the order we put them in.

### 1\. A dedicated read-only role

The agent never gets the application’s login, and never a superuser, `rds_superuser` or a role with `BYPASSRLS`. Grant only what it needs:

```
CREATE ROLE mcp_readonly WITH LOGIN PASSWORD 'from-your-secrets-manager'
  NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS;

GRANT CONNECT ON DATABASE appdb TO mcp_readonly;
GRANT USAGE ON SCHEMA reporting TO mcp_readonly;
GRANT SELECT ON ALL TABLES IN SCHEMA reporting TO mcp_readonly;
ALTER DEFAULT PRIVILEGES IN SCHEMA reporting GRANT SELECT ON TABLES TO mcp_readonly;

ALTER ROLE mcp_readonly SET default_transaction_read_only = on;
```

Give it a curated schema of views, not your raw tables. Don’t grant `pg_read_server_files`, `pg_write_server_files` or `pg_execute_server_program`, or `USAGE` on foreign data wrappers; AWS’s docs call those out as the paths to file access, command execution and outbound network calls. Note that `default_transaction_read_only` is a default the session can change, so the grants are the real limit. Without `INSERT`, `UPDATE` or `DELETE`, a `COMMIT;` trick has nothing to write with.

### 2\. Row-level security

A read-only role can still read everyone’s data. Row-level security limits each query to the rows the requesting user may see:

```
ALTER TABLE reporting.orders ENABLE ROW LEVEL SECURITY;

CREATE POLICY orders_by_region ON reporting.orders
  FOR SELECT TO mcp_readonly
  USING (region_id = current_setting('app.region_id')::int);
```

The MCP server sets `app.region_id` from the verified user’s token at the start of each request, for example with `SELECT set_config('app.region_id', $1, true)`. The agent never chooses it, and because a stacked statement could try to change it, this only holds when the server also enforces single statements (step 5).

### 3\. A read replica

Point the agent at a replica, not the primary. An expensive query an agent writes then slows a reporting copy, not checkout, and writes are refused by the replica itself. On AWS that’s an RDS read replica or an Aurora reader endpoint.

### 4\. statement\_timeout and row caps

Agents write unbounded queries. Cap time and rows:

```
ALTER ROLE mcp_readonly SET statement_timeout = '15s';
ALTER ROLE mcp_readonly SET idle_in_transaction_session_timeout = '30s';
```

In the server, wrap every query so the result can’t be huge:

```
SELECT * FROM ( <agent query> ) AS q LIMIT 1000;
```

A session can override role settings with `SET`, which is exactly what Datadog’s `statement_timeout` attack did, so these limits depend on step 5 too. Many teams also set limits in the connection pooler.

### 5\. Single-statement execution

This is the fix for the stacked-`COMMIT` problem. Run agent SQL through the extended query protocol (a prepared statement), which PostgreSQL rejects if it contains more than one command. That’s how the patched fork of the reference server fixed it. Better still, parse first and only allow `SELECT`, as the AWS Labs server does with `pglast`. Also start a fresh session per call, or reset it, so one request can’t change the next one’s settings.

### 6\. Per-user OAuth with audience validation

A shared service login means every query looks like “the agent.” For remote MCP servers, the [MCP authorization spec](https://modelcontextprotocol.io/specification/2025-06-18/basic/authorization) uses OAuth 2.1 and says servers must validate that each access token was “issued specifically for them as the intended audience,” and must not pass the client’s token through to other services.

That check is easy to miss. On October 5, 2026, the MCP Python SDK published [advisory GHSA-w4fh-qvv9-3v23](https://github.com/modelcontextprotocol/python-sdk/security/advisories/GHSA-w4fh-qvv9-3v23) (moderate, CVSS 6.8): its bearer-token authentication had no way to check a token’s audience. If your authorization server also issues tokens for other services, a token for one of them was accepted by your MCP server. Versions 1.10.0 to 1.29.1 and 2.0.0 to 2.1.1 are affected. Upgrading to 1.30.0 or 2.2.0 **changes nothing by itself**; you must also set `validate_token_resource=True` with `resource_server_url`, and return the token’s audience from `verify_token()` as `AccessToken.resource`. If you can’t upgrade, reject any token whose `aud` doesn’t include your server inside `verify_token()`.

Once each request carries a verified user, map that user to the RLS setting above and to the audit log below.

### 7\. Audit logging

Log every query with who asked for it. In the MCP server, record the user, tool, SQL text, row count and duration. In the database, use the pgAudit extension or `log_statement` on the agent’s role:

```
ALTER ROLE mcp_readonly SET log_statement = 'all';
```

### 8\. Human approval for writes

If an agent must change data, don’t widen the read-only role. Expose a narrow write tool, such as “refund order X up to $Y,” backed by a separate role with `INSERT` or `UPDATE` on exactly the tables it needs. The server shows the proposed change to a person and runs it only after they approve. MCP clients may ask before running a tool, but enforce the approval on the server, where the agent can’t skip it.

**Planning an agent rollout on production data?** [Book a call](https://axiointelligence.com/book) and we’ll review your MCP server, database roles and auth setup before anything touches production.

## How do you secure an Oracle MCP server?

The same layers apply, with Oracle’s own tools:

- **Read-only user:** `CREATE USER mcp_ro ...; GRANT CREATE SESSION TO mcp_ro;` plus `SELECT` on specific views only.
- **Row filtering:** Virtual Private Database policies (`DBMS_RLS.ADD_POLICY`) instead of Postgres RLS.
- **Replica:** an Active Data Guard standby opened read-only, if you license it.
- **Row caps:** `FETCH FIRST 1000 ROWS ONLY` around agent queries.
- **Auditing:** a Unified Auditing policy on the agent user.

Oracle also ships a managed option. The [Oracle Autonomous AI Database MCP Server](https://blogs.oracle.com/machinelearning+selectai/announcing-the-oracle-autonomous-ai-database-mcp-server), generally available for database versions 19c and 26ai, runs inside Autonomous AI Database Serverless. Oracle says it respects your existing roles, auditing and VPD policies, and users sign in with database credentials so each sees only the tools they’re allowed to use. Oracle’s own sample run-SQL tool describes itself as read-only and paginates results with `OFFSET`/`FETCH`, but the query text is still passed in by the agent, so the database user’s grants and VPD policies are what actually keep it read-only.

## Should you move off Oracle before adding agents?

Not just for this. Agent access is a reason to tighten roles, not a reason to migrate. If the Oracle license is already under review, though, it’s worth knowing what a move costs; we broke that down in [what an Oracle to PostgreSQL migration really costs](https://axiointelligence.com/blog/oracle_to_postgres_migration_cost).

## Why does this matter now?

Agents are reaching real systems faster than controls are. On October 22, 2026, [Axios reported](https://www.axios.com/2026/10/22/ai-agents-banks-unauthorized-accounts-access) that major U.S. banks are detecting unvetted third-party AI agents inside customer accounts, are restricting them, and are mostly moving toward allowing read-only access. The same logic applies inside your company: start agents read-only, prove the controls, and add writes one approved tool at a time.

## FAQ

### What is a Postgres MCP server?

A Model Context Protocol server that lets an AI client such as a coding assistant or chat agent list tables, read schemas and run SQL against PostgreSQL through standard tool calls.

### How do I make a PostgreSQL MCP server read only?

Connect it with a dedicated role that has only `SELECT` on approved schemas, set `default_transaction_read_only = on`, point it at a read replica, and enforce one statement per call. Don’t rely on the server’s read-only flag alone.

### What are MCP server security best practices for databases?

Least-privilege roles, row-level security or VPD, a replica, statement timeouts and row limits, single-statement execution, per-user OAuth with audience validation, audit logs, and human approval for writes.

### How does MCP authentication work?

Remote MCP servers act as OAuth 2.1 resource servers. Clients get a token from an authorization server, requesting it for the MCP server’s URL, and the MCP server must check that the token was issued for it before doing anything.

### Am I affected by the MCP Python SDK audience advisory?

If your HTTP server uses the SDK’s bearer authentication, your authorization server also issues tokens for other services, and your token verifier doesn’t check `aud`, yes. Upgrade and turn on `validate_token_resource`, or check `aud` yourself.

## Where to go from here

Start with one read-only use case on a replica, with a dedicated role, per-user auth and logging, and grow from there. Our [data and AI platform services](https://axiointelligence.com/services/data-ai-platforms) cover building agent access that your security team will sign off on. When you’re ready, we’re happy to [talk it through](https://axiointelligence.com/book).

## We do this work for a living.

A 30-minute scoping call with the engineers who would do the work.

[Book a scoping call](https://axiointelligence.com/book)

Or email [contact@axiointelligence.com](mailto:contact@axiointelligence.com?subject=Project%20inquiry) and we’ll reply.

## Related posts

Nov 25, 2026

### [Converting Oracle PL/SQL Packages, Triggers and Cursors to PostgreSQL](https://axiointelligence.com/blog/migrate_oracle_plsql_packages_to_postgresql)

Migrate Oracle PL/SQL packages, triggers and cursors to PostgreSQL: package state, autonomous transactions, exceptions, and what Ora2Pg leaves.

pl/sql, plpgsql, oracle packages

Nov 13, 2026

### [Oracle to PostgreSQL Migration, Step by Step: Schema, Data Sync and a Minimal-Downtime Cutover](https://axiointelligence.com/blog/oracle_to_postgresql_migration_step_by_step)

The real sequence for an Oracle to PostgreSQL migration: assess, convert, sync with CDC, validate, rehearse and cut over, and where projects usually slip.

oracle to postgresql, database migration, postgresql

Oct 28, 2026

### [Running Qwen, DeepSeek and Other Open-Weight Models In-House Without Letting Them Phone Home](https://axiointelligence.com/blog/self_hosted_llm_security_open_weight_models)

Self hosted LLM security for Qwen, DeepSeek and other open-weight models: deny egress, limit tools, check weights, log every call, test before real data.

self hosted llm, llm security, llm sandbox
