返回市场
pg-mcp-服务器

pg-mcp-服务器

作者:ericzakariasson135 星标更新:2025-11-04

项目介绍

Postgres MCP 服务器

PostgreSQL 数据库的模型上下文协议服务器。通过受控接口使大语言模型能够查询和分析 PostgreSQL 数据库。

https://github.com/user-attachments/assets/6571c20c-91c9-4a6e-8332-13b587b79fbf

安装

安装 MCP 服务器

在您的 MCP 客户端设置中添加以下内容:

{
  "mcpServers": {
    "postgres": {
      "command": "npx",
      "args": ["--yes", "pg-mcp-server", "--transport", "stdio"],
      "env": {
        "DATABASE_URL": "postgresql://postgres:postgres@localhost:5432/postgres"
      }
    }
  }
}

配置

  • DATABASE_URL - PostgreSQL 连接字符串(必需)
  • DANGEROUSLY_ALLOW_WRITE_OPS - 启用写操作(默认:false
  • DEBUG - 启用调试日志记录(默认:false
  • PG_SSL_ROOT_CERT - 可选的 TLS CA 证书捆绑包路径(例如,AWS RDS 全局捆绑包)

使用方法

传输方式

  • 默认传输方式是 stdio。使用 --transport 标志切换到 HTTP
  • HTTP 模式在 PORT(默认 3000)上的 /mcp 提供 MCP Streamable HTTP 端点。
  • 支持 Streamable HTTP 的客户端应连接到 http://localhost:3000/mcp

启动命令:

# stdio 传输(默认,通过已安装的 CLI)
pg-mcp-server --transport=stdio

# http 传输
pg-mcp-server --transport=http

工具

  • query - 执行 SQL 查询
    { "sql": "SELECT * FROM users WHERE active = true LIMIT 1 0" }
    

资源

  • postgres://tables - 列出所有表
  • postgres://table/{schema}/{table} - 获取表模式和样本数据

示例提示

这是一个测试 MCP 服务器是否工作的示例提示:

给我数据库中的前5个用户

数据分析与笔记本

为了数据分析和探索,我添加了一个 Cursor 规则,用于将 MCP 服务器与笔记本一起使用,在 .cursor/rules/notebooks.mdc 中:

快速开始使用 Docker

# 启动带有示例数据的 PostgreSQL
bun run db:start

# 使用 MCP Inspector 测试
bun run inspector

# 停止 PostgreSQL
bun run db:stop

包含的示例表有:users, products, orders, order_items

开发

# 克隆并安装
git clone https://github.com/ericzakariasson/pg-mcp-server.git
cd pg-mcp-server
bun install

# 运行(stdio 传输)
bun run index.ts -- --transport=stdio
DEBUG=true bun run index.ts -- --transport=stdio

# 运行(http 传输)
bun run index.ts -- --transport=http
DEBUG=true bun run index.ts -- --transport=http
bun test                      # 运行测试

在 MCP 客户端设置中使用本地构建:

bun run build:js
{
  "mcpServers": {
    "postgres": {
      "command": "node",
      "args": ["/absolute/path/to/pg-mcp-server/lib/index.js", "--transport", "stdio"],
      "env": {
        "DATABASE_URL": "postgresql://postgres:postgres@localhost:5432/postgres"
      }
    }
  }
}

发布

当您推送一个与 package.json 中版本匹配的标签时,此仓库会自动生成一个 GitHub 发布:

  1. 更新 CHANGELOG.md 并在 package.json 中提升版本。
  2. main(或您的发布分支)上提交更改。
  3. 创建并推送一个匹配的标签:
VERSION=$(jq -r .version package.json)
git tag v"$VERSION"
git push origin v"$VERSION"

GitHub Actions 工作流将验证标签(例如 v0.1.0)是否与 package.json 匹配,然后使用 gh 创建带有生成说明的发布,并发布到 npm。

许可证

MIT - 查看 LICENSE