> ## Documentation Index
> Fetch the complete documentation index at: https://clickhouse.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Claude Agent SDK と ClickHouse MCPサーバーを使って AIエージェントを構築する方法

> Claude Agent SDK と ClickHouse MCPサーバーを使って AIエージェントを構築する方法を学びます

このガイドでは、[Claude Agent SDK](https://docs.claude.com/en/api/agent-sdk/overview) を使って AIエージェントを構築し、[ClickHouse の MCPサーバー](https://github.com/ClickHouse/mcp-clickhouse) 経由で [ClickHouse の SQL Playground](https://sql.clickhouse.com/) と連携する方法を学びます。

<Info>
  **サンプルノートブック**

  このサンプルは、[examples リポジトリ](https://github.com/ClickHouse/examples/blob/main/ai/mcp/claude-agent/claude-agent.ipynb)のノートブックとして利用できます。
</Info>

<div id="prerequisites">
  ## 前提条件
</div>

* システムに Python がインストールされている必要があります。
* システムに `pip` がインストールされている必要があります。
* Anthropic APIキーが必要です。

以下の手順は、Python REPL からでもスクリプトからでも実行できます。

<Steps>
  <Step title="ライブラリをインストールする" id="install-libraries">
    次のコマンドを実行して、Claude Agent SDK ライブラリをインストールします。

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

  <Step title="認証情報を設定する" id="setup-credentials">
    次に、Anthropic APIキーを指定する必要があります。

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

    ```response title="レスポンス" theme={null}
    Enter Anthropic 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 title="MCPサーバーと Claude Agent SDK エージェントを初期化する" id="initialize-mcp-and-agent">
    ここでは、ClickHouse MCPサーバーが ClickHouse SQL Playground を参照するように設定し、
    あわせてエージェントを初期化して質問します。

    ```python theme={null}
    from claude_agent_sdk import query, ClaudeAgentOptions, AssistantMessage, UserMessage, TextBlock, ToolUseBlock
    ```

    ```python theme={null}
    options = ClaudeAgentOptions(
        allowed_tools=[
            "mcp__mcp-clickhouse__list_databases",
            "mcp__mcp-clickhouse__list_tables", 
            "mcp__mcp-clickhouse__run_select_query",
            "mcp__mcp-clickhouse__run_chdb_select_query"
        ],
        mcp_servers={
            "mcp-clickhouse": {
                "command": "uv",
                "args": [
                    "run",
                    "--with", "mcp-clickhouse",
                    "--python", "3.10",
                    "mcp-clickhouse"
                ],
                "env": env
            }
        }
    )

    async for message in query(prompt="Tell me something interesting about UK property sales", options=options):
        if isinstance(message, AssistantMessage):
            for block in message.content:
                if isinstance(block, TextBlock):
                    print(f"🤖 {block.text}")
                if isinstance(block, ToolUseBlock):
                    print(f"🛠️ {block.name} {block.input}")
        elif isinstance(message, UserMessage):
            for block in message.content:
                if isinstance(block, TextBlock):
                    print(block.text)
    ```

    簡潔にするため、`for` ブロック内のコードでは出力を絞り込んでいます。

    ```response title="レスポンス" theme={null}
    🤖 I'll query the ClickHouse database to find something interesting about UK property sales.

    Let me first see what databases are available:
    🛠️ mcp__mcp-clickhouse__list_databases {}
    🤖 Great! There's a "uk" database. Let me see what tables are available:
    🛠️ mcp__mcp-clickhouse__list_tables {'database': 'uk'}
    🤖 Perfect! The `uk_price_paid` table has over 30 million property sales records. Let me find something interesting:
    🛠️ mcp__mcp-clickhouse__run_select_query {'query': "\nSELECT \n    street,\n    town,\n    max(price) as max_price,\n    min(price) as min_price,\n    max(price) - min(price) as price_difference,\n    count() as sales_count\nFROM uk.uk_price_paid\nWHERE street != ''\nGROUP BY street, town\nHAVING sales_count > 100\nORDER BY price_difference DESC\nLIMIT 1\n"}
    🤖 Here's something fascinating: **Baker Street in London** (yes, the famous Sherlock Holmes street!) has the largest price range of any street with over 100 sales - properties sold for as low as **£2,500** and as high as **£594.3 million**, a staggering difference of over £594 million!

    This makes sense given Baker Street is one of London's most prestigious addresses, running through wealthy areas like Marylebone, and has had 541 recorded sales in this dataset.
    ```
  </Step>
</Steps>
