# Read-Only Database Access for Agents via MCP

> Give an agent safe SQL querying through an MCP server connected with a read-only database role.

Category: MCP & Tool Use  
Tags: mcp, postgres, sql, security  
Setup time (estimate): 30 minutes  
Estimated cost: Free software; uses your database's read capacity.  
Last verified: 2026-10-14

Enforce safety in the database, not only in the prompt.

## 1. Create a read-only role

```sql
CREATE ROLE agent_ro LOGIN PASSWORD 'change-me';
GRANT CONNECT ON DATABASE app 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;
ALTER ROLE agent_ro SET statement_timeout = '5s';
```

Better still: point it at a read replica and grant only on views that exclude sensitive columns.

## 2. MCP config

```json
{
  "mcpServers": {
    "postgres": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-postgres",
               "postgresql://agent_ro:change-me@localhost:5432/app"]
    }
  }
}
```

The reference Postgres server is archived (github.com/modelcontextprotocol/servers-archived) and the npm package `@modelcontextprotocol/server-postgres` is marked deprecated ("no longer supported"); the config above still shows the pattern, but for production use a maintained Postgres MCP server, and keep the same read-only-role principle.

## Failure modes

- The reference server package is deprecated; plan a maintained replacement.
- Expensive queries can load production; use a replica and statement_timeout.
- Views that include sensitive columns leak data; grant only on safe views.
