使用说明
PostgreSQL MCP服务器
一个模型上下文协议(MCP)服务器,为AI助手提供全面的PostgreSQL数据库管理功能。
🚀 最新动态该服务器已通过整合(34→8个元工具)和增强(+4个新工具)从46个独立工具完全重新设计为18个智能工具,提供了更好的人工智能发现,同时增加了强大的数据操作和评论管理功能。
2.0.0中的重大更改
2.0.0版本引入了安全边界,有意更改1.x行的默认行为:
- 服务器启动于
readonly模式。修改、DDL、角色管理、文件系统导入/导出和任意SQL都需要--security-mode write,--security-mode admin,或--security-mode unsafe视情况而定。 - 破坏性操作,如删除、重置、广泛角色授予和任意SQL,都需要
--allow-destructive. - 每个工具
connectionString,sourceConnectionString,以及targetConnectionString默认情况下,参数是禁用的。使用服务器级别--connection-string或POSTGRES_CONNECTION_STRING,或明确选择加入--allow-tool-connection-string. - 传统字符串
where对于变异、索引、导出和复制过滤器,子句将被拒绝。使用结构化where谓词,或rawWhere只有--security-mode unsafe --allow-destructive. - 多语句
pg_execute_sql通话必须使用transactional: true,expectRows: false,没有约束parameters. - 工具模式拒绝未知字段,因此拼写错误或意外的输入在连接解析之前失败。
- 用户和目标标识符仅限于安全的简单PostgreSQL标识符。
对于不中断的安全接插线,请使用 @henkey/postgres-mcp-server@1.0.7.
快速开始
先决条件
- Node.js≥18.0.0
- 访问PostgreSQL服务器
- (可选)用于AI集成的MCP客户端,如Cursor或Claude
选项1:npm(推荐)
# Install globally
npm install -g @henkey/postgres-mcp-server
# Or run directly with npx (no installation)
# Use env var for connection string (optional)
export POSTGRES_CONNECTION_STRING="postgresql://user:pass@localhost:5432/db"
npx @henkey/postgres-mcp-server
# Or pass directly:
npx @henkey/postgres-mcp-server --connection-string "postgresql://user:pass@localhost:5432/db"
验证安装
npx@henkey/postgres-mcp服务器--帮助
添加到MCP客户端配置中:
{
"mcpServers": {
"postgresql-mcp": {
"command": "npx",
"args": [
"@henkey/postgres-mcp-server",
"--connection-string", "postgresql://user:password@host:port/database"
]
}
}
}
选项2:通过Smithery安装
npx -y @smithery/cli install @HenkDz/postgresql-mcp-server --client claude
选项3:Docker(推荐用于生产环境)
# Build the Docker image
docker build -t postgres-mcp-server .
# Run with environment variable
docker run -i --rm \
-e POSTGRES_CONNECTION_STRING="postgresql://user:password@host:port/database" \
postgres-mcp-server
添加到MCP客户端配置中:
{
"mcpServers": {
"postgresql-mcp": {
"command": "docker",
"args": [
"run",
"-i",
"--rm",
"henkey/postgres-mcp:latest",
"-e",
"POSTGRES_CONNECTION_STRING"
],
"env": {
"POSTGRES_CONNECTION_STRING": "postgresql://user:password@host:port/database"
}
}
}
}
选项4:手动安装(开发)
git clone <repository-url>
cd postgresql-mcp-server
npm install
npm run build
添加到MCP客户端配置中:
{
"mcpServers": {
"postgresql-mcp": {
"command": "node",
"args": [
"/path/to/postgresql-mcp-server/build/index.js",
"--connection-string", "postgresql://user:password@host:port/database"
]
}
}
}
安全模式
服务器现在启动于 readonly 默认模式。MCP发现工具可能仍会列出,但每次调用在到达数据库之前都会进行分类和检查。
| 模式 | 允许 | 默认情况下阻止 |
|---|---|---|
readonly |
模式检查、分析、监控、SELECT风格查询工具 | 突变、DDL、角色更改、文件系统导入/导出、任意SQL |
write |
只读操作加上数据突变 | DDL、角色更改、文件系统导入/导出、任意SQL |
admin |
写操作加上模式、索引、函数、触发器、RLS、角色和文件系统工具 | 任意SQL |
unsafe |
所有工具类别,包括任意SQL | 破坏性操作,除非明确允许 |
破坏性操作,如删除、重置和任意SQL,也需要明确的选择加入:
# Default: readonly, no per-tool connection strings
npx @henkey/postgres-mcp-server --connection-string "postgresql://readonly_user:pass@host:5432/db"
# Enable DML mutations, but still block DDL/admin/arbitrary SQL
npx @henkey/postgres-mcp-server --security-mode write --connection-string "postgresql://app_writer:pass@host:5432/db"
# Enable admin tools and destructive operations
npx @henkey/postgres-mcp-server --security-mode admin --allow-destructive --connection-string "postgresql://admin_user:pass@host:5432/db"
# Enable arbitrary SQL only for trusted local/admin use
npx @henkey/postgres-mcp-server --security-mode unsafe --allow-destructive --connection-string "postgresql://admin_user:pass@host:5432/db"
每个工具 connectionString, sourceConnectionString,以及 targetConnectionString 默认情况下,参数是禁用的。首选具有最低权限PostgreSQL角色的固定服务器级连接字符串。仅用于开发,启用每个工具的连接字符串 --allow-tool-connection-string 或 POSTGRES_MCP_ALLOW_TOOL_CONNECTION_STRING=true.
按工具、CLI和 POSTGRES_CONNECTION_STRING 值必须是非空字符串。空白的高优先级连接字符串验证失败,而不是退回到低优先级源。
可选择将所有服务器级别和每个工具的连接字符串限制为具有以下内容的满列表 --allowed-connection-target, allowedConnectionTargets,或 POSTGRES_MCP_ALLOWED_CONNECTION_TARGETS.目标模式使用 [user@]host[:port][/database];省略的字段不受约束 * 仅允许作为全字段通配符,例如 readonly@db.internal:5432/app 或 *@localhost:*/dev.
有关部署授权,请参阅 PostgreSQL角色模板模板将只读、写入、模式管理员和角色管理员凭据分开,以便PostgreSQL角色与所选MCP保持一致 securityMode.
安全设置也可以放置在工具配置文件中:
{
"securityMode": "readonly",
"allowDestructive": false,
"allowToolConnectionString": false,
"workspaceDir": "/path/to/mcp-workspace",
"auditFile": "/path/to/postgres-mcp-audit.jsonl",
"maxConnections": 20,
"idleTimeoutMillis": 30000,
"connectionTimeoutMillis": 2000,
"maxFileBytes": 10485760,
"statementTimeoutMs": 30000,
"queryTimeoutMs": 45000,
"lockTimeoutMs": 10000,
"idleInTransactionSessionTimeoutMs": 60000,
"allowedConnectionTargets": [
"readonly@db.internal:5432/app"
],
"enabledTools": [
"pg_analyze_database",
"pg_manage_schema",
"pg_execute_query"
]
}
运行时配置优先级是CLI选项,然后是工具配置文件,然后是环境变量。明确的 false 工具配置中的值会覆盖启用环境变量,例如 POSTGRES_MCP_ALLOW_DESTRUCTIVE=true.
如果提供了工具配置路径,服务器将按要求处理:不可读、格式错误、非对象、类型错误、密钥未知、无效 securityMode,或未知 enabledTools 条目停止启动,而不是退回到所有可用的工具。
CLI选项:
--version--connection-string--tools-config--security-mode--allow-destructive--allow-tool-connection-string--workspace-dir--audit-file--max-connections--idle-timeout-ms--connection-timeout-ms--max-file-bytes--statement-timeout-ms--query-timeout-ms--lock-timeout-ms--idle-in-transaction-session-timeout-ms--allowed-connection-target
环境变量:
POSTGRES_TOOLS_CONFIG=/path/to/tools.jsonPOSTGRES_MCP_SECURITY_MODE=readonly|write|admin|unsafePOSTGRES_MCP_ALLOW_DESTRUCTIVE=truePOSTGRES_MCP_ALLOW_TOOL_CONNECTION_STRING=truePOSTGRES_MCP_WORKSPACE_DIR=/path/to/mcp-workspacePOSTGRES_MCP_AUDIT_FILE=/path/to/postgres-mcp-audit.jsonlPOSTGRES_MCP_MAX_CONNECTIONS=20POSTGRES_MCP_IDLE_TIMEOUT_MS=30000POSTGRES_MCP_CONNECTION_TIMEOUT_MS=2000POSTGRES_MCP_MAX_FILE_BYTES=10485760POSTGRES_MCP_STATEMENT_TIMEOUT_MS=60000POSTGRES_MCP_QUERY_TIMEOUT_MS=65000POSTGRES_MCP_LOCK_TIMEOUT_MS=10000POSTGRES_MCP_IDLE_IN_TRANSACTION_SESSION_TIMEOUT_MS=60000POSTGRES_MCP_ALLOWED_CONNECTION_TARGETS=readonly@db.internal:5432/app,*@localhost:*/devPOSTGRES_MCP_DEBUG_SQL=true选择进入详细模式pg-monitorSQL跟踪。这可能会记录原始SQL和绑定值,因此除非您正在调试受信任的本地数据库,否则请将其禁用。
布尔环境标志必须精确 true 或 false 当设置时。
CLI、工具配置或环境变量中的数字资源设置必须是正整数。运行时默认使用20个连接池、30000毫秒池空闲超时、2000毫秒连接超时、60000毫秒PostgreSQL statement_timeout,65000毫秒的节点postgres查询超时,10000毫秒的PostgreSQL lock_timeout,以及一个60000毫秒的PostgreSQL idle_in_transaction_session_timeout。池和超时设置可以通过以下方式升高或降低 --max-connections, --idle-timeout-ms, --connection-timeout-ms, --statement-timeout-ms, --query-timeout-ms, --lock-timeout-ms, --idle-in-transaction-session-timeout-ms, maxConnections, idleTimeoutMillis, connectionTimeoutMillis, statementTimeoutMs, queryTimeoutMs, lockTimeoutMs, idleInTransactionSessionTimeoutMs, POSTGRES_MCP_MAX_CONNECTIONS, POSTGRES_MCP_IDLE_TIMEOUT_MS, POSTGRES_MCP_CONNECTION_TIMEOUT_MS, POSTGRES_MCP_STATEMENT_TIMEOUT_MS, POSTGRES_MCP_QUERY_TIMEOUT_MS, POSTGRES_MCP_LOCK_TIMEOUT_MS,或 POSTGRES_MCP_IDLE_IN_TRANSACTION_SESSION_TIMEOUT_MS.
显式连接字符串, workspaceDir, auditFile, --workspace-dir,以及 --audit-file 值必须是非空字符串。
在每个工具连接字符串的工具执行之前以及服务器级源的连接解析期间,都会强制执行连接目标分配列表。配置满列表时,连接字符串必须是PostgreSQL URL或具有显式 host 或 hostaddr.
变异、索引、导出和复制过滤器应使用结构化 where 谓词。传统字符串 where 条款被拒绝;明确的 rawWhere 逃逸舱口被视为任意SQL,需要 --security-mode unsafe --allow-destructive.
EXPLAIN工具只接受一个只读语句,并在只读事务中运行。 analyze: true 仍然需要不安全模式,因为PostgreSQL执行提供的查询来收集运行时统计信息。
多语句 pg_execute_sql 通话必须使用 transactional: true, expectRows: false,没有约束 parameters。当需要绑定参数时,使用单个参数化语句或CTE。
默认情况下,会对错误消息、诊断和目录元数据进行清理。来自的SQL文本 pg_stat_statements,函数定义、RLS谓词、检查约束、索引定义和列默认值将被编辑,除非它们被有意作为用户数据返回。
数据执行、查询/性能、模式、索引、约束、用户/权限、触发器、注释、函数、RLS、迁移和诊断工具拒绝未知的输入字段,因此拼写错误或意外的参数在连接解析之前失败。
被拒绝的安全边界请求发出一个前缀为的结构化stderr行 [MCP Audit]审核事件包括经过净化的字段,例如 toolName, reason, securityMode, risk,以及是否存在每个工具的连接串;它们不会记录原始SQL、完整的请求有效负载或连接字符串密码。集 POSTGRES_MCP_AUDIT_FILE, --audit-file,或 auditFile 将相同的经过净化的审计事件附加到JSONL文件中。
文件系统工具(如表导出/导入)需要一个工作区目录,并且只能读或写 .json 和 .csv 其中的文件:
npx @henkey/postgres-mcp-server \
--security-mode admin \
--allow-destructive \
--workspace-dir /path/to/mcp-workspace \
--connection-string "postgresql://admin_user:pass@host:5432/db"
包含内容
18个强大的工具 分为三类:
- 🔄 整合:34个原始工具合并为8个智能元工具
- 🔧 专业:6个工具分开存放,用于复杂操作
- 🆕 增强:4个全新工具(不是原来的46个)
📊 整合元工具 (8工具)
- 模式管理 -表、列、ENUM、约束
- 用户和权限 -创建用户,授予/撤销权限
- 查询性能 -解释计划、慢速查询、统计数据
- 索引管理 -创建、分析、优化指标
- 函数 -创建、修改、管理存储的函数
- 触发器 -数据库触发器管理
- 约束 -外键、检查、唯一约束
- 行级安全 -RLS政策和管理
🚀 增强工具 (4个新工具)
原始46个工具中没有的全新功能
- 执行查询 -支持计数/存在的SELECT操作
- 执行突变 -插入/更新/删除/更新操作
- 执行SQL -支持事务的任意SQL执行
- 评论管理 -对所有数据库对象进行全面的注释管理
🔧 专用工具 (6个工具)
- 数据库分析 -性能和配置分析
- 调试数据库 -对连接、性能、锁进行故障排除
- 数据导出 -JSON/CSV数据导出
- 数据导入 -JSON/CSV数据导入
- 数据库之间的复制 -跨数据库数据传输
- 实时监控 -实时数据库指标和警报
示例用法
// Analyze database performance
{ "analysisType": "performance", "schema": "public" }
// Create a table with constraints
{
"operation": "create_table",
"tableName": "users",
"columns": [
{ "name": "id", "type": "SERIAL PRIMARY KEY" },
{ "name": "email", "type": "VARCHAR(255) UNIQUE NOT NULL" }
]
}
// Query data with parameters
{
"operation": "select",
"query": "SELECT * FROM users WHERE created_at > $1",
"parameters": ["2024-01-01"],
"limit": 100
}
// Select results are always bounded: default limit 100, max 1000.
// Insert new data
{
"operation": "insert",
"table": "users",
"data": {"name": "John Doe", "email": "john@example.com"},
"returning": "*",
"maxReturningRows": 100
}
// Mutation RETURNING output is capped in the response: default 100, max 1000.
// Find slow queries
{
"operation": "get_slow_queries",
"limit": 5,
"minDuration": 100
}
// Execute a parameterized SELECT query
{
"operation": "select",
"query": "SELECT * FROM users WHERE id = $1",
"parameters": [1]
}
// Perform an INSERT mutation
{
"operation": "insert",
"table": "products",
"data": {"name": "New Product", "price": 99.99},
"returning": "id",
"maxReturningRows": 100
}
// Perform an UPDATE mutation with a structured WHERE predicate
{
"operation": "update",
"table": "products",
"data": {"price": 89.99},
"where": {"id": 123},
"returning": ["id", "price"]
}
// Manage database object comments
{
"operation": "set",
"objectType": "table",
"objectName": "users",
"comment": "Main user account information table"
}
📚 文档
📋 完整的工具架构参考 -将所有18个工具参数和示例放在一个地方
有关更多信息,请参阅 docs/ 文件夹:
- 🔐 安全态势 -沙盒、审批、审计事件和部署态势
- PostgreSQL角色模板 -每个部署配置文件的最低权限数据库角色
- 📖 使用指南 -强化使用模式和示例
- 🛠️ 开发指南 -设置和发布检查表
- ⚙️ 技术细节 -安全架构和实施约束
- 👨💻 开发人员参考 -工具和政策变更的贡献规则
- 📋 文档索引 -完整的文档概述
功能亮点
🔄 整合成果
✅ 34→8 元工具 -智能整合,更好地发现人工智能
✅ 每个工具可执行多项操作 -具有操作参数的统一模式
✅ 智能参数验证 -清晰的错误信息和类型安全
🆕 增强的数据能力
✅ 完成CRUD操作 -带参数化查询的INSERT/UPDATE/DELETE/UPSERT
✅ 灵活查询 -带计数/存在支持和有界安全限制的SELECT
✅ 任意SQL执行 -复杂操作的交易支持
🔧 生产就绪
✅ 受控连接 -默认情况下为CLI参数或env变量;每个工具的连接字符串都需要选择加入 ✅ 注重安全 -只读默认模式、集中式策略检查、结构化变异谓词 ✅ 稳健的体系结构 -连接池,全面的错误处理
Docker使用
PostgreSQL MCP服务器完全兼容Docker,可以在生产环境中使用。该映像使用多阶段构建,在运行时阶段仅安装生产依赖项,并以非root身份运行 node 用户。
塑造形象
# Build locally
docker build -t postgres-mcp-server .
# Or pull from Docker Hub
docker pull henkey/postgres-mcp:latest
使用环境变量运行
# Basic usage (using Docker Hub image)
docker run -i --rm \
-e POSTGRES_CONNECTION_STRING="postgresql://user:password@host:port/database" \
henkey/postgres-mcp:latest
# Or with locally built image
docker run -i --rm \
-e POSTGRES_CONNECTION_STRING="postgresql://user:password@host:port/database" \
postgres-mcp-server
# With tools configuration
docker run -i --rm \
-e POSTGRES_CONNECTION_STRING="postgresql://user:password@host:port/database" \
-e POSTGRES_TOOLS_CONFIG="/app/config/tools.json" \
-v /path/to/config:/app/config \
postgres-mcp-server
Docker编写示例
version: '3.8'
services:
postgres-mcp:
build: .
environment:
- POSTGRES_CONNECTION_STRING=postgresql://user:password@postgres:5432/database
depends_on:
- postgres
stdin_open: true
tty: true
postgres:
image: postgres:15
environment:
- POSTGRES_DB=database
- POSTGRES_USER=user
- POSTGRES_PASSWORD=password
ports:
- "5432:5432"
MCP客户端配置
适用于Cursor或Claude Desktop等MCP客户端:
{
"mcpServers": {
"postgresql-mcp": {
"command": "docker",
"args": [
"run",
"-i",
"--rm",
"-e",
"POSTGRES_CONNECTION_STRING",
"henkey/postgres-mcp:latest"
],
"env": {
"POSTGRES_CONNECTION_STRING": "postgresql://user:password@host:port/database"
}
}
}
}
先决条件
- Node.js≥18.0.0(用于本地开发)
- Docker(用于容器化部署)
- PostgreSQL服务器访问
- 有效的连接凭据
贡献
- 分叉存储库
- 创建要素分支
- 提交您的更改
- 创建拉取请求
看 开发指南 有关详细的设置说明。
许可证
AGPLv3许可证-请参阅 许可证 文件以获取详细信息。