# Connecting PostgreSQL to an AI Agent: Read-Only Role, MCP and Text-to-SQL

> Create a dedicated login role that can only SELECT from views in its own schema, and attach default_transaction_read_only and statement_timeout to it. Then connect the agent through a Postgres MCP server in restricted mode, or through your own tool that accepts exactly one statement per call.

Canonical URL: https://www.ruebstudio.de/en/guides/ai-agent-integrations/connect-postgresql-ai-agent  
Author: Dr.-Ing. Marcus Rüb, CEO  
Published: 2026-11-23

Text-to-SQL agents are useful exactly because they write queries nobody planned for. That is also the risk. PostgreSQL gives you enough built-in controls to make the database itself the safety boundary, so this tutorial focuses on those Postgres-specific controls. For the general patterns that apply to any database, start with [connecting an AI agent to databases](https://www.ruebstudio.de/en/guides/ai-agent-integrations/connect-ai-agent-to-database).

## What will you have at the end?

You will have a dedicated agent role that can read one curated schema, gives up on slow queries after a few seconds and only sees the rows meant for it. The agent reaches it either through a Postgres MCP server or through a small Python tool you own.

Each layer catches a different failure:

- **Role and privileges** block writes and keep other schemas out of sight.
- **Timeouts** protect production from the expensive queries models like to produce, such as a join with no condition.
- **Views** form the interface: readable names, only the columns needed, no bank details or salary fields.
- **Row-level security** limits visible rows when different agents should see different slices of the same table.
- **The connector** makes sure exactly one statement reaches the server per call.

A system prompt saying "only run SELECT" is a polite request, not a control. Text pulled from records or user input can override it, which is the classic [prompt injection](https://www.ruebstudio.de/en/glossary/prompt-injection) pattern.

## What do you need before you start?

You need PostgreSQL 15 or newer, an admin role allowed to create roles, and Python 3.9+ if you build your own tool. Everything below was run against PostgreSQL 16.13 with psycopg 3.2.13 on Python 3.9, as of November 2026.

Version 15 is the floor because its [release notes](https://www.postgresql.org/docs/release/15.0/) added views that check privileges as the calling user, which step 3 depends on. According to [postgresql.org](https://www.postgresql.org/), the newest major release is PostgreSQL 19, published on 19 November 2026. The settings used here are long-standing core features documented in the [current manual](https://www.postgresql.org/docs/current/runtime-config-client.html).

You will also want:

- a copy or read replica of the database for the first experiments,
- a list of real questions the agent should answer, which will drive the views,
- an MCP client such as Claude Code or Claude Desktop if you take the MCP route.

## Step 1: Create a dedicated role with read-only defaults and timeouts

Give every agent its own login role and attach the runtime limits to the role itself. The [ALTER ROLE documentation](https://www.postgresql.org/docs/current/sql-alterrole.html) states that role-specific settings take effect at login, so they apply no matter which client connects.

```sql
-- Run as an admin in the target database (here: erp)
CREATE ROLE agent_ro LOGIN PASSWORD 'change-me'
  NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT CONNECTION LIMIT 5;

ALTER ROLE agent_ro SET default_transaction_read_only = on;
ALTER ROLE agent_ro SET statement_timeout = '5s';
ALTER ROLE agent_ro SET idle_in_transaction_session_timeout = '30s';
ALTER ROLE agent_ro SET lock_timeout = '1s';

REVOKE ALL ON DATABASE erp FROM PUBLIC;
GRANT CONNECT ON DATABASE erp TO agent_ro;
```

The [client connection defaults](https://www.postgresql.org/docs/current/runtime-config-client.html) page describes each one. `statement_timeout` aborts any statement running longer than the limit, and a value without units is read as milliseconds. `idle_in_transaction_session_timeout` ends sessions left idle inside an open transaction. `lock_timeout` stops the agent from queueing behind locks. `default_transaction_read_only` marks new transactions as read-only.

Here is the part many guides skip. `default_transaction_read_only` is a default, not a lock. In our test, `agent_ro` ran `SET default_transaction_read_only = off` and `BEGIN; SET TRANSACTION READ WRITE;` without any error. The read-only default catches accidents. What actually prevents writes is that the role holds no INSERT, UPDATE, DELETE or CREATE privilege anywhere. Note that `REVOKE ALL ... FROM PUBLIC` also removes the blanket connect right from every other role, so grant CONNECT explicitly to the applications that relied on it before you run it.

Avoid the predefined `pg_read_all_data` role for agents. As the [predefined roles documentation](https://www.postgresql.org/docs/current/predefined-roles.html) notes, it does respect row-level security, but it still exposes every column of every table in every schema.

## Step 2: Expose views as the agent's interface

The agent should never query your operational tables directly. Give it a dedicated schema of views that carry only the columns its questions need, with plain names and comments. This hides sensitive fields and also helps the model, because there is less to guess.

```sql
CREATE SCHEMA agent_api;
GRANT USAGE ON SCHEMA agent_api TO agent_ro;

CREATE VIEW agent_api.orders WITH (security_barrier) AS
  SELECT id, customer, region, amount
  FROM sales.orders;                  -- iban column stays out

COMMENT ON VIEW agent_api.orders IS
  'Orders without bank details; amount is net, in EUR';

GRANT SELECT ON agent_api.orders TO agent_ro;
```

The [CREATE VIEW documentation](https://www.postgresql.org/docs/current/sql-createview.html) says `security_barrier` should be used when a view is meant to provide row-level protection. It stops conditions supplied by the caller from being evaluated before the view's own filter, which could otherwise leak hidden rows. Comments keep units and meaning next to the data, so pass them to the model through the schema description in the prompt or through a tool that fetches object details.

Design views around the question list, not around the table list. Five narrow views usually work better than one wide view that joins everything. For large tables, pre-aggregated views such as "revenue by month and region" keep the model from grouping millions of rows on every question.

## Step 3: Restrict rows with row-level security

When an agent should only see part of a table, for example one sales region, enable row-level security on the base table and read it through a view created with `security_invoker`. Without that option, PostgreSQL checks the view owner's privileges and policies instead of the agent's.

```sql
CREATE ROLE agent_south LOGIN PASSWORD 'change-me' NOINHERIT;
ALTER ROLE agent_south SET default_transaction_read_only = on;
GRANT CONNECT ON DATABASE erp TO agent_south;
GRANT USAGE ON SCHEMA agent_api, sales TO agent_south;
GRANT SELECT (id, customer, region, amount) ON sales.orders TO agent_south;

ALTER TABLE sales.orders ENABLE ROW LEVEL SECURITY;
CREATE POLICY south_only ON sales.orders
  FOR SELECT TO agent_south USING (region = 'south');

CREATE VIEW agent_api.orders_south
  WITH (security_invoker = true, security_barrier = true) AS
  SELECT id, customer, region, amount FROM sales.orders;
GRANT SELECT ON agent_api.orders_south TO agent_south;
```

Because `security_invoker` checks base tables against the caller, `agent_south` needs a column-level grant on the table. In our test the `iban` column remained off limits and only the south-region row came back.

Watch out for ownership. The [row security documentation](https://www.postgresql.org/docs/current/ddl-rowsecurity.html) states that superusers, roles with BYPASSRLS and normally the table owner all bypass policies. In our test, the step 2 view, owned by a superuser, kept returning every row after RLS was switched on. Also remember that a role with no applicable policy sees nothing at all, because the default is deny.

Bind policies to roles (`TO agent_south`) rather than to a custom setting such as `app.region`. Any session can change custom settings with SET, and an agent that writes its own SQL can do so too.

## Step 4: Connect the agent through a Postgres MCP server

The Model Context Protocol hands the agent ready-made tools for schema discovery and query execution. For PostgreSQL, [Postgres MCP Pro](https://github.com/crystaldba/postgres-mcp) with `--access-mode=restricted` is a reasonable choice today. Its README says restricted mode limits operations to read-only transactions and caps execution time.

For general guidance on choosing and running servers, see [MCP servers for AI agents](https://www.ruebstudio.de/en/guides/ai-agent-integrations/mcp-servers-connect-ai-agents).

Do not reach for the original reference server, `@modelcontextprotocol/server-postgres`. It now lives in the [archived servers repository](https://github.com/modelcontextprotocol/servers-archived/tree/main/src/postgres) and is unmaintained. [Datadog Security Labs](https://securitylabs.datadoghq.com/articles/mcp-vulnerability-case-study-SQL-injection-in-the-postgresql-mcp-server/) showed that its READ ONLY transaction wrapper could be escaped with input like `COMMIT; DROP SCHEMA public CASCADE;`, because the driver accepted several statements per call. This is exactly why step 1 matters: if a connector loses its wrapper, a role without write privileges still cannot write.

Registering the server in Claude Code, following the syntax in the [Claude Code MCP documentation](https://code.claude.com/docs/en/mcp):

```bash
claude mcp add --env DATABASE_URI="postgresql://agent_ro:PASSWORD@db.internal:5432/erp" \
  --transport stdio postgres \
  -- uvx postgres-mcp --access-mode=restricted
```

The documentation notes that another option, here `--transport stdio`, has to sit between `--env` and the server name, and that everything after `--` is passed to the server untouched. The README also offers a Docker image, `crystaldba/postgres-mcp`, which reads the same `DATABASE_URI` variable.

Besides `execute_sql`, the README lists tools such as `list_schemas`, `list_objects`, `get_object_details` and `explain_query`, plus index and health analysis aimed at database maintenance. None of them can see more than the role behind `DATABASE_URI`, which is why the role design comes first.

## Step 5: Alternative with your own text-to-SQL tool in Python

If you embed the agent in your own application or prefer not to run an MCP server, a short tool function is enough. What matters is that exactly one statement reaches the server per call and that results are capped.

```python
import os
import psycopg

MAX_ROWS = 200

def run_sql(sql: str) -> dict:
    """Agent tool: one read-only statement, capped result."""
    with psycopg.connect(os.environ["AGENT_DATABASE_URL"]) as conn:
        conn.read_only = True  # on top of the role default
        with conn.cursor() as cur:
            try:
                # prepare=True: the server rejects "COMMIT; DROP ..."
                cur.execute(sql, prepare=True)
            except psycopg.Error as e:
                return {"error": str(e).strip()}
            if cur.description is None:
                return {"error": "No result set"}
            cols = [d.name for d in cur.description]
            rows = cur.fetchmany(MAX_ROWS)
            return {"columns": cols,
                    "rows": [list(r) for r in rows],
                    "truncated": cur.fetchone() is not None}
```

The [psycopg documentation](https://www.psycopg.org/psycopg3/docs/basic/from_pg2.html) explains that several statements in one `execute()` only work without parameters. With `prepare=True` the query runs as a prepared statement, and the server answers `COMMIT; DROP ...` with "cannot insert multiple commands into a prepared statement". The `read_only` connection attribute exists since psycopg 3.2, per the [connection API](https://www.psycopg.org/psycopg3/docs/api/connections.html), and has no effect in autocommit mode.

Return database errors to the agent rather than hiding them. A message like "column amount_gross does not exist" lets the model fix its own query. Convert `Decimal` and date values to strings before handing results to the model, for example with `json.dumps(..., default=str)`.

## How do you test the access path?

Test with the exact role the agent uses, and test the things that should fail. Only open access once writes, foreign schemas, slow queries and stacked statements are all rejected.

What we observed on PostgreSQL 16 with `agent_ro`:

| Attempt | Result |
|---|---|
| `SELECT * FROM agent_api.orders` | rows, no `iban` column |
| `SELECT * FROM sales.orders` | permission denied for schema |
| `INSERT INTO agent_api.orders ...` | permission denied |
| `CREATE TABLE public.t (x int)` | cannot execute CREATE TABLE in a read-only transaction |
| `SELECT pg_sleep(7)` | canceling statement due to statement timeout |
| `COMMIT; DROP SCHEMA agent_api CASCADE` via the tool | cannot insert multiple commands into a prepared statement |

Then run a functional test. Ask twenty real questions from daily work and compare the agent's answers with queries you wrote yourself. Wrong answers usually trace back to an ambiguous column, fixed with a comment or a dedicated view, or to a business rule that is written down nowhere, such as what counts as an "open order".

## Operations, cost and security

In production, point the agent at a read replica rather than the primary, log its queries, and keep credentials in a secrets manager instead of a config file.

- **Logging:** `ALTER ROLE agent_ro SET log_statement = 'all'` writes every agent query to the server log, showing which questions people ask and where views are missing.
- **Load:** `CONNECTION LIMIT` and `statement_timeout` contain runaway loops. A replica separates agent load from operational traffic entirely.
- **Cost:** every schema description and every returned row is billed as tokens by the model provider. Narrow views and the row cap keep responses small.
- **Data protection:** anything the role can read may end up with the model provider. Running a local model keeps data on your own network; see [sovereign AI](https://www.ruebstudio.de/en/sovereign-ai). Whether a setup can be operated in line with the GDPR depends on data categories and contracts, and this is not legal advice.

When this approach is the wrong fit: if answers must be authoritative, such as board-level KPIs, free-form text-to-SQL is too unpredictable, because the model may translate the same question differently on different days. Fixed, reviewed queries exposed as tools are safer there. In our own operations, a mix works well: fixed queries for recurring figures, free SQL over views for one-off questions.

## What should you do next?

Start with one role, three views and a read replica, then grow the views along the questions people actually ask. The privileges stay the same as you go.

1. Collect real questions and derive the first views from them.
2. Create the role and views from steps 1 and 2, then run the test table above.
3. Connect the agent through Postgres MCP Pro or your own tool.
4. After two weeks, review the query log: which questions fail and which views are missing?

To see how database agents fit into larger workflows like quoting or field service, browse the overview of [AI agents for business teams](https://www.ruebstudio.de/en/ai-agents).

## Frequently asked questions

### Is default_transaction_read_only enough to stop writes?

No. It only sets the default for new transactions, and any session can switch it off with SET or SET TRANSACTION READ WRITE. Privileges are what stop writes, so grant the role nothing but SELECT.

### Should I still use the original reference Postgres MCP server?

No. The @modelcontextprotocol/server-postgres package is archived and unmaintained, and Datadog Security Labs showed its read-only wrapper could be escaped with a leading COMMIT.

### Does the agent need every table to write good SQL?

Usually not. A handful of clearly named, commented views gives the model less to guess and tends to produce cleaner queries than a schema with hundreds of tables.

### Does this work on managed PostgreSQL services?

Roles, timeouts, views and row-level security are core PostgreSQL features, so yes. Check that your provider lets your admin role run ALTER ROLE ... SET.

## Sources

- [PostgreSQL documentation: Client Connection Defaults](https://www.postgresql.org/docs/current/runtime-config-client.html)
- [PostgreSQL documentation: ALTER ROLE](https://www.postgresql.org/docs/current/sql-alterrole.html)
- [PostgreSQL documentation: Row Security Policies](https://www.postgresql.org/docs/current/ddl-rowsecurity.html)
- [PostgreSQL documentation: CREATE VIEW](https://www.postgresql.org/docs/current/sql-createview.html)
- [PostgreSQL documentation: Predefined Roles](https://www.postgresql.org/docs/current/predefined-roles.html)
- [PostgreSQL 15 release notes](https://www.postgresql.org/docs/release/15.0/)
- [PostgreSQL: current releases](https://www.postgresql.org/)
- [Postgres MCP Pro (crystaldba/postgres-mcp)](https://github.com/crystaldba/postgres-mcp)
- [Archived Model Context Protocol reference server for PostgreSQL](https://github.com/modelcontextprotocol/servers-archived/tree/main/src/postgres)
- [Datadog Security Labs: SQL injection in the PostgreSQL MCP server](https://securitylabs.datadoghq.com/articles/mcp-vulnerability-case-study-SQL-injection-in-the-postgresql-mcp-server/)
- [psycopg 3: differences from psycopg2 (multiple statements)](https://www.psycopg.org/psycopg3/docs/basic/from_pg2.html)
- [psycopg 3: Connection API (read_only)](https://www.psycopg.org/psycopg3/docs/api/connections.html)
- [Claude Code: connecting MCP servers](https://code.claude.com/docs/en/mcp)
