pg-mcp
pg-mcp
通过 MCP(模型上下文协议)实现的自然语言 PostgreSQL 查询服务。使用 OpenAI 将自然语言转换为 SQL,进行安全验证并执行,然后将结果返回给任何支持 MCP 的客户端。
功能特性
通过 OpenAI 将自然语言转换为 SQL
启动时自动发现数据库架构(表、视图、列、索引、外键、枚举)
带有可选磁盘持久化的架构缓存
SQL 安全验证(仅限 SELECT,拦截危险函数,强制执行 LIMIT)
带有可配置超时的只读事务执行
结果验证,并在结果为空时自动重试
支持多个数据库
Related MCP server: PostgreSQL MCP Server
要求
Python 3.11+
PostgreSQL
OpenAI API 密钥
安装
pip install -e .开发环境安装:
pip install -e ".[dev]"配置
将 .env.example 复制为 .env 并填入您的值:
cp .env.example .env变量 | 必需 | 默认值 | 描述 |
| 是 | — | 以逗号分隔的 PostgreSQL 连接字符串 |
| 否 | 第一个 DSN | 查询的默认数据库 |
| 是 | — | OpenAI API 密钥 |
| 否 |
| 用于 SQL 生成的模型 |
| 否 | OpenAI 默认 | 自定义端点(Azure、代理等) |
| 否 |
| 查询超时时间(秒) |
| 否 |
| 返回的最大行数(1-1000) |
| 否 | 无 | 持久化架构缓存的路径 |
| 否 |
|
|
多数据库示例:
PG_MCP_DATABASES=postgresql://user:pass@host1:5432/db1,postgresql://user:pass@host2:5432/db2在 Claude Desktop 中使用
添加到您的 claude_desktop_config.json:
{
"mcpServers": {
"pg-mcp": {
"command": "pg-mcp",
"args": [],
"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 工具
query
使用自然语言查询数据库。
{
"question": "What are the top 10 customers by sales last month?",
"database": "mydb",
"return_sql": false,
"max_rows": 100
}return_sql: true— 返回生成的 SQL 而不执行return_sql: false(默认) — 执行并返回结果
list_databases
列出所有可访问的数据库及其摘要信息。
describe_database
获取数据库的详细架构信息。
{
"database": "mydb",
"schema": "public",
"pattern": "user"
}refresh_schema
从数据库重新加载架构缓存。
{
"database": "mydb"
}省略 database 参数可刷新所有数据库。
使用测试数据库进行测试
fixtures/ 目录提供了三个预构建的数据库用于本地测试。
设置
# From project root, create & seed all fixture databases
cd fixtures
make all
# Or create individual ones
make small # pg_mcp_test_small — bookshelf (4 tables, ~50 rows)
make medium # pg_mcp_test_medium — ecommerce (12 tables, ~500 rows)
make large # pg_mcp_test_large — enterprise (28 tables, ~5000 rows)通过环境变量覆盖 PostgreSQL 凭据(默认:root / admin123 @ localhost:5432):
make all PGUSER=myuser PGPASSWORD=mypass PGHOST=127.0.0.1配置 .env
将 PG_MCP_DATABASES 指向测试数据库:
PG_MCP_DATABASES=postgresql://root:admin123@localhost:5432/pg_mcp_test_small,postgresql://root:admin123@localhost:5432/pg_mcp_test_medium,postgresql://root:admin123@localhost:5432/pg_mcp_test_large使用 MCP Inspector 进行测试
使用内置的 MCP inspector 进行交互式测试:
cd /path/to/postgres-mcp
fastmcp dev src/pg_mcp/server.py:mcp这将打开一个浏览器 UI,您可以在其中直接调用 query、list_databases 和 describe_database 等工具。
使用 Claude Desktop 进行测试
添加到 claude_desktop_config.json:
{
"mcpServers": {
"pg-mcp": {
"command": "python3",
"args": ["-m", "pg_mcp.server"],
"cwd": "/path/to/postgres-mcp"
}
}
}注意:使用
cwd时,服务器会从该目录读取.env。您也可以通过"env"键传递环境变量。
测试查询
连接后,尝试针对测试数据库进行以下自然语言查询:
数据库 | 示例查询 |
| "列出所有评分高于4分的图书" |
| "哪个国家的作者最多" |
| "上个月销量前10的商品" |
| "每个用户的总消费金额" |
| "各部门员工数量和平均薪资" |
| "今年收入最高的前5个销售代表" |
清理
cd fixtures
make drop-all # Remove all fixture databases
make refresh-all # Drop + recreate + re-seed运行测试
python3 -m pytest tests/ -v工作原理
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安全性
生成的 SQL 经过验证,确保仅限 SELECT 操作(包括 CTE 检查)
拦截了 40 多种危险的 PostgreSQL 函数(会话控制、咨询锁、dblink、文件系统访问、序列修改等)
所有查询均在只读事务中执行
自动强制执行 LIMIT 以防止返回过大的结果集
查询超时设置可防止长时间运行的查询
连接密码绝不会出现在日志或 API 响应中
This server cannot be deployed
Maintenance
Related MCP Connectors
Query PostgreSQL databases in plain English — LLM-generated, safety-validated SQL.
Text-to-SQL MCP server: read-only queries on PostgreSQL, MySQL and SQL Server with your real schema
Query your org's data in natural language — read-only MCP access to SQL, NoSQL, files & warehouses.
Query your warehouse or a CSV with Claude/ChatGPT over MCP, governed by table-level ACL + audit.
Related MCP Servers
- -licenseNot gradedqualityAmaintenanceA Model Context Protocol server that provides read-only access to PostgreSQL databases. This server enables LLMs to inspect database schemas and execute read-only queries.122,323 npm91,120MIT
- AlicenseNot gradedqualityDmaintenanceA Model Context Protocol server providing LLMs read-only access to PostgreSQL databases for inspecting schemas and executing queries.122,323 npm27MIT
- FlicenseDqualityDmaintenanceA secure Model Context Protocol server that allows Claude to execute read-only SQL queries against a PostgreSQL database, enabling natural language interaction with database data.1-
- AlicenseNot gradedqualityDmaintenanceEnables AI agents to query, explore, and analyze PostgreSQL databases through the Model Context Protocol. It provides robust security features including read-only mode, schema restrictions, and query timeouts for safe data interaction.7 npmMIT