Skip to main content
Glama
lastfore

PostgreSQL MCP Server

by lastfore

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:

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 .env

Mit 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 .env

Konfiguration

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=30

Für vollständige Konfigurationsoptionen siehe .env.example.

Server starten

Standalone-Modus

# 使用 UV
uv run python main.py

# 或使用 pip
python main.py

Integration 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(*) > 1

Rückgabetypen

Der Server unterstützt zwei Rückgabetypen:

  • result (Standard): Führt die Abfrage aus und gibt die Ergebnisse zurück

  • sql: 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

  1. Erzwingung von Read-Only: Standardmäßig sind nur SELECT-Abfragen erlaubt

  2. Blockierung gefährlicher Funktionen: Blacklist enthält gefährliche PostgreSQL-Funktionen (pg_sleep, Datei-I/O, etc.)

  3. SQL-Parsing: Verwendung von sqlglot für eine präzise SQL-Strukturvalidierung

  4. Injection-Schutz: Parametrisierte Abfragen und Eingabebereinigung

  5. Ressourcenbeschränkungen:

    • Zeilenlimit (Standard: 10.000)

    • Abfrage-Timeout (Standard: 30 Sekunden)

    • Verbindungspool-Management

  6. 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

DATABASE_HOST

PostgreSQL-Host

localhost

DATABASE_PORT

PostgreSQL-Port

5432

DATABASE_NAME

Datenbankname

Erforderlich

DATABASE_USER

Datenbankbenutzer

Erforderlich

DATABASE_PASSWORD

Datenbankpasswort

Erforderlich

DATABASE_MIN_POOL_SIZE

Min. Verbindungen im Pool

5

DATABASE_MAX_POOL_SIZE

Max. Verbindungen im Pool

20

DATABASE_COMMAND_TIMEOUT

Abfrage-Timeout (Sek.)

30

OpenAI-Einstellungen

Variable

Beschreibung

Standardwert

OPENAI_API_KEY

OpenAI API-Schlüssel

Erforderlich

OPENAI_MODEL

Verwendetes Modell

gpt-5.2-mini

OPENAI_MAX_TOKENS

Max. Token pro Anfrage

32000

OPENAI_TEMPERATURE

Modell-Temperatur

0.0

OPENAI_TIMEOUT

API-Timeout (Sek.)

30

Sicherheitseinstellungen

Variable

Beschreibung

Standardwert

SECURITY_ALLOW_WRITE_OPERATIONS

Erlaubt INSERT/UPDATE/DELETE

false

SECURITY_BLOCKED_FUNCTIONS

Kommagetrennte Blacklist

Siehe .env.example

SECURITY_MAX_ROWS

Max. Zeilen pro Abfrage

10000

SECURITY_MAX_EXECUTION_TIME

Abfrage-Timeout (Sek.)

30

Cache-Einstellungen

Variable

Beschreibung

Standardwert

CACHE_ENABLED

Schema-Caching aktivieren

true

CACHE_SCHEMA_TTL

Schema-Cache TTL (Sek.)

3600

CACHE_MAX_SIZE

Max. Anzahl gecachter Schemas

100

Resilienzeinstellungen

Variable

Beschreibung

Standardwert

RESILIENCE_MAX_RETRIES

Max. Wiederholungsversuche

3

RESILIENCE_RETRY_DELAY

Initiale Verzögerung (Sek.)

1.0

RESILIENCE_BACKOFF_FACTOR

Exponentieller Backoff-Faktor

2.0

RESILIENCE_CIRCUIT_BREAKER_THRESHOLD

Fehler vor Circuit Break

5

RESILIENCE_CIRCUIT_BREAKER_TIMEOUT

Circuit Breaker Timeout (Sek.)

60

Beobachtbarkeitseinstellungen

Variable

Beschreibung

Standardwert

OBSERVABILITY_METRICS_ENABLED

Prometheus-Metriken aktivieren

true

OBSERVABILITY_METRICS_PORT

Metriken HTTP-Port

9090

OBSERVABILITY_LOG_LEVEL

Log-Level

INFO

OBSERVABILITY_LOG_FORMAT

Log-Format (json/text)

json

Entwicklung

Entwicklungsumgebung einrichten

# 安装开发依赖
uv sync --all-extras

# 安装 pre-commit 钩子(可选)
pre-commit install

Tests 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:latest

Docker Compose

# 启动所有服务(PostgreSQL + pg-mcp)
docker-compose up -d

# 查看日志
docker-compose logs -f pg-mcp

# 停止服务
docker-compose down

Ausführliche Konfiguration siehe docker-compose.yml.

Überwachung

Metriken

Der Server stellt Prometheus-Metriken auf Port 9090 (konfigurierbar) bereit:

curl http://localhost:9090/metrics

Verfügbare Metriken:

  • pg_mcp_queries_total - Gesamtzahl der verarbeiteten Abfragen

  • pg_mcp_query_duration_seconds - Histogramm der Abfrageausführungszeit

  • pg_mcp_sql_generation_duration_seconds - SQL-Generierungszeit

  • pg_mcp_sql_validation_failures_total - Anzahl der Validierungsfehler

  • pg_mcp_database_errors_total - Anzahl der Datenbankfehler

  • pg_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 failed

Lösung: Überprüfen Sie, ob PostgreSQL läuft und die Anmeldedaten korrekt sind:

psql -h $DATABASE_HOST -U $DATABASE_USER -d $DATABASE_NAME

OpenAI API-Fehler

Error: OpenAI API request failed

Lösung:

  1. Prüfen Sie, ob der API-Schlüssel gültig ist und über Guthaben verfügt

  2. Überprüfen Sie die Netzwerkverbindung

  3. Bei Timeout-Fehlern prüfen Sie die OPENAI_TIMEOUT-Einstellung

Abfrage-Timeout

Error: Query execution timeout exceeded

Lösung:

  1. Erhöhen Sie SECURITY_MAX_EXECUTION_TIME

  2. Optimieren Sie die Datenbank (Indizes hinzufügen, VACUUM)

  3. Vereinfachen Sie die Abfrage oder fügen Sie Filterbedingungen hinzu

Schema-Cache-Probleme

Error: Schema not found in cache

Lösung:

  1. Starten Sie den Server neu, um das Schema neu zu laden

  2. Überprüfen Sie, ob der Datenbankbenutzer Leserechte für das Schema hat

  3. Prüfen Sie, ob CACHE_ENABLED auf true gesetzt ist

Debug-Modus

Debug-Logs aktivieren:

export OBSERVABILITY_LOG_LEVEL=DEBUG
uv run python main.py

Claude 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:

  1. Beenden Sie Claude Desktop vollständig

  2. Starten Sie Claude Desktop neu

  3. Der PostgreSQL MCP-Server ist nun verfügbar

Sicherheitsüberlegungen

Bereitstellung in der Produktion

  1. 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;
  1. API-Schlüssel schützen: Verwenden Sie Umgebungsvariablen oder Secret-Management-Systeme, niemals in die Versionskontrolle einchecken

  2. Netzwerkisolierung: Betreiben Sie den Server in einem isolierten Netzwerk und beschränken Sie den Datenbankzugriff per IP

  3. Nutzung überwachen: Aktivieren Sie Metriken und richten Sie Alarme für ungewöhnliche Muster ein

  4. Ratenbegrenzung: Konfigurieren Sie geeignete Ratenbegrenzungsparameter, um Missbrauch zu verhindern

  5. 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 tool
addA

Add two numbers

ParametersJSON Schema
NameRequiredDescriptionDefault
aYes
bYes

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

A4.2/5.0
Behavior4/5

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.

Conciseness5/5

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.

Completeness4/5

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.

Parameters3/5

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.

Purpose5/5

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.

Usage Guidelines4/5

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. 1 tool updatev0.2.1
    • First observedadd

TDQS

B3.1/5.0

Scored across 1 tool

Disambiguation5/5

Only one tool exists, so no ambiguity between tools.

Naming Consistency5/5

With a single tool, naming consistency is inherently maintained.

Tool Count1/5

A single trivial arithmetic tool is extremely thin for a PostgreSQL MCP server, fitting the description of an extreme mismatch.

Completeness1/5

The server's name suggests database-related functionality, but the only tool adds two numbers, leaving the entire database surface missing.

Maintenance

ActivityInactive
ResponsivenessNo issues

Related MCP Connectors

Related MCP Servers

  • -
    license
    Not graded
    quality
    Not graded
    maintenance
    Enables secure read-only interactions with PostgreSQL databases through natural language. Provides database inspection, table listing, and SQL query execution with built-in security validation.
    -
  • A
    license
    A
    quality
    B
    maintenance
    Enables read-only interaction with PostgreSQL databases through natural language queries, supporting dynamic connections and secure query validation.
    3
    134 npm
    2
    MIT
  • F
    license
    Not graded
    quality
    D
    maintenance
    Converts 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.
    -