pg-mcp

pg-mcp

Enables natural language querying of PostgreSQL databases through the Model Context Protocol. It translates user questions into validated SQL, executes read-only queries safely, and returns results to MCP-compatible clients like Claude Desktop.

Category
访问服务器

README

pg-mcp

Natural language PostgreSQL query service via MCP (Model Context Protocol). Uses OpenAI to translate natural language into SQL, validates and executes it safely, and returns results to any MCP-compatible client.

Features

  • Natural language to SQL via OpenAI
  • Auto-discovers database schema on startup (tables, views, columns, indexes, foreign keys, enums)
  • Schema cache with optional disk persistence
  • SQL safety validation (SELECT-only, dangerous function blocking, LIMIT enforcement)
  • Read-only transaction execution with configurable timeout
  • Result validation with automatic retry on empty results
  • Supports multiple databases

Requirements

  • Python 3.11+
  • PostgreSQL
  • OpenAI API key

Installation

pip install -e .

For development:

pip install -e ".[dev]"

Configuration

Copy .env.example to .env and fill in your values:

cp .env.example .env
Variable Required Default Description
PG_MCP_DATABASES Yes Comma-separated PostgreSQL connection strings
PG_MCP_DEFAULT_DB No First DSN Default database for queries
OPENAI_API_KEY Yes OpenAI API key
OPENAI_MODEL No gpt-4o Model to use for SQL generation
OPENAI_BASE_URL No OpenAI default Custom endpoint (Azure, proxy, etc.)
PG_MCP_QUERY_TIMEOUT No 30 Query timeout in seconds
PG_MCP_MAX_ROWS No 100 Max rows returned (1-1000)
PG_MCP_SCHEMA_CACHE_PATH No None Path for persistent schema cache
PG_MCP_LOG_LEVEL No INFO DEBUG / INFO / WARNING / ERROR

Multiple databases example:

PG_MCP_DATABASES=postgresql://user:pass@host1:5432/db1,postgresql://user:pass@host2:5432/db2

Usage with Claude Desktop

Add to your claude_desktop_config.json:

{
  "mcpServers": {
    "pg-mcp": {
      "command": "python3",
      "args": ["-m", "pg_mcp.server"],
      "env": {
        "PG_MCP_DATABASES": "postgresql://user:pass@localhost:5432/mydb",
        "OPENAI_API_KEY": "sk-...",
        "PG_MCP_SCHEMA_CACHE_PATH": "~/.cache/pg-mcp/schema.json"
      }
    }
  }
}

MCP Tools

query

Query a database using natural language.

{
  "question": "What are the top 10 customers by sales last month?",
  "database": "mydb",
  "return_sql": false,
  "max_rows": 100
}
  • return_sql: true — returns the generated SQL without executing
  • return_sql: false (default) — executes and returns results

list_databases

List all accessible databases with summary info.

describe_database

Get detailed schema info for a database.

{
  "database": "mydb",
  "schema": "public",
  "pattern": "user"
}

refresh_schema

Reload schema cache from the database.

{
  "database": "mydb"
}

Omit database to refresh all databases.

Running Tests

python3 -m pytest tests/ -v

How It Works

User question
  → Schema context assembled from cache
  → OpenAI generates SQL
  → Safety validation (SELECT-only, no dangerous functions, LIMIT injection)
  → Execute in read-only transaction with timeout
  → Optional result validation on empty results
  → Return SQL or query results

Security

  • Generated SQL is validated to be SELECT-only (including CTE checks)
  • Dangerous PostgreSQL functions are blocked (pg_sleep, lo_import, etc.)
  • All queries execute in read-only transactions
  • Automatic LIMIT enforcement prevents large result sets
  • Query timeout prevents long-running queries
  • Connection passwords never appear in logs or API responses

推荐服务器

Baidu Map

Baidu Map

百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。

官方
精选
JavaScript
Playwright MCP Server

Playwright MCP Server

一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。

官方
精选
TypeScript
Magic Component Platform (MCP)

Magic Component Platform (MCP)

一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。

官方
精选
本地
TypeScript
Audiense Insights MCP Server

Audiense Insights MCP Server

通过模型上下文协议启用与 Audiense Insights 账户的交互,从而促进营销洞察和受众数据的提取和分析,包括人口统计信息、行为和影响者互动。

官方
精选
本地
TypeScript
VeyraX

VeyraX

一个单一的 MCP 工具,连接你所有喜爱的工具:Gmail、日历以及其他 40 多个工具。

官方
精选
本地
graphlit-mcp-server

graphlit-mcp-server

模型上下文协议 (MCP) 服务器实现了 MCP 客户端与 Graphlit 服务之间的集成。 除了网络爬取之外,还可以将任何内容(从 Slack 到 Gmail 再到播客订阅源)导入到 Graphlit 项目中,然后从 MCP 客户端检索相关内容。

官方
精选
TypeScript
Kagi MCP Server

Kagi MCP Server

一个 MCP 服务器,集成了 Kagi 搜索功能和 Claude AI,使 Claude 能够在回答需要最新信息的问题时执行实时网络搜索。

官方
精选
Python
e2b-mcp-server

e2b-mcp-server

使用 MCP 通过 e2b 运行代码。

官方
精选
Neon MCP Server

Neon MCP Server

用于与 Neon 管理 API 和数据库交互的 MCP 服务器

官方
精选
Exa MCP Server

Exa MCP Server

模型上下文协议(MCP)服务器允许像 Claude 这样的 AI 助手使用 Exa AI 搜索 API 进行网络搜索。这种设置允许 AI 模型以安全和受控的方式获取实时的网络信息。

官方
精选