PostgreSQL模型上下文协议服务器

PostgreSQL MCP服务器是一个为PostgreSQL数据库设计的模型上下文协议服务器,允许LLM通过受控接口查询和分析数据库。

  • by ericzakariasson
  • TypeScript
  • 本地部署
  • 179 星标
  • 更新于
在 GitHub 查看 ericzakariasson/pg-mcp-server

使用说明

Postgres MCP服务器

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

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

安装

添加到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全局捆绑包)

用法

运输

  • 默认传输方式为 标准输入输出.切换到 超文本传输协议 随着 --transport 旗帜。
  • HTTP模式为MCP Streamable HTTP端点提供服务 /mcp 在…上 PORT (默认值 3000).
  • 支持Streamable HTTP的客户端应连接到 http://localhost:3000/mcp.

启动命令:

# stdio transport (default, via installed CLI)
pg-mcp-server --transport=stdio

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

工具

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

资源

  • postgres://tables -列出所有表格
  • postgres://table/{schema}/{table} -获取表架构和示例数据

示例提示

以下是一个示例提示,用于测试您的MCP服务器是否正常工作:

Show me the first 5 users from the database

数据分析和笔记本

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

Docker快速入门

# Start PostgreSQL with sample data
bun run db:start

# Test with MCP Inspector
bun run inspector

# Stop PostgreSQL
bun run db:stop

示例表包括: users, products, orders, order_items

发展

# Clone and install
git clone https://github.com/ericzakariasson/pg-mcp-server.git
cd pg-mcp-server
bun install

# Run (stdio transport)
bun run index.ts -- --transport=stdio
DEBUG=true bun run index.ts -- --transport=stdio

# Run (http transport)
bun run index.ts -- --transport=http
DEBUG=true bun run index.ts -- --transport=http
bun test                      # Run tests

使用本地内置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"
      }
    }
  }
}

发布

当您推送与中的版本匹配的标签时,此仓库会自动创建GitHub Release package.json:

  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 使用生成的notes创建一个版本,并发布到npm。

许可证

麻省理工学院-见 许可证