PostgreSQL数据库查询服务

一个提供对PostgreSQL数据库只读访问的模型上下文协议服务器,允许LLMs检查数据库模式和执行只读查询。

  • by helloscoopa
  • TypeScript
  • 本地部署
  • 2 星标
  • 更新于
在 GitHub 查看 helloscoopa/mcp-postgres

使用说明

PostgreSQL MCP服务器

一个模型上下文协议服务器,提供对PostgreSQL数据库的只读访问。此服务器使LLM能够检查数据库模式并执行只读查询。

组件

工具

  • 怎么翻译

    • 根据配置的权限对连接的数据库执行SQL查询
    • 输入: sql (string):要执行的SQL查询
    • 权限控制允许哪些操作:
      • read:仅选择查询(默认情况下,使用只读事务)
      • ddl:数据定义语言(CREATE、DROP、ALTER等)
      • dml:数据操作语言(INSERT、UPDATE、DELETE等)
    • 可以组合多个权限(例如。, read,dml)
  • 模式

    • 获取所有表及其列的全面数据库模式信息
    • 输入: table_name (字符串,可选):仅获取特定表的架构
    • 返回详细的列信息,包括:
      • 列名和数据类型
      • 可为空的约束
      • 默认值
      • 字符限制和数字精度
    • 未指定表时,返回公共架构中所有表的架构
    • 使AI代理在编写查询之前能够理解数据库结构

资源

服务器为数据库中的每个表提供架构信息:

  • 持微软签名的表模式 (postgres://<host>/<table>/schema)
    • 每个表的JSON模式信息
    • 包括列名和数据类型
    • 从数据库元数据中自动发现

配置

服务器支持多种方式指定数据库连接和权限:

  1. 环境变量 (建议用于托管):设置 DATABASE_URL
  2. 命令行参数:将PostgreSQL URL作为第一个参数传递
  3. URL参数:用于具有自定义权限的web部署

权限系统

使用控制SQL操作 permissions 参数:

  • read (默认):只允许SELECT查询,使用只读事务
  • ddl:数据定义语言-CREATE、DROP、ALTER、TRUNCATE、COMMENT
  • dml:数据操作语言-INSERT、UPDATE、DELETE、MERGE、UPSERT

示例:

  • permissions=read -只读访问(默认)
  • permissions=read,dml -读取和修改数据
  • permissions=read,ddl,dml -完全数据库访问

使用Claude Desktop

要将此服务器与Claude Desktop应用程序一起使用,请将以下配置添加到您的“mcpServers”部分 claude_desktop_config.json:

码头工人

  • 在macos上运行docker时,如果服务器在主机网络上运行(例如localhost),请使用host.docker.internal
  • 用户名/密码可以添加到postgresql url中 postgresql://user:password@host:port/db-name
{
  "mcpServers": {
    "postgres": {
      "command": "docker",
      "args": [
        "run", 
        "-i", 
        "--rm", 
        "mcp/postgres", 
        "postgresql://host.docker.internal:5432/mydb"]
    }
  }
}

NPX

{
  "mcpServers": {
    "postgres": {
      "command": "npx",
      "args": [
        "-y",
        "@modelcontextprotocol/server-postgres",
        "postgresql://localhost/mydb"
      ]
    }
  }
}

替换 /mydb 使用您的数据库名称。

环境变量配置

对于托管或部署场景,您可以通过环境变量设置数据库URL:

# Set the environment variable
export DATABASE_URL="postgresql://user:password@host:port/database"

# Run the server (no CLI argument needed)
node dist/index.js

这种方法特别适用于:

  • 网络托管:部署服务器并配置 DATABASE_URL 在您的托管平台中
  • Claude Web自定义连接器:使用基于环境的配置来托管服务器
  • 生产部署:将敏感的连接字符串从命令行中删除

带有环境变量的Docker

{
  "mcpServers": {
    "postgres": {
      "command": "docker",
      "args": [
        "run", 
        "-i", 
        "--rm",
        "-e", "DATABASE_URL=postgresql://host.docker.internal:5432/mydb",
        "mcp/postgres"
      ]
    }
  }
}

使用VS代码

为了快速安装,请使用下面的一键安装按钮之一。..

对于手动安装,请将以下JSON块添加到VS Code中的用户设置(JSON)文件中。您可以按 Ctrl + Shift + P 和打字 Preferences: Open User Settings (JSON).

您可以选择将其添加到名为的文件中 .vscode/mcp.json 在您的工作空间中。这将允许您与他人共享配置。

请注意 mcp 中不需要密钥 .vscode/mcp.json 文件。

码头工人

备注:使用Docker并连接到主机上的PostgreSQL服务器时,请使用 host.docker.internal 而不是 localhost 在连接URL中。

{
  "mcp": {
    "inputs": [
      {
        "type": "promptString",
        "id": "pg_url",
        "description": "PostgreSQL URL (e.g. postgresql://user:pass@host.docker.internal:5432/mydb)"
      }
    ],
    "servers": {
      "postgres": {
        "command": "docker",
        "args": [
          "run",
          "-i",
          "--rm",
          "mcp/postgres",
          "${input:pg_url}"
        ]
      }
    }
  }
}

NPX

{
  "mcp": {
    "inputs": [
      {
        "type": "promptString",
        "id": "pg_url",
        "description": "PostgreSQL URL (e.g. postgresql://user:pass@localhost:5432/mydb)"
      }
    ],
    "servers": {
      "postgres": {
        "command": "npx",
        "args": [
          "-y",
          "@modelcontextprotocol/server-postgres",
          "${input:pg_url}"
        ]
      }
    }
  }
}

建筑

此服务器具有干净的模块化架构,可维护性和可扩展性:

src/postgres/
├── index.ts              # Main entry point and server setup
├── types.ts              # TypeScript type definitions
├── database.ts           # Database connection management
├── server.ts             # HTTP server and transport handling
├── handlers/
│   ├── resources.ts      # MCP resource handlers
│   └── tools.ts          # MCP tool handlers (query & schema)
└── utils/
    └── permissions.ts    # Permission validation and parsing

关键模块

  • types.ts:权限和数据库状态的集中类型定义
  • database.ts:数据库连接池和URL解析逻辑
  • 处理人员/:资源和工具的请求处理程序分开
  • utils/:权限和验证的实用函数
  • server.ts:具有SSE传输管理的HTTP服务器逻辑

这种模块化设计使代码库更容易:

  • 维护和调试单个组件
  • 隔离测试模块
  • 扩展新功能
  • 理解并贡献于

建筑

Docker:

docker build -t mcp/postgres -f src/postgres/Dockerfile . 

安全功能

此服务器实施了多种安全措施,以防止数据修改和未经授权的访问:

数据保护

  • 基于权限的访问:可配置的SQL操作权限(读取、ddl、dml)
  • 默认情况下为只读:除非明确授予更高的权限,否则只允许SELECT查询
  • 智能交易处理:只读权限为只读事务,写权限为提交/回滚的常规事务
  • SQL操作验证:如果查询超出授予的权限,则会对其进行分析和阻止
  • 连接隔离:每个请求都使用隔离的数据库连接

访问控制(HTTP模式)

  • 强制身份验证:建立SSE连接需要密钥令牌
  • 查询参数验证: ?secret=<token> 必须匹配 MCP_SECRET 环境变量
  • 基于会话的保护:消息端点受已建立的SSE连接的会话ID保护
  • 401未经授权:无效或缺少机密返回正确的HTTP错误代码
  • CORS支持:通过身份验证正确处理跨源请求

最佳实践

  • 使用强随机秘密令牌(例如,使用 openssl rand -base64 32)
  • 将机密安全地存储在托管平台的环境变量中
  • 定期轮换机密以进行生产部署
  • 监控访问日志,防止未经授权的尝试

部署选项

地方发展

# Using CLI argument
node dist/index.js "postgresql://localhost:5432/mydb"

# Using environment variable
export DATABASE_URL="postgresql://localhost:5432/mydb"
node dist/index.js

Claude Web自定义连接器的虚拟主机

部署到任何Node.js托管平台(Railway、Vercel、Heroku等):

  1. 设置环境变量:

    DATABASE_URL=postgresql://user:pass@host:port/db
    MCP_HTTP_MODE=true
    MCP_SECRET=your-secret-token    # REQUIRED for HTTP mode
    PORT=3000  # Optional, defaults to 3000
    
  2. 部署并运行: node dist/index.js

  3. 在Claude Web中,添加自定义连接器:

    https://your-deployed-server.com/sse?secret=your-secret-token
    

铁路部署示例

# Set environment variables in Railway dashboard:
DATABASE_URL=postgresql://user:pass@host:port/db
MCP_HTTP_MODE=true
MCP_SECRET=your-secret-token

# Deploy this repository
# Your connector URL will be: https://your-app.railway.app/sse?secret=your-secret-token

URL参数方法

方法1:数据库环境变量(推荐)

# Read-only access (default)
https://your-deployed-server.com/sse?secret=your-secret-token

# Custom permissions
https://your-deployed-server.com/sse?secret=your-secret-token&permissions=read,dml

方法2:通过查询参数访问数据库URL

# Read-only with custom database
https://your-deployed-server.com/sse?secret=your-secret-token&db=postgresql://user:pass@host:port/db

# Full permissions with custom database
https://your-deployed-server.com/sse?secret=your-secret-token&db=postgresql://user:pass@host:port/db&permissions=read,ddl,dml

安全说明:

  • 这 secret 参数为 始终需要 用于HTTP模式
  • 确保您的秘密令牌安全,并使用强随机值
  • 环境变量方法对数据库凭据更安全
  • 使用 permissions=read (默认)为了获得最大安全性-只允许SELECT查询
  • 小心 ddl 和 dml 权限,因为它们允许数据修改

许可证

此MCP服务器根据MIT许可证获得许可。这意味着您可以根据MIT许可证的条款和条件自由使用、修改和分发软件。有关更多详细信息,请参阅项目存储库中的LICENSE文件。