PostgreSQL MCP Server
Click on "Install Server".
Wait a few minutes for the server to deploy. Once ready, it will show a "Started" state.
In the chat, type
@followed by the MCP server name and your instructions, e.g., "@PostgreSQL MCP Serverdescribe the orders table"
That's it! The server will respond to your query, and you can continue using it as needed.
Here is a step-by-step guide with screenshots.
PostgreSQL MCP Server
A production-ready Model Context Protocol (MCP) server for PostgreSQL, enabling AI assistants to securely interact with PostgreSQL databases.
Features
30+ MCP tools for database operations
Security guardrails with SQL injection detection
Role-based access control (Viewer, Analyst, Developer, DBA, Admin)
Read-only mode for safe query execution
Transaction management with begin/commit/rollback
AI-powered tools for SQL generation, optimization, and analysis
Structured audit logging for compliance
Async execution with connection pooling
Related MCP server: PostgreSQL MCP Server
Quick Start
Prerequisites
Python 3.12+
PostgreSQL 14+
pip
Installation
# Clone the repository
git clone https://github.com/your-org/postgres-mcp.git
cd postgres-mcp
# Create virtual environment
python -m venv .venv
.venv\Scripts\activate # Windows
# source .venv/bin/activate # Linux/Mac
# Install dependencies
pip install -r requirements.txt
# Copy and configure environment
copy .env.example .env
# Edit .env with your database credentialsConfigure .env
DATABASE_URL=postgresql+asyncpg://user:password@localhost:5432/your_db
DATABASE_HOST=localhost
DATABASE_PORT=5432
DATABASE_NAME=your_db
DATABASE_USER=your_user
DATABASE_PASSWORD=your_password
READ_ONLY_MODE=false
ENABLE_AI_SQL=true
ENABLE_AUDIT_LOG=trueRun the Server
python -m app.serverRun Tests
pytest -vMCP Client Configuration
Claude Desktop
Add to claude_desktop_config.json:
{
"mcpServers": {
"postgres": {
"command": "python",
"args": ["-m", "app.server"],
"cwd": "/path/to/postgres-mcp",
"env": {
"DATABASE_URL": "postgresql+asyncpg://user:pass@localhost:5432/db"
}
}
}
}Cursor / VS Code
{
"mcpServers": {
"postgres": {
"command": "python",
"args": ["-m", "app.server"],
"cwd": "/path/to/postgres-mcp"
}
}
}Available Tools
Database Information
Tool | Description |
| List all accessible databases |
| Get current database name |
| List all schemas |
| List tables in a schema |
| List views in a schema |
| List functions in a schema |
| List indexes in a schema |
| List sequences in a schema |
| List installed extensions |
Schema Inspection
Tool | Description |
| Full table description |
| Column metadata |
| Foreign key relationships |
| Primary key columns |
| Unique constraints |
| Check constraints |
| Table size with indexes |
| Total database size |
Query Execution
Tool | Description |
| Structured SELECT queries |
| Insert rows |
| Update rows |
| Delete rows |
| Raw SQL execution |
Transactions
Tool | Description |
| Start a transaction |
| Commit changes |
| Undo changes |
Admin Tools
Tool | Description |
| List active connections |
| List running queries |
| List locks and deadlocks |
| Vacuum and dead tuple info |
| Update table statistics |
| Get server version |
| Get server settings |
AI Tools
Tool | Description |
| Generate SQL from description |
| Human-readable query explanation |
| Query optimization suggestions |
| Validate without executing |
| Security analysis |
| Cost estimation |
Security
Guardrails
The server automatically blocks dangerous operations:
DROP DATABASE/DROP ROLEALTER SYSTEMCOPY ... PROGRAMTRUNCATE(requires confirmation)pg_sleep(),pg_read_file(),pg_write_file()Multi-statement queries
SQL injection patterns
Read-Only Mode
When READ_ONLY_MODE=true, only SELECT and EXPLAIN are allowed.
Role-Based Access
Role | Access Level |
Viewer | Read metadata only |
Analyst | SELECT queries + AI tools |
Developer | INSERT/UPDATE/DELETE + transactions |
DBA | Admin tools (connections, settings) |
Admin | Full access |
Docker
# Build
docker build -t postgres-mcp .
# Run
docker run -p 8000:8000 \
-e DATABASE_URL=postgresql+asyncpg://user:pass@host:5432/db \
postgres-mcpArchitecture
app/
├── server.py # FastMCP server with all tool registrations
├── config.py # Pydantic Settings configuration
├── database.py # Async database connection manager
├── guards/
│ ├── sql_guard.py # SQL validation and risk classification
│ └── permissions.py # Role-based access control
├── tools/
│ ├── schema_tools.py # Database/schema inspection
│ ├── query_tools.py # CRUD query execution
│ ├── transaction_tools.py # Transaction management
│ ├── admin_tools.py # Monitoring and admin
│ └── ai_tools.py # AI-powered SQL analysis
├── services/
│ └── audit.py # Audit logging
├── models/
│ └── schemas.py # Pydantic input/output models
└── utils/
├── logging.py # Structured logging
└── helpers.py # Utilities (pagination, injection detection)Development
# Install dev dependencies
pip install -r requirements.txt
# Run linter
ruff check app/ tests/
# Run formatter
black app/ tests/
# Run type checker
mypy app/
# Run tests with coverage
pytest --cov=app --cov-report=term-missingFuture Enhancements
pgvector integration for vector similarity search
Semantic search across database schemas
RAG workflows for database documentation
Multi-database support (MySQL, SQLite, SQL Server)
Streaming for large result sets
Prepared statement caching
Query result caching with TTL
Webhook notifications for schema changes
GraphQL endpoint alongside MCP
Dashboard UI for monitoring
License
MIT
This server cannot be installed
Maintenance
Latest Blog Posts
- Who's Calling? MCP Hosts Are an Identity Blind Spot (And the Spec Knows It)By Om-Shree-0709 on .mcpAgent IdentityOAuth 2.1
- Your AI Chatbot Just Exposed Your CEO's Salary to an InternBy Om-Shree-0709 on .Agent IdentityMCP SecurityOAuth Delegation
- Why MCP Servers Need Execution Sandboxing (And Why Your Current Stack Isn't Enough)By Om-Shree-0709 on .Agentic AiPrompt InjectionWebAssembly
MCP directory API
We provide all the information about MCP servers via our MCP API.
curl -X GET 'https://glama.ai/api/mcp/v1/servers/SaadRiaz99/postgres-mcp-server'
If you have feedback or need assistance with the MCP directory API, please join our Discord server