MCP Database Server

by dwarvesf
Verified

hybrid server

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

Integrations

  • Enables querying Parquet files through DuckDB, providing data analysis capabilities on structured files

  • Allows reading and querying Parquet files stored in Google Cloud Storage buckets

  • Provides tools for executing SQL queries against PostgreSQL databases, including SELECT, CREATE/INSERT, UPDATE, and DELETE operations

MCP データベース サーバー

mcp-frameworkを使用して構築されたモデル コンテキスト プロトコル (MCP) サーバー。データベース (DuckDB 経由の PostgreSQL) および Google Cloud Storage (GCS) と対話するためのツールとリソースを提供します。

前提条件

  • Node.js 22以上
  • タイプスクリプト
  • PostgreSQL(データベース機能に必要)
  • Google Cloud 認証情報(オプション、GCS 機能用)
  • Devboxmakeコマンドを使用したローカル開発用)

プロジェクト構造

. ├── docs │   ├── assets │   │   └── etl.png │   ├── etl-workflow.md │   └── setup-with-claude-desktop.md ├── migrations │   ├── 1743322886782_initial-schema.cjs │   └── 1743323460433_continuous-aggregates.cjs ├── scripts │   └── setup-continuous-aggregates.sql ├── src │   ├── resources # MCP Resource definitions │   │   ├── gcs_objects.ts │   │   └── sql_tables.ts │   ├── services # Service initializers (DB connections, GCS client) │   │   ├── duckdb.ts │   │   ├── gcs.ts │   │   └── postgres.ts │   ├── tools # MCP Tool definitions │   │   ├── duckdb_insert.ts │   │   ├── duckdb_query.ts │   │   ├── duckdb_read_parquet.ts │   │   └── gcs_directory_tree.ts │   ├── utils # Utility functions (logging, formatting) │   │   ├── index.ts │   │   └── logger.ts │   ├── config.ts # Configuration loading and validation │   ├── index.ts # Main server entry point │   └── utils.ts # Deprecated utils? (Consider removing if unused) ├── .env.example # Example environment variables ├── .gitignore ├── CLAUDE.md ├── Dockerfile ├── MIGRATION.md ├── Makefile # Development commands ├── README.md ├── database.json # Migration configuration ├── devbox.json # Devbox configuration ├── devbox.lock ├── docker-compose.yml # Docker setup for DBs ├── fly.toml # Fly.io deployment config ├── package-lock.json ├── package.json └── tsconfig.json

インストール

  1. リポジトリをクローンします。
    git clone <repository-url> cd mcp-db
  2. 依存関係をインストールします (一貫性を保つために Devbox の使用をお勧めします)。
    devbox install # Or using npm directly if not using Devbox # npm install
  3. .env.example.envにコピーし、環境変数を入力します。
    cp .env.example .env # Edit .env with your details
  4. プロジェクトをビルドします。
    # Using make (requires Devbox) make build # Or using npm directly # npm run build

構成

環境変数

次の環境変数 (またはコマンドライン引数) を使用してサーバーを構成します。

  • DATABASE_URL : PostgreSQL 接続文字列 (supergateway で実行しない限り必須)。
  • DATABASE_URLS : 複数のデータベース接続のalias=urlペアのコンマ区切りリスト ( DATABASE_URLの代替)。
  • LOG_LEVEL : ログレベル( debuginfoerror )。デフォルト: info
  • GCS_BUCKET : デフォルトの Google Cloud Storage バケット名 (オプション)。
  • GCP_SERVICE_ACCOUNT : Base64 でエンコードされた Google Cloud サービス アカウント キー JSON (オプション、GCS 認証用)。
  • GCS_KEY_ID / GCS_SECRET : DuckDB のhttpfs拡張機能専用の代替 GCS 認証情報 (オプション)。
  • TRANSPORT : トランスポートタイプ( stdioまたはsse )。デフォルト: stdio
  • PORT : SSEトランスポートのポート番号。デフォルト: 3001
  • HOST : SSEトランスポートのホスト名。デフォルト: localhost
  • API_KEY : サーバーを保護するためのオプションの API キー (設定されている場合、クライアントはAuthorization: Bearer <key>ヘッダーでそれを提供する必要があります)。

コマンドライン引数(例: --port 8080--gcs-bucket my-bucket )は環境変数を上書きします。詳細はsrc/config.tsを参照してください。

データベースの移行

このプロジェクトでは、PostgreSQLのスキーマ変更の管理にnode-pg-migrate使用しています。マイグレーションの実行と作成の詳細については、上記の元のREADMEの「データベースマイグレーション」セクションをご覧ください。

**注:**前述のnpm run setup:dbコマンドは、現在の設定に基づいて確認または更新する必要がある場合があります。

サーバーの実行

便利な開発コマンドにはMakefileを使用します (Devbox が必要です)。

# Run in development mode (builds and starts with nodemon for auto-restarts) # Uses SSE transport by default on port 3001 make dev # Run tests (if configured) # make test # Build for production # make build

makeなしで実行するには ( npm run buildの後):

# Run with stdio transport node dist/index.js --transport stdio # Run with SSE transport on default port 3001 node dist/index.js --transport sse # Run with SSE on a different port node dist/index.js --transport sse --port 8080

クライアント構成

MCP クライアント (例: mcp-cli 、Claude Desktop) をローカル サーバーに接続するには:

SSE トランスポートの場合 (例: ポート 3001):

{ "mcpServers": { "mcp-db-local": { "command": "node", "args": [ "/path/to/mcp-db/dist/index.js", // Adjust path if needed "--transport", "sse", "--port", "3001" // Match the port the server is running on ], // Add "env" if API_KEY is set // "env": { "API_KEY": "your-secret-key" } } } }

(注: 以前の README の Docker/supergateway の例は古くなっているか、別のデプロイメント設定に固有のものである可能性があります。)

Stdio トランスポートの場合:

{ "mcpServers": { "mcp-db-local": { "command": "node", "args": [ "/path/to/mcp-db/dist/index.js", // Adjust path if needed "--transport", "stdio" ], // Add "env" if API_KEY is set // "env": { "API_KEY": "your-secret-key" } } } }

GitHubからnpxを実行する

npx を使用してサーバーを直接実行できます (パッケージ内のビルド ステップが必要です)。

# Ensure required env vars are set export DATABASE_URL="postgresql://user:password@localhost:5432/db" export GCS_BUCKET="my-bucket" npx github:dwarvesf/mcp-db --transport sse --port 3001

利用可能なツール

  • duckdb_insert : DuckDBを介して接続されたPostgreSQLデータベースに対してINSERT文を実行します。INSERT INSERTのみが許可されます。
  • duckdb_query : DuckDBのpostgres_query関数を使用して、接続されたPostgreSQLデータベース( postgres_db )に対して読み取り専用のSQLクエリを直接実行します。修飾されていないテーブル名には自動的にプレフィックスが付けられます(例: my_table``postgres_db.public.my_tableになります)。
  • duckdb_read_parquet : DuckDB を使用して (設定されている場合は GCS から) Parquet ファイルをクエリします。
  • gcs_directory_tree : ページ区切りをサポートする GCS バケットからディレクトリ ツリー構造を取得します。

利用可能なリソース

  • mcp://gcs/objects ( gcs_objects ): 設定された GCS バケット内のオブジェクトを一覧表示します。
  • mcp://db/tables ( sql_tables ): 構成された PostgreSQL データベース内のすべてのテーブルとその列を一覧表示します。

開発:新しいツール/リソースの統合

このプロジェクトはmcp-frameworkを使用しています。新しいツールまたはリソースを追加するには:

  1. クラスを作成します:
    • src/tools/またはsrc/resources/に新しい.tsファイルを作成します。
    • MCPToolまたはMCPResourceを拡張するクラスを定義します。
    • 必要なプロパティ (ツールの場合はnamedescriptionschema ) とメソッド (ツールの場合はexecute 、リソースの場合はread ) を実装します。
    • 入力検証 (ツール) には、 schemaプロパティで Zod を使用します。
    • クラス内の依存関係 (DB 接続や GCS クライアントなど) を初期化します。多くの場合、コンストラクター内で、 src/services/のサービスまたはsrc/config.tsの構成を使用する可能性があります。

    サンプルツール ( src/tools/my_tool.ts ):

    import { MCPTool } from "mcp-framework"; import { z } from "zod"; import { formatSuccessResponse } from "../utils.js"; import { getDuckDBConnection } from "../services/duckdb.js"; // Example dependency const MyToolInputSchema = z.object({ param1: z.string().describe("Description for parameter 1"), }); type MyToolInput = z.infer<typeof MyToolInputSchema>; export class MyTool extends MCPTool<MyToolInput> { name = "my_tool"; description = "Description of what my tool does."; schema = { // Matches Zod schema structure param1: { type: z.string(), description: "Description for parameter 1" }, }; async execute(args: MyToolInput): Promise<any> { console.error(`Handling tool request: ${this.name}`); const duckDBConn = getDuckDBConnection(); // Get dependency // ... implement logic using args and duckDBConn ... const result = { message: `Processed ${args.param1}` }; return formatSuccessResponse(result); } } export default MyTool; // Ensure default export
  2. 自動検出:
    • mcp-framework``src/toolsおよびsrc/resourcesディレクトリ内のファイルからデフォルトでエクスポートされるツール/リソース クラスを自動的に検出して登録します。
    • 新しいクラスがファイル内のdefault exportであることを確認します。
  3. テスト:
    • サーバーを実行します ( make dev )。
    • 起動ログをチェックして、新しいツール/リソースがリストされていることを確認します。
    • MCP クライアント ( mcp-cliや MCP Inspector など) を使用してツールを呼び出すか、リソースを読み取ってその機能を検証します。

ベストプラクティス

  • ツール用の Zod を使用して明確な入力スキーマを定義します。
  • execute / read内でエラーを適切に処理し、 formatErrorResponseを使用してフォーマットされたエラー応答を返します (またはエラーをスローします)。
  • 必要に応じて、 getConfig()を介して集中構成 ( src/config.ts ) を使用します。
  • データベース接続などの依存関係には、 src/services/内のサービス初期化子を活用します。
  • 可視性のためにログ ( console.error ) を追加します。
-
security - not tested
F
license - not found
-
quality - not tested

PostgreSQL、DuckDB、Google Cloud Storage Parquet ファイルなどのデータベースと対話するためのツールを提供するモデル コンテキスト プロトコル サーバー。

  1. Prerequisites
    1. Project Structure
      1. Installation
        1. Configuration
          1. Environment Variables
        2. Database Migrations
          1. Running the Server
            1. Client Configuration
            2. Running with npx from GitHub
          2. Available Tools
            1. Available Resources
              1. Development: Integrating a New Tool/Resource
                1. Best Practices
              ID: sq86lal1oy