Postgres MCP服务器
一种模型上下文协议(MCP)服务器,它公开PostgreSQL资源和工具,用于结构化数据访问、变异和功能管理。
______________________________________________________________________
🚀 功能概述
| 能力 | 它做什么 |
|---|---|
| 📚 模式资源管理器 | 将Postgres实例中的表模式作为MCP资源进行处理 |
| 🔍 安全查询 | 在仅回滚事务中执行只读SQL |
| ✍️ 数据突变 | 插入、更新、删除自动提交事务 |
| 🧠 函数工具 | 调用现有函数或直接创建/替换它们 |
| 🔐 可配置 | 从加载连接信息 .env 或CLI参数 |
______________________________________________________________________
🧱 建筑一瞥
flowchart TD
Client[Chat Client / MCP Agent]
Server[Postgres MCP Server]
Pool[(pg Pool)]
DB[(PostgreSQL)]
Client -- MCP requests --> Server
Server -- tool executions --> Pool
Pool -- SQL --> DB
DB -- rows/result metadata --> Pool -- JSON --> Server -- responses --> Client- 服务器:
src/postgres.ts启动MCP服务器,加载环境变量,注册资源,并公开工具。 - 池:专用
pg所有工具调用共享的池。 - 交易:只读工具回滚;写工具承诺成功。
______________________________________________________________________
🛠️ 需求
- Node.js 18+ (对于ES模块和
node:path助手) - npm(与Node捆绑在一起)
- 可访问的PostgreSQL数据库和凭据
可选助手: nvm 对于版本管理, psql CLI用于手动验证。
______________________________________________________________________
🧾 安装和设置(逐步)
1.克隆并安装依赖项
git clone postgres-mcp-crud
cd postgres-mcp-crud
npm install2.配置环境变量
创建 .env (已被gitignored)在项目根目录中:
DATABASE_URL=postgres://username:password@host:5432/database稍后可以通过将连接字符串作为命令行参数传递来覆盖此设置。
3.构建TypeScript源代码
npm run build编译后的JavaScript在 build/ 目录。
4.启动MCP服务器
- 使用
.env:
node build/postgres.js- 显式提供连接:
node build/postgres.js "postgres://username:password@host:5432/database"服务器通过STDIO进行通信。将其连接到您的MCP感知客户端或代理配置中。
______________________________________________________________________
🧪 可用的MCP工具
| 工具 | 描述 | 事务模式 | 响应负载 |
|---|---|---|---|
query | 执行只读SQL | BEGIN TRANSACTION READ ONLY +回滚 | rows |
insert | 执行 INSERT 声明 | BEGIN +承诺 | { rowCount, rows, command } |
update | 执行 UPDATE 声明 | BEGIN +承诺 | { rowCount, rows, command } |
delete | 执行 DELETE 声明 | BEGIN +承诺 | { rowCount, rows, command } |
function_call | 快跑 SELECT fn(...) 或 CALL fn(...) | BEGIN +承诺 | { rowCount, rows, command } |
function_create | 创建/替换存储的函数 | BEGIN +承诺 | { rowCount, rows, command } |
所有工具都强制使用非空 sql string参数,并返回JSON作为字符串内容。请求有效载荷示例
{
"sql": "UPDATE customers SET status = 'active' WHERE id = 42"
}响应处理示例(TypeScript代码段)
const toolCall = await mcpClient.callTool("insert", {
sql: "INSERT INTO audit_log(event) VALUES('server-started');"
});
const payload = JSON.parse(toolCall.content[0].text);
console.log(payload.rowCount);
}
---
## 🤝 Integrating with MCP Clients
1. Configure your MCP-capable app to launch `node build/postgres.js` (or invoke `tsx src/postgres.ts` during development).
2. Provide tool inputs as JSON payloads (see examples above).
3. Handle responses as JSON strings—parse them if you need structured data.
### Claude Desktop
Claude Desktop loads server definitions from `claude_desktop_config.json`.
- **Windows:** `%APPDATA%/Claude/claude_desktop_config.json`
- **macOS:** `~/Library/Application Support/Claude/claude_desktop_config.json`
Add (or merge) the following under the top-level `"mcpServers"` object:
{ "postgres-mcp": { "command": "node", "args": [ "C:/path/to/postgres/build/postgres.js" ] } }
提示:
- 更新已编译的路径 `postgres.js` 为了你的机器。
- 确保您的项目根目录包含 `.env` 提交 `DATABASE_URL=postgres://username:password@host:5432/database` (请参阅上面的设置说明)。
- 编辑配置文件后重新启动Claude Desktop(或重新加载MCP服务器)。
### 其他MCP客户端
大多数MCP客户端遵循类似的模式:
1. 注册服务器命令(`node build/postgres.js`).
1. 根据需要传递CLI参数或环境变量。
1. 确保工作目录是项目根目录,以便 `.env` 正确解决。
1. 解析每个工具响应——内容以JSON字符串的形式发出,便于使用。
示例集成代码段(伪代码):
const response = await mcpClient.callTool("query", { sql: "SELECT NOW();" });
const data = JSON.parse(response.content[0].text); console.log(data);
______________________________________________________________________
## 📚 资源端点
- `ListResources` 返回如下表格条目:
postgres://user@host:5432/database/orders/schema
- `ReadResource` 生成列元数据:
[ { "column_name": "id", "data_type": "integer" }, { "column_name": "created_at", "data_type": "timestamp without time zone" } ]
______________________________________________________________________
## 🧰 开发工作流程提示
Rebuild on change
npm run build
TypeScript in watch mode
npx tsc --watch
(Optional) linting – configure ESLint first
npx eslint "src/**/*.ts"
请随意调整脚本以匹配您的工具偏好。
______________________________________________________________________
## 🛡️ 操作指南
- 在发出写命令之前验证SQL;语句按提供的方式执行。
- 将多语句迁移分组到单个 `sql` 有效载荷以原子方式运行。
- 定期轮换凭据并保存 `.env` 脱离源代码控制。
______________________________________________________________________
## 🧭 项目布局
postgres/ ├─ build/ # Compiled JS output ├─ src/ │ └─ postgres.ts # MCP server implementation ├─ package.json ├─ tsconfig.json └─ README.md
______________________________________________________________________
## 🤝 贡献
1. 分叉存储库
1. 创建分支: `git checkout -b feature/your-idea`
1. 以明确的信息承诺: `git commit -m "feat: add new tool"`
1. 推送并打开拉取请求
欢迎提出建议、问题和讨论!
______________________________________________________________________
## 📄 许可证
麻省理工学院
______________________________________________________________________
## 💡 需要支持?
- 检查Postgres日志是否存在身份验证或连接失败
- 确保 `.env` 通过运行加载 `console.log(process.env.DATABASE_URL)` 本地一次
- 如果遇到MCP集成怪癖,请打开复制步骤的问题
享受在PostgreSQL数据之上构建智能助手的乐趣! 🌤️