FastPostgresMCP

by llm-graph
Verified

hybrid server

The server is able to function both locally and remotely, depending on the configuration or use case.

Integrations

  • Built on Bun runtime for high performance server execution, leveraging Bun's speed and JavaScript/TypeScript capabilities.

  • Allows AI agents to interact with multiple PostgreSQL databases, including running read-only queries, executing data-modifying statements, performing transactions, listing tables, and inspecting database schemas.

  • Implements end-to-end type-safety throughout the server with TypeScript, ensuring robust and error-resistant database interactions.

FastPostgresMCP 🐘⚡️ (フル機能のマルチ DB MCP サーバー)

このプロジェクトは、AI エージェント (Cursor、Claude Desktop など) がテーブルの一覧表示やスキーマの検査など、複数の PostgreSQL データベースと対話できるように設計された、非常に高速で型安全、かつフル機能のモデル コンテキスト プロトコル (MCP) サーバーを実装します。

これは、Bun、TypeScript、 postgresを使用して構築されており、堅牢な MCP サーバーを構築するためのfastmcpフレームワークの高度な機能を活用しています。

目的: AIエージェント用のMCPサーバー

これはコードにインポートするライブラリではありませんスタンドアロンのサーバーアプリケーションです。プロセスとして実行され、MCPクライアント(AIエージェントなど)はJSONベースのモデルコンテキストプロトコル(v2.0)を使用してサーバーアプリケーションと通信します。通常は、クライアントアプリケーション(例:Cursor)が管理するstdio接続を介して通信します。

トラブルシューティングと開発

CLI を使用したテスト

パッケージには、MCP サーバーを直接テストするための組み込み CLI コマンドが含まれています。

# From the project repository: bun run cli # This will start an interactive MCP CLI session where you can: # - Call any of the PostgreSQL tools (query_tool, execute_tool, etc.) # - View server capabilities # - Test queries against your configured databases

組み込みのMCPインスペクターによるテスト

MCP インスペクターを使用して視覚的にテストおよびデバッグすることもできます。

# From the project repository: bun run inspect

よくある問題

bunx postgres-mcp実行中にこのエラーが表示された場合:

FastPostgresMCP started [warning] FastMCP could not infer client capabilities

ping メッセージが続く場合は、次のことを意味します。

  1. MCPサーバーが正常に起動しました
  2. クライアントは正常に接続しました
  3. しかし、クライアントはpingリクエストを送信するだけで、適切に機能のネゴシエーションを行っていません。

これは通常、適切なMCPクライアントを使用する必要があることを示しています。以下をお試しください。

  • bun run cliを使用して MCP CLI でテストする
  • インストールセクションの説明に従って、Cursor または Claude Desktop で MCP サーバーを構成する

カスタム MCP クライアントを開発している場合は、機能ネゴシエーションを含む MCP プロトコルが適切に実装されていることを確認してください。

✨ コア機能

  • 🚀 超高速: Bun とfastmcp上に構築されています。
  • 🔒 タイプセーフ: Zod スキーマ検証を備えたエンドツーエンドの TypeScript。
  • 🐘 マルチデータベースのサポート: .envで定義された複数の PostgreSQL インスタンスに接続し、それらのインスタンス間のやり取りを管理します。
  • 🛡️ 設計によるセキュリティ: postgres経由のパラメーター化されたクエリにより、SQL インジェクションを防止します。
  • 🔑 オプションの認証: API キー検証 ( fastmcpauthenticateフック) を使用して、ネットワークベースの接続 (SSE/HTTP) を保護します。
  • 📄 MCP リソース経由のデータベース スキーマ:
    • テーブルの一覧: db://{dbAlias}/schema/tablesを介してデータベース内のテーブルの一覧を取得します。
    • テーブル スキーマの検査: db://{dbAlias}/schema/{tableName}を介して特定のテーブルの詳細な列情報を取得します。
  • 💬 強化されたツールインタラクション:
    • **ツール内ログ:**ツールは詳細なログをクライアントに送り返します ( logコンテキスト)。
    • **進行状況レポート:**長時間実行される操作は進行状況を報告します ( reportProgressコンテキスト)。
  • **🧠 セッション対応:**ツール実行コンテキスト ( sessionコンテキスト) 内のセッション情報にアクセスします。
  • **📡 イベント駆動型:**接続/セッション イベントの処理にserver.onsession.onを使用します。
  • **🔧 最新の開発者エクスペリエンス (DX):**明確な構成、直感的な API、 fastmcpツールによる簡単なテスト。

含まれるもの(fastmcp の機能を活用)

  • FastMCPサーバーコア
  • server.addTool ( query_toolexecute_toolschema_tooltransaction_toolの場合)
  • server.addResourceTemplate (テーブルの一覧表示とテーブルスキーマの検査用)
  • server.start ( stdioに重点を置き、 sse / httpに適応可能)
  • オプション: authenticateフック (API キー検証用)
  • ツール実行context ( logreportProgresssession )
  • パラメータスキーマ検証のためのZod
  • server.on (接続ログ用)
  • (潜在的に)セッション固有のロジックのためのsession.on

📋 前提条件

  • **Bun (v1.0 以降を推奨):**インストールされ、PATH に含まれています。
  • **PostgreSQL データベース:**アクセス資格情報と接続。ユーザーにはinformation_schemaをクエリする権限が必要です。

⚙️ インストール

オプション1: NPMパッケージ

# Install globally npm install -g postgres-mcp # Or install locally in your project npm install postgres-mcp

npm パッケージはhttps://www.npmjs.com/package/postgres-mcpから入手できます。

オプション2: リポジトリのクローン

  1. リポジトリをクローンします。
    # Replace with your actual repository URL git clone https://github.com/llm-graph/postgres-mcp.git cd postgres-mcp
  2. 依存関係をインストールします:
    bun install

🔑 構成(マルチデータベースとオプションの認証)

適切な.envファイルから読み込まれた環境変数を使用して構成します。

  1. 環境ファイルを作成します。
    • 本番環境の場合: cp .env.example .env
    • 開発の場合: cp .env.development.example .env.development
  2. **環境ファイルの読み込み順序:**サーバーは、次の優先順位でファイルから環境変数を読み込みます。
    • .env.<NODE_ENV> (例: .env.development.env.production.env.staging )
    • .env.local (バージョン管理されていないローカルオーバーライド用)
    • .env (デフォルトのフォールバック) これにより、環境ごとに異なる構成が可能になります。
  3. 環境ファイルを編集して、データベース接続と認証を定義します。
    • DB_ALIASES - 一意のDBエイリアスのカンマ区切りリスト
    • DEFAULT_DB_ALIAS - ツール呼び出しで 'dbAlias' が省略された場合のデフォルトのエイリアス
    • 各エイリアスのデータベース接続の詳細(例: DB_MAIN_HOSTDB_REPORTING_HOST
    • オプションのAPIキー認証( ENABLE_AUTHMCP_API_KEY
# Example .env file - Key Variables # REQUIRED: Comma-separated list of unique DB aliases DB_ALIASES=main,reporting # REQUIRED: Default alias if 'dbAlias' is omitted in tool calls DEFAULT_DB_ALIAS=main # OPTIONAL: Enable API Key auth (primarily for network transports) ENABLE_AUTH=false MCP_API_KEY=your_super_secret_api_key_here # CHANGE THIS # Define DB connection details for each alias (DB_MAIN_*, DB_REPORTING_*, etc.) DB_MAIN_HOST=localhost DB_MAIN_PORT=5432 DB_MAIN_NAME=app_prod_db DB_MAIN_USER=app_user DB_MAIN_PASSWORD=app_secret_password DB_MAIN_SSL=disable # Alternative: Use connection URLs # DB_MAIN_URL=postgres://user:password@localhost:5432/database?sslmode=require # --- Optional: Server Logging Level --- # LOG_LEVEL=info # debug, info, warn, error (defaults to info)

🚀 サーバーの実行(プロセスとして)

Bunを使用してこのサーバーを直接実行します。通常、AIクライアント(Cursorなど)がこのコマンドの起動と管理を行います。

オプション1: グローバルにインストールされたパッケージを使用する

  • 手動で実行するには: postgres-mcp

オプション2: プロジェクトでパッケージを使用する

  • プロジェクトから実行するには: npx postgres-mcp
  • またはプログラムでインポートします:
    // server.js import { startServer } from 'postgres-mcp'; // Start the MCP server startServer();

オプション3: クローンしたリポジトリから

  • 手動で実行するには(テスト用): bun run src/index.ts
  • 手動開発モード: bun run --watch src/index.ts

fastmcp CLIツールを使ったテスト

  • 対話型ターミナル: bunx fastmcp dev src/index.ts
  • Web UI インスペクター: bunx fastmcp inspect src/index.ts

💻 プログラム API の使用(ライブラリとして)

postgres-mcp は、スタンドアロンの MCP サーバーとして実行するだけでなく、Node.js/TypeScript アプリケーション内のライブラリとしてプログラム的に使用することもできます。

基本的な使い方

import { createPostgresMcp } from 'postgres-mcp'; // Create the PostgresMcp instance const postgresMcp = createPostgresMcp(); // Start the server postgresMcp.start(); // Direct database operations const results = await postgresMcp.executeQuery( 'SELECT * FROM users WHERE role = $1', ['admin'], 'main' // optional database alias ); // When done, stop the server and close connections await postgresMcp.stop();

直接関数インポート

より単純なユースケースでは、特定の関数を直接インポートできます。

import { initConnections, closeConnections, executeQuery, executeCommand, executeTransaction, getTableSchema, getAllTableSchemas } from 'postgres-mcp'; // Configure database connections const dbConfigs = { main: { host: 'localhost', port: 5432, database: 'my_db', user: 'db_user', password: 'db_password' } }; // Initialize connections initConnections(dbConfigs); // Execute a query const results = await executeQuery( 'SELECT * FROM users WHERE role = $1', ['admin'], 'main' ); // Get schema for a single table const schema = await getTableSchema('users', 'main'); // Get schema for all tables in the database const allSchemas = await getAllTableSchemas('main'); // Close connections when done await closeConnections();

設定オプション

const postgresMcp = createPostgresMcp({ // Custom database configurations (override .env) databaseConfigs: { main: { host: 'localhost', port: 5432, database: 'app_db', user: 'app_user', password: 'password', ssl: 'disable' } }, // Server configuration serverConfig: { name: 'Custom PostgresMCP', defaultDbAlias: 'main' }, // Transport options: 'stdio', 'sse', or 'http' transport: 'http', port: 3456 });

プログラム API の完全なドキュメントについては、 docs/programmatic-api.mdを参照してください。

🔌 AI クライアントとの接続 (Cursor、Claude Desktop)

AI エージェント (MCP クライアント) を構成して、コマンド/引数メカニズムを介してこのサーバー スクリプトを実行します

カーソルAI - 詳細な例

  1. カーソル設定/環境設定を開きます (Cmd+, または Ctrl+,)。
  2. 「拡張機能」->「MCP」に移動します。
  3. 「MCP サーバーの追加」をクリックするか、 settings.jsonを編集します。
  4. 次の JSON 構成を追加します。
    // In Cursor's settings.json or MCP configuration UI { "mcpServers": { "postgres-mcp": { // Unique name for Cursor "description": "MCP Server for PostgreSQL DBs (Main, Reporting)", "command": "bunx", // Use 'bun' or provide absolute path: "/Users/your_username/.bun/bin/bun" "args": [ "postgres-mcp" // or // *** ABSOLUTE PATH to your server's entry point *** // "/Users/your_username/projects/postgres-mcp/src/index.ts" / ], "env": { // .env file in project dir is loaded automatically by Bun. // Add overrides or Cursor-specific vars here if needed. }, "enabled": true } } }
  5. カーソル を保存して再起動するか、「MCP サーバーを再ロード」します。
  6. カーソルの MCP ステータス/ログで接続を確認します

クロードデスクトップ

  1. config.jsonを見つけて編集します (パスについては前の README を参照してください)。
  2. args絶対パスを使用して、 mcpServersの下に同様のエントリを追加します。
  3. Claude Desktop を再起動します。

🛠️ MCP 機能の公開

認証(オプション)

  • ENABLE_AUTH=trueの場合、 MCP_API_KEYに一致するX-API-Keyヘッダーを介してネットワーク トランスポート (HTTP/SSE) を保護します。
  • stdio接続 (Cursor/Claude のデフォルト) は通常、このチェックをバイパスします。

リソース

1. データベーステーブルの一覧表示

  • URI テンプレート: db://{dbAlias}/schema/tables
  • **説明:**指定されたデータベースエイリアス (通常は「public」スキーマ) 内のユーザー テーブル名のリストを取得します。
  • リソース定義 ( addResourceTemplate ):
    • uriTemplate : "db://{dbAlias}/schema/tables"
    • arguments :
      • dbAlias : (文字列、必須) - データベースのエイリアス ( .envから)。
    • load({ dbAlias }) : データベースに接続し、 information_schema.tables (パブリック スキーマの基本テーブルに対してフィルター処理され、実装でカスタマイズ可能) をクエリし、結果を JSON 文字列配列["table1", "table2", ...]としてフォーマットし、 { text: "..." }を返します。

使用例 (AI プロンプト): 「リソースdb://main/schema/tablesを取得して、メイン データベース内のテーブルを一覧表示します。」

2. テーブルスキーマの検査

  • URI テンプレート: db://{dbAlias}/schema/{tableName}
  • **説明:**特定のテーブルの詳細なスキーマ情報 (列、タイプ、NULL 値可能性、デフォルト) を提供します。
  • リソース定義 ( addResourceTemplate ):
    • uriTemplate : "db://{dbAlias}/schema/{tableName}"
    • arguments :
      • dbAlias : (文字列、必須) - データベースの別名。
      • tableName : (文字列、必須) - テーブルの名前。
    • load({ dbAlias, tableName }) : 接続し、特定のテーブルのinformation_schema.columnsを照会し、列オブジェクトの JSON 文字列配列としてフォーマットし、 { text: "..." }を返します。

使用例 (AI プロンプト): 「リソースdb://reporting/schema/daily_salesについて説明してください。」

応答コンテンツの例 (JSON 文字列):

"[{\"column_name\":\"session_id\",\"data_type\":\"uuid\",\"is_nullable\":\"NO\",\"column_default\":\"gen_random_uuid()\"},{\"column_name\":\"user_id\",\"data_type\":\"integer\",\"is_nullable\":\"NO\",\"column_default\":null},{\"column_name\":\"created_at\",\"data_type\":\"timestamp with time zone\",\"is_nullable\":\"YES\",\"column_default\":\"now()\"},{\"column_name\":\"expires_at\",\"data_type\":\"timestamp with time zone\",\"is_nullable\":\"YES\",\"column_default\":null}]"

ツール

ツールはcontextオブジェクト ( logreportProgresssession ) を受け取ります。


1. query_tool

読み取り専用の SQL クエリを実行します。

  • **説明:**読み取り専用 SQL を安全に実行し、実行ログ/進行状況とともに結果を取得します。
  • パラメーター: statement (文字列)、 params (配列、opt)、 dbAlias (文字列、opt)。
  • コンテキストの使用法: log.info/debug 、オプションのreportProgress 、アクセスsession
  • **戻り値:**行配列の JSON 文字列。

リクエスト例:

{ "tool_name": "query_tool", "arguments": { "statement": "SELECT product_id, name, price FROM products WHERE category = $1 AND price < $2 ORDER BY name LIMIT 10", "params": ["electronics", 500], "dbAlias": "main" } }

応答コンテンツの例 (JSON 文字列):

"[{\"product_id\":123,\"name\":\"Example Gadget\",\"price\":499.99},{\"product_id\":456,\"name\":\"Another Device\",\"price\":350.00}]"

2. execute_tool

データを変更する SQL ステートメントを実行します。

  • **説明:**実行ログを使用して、データを変更する SQL を安全に実行します。
  • パラメーター: statement (文字列)、 params (配列、opt)、 dbAlias (文字列、opt)。
  • コンテキストの使用法: log.info/debug 、アクセスsession
  • **戻り値:**影響を受ける行を示す文字列。

リクエスト例:

{ "tool_name": "execute_tool", "arguments": { "statement": "UPDATE users SET last_login = NOW() WHERE user_id = $1", "params": [54321] // dbAlias omitted, uses DEFAULT_DB_ALIAS } }

応答内容の例(文字列):

"Rows affected: 1"

3. schema_tool

特定のテーブルの詳細なスキーマ情報を取得します。

  • **説明:**データベース テーブルの列の定義と詳細を取得します。
  • パラメータ: tableName (文字列)、 dbAlias (文字列、opt)。
  • コンテキストの使用法: log.info 、アクセスsession
  • **戻り値:**列情報オブジェクトの JSON 文字列配列。

リクエスト例:

{ "tool_name": "schema_tool", "arguments": { "tableName": "user_sessions", "dbAlias": "main" } }

応答コンテンツの例 (JSON 文字列):

"[{\"column_name\":\"session_id\",\"data_type\":\"uuid\",\"is_nullable\":\"NO\",\"column_default\":\"gen_random_uuid()\"},{\"column_name\":\"user_id\",\"data_type\":\"integer\",\"is_nullable\":\"NO\",\"column_default\":null},{\"column_name\":\"created_at\",\"data_type\":\"timestamp with time zone\",\"is_nullable\":\"YES\",\"column_default\":\"now()\"},{\"column_name\":\"expires_at\",\"data_type\":\"timestamp with time zone\",\"is_nullable\":\"YES\",\"column_default\":null}]"

4. transaction_tool

複数の SQL ステートメントをアトミックに実行します。

  • **説明:**ステップのログ記録/進行状況とともに、トランザクション内で SQL シーケンスを実行します。
  • パラメーター: operations ({statement, params} の配列)、 dbAlias (文字列、opt)。
  • コンテキストの使用reportProgress: log.info/debug/error``session
  • **戻り値:**成功/失敗をまとめた JSON 文字列: {"success": true, "results": [...]}または{"success": false, "error": ..., "failedOperationIndex": ...}

リクエスト例:

{ "tool_name": "transaction_tool", "arguments": { "operations": [ { "statement": "INSERT INTO orders (customer_id, order_date, status) VALUES ($1, NOW(), 'pending') RETURNING order_id", "params": [101] }, { "statement": "INSERT INTO order_items (order_id, product_sku, quantity, price) VALUES ($1, $2, $3, $4)", "params": [9999, "GADGET-X", 2, 49.99] }, { "statement": "UPDATE inventory SET stock_count = stock_count - $1 WHERE product_sku = $2 AND stock_count >= $1", "params": [2, "GADGET-X"] } ], "dbAlias": "main" } }

成功応答コンテンツの例 (JSON 文字列):

"{\"success\":true,\"results\":[{\"operation\":0,\"rowsAffected\":1},{\"operation\":1,\"rowsAffected\":1},{\"operation\":2,\"rowsAffected\":1}]}"

エラー応答コンテンツの例 (JSON 文字列):

"{\"success\":false,\"error\":\"Error executing operation 2: new row for relation \\\"inventory\\\" violates check constraint \\\"stock_count_non_negative\\\"\",\"failedOperationIndex\":2}"

サーバーとセッションのイベント

  • クライアント接続のログを記録するためにserver.on('connect'/'disconnect')を使用します。
  • 必要に応じて、より詳細なセッション イベント処理のためにsession.on(...)を使用できます。

🔒 セキュリティに関する考慮事項

  • **SQLインジェクション:**パラメータ化されたクエリによって軽減されます。直接入力の連結は行われません。
  • データベース権限: **重要。**DB_<ALIAS>_USERに、スキーマ/テーブル一覧リソースのinformation_schemaへの読み取りアクセスを含む最小限の権限を割り当てます。
  • SSL/TLS:本番環境では必須( DB_<ALIAS>_SSL=requireまたはより厳密)。
  • シークレット管理: .envファイルを保護します( .gitignoreに追加します)。本番環境では、安全なシークレット管理(Vault、Doppler、クラウドシークレット)を使用します。
  • 認証スコープ: authenticateフックは主にネットワーク トランスポートを保護します。stdio stdioは実行環境に依存します。
  • **データの機密性:**接続/ツールを介してアクセスできるデータに注意してください。
  • **リソースクエリ:**テーブル( information_schema.tables )とスキーマ( information_schema.columns )の一覧表示に使用されるクエリは、一般的に安全ですが、データベース権限に依存します。設定されたユーザーに適切な読み取りアクセス権があることを確認してください。セキュリティや明確さの観点から、必要に応じてテーブル一覧表示クエリ(例:スキーマフィルタリング)をカスタマイズしてください。

📜 ライセンス

このプロジェクトはMITライセンスに基づいてライセンスされています。詳細はLICENSEファイルをご覧ください。

📋 変更履歴

1.0.0

  • 初回リリース
  • PostgreSQL 用のフル機能 MCP サーバー
  • 複数のデータベース接続のサポート
  • クエリ、実行、スキーマ検査、トランザクションのためのツール
  • スキーマイントロスペクションのリソース
  • 包括的なドキュメントと例
ID: cu9jnv9gk1