Why you'd want this
Imagine asking Claude: "Can you write me a query that finds customers who haven't ordered in the last six months?" Rather than describing your schema and hoping for the best, Claude can browse your actual tables, understand your data model, and generate accurate SQL in seconds.
Or you're debugging production behaviour. Instead of manually pulling data and pasting it into a chat, Claude can query your database directly, see patterns, and ask clarifying questions about what it finds.
Model Context Protocol (MCP) makes this safe and practical. It gives Claude a structured way to query your database without exposing it to unbounded risk.
The security foundation: read-only access
Before we dive into setup, the golden rule: Claude should only read data, never modify it. This isn't about distrust — it's about boundaries. If something goes wrong (a badly phrased query, an unexpected interpretation, a bug in the connection), the worst that happens is a slow query or a confusing result, not data loss.
To enforce this, PostgreSQL lets you create roles with SELECT permission only. These roles cannot INSERT, UPDATE, or DELETE. They can't even create temporary tables. This is the principle of least privilege applied strictly.
For production databases, use a read replica — a synchronized copy of your database that handles only read queries. This is not just a security layer. It's also practical: AI queries can be expensive and slow, and you don't want that load hitting your primary database.
What is MCP and why does it matter?
MCP is an open protocol that lets AI models connect to external tools and databases in a safe, structured way. Instead of Claude making raw SQL connections, it uses MCP as an intermediary.
Here's the flow:
- You run an MCP server (in this case, Anthropic's PostgreSQL server) on your machine or infrastructure.
- Claude Code (or Claude Desktop) connects to that server as an MCP client.
- When Claude needs data, it sends structured requests through MCP, not raw SQL commands.
- The MCP server handles schema introspection, query validation, and execution.
- Claude sees the results and can reason about your data.
This structure creates a safety boundary. Claude doesn't write its own connection strings or manage credentials directly. The MCP server owns the connection, validates requests, and enforces permissions.
Step-by-step setup for PostgreSQL + Claude Code
1. Prerequisites
You'll need:
- Node.js 18 or later (check with
node --version) - A PostgreSQL database you can connect to (local or remote)
- Claude Code or Claude Desktop (Pro subscription required for MCP)
- A PostgreSQL connection string ready (more below if you need to create one)
2. Create a read-only role in PostgreSQL
Connect to your PostgreSQL database as an administrator. If you're using a local database:
psql -U postgres -h localhostThen run these commands to create a read-only role:
-- Create the read-only role
CREATE ROLE claude_readonly WITH LOGIN PASSWORD 'strong_password_here';
-- Grant connection to the database
GRANT CONNECT ON DATABASE your_database TO claude_readonly;
-- Grant usage on schemas (assuming public schema)
GRANT USAGE ON SCHEMA public TO claude_readonly;
-- Grant SELECT on all tables
GRANT SELECT ON ALL TABLES IN SCHEMA public TO claude_readonly;
-- Ensure future tables are also readable
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO claude_readonly;Replace your_database with your actual database name and choose a strong password. This role can now read every table but cannot write, delete, or modify anything.
3. Build your connection string
PostgreSQL connection strings follow this format:
postgresql://username:password@host:port/databaseFor example:
postgresql://claude_readonly:strong_password_here@localhost:5432/your_databaseIf your database is remote (e.g., on Render or Railway), use their provided connection string instead. If SSL is required, append ?sslmode=require to the end.
4. Configure Claude Code or Claude Desktop
You have two options: the command-line approach or manual configuration.
Option A: Using the claude mcp add command
If you're using Claude Code, run:
claude mcp add postgres postgresql://claude_readonly:password@localhost:5432/your_databaseReplace the connection string with yours. This command automatically updates your configuration file.
Option B: Manual configuration (Claude Desktop or detailed setup)
Edit or create ~/.claude.json (in your home directory) and add this block:
{
"mcpServers": {
"postgres": {
"command": "npx",
"args": [
"-y",
"@modelcontextprotocol/server-postgres",
"postgresql://claude_readonly:password@localhost:5432/your_database"
]
}
}
}Save the file. Restart Claude Code or Claude Desktop. The connection should initialise on next startup.
5. Test the connection
Open Claude Code. In a new conversation, ask Claude to show you the tables in your database:
What tables do I have in this database? Can you describe the schema?If the connection works, Claude will list your tables and describe their columns, constraints, and relationships. If it fails, check:
- PostgreSQL is running and accessible from your machine
- The connection string is correct (especially the password)
- The read-only role has the right permissions (re-run the GRANT commands above if unsure)
- If remote, verify your firewall and network settings allow the connection
The Supabase shortcut
If you want something faster, Supabase (a managed PostgreSQL backend) offers a pre-built MCP integration. Sign up at supabase.com, create a project (which spins up a PostgreSQL database instantly), then connect it to Claude using their official MCP server.
The advantage: no manual role creation or infrastructure worries. The tradeoff: Supabase's MCP server is for development and testing only, not production use. For a quick experiment or learning, though, it's hard to beat.
Practical examples: what to ask Claude
Once connected, you can ask Claude to:
- Explore your data: "How many users are in the database? What's the date range of orders?"
- Generate queries: "Write a query to find users who haven't logged in for 90 days."
- Spot patterns: "Are there any tables with unusually high row counts? What might that mean?"
- Debug: "Why might this column have null values for some users?"
- Optimisation ideas: "Which queries are likely to be slow given this schema?"
Claude will see the actual data shapes, constraints, and relationships, making its answers far more useful than if you'd just described the database in text.
What can go wrong (and how to prevent it)
Slow or runaway queries
If Claude writes a query that scans millions of rows, your database will feel it. Mitigation: run Claude against a read replica, not your primary database. Set statement_timeout in PostgreSQL to kill queries that run longer than (say) 30 seconds.
ALTER ROLE claude_readonly SET statement_timeout = '30s';Exposing sensitive data
If your database contains PII (personally identifiable information), passwords, API keys, or secrets, Claude will see them if they're in readable columns. Before connecting an AI to your database, audit what's there. Mask or exclude sensitive columns, or exclude entire tables from the read-only role:
-- Exclude the secrets table
REVOKE SELECT ON secrets FROM claude_readonly;Connection credentials in chat
Never paste a connection string with a real password into Claude. The configuration lives in ~/.claude.json on your machine, not in your conversations. If you ever do paste a password anywhere, rotate it immediately.
Network exposure
If your PostgreSQL is on a remote server, ensure it only accepts connections from your IP address or through a VPN. Don't open port 5432 to the whole internet. Configure pg_hba.conf strictly.
Frequently asked questions
Do I need Claude Pro to use this?
Yes. MCP support requires Claude Desktop (Pro) or Claude Code. Free tier users cannot use MCP.
Can Claude write to my database?
Not if you set up the read-only role correctly. The PostgreSQL role permissions will block any INSERT, UPDATE, or DELETE attempts. Claude will get an error if it tries.
Is it safe to connect my production database?
Only if you connect a read replica, not the primary. A read replica is a synchronised copy that handles reads only. This way, even if something goes wrong, your primary database is untouched. For safety-critical systems, test against a staging copy first.
Can I connect multiple databases?
Yes. Add multiple entries to the mcpServers object in ~/.claude.json, each with a different name and connection string. Claude will have access to all of them in a single session.
What if my database is behind a firewall or VPN?
The Claude Code client (which runs on your machine) handles the connection, so if you can reach the database from your machine, Claude can too. No special network setup needed beyond what you already have.
How does Claude know what tables and columns I have?
The PostgreSQL MCP server introspects your schema on connection. It pulls the table list, column names, types, constraints, and relationships directly from PostgreSQL's system tables. Claude sees this information and uses it to write smarter queries.
Next steps
Start small. Connect a development or staging database first. Ask Claude simple exploratory questions: "Show me the schema." "How many rows in each table?" Once you're comfortable, expand to query writing and problem-solving.
For larger databases or more advanced use cases, explore pgEdge's MCP server or other alternatives. For rapid prototyping, Supabase's managed option is worth trying. The principle stays the same: read-only access, MCP as the intermediary, and clear boundaries about what the AI can do.