PostgreSQL MCP Server
Provides tools for securely interacting with PostgreSQL databases, including schema inspection, SELECT/INSERT/UPDATE/DELETE query execution, transaction management, admin monitoring, and AI-powered SQL generation, validation, explanation, and optimization.
Click on "Deploy 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/SaadRiaz99/postgres-mcp-server.git
cd postgres-mcp-server
# 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=true
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-server",
"env": {
"DATABASE_HOST": "localhost",
"DATABASE_PORT": "5432",
"DATABASE_NAME": "your_db",
"DATABASE_USER": "your_user",
"DATABASE_PASSWORD": "your_password",
"READ_ONLY_MODE": "true"
}
}
}
}Cursor / VS Code
{
"mcpServers": {
"postgres": {
"command": "python",
"args": ["-m", "app.server"],
"cwd": "/path/to/postgres-mcp-server"
}
}
}Fork and use it
Click Fork on this repository.
Clone your fork (
git clone https://github.com/YOUR_USERNAME/postgres-mcp-server.git).Follow Installation above. On Linux/macOS use
cp .env.example .envinstead ofcopy.Set
DATABASE_HOST,DATABASE_PORT,DATABASE_NAME,DATABASE_USER, andDATABASE_PASSWORDin.env. The asyncpg pool uses these separate fields; changingDATABASE_URLalone does not configure that pool.Use a dedicated PostgreSQL role with only the privileges you need. Start with read-only database grants and
READ_ONLY_MODE=true. Existing write/admin tools remain exposed; the application flag and role metadata are not a substitute for database-level permissions or authenticated authorization.Configure your MCP client to launch the virtual environment's Python with
-m app.serverand this repository as its working directory. If the client does not supportcwd, launch through a script that changes directory first.Try: “Find columns containing email in public”, “Show index usage”, or “Which sessions are blocking queries?”
These six new inspection tools do not require a paid model API key. An AI client
may have its own model costs. Keep .env private and use a test database first.
New inspection and diagnostic tools
Tool | Inputs | Purpose |
|
| Literal case-insensitive column-name search |
|
| Visible trigger events and actions |
|
| Visible table grants |
|
| Estimated rows, scans and maintenance timestamps |
|
| Index scans, bytes, uniqueness and validity |
|
| Blocked and blocking process IDs in this database |
schema defaults to public; limit defaults to 100 and accepts 1–1000.
Results include success, data, count, limit, and duration_ms.
Invalid input and database errors return structured error objects. No new tool
modifies data or cancels sessions; schema/search/table values are bound parameters.
Results are capped (not paginated); narrow the schema or table to reduce results.
Catalog visibility depends on database grants. Empty results can mean no matching
objects or insufficient visibility. Multi-event triggers appear once per event.
Table grants are not a complete effective-permission audit. Statistics are
estimates/counters since collection/reset; zero index scans alone do not mean
an index should be removed. Session details can be null for restricted roles.
query_age_seconds is query age, not exact lock-wait duration.
References: PostgreSQL statistics and blocking PID functions.
Run the focused tests with:
python -m pytest tests/test_inspection_tools.py --no-covAvailable 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 deployed
Maintenance
Related MCP Connectors
Query PostgreSQL databases in plain English — LLM-generated, safety-validated SQL.
Safe, read-only Postgres and MySQL access for AI agents. Audit log + column-level controls.
Deterministic safety, correctness & cost gate that vets Postgres SQL before your AI agent runs it.
Query Postgres, MySQL, SQL Server, Oracle, BigQuery, ClickHouse and Redshift from your AI client.
Related MCP Servers
- FlicenseAqualityDmaintenanceEnables AI assistants to interact with PostgreSQL databases using natural language queries, providing secure read-only access to database schemas and SQL translation capabilities.68 npm-
- AlicenseNot gradedqualityAmaintenanceEnables secure, AI-driven PostgreSQL database administration, observability, and querying with support for extensions like PostGIS and pgvector, connection pooling, and advanced tool filtering.66 npm12MIT
- AlicenseNot gradedqualityDmaintenanceEnables AI assistants to safely explore, analyze, and maintain PostgreSQL databases with read-only mode by default, SQL injection prevention, query performance analysis, and optional write operations.41 npmApache 2.0
- AlicenseNot gradedqualityNot gradedmaintenanceProvides AI assistants with safe, controlled access to PostgreSQL databases with read-only defaults, granular permissions, query safety features, and schema introspection capabilities.1-