> ## 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.

# Como criar um agente de IA com LangChain/LangGraph usando o servidor MCP do ClickHouse.

> Aprenda a criar um agente de IA com LangChain/LangGraph que pode interagir com o Playground SQL do ClickHouse usando o servidor MCP do ClickHouse.

Neste guia, você aprenderá a criar um agente de IA com [LangChain/LangGraph](https://github.com/langchain-ai/langgraph) que
pode interagir com o [Playground SQL do ClickHouse](https://sql.clickhouse.com/) usando o [servidor MCP do ClickHouse](https://github.com/ClickHouse/mcp-clickhouse).

<Info>
  **Notebook de exemplo**

  Este exemplo está disponível como um notebook no [repositório de exemplos](https://github.com/ClickHouse/examples/blob/main/ai/mcp/langchain/langchain.ipynb).
</Info>

<div id="prerequisites">
  ## Pré-requisitos
</div>

* Você precisará ter o Python instalado no seu sistema.
* Você precisará ter o `pip` instalado no seu sistema.
* Você precisará de uma API key da Anthropic ou de outro provedor de LLM

Você pode executar as etapas a seguir no REPL do Python ou por meio de um script.

<Steps>
  <Step title="Instale as bibliotecas" id="install-libraries">
    Instale as bibliotecas necessárias executando os comandos a seguir:

    ```python theme={null}
    pip install -q --upgrade pip
    pip install -q langchain-mcp-adapters langgraph "langchain[anthropic]"
    ```
  </Step>

  <Step title="Configurar credenciais" id="setup-credentials">
    Em seguida, você precisará informar sua API key da Anthropic:

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

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

    <Info>
      **Usando outro provedor de LLM**

      Se você não tiver uma API key da Anthropic e quiser usar outro provedor de LLM,
      poderá encontrar instruções para configurar suas credenciais na [documentação de provedores do LangChain](https://python.langchain.com/docs/integrations/providers/)
    </Info>
  </Step>

  <Step title="Inicialize o ClickHouse MCP server" id="initialize-mcp-and-agent">
    Agora, configure o ClickHouse MCP server para apontar para o Playground do ClickHouse SQL:

    ```python theme={null}
    from mcp import ClientSession, StdioServerParameters
    from mcp.client.stdio import stdio_client

    server_params = StdioServerParameters(
        command="uv",
        args=[
            "run",
            "--with", "mcp-clickhouse",
            "--python", "3.13",
            "mcp-clickhouse"
        ],
        env={
            "CLICKHOUSE_HOST": "sql-clickhouse.clickhouse.com",
            "CLICKHOUSE_PORT": "8443",
            "CLICKHOUSE_USER": "demo",
            "CLICKHOUSE_PASSWORD": "",
            "CLICKHOUSE_SECURE": "true"
        }
    )
    ```
  </Step>

  <Step title="Configure o manipulador de stream" id="configure-the-stream-handler">
    Ao trabalhar com Langchain e o ClickHouse MCP server, os resultados das consultas costumam
    ser retornados como dados em streaming, em vez de uma única resposta. Para grandes conjuntos de dados ou
    consultas analíticas complexas que podem levar tempo para serem processadas, é importante configurar
    um manipulador de stream. Sem o tratamento adequado, essa saída em streaming pode ser difícil
    de usar no seu aplicativo.

    Configure o manipulador para a saída em streaming para que ela seja mais fácil de consumir:

    ```python theme={null}
    class UltraCleanStreamHandler:
        def __init__(self):
            self.buffer = ""
            self.in_text_generation = False
            self.last_was_tool = False
            
        def handle_chunk(self, chunk):
            event = chunk.get("event", "")
            
            if event == "on_chat_model_stream":
                data = chunk.get("data", {})
                chunk_data = data.get("chunk", {})
                
                # Only handle actual text content, skip tool invocation streams
                if hasattr(chunk_data, 'content'):
                    content = chunk_data.content
                    if isinstance(content, str) and not content.startswith('{"'):
                        # Add space after tool completion if needed
                        if self.last_was_tool:
                            print(" ", end="", flush=True)
                            self.last_was_tool = False
                        print(content, end="", flush=True)
                        self.in_text_generation = True
                    elif isinstance(content, list):
                        for item in content:
                            if (isinstance(item, dict) and 
                                item.get('type') == 'text' and 
                                'partial_json' not in str(item)):
                                text = item.get('text', '')
                                if text and not text.startswith('{"'):
                                    # Add space after tool completion if needed
                                    if self.last_was_tool:
                                        print(" ", end="", flush=True)
                                        self.last_was_tool = False
                                    print(text, end="", flush=True)
                                    self.in_text_generation = True
                                    
            elif event == "on_tool_start":
                if self.in_text_generation:
                    print(f"\n🔧 {chunk.get('name', 'tool')}", end="", flush=True)
                    self.in_text_generation = False
                    
            elif event == "on_tool_end":
                print(" ✅", end="", flush=True)
                self.last_was_tool = True
    ```
  </Step>

  <Step title="Chame o agente" id="call-the-agent">
    Por fim, chame seu agente e pergunte a ele quem mais contribuiu com código para o ClickHouse:

    ```python theme={null}
    async with stdio_client(server_params) as (read, write):
        async with ClientSession(read, write) as session:
            await session.initialize()
            tools = await load_mcp_tools(session)
            agent = create_react_agent("anthropic:claude-sonnet-4-0", tools)
            
            handler = UltraCleanStreamHandler()        
            async for chunk in agent.astream_events(
                {"messages": [{"role": "user", "content": "Who's committed the most code to ClickHouse?"}]}, 
                version="v1"
            ):
                handler.handle_chunk(chunk)
                
            print("\n")
    ```

    Você deverá ver uma resposta semelhante à mostrada abaixo:

    ```response title="Response" theme={null}
    I'll help you find who has committed the most code to ClickHouse by exploring the available databases and tables to locate git commit data.
    🔧 list_databases ✅ I can see there's a `git` database which likely contains git commit information. Let me explore the tables in that database:
    🔧 list_tables ✅ Perfect! I can see the `clickhouse_commits` table in the git database contains ClickHouse commit data with 80,644 commits. This table has information about each commit including the author, lines added/deleted, files modified, etc. Let me query this table to find who has committed the most code based on different metrics.
    🔧 run_select_query ✅ Let me also look at just the lines added to see who has contributed the most new code:
    🔧 run_select_query ✅ Based on the ClickHouse git commit data, **Alexey Milovidov** has committed the most code to ClickHouse by several measures:

    ## Key Statistics:

    1. **Most Total Lines Changed**: Alexey Milovidov with **1,696,929 total lines changed** (853,049 added + 843,880 deleted)
    2. **Most Lines Added**: Alexey Milovidov with **853,049 lines added**
    3. **Most Commits**: Alexey Milovidov with **15,375 commits**
    4. **Most Files Changed**: Alexey Milovidov with **73,529 files changed**

    ## Top Contributors by Lines Added:

    1. **Alexey Milovidov**: 853,049 lines added (15,375 commits)
    2. **s-kat**: 541,609 lines added (50 commits) 
    3. **Nikolai Kochetov**: 219,020 lines added (4,218 commits)
    4. **alesapin**: 193,566 lines added (4,783 commits)
    5. **Vitaly Baranov**: 168,807 lines added (1,152 commits)

    Alexey Milovidov is clearly the most prolific contributor to ClickHouse, which makes sense as he is one of the original creators and lead developers of the project. His contribution dwarfs others both in terms of total code volume and number of commits, with nearly 16,000 commits and over 850,000 lines of code added to the project.
    ```
  </Step>
</Steps>
