Skip to main content
Glama

PostgreSQL MCP Server

AGPL 3.0
355
46
  • Linux
  • Apple

PostgreSQL MCP 服务器

提供 PostgreSQL 数据库管理功能的模型上下文协议 (MCP) 服务器。该服务器可协助分析现有 PostgreSQL 设置、提供实施指导、调试数据库问题、管理架构、迁移数据以及监控数据库性能。

版本 0.2.0

特征

该服务器提供以下工具:

1. 数据库分析和设置

1.1. 分析数据库( analyze_database

分析 PostgreSQL 数据库配置和性能指标:

  • 配置分析
  • 性能指标
  • 安全评估
  • 优化建议
// Example usage { "analysisType": "performance" // Optional: "configuration" | "performance" | "security" }
1.2. 获取设置说明( get_setup_instructions

提供分步 PostgreSQL 安装和配置指南:

  • 特定于平台的安装步骤
  • 配置建议
  • 安全最佳实践
  • 安装后任务
// Example usage { "platform": "linux", // Required: "linux" | "macos" | "windows" "version": "15", // Optional: PostgreSQL version "useCase": "production" // Optional: "development" | "production" }
1.3. 调试数据库( debug_database

调试常见的 PostgreSQL 问题:

  • 连接问题
  • 性能瓶颈
  • 锁冲突
  • 复制状态
// Example usage { "issue": "performance", // Required: "connection" | "performance" | "locks" | "replication" "logLevel": "debug" // Optional: "info" | "debug" | "trace" }

2. 模式管理

2.1. 获取架构信息( get_schema_info

获取数据库或特定表的详细架构信息:

  • 数据库中的表列表
  • 列定义
  • 约束(主键、外键等)
  • 索引
// Example usage { "tableName": "users" // Optional: specific table to get info for }
2.2. 创建表( create_table

创建具有指定列的新表:

  • 定义列名称和类型
  • 设置可空约束
  • 设置默认值
// Example usage { "tableName": "users", // Required "columns": [ // Required { "name": "id", "type": "SERIAL", "nullable": false }, { "name": "username", "type": "VARCHAR(100)", "nullable": false }, { "name": "email", "type": "VARCHAR(255)", "nullable": false }, { "name": "created_at", "type": "TIMESTAMP", "default": "NOW()" } ] }
2.3. 修改表( alter_table

修改现有表:

  • 添加新列
  • 修改列类型或约束
  • 删除列
// Example usage { "tableName": "users", // Required "operations": [ // Required { "type": "add", "columnName": "last_login", "dataType": "TIMESTAMP" }, { "type": "alter", "columnName": "email", "nullable": false }, { "type": "drop", "columnName": "temporary_field" } ] }
2.4. 获取枚举( get_enums

获取有关 PostgreSQL ENUM 类型的信息。

// Example usage { "schema": "public", // Optional "enumName": "user_status" // Optional }
2.5. 创建枚举( create_enum

在数据库中创建一个新的 ENUM 类型。

// Example usage { "enumName": "order_status", // Required "values": ["pending", "processing", "shipped", "delivered"], // Required "schema": "public", // Optional "ifNotExists": true // Optional }

3.数据迁移

3.1. 导出表数据( export_table_data

将表数据导出为 JSON 或 CSV 格式:

  • 使用 WHERE 子句过滤数据
  • 限制行数
  • 选择输出格式
// Example usage { "tableName": "users", // Required "outputPath": "./exports/users.json", // Required "where": "created_at > '2023-01-01'", // Optional "limit": 1000, // Optional "format": "json" // Optional: "json" | "csv" }
3.2. 导入表数据( import_table_data

从 JSON 或 CSV 文件导入数据:

  • 导入前可选择截断表
  • 支持不同格式
  • 自定义 CSV 分隔符
// Example usage { "tableName": "users", // Required "inputPath": "./imports/users.json", // Required "truncateFirst": false, // Optional "format": "json", // Optional: "json" | "csv" "delimiter": "," // Optional: for CSV files }
3.3. 数据库间复制( copy_between_databases

在两个 PostgreSQL 数据库之间复制数据:

  • 使用 WHERE 子句过滤数据
  • 选择性地截断目标表
// Example usage { "sourceConnectionString": "postgresql://user:password@localhost:5432/source_db", // Required "targetConnectionString": "postgresql://user:password@localhost:5432/target_db", // Required "tableName": "users", // Required "where": "active = true", // Optional "truncateTarget": false // Optional }

4. 监控

4.1. 监控数据库( monitor_database

PostgreSQL数据库实时监控:

  • 数据库指标(连接数、缓存命中率等)
  • 表指标(大小、行数、死元组)
  • 主动查询信息
  • 锁信息
  • 复制状态
  • 可配置警报
// Example usage { "includeTables": true, // Optional "includeQueries": true, // Optional "includeLocks": true, // Optional "includeReplication": false, // Optional "alertThresholds": { // Optional "connectionPercentage": 80, "longRunningQuerySeconds": 30, "cacheHitRatio": 0.95, "deadTuplesPercentage": 10, "vacuumAge": 7 } }

5. 功能

5.1. 获取函数( get_functions

获取有关 PostgreSQL 函数的信息。

// Example usage { "functionName": "calculate_total", // Optional "schema": "public" // Optional }
5.2. 创建函数( create_function

创建或替换 PostgreSQL 函数。

// Example usage { "functionName": "get_user_count", // Required "parameters": "", // Required (empty if no params) "returnType": "integer", // Required "functionBody": "SELECT count(*) FROM users;", // Required "language": "sql", // Optional "volatility": "STABLE", // Optional "schema": "public", // Optional "security": "INVOKER", // Optional "replace": true // Optional }
5.3. 删除函数( drop_function

删除一个 PostgreSQL 函数。

// Example usage { "functionName": "old_function", // Required "parameters": "integer", // Optional: required for overloaded functions "schema": "public", // Optional "ifExists": true, // Optional "cascade": false // Optional }

6. 行级安全性(RLS)

6.1. 启用 RLS ( enable_rls )

在表上启用行级安全性。

// Example usage { "tableName": "sensitive_data", // Required "schema": "secure" // Optional }
6.2. 禁用 RLS ( disable_rls )

禁用表上的行级安全性。

// Example usage { "tableName": "sensitive_data", // Required "schema": "secure" // Optional }
6.3. 创建 RLS 策略( create_rls_policy

创建行级安全策略。

// Example usage { "tableName": "documents", // Required "policyName": "user_can_see_own_docs", // Required "using": "owner_id = current_user_id()", // Required "check": "owner_id = current_user_id()", // Optional "schema": "public", // Optional "command": "SELECT", // Optional "role": "app_user", // Optional "replace": false // Optional }
6.4. 编辑 RLS 策略( edit_rls_policy

编辑现有的行级安全策略。

// Example usage { "tableName": "documents", // Required "policyName": "user_can_see_own_docs", // Required "schema": "public", // Optional "roles": ["app_user", "admin_user"], // Optional: New roles (empty or omit to keep existing/use default) "using": "owner_id = current_user_id() OR is_admin(current_user_id())", // Optional: New USING expression "check": "owner_id = current_user_id()" // Optional: New WITH CHECK expression }
6.5. 删除 RLS 策略( drop_rls_policy

删除行级安全策略。

// Example usage { "tableName": "documents", // Required "policyName": "old_policy", // Required "schema": "public", // Optional "ifExists": true // Optional }
6.6. 获取 RLS 策略( get_rls_policies

获取行级安全策略。

// Example usage { "tableName": "documents", // Optional "schema": "public" // Optional }

7. 触发器

7.1. 获取触发器( get_triggers

获取有关 PostgreSQL 触发器的信息。

// Example usage { "tableName": "audit_log", // Optional "schema": "public" // Optional }
7.2. 创建触发器( create_trigger

创建一个 PostgreSQL 触发器。

// Example usage { "triggerName": "log_user_update", // Required "tableName": "users", // Required "functionName": "audit_user_change", // Required "schema": "public", // Optional "timing": "AFTER", // Optional "events": ["UPDATE"], // Optional "when": "OLD.email IS DISTINCT FROM NEW.email", // Optional "forEach": "ROW", // Optional "replace": false // Optional }
7.3. 删除触发器( drop_trigger

删除 PostgreSQL 触发器。

// Example usage { "triggerName": "old_trigger", // Required "tableName": "users", // Required "schema": "public", // Optional "ifExists": true, // Optional "cascade": false // Optional }
7.4. 设置触发器状态( set_trigger_state

启用或禁用 PostgreSQL 触发器。

// Example usage { "triggerName": "log_user_update", // Required "tableName": "users", // Required "enable": false, // Required: true to enable, false to disable "schema": "public" // Optional }

先决条件

  • Node.js >= 18.0.0
  • PostgreSQL 服务器(用于目标数据库操作)
  • 对目标 PostgreSQL 实例的网络访问

安装

通过 Smithery 安装

要通过Smithery自动为 Claude Desktop 安装 postgresql-mcp-server:

npx -y @smithery/cli install @HenkDz/postgresql-mcp-server --client claude

手动安装

  1. 克隆存储库
  2. 安装依赖项:
    npm install
  3. 构建服务器:
    npm run build
  4. 添加到 MCP 设置文件(例如,在您的 IDE 设置或全局 MCP 配置中):有几种方法可以配置服务器的连接字符串,其优先顺序如下:
    1. 工具特定参数:如果在调用特定工具时在参数中直接提供了connectionString ,则该值将用于该调用。
    2. CLI 参数:您可以在使用-cs--connection-string参数启动服务器时提供默认连接字符串。
    3. 环境变量:如果以上均未提供,服务器将查找POSTGRES_CONNECTION_STRING环境变量。

    如果通过任何一种方法都找不到连接字符串,则需要数据库连接的工具将会失败。

    在 MCP 设置中使用 CLI 参数的示例:

    { "mcpServers": { "postgresql-mcp": { "command": "node", "args": [ "/path/to/postgresql-mcp-server/build/index.js", "--connection-string", "postgresql://username:password@server:port/dbname" // Optionally, add "--tools-config", "/path/to/your/mcp-tools.json" ], "disabled": false, "alwaysAllow": [] // Note: 'env' block for POSTGRES_CONNECTION_STRING can still be used as a fallback // if --connection-string is not provided in args. } } }

    使用环境变量的示例(如果不使用 CLI 参数):

    { "mcpServers": { "postgresql-mcp": { "command": "node", "args": [ "/path/to/postgresql-mcp-server/build/index.js" // Optionally, add "--tools-config", "/path/to/your/mcp-tools.json" ], "disabled": false, "alwaysAllow": [], "env": { "POSTGRES_CONNECTION_STRING": "postgresql://username:password@server:port/dbname" } } } }

    使用--connection-string CLI 参数或POSTGRES_CONNECTION_STRING环境变量使得connectionString参数对于大多数工具调用而言成为可选项。

工具配置

服务器支持通过外部 JSON 配置文件过滤启用哪些工具。

  • CLI 选项:使用-tc <path>--tools-config <path>指定工具配置文件的路径。
  • 文件格式:JSON 文件应包含一个带有enabledTools键的对象,该对象包含一个工具名称字符串数组。示例mcp-tools.json
    { "enabledTools": [ "get_schema_info", "analyze_database", "export_table_data" ] }
  • 行为
    • 如果提供了配置文件并且该配置文件有效,则仅启用列出的工具。
    • 如果未提供文件、文件无效或无法读取,则所有工具将默认启用。
    • 服务器将根据此配置记录启用了哪些工具。

发展

  • npm run dev - 使用热重载启动开发服务器
  • npm run lint - 运行 ESLint
  • npm test - 运行测试(如果已配置)

安全注意事项

  1. 连接安全
    • 服务器根据以下优先级确定数据库连接字符串:
      1. 工具参数中直接提供的connectionString
      2. --connection-string启动服务器时使用的 CLI 参数。
      3. POSTGRES_CONNECTION_STRING环境变量。
    • 确保连接字符串(尤其是带有凭据的连接字符串)得到安全管理。
    • 通过pg (以前@vercel/postgres ) 使用连接池。
    • 验证连接字符串。
    • 支持 SSL/TLS 连接(通过连接字符串配置)。
  2. 查询安全
    • 执行预定义的操作;尽可能避免任意 SQL 执行。
    • 在适用的情况下使用参数化查询来防止 SQL 注入。
    • 记录操作以供审计。
  3. 验证
    • 通过连接字符串依赖于 PostgreSQL 的身份验证机制。
    • 安全地管理您的数据库凭据。如果可以避免,请勿在客户端请求中对其进行硬编码;在配置服务器时,建议使用--connection-string CLI 选项或POSTGRES_CONNECTION_STRING环境变量。

最佳实践

  1. 使用--connection-string CLI 选项或POSTGRES_CONNECTION_STRING环境变量安全地配置默认数据库连接字符串。
  2. 如果工具需要连接到与默认数据库不同的数据库,请直接在该工具的参数中提供connectionString
  3. 始终使用具有适当凭据的安全连接字符串,最好通过POSTGRES_CONNECTION_STRING环境变量进行配置。
  4. 遵循敏感环境的生产安全建议。
  5. 使用monitor_database工具定期监控和分析数据库性能。
  6. 保持 PostgreSQL 版本为最新版本。
  7. 独立实施适当的备份策略。
  8. 使用连接池实现更好的资源管理(内部处理)。
  9. 实施适当的错误处理和日志记录。
  10. 定期进行安全审核和更新。

错误处理

服务器实现以下错误处理:

  • 连接失败
  • 查询错误
  • 无效输入
  • 权限问题

错误以标准 MCP 错误格式返回。

贡献

  1. 分叉存储库
  2. 创建功能分支
  3. 提交你的更改
  4. 推送到分支
  5. 创建拉取请求

执照

该项目根据 AGPLv3 许可证获得许可 - 有关详细信息,请参阅 LICENSE 文件。

-
security - not tested
A
license - permissive license
-
quality - not tested

remote-capable server

The server can be hosted and run remotely because it primarily relies on remote services or has no dependency on the local environment.

模型上下文协议服务器,支持强大的 PostgreSQL 数据库管理功能,包括分析、模式管理、数据迁移和通过自然语言交互进行监控。

  1. 版本 0.2.0
    1. 特征
      1. 数据库分析和设置
      2. 模式管理
      3. 3.数据迁移
      4. 监控
      5. 功能
      6. 行级安全性(RLS)
      7. 触发器
    2. 先决条件
      1. 安装
        1. 通过 Smithery 安装
        2. 手动安装
      2. 工具配置
        1. 发展
          1. 安全注意事项
            1. 最佳实践
              1. 错误处理
                1. 贡献
                  1. 执照

                    Related MCP Servers

                    • -
                      security
                      A
                      license
                      -
                      quality
                      A Model Context Protocol server that provides read-only access to PostgreSQL databases with enhanced multi-schema support, allowing LLMs to inspect database schemas across multiple namespaces and execute read-only queries while maintaining schema isolation.
                      Last updated -
                      13
                      2
                      JavaScript
                      MIT License
                    • -
                      security
                      F
                      license
                      -
                      quality
                      A Model Context Protocol server providing both read and write access to PostgreSQL databases, enabling LLMs to query data, modify records, and manage database schemas.
                      Last updated -
                      4
                      JavaScript
                    • -
                      security
                      F
                      license
                      -
                      quality
                      A Model Context Protocol server that enables performing PostgreSQL database operations (create, read, update, delete) on User and Post entities through MCP tools.
                      Last updated -
                      TypeScript
                    • -
                      security
                      F
                      license
                      -
                      quality
                      A Model Context Protocol server that enables interaction with PostgreSQL databases to list tables, retrieve schemas, and execute read-only SQL queries.
                      Last updated -
                      16,948
                      JavaScript
                      • Linux
                      • Apple

                    View all related MCP servers

                    MCP directory API

                    We provide all the information about MCP servers via our MCP API.

                    curl -X GET 'https://glama.ai/api/mcp/v1/servers/HenkDz/postgresql-mcp-server'

                    If you have feedback or need assistance with the MCP directory API, please join our Discord server