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 )

指定された列を持つ新しいテーブルを作成します。

  • 列名と型を定義する

  • null許容制約を設定する

  • デフォルト値を設定する

// 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 )

2 つの 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 環境変数を使用して構成することを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