跳转到主内容
跳转到主内容

如何使用 ClickHouse MCP 服务器 构建 PydanticAI agent

在本指南中,您将学习如何构建一个 PydanticAI agent, 使其能够通过 ClickHouse 的 MCP 服务器ClickHouse 的 ClickHouse SQL playground 进行交互。

示例 notebook

该示例可以在 示例仓库 中以 notebook 形式查阅。

前置条件

  • 您的系统上需要安装 Python。
  • 您的系统上需要安装 pip
  • 您需要 Anthropic API 密钥,或其他 LLM 提供商的 API 密钥

您既可以在 Python REPL 中执行以下步骤,也可以通过脚本执行。

安装库

运行以下命令安装必需库:

pip install -q --upgrade pip
pip install -q "pydantic-ai-slim[mcp]"
pip install -q "pydantic-ai-slim[anthropic]" # 如果使用其他 LLM 提供商,请替换为相应的软件包

配置凭证

接下来,您需要提供 Anthropic API 密钥:

import os, getpass
os.environ["ANTHROPIC_API_KEY"] = getpass.getpass("Enter Anthropic API Key:")
Enter Anthropic API Key: ········
使用其他 LLM 提供商

如果您没有 Anthropic API 密钥,并且想使用其他 LLM 提供商, 可以在 PydanticAI docs 中找到配置凭证的说明。

接下来,定义连接到 ClickHouse SQL playground 所需的凭证:

env = {
    "CLICKHOUSE_HOST": "sql-clickhouse.clickhouse.com",
    "CLICKHOUSE_PORT": "8443",
    "CLICKHOUSE_USER": "demo",
    "CLICKHOUSE_PASSWORD": "",
    "CLICKHOUSE_SECURE": "true"
}

初始化 MCP 服务器 和 PydanticAI agent

现在,将 ClickHouse MCP 服务器 配置为指向 ClickHouse SQL playground:

from pydantic_ai import Agent
from pydantic_ai.mcp import MCPServerStdio
from pydantic_ai.messages import ToolCallPart, ToolReturnPart

server = MCPServerStdio(
    'uv',
    args=[
        'run',
        '--with', 'mcp-clickhouse',
        '--python', '3.13',
        'mcp-clickhouse'
    ],
    env=env
)
agent = Agent('anthropic:claude-sonnet-4-0', mcp_servers=[server])

向 agent 提问

最后,您可以向 agent 提出一个问题:

async with agent.run_mcp_servers():
    result = await agent.run("Who's done the most PRs for ClickHouse?")
    print(result.output)

您会得到类似下面的响应:

Based on the data from the ClickHouse GitHub repository, here are the top contributors by number of pull requests created:

**Top contributors to ClickHouse by PRs opened:**

1. **alexey-milovidov** - 3,370 PRs opened
2. **azat** - 1,905 PRs opened  
3. **rschu1ze** - 979 PRs opened
4. **alesapin** - 947 PRs opened
5. **tavplubix** - 896 PRs opened
6. **kssenii** - 871 PRs opened
7. **Avogar** - 805 PRs opened
8. **KochetovNicolai** - 700 PRs opened
9. **Algunenano** - 658 PRs opened
10. **kitaisreal** - 630 PRs opened

**Alexey Milovidov** stands out as by far the most active contributor with over 3,370 pull requests opened, which is significantly more than any other contributor. This makes sense as Alexey Milovidov is one of the founders and lead developers of ClickHouse.

The data also shows that alexey-milovidov has been very active in managing PRs, with 12,818 "closed" events (likely reviewing and closing PRs from other contributors) in addition to creating his own PRs.

It's worth noting that I filtered out various robot/bot accounts that handle automated processes, focusing on human contributors to give you the most meaningful answer about who has contributed the most PRs to ClickHouse.