
PostgreSQL MCP Server
A Model Context Protocol server that provides AI assistants with secure, read-only access to PostgreSQL databases while offering comprehensive tools for schema exploration, query validation, and performance optimization.
README
PostgreSQL MCP Server
A Model Context Protocol (MCP) server that provides AI assistants with secure access to PostgreSQL databases.
Features
- 🔒 Secure database access with read-only queries by default
- 🛠️ Comprehensive database tools for schema exploration and querying
- 🧠 Intelligent query validation with security and performance analysis
- ⚡ Real-time optimization suggestions for better query performance
- 🎯 SQL injection detection and dangerous operation blocking
- ⚙️ Configurable connection pooling and query limits
- 🔍 Schema filtering for multi-tenant environments
- 📝 Detailed logging and query monitoring
- 🚀 Easy setup with environment variables or config files
Installation
- Clone the repository:
git clone <your-repo-url>
cd postgresql-mcp-server
- Install dependencies:
pip install -r requirements.txt
- Configure your database connection (see Configuration)
Configuration
Environment Variables (Recommended)
Copy .env.example
to .env
and configure your database:
cp .env.example .env
Edit .env
with your database credentials:
# PostgreSQL Database Configuration
POSTGRES_HOST=localhost
POSTGRES_PORT=5432
POSTGRES_DATABASE=your_database_name
POSTGRES_USERNAME=your_username
POSTGRES_PASSWORD=your_password
POSTGRES_SSL_MODE=prefer
POSTGRES_MIN_CONNECTIONS=1
POSTGRES_MAX_CONNECTIONS=10
# MCP Server Configuration
MCP_NAME=postgresql-mcp-server
MCP_VERSION=1.0.0
MCP_MAX_QUERY_TIME=30
MCP_MAX_ROWS=1000
MCP_ALLOWED_SCHEMAS=
MCP_LOG_LEVEL=INFO
MCP_LOG_QUERIES=true
JSON Configuration (Alternative)
Copy config.example.json
to config.json
and modify as needed.
Usage
Start the MCP Server
python main.py
Test Database Connection
python main.py --test
Enable Verbose Logging
python main.py --verbose
Demo Query Validation (No Database Required)
python demo_validation.py
This demo script showcases the query validation features without requiring a database connection.
Available Tools
The MCP server provides the following tools for AI assistants with built-in query validation and optimization:
1. query
Execute SELECT queries on the database.
Parameters:
sql
(required): SQL SELECT query to executeparams
(optional): Array of parameters for the query
Example:
{
"name": "query",
"arguments": {
"sql": "SELECT id, name FROM users WHERE active = $1 LIMIT 10",
"params": ["true"]
}
}
2. list_tables
List all tables in a database schema.
Parameters:
schema
(optional): Schema name (default: "public")
Example:
{
"name": "list_tables",
"arguments": {
"schema": "public"
}
}
3. describe_table
Get detailed information about a table's columns and structure.
Parameters:
table_name
(required): Name of the table to describeschema
(optional): Schema name (default: "public")
Example:
{
"name": "describe_table",
"arguments": {
"table_name": "users",
"schema": "public"
}
}
4. list_schemas
List all available database schemas.
Example:
{
"name": "list_schemas",
"arguments": {}
}
5. test_connection
Test the database connection and get server information.
Example:
{
"name": "test_connection",
"arguments": {}
}
6. validate_query
Validate and analyze a SQL query for security issues, performance problems, and optimization opportunities.
Parameters:
sql
(required): SQL query to validate and analyzeschema
(optional): Database schema name for validation context (default: "public")
Example:
{
"name": "validate_query",
"arguments": {
"sql": "SELECT * FROM users WHERE email LIKE '%@gmail.com' ORDER BY created_at",
"schema": "public"
}
}
Features:
- Security Analysis: Detects SQL injection patterns and dangerous operations
- Performance Warnings: Identifies inefficient query patterns
- Optimization Suggestions: Recommends improvements for better performance
- Complexity Scoring: Rates query complexity on a 1-10 scale
- Index Recommendations: Suggests indexes for better performance
Example Response:
Query Analysis Report
==================================================
Valid: ✅ Yes
Complexity: 4/10
⚡ Performance Warnings:
WARNING: SELECT * can be inefficient
💡 Specify only needed columns instead of using SELECT *
WARNING: LIKE with leading wildcard prevents index usage
💡 Avoid leading wildcards in LIKE patterns or consider full-text search
💡 Optimization Suggestions:
1. Run EXPLAIN ANALYZE to see the actual execution plan
2. Consider adding an index on users.email if queries are slow
3. For ORDER BY with LIMIT, ensure there's an index on the ORDER BY columns
Query Validation & Optimization
The MCP server includes intelligent query analysis that automatically validates every query for security and performance issues.
Real-Time Query Analysis
- Automatic validation of all queries before execution
- Security threat detection including SQL injection patterns
- Performance issue identification for slow query patterns
- Optimization suggestions with specific recommendations
- Complexity scoring to help understand query resource usage
Security Validation
- SQL injection detection using pattern matching
- Dangerous function blocking (e.g.,
pg_read_file
,COPY
) - Statement type validation (only SELECT allowed)
- Comment pattern analysis for potential bypass attempts
Performance Analysis
- SELECT * detection with column-specific recommendations
- Missing index suggestions based on WHERE/JOIN clauses
- Cartesian product warnings for JOINs without conditions
- Leading wildcard detection in LIKE patterns
- Query complexity scoring (1-10 scale)
Optimization Suggestions
- Index recommendations for frequently filtered columns
- Query restructuring suggestions for better performance
- LIMIT clause recommendations for large result sets
- JOIN order optimization for complex queries
- EXISTS vs IN recommendations for subqueries
Security Features
Read-Only Queries
By default, only SELECT
statements are allowed. This prevents accidental data modification through the MCP server.
Row Limits
All queries are automatically limited to prevent excessive memory usage and long-running queries.
Schema Filtering
You can restrict access to specific database schemas using the MCP_ALLOWED_SCHEMAS
configuration.
Connection Pooling
Database connections are managed through a connection pool to ensure efficient resource usage.
Development
Running Tests
pip install pytest pytest-asyncio
pytest tests/
Code Formatting
pip install black
black .
Type Checking
pip install mypy
mypy src/
Configuration Options
Database Configuration
Variable | Description | Default |
---|---|---|
POSTGRES_HOST |
PostgreSQL server host | localhost |
POSTGRES_PORT |
PostgreSQL server port | 5432 |
POSTGRES_DATABASE |
Database name | Required |
POSTGRES_USERNAME |
Database username | Required |
POSTGRES_PASSWORD |
Database password | Required |
POSTGRES_SSL_MODE |
SSL connection mode | prefer |
POSTGRES_MIN_CONNECTIONS |
Minimum pool connections | 1 |
POSTGRES_MAX_CONNECTIONS |
Maximum pool connections | 10 |
Server Configuration
Variable | Description | Default |
---|---|---|
MCP_NAME |
Server name | postgresql-mcp-server |
MCP_VERSION |
Server version | 1.0.0 |
MCP_MAX_QUERY_TIME |
Max query execution time (seconds) | 30 |
MCP_MAX_ROWS |
Maximum rows returned per query | 1000 |
MCP_ALLOWED_SCHEMAS |
Comma-separated list of allowed schemas | All schemas |
MCP_LOG_LEVEL |
Logging level | INFO |
MCP_LOG_QUERIES |
Whether to log executed queries | true |
Troubleshooting
Connection Issues
- Verify your database credentials in
.env
- Ensure PostgreSQL is running and accessible
- Check firewall and network connectivity
- Test connection:
python main.py --test
Permission Issues
- Ensure the database user has appropriate SELECT permissions
- Check schema access permissions
- Verify SSL configuration if required
Performance Issues
- Adjust connection pool settings
- Implement query optimization
- Consider adding row limits to queries
- Monitor query execution times
Contributing
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests for new functionality
- Submit a pull request
License
MIT License - see LICENSE file for details.
推荐服务器

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 模型以安全和受控的方式获取实时的网络信息。