PostgreSQL MCP Server
PostgreSQL MCP-Server
Ein produktionsreifer Model Context Protocol (MCP) Server, der es Benutzern ermöglicht, über natürliche Sprache mit PostgreSQL-Datenbanken zu interagieren. Der Server basiert auf FastMCP, wandelt natürlichsprachliche Fragen in sichere SQL-Abfragen um, führt diese aus und validiert die Ergebnisse. Einige Referenzdokumente:
Python Postgres MCP Bedarfsanalyse : https://gemini.google.com/share/c87a73f0969b
SQLGlot Deep-Dive-Konzept : https://gemini.google.com/share/cc5e45c76c8f
Funktionen
Natürliche Sprache zu SQL: Verwendet GPT-5.2-mini, um einfache englische Fragen in optimierte PostgreSQL-Abfragen umzuwandeln
Sicherheit zuerst: Erzwingung von Read-Only, Blockierung gefährlicher Funktionen, Schutz vor SQL-Injection, Abfrage-Timeout-Kontrolle
Ergebnisvalidierung: KI-basierte Ergebnisvalidierung mit Konfidenzbewertung
Intelligentes Schema: Automatisches Schema-Caching mit TTL-basiertem Aktualisierungsmechanismus
Produktionsbereit: Verbindungspool-Management, Circuit Breaker, Ratenbegrenzung, umfassende Metrikerfassung
MCP-kompatibel: Unterstützt Claude Desktop und jeden MCP-kompatiblen Client
Related MCP server: PostgreSQL MCP Server
Schnellstart
Voraussetzungen
Python 3.14+
PostgreSQL 12+
OpenAI API-Schlüssel (für GPT-5.2-mini)
UV-Paketmanager (empfohlen) oder pip
Installation
Mit UV (empfohlen)
# 克隆仓库
git clone <repository-url>
cd pg-mcp
# 安装依赖
uv sync
# 复制环境配置模板
cp .env.example .env
# 编辑 .env 并配置参数
vi .envMit pip
# 克隆仓库
git clone <repository-url>
cd pg-mcp
# 创建虚拟环境
python -m venv .venv
source .venv/bin/activate # Windows 系统: .venv\Scripts\activate
# 安装依赖
pip install -e .
# 复制环境配置模板
cp .env.example .env
# 编辑 .env 并配置参数
vi .envKonfiguration
Bearbeiten Sie die .env-Datei, um Ihre Einstellungen zu konfigurieren:
# 数据库配置
DATABASE_HOST=localhost
DATABASE_PORT=5432
DATABASE_NAME=your_database
DATABASE_USER=your_user
DATABASE_PASSWORD=your_password
# OpenAI 配置
OPENAI_API_KEY=sk-your-api-key-here
OPENAI_MODEL=gpt-5.2-mini
# 安全设置(可选,显示默认值)
SECURITY_ALLOW_WRITE_OPERATIONS=false
SECURITY_MAX_ROWS=10000
SECURITY_MAX_EXECUTION_TIME=30Für vollständige Konfigurationsoptionen siehe .env.example.
Server starten
Standalone-Modus
# 使用 UV
uv run python main.py
# 或使用 pip
python main.pyIntegration mit Claude Desktop
Fügen Sie die folgende Konfiguration zur Claude Desktop MCP-Konfigurationsdatei hinzu:
macOS/Linux: ~/Library/Application Support/Claude/claude_desktop_config.json
Windows: %APPDATA%\Claude\claude_desktop_config.json
{
"mcpServers": {
"postgres": {
"command": "uv",
"args": [
"--directory",
"/absolute/path/to/pg-mcp",
"run",
"python",
"main.py"
],
"env": {
"DATABASE_HOST": "localhost",
"DATABASE_NAME": "your_database",
"DATABASE_USER": "your_user",
"DATABASE_PASSWORD": "your_password",
"OPENAI_API_KEY": "sk-your-api-key-here"
}
}
}
}Ausführliche Konfigurationsanweisungen finden Sie unter Claude Desktop Konfiguration.
Verwendung
Beispielabfragen
Nach der Verbindung über Claude Desktop oder einen anderen MCP-Client können Sie Fragen in natürlicher Sprache stellen:
Einfache Abfrage
How many tables are in the database?
→ SELECT COUNT(*) FROM information_schema.tables WHERE table_schema = 'public'
Show me all users
→ SELECT * FROM users LIMIT 10000
What are the column names in the products table?
→ SELECT column_name, data_type FROM information_schema.columns
WHERE table_name = 'products'Analyse-Abfrage
What are the top 10 products by sales?
→ SELECT product_name, SUM(quantity * price) as total_sales
FROM orders
GROUP BY product_name
ORDER BY total_sales DESC
LIMIT 10
How many users registered in the last 30 days?
→ SELECT COUNT(*) FROM users
WHERE created_at > CURRENT_DATE - INTERVAL '30 days'Nur-SQL-Modus
Sie können auch nur SQL anfordern, ohne es auszuführen:
Generate SQL to find duplicate emails
Return Type: sql
→ Returns: SELECT email, COUNT(*) FROM users GROUP BY email HAVING COUNT(*) > 1Rückgabetypen
Der Server unterstützt zwei Rückgabetypen:
result(Standard): Führt die Abfrage aus und gibt die Ergebnisse zurücksql: Generiert und validiert SQL, führt es aber nicht aus
Antwortformat
Antwort bei erfolgreicher Abfrage
{
"success": true,
"generated_sql": "SELECT COUNT(*) FROM users",
"data": {
"columns": ["count"],
"rows": [[1523]],
"row_count": 1,
"execution_time": 0.023
},
"confidence": 95,
"tokens_used": 234
}Antwort bei Nur-SQL-Modus
{
"success": true,
"generated_sql": "SELECT * FROM users WHERE created_at > CURRENT_DATE - INTERVAL '30 days'",
"confidence": 90,
"tokens_used": 156
}Fehlerantwort
{
"success": false,
"error": {
"code": "SECURITY_VIOLATION",
"message": "Query contains blocked operation: DELETE",
"details": {
"blocked_operation": "DELETE"
}
}
}Architektur
Kernkomponenten
┌─────────────────────────────────────────────────────────────┐
│ MCP Server (FastMCP) │
└─────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ Query Orchestrator │
│ - Coordinates all components │
│ - Manages retry logic │
│ - Handles error recovery │
└─────────────────────────────────────────────────────────────┘
│ │ │
▼ ▼ ▼
┌───────────┐ ┌────────────┐ ┌──────────────┐
│ SQL │ │ SQL │ │ SQL │
│ Generator │────▶│ Validator │────▶│ Executor │
│ (LLM) │ │ (Security) │ │ (Database) │
└───────────┘ └────────────┘ └──────────────┘
│ │
▼ ▼
┌───────────┐ ┌──────────────┐
│ Schema │ │ Result │
│ Cache │ │ Validator │
└───────────┘ │ (LLM) │
└──────────────┘Sicherheitsmerkmale
Erzwingung von Read-Only: Standardmäßig sind nur SELECT-Abfragen erlaubt
Blockierung gefährlicher Funktionen: Blacklist enthält gefährliche PostgreSQL-Funktionen (pg_sleep, Datei-I/O, etc.)
SQL-Parsing: Verwendung von sqlglot für eine präzise SQL-Strukturvalidierung
Injection-Schutz: Parametrisierte Abfragen und Eingabebereinigung
Ressourcenbeschränkungen:
Zeilenlimit (Standard: 10.000)
Abfrage-Timeout (Standard: 30 Sekunden)
Verbindungspool-Management
Transaktionsisolation: Alle Abfragen laufen in einer Read-Only-Transaktion
Resilienzmerkmale
Circuit Breaker: Verhindert kaskadierende LLM-API-Fehler
Ratenbegrenzung: Verhindert die Erschöpfung des API-Kontingents
Wiederholungslogik: Automatische Wiederholung bei transienten Fehlern mit exponentiellem Backoff
Verbindungspooling: Effiziente Wiederverwendung von Datenbankverbindungen
Schema-Caching: TTL-basiertes Caching reduziert Datenbank-Metadatenabfragen
Konfigurationsreferenz
Datenbankeinstellungen
Variable | Beschreibung | Standardwert |
| PostgreSQL-Host |
|
| PostgreSQL-Port |
|
| Datenbankname | Erforderlich |
| Datenbankbenutzer | Erforderlich |
| Datenbankpasswort | Erforderlich |
| Min. Verbindungen im Pool |
|
| Max. Verbindungen im Pool |
|
| Abfrage-Timeout (Sek.) |
|
OpenAI-Einstellungen
Variable | Beschreibung | Standardwert |
| OpenAI API-Schlüssel | Erforderlich |
| Verwendetes Modell |
|
| Max. Token pro Anfrage |
|
| Modell-Temperatur |
|
| API-Timeout (Sek.) |
|
Sicherheitseinstellungen
Variable | Beschreibung | Standardwert |
| Erlaubt INSERT/UPDATE/DELETE |
|
| Kommagetrennte Blacklist | Siehe .env.example |
| Max. Zeilen pro Abfrage |
|
| Abfrage-Timeout (Sek.) |
|
Cache-Einstellungen
Variable | Beschreibung | Standardwert |
| Schema-Caching aktivieren |
|
| Schema-Cache TTL (Sek.) |
|
| Max. Anzahl gecachter Schemas |
|
Resilienzeinstellungen
Variable | Beschreibung | Standardwert |
| Max. Wiederholungsversuche |
|
| Initiale Verzögerung (Sek.) |
|
| Exponentieller Backoff-Faktor |
|
| Fehler vor Circuit Break |
|
| Circuit Breaker Timeout (Sek.) |
|
Beobachtbarkeitseinstellungen
Variable | Beschreibung | Standardwert |
| Prometheus-Metriken aktivieren |
|
| Metriken HTTP-Port |
|
| Log-Level |
|
| Log-Format (json/text) |
|
Entwicklung
Entwicklungsumgebung einrichten
# 安装开发依赖
uv sync --all-extras
# 安装 pre-commit 钩子(可选)
pre-commit installTests ausführen
# 运行所有测试
uv run pytest
# 运行并生成覆盖率报告
uv run pytest --cov=src --cov-report=html
# 运行特定测试类别
uv run pytest tests/unit/ # 仅单元测试
uv run pytest tests/integration/ # 集成测试
uv run pytest tests/e2e/ # 端到端测试
uv run pytest -m integration # 标记为集成的测试Codequalität
# 类型检查
uv run mypy src
# Lint 和格式化
uv run ruff check --fix .
uv run ruff format .
# 运行所有质量检查
uv run pytest --cov=src --cov-fail-under=80
uv run mypy src
uv run ruff check .Projektstruktur
pg-mcp/
├── src/pg_mcp/
│ ├── cache/ # Schema 缓存
│ ├── config/ # 配置管理
│ ├── db/ # 数据库连接池
│ ├── models/ # 数据模型
│ ├── observability/ # 日志、指标、追踪
│ ├── prompts/ # LLM Prompt 模板
│ ├── resilience/ # 熔断器、限流器
│ ├── services/ # 核心业务逻辑
│ │ ├── orchestrator.py # 查询协调
│ │ ├── sql_generator.py # 基于 LLM 的 SQL 生成
│ │ ├── sql_validator.py # 安全验证
│ │ ├── sql_executor.py # 查询执行
│ │ └── result_validator.py # 结果验证
│ └── server.py # FastMCP 服务器
├── tests/
│ ├── unit/ # 单元测试
│ ├── integration/ # 集成测试
│ └── e2e/ # 端到端测试
├── fixtures/ # 测试数据库 fixture
├── .env.example # 环境模板
├── pyproject.toml # 项目配置
└── main.py # 入口点Docker-Bereitstellung
Image bauen
docker build -t pg-mcp:latest .Container ausführen
docker run -d \
--name pg-mcp \
-e DATABASE_HOST=your-db-host \
-e DATABASE_NAME=your-db \
-e DATABASE_USER=your-user \
-e DATABASE_PASSWORD=your-password \
-e OPENAI_API_KEY=sk-your-key \
-p 9090:9090 \
pg-mcp:latestDocker Compose
# 启动所有服务(PostgreSQL + pg-mcp)
docker-compose up -d
# 查看日志
docker-compose logs -f pg-mcp
# 停止服务
docker-compose downAusführliche Konfiguration siehe docker-compose.yml.
Überwachung
Metriken
Der Server stellt Prometheus-Metriken auf Port 9090 (konfigurierbar) bereit:
curl http://localhost:9090/metricsVerfügbare Metriken:
pg_mcp_queries_total- Gesamtzahl der verarbeiteten Abfragenpg_mcp_query_duration_seconds- Histogramm der Abfrageausführungszeitpg_mcp_sql_generation_duration_seconds- SQL-Generierungszeitpg_mcp_sql_validation_failures_total- Anzahl der Validierungsfehlerpg_mcp_database_errors_total- Anzahl der Datenbankfehlerpg_mcp_llm_tokens_used_total- Gesamtzahl der verwendeten LLM-Token
Logs
Strukturierte JSON-Logs (oder Textformat) werden an stdout ausgegeben:
{
"timestamp": "2025-12-20T10:30:00.123Z",
"level": "INFO",
"message": "Query executed successfully",
"database": "mydb",
"execution_time": 0.023,
"row_count": 42
}Fehlerbehebung
Häufige Probleme
Verbindung verweigert
Error: Connection to database failedLösung: Überprüfen Sie, ob PostgreSQL läuft und die Anmeldedaten korrekt sind:
psql -h $DATABASE_HOST -U $DATABASE_USER -d $DATABASE_NAMEOpenAI API-Fehler
Error: OpenAI API request failedLösung:
Prüfen Sie, ob der API-Schlüssel gültig ist und über Guthaben verfügt
Überprüfen Sie die Netzwerkverbindung
Bei Timeout-Fehlern prüfen Sie die
OPENAI_TIMEOUT-Einstellung
Abfrage-Timeout
Error: Query execution timeout exceededLösung:
Erhöhen Sie
SECURITY_MAX_EXECUTION_TIMEOptimieren Sie die Datenbank (Indizes hinzufügen, VACUUM)
Vereinfachen Sie die Abfrage oder fügen Sie Filterbedingungen hinzu
Schema-Cache-Probleme
Error: Schema not found in cacheLösung:
Starten Sie den Server neu, um das Schema neu zu laden
Überprüfen Sie, ob der Datenbankbenutzer Leserechte für das Schema hat
Prüfen Sie, ob
CACHE_ENABLEDauftruegesetzt ist
Debug-Modus
Debug-Logs aktivieren:
export OBSERVABILITY_LOG_LEVEL=DEBUG
uv run python main.pyClaude Desktop Konfiguration
macOS/Linux Konfiguration
Bearbeiten Sie ~/Library/Application Support/Claude/claude_desktop_config.json:
{
"mcpServers": {
"postgres": {
"command": "uv",
"args": [
"--directory",
"/Users/yourname/projects/pg-mcp",
"run",
"python",
"main.py"
],
"env": {
"DATABASE_HOST": "localhost",
"DATABASE_PORT": "5432",
"DATABASE_NAME": "mydb",
"DATABASE_USER": "postgres",
"DATABASE_PASSWORD": "your-password",
"OPENAI_API_KEY": "sk-your-api-key-here",
"OPENAI_MODEL": "gpt-5.2-mini",
"SECURITY_MAX_ROWS": "10000",
"CACHE_ENABLED": "true",
"OBSERVABILITY_LOG_LEVEL": "INFO"
}
}
}
}Windows Konfiguration
Bearbeiten Sie %APPDATA%\Claude\claude_desktop_config.json:
{
"mcpServers": {
"postgres": {
"command": "uv",
"args": [
"--directory",
"C:\\Users\\YourName\\projects\\pg-mcp",
"run",
"python",
"main.py"
],
"env": {
"DATABASE_HOST": "localhost",
"DATABASE_NAME": "mydb",
"DATABASE_USER": "postgres",
"DATABASE_PASSWORD": "your-password",
"OPENAI_API_KEY": "sk-your-api-key-here"
}
}
}
}Python Virtualenv verwenden
Wenn Sie kein UV verwenden, konfigurieren Sie Python direkt:
{
"mcpServers": {
"postgres": {
"command": "/absolute/path/to/pg-mcp/.venv/bin/python",
"args": ["main.py"],
"cwd": "/absolute/path/to/pg-mcp",
"env": {
"DATABASE_HOST": "localhost",
...
}
}
}
}Claude Desktop neu starten
Nach dem Bearbeiten der Konfiguration:
Beenden Sie Claude Desktop vollständig
Starten Sie Claude Desktop neu
Der PostgreSQL MCP-Server ist nun verfügbar
Sicherheitsüberlegungen
Bereitstellung in der Produktion
Verwenden Sie einen Read-Only-Datenbankbenutzer: Erstellen Sie einen dedizierten PostgreSQL-Benutzer, der nur SELECT-Berechtigungen hat:
CREATE USER pg_mcp_readonly WITH PASSWORD 'secure-password';
GRANT CONNECT ON DATABASE your_database TO pg_mcp_readonly;
GRANT USAGE ON SCHEMA public TO pg_mcp_readonly;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO pg_mcp_readonly;
ALTER DEFAULT PRIVILEGES IN SCHEMA public
GRANT SELECT ON TABLES TO pg_mcp_readonly;API-Schlüssel schützen: Verwenden Sie Umgebungsvariablen oder Secret-Management-Systeme, niemals in die Versionskontrolle einchecken
Netzwerkisolierung: Betreiben Sie den Server in einem isolierten Netzwerk und beschränken Sie den Datenbankzugriff per IP
Nutzung überwachen: Aktivieren Sie Metriken und richten Sie Alarme für ungewöhnliche Muster ein
Ratenbegrenzung: Konfigurieren Sie geeignete Ratenbegrenzungsparameter, um Missbrauch zu verhindern
Log-Bereinigung: Sensible Daten werden automatisch aus den Logs gefiltert
Lizenz
[Ihre Lizenzinformationen]
Mitwirken
Beiträge sind willkommen! Bitte lesen Sie CONTRIBUTING.md für Richtlinien.
Support
Bei Fragen und Problemen:
GitHub Issues: [repository-url]/issues
Dokumentation: Siehe Verzeichnis
specs/w5/für detaillierte Designdokumente
Danksagungen
Available Tools
1 tooladdA
Add two numbers
| Name | Required | Description | Default |
|---|---|---|---|
| a | Yes | ||
| b | Yes |
Output Schema
| Name | Required | Description |
|---|---|---|
| result | Yes |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations are provided, so the description carries the behavioral burden. 'Add two numbers' accurately and sufficiently communicates a pure arithmetic operation, with no indication of side effects or hidden behavior.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is four words long, contains zero filler, and conveys the complete operation. It is front-loaded and every word earns its place.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
For a simple two-integer addition tool with an output schema and no siblings, this description is nearly complete. It could mention the return value or pure behavior explicitly, but the output schema and inherent simplicity reduce that need.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema description coverage is 0%, so the description must compensate. It clarifies that both parameters are numbers to be added, but it does not name them or describe each parameter individually. Since addition is commutative, the lack of role differentiation is a minor gap.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description states a precise verb ('add') and a clear resource ('two numbers'), making the tool's purpose immediately obvious. With no sibling tools, there is no ambiguity to resolve.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The intended use is clear: this tool is for summing two numbers. It does not explicitly discuss when not to use it, but with no sibling tools and only two integer parameters, the context is straightforward.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
1 tool update
v0.2.1- First observed
add
TDQS
Scored across 1 tool
Only one tool exists, so no ambiguity between tools.
With a single tool, naming consistency is inherently maintained.
A single trivial arithmetic tool is extremely thin for a PostgreSQL MCP server, fitting the description of an extreme mismatch.
The server's name suggests database-related functionality, but the only tool adds two numbers, leaving the entire database surface missing.
Maintenance
Related MCP Connectors
Query PostgreSQL databases in plain English — LLM-generated, safety-validated SQL.
Deterministic safety, correctness & cost gate that vets Postgres SQL before your AI agent runs it.
Query Postgres, MySQL, SQL Server, Oracle, BigQuery, ClickHouse and Redshift from your AI client.
Ask data questions in natural language. Get SQL, insights, and charts from your databases.
Related MCP Servers
- -licenseNot gradedqualityNot gradedmaintenanceEnables secure read-only interactions with PostgreSQL databases through natural language. Provides database inspection, table listing, and SQL query execution with built-in security validation.-
- AlicenseAqualityBmaintenanceEnables read-only interaction with PostgreSQL databases through natural language queries, supporting dynamic connections and secure query validation.3134 npm2MIT
- FlicenseNot gradedqualityDmaintenanceEnables AI assistants to interact with PostgreSQL databases through natural language queries, schema inspection, and safe SQL execution.6 npm1-
- FlicenseNot gradedqualityDmaintenanceConverts natural language to safe SQL queries for PostgreSQL databases with read-only access and multi-layer security validation. Provides tools for running validated SELECT queries, retrieving schema, and sampling table data.-