Databases·
intermediate
·10 min read·Apr 4, 2026How to Connect PostgreSQL to AI Agents Using MCP
Step-by-step guide to setting up the PostgreSQL MCP server. Give your AI agent read-only access to query your PostgreSQL databases.
PostgreSQLdatabaseSQLClaudedata analysis
Connect PostgreSQL to AI Agents Using MCP
The PostgreSQL MCP server allows AI agents to inspect database schemas and execute read-only SQL queries against your PostgreSQL databases.
Prerequisites
- ▸PostgreSQL database running and accessible
- ▸Node.js 18+ installed
- ▸Claude Desktop or another MCP host
Installation
The PostgreSQL server is available as an npm package:
bash
npx -y @modelcontextprotocol/server-postgres postgresql://user:password@/mydbConfiguration
Add to your Claude Desktop config:
json
{
"mcpServers": {
"postgres": {
"command": "npx",
"args": [
"-y",
"@modelcontextprotocol/server-postgres",
"postgresql://user:password@/mydb"
]
}
}
}Available Tools
Once connected, the server exposes:
- ▸— Execute read-only SQL queriescode
query - ▸— List all tables in the databasecode
list_tables - ▸— Get schema information for a specific tablecode
describe_table
Security Best Practices
- ▸Use a read-only database user: Create a dedicated user with SELECT-only permissions
- ▸Limit accessible schemas: Configure the server to only expose specific schemas
- ▸Use environment variables for connection strings — never hardcode credentials
sql
-- Create a read-only user
CREATE USER mcp_reader WITH PASSWORD 'secure_password';
GRANT CONNECT ON DATABASE mydb TO mcp_reader;
GRANT USAGE ON SCHEMA public TO mcp_reader;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO mcp_reader;Example Usage
Once configured, you can ask your AI agent:
- ▸"What tables exist in my database?"
- ▸"Show me the schema for the users table"
- ▸"What are the top 10 customers by order value?"
- ▸"Analyze the distribution of orders by month"
Environment Variables
For production setups, use environment variables:
json
{
"mcpServers": {
"postgres": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-postgres"],
"env": {
"DATABASE_URL": "postgresql://user:password@host:5432/db"
}
}
}
}Troubleshooting
- ▸Connection refused: Ensure PostgreSQL is running and accepting connections
- ▸Authentication failed: Verify credentials and pg_hba.conf settings
- ▸SSL required: Add to your connection stringcode
?sslmode=require