A Model Context Protocol server for PostgreSQL databases with SSL support
Project description
PostgreSQL MCP Server
A Python implementation of a Model Context Protocol (MCP) server for PostgreSQL databases. This server provides read-only access to PostgreSQL databases through the MCP protocol, allowing AI assistants to query database schemas and execute SELECT queries safely.
Features
- Schema Exploration: Browse database tables and their column information
- Read-only Queries: Execute SELECT queries safely with transaction isolation
- SSL Support: Handles SSL connections with proper fallback options
- Connection Pooling: Efficient database connection management
- Security: Only allows SELECT queries to prevent data modification
Installation
Via uvx (Recommended)
# Run directly without installation
uvx postgres-mcp-server "postgresql://username:password@hostname:port/database"
Via pip
# Global installation
pip install postgres-mcp-server
# Run
postgres-mcp-server "postgresql://username:password@hostname:port/database"
From Source
- Clone this repository:
git clone <repository-url>
cd postgres-mcp
- Install dependencies:
pip install -r requirements.txt
Usage
Running the Server
With uvx (easiest)
uvx postgres-mcp-server "postgresql://username:password@hostname:port/database"
With pip install
postgres-mcp-server "postgresql://username:password@hostname:port/database"
From source
python postgres_mcp_server.py "postgresql://username:password@hostname:port/database"
Example
uvx
uvx postgres-mcp-server "postgresql://myuser:mypass@localhost:5432/mydb"
pip
postgres-mcp-server "postgresql://myuser:mypass@localhost:5432/mydb"
Source
python postgres_mcp_server.py "postgresql://myuser:mypass@localhost:5432/mydb"
SSL Configuration
The server automatically handles SSL connections. If no SSL mode is specified in the connection string, it defaults to prefer mode, which attempts SSL but falls back to non-SSL if needed.
To explicitly set SSL mode:
# uvx
uvx postgres-mcp-server "postgresql://user:pass@host:5432/db?sslmode=require"
# pip
postgres-mcp-server "postgresql://user:pass@host:5432/db?sslmode=require"
# source
python postgres_mcp_server.py "postgresql://user:pass@host:5432/db?sslmode=require"
Available SSL modes:
disable: No SSLallow: Try non-SSL, then SSLprefer: Try SSL, then non-SSL (default)require: SSL requiredverify-ca: SSL required with CA verificationverify-full: SSL required with full verification
MCP Resources and Tools
Resources
The server exposes database tables as resources with the following format:
- URI:
postgres://host:port/path/table_name/schema - Name:
"table_name" database schema - Content: JSON array of column information including name, data type, nullability, and defaults
Tools
query
Executes read-only SQL SELECT queries against the database.
Parameters:
sql(string): The SQL SELECT query to execute
Example:
{
"name": "query",
"arguments": {
"sql": "SELECT id, name FROM users WHERE active = true LIMIT 10"
}
}
Security Features
- Read-only Access: Only SELECT statements are allowed
- Transaction Isolation: Each query runs in a read-only transaction
- Connection Pooling: Secure connection management with proper cleanup
- SQL Injection Protection: Uses parameterized queries where applicable
- Password Sanitization: Removes passwords from logged URLs
Testing
Run the test suite:
# Install test dependencies
pip install pytest pytest-asyncio
# Run tests
pytest test_postgres_mcp_server.py -v
# Run with coverage
pytest test_postgres_mcp_server.py --cov=postgres_mcp_server --cov-report=html
Test Categories
- Unit Tests: Test individual components and functions
- Integration Tests: Test complete workflows with mocked database
- Error Handling: Test various error conditions and edge cases
- Security Tests: Verify SQL injection protection and access controls
Configuration
Environment Variables
You can also configure the database connection using environment variables:
export DATABASE_URL="postgresql://user:password@localhost:5432/dbname"
python postgres_mcp_server.py $DATABASE_URL
Connection Pool Settings
The server uses a connection pool with the following default settings:
- Minimum connections: 1
- Maximum connections: 10
- Connection factory: RealDictCursor (returns dictionaries)
Error Handling
The server handles various error conditions gracefully:
- Connection Failures: Proper error reporting for database connectivity issues
- Invalid Queries: Clear error messages for malformed SQL
- Permission Errors: Informative messages for access-related problems
- Resource Not Found: Appropriate responses for non-existent tables/schemas
Development
Project Structure
postgres-mcp/
├── postgres_mcp_server.py # Main server implementation
├── test_postgres_mcp_server.py # Comprehensive test suite
├── requirements.txt # Python dependencies
├── README.md # This file
└── setup.py # Package setup (optional)
Contributing
- Fork the repository
- Create a feature branch
- Add tests for new functionality
- Ensure all tests pass
- Submit a pull request
Troubleshooting
Common Issues
-
SSL Connection Errors
- Solution: Add
?sslmode=disableto your connection string or ensure SSL certificates are properly configured
- Solution: Add
-
Connection Pool Exhaustion
- Solution: Ensure proper connection cleanup or adjust pool settings
-
Permission Denied
- Solution: Verify database user has SELECT permissions on target tables
-
Module Import Errors
- Solution: Ensure all dependencies are installed:
pip install -r requirements.txt
- Solution: Ensure all dependencies are installed:
Logging
The server uses Python's logging module. To enable debug logging:
import logging
logging.basicConfig(level=logging.DEBUG)
License
[Specify your license here]
Dependencies
mcp: Model Context Protocol SDKpsycopg2-binary: PostgreSQL adapter for Pythonpytest: Testing frameworkpytest-asyncio: Async testing support
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file postgres_mcp_server-1.0.0.tar.gz.
File metadata
- Download URL: postgres_mcp_server-1.0.0.tar.gz
- Upload date:
- Size: 8.2 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: uv/0.7.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
63d8115b658f0e10786eb833059a04a90d5bc3cbe7db8d145a3fafef20b0e12f
|
|
| MD5 |
5b7ed98053ab6d39ee4c96ceeffcfd21
|
|
| BLAKE2b-256 |
89fa10e05e43585078633c17f3ca66755c43ceff0a869bc22d5e087623dccf62
|
File details
Details for the file postgres_mcp_server-1.0.0-py3-none-any.whl.
File metadata
- Download URL: postgres_mcp_server-1.0.0-py3-none-any.whl
- Upload date:
- Size: 8.1 kB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: uv/0.7.9
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
cfea6ee0acd348a29334aa2bd834b8a18f1a973db2cdb041368d7f5b084a067e
|
|
| MD5 |
61190b02ff606beca61efd9ed5f2b2f0
|
|
| BLAKE2b-256 |
0f727141b29c57a892aef90597f830ecfeaea93f792a90f69592660914bb4f3b
|