Doris MCP Server

by apache
Apache 2.0
2
  • Linux
  • Apple

Integrations

  • Uses .ENV files for flexible configuration of database connections, server settings, logging preferences, and other environment variables.

  • Provides tools for interacting with Apache Doris databases, enabling database metadata retrieval, SQL query execution, schema exploration, and audit log retrieval through a standardized Model Control Panel interface.

  • Implemented using FastAPI to provide both SSE and HTTP streaming endpoints for clients to interact with the MCP protocol, supporting tool calls and prompt interactions.

도리스 MCP 서버

Doris MCP(모델 제어판) 서버는 Python과 FastAPI로 구축된 백엔드 서비스입니다. MCP(모델 제어판) 프로토콜을 구현하여 클라이언트가 정의된 "도구"를 통해 상호 작용할 수 있도록 합니다. 주로 Apache Doris 데이터베이스에 연결하도록 설계되었으며, 자연어 쿼리를 SQL(NL2SQL)로 변환하고, 쿼리를 실행하고, 메타데이터 관리 및 분석을 수행하는 등의 작업에 대용량 언어 모델(LLM)을 활용할 수 있습니다.

핵심 기능

  • MCP 프로토콜 구현 : 표준 MCP 인터페이스를 제공하여 도구 호출, 리소스 관리, 즉각적인 상호 작용을 지원합니다.
  • 다양한 통신 모드 :
    • SSE(서버에서 보낸 이벤트) : /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 ).

시스템 요구 사항

  • 파이썬 3.12+
  • 데이터베이스 연결 세부 정보(예: Doris 호스트, 포트, 사용자, 비밀번호, 데이터베이스)

빠른 시작

1. 저장소 복제

지엑스피1

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 (문자열, 선택 사항, 기본값은 현재 db)✅ 활동적
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_querySQL 쿼리를 실행하고 결과 명령을 반환합니다.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

이 명령은 기본적으로 SSE와 Streamable HTTP MCP 서비스를 모두 제공하는 FastAPI 애플리케이션을 시작합니다.

서비스 엔드포인트:

  • 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_namearguments 지정하여 tool_call 메시지/요청을 보냅니다.
    • 예: 테이블 스키마 가져오기
      • tool_name : mcp_doris_get_table_schema (또는 모드별 이름)
      • arguments : random_string , table_name , db_name 포함합니다.
  4. 핸들 응답 :
    • 비스트리밍 : 클라이언트가 resulterror 포함하는 응답을 받습니다.
    • 스트리밍 : 클라이언트는 일련의 tools/progress 알림을 받은 후 resulterror 포함된 최종 응답을 받습니다.

특정 도구 이름과 매개변수는 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 구성: 프로젝트 디렉토리 내의 .env 파일에 데이터베이스 자격 증명과 기타 필요한 설정(기본값인 3000을 사용하지 않는 경우 SERVER_PORT 등)이 올바르게 구성되어 있는지 확인하세요.
  2. 서버 시작: 프로젝트의 루트 디렉토리에 있는 터미널에서 서버를 실행합니다.
    ./start_server.sh
    이 스크립트는 일반적으로 .env 파일을 읽고 FastAPI 서버를 SSE 모드로 시작합니다(자세한 내용은 스크립트와 sse_server.py / main.py 확인하세요). 서버가 수신 대기하는 호스트와 포트를 기록해 두세요(기본값은 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

새로운 도구 개발

이 섹션에서는 현재 프로젝트 구조를 고려하여 Doris MCP 서버에 새로운 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 함수) : 보안 검사(선택 사항, ENABLE_SQL_SECURITY_CHECK 환경 변수로 제어됨) db.execute_query 포함하고, SELECT 쿼리에 자동 LIMIT 추가하고, 결과 직렬화(날짜, 소수)를 처리하고, 출력을 표준 MCP 성공/오류 구조로 포맷하는 db.execute_query 래퍼를 제공합니다. 사용자가 제공하거나 생성된 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 모드를 별도로 처리하기 때문에 도구를 두 곳에 등록해야 합니다.

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. Stdio 등록( mcp_core.py )

  • SSE와 비슷하게 @stdio_mcp.tool() 로 장식된 새로운 래퍼 함수를 추가합니다.
  • 중요: 래퍼 함수 내부로 핵심 도구 함수( mcp_doris_get_server_time )를 가져옵니다(이 파일에서는 지연된 가져오기 패턴을 사용했습니다).
  • 래퍼는 핵심 도구 함수를 호출합니다. 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 서버를 다시 시작합니다(두 SSE 모드 모두 ./start_server.sh 를 통해, 필요한 경우 Cursor에서 사용하는 Stdio 명령이 업데이트되었는지 확인합니다). 그리고 두 연결 모드에서 MCP 클라이언트(예: Cursor)를 사용하여 새 도구를 테스트합니다.

기여하다

이슈나 풀 리퀘스트를 통한 기여를 환영합니다.

특허

이 프로젝트는 Apache 2.0 라이선스에 따라 라이선스가 부여됩니다. 자세한 내용은 LICENSE 파일(있는 경우)을 참조하세요.

You must be authenticated.

A
security – no known vulnerabilities
A
license - permissive license
A
quality - confirmed to work

Apache Doris 데이터베이스에 연결하는 모델 제어판 프로토콜을 구현하는 백엔드 서비스로, 이를 통해 사용자는 SQL 쿼리를 실행하고, 메타데이터를 관리하고, 자연어를 SQL로 변환하는 등의 작업에 LLM을 활용할 수 있습니다.

  1. 핵심 기능
    1. 시스템 요구 사항
      1. 빠른 시작
        1. 1. 저장소 복제
        2. 2. 종속성 설치
        3. 3. 환경 변수 구성
        4. 사용 가능한 MCP 도구
        5. 4. 서비스 실행
      2. 용법
        1. 커서로 연결하기
          1. 표준 모드
          2. SSE 모드
        2. 디렉토리 구조
          1. 새로운 도구 개발
            1. 1. 유틸리티 모듈 활용
            2. 2. 도구 논리 구현
            3. 3. 도구 등록(이중 등록)
            4. 4. 재시작 및 테스트
          2. 기여하다
            1. 특허

              Related MCP Servers

              • -
                security
                A
                license
                -
                quality
                A Model Context Protocol server that provides access to BigQuery. This server enables LLMs to inspect database schemas and execute queries.
                Last updated -
                63
                Python
                MIT License
                • Apple
              • A
                security
                A
                license
                A
                quality
                A Model Context Protocol server that enables LLMs to interact with Salesforce data through SOQL queries, SOSL searches, and various API operations including record management.
                Last updated -
                10
                53
                Python
                MIT License
              • -
                security
                F
                license
                -
                quality
                A Model Context Protocol server providing both read and write access to PostgreSQL databases, enabling LLMs to query data, modify records, and manage database schemas.
                Last updated -
                4
                JavaScript
              • -
                security
                F
                license
                -
                quality
                A server implementing Model Context Protocol that enables LLMs to interact with the ZenML platform, providing access to pipeline data, stack information, and the ability to trigger new pipeline runs.
                Last updated -
                13
                Python

              View all related MCP servers

              ID: el1kbjxehg