postgres-mcp
A secure PostgreSQL MCP server allowing AI models to read, write, update, and delete database records with parameterized queries, transactional dry-runs, disposable testing, and automated backups.
README
PostgreSQL Model Context Protocol (MCP) Server
A secure, robust Model Context Protocol (MCP) server written in Python that allows AI models to safely read, write, update, and delete records from a PostgreSQL database.
Project Overview
Purpose & Problem Solved
AI models lack direct access to databases, which hinders their ability to build reports, analyze database structure, and manage records on demand. Traditional integrations can expose databases to major security risks, such as SQL injection, resource exhaustion, or accidental truncation.
This PostgreSQL MCP Server acts as a secure, sandboxed gateway for AI agents. It implements:
- Strict parameterized query enforcement to eliminate SQL injection risks.
- Multi-tier security verification:
- Transactional Dry-Runs (Small/Medium operations): Runs write operations inside a PostgreSQL
BEGINtransaction, captures a sample preview of affected records, and automatically issues aROLLBACKso zero disk changes persist until explicitly confirmed. - Disposable Environment Testing (High-Risk/Large-Scale operations): Tests high-risk DDL (
DROP TABLE,TRUNCATE) or large-scale modifications (> 1,000 rows) inside an isolated temporary schema (_mcp_disposable_...), inspects structural outcomes, and automatically drops the disposable environment.
- Transactional Dry-Runs (Small/Medium operations): Runs write operations inside a PostgreSQL
- Row limits preventing memory exhaustion from accidental massive selects.
- Automated pre-deletion backups (CSV and database dumps) with built-in age and count retention policies.
- Error feedback loops and Explain Plan integrations to allow self-correcting query generation.
Tech Stack
- FastMCP: High-level SDK for creating MCP tools, resources, and prompts.
- asyncpg: High-performance, asynchronous PostgreSQL client library.
- sqlglot: SQL parser and transpiler used to inspect ASTs and validate query safety.
- python-dotenv: Configuration management via
.envfiles.
Installation & Configuration
Prerequisites
- Python 3.10+
- PostgreSQL database instance
pg_dump(Optional, fallback Python backup generator will be used if missing)
Installation
- Clone the repository and navigate to the project directory:
cd "Postgres MCP" - Create and activate a virtual environment:
python3 -m venv venv source venv/bin/activate - Install the dependencies:
pip install -r requirements.txt
Configuration
Create a .env file in the root of the workspace directory. The server loads parameters using both standard PostgreSQL keys and user-friendly aliases:
# Database Connection (Uses URL or individual variables)
DATABASE_URL=postgresql://user:password@host:5432/dbname
# Fallback individual configuration parameters
DB_HOST=localhost
DB_PORT=5432
DB_USER=postgres
DB_PASSWORD=your_password
DB_NAME=postgres
# SSL / TLS Settings ('disable', 'prefer', 'require', 'verify-ca', 'verify-full')
PGSSLMODE=prefer
# Row limit guardrail for SELECT queries
ROW_LIMIT=500
# Large Scale Operation Threshold (triggers Disposable Environment testing)
LARGE_SCALE_THRESHOLD=1000
# Backup Retention Configurations
BACKUP_DIR=./backups
MAX_BACKUPS=10
MAX_BACKUP_AGE_DAYS=7.0
DB_BACKUP_THRESHOLD_BYTES=10485760 # 10MB
MCP Client Integration (mcp.json)
To register the server with an MCP client (such as Claude Desktop or other AI interfaces), add the server setup details to your client configuration file.
Use absolute paths for the virtual environment's python interpreter and the mcp_server.py script:
{
"mcpServers": {
"postgres-mcp": {
"command": "/Users/dbearsong/Documents/projects/python/Postgres MCP/venv/bin/python",
"args": [
"/Users/dbearsong/Documents/projects/python/Postgres MCP/mcp_server.py"
],
"env": {
"DB_HOST": "192.168.1.89",
"DB_PORT": "5432",
"DB_USER": "postgres",
"DB_PASSWORD": "G382XM284YZ-1281!Cy7127#",
"DB_NAME": "job_searcher"
}
}
}
}
Note: Passing environment variables inside the "env" key in the client configuration is a secure way to supply database credentials at runtime.
Usage Examples
Running the Server
Run the main script to start the server over stdio transport:
python mcp_server.py
Context Injection (Resources)
The server exposes the database schema to the AI via:
- Resource URI:
postgres://schema- Returns: A complete Markdown outline of all tables, comments, column types, nullability, defaults, check constraints, indexes, and foreign keys.
Tools Exposed to the AI
1. get_schema_info
Lists all database tables and schema-wide foreign key relationships.
2. get_table_details
Retrieves column schemas, CHECK constraints, indexes, and descriptions for a specific table.
- Parameters:
table_name(string)
3. execute_read_query
Executes a read-only query. Limits results to ROW_LIMIT (default 500) and returns results in a structured JSON format.
- Parameters:
query(string): e.g.,"SELECT name, email FROM users WHERE age > $1"parameters(list, optional): e.g.,[25]explain(boolean, optional): PrependEXPLAIN ANALYZEto the query.
4. execute_write_query
Executes write queries (INSERT, UPDATE, DELETE). Requires explicit confirmation.
- Parameters:
query(string): e.g.,"INSERT INTO users (name, email) VALUES ($1, $2)"parameters(list, optional): e.g.,["Alice", "alice@example.com"]confirm(boolean): DefaultFalse. IfFalse, the query is not run and apending_approvalmessage is returned.
5. delete_records
Deletes rows from a table. Backs up matching records to a timestamped CSV before performing the delete. Rotates backups based on retention settings, and runs a full database backup if the CSV size exceeds the database backup threshold.
- Parameters:
table_name(string)where_clause(string): e.g.,"id = $1"(Must not be empty or evaluate to1=1)parameters(list, optional): e.g.,[104]confirm(boolean): DefaultFalse.
6. export_to_csv
Executes a SELECT query and exports the structured results directly to a CSV file in the backups directory.
- Parameters:
query(string)parameters(list, optional)filename(string, optional)
7. backup_database
Runs a full database schema and data backup immediately.
Contribution Guidelines
We welcome contributions to enhance security features, support additional dialects, or improve parsing performance.
Project Layout
- [config.py](file:///Users/dbearsong/Documents/projects/python/Postgres%20MCP/config.py): Configuration parser.
- [safety.py](file:///Users/dbearsong/Documents/projects/python/Postgres%20MCP/safety.py): Query AST checks and literal validation.
- [database.py](file:///Users/dbearsong/Documents/projects/python/Postgres%20MCP/database.py): Connection pool and database queries.
- [backup.py](file:///Users/dbearsong/Documents/projects/python/Postgres%20MCP/backup.py): Pre-deletion backups and retention rotation.
- [mcp_server.py](file:///Users/dbearsong/Documents/projects/python/Postgres%20MCP/mcp_server.py): FastMCP API registration.
- [test_server.py](file:///Users/dbearsong/Documents/projects/python/Postgres%20MCP/test_server.py): Integration test suite.
Testing
To run the integration and safety test suite, ensure your .env connection values are set and run:
python test_server.py
Note: The test suite sets up temporary tables (test_mcp_users, test_mcp_logs), executes query tools, attempts SQL injection/destructive actions, validates backups, and cleans up the tables automatically upon completion.
推荐服务器
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 模型以安全和受控的方式获取实时的网络信息。