> ## Documentation Index
> Fetch the complete documentation index at: https://private-7c7dfe99-mintlify-fbfa8bee.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# mcp-agent와 ClickHouse MCP 서버로 AI 에이전트를 구축하는 방법

> mcp-agent와 ClickHouse MCP 서버로 AI 에이전트를 구축하는 방법을 알아보세요

이 가이드에서는 [mcp-agent](https://github.com/lastmile-ai/mcp-agent)를 사용해 [ClickHouse SQL Playground](https://sql.clickhouse.com/)와 상호작용할 수 있는 AI 에이전트를 [ClickHouse MCP 서버](https://github.com/ClickHouse/mcp-clickhouse)로 구축하는 방법을 알아봅니다.

<Info>
  **예시 노트북**

  이 예시는 [examples 리포지토리](https://github.com/ClickHouse/examples/blob/main/ai/mcp/mcp-agent/mcp-agent.ipynb)의 노트북으로도 확인할 수 있습니다.
</Info>

<div id="prerequisites">
  ## 사전 준비 사항
</div>

* 시스템에 Python이 설치되어 있어야 합니다.
* 시스템에 `pip`가 설치되어 있어야 합니다.
* OpenAI API Key가 필요합니다.

다음 단계는 Python REPL 또는 스크립트에서 실행할 수 있습니다.

<Steps>
  <Step>
    ## 라이브러리 설치

    다음 명령을 실행해 mcp-agent 라이브러리를 설치합니다:

    ```python theme={null}
    pip install -q --upgrade pip
    pip install -q mcp-agent openai
    pip install -q ipywidgets
    ```
  </Step>

  <Step>
    ## 자격 증명 설정

    다음으로, OpenAI API Key를 입력해야 합니다:

    ```python theme={null}
    import os, getpass
    os.environ["OPENAI_API_KEY"] = getpass.getpass("Enter OpenAI API Key:")
    ```

    ```response title="Response" theme={null}
    Enter OpenAI API Key: ········
    ```

    다음으로 ClickHouse SQL Playground에 연결하는 데 필요한 자격 증명을 설정합니다:

    ```python theme={null}
    env = {
        "CLICKHOUSE_HOST": "sql-clickhouse.clickhouse.com",
        "CLICKHOUSE_PORT": "8443",
        "CLICKHOUSE_USER": "demo",
        "CLICKHOUSE_PASSWORD": "",
        "CLICKHOUSE_SECURE": "true"
    }
    ```
  </Step>

  <Step>
    ## MCP Server 및 mcp-agent 에이전트 초기화

    이제 ClickHouse MCP 서버가 ClickHouse SQL 플레이그라운드를 가리키도록 구성하고, 에이전트를 초기화한 다음 질문을 입력합니다:

    ```python theme={null}
    from mcp_agent.app import MCPApp
    from mcp_agent.agents.agent import Agent
    from mcp_agent.workflows.llm.augmented_llm_openai import OpenAIAugmentedLLM
    from mcp_agent.config import Settings, MCPSettings, MCPServerSettings, OpenAISettings
    ```

    ```python theme={null}
    settings = Settings(
        execution_engine="asyncio",
        openai=OpenAISettings(
            default_model="gpt-5-mini-2025-08-07",
        ),
        mcp=MCPSettings(
            servers={
                "clickhouse": MCPServerSettings(
                    command='uv',
                    args=[
                        "run",
                        "--with", "mcp-clickhouse",
                        "--python", "3.10",
                        "mcp-clickhouse"
                    ],
                    env=env
                ),
            }
        ),
    )

    app = MCPApp(name="mcp_basic_agent", settings=settings)

    async with app.run() as mcp_agent_app:
        logger = mcp_agent_app.logger
        data_agent = Agent(
            name="database-anayst",
            instruction="""You can answer questions with help from a ClickHouse database.""",
            server_names=["clickhouse"],
        )

        async with data_agent:
            llm = await data_agent.attach_llm(OpenAIAugmentedLLM)
            result = await llm.generate_str(
                message="Tell me about UK property prices in 2025. Use ClickHouse to work it out."
            )
            
            logger.info(result)
    ```

    ```response title="Response" theme={null}
    [10/10/25 11:26:20] INFO     Starting MCP server 'mcp-clickhouse' with transport 'stdio'                                      server.py:1502
    2025-10-10 11:26:20,183 - mcp.server.lowlevel.server - INFO - Processing request of type ListToolsRequest
    2025-10-10 11:26:20,184 - mcp.server.lowlevel.server - INFO - Processing request of type ListPromptsRequest
    2025-10-10 11:26:20,185 - mcp.server.lowlevel.server - INFO - Processing request of type ListResourcesRequest
    [INFO] 2025-10-10T11:26:20 mcp_agent.workflows.llm.augmented_llm_openai.database-anayst - Using reasoning model 'gpt-5-mini-2025-08-07' with
    'medium' reasoning effort
    [INFO] 2025-10-10T11:26:23 mcp_agent.mcp.mcp_aggregator.database-anayst - Requesting tool call
    {
      "data": {
        "progress_action": "Calling Tool",
        "tool_name": "list_databases",
        "server_name": "clickhouse",
        "agent_name": "database-anayst"
      }
    }
    2025-10-10 11:26:23,477 - mcp.server.lowlevel.server - INFO - Processing request of type CallToolRequest
    2025-10-10 11:26:23,479 - mcp-clickhouse - INFO - Listing all databases
    2025-10-10 11:26:23,479 - mcp-clickhouse - INFO - Creating ClickHouse client connection to sql-clickhouse.clickhouse.com:8443 as demo (secure=True, verify=True, connect_timeout=30s, send_receive_timeout=30s)
    2025-10-10 11:26:24,375 - mcp-clickhouse - INFO - Successfully connected to ClickHouse server version 25.8.1.8344
    2025-10-10 11:26:24,551 - mcp-clickhouse - INFO - Found 38 databases
    [INFO] 2025-10-10T11:26:26 mcp_agent.mcp.mcp_aggregator.database-anayst - Requesting tool call
    {
      "data": {
        "progress_action": "Calling Tool",
        "tool_name": "list_tables",
        "server_name": "clickhouse",
        "agent_name": "database-anayst"
      }
    }
    2025-10-10 11:26:26,825 - mcp.server.lowlevel.server - INFO - Processing request of type CallToolRequest
    2025-10-10 11:26:26,832 - mcp-clickhouse - INFO - Listing tables in database 'uk'
    2025-10-10 11:26:26,832 - mcp-clickhouse - INFO - Creating ClickHouse client connection to sql-clickhouse.clickhouse.com:8443 as demo (secure=True, verify=True, connect_timeout=30s, send_receive_timeout=30s)
    2025-10-10 11:26:27,311 - mcp-clickhouse - INFO - Successfully connected to ClickHouse server version 25.8.1.8344
    2025-10-10 11:26:28,738 - mcp-clickhouse - INFO - Found 9 tables
    [INFO] 2025-10-10T11:26:48 mcp_agent.mcp.mcp_aggregator.database-anayst - Requesting tool call
    {
      "data": {
        "progress_action": "Calling Tool",
        "tool_name": "run_select_query",
        "server_name": "clickhouse",
        "agent_name": "database-anayst"
      }
    }
    [INFO] 2025-10-10T11:26:48 mcp_agent.mcp.mcp_aggregator.database-anayst - Requesting tool call
    {
      "data": {
        "progress_action": "Calling Tool",
        "tool_name": "run_select_query",
        "server_name": "clickhouse",
        "agent_name": "database-anayst"
      }
    }
    [INFO] 2025-10-10T11:26:48 mcp_agent.mcp.mcp_aggregator.database-anayst - Requesting tool call
    {
      "data": {
        "progress_action": "Calling Tool",
        "tool_name": "run_select_query",
        "server_name": "clickhouse",
        "agent_name": "database-anayst"
      }
    }
    [INFO] 2025-10-10T11:26:48 mcp_agent.mcp.mcp_aggregator.database-anayst - Requesting tool call
    {
      "data": {
        "progress_action": "Calling Tool",
        "tool_name": "run_select_query",
        "server_name": "clickhouse",
        "agent_name": "database-anayst"
      }
    }
    [INFO] 2025-10-10T11:26:48 mcp_agent.mcp.mcp_aggregator.database-anayst - Requesting tool call
    {
      "data": {
        "progress_action": "Calling Tool",
        "tool_name": "run_select_query",
        "server_name": "clickhouse",
        "agent_name": "database-anayst"
      }
    }
    2025-10-10 11:26:48,366 - mcp.server.lowlevel.server - INFO - Processing request of type CallToolRequest
    2025-10-10 11:26:48,367 - mcp-clickhouse - INFO - Executing SELECT query: SELECT
    count(*) AS transactions,
    avg(price) AS avg_price,
    quantileExact(0.5)(price) AS median_price,
    min(price) AS min_price,
    max(price) AS max_price
    FROM uk.uk_price_paid_simple_partitioned
    WHERE toYear(date)=2025
    2025-10-10 11:26:48,367 - mcp-clickhouse - INFO - Creating ClickHouse client connection to sql-clickhouse.clickhouse.com:8443 as demo (secure=True, verify=True, connect_timeout=30s, send_receive_timeout=30s)
    2025-10-10 11:26:49,262 - mcp-clickhouse - INFO - Successfully connected to ClickHouse server version 25.8.1.8344
    2025-10-10 11:26:49,407 - mcp-clickhouse - INFO - Query returned 1 rows
    2025-10-10 11:26:49,408 - mcp.server.lowlevel.server - INFO - Processing request of type CallToolRequest
    2025-10-10 11:26:49,408 - mcp-clickhouse - INFO - Executing SELECT query: SELECT toMonth(date) AS month, count(*) AS transactions, avg(price) AS avg_price, quantileExact(0.5)(price) AS median_price
    FROM uk.uk_price_paid_simple_partitioned
    WHERE toYear(date)=2025
    GROUP BY month
    ORDER BY month
    2025-10-10 11:26:49,408 - mcp-clickhouse - INFO - Creating ClickHouse client connection to sql-clickhouse.clickhouse.com:8443 as demo (secure=True, verify=True, connect_timeout=30s, send_receive_timeout=30s)
    2025-10-10 11:26:49,857 - mcp-clickhouse - INFO - Successfully connected to ClickHouse server version 25.8.1.8344
    2025-10-10 11:26:50,067 - mcp-clickhouse - INFO - Query returned 8 rows
    2025-10-10 11:26:50,068 - mcp.server.lowlevel.server - INFO - Processing request of type CallToolRequest
    2025-10-10 11:26:50,069 - mcp-clickhouse - INFO - Executing SELECT query: SELECT town, count(*) AS transactions, avg(price) AS avg_price
    FROM uk.uk_price_paid_simple_partitioned
    WHERE toYear(date)=2025
    GROUP BY town
    HAVING transactions >= 50
    ORDER BY avg_price DESC
    LIMIT 10
    2025-10-10 11:26:50,069 - mcp-clickhouse - INFO - Creating ClickHouse client connection to sql-clickhouse.clickhouse.com:8443 as demo (secure=True, verify=True, connect_timeout=30s, send_receive_timeout=30s)
    2025-10-10 11:26:50,594 - mcp-clickhouse - INFO - Successfully connected to ClickHouse server version 25.8.1.8344
    2025-10-10 11:26:50,741 - mcp-clickhouse - INFO - Query returned 10 rows
    2025-10-10 11:26:50,744 - mcp.server.lowlevel.server - INFO - Processing request of type CallToolRequest
    2025-10-10 11:26:50,746 - mcp-clickhouse - INFO - Executing SELECT query: SELECT toYear(date) AS year, count(*) AS transactions, avg(price) AS avg_price, quantileExact(0.5)(price) AS median_price
    FROM uk.uk_price_paid_simple_partitioned
    WHERE toYear(date) IN (2024,2025)
    GROUP BY year
    ORDER BY year
    2025-10-10 11:26:50,747 - mcp-clickhouse - INFO - Creating ClickHouse client connection to sql-clickhouse.clickhouse.com:8443 as demo (secure=True, verify=True, connect_timeout=30s, send_receive_timeout=30s)
    2025-10-10 11:26:51,256 - mcp-clickhouse - INFO - Successfully connected to ClickHouse server version 25.8.1.8344
    2025-10-10 11:26:51,447 - mcp-clickhouse - INFO - Query returned 2 rows
    2025-10-10 11:26:51,449 - mcp.server.lowlevel.server - INFO - Processing request of type CallToolRequest
    2025-10-10 11:26:51,452 - mcp-clickhouse - INFO - Executing SELECT query: SELECT type, count(*) AS transactions, avg(price) AS avg_price, quantileExact(0.5)(price) AS median_price
    FROM uk.uk_price_paid
    WHERE toYear(date)=2025
    GROUP BY type
    ORDER BY avg_price DESC
    2025-10-10 11:26:51,452 - mcp-clickhouse - INFO - Creating ClickHouse client connection to sql-clickhouse.clickhouse.com:8443 as demo (secure=True, verify=True, connect_timeout=30s, send_receive_timeout=30s)
    2025-10-10 11:26:51,952 - mcp-clickhouse - INFO - Successfully connected to ClickHouse server version 25.8.1.8344
    2025-10-10 11:26:52,166 - mcp-clickhouse - INFO - Query returned 5 rows
    [INFO] 2025-10-10T11:27:51 mcp_agent.mcp_basic_agent - Summary (TL;DR)
    - Based on the UK Price Paid tables in ClickHouse, for transactions recorded in 2025 so far there are 376,633 sales with an average price of
    £362,283 and a median price of £281,000. The data appears to include only months Jan–Aug 2025 (so 2025 is incomplete). There are extreme
    outliers (min £100, max £127,700,000) that skew the mean.

    계산한 내용 (방법)
    ClickHouse의 uk.price-paid 테이블에서 집계를 실행했습니다:
    - uk.uk_price_paid_simple_partitioned에서 2025년 전체 요약 (건수, 평균, 중앙값, 최솟값, 최댓값)
    - 2025년 월별 분석 (거래 건수, 평균, 중앙값)
    - 2025년 평균 가격 기준 상위 도시 (거래 건수 >= 50인 도시)
    - 연도 비교: 2024년 vs 2025년 (건수, 평균, 중앙값)
    - uk.uk_price_paid를 사용한 2025년 부동산 유형별 분석 (건수, 평균, 중앙값)

    주요 수치 (데이터셋 기준)
    - 2025년 전체 (기록된 거래): 거래 건수 = 376,633; 평균 가격 = £362,282.66; 중앙값 = £281,000; 최솟값 = £100; 최댓값 =
    £127,700,000.
    - 월별 (2025년): (월, 거래 건수, 평균 가격, 중앙값)
      - 1월: 53,927건, 평균 £386,053, 중앙값 £285,000
      - 2월: 58,740건, 평균 £371,803, 중앙값 £285,000
      - 3월: 95,274건, 평균 £377,200, 중앙값 £315,000
      - 4월: 24,987건, 평균 £331,692, 중앙값 £235,000
      - 5월: 39,013건, 평균 £342,380, 중앙값 £255,000
      - 6월: 41,446건, 평균 £334,667, 중앙값 £268,500
      - 7월: 44,431건, 평균 £348,293, 중앙값 £277,500
      - 8월: 18,815건, 평균 £364,653, 중앙값 £292,999
      (데이터셋에는 1~8월 데이터만 포함되어 있습니다.)
    - 평균 가격 기준 상위 도시 (2025년, 거래 건수 ≥50인 도시)
      - TRING: 126건, 평균 £1,973,274
      - BUCKHURST HILL: 98건, 평균 £1,441,331
      - ASCOT: 175건, 평균 £1,300,748
      - RADLETT: 69건, 평균 £1,160,217
      - COBHAM: 115건, 평균 £1,035,192
      - EAST MOLESEY, BEACONSFIELD, ESHER, CHALFONT ST GILES, THAMES DITTON도 상위 10위에 포함됩니다 (모두 평균 가격이 높은 통근자/부유층 도시).
    - 연도 비교 (기록 기준 2024년 vs 2025년)
      - 2024년: 859,960건, 평균 £390,879, 중앙값 £280,000
      - 2025년: 376,633건, 평균 £362,283, 중앙값 £281,000
      (2025년 건수가 훨씬 적은 이유는 데이터셋이 연도의 일부만 포함하기 때문입니다.)
    - 부동산 유형별 (2025년)
      - 단독주택(detached): 85,362건, 평균 £495,714, 중앙값 £415,000
      - 반단독주택(semi-detached): 107,580건, 평균 £319,922, 중앙값 £270,000
      - 아파트(flat): 62,975건, 평균 £298,529, 중앙값 £227,000
      - 연립주택(terraced): 112,832건, 평균 £286,616, 중앙값 £227,000
      - 기타(other): 7,884건, 평균 £1,087,765 (중앙값 £315,000) — 소규모 그룹 및 이상값 효과 주의

    중요한 주의사항 및 데이터 품질 참고사항
    - 데이터셋은 2025년에 대해 부분적으로만 존재합니다 (1~8월만 포함). "2025년" 합계는 연간 전체 수치가 아닙니다.
    - 큰 이상값이 존재합니다 (예: 최댓값 £127.7M, 최솟값 £100). 이는 데이터 입력 오류 또는 비표준 기록을 포함할 가능성이 있으며 평균을 왜곡합니다. 여기서는 중앙값이 더 견고한 지표입니다.
    - "기타" 부동산 유형의 평균은 건수가 적고 이질적이며 이상값으로 인해 불안정합니다.
    - is_new, duration 또는 기타 메타데이터로 필터링하지 않았습니다. 해당 필터를 적용하면 결과가 달라질 수 있습니다 (예: 신축 건물 또는 임차권 제외).
    - 테이블은 Price Paid 방식의 거래 기록(기록된 매매)입니다 — 호가나 감정가를 직접 나타내지 않습니다.

    다음 단계 제안 (실행 가능)
    - 명백한 이상값 제거 (예: £10k 미만 또는 £10M 초과 가격) 후 평균/중앙값 재계산.
    - 지역 / 카운티 / 우편번호 구역별 요약 및 지도 생성.
    - 2025년 추세를 보여주기 위한 전월 대비 또는 3개월 이동 중앙값 계산.
    - 월별 전년 대비(YoY) 성장률 산출 (예: 2025년 3월 vs 2024년 3월).
    - 단순 외삽 또는 시계열 모델링을 사용한 2025년 전체 예측 (단, 누락된 월/이상값 처리 방법 결정 후 진행하는 것이 좋습니다).

    원하신다면:
    - 극단적인 이상값 제거 후 동일한 집계를 재실행하여 정제된 결과를 보여드릴 수 있습니다.
    - YoY 월별 성장률 및 차트 생성 (차트로 활용 가능한 CSV 또는 JSON 집계 반환 가능).
    다음으로 무엇을 원하시나요?
    [INFO] 2025-10-10T11:27:51 mcp_agent.mcp.mcp_aggregator.database-anayst - Last aggregator closing, shutting down all persistent
    connections...
    [INFO] 2025-10-10T11:27:51 mcp_agent.mcp.mcp_connection_manager - Disconnecting all persistent server connections...
    [INFO] 2025-10-10T11:27:51 mcp_agent.mcp.mcp_connection_manager - clickhouse: Requesting shutdown...
    [INFO] 2025-10-10T11:27:51 mcp_agent.mcp.mcp_connection_manager - All persistent server connections signaled to disconnect.
    [INFO] 2025-10-10T11:27:52 mcp_agent.mcp.mcp_aggregator.database-anayst - Connection manager successfully closed and removed from context
    [INFO] 2025-10-10T11:27:52 mcp_agent.mcp_basic_agent - MCPApp cleanup
    {
      "data": {
        "progress_action": "Finished",
        "target": "mcp_basic_agent",
        "agent_name": "mcp_application_loop"
      }
    }
    ```
  </Step>
</Steps>
