Skip to main content
Glama

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

变量

必需

默认值

描述

PG_MCP_DATABASES

是

—

以逗号分隔的 PostgreSQL 连接字符串

PG_MCP_DEFAULT_DB

否

第一个 DSN

查询的默认数据库

OPENAI_API_KEY

是

—

OpenAI API 密钥

OPENAI_MODEL

否

gpt-4o

用于 SQL 生成的模型

OPENAI_BASE_URL

否

OpenAI 默认

自定义端点(Azure、代理等)

PG_MCP_QUERY_TIMEOUT

否

30

查询超时时间(秒)

PG_MCP_MAX_ROWS

否

100

返回的最大行数(1-1000)

PG_MCP_SCHEMA_CACHE_PATH

否

无

持久化架构缓存的路径

PG_MCP_LOG_LEVEL

否

INFO

DEBUG / INFO / WARNING / ERROR

多数据库示例:

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" 键传递环境变量。

测试查询

连接后,尝试针对测试数据库进行以下自然语言查询:

数据库

示例查询

pg_mcp_test_small

"列出所有评分高于4分的图书"

pg_mcp_test_small

"哪个国家的作者最多"

pg_mcp_test_medium

"上个月销量前10的商品"

pg_mcp_test_medium

"每个用户的总消费金额"

pg_mcp_test_large

"各部门员工数量和平均薪资"

pg_mcp_test_large

"今年收入最高的前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 响应中

Related MCP Connectors

Related MCP Servers

  • -
    license
    Not graded
    quality
    A
    maintenance
    A 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 npm
    91,120
    MIT
  • A
    license
    Not graded
    quality
    D
    maintenance
    Enables 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 npm
    MIT