PostgreSQL数据库查询服务

一个通过自然语言提供PostgreSQL数据库探索和查询功能的MCP服务器,支持直接数据库交互、模式探索和智能关系发现。

  • by Aftabbs
  • Python
  • 本地部署
  • 更新于
在 GitHub 查看 aftabbs/postgresql-mcp-server

使用说明

PostgreSQL MCP服务器

一个模型上下文协议(MCP)服务器,通过Claude提供PostgreSQL数据库探索和查询功能。此服务器支持通过自然语言查询进行直接数据库交互、模式探索和智能关系发现。

特性

  • 数据库查询:直接通过Claude执行SQL查询
  • 模式探索:列出数据库、表,并获取详细的表描述
  • 关系发现:查找显式外键关系和隐式关系
  • 智能分析:自动检测模式并建议表之间的关系
  • 安全查询执行:具有适当转义和错误处理的参数化查询
  • 综合录井:调试和监控的详细日志记录

先决条件

  • Python 3.8+
  • Docker(用于PostgreSQL数据库)
  • Claude桌面应用程序
  • UV包管理器

安装

1.建立项目

# Clone or create your project directory
mkdir postgres-mcp-server
cd postgres-mcp-server

# Initialize with UV
uv init

2.安装依赖项

# Install required packages
uv add psycopg2-binary fastmcp pandas

3.使用Docker设置PostgreSQL

# Pull and run PostgreSQL container
docker run --name postgres-mcp \
  -e POSTGRES_DB=testdb \
  -e POSTGRES_USER=testuser \
  -e POSTGRES_PASSWORD=testpass \
  -p 5432:5432 \
  -d postgres:latest

# Wait for PostgreSQL to start (about 10-15 seconds)
# You can check if it's ready with:
docker logs postgres-mcp

4.配置克劳德桌面

将以下配置添加到您的 claude_desktop_config.json 文件:

在 macOS 上:

# Location: ~/Library/Application\ Support/Claude/claude_desktop_config.json

在Windows上:

# Location: %APPDATA%/Claude/claude_desktop_config.json

配置:

{
  "mcpServers": {
    "postgres-explorer": {
      "command": "uv",
      "args": [
        "run",
        "python",
        "/path/to/your/postgres-mcp-server/main.py",
        "--conn",
        "postgresql://testuser:testpass@localhost:5432/testdb"
      ],
      "cwd": "/path/to/your/postgres-mcp-server"
    }
  }
}

备注:替换 /path/to/your/postgres-mcp-server 带有项目目录的实际路径。

5.替代环境变量设置

您可以将其设置为环境变量,而不是在配置中传递连接字符串:

# Set environment variable
export POSTGRES_CONNECTION_STRING="postgresql://testuser:testpass@localhost:5432/testdb"

然后使用这个更简单的配置:

{
  "mcpServers": {
    "postgres-explorer": {
      "command": "uv",
      "args": [
        "run",
        "python",
        "/path/to/your/postgres-mcp-server/main.py"
      ],
      "cwd": "/path/to/your/postgres-mcp-server",
      "env": {
        "POSTGRES_CONNECTION_STRING": "postgresql://testuser:testpass@localhost:5432/testdb"
      }
    }
  }
}

用法

启动服务器

  1. 启动PostgreSQL容器 (如果尚未运行):

    docker start postgres-mcp
    
  2. 重新启动克劳德桌面 加载MCP服务器配置。

  3. 验证连接 克劳德问:

    Can you list the available schemas in the database?
    

查询示例

连接后,您可以使用自然语言通过Claude与PostgreSQL数据库进行交互:

模式探索

- "Show me all the tables in the database"
- "What's the structure of the users table?"
- "List all schemas available"

数据查询

- "Show me the first 10 records from the products table"
- "Find all users created in the last 30 days"
- "What are the unique categories in the products table?"

关系发现

- "What are the relationships for the orders table?"
- "Show me foreign key constraints for the customers table"
- "Find implied relationships in the inventory table"

高级分析

- "Create a summary of sales by month"
- "Find duplicate records in the users table"
- "Show me tables that might be related to the orders table"

可用工具

MCP服务器提供了Claude可以使用的以下工具:

  1. query(sql, parameters) -执行SQL查询
  2. list_schemas() -列出所有数据库架构
  3. list_tables(schema) -列出特定架构中的表
  4. describe_table(table_name, schema) -获取表结构
  5. get_foreign_keys(table_name, schema) -获取外键关系
  6. find_relationships(table_name, schema) -找到明确和隐含的关系

配置选项

连接字符串格式

服务器支持多种PostgreSQL连接字符串格式:

# Basic format
postgresql://username:password@host:port/database

# With additional parameters
postgresql://username:password@host:port/database?sslmode=require

# Using environment variables
postgresql://${DB_USER}:${DB_PASSWORD}@${DB_HOST}:${DB_PORT}/${DB_NAME}

环境变量

  • POSTGRES_CONNECTION_STRING -数据库连接字符串
  • LOG_LEVEL -日志记录级别(调试、信息、警告、错误)

故障排除

常见问题

  1. “连接被拒绝”错误

    • 确保PostgreSQL容器正在运行: docker ps
    • 检查端口5432是否可用: netstat -an | grep 5432
  2. “身份验证失败”错误

    • 验证连接字符串中的用户名和密码
    • 检查PostgreSQL容器日志: docker logs postgres-mcp
  3. MCP服务器未加载

    • 验证中的路径 claude_desktop_config.json 是正确的
    • 检查Claude Desktop日志中的错误消息
    • 确保UV已安装且可访问
  4. 权限错误

    • 确保用户具有适当的数据库权限
    • 检查数据库是否存在并且可以访问

测试设置

您可以独立测试服务器:

# Test database connection
uv run python main.py --conn "postgresql://testuser:testpass@localhost:5432/testdb"

日志和调试

服务器提供全面的日志记录。如果遇到问题,请检查日志:

  • 服务器日志将显示在Claude Desktop的控制台中
  • PostgreSQL日志: docker logs postgres-mcp
  • 通过设置启用调试日志记录 LOG_LEVEL=DEBUG

示例数据设置

要使用示例数据测试服务器,请执行以下操作:

-- Connect to your PostgreSQL instance
docker exec -it postgres-mcp psql -U testuser -d testdb

-- Create sample tables
CREATE TABLE customers (
    id SERIAL PRIMARY KEY,
    name VARCHAR(100),
    email VARCHAR(100),
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

CREATE TABLE orders (
    id SERIAL PRIMARY KEY,
    customer_id INTEGER REFERENCES customers(id),
    total_amount DECIMAL(10,2),
    order_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

-- Insert sample data
INSERT INTO customers (name, email) VALUES 
('John Doe', 'john@example.com'),
('Jane Smith', 'jane@example.com');

INSERT INTO orders (customer_id, total_amount) VALUES 
(1, 99.99),
(2, 149.50);

安全考虑

  • 在生产环境中为连接字符串使用环境变量
  • 实施适当的数据库用户权限
  • 考虑在高流量场景中使用连接池
  • 在生产环境中启用SSL连接
  • 定期更新安全补丁的依赖关系

贡献

  1. 分叉存储库
  2. 创建要素分支
  3. 进行更改
  4. 如果适用,添加测试
  5. 提交拉取请求

许可证

该项目是开源的,可在 MIT许可证.

支持

对于问题和疑问:

  • 检查上面的故障排除部分
  • 查看Claude Desktop MCP文档
  • 在项目存储库中打开问题