Skip to main content
Glama
PostgreSQL MCP Server

PostgreSQL MCP Server

by HenkDz

PostgreSQL MCP 服务器

铁匠徽章

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

版本 0.2.0

Related MCP server: PostgreSQL MCP Server

特征

该服务器提供以下工具:

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 文件。

Available Tools

18 tools
pg_analyze_databaseC

Analyze PostgreSQL database configuration and performance

Inputs: connectionString, analysisType.

pg_copy_between_databasesC

Copy data between two databases

Inputs: sourceConnectionString (required), targetConnectionString (required), tableName (required), where, +1 more.

pg_debug_databaseC

Debug common PostgreSQL issues

Inputs: issue (required), connectionString, logLevel.

pg_execute_mutationC

Execute data modification operations (INSERT/UPDATE/DELETE/UPSERT) - operation="insert/update/delete/upsert" with table and data. Examples: operation="insert", table="users", data={"name":"John","email":"john@example.com"}

Inputs: operation (required), table (required), connectionString, data, +4 more.

pg_execute_queryA

Execute SELECT queries and data retrieval operations - operation="select/count/exists" with query and optional parameters. Examples: operation="select", query="SELECT * FROM users WHERE created_at > $1", parameters=["2024-01-01"]

Inputs: operation (required), query (required), connectionString, parameters, +2 more.

pg_execute_sqlA

Execute arbitrary SQL statements - sql="ANY_VALID_SQL" with optional parameters and transaction support. Examples: sql="CREATE INDEX ...", sql="WITH complex_cte AS (...) SELECT ...", transactional=true

Inputs: sql (required), connectionString, parameters, expectRows, +2 more.

pg_export_table_dataC

Export table data to JSON or CSV format

Inputs: tableName (required), outputPath (required), connectionString, where, +2 more.

pg_import_table_dataC

Import data from JSON or CSV file into a table

Inputs: tableName (required), inputPath (required), connectionString, truncateFirst, +2 more.

pg_manage_commentsA

Manage PostgreSQL object comments - get, set, remove comments on tables, columns, functions, and other database objects. Examples: operation="get" with objectType="table", objectName="users", operation="set" with comment text, operation="bulk_get" for discovery

Inputs: operation (required), connectionString, objectType, objectName, +5 more.

pg_manage_constraintsB

Manage PostgreSQL constraints - get, create foreign keys, drop foreign keys, create constraints, drop constraints. Examples: operation="get" to list constraints, operation="create_fk" with constraintName, tableName, columnNames, referencedTable, referencedColumns

Inputs: operation (required), connectionString, schema, constraintName, +14 more.

pg_manage_functionsA

Manage PostgreSQL functions - get, create, or drop functions with a single tool. Examples: operation="get" to list functions, operation="create" with functionName="test_func", parameters="" (empty for no params), returnType="TEXT", functionBody="SELECT 'Hello'"

Inputs: operation (required), connectionString, functionName, schema, +9 more.

pg_manage_indexesB

Manage PostgreSQL indexes - get, create, drop, reindex, and analyze usage with a single tool. Examples: operation="get" to list indexes, operation="create" with indexName, tableName, columns, operation="analyze_usage" for performance analysis

Inputs: operation (required), connectionString, schema, tableName, +15 more.

pg_manage_queryA

Manage PostgreSQL query analysis and performance - operation="explain" for EXPLAIN plans, operation="get_slow_queries" for slow query analysis, operation="get_stats" for query statistics, operation="reset_stats" for clearing statistics

Inputs: operation (required), connectionString, query, analyze, +11 more.

pg_manage_rlsB

Manage PostgreSQL Row-Level Security - enable/disable RLS and manage policies. Examples: operation="enable" with tableName="users", operation="create_policy" with tableName, policyName, using, check

Inputs: operation (required), connectionString, tableName, schema, +8 more.

pg_manage_schemaB

Manage PostgreSQL schema - get schema info, create/alter tables, manage enums. Examples: operation="get_info" for table lists, operation="create_table" with tableName and columns, operation="get_enums" to list enums, operation="create_enum" with enumName and values

Inputs: operation (required), connectionString, tableName, schema, +5 more.

pg_manage_triggersA

Manage PostgreSQL triggers - get, create, drop, and enable/disable triggers. Examples: operation="get" to list triggers, operation="create" with triggerName, tableName, functionName, operation="drop" with triggerName and tableName, operation="set_state" with triggerName, tableName, enable

Inputs: operation (required), connectionString, schema, tableName, +10 more.

pg_manage_usersB

Manage PostgreSQL users and permissions - create, drop, alter users, grant/revoke permissions. Examples: operation="create" with username="testuser", operation="grant" with username, permissions, target, targetType

Inputs: operation (required), connectionString, username, password, +16 more.

pg_monitor_databaseC

Get real-time monitoring information for a PostgreSQL database

Inputs: connectionString, includeTables, includeQueries, includeLocks, +2 more.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    B3.2/5.0

    Scored across 18 tools

    Disambiguation4/5

    Most tools have distinct purposes targeting specific PostgreSQL management areas (e.g., schema, indexes, constraints), but some overlap exists. For example, pg_execute_mutation and pg_execute_sql both handle data modifications, and pg_manage_query's performance analysis overlaps with pg_analyze_database. However, descriptions help clarify boundaries, preventing major confusion.

    Naming Consistency5/5

    All tools follow a consistent 'pg_verb_noun' pattern with snake_case throughout (e.g., pg_manage_schema, pg_execute_query). This predictable naming convention makes it easy for agents to identify tool purposes and maintain readability across the set.

    Tool Count4/5

    With 18 tools, the count is slightly high but reasonable for a comprehensive PostgreSQL management server. It covers a wide range of database operations from queries to administration, though it might feel heavy for simpler use cases. Each tool appears to earn its place by addressing specific PostgreSQL features.

    Completeness5/5

    The tool set provides extensive coverage of PostgreSQL management, including CRUD operations (via pg_execute_mutation/query), schema management, performance monitoring, security (RLS, users), and data import/export. No obvious gaps are present; agents can handle full database lifecycles and advanced features without dead ends.

    Maintenance

    ActivityInactive
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      A
      quality
      D
      maintenance
      A Model Context Protocol server that enables interaction with PostgreSQL databases for analyzing setups, debugging issues, managing schemas, migrating data, and monitoring performance.
      1
      1
      MIT
    • A
      license
      Not graded
      quality
      D
      maintenance
      A Model Context Protocol server providing dual transport (HTTP and Stdio) access to PostgreSQL databases, allowing AI assistants to query databases and fetch schema information through natural language.
      34 npm
      31
      MIT
    • A
      license
      B
      quality
      D
      maintenance
      An open source Model Context Protocol server for PostgreSQL that provides database health analysis, index tuning, query plan exploration, and safe SQL execution for AI agents throughout the development process.
      9
      MIT
    • A
      license
      Not graded
      quality
      D
      maintenance
      A Model Context Protocol server for PostgreSQL databases that enables AI agents to connect, query, and explore multiple databases with schema discovery and extension context.
      542
      MIT