使用说明
MCP:Postgres MCP服务器
用TypeScript编写的模型上下文协议(MCP)服务器,通过stdio公开Postgres数据库实用程序。
- 列出模式和表
- 生成简单表DDL
- 预览表格数据
- 使用安全默认限制执行即席SQL
适用于MCP兼容的IDE/客户端,如Cursor和GitHub Copilot for VS Code。
需求
- Node.js 18+
- npm
- TypeScript(通过开发依赖关系)
- 可访问的Postgres实例
安装
npm install
构建
npm run build
这将从以下位置编译TypeScript src/ 进入 dist/ 并使 dist/index.js 可执行。
运行(直接)
入口点是 dist/index.js.提供环境变量来配置Postgres。
# Example (with defaults) – update to your environment
PGUSER=local_user \
PGPASSWORD=local_password \
PGHOST=localhost \
PGDATABASE=sigear_tst \
PGPORT=54320 \
node ./dist/index.js
您应该看到:
Postgres MCP Server running on stdio
配置(环境)
服务器(src/index.ts)读取这些变量:
PGUSER(默认值:local_user)PGPASSWORD(默认值:local_password)PGHOST(默认值:localhost)PGDATABASE(默认值:sigear_tst)PGPORT(默认值:54320)
根据您的数据库设置它们。
添加到光标(MCP)–本地服务器
Cursor通过以下方式支持MCP提供商 ~/.cursor/mcp.json (或项目 .cursor/mcp.json).添加一个指向构建的JS文件和stdio传输的条目。
配置示例:
{
"$schema": "https://schemas.cursor.sh/mcp.json",
"mcpServers": {
"postgres-mcp": {
"command": "node",
"args": ["/home/monte/projetos/mcp/dist/index.js"],
"env": {
"PGUSER": "local_user",
"PGPASSWORD": "local_password",
"PGHOST": "localhost",
"PGDATABASE": "sigear_tst",
"PGPORT": "54320"
}
}
}
}
保存配置后,重新启动Cursor。在MCP面板中,启用服务器并测试工具。
添加到VS代码(GitHub Copilot)
GitHub Copilot for VS Code支持MCP服务器。完成此项目后:
- 在VS Code中安装“GitHub Copilot”扩展。
- 打开设置(JSON):文件→ 偏好设置→ 设置→ 打开设置(JSON)。
- 添加/合并MCP服务器配置:
{
"servers": {
"postgres-mcp": {
"type": "stdio",
"command": "node",
"args": ["/home/monte/projetos/mcp/dist/index.js"],
"env": {
"PGUSER": "local_user",
"PGPASSWORD": "local_password",
"PGHOST": "localhost",
"PGDATABASE": "sigear_tst",
"PGPORT": "54320"
}
}
}
}
- 重新加载VS代码。打开Copilot Chat视图,确保MCP服务器已列出/启用,并按名称使用工具(例如。,
listSchemas).
提示:较新的Copilot版本还支持通过命令面板添加服务器(尝试:“MCP:Add Server”)。
功能(工具)
listSchemas()–列出数据库中的所有模式。listTables(schema)–列出架构的表。getTableDDL(schema, table)–生成基本CREATE TABLE来自information_schema的DDL。getTableData(schema, table, limit=10)–返回到limit排。executeSQL(query, limit=100)–执行任意SQL;自动附加LIMIT如果丢失。
示例提示(来自MCP客户端,如Cursor/Copilot):
- “跑
listSchemas." - “使用
listTables带模式public." - “获取表的DDL
public.users使用getTableDDL." - “预览5行
public.users使用getTableData限5” - “跑
executeSQL随着SELECT id, email FROM public.users ORDER BY id限制50”
开发说明
- 来源:
src/index.ts - 构建输出:
dist/ - TypeScript配置:
tsconfig.json - 包脚本:
npm run build
故障排除
- 连接被拒绝/超时:验证
PGHOST,PGPORT以及DB可访问性。 - 验证错误:确认
PGUSER/PGPASSWORD是有效的。 - 无结果:检查架构/表名称是否正确以及用户是否具有权限。
许可证
国际协调委员会