postgres-mcp-server
Acts as a secure bridge connecting PostgreSQL databases to AI models, enabling natural language querying, schema analysis, and controlled write operations with multi-layer security.
README
PostgreSQL DBQA with MCP (Model Context Protocol)
This project acts as a secure bridge connecting your PostgreSQL database to Artificial Intelligence (AI) models (like Claude, Cursor, etc.).
By leveraging the Model Context Protocol (MCP), it enables AI models to understand your database schema, securely query it (SELECT), and perform controlled data modifications (INSERT, UPDATE, DELETE).
Features
- Schema Analysis: Automatically introduces database tables, columns, and relationships to the AI.
- Natural Language Querying: AI translates natural language questions into SQL and retrieves results.
- Secure Write Operations:
- Supports
INSERT,UPDATE,DELETEoperations. - Two-Phase Approval: AI first previews the affected rows using
modify_data, then confirms the modification withconfirm_modification. - Kill Switch: Write permissions can be instantly disabled with
WRITE_ENABLED=false.
- Supports
7-Layer Security Model
This server employs a multi-layered protection system to ensure data safety:
- DDL Blocking: Structural modification commands like
DROP,TRUNCATE,ALTER,CREATEare always strictly forbidden. - WHERE Clause Enforcement:
UPDATEandDELETEqueries are prevented from running without aWHEREclause. - Row Limit: The maximum number of rows affected by a single query is limited (Default: 100).
- Table Whitelist: Write permission is granted only to tables specified in the
.envfile. - Two-Phase Transaction: Write operations first run in "Dry-Run" (preview) mode to calculate the number of affected rows.
- Separate Isolation: Distinct connection managers and validators are used for read and write operations.
- Audit Log: All operations are logged in detail.
Installation (Docker)
-
Docker image oluşturun:
docker build -t postgres-mcp-server . -
Bir
.envdosyası oluşturun (.env.example'dan kopyalayabilirsiniz):copy .env.example .env # Windows cp .env.example .env # Linux/Mac -
.envdosyasında veritabanı URI'nizi ayarlayın:# Bağlantı URI - tek satırda tüm bilgiler DATABASE_URI=postgresql://username:password@host:port/dbname # Yazma İşlemleri WRITE_ENABLED=true WRITABLE_TABLES=customers,orders,products # Boş = tüm tablolar MAX_WRITE_ROWS=100
Usage
AI Client Configuration (Claude Desktop / Cursor)
Add the following to your AI client config (e.g., claude_desktop_config.json or Cursor MCP settings):
{
"mcpServers": {
"postgres-dbq": {
"command": "docker",
"args": [
"run", "-i", "--rm", "--network", "host",
"-e", "DATABASE_URI",
"-e", "WRITE_ENABLED",
"-e", "WRITABLE_TABLES",
"-e", "MAX_WRITE_ROWS",
"postgres-mcp-server"
],
"env": {
"DATABASE_URI": "postgresql://postgres:your_password@localhost:5432/your_database",
"WRITE_ENABLED": "true",
"WRITABLE_TABLES": "",
"MAX_WRITE_ROWS": "100"
}
}
}
}
Note:
--network hostallows the container to accesslocalhostservices (e.g., PostgreSQL running on the host). On Windows/Mac Docker Desktop, you may also usehost.docker.internalin the URI instead oflocalhost.
Local Development (without Docker)
pip install -r requirements.txt
python mcp_server.py
Project Structure
mcp_server.py: Main MCP server file. Tool definitions are located here.src/database/:executor.py: SQL execution engine (preview_writeandexecute_writemethods).schema_manager.py: Module analyzing the database schema.
src/validation/:sql_validator.py: SQL security checks and validation logic.rules.py: Forbidden keywords and limit definitions.
src/config.py: Pydantic-based configuration management.Dockerfile: Docker image definition.
Environment Variables
| Variable | Required | Default | Description |
|---|---|---|---|
DATABASE_URI |
✅ | — | PostgreSQL connection URI (postgresql://user:pass@host:port/db) |
WRITE_ENABLED |
❌ | false |
Enable write operations |
WRITABLE_TABLES |
❌ | "" (all) |
Comma-separated list of writable tables |
MAX_WRITE_ROWS |
❌ | 100 |
Max rows affected per write query |
MAX_QUERY_TIMEOUT |
❌ | 30 |
Query timeout in seconds |
MAX_RESULT_ROWS |
❌ | 1000 |
Max rows returned per SELECT |
Security Warning
This tool possesses powerful capabilities. When WRITE_ENABLED=true is set, your AI model can make changes to the database.
- Configure
WRITABLE_TABLESstrictly before using in a Production environment. - Ensure you have regular backups of your critical data.
Recommended Servers
playwright-mcp
A Model Context Protocol server that enables LLMs to interact with web pages through structured accessibility snapshots without requiring vision models or screenshots.
Audiense Insights MCP Server
Enables interaction with Audiense Insights accounts via the Model Context Protocol, facilitating the extraction and analysis of marketing insights and audience data including demographics, behavior, and influencer engagement.
Magic Component Platform (MCP)
An AI-powered tool that generates modern UI components from natural language descriptions, integrating with popular IDEs to streamline UI development workflow.
VeyraX MCP
Single MCP tool to connect all your favorite tools: Gmail, Calendar and 40 more.
graphlit-mcp-server
The Model Context Protocol (MCP) Server enables integration between MCP clients and the Graphlit service. Ingest anything from Slack to Gmail to podcast feeds, in addition to web crawling, into a Graphlit project - and then retrieve relevant contents from the MCP client.
Kagi MCP Server
An MCP server that integrates Kagi search capabilities with Claude AI, enabling Claude to perform real-time web searches when answering questions that require up-to-date information.
E2B
Using MCP to run code via e2b.
Neon Database
MCP server for interacting with Neon Management API and databases
Exa Search
A Model Context Protocol (MCP) server lets AI assistants like Claude use the Exa AI Search API for web searches. This setup allows AI models to get real-time web information in a safe and controlled way.
Qdrant Server
This repository is an example of how to create a MCP server for Qdrant, a vector search engine.