PostgreSQL MCP Server
Enables AI assistants to securely interact with PostgreSQL databases, offering 30+ tools, role-based access control, and security guardrails.
README
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
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 credentials
Configure .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=true
Run the Server
python -m app.server
Run Tests
pytest -v
MCP 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_databases |
List all accessible databases |
current_database |
Get current database name |
list_schemas |
List all schemas |
list_tables |
List tables in a schema |
list_views |
List views in a schema |
list_functions |
List functions in a schema |
list_indexes |
List indexes in a schema |
list_sequences |
List sequences in a schema |
list_extensions |
List installed extensions |
Schema Inspection
| Tool | Description |
|---|---|
describe_table |
Full table description |
describe_column |
Column metadata |
foreign_keys |
Foreign key relationships |
primary_keys |
Primary key columns |
unique_constraints |
Unique constraints |
check_constraints |
Check constraints |
table_size |
Table size with indexes |
database_size |
Total database size |
Query Execution
| Tool | Description |
|---|---|
execute_select |
Structured SELECT queries |
execute_insert |
Insert rows |
execute_update |
Update rows |
execute_delete |
Delete rows |
execute_query |
Raw SQL execution |
Transactions
| Tool | Description |
|---|---|
begin_transaction |
Start a transaction |
commit_transaction |
Commit changes |
rollback_transaction |
Undo changes |
Admin Tools
| Tool | Description |
|---|---|
active_connections |
List active connections |
running_queries |
List running queries |
locks |
List locks and deadlocks |
vacuum_status |
Vacuum and dead tuple info |
analyze_table |
Update table statistics |
server_version |
Get server version |
server_settings |
Get server settings |
AI Tools
| Tool | Description |
|---|---|
generate_sql |
Generate SQL from description |
explain_sql |
Human-readable query explanation |
optimize_sql |
Query optimization suggestions |
validate_sql |
Validate without executing |
detect_sql_injection |
Security analysis |
estimate_query_cost |
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-mcp
Architecture
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-missing
Future 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
推荐服务器
Baidu Map
百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。
Playwright MCP Server
一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。
Magic Component Platform (MCP)
一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。
Audiense Insights MCP Server
通过模型上下文协议启用与 Audiense Insights 账户的交互,从而促进营销洞察和受众数据的提取和分析,包括人口统计信息、行为和影响者互动。
VeyraX
一个单一的 MCP 工具,连接你所有喜爱的工具:Gmail、日历以及其他 40 多个工具。
graphlit-mcp-server
模型上下文协议 (MCP) 服务器实现了 MCP 客户端与 Graphlit 服务之间的集成。 除了网络爬取之外,还可以将任何内容(从 Slack 到 Gmail 再到播客订阅源)导入到 Graphlit 项目中,然后从 MCP 客户端检索相关内容。
Kagi MCP Server
一个 MCP 服务器,集成了 Kagi 搜索功能和 Claude AI,使 Claude 能够在回答需要最新信息的问题时执行实时网络搜索。
e2b-mcp-server
使用 MCP 通过 e2b 运行代码。
Neon MCP Server
用于与 Neon 管理 API 和数据库交互的 MCP 服务器
Exa MCP Server
模型上下文协议(MCP)服务器允许像 Claude 这样的 AI 助手使用 Exa AI 搜索 API 进行网络搜索。这种设置允许 AI 模型以安全和受控的方式获取实时的网络信息。