abdulhaseeb-dharwa/postgres-mcp-server
If you are the rightful owner of postgres-mcp-server and would like to certify it and/or have it hosted online, please leave a comment on the right or send an email to henry@mcphub.com.
The MCP PostgreSQL Server provides a standardized interface for AI assistants and other MCP clients to interact with PostgreSQL databases safely and efficiently.
MCP PostgreSQL Server
A Model Context Protocol (MCP) server that provides PostgreSQL database connectivity through a standardized interface. This server allows AI assistants and other MCP clients to interact with PostgreSQL databases safely and efficiently.
Features
- Health Check: Monitor database connectivity and response times
- Table Description: Get detailed schema information for database tables
- SQL Query Execution: Execute both read and write operations with safety controls
- Connection Pooling: Efficient database connection management using asyncpg
- Security: Built-in protection against unauthorized schema access and write operations
- JSON Parsing: Robust handling of malformed JSON from LLM responses
Prerequisites
- Python 3.13 or higher
- PostgreSQL database
- MCP client (like Claude Desktop, etc.)
Installation
- Clone this repository:
git clone <repository-url>
cd mcp-postgres
- Install dependencies using uv (recommended):
uv sync
Or using pip:
pip install -r requirements.txt
Configuration
- Create a
.env
file in the project root:
PG_DSN=postgresql://username:password@localhost:5432/database_name
- Replace the connection string with your actual PostgreSQL connection details.
Usage
Running the Server
Start the MCP server (using uv):
uv run server.py
Or via the mcp
CLI:
uv run mcp run server.py
You can also test with the MCP Inspector:
npx @modelcontextprotocol/inspector uv run server.py
The server will start and listen for MCP client connections via stdio transport.
Available Tools
1. Health Check (ping
)
# Returns connection status and response time
ping()
2. Describe Table (describe_table
)
# Get table structure information
describe_table({
"schema": "public",
"table": "users"
})
# Or as a string
describe_table('{"schema": "public", "table": "users"}')
3. Execute Query (query
)
# Read operation (default)
query(
sql="SELECT * FROM users WHERE active = true",
params={"active": True},
role="read",
limit=100
)
# Write operation
query(
sql="INSERT INTO users (name, email) VALUES ($1, $2)",
params={"name": "John Doe", "email": "john@example.com"},
role="write"
)
Security Features
- Read-only by default: Queries default to read-only mode
- Schema restrictions: Only the
public
schema is accessible - SQL injection protection: Uses parameterized queries
- Query limits: Automatic LIMIT clauses for SELECT queries
- Role-based access: Separate read/write roles for different operations
Supported SQL Operations
Read Operations:
SELECT
statementsSHOW
commandsEXPLAIN
queriesWITH
clauses (CTEs)
Write Operations:
INSERT
statementsUPDATE
statementsDELETE
statementsCREATE
statementsDROP
statementsALTER
statements
Development
Project Structure
mcp-postgres/
āāā server.py # Main MCP server implementation
āāā pyproject.toml # Project configuration and dependencies
āāā README.md # This file
āāā uv.lock # Dependency lock file
āāā .gitignore # Git ignore rules
āāā .env # Environment variables (create this)
Dependencies
asyncpg
: Async PostgreSQL drivermcp[cli]
: Model Context Protocol frameworkpsycopg[binary]
: PostgreSQL adapterpydantic
: Data validationpython-dotenv
: Environment variable management
Adding New Tools
To add new MCP tools, use the @mcp.tool()
decorator:
@mcp.tool()
async def your_tool_name(param1: str, param2: int) -> Dict[str, Any]:
"""Tool description for the MCP client."""
# Your implementation here
return {"result": "success"}
Error Handling
The server includes robust error handling for:
- Database connection issues
- SQL syntax errors
- Malformed JSON payloads
- Unauthorized operations
- Validation errors
Contributing
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests if applicable
- Submit a pull request
License
This project is licensed under the MIT License - see the file for details.
Support
For issues and questions, please open an issue on the project repository.