Skip to main content
Glama
Doris MCP Server

Doris MCP Server

Official
by apache

ドリスMCPサーバー

Doris MCP(モデルコントロールパネル)サーバーは、PythonとFastAPIで構築されたバックエンドサービスです。MCP(モデルコントロールパネル)プロトコルを実装しており、クライアントは定義された「ツール」を介してDorisサーバーと対話できます。主にApache Dorisデータベースへの接続を目的として設計されており、大規模言語モデル(LLM)を活用して、自然言語クエリをSQL(NL2SQL)に変換したり、クエリを実行したり、メタデータの管理と分析を行ったりといったタスクを実行できます。

コア機能

  • MCP プロトコル実装: 標準の MCP インターフェイスを提供し、ツール呼び出し、リソース管理、プロンプト対話をサポートします。

  • 複数の通信モード:

    • SSE (Server-Sent Events) : /sse (初期化) および/mcp/messages (通信) エンドポイント ( src/sse_server.py ) を介して提供されます。

    • ストリーミング可能な HTTP : 統合された/mcpエンドポイントを介して提供され、リクエスト/レスポンスとストリーミングをサポートします ( src/streamable_server.py )。

    • (オプション) Stdio : 標準入出力 ( src/stdio_server.py ) を介して対話が可能で、特定の起動構成が必要です。

  • ツールベースのインターフェース:コア機能はMCPツールとしてカプセル化されており、クライアントは必要に応じてツールを呼び出すことができます。現在利用可能な主要なツールは、データベースとの直接的なやり取りに重点を置いています。

    • SQL 実行 ( mcp_doris_exec_query )

    • データベースとテーブルの一覧表示 ( mcp_doris_get_db_list 、 mcp_doris_get_db_table_list )

    • メタデータの取得 ( mcp_doris_get_table_schema 、 mcp_doris_get_table_comment 、 mcp_doris_get_table_column_comments 、 mcp_doris_get_table_indexes )

    • 監査ログの取得 ( mcp_doris_get_recent_audit_logs )注: 現在のツールは主に直接的な DB 操作に重点を置いています。

  • データベースインタラクション: Apache Doris (またはその他の互換性のあるデータベース) に接続し、クエリを実行する機能を提供します ( src/utils/db.py )。

  • 柔軟な構成: .envファイルを介して構成され、データベース接続、LLM プロバイダー/モデル、API キー、ログ レベルなどの設定をサポートします。

  • メタデータ抽出: データベースのメタデータ情報を抽出できます ( src/utils/schema_extractor.py )。

Related MCP server: StarRocks MCP Server

システム要件

  • Python 3.12以上

  • データベース接続の詳細(例:Doris ホスト、ポート、ユーザー、パスワード、データベース)

クイックスタート

1. リポジトリのクローンを作成する

# Replace with the actual repository URL if different
git clone https://github.com/apache/doris-mcp-server.git
cd doris-mcp-server

2. 依存関係をインストールする

pip install -r requirements.txt

3. 環境変数を設定する

.env.exampleファイルを.envにコピーし、環境に応じて設定を変更します。

cp env.example .env

主要な環境変数:

  • データベース接続:

    • DB_HOST : データベースのホスト名

    • DB_PORT : データベースポート(デフォルトは9030)

    • DB_USER : データベースユーザー名

    • DB_PASSWORD : データベースパスワード

    • DB_DATABASE : デフォルトのデータベース名

  • サーバー構成:

    • SERVER_HOST : サーバーがリッスンするホストアドレス(デフォルト0.0.0.0 )

    • SERVER_PORT : サーバーがリッスンするポート (デフォルト3000 )

    • ALLOWED_ORIGINS : CORS で許可されたオリジン(カンマ区切り、 *はすべて許可)

    • MCP_ALLOW_CREDENTIALS : CORS 資格情報を許可するかどうか (デフォルトはfalse )

  • ログ構成:

    • LOG_DIR : ログファイルのディレクトリ(デフォルトは./logs )

    • LOG_LEVEL : ログレベル (例: INFO 、 DEBUG 、 WARNING 、 ERROR 、デフォルトはINFO )

    • CONSOLE_LOGGING : コンソールにログを出力するかどうか(デフォルトはfalse )

利用可能なMCPツール

次の表は、MCP クライアント経由で呼び出すことができる主なツールを現在示しています。

ツール名

説明

パラメータ

状態

mcp_doris_get_db_list

サーバー上のすべてのデータベース名のリストを取得します。

random_string (文字列、必須)

✅ アクティブ

mcp_doris_get_db_table_list

指定されたデータベース内のすべてのテーブル名のリストを取得します。

random_string (文字列、必須)、 db_name (文字列、オプション、デフォルトは現在のデータベース)

✅ アクティブ

mcp_doris_get_table_schema

指定されたテーブルの詳細な構造を取得します。

random_string (文字列、必須)、 table_name (文字列、必須)、 db_name (文字列、オプション)

✅ アクティブ

mcp_doris_get_table_comment

指定されたテーブルのコメントを取得します。

random_string (文字列、必須)、 table_name (文字列、必須)、 db_name (文字列、オプション)

✅ アクティブ

mcp_doris_get_table_column_comments

指定されたテーブル内のすべての列のコメントを取得します。

random_string (文字列、必須)、 table_name (文字列、必須)、 db_name (文字列、オプション)

✅ アクティブ

mcp_doris_get_table_indexes

指定されたテーブルのインデックス情報を取得します。

random_string (文字列、必須)、 table_name (文字列、必須)、 db_name (文字列、オプション)

✅ アクティブ

mcp_doris_exec_query

SQL クエリを実行し、結果コマンドを返します。

random_string (文字列、必須)、 sql (文字列、必須)、 db_name (文字列、オプション)、 max_rows (整数、オプション、デフォルト 100)、 timeout (整数、オプション、デフォルト 30)

✅ アクティブ

mcp_doris_get_recent_audit_logs

最近の期間の監査ログ レコードを取得します。

random_string (文字列、必須)、 days (整数、オプション、デフォルト7)、 limit (整数、オプション、デフォルト100)

✅ アクティブ

**注:**すべてのツールは、呼び出し識別子としてrandom_stringパラメータを必要とします。これは通常、MCPクライアントによって自動的に処理されます。「オプション」および「必須」はツールの内部ロジックを参照します。クライアントは、実装によってはすべてのパラメータの値を指定する必要がある場合があります。ここに記載されたツール名は基本名です。接続モードによっては、クライアントにはプレフィックス(例: mcp_doris_stdio3_get_db_list )が付加されて表示されることがあります。

4. サービスを実行する

SSE モードを使用する場合は、次のコマンドを実行します。

./start_server.sh

このコマンドは、FastAPI アプリケーションを起動し、デフォルトで SSE と Streamable HTTP MCP サービスの両方を提供します。

サービスエンドポイント:

  • SSE 初期化: http://<host>:<port>/sse

  • SSE通信: http://<host>:<port>/mcp/messages (POST)

  • ストリーミング可能な HTTP : http://<host>:<port>/mcp (GET、POST、DELETE、OPTIONS をサポート)

  • ヘルスチェック: http://<host>:<port>/health

  • (潜在的) ステータス チェック: http://<host>:<port>/status ( main.pyに実装されているかどうかを確認)

使用法

Doris MCPサーバーとのやり取りには、 MCPクライアントが必要です。クライアントはサーバーのSSEまたはStreamable HTTPエンドポイントに接続し、MCP仕様に従ってリクエスト( tool_callなど)を送信してサーバーのツールを呼び出します。

主なインタラクションフロー:

  1. クライアントの初期化: /sse (SSE) に接続するか、 /mcp (Streamable) にinitializeメソッド呼び出しを送信します。

  2. (オプション) ツールの検出: クライアントはmcp/listToolsまたはmcp/listOfferingsを呼び出して、サポートされているツールのリスト、その説明、およびパラメーター スキーマを取得できます。

  3. ツールの呼び出し: クライアントは、 tool_nameとargumentsを指定して、 tool_callメッセージ/要求を送信します。

    • 例: テーブルスキーマの取得

      • tool_name : mcp_doris_get_table_schema (またはモード固有の名前)

      • arguments : random_string 、 table_name 、 db_nameを含めます。

  4. ハンドル応答:

    • 非ストリーミング: クライアントはresultまたはerrorを含む応答を受信します。

    • ストリーミング: クライアントは一連のtools/progress通知を受信し、その後にresultまたはerrorを含む最終応答を受信します。

特定のツール名とパラメータはsrc/tools/コードから参照するか、MCP 検出メカニズムを介して取得する必要があります。

カーソルで接続する

Stdio モードまたは SSE モードのいずれかを使用して、Cursor をこの MCP サーバーに接続できます。

標準モード

stdioモードでは、Cursorがサーバープロセスを直接管理できます。設定はCursorのMCPサーバー設定ファイル(通常は~/.cursor/mcp.jsonなど)内で行います。

stdio モードを使用する場合は、次のコマンドを実行して環境依存パッケージをダウンロードしてビルドしてください。ただし、プロジェクト パスを正しいパス アドレスに変更する必要があることに注意してください。

uv --project /your/path/doris-mcp-server run doris-mcp
  1. **カーソルの構成:**カーソル MCP 構成に次のようなエントリを追加します。

    {
      "mcpServers": {
        "doris-stdio": {
          "command": "uv",
          "args": ["--project", "/path/to/your/doris-mcp-server", "run", "doris-mcp"],
          "env": {
            "DB_HOST": "127.0.0.1",
            "DB_PORT": "9030",
            "DB_USER": "root",
            "DB_PASSWORD": "your_db_password",
            "DB_DATABASE": "your_default_db" 
          }
        },
        // ... other server configurations ...
      }
    }
  2. 要点:

    • /path/to/your/doris-mcpを、システム上のプロジェクトのルートディレクトリへの実際の絶対パスに置き換えてください。-- --project引数は、 uv``pyproject.toml見つけて正しいコマンドを実行するために不可欠です。

    • command``uvに設定されています( uv.lockで示されているように、パッケージ管理にuvを使用していると仮定します)。 args``--project 、パス、 run 、 mcp-doris ( pyproject.tomlで定義されたスクリプトに対応するもの)が含まれます。

    • データベース接続の詳細( DB_HOST 、 DB_PORT 、 DB_USER 、 DB_PASSWORD 、 DB_DATABASE )は、設定ファイル内のenvブロックに直接設定されます。Cursor はこれらの情報をサーバープロセスに渡します。Cursor 経由で設定する場合、このモードでは.envファイルは必要ありません。

SSEモード

SSE モードでは、最初に MCP サーバーを独立して実行し、次に Cursor に接続する方法を指示する必要があります。

  1. **.envを構成する:**データベースの資格情報とその他の必要な設定 (デフォルトの 3000 を使用していない場合はSERVER_PORTなど) が、プロジェクト ディレクトリ内の.envファイルで正しく構成されていることを確認します。

  2. **サーバーを起動する:**プロジェクトのルート ディレクトリでターミナルからサーバーを実行します。

    ./start_server.sh

    このスクリプトは通常、 .envファイルを読み取り、FastAPI サーバーを SSE モードで起動します(詳細はスクリプトとsse_server.py / main.py参照してください)。サーバーが listen しているホストとポート番号に注意してください(デフォルトは0.0.0.0:3000です)。

  3. **カーソルを構成する:**実行中のサーバーの SSE エンドポイントを指す次のようなエントリをカーソル MCP 構成に追加します。

    {
      "mcpServers": {
        "doris-sse": {
           "url": "http://127.0.0.1:3000/sse" // Adjust host/port if your server runs elsewhere
        },
        // ... other server configurations ...
      }
    }

    注: この例ではデフォルトのポート3000使用しています。サーバーが別のポート(例の3010など)で動作するように設定されている場合は、URL を適宜調整してください。

Cursor でいずれかのモードを設定したら、サーバー (例: doris-stdioまたはdoris-sse ) を選択してそのツールを使用できるようになります。

ディレクトリ構造

doris-mcp-server/
├── doris_mcp_server/    # Source code for the MCP server
│   ├── main.py          # Main entry point, FastAPI app definition
│   ├── mcp_core.py      # Core MCP tool registration and Stdio handling
│   ├── sse_server.py    # SSE server implementation
│   ├── streamable_server.py # Streamable HTTP server implementation
│   ├── config.py        # Configuration loading
│   ├── tools/           # MCP tool definitions
│   │   ├── mcp_doris_tools.py # Main Doris-related MCP tools
│   │   ├── tool_initializer.py # Tool registration helper (used by mcp_core.py)
│   │   └── __init__.py
│   ├── utils/           # Utility classes and helper functions
│   │   ├── db.py              # Database connection and operations
│   │   ├── logger.py          # Logging configuration
│   │   ├── schema_extractor.py # Doris metadata/schema extraction logic
│   │   ├── sql_executor_tools.py # SQL execution helper (might be legacy)
│   │   └── __init__.py
│   └── __init__.py
├── logs/                # Log file directory (if file logging enabled)
├── README.md            # This file
├── .env.example         # Example environment variable file
├── requirements.txt     # Python dependencies for pip
├── pyproject.toml       # Project metadata and build system configuration (PEP 518)
├── uv.lock              # Lock file for 'uv' package manager (alternative to pip)
├── start_server.sh      # Script to start the server
└── restart_server.sh    # Script to restart the server

新しいツールの開発

このセクションでは、現在のプロジェクト構造を考慮して、新しい MCP ツールを Doris MCP サーバーに追加するプロセスの概要を説明します。

1. ユーティリティモジュールを活用する

新しいデータベース相互作用ロジックを最初から記述する前に、既存のユーティリティ モジュールを確認します。

  • doris_mcp_server/utils/db.py : データベース接続 ( get_db_connection ) を取得し、生のクエリ ( execute_query 、 execute_query_df ) を実行するための基本関数を提供します。

  • doris_mcp_server/utils/schema_extractor.py ( MetadataExtractorクラス) : データベース/テーブルの一覧表示 ( get_all_databases 、 get_database_tables )、テーブルスキーマ/コメント/インデックスの取得 ( get_table_schema 、 get_table_comment 、 get_column_comments 、 get_table_indexes )、監査ログへのアクセス ( get_recent_audit_logs ) など、データベースメタデータを取得するための高レベルメソッドを提供します。キャッシュメカニズムも備えています。

  • doris_mcp_server/utils/sql_executor_tools.py ( execute_sql_query関数) : db.execute_queryのラッパーを提供します。セキュリティチェック(オプション、 ENABLE_SQL_SECURITY_CHECK環境変数で制御)、SELECT クエリへの自動LIMITの追加、結果のシリアル化(日付、小数点)の処理、MCP 標準の成功/エラー構造への出力のフォーマットが含まれます。ユーザーが指定した SQL または生成された SQL を実行する場合は、このラッパーの使用をお勧めします。

これらのモジュールから機能をインポートして組み合わせ、新しいツールを構築できます。

2. ツールロジックを実装する

新しいツールのコアロジックを、 doris_mcp_server/tools/mcp_doris_tools.py内のasync関数として実装します。これにより、主要なツール実装を一元化できます。関数が返すデータは、標準的なMCPレスポンス構造に簡単にラップできる形式でなければなりません(同じファイル内の_format_response参照してください)。

**例:**シンプルなツールget_server_timeを作成しましょう。

# In doris_mcp_server/tools/mcp_doris_tools.py
import datetime
# ... other imports ...
from doris_mcp_server.tools.mcp_doris_tools import _format_response # Reuse formatter

# ... existing tools ...

async def mcp_doris_get_server_time() -> Dict[str, Any]:
    """Gets the current server time."""
    logger.info(f"MCP Tool Call: mcp_doris_get_server_time")
    try:
        current_time = datetime.datetime.now().isoformat()
        # Use the existing formatter for consistency
        return _format_response(success=True, result={"server_time": current_time})
    except Exception as e:
        logger.error(f"MCP tool execution failed mcp_doris_get_server_time: {str(e)}", exc_info=True)
        return _format_response(success=False, error=str(e), message="Error getting server time")

3. ツールを登録する(二重登録)

SSE/Streamable モードと Stdio モードを別々に処理するため、ツールを次の 2 つの場所に登録する必要があります。

A. SSE/Streamable 登録 ( tool_initializer.py )

  • mcp_doris_tools.pyから新しいツール関数をインポートします。

  • register_mcp_tools関数内に、 @mcp.tool()で装飾された新しいラッパー関数を追加します。

  • ラッパー関数はコア ツール関数を呼び出す必要があります。

  • ツール名を定義し、デコレータで詳細な説明(パラメータがある場合はそれも含む)を指定します。クライアントとの互換性を保つため、ラッパーで明示的に使用しない場合でも、必須のrandom_stringパラメータの説明を必ず含めてください。

例 ( tool_initializer.py ):

# In doris_mcp_server/tools/tool_initializer.py
# ... other imports ...
from doris_mcp_server.tools.mcp_doris_tools import (
    # ... existing tool imports ...
    mcp_doris_get_server_time # <-- Import the new tool
)

async def register_mcp_tools(mcp):
    # ... existing tool registrations ...

    # Register Tool: Get Server Time
    @mcp.tool("get_server_time", description="""[Function Description]: Get the current time of the MCP server.\n
[Parameter Content]:\n
- random_string (string) [Required] - Unique identifier for the tool call\n""")
    async def get_server_time_tool() -> Dict[str, Any]:
        """Wrapper: Get server time"""
        # Note: No parameters needed for the core function call here
        return await mcp_doris_get_server_time()

    # ... logging registration count ...

B. 標準入出力登録 ( mcp_core.py )

  • SSE と同様に、 @stdio_mcp.tool()で装飾された新しいラッパー関数を追加します。

  • **重要:**ラッパー関数内にコア ツール関数 ( mcp_doris_get_server_time ) をインポートします (このファイルで使用される遅延インポート パターン)。

  • ラッパーはコアツール関数を呼び出します。FastMCP FastMCP Stdioモードでツールを処理する方法によっては、ラッパー自体をasync defで記述する必要がある場合があります。これは、基盤となる関数が単純な場合(現在のファイル構造からわかるように)でも同様です。呼び出しが一致していることを確認してください(例えば、非同期関数を呼び出す場合はawaitを使用してください)。

例 ( mcp_core.py ):

# In doris_mcp_server/mcp_core.py
# ... other imports and setup ...

# ... existing Stdio tool registrations ...

# Register Tool: Get Server Time (for Stdio)
@stdio_mcp.tool("get_server_time", description="""[Function Description]: Get the current time of the MCP server.\n
[Parameter Content]:\n
- random_string (string) [Required] - Unique identifier for the tool call\n""")
async def get_server_time_tool_stdio() -> Dict[str, Any]: # Using a slightly different wrapper name for clarity if needed
    """Wrapper: Get server time (Stdio)"""
    from doris_mcp_server.tools.mcp_doris_tools import mcp_doris_get_server_time # <-- Delayed import
    # Assuming the Stdio runner handles async wrappers correctly
    return await mcp_doris_get_server_time()

# --- Register Tools --- (Or wherever the registrations are finalized)

4. 再起動してテストする

両方のファイルにツールを実装して登録した後、MCP サーバーを再起動し ( ./start_server.sh経由で両方の SSE モードを実行し、必要に応じて Cursor によって使用される Stdio コマンドが更新されていることを確認します)、両方の接続モードで MCP クライアント (Cursor など) を使用して新しいツールをテストします。

貢献

Issue または Pull Request 経由での貢献を歓迎します。

ライセンス

このプロジェクトはApache 2.0ライセンスに基づいてライセンスされています。詳細については、LICENSEファイル(存在する場合)を参照してください。

Available Tools

8 tools
exec_queryB

[Function Description]: Execute SQL query and return result command (executed by the client).

[Parameter Content]:

  • sql (string) [Required] - SQL statement to execute

  • db_name (string) [Optional] - Target database name, defaults to the current database

  • max_rows (integer) [Optional] - Maximum number of rows to return, default 100

  • timeout (integer) [Optional] - Query timeout in seconds, default 30

Inputs: sql (required), db_name, max_rows, timeout.

get_db_listC

[Function Description]: Get a list of all database names on the server.

[Parameter Content]:

  • random_string (string) [Required] - Unique identifier for the tool call

Inputs: no named parameters.

get_db_table_listB

[Function Description]: Get a list of all table names in the specified database.

[Parameter Content]:

  • db_name (string) [Optional] - Target database name, defaults to the current database

Inputs: db_name.

get_recent_audit_logsC

[Function Description]: Get audit log records for a recent period.

[Parameter Content]:

  • days (integer) [Optional] - Number of recent days of logs to retrieve, default is 7

  • limit (integer) [Optional] - Maximum number of records to return, default is 100

Inputs: days, limit.

get_table_column_commentsC

[Function Description]: Get comment information for all columns in the specified table.

[Parameter Content]:

  • table_name (string) [Required] - Name of the table to query

  • db_name (string) [Optional] - Target database name, defaults to the current database

Inputs: table_name (required), db_name.

get_table_commentC

[Function Description]: Get the comment information for the specified table.

[Parameter Content]:

  • table_name (string) [Required] - Name of the table to query

  • db_name (string) [Optional] - Target database name, defaults to the current database

Inputs: table_name (required), db_name.

get_table_indexesB

[Function Description]: Get index information for the specified table. [Parameter Content]:

  • table_name (string) [Required] - Name of the table to query

  • db_name (string) [Optional] - Target database name, defaults to the current database

Inputs: table_name (required), db_name.

get_table_schemaB

[Function Description]: Get detailed structure information of the specified table (columns, types, comments, etc.).

[Parameter Content]:

  • table_name (string) [Required] - Name of the table to query

  • db_name (string) [Optional] - Target database name, defaults to the current database

Inputs: table_name (required), db_name.

Tool Schema Changelog

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

Loading tool schema changelog…

    TDQS

    A3.5/5.0

    Scored across 8 tools

    Disambiguation5/5

    Each tool has a clearly distinct purpose with no ambiguity. exec_query handles SQL execution, get_db_list retrieves database names, get_db_table_list lists tables, get_recent_audit_logs fetches logs, and the remaining tools (get_table_column_comments, get_table_comment, get_table_indexes, get_table_schema) each target specific table metadata aspects without overlap.

    Naming Consistency5/5

    All tools follow a consistent verb_noun pattern using snake_case. The naming is highly predictable: exec_query, get_db_list, get_db_table_list, get_recent_audit_logs, get_table_column_comments, get_table_comment, get_table_indexes, and get_table_schema all adhere to the same convention.

    Tool Count5/5

    With 8 tools, this server is well-scoped for database interaction and metadata exploration. Each tool earns its place by covering distinct aspects like query execution, database/table listing, audit logs, and detailed table metadata, without being overly sparse or bloated.

    Completeness4/5

    The toolset provides strong coverage for querying and inspecting databases, including CRUD-like operations via exec_query and comprehensive metadata retrieval. Minor gaps exist, such as no explicit tools for creating/dropping databases or tables, but agents can work around this using exec_query for such operations.

    Maintenance

    ActivityMaintained
    ResponsivenessOutdated data

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      D
      maintenance
      This MCP server provides connection to Starrocks allows you to explore this query engine with minimum effort.
      1
      MIT
    • F
      license
      Not graded
      quality
      Not graded
      maintenance
      A TypeScript implementation of a Model Context Protocol server that enables interaction with StarRocks databases, supporting SQL operations like queries, table creation, and data manipulation through standardized MCP tools.
      1
      -
    • A
      license
      Not graded
      quality
      D
      maintenance
      Enables LLMs to explore database schemas, execute read-only SQL queries, and perform data analysis on Apache Doris or MySQL-compatible databases through a standardized MCP interface with built-in analytical prompts.
      1
      MIT
    • A
      license
      Not graded
      quality
      D
      maintenance
      Enables natural language querying of Apache Doris databases via LLM-powered SQL generation, execution, and metadata management through the MCP protocol.
      9
      Apache 2.0

    Appeared in Searches