使用说明
MCP Postgres服务器
一个模型上下文协议服务器,用于使用数据检索和模式检查工具查询PostgreSQL数据库。
设置
先决条件:Python 3.11+和PostgreSQL
# Install dependencies
pip install -r requirements.txt
# Configure database connection (defaults shown)
export POSTGRES_HOST=localhost
export POSTGRES_PORT=5432
export POSTGRES_USER=postgres
export POSTGRES_PASSWORD=postgres
export POSTGRES_DB=housing
用法
发展
运行以下命令以在开发模式下启动服务器并启动MCP检查器:
mcp dev main.py
MCP客户端集成
您还可以将以下内容添加到MCP客户端配置中以使用服务器:
{
"mcpServers": {
"postgres": {
"command": "python",
"args": ["main.py"],
"env": {
"POSTGRES_HOST": "localhost",
"POSTGRES_PORT": "5432",
"POSTGRES_USER": "postgres",
"POSTGRES_PASSWORD": "postgres",
"POSTGRES_DB": "housing"
}
}
}
}
看 mcp.json 例如如何在Cursor IDE中添加服务器。
可用工具
query_database-执行SELECT查询(具有SQL注入保护)get_table_schema-获取表列信息和约束list_tables-列出所有数据库表postgres://schema-访问完整的数据库架构(资源)
与官方MCP Postgres服务器的比较
此实现与官方不同 @模型上下文协议/服务器postgres 在几个关键方面:
| 功能 | 此服务器(Python) | 官方服务器(TypeScript) |
|---|---|---|
| 安全 | 防止SQL注入 | 无保护 |
| 连接池 | ✅ 内置(asyncpg) | ❌ 单连接 |
安全
- 仅
SELECT允许声明 - 支持参数化查询
- 基于环境的配置(无硬编码凭据)
后续步骤
- []为postgres实现auth-目前我仍然依赖env变量,这似乎不太安全
- []将其扩展到在多个数据库和潜在的多个postgres实例上运行
- []执行表/列修剪