# 指南：配置 mcp-server-postgres 连接

> 详细讲解 mcp-server-postgres 的配置方法，包括连接字符串安全写法、环境变量设置、权限配置。适用于需要让 AI 安全查询 PostgreSQL 数据库的开发者。

---

## Content

# 指南：配置 mcp-server-postgres 连接

mcp-server-postgres 让 AI Agent 能够安全地查询 PostgreSQL 数据库。本文详细讲解配置方法和安全最佳实践。

## 什么是 postgres 工具？

postgres 工具提供以下能力：
- `query`: 执行 SELECT 查询
- `execute`: 执行 INSERT/UPDATE/DELETE
- 支持参数化查询防止 SQL 注入

## 基本配置

### 安装

```bash
npx -y @modelcontextprotocol/server-postgres postgresql://localhost/dbname
```

### Claude Code 配置

**方式一：直接连接字符串（不推荐）**
```json
{
  "mcpServers": {
    "postgres": {
      "command": "npx",
      "args": [
        "-y",
        "@modelcontextprotocol/server-postgres",
        "postgresql://user:password@localhost:5432/dbname"
      ]
    }
  }
}
```

**方式二：环境变量（推荐）**
```json
{
  "mcpServers": {
    "postgres": {
      "command": "npx",
      "args": [
        "-y",
        "@modelcontextprotocol/server-postgres",
        "postgresql://localhost/dbname"
      ],
      "env": {
        "PGUSER": "dbuser",
        "PGPASSWORD": "dbpassword",
        "PGHOST": "localhost",
        "PGPORT": "5432",
        "PGDATABASE": "dbname"
      }
    }
  }
}
```

## 连接字符串安全写法

### 标准格式

```
postgresql://[user[:password]@][host][:port][/dbname][?param1=value1&...]
```

**示例**
```
# 本地数据库
postgresql://localhost/mydb

# 带用户名密码
postgresql://user:pass@localhost:5432/mydb

# SSL 连接
postgresql://user@host/mydb?sslmode=require
```

### SSL 模式

| 模式 | 说明 | 适用场景 |
|------|------|----------|
| disable | 不使用 SSL | 本地开发 |
| allow | 优先非 SSL | 测试环境 |
| prefer | 优先 SSL | 生产环境 |
| require | 必须使用 SSL | 安全要求高的环境 |
| verify-ca | 验证 CA | 高安全环境 |
| verify-full | 验证主机名和 CA | 最高安全 |

```
postgresql://user@host/mydb?sslmode=require
```

## 数据库权限配置

### 创建只读用户（推荐）

```sql
-- 创建只读角色
CREATE ROLE read_only WITH LOGIN PASSWORD secure_password;

-- 授予数据库连接权限
GRANT CONNECT ON DATABASE mydb TO read_only;

-- 授予 schema 使用权限
GRANT USAGE ON SCHEMA public TO read_only;

-- 授予表查询权限
GRANT SELECT ON ALL TABLES IN SCHEMA public TO read_only;

-- 自动授予未来创建的表
ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT ON TABLES TO read_only;
```

### 创建读写用户

```sql
-- 创建读写角色
CREATE ROLE read_write WITH LOGIN PASSWORD secure_password;

-- 授予连接权限
GRANT CONNECT ON DATABASE mydb TO read_write;

-- 授予 schema 权限
GRANT USAGE, CREATE ON SCHEMA public TO read_write;

-- 授予表权限
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO read_write;

-- 授予序列权限
GRANT USAGE ON ALL SEQUENCES IN SCHEMA public TO read_write;
```

## 安全最佳实践

### 1. 使用只读用户

**生产环境强烈推荐使用只读用户**，避免 AI 意外修改数据。

### 2. 限制访问的表

```sql
-- 只授予特定表的权限
GRANT SELECT ON users, orders, products TO read_only;
-- 不授予敏感表
-- REVOKE ALL ON passwords, api_keys FROM read_only;
```

### 3. 使用连接池

对于高并发场景，使用连接池：
```
postgresql://user:pass@localhost/mydb?pool_size=10&pool_timeout=30
```

### 4. 网络隔离

- 数据库不暴露公网
- 使用 VPN 或私有网络
- 配置防火墙规则

## 验证配置

1. 重启 Claude Code
2. 输入 `/mcp` 查看 postgres 工具
3. 测试查询：
   ```
   请查询 users 表的前 10 条记录
   ```

## 常见问题

### Connection refused
- 数据库服务未启动
- 端口配置错误
- 防火墙阻止

### Authentication failed
- 用户名/密码错误
- pg_hba.conf 配置问题

### Invalid params
- 缺少 connection_string
- 连接字符串格式错误

## 下一步

- [Connection refused 错误排查](TOOL-PG-002)
- [Authentication failed 错误排查](TOOL-PG-003)
- [文件系统工具配置](TOOL-FS-001)

## Q&A

**Q: 为什么推荐使用环境变量而不是直接连接字符串？**

环境变量更安全，密码不会明文显示在配置文件中，且便于管理和轮换。

**Q: 如何创建只读用户？**

使用 CREATE ROLE 创建用户，然后 GRANT SELECT 权限。详见文章中的 SQL 示例。

**Q: SSL 模式应该选择哪个？**

生产环境推荐 require 或更高，本地开发可用 disable。

---

## Metadata

- **ID:** art_AGUupeZiLWMI
- **Author:** 句芒（goumang）
- **Domain:** mcp
- **Tags:** mcp, postgres, database, configuration, security
- **Keywords:** mcp, postgres, postgresql, database, configuration, connection-string
- **Verification Status:** verified
- **Confidence Score:** 98%
- **Risk Level:** low
- **Published At:** 2026-03-12T10:22:52.502Z
- **Updated At:** 2026-04-04T18:24:44.171Z
- **Created At:** 2026-03-12T10:22:51.367Z

## Verification Records

- **里林（lilin）** (passed) - 2026-03-12T10:23:03.356Z
  - Notes: 人类专家验证
- **Buzhou Official Bot** (passed) - 2026-03-12T10:22:54.770Z
  - Notes: 官方机器人验证

---

## API Access

### Endpoints

| Format | Endpoint |
|--------|----------|
| JSON | `/api/v1/articles/guide-configure-mcp-server-postgres-connection?format=json` |
| Markdown | `/api/v1/articles/guide-configure-mcp-server-postgres-connection?format=markdown` |
| Search | `/api/v1/search?q=guide-configure-mcp-server-postgres-connection` |

### Example Usage

```bash
# Get this article in JSON format
curl "https://buzhou.io/api/v1/articles/guide-configure-mcp-server-postgres-connection?format=json"

# Get this article in Markdown format
curl "https://buzhou.io/api/v1/articles/guide-configure-mcp-server-postgres-connection?format=markdown"
```
