Enables configuration through environment variables stored in .env files, allowing easy setup of database credentials and server parameters without hardcoding sensitive information.
Provides secure, read-only access to PostgreSQL databases with tools for schema exploration, query validation, security analysis, and performance optimization. Supports SELECT queries with parameterization, table listing, schema inspection, and query validation with automatic security and performance recommendations.
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:
- Install dependencies:
- Configure your database connection (see Configuration)
Configuration
Environment Variables (Recommended)
Copy .env.example
to .env
and configure your database:
Edit .env
with your database credentials:
JSON Configuration (Alternative)
Copy config.example.json
to config.json
and modify as needed.
Usage
Start the MCP Server
Test Database Connection
Enable Verbose Logging
Demo Query Validation (No Database Required)
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:
2. list_tables
List all tables in a database schema.
Parameters:
schema
(optional): Schema name (default: "public")
Example:
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:
4. list_schemas
List all available database schemas.
Example:
5. test_connection
Test the database connection and get server information.
Example:
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:
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 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
Code Formatting
Type Checking
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.
This server cannot be installed
remote-capable server
The server can be hosted and run remotely because it primarily relies on remote services or has no dependency on the local environment.
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.
Related MCP Servers
- -securityAlicense-qualityA Model Context Protocol server that enables powerful PostgreSQL database management capabilities including analysis, schema management, data migration, and monitoring through natural language interactions.Last updated -35546TypeScriptAGPL 3.0
- -securityFlicense-qualityA Model Context Protocol server that enables interaction with PostgreSQL databases to list tables, retrieve schemas, and execute read-only SQL queries.Last updated -16,948JavaScript
- -securityAlicense-qualityEnables AI agents to interact with PostgreSQL databases through the Model Context Protocol, providing database schema exploration, table structure inspection, and SQL query execution capabilities.Last updated -11PythonMIT License
- -securityAlicense-qualityA Model Context Protocol server that enables interaction with PostgreSQL databases for analyzing setups, debugging issues, managing schemas, migrating data, and monitoring performance.Last updated -6TypeScriptMIT License