内容
# 面向生产的 PostgreSQL MCP 服务器
面向生产的 PostgreSQL MCP 服务器,将数据库操作暴露给 MCP 客户端(Claude Desktop,VS Code Copilot,Cursor 及兼容的主机)。
## 功能特点
- 查询执行(`SELECT`,`INSERT`,`UPDATE`,`DELETE`)
- 数据库发现和模式 introspection
- 表元数据检查(列,类型,可空性,默认值,主键)
- 索引和外键发现
- 环境驱动的配置,实现安全部署
## 可用工具
| 工具 | 描述 |
|---|---|
| `execute_query` | 执行 SQL 语句并返回行或受影响的行数 |
| `list_tables` | 列出 `INFORMATION_SCHEMA.TABLES` 中的表(可选模式过滤) |
| `describe_table` | 返回表列元数据和主键标记 |
| `list_databases` | 列出所有 PostgreSQL 数据库 |
| `get_table_indexes` | 列出具有定义和主键/唯一标志的表索引 |
| `get_foreign_keys` | 列出表外键和引用的目标 |
## 要求
- Node.js 18+
- 访问 PostgreSQL 实例
- 从 MCP 主机到 PostgreSQL 的网络连接(`主机:端口`)
## 配置
使用环境变量设置连接设置:
| 变量 | 是否必需 | 默认值 | 描述 |
|---|---|---|---|
| `PGHOST`(或 `POSTGRES_HOST`) | 否 | `localhost` | PostgreSQL 主机或 IP |
| `PGPORT`(或 `POSTGRES_PORT`) | 否 | `5432` | PostgreSQL TCP 端口 |
| `PGDATABASE`(或 `POSTGRES_DB`) | 否 | `postgres` | 默认数据库 |
| `PGUSER`(或 `POSTGRES_USER`) | 是 | — | 数据库用户 |
| `PGPASSWORD`(或 `POSTGRES_PASSWORD`) | 是 | — | 数据库密码 |
| `PGSSL`(或 `POSTGRES_SSL`) | 否 | `false` | 启用 SSL/TLS |
| `PGPOOL_MAX` | 否 | `10` | 最大连接池连接数 |
| `PGPOOL_IDLE_TIMEOUT_MS` | 否 | `30000` | 连接池空闲超时(毫秒) |
## 用法
### 直接从 GitHub 运行
```bash
npx github:ferronicardoso/mcp-postgresql
```
### Claude Desktop 配置
`%APPDATA%\\Claude\\claude_desktop_config.json`:
```json
{
"mcpServers": {
"postgresql": {
"command": "npx",
"args": ["github:ferronicardoso/mcp-postgresql"],
"env": {
"PGHOST": "localhost",
"PGPORT": "5432",
"PGDATABASE": "postgres",
"PGUSER": "postgres",
"PGPASSWORD": "your-password"
}
}
}
}
```
### VS Code MCP 配置
`.vscode/mcp.json`:
```json
{
"servers": {
"postgresql": {
"command": "npx",
"args": ["github:ferronicardoso/mcp-postgresql"],
"env": {
"PGHOST": "localhost",
"PGPORT": "5432",
"PGDATABASE": "postgres",
"PGUSER": "postgres",
"PGPASSWORD": "your-password"
}
}
}
}
```
## 本地开发
```bash
git clone https://github.com/ferronicardoso/mcp-postgresql
cd mcp-postgresql
npm install
npm run build
```
启动编译后的服务器:
```bash
npm start
```
## 构建和提交工作流
本仓库有意跟踪 `dist/` 以支持 `npx github:user/repo` 用法。
项目使用 Husky `pre-commit` 钩子:
1. 构建 TypeScript(`npm run build`)
2. 暂存生成的工件(`git add dist`)
手动回退:
```bash
npm run build
git add dist
```
## 安全注意事项
- 永远不要提交真实的凭证或 `.env` 文件。
- 优先使用生产环境中权限最小的数据库用户。
- 对于公共或不受信任的网络,启用加密(`PGSSL=true`)并适当地配置证书。