Skip to main content Switch to mobile version clickhouse-mcp-agent 0.13.0 AI agent for ClickHouse database analysis via MCP
pip install clickhouse-mcp-agent==0.13.0 Copy PIP instructions
AI agent for ClickHouse database analysis via MCP (Model Context Protocol).
A single MCP server (mcp-clickhouse) driven by a single agent instance. You can scope what the agent discovers per call with allow-lists (allowed_tables, allowed_databases). See Security for what they do and do not restrict.
Query ClickHouse databases using natural language with AI models
Structured output: analysis, confidence, sql_used
Easy connection management (predefined or custom)
Conversational context with message-history pruning/summarization
No CLI or external .env required — configure at runtime
Per-call discovery scoping via allow-lists (allowed_tables, allowed_databases)
Read-only queries by default (enforced by mcp-clickhouse)
Streamable results via run_stream()
Persistent MCP server mode via async with ClickHouseAgent()
Parallel queries via run_batch()
Lifecycle reset via reset()
Query result cache via enable_cache=True
Typed exception hierarchy for reliable error handling
Optional structlog integration (pip install ".[logging]")
Local Development (Docker)
The fastest way to get started — no cloud ClickHouse account needed:
# Start ClickHouse with seeded demo data (orders + products) docker compose up -d # Install the package with dev dependencies pip install -e ".[dev]" # Run the examples (set your Google API key first) GOOGLE_API_KEY=... python examples/example_minimal.py GOOGLE_API_KEY=... python examples/example_stream.py GOOGLE_API_KEY=... python examples/example_0_11.py GOOGLE_API_KEY=... python examples/example_integration.py The docker/init.sql file seeds demo.orders (25 orders, May 2026) and demo.products (10 products across Electronics, Sports, Home, Books) automatically on first start.
import asyncio from agent.clickhouse_agent import ClickHouseAgent from agent.config import config config.set_ai_model("openai:gpt-4o-mini") config.set_model_api_key("openai", "your_api_key_here") config.set_clickhouse(host="localhost", port="8123", user="default", password="", secure="false") async def main(): agent = ClickHouseAgent() result = await agent.run( allowed_tables=["orders", "products"], allowed_databases=["demo"], query="give me some insights on the recent data", ) print("Analysis:", result.analysis) print("Confidence:", result.confidence) print("SQL used:", result.sql_used) asyncio.run(main()) Persistent server (multiple queries)
Use the context manager to keep the MCP subprocess alive across calls — avoids subprocess startup overhead on every query:
async def main(): async with ClickHouseAgent() as agent: r1 = await agent.run(query="how many orders were placed last week?") r2 = await agent.run(query="which products are selling fastest?", message_history=r1.messages) Parallel queries
async with ClickHouseAgent() as agent: results = await agent.run_batch( ["how many orders?", "total revenue?", "top 5 products?"], allowed_databases=["demo"], ) for r in results: print(r.analysis) # Keep successful results when some queries fail: mixed = await agent.run_batch(["ok query", "bad query"], return_exceptions=True) # -> [RunResult, Exception] in input order Connection presets and options
config.use_connection("local") # localhost:8123, no TLS (docker compose) config.use_connection("playground") # public ClickHouse demo server # Ports and flags accept ints/bools; extra options are passed to mcp-clickhouse config.set_clickhouse( host="ch.internal", port=8443, user="agent_reader", password="...", secure=True, database="demo", role="analyst", query_timeout=60, connect_timeout=10, ) Query result cache
agent = ClickHouseAgent(enable_cache=True) result = await agent.run(query="how many orders?", allowed_databases=["demo"]) # identical call returns instantly from cache (stateless queries only) Lifecycle reset
agent = ClickHouseAgent() await agent.run(query="...") await agent.reset() # tear down MCP subprocess await agent.run(query="...") # re-initializes on next call Switching providers
All providers use the same interface — just swap the model string and key. The provider is read from the model prefix (openai:, anthropic:, ...), and a key passed to set_model_api_key overrides one already in the environment:
# Anthropic Claude 4 config.set_ai_model("anthropic:claude-sonnet-4-6") config.set_model_api_key("anthropic", "your_key") # Google Gemini config.set_ai_model("google:gemini-3.1-flash-lite") config.set_model_api_key("google", "your_key") # Grok (xAI) config.set_ai_model("xai:grok-4") config.set_model_api_key("xai", "your_key") # Groq (fast open models, free tier — good for testing) config.set_ai_model("groq:llama-3.3-70b-versatile") config.set_model_api_key("groq", "your_key") Security
Queries are read-only. mcp-clickhouse runs every query with ClickHouse's readonly setting unless CLICKHOUSE_ALLOW_WRITE_ACCESS=true is set for the server, so the agent cannot modify data.
Allow-lists scope discovery; they are not an access control. allowed_databases and allowed_tables filter what the list_databases and list_tables tools return, which keeps the model focused on the right tables. They do not inspect the SQL passed to run_query: a model that writes SELECT * FROM other_db.other_table directly can still read it.
To restrict what can be read, use ClickHouse permissions. Connect with a ClickHouse user that only has SELECT grants on the data the agent may see:
CREATE USER agent_reader IDENTIFIED BY '...'; GRANT SELECT ON demo.orders TO agent_reader; GRANT SELECT ON demo.products TO agent_reader; ClickHouse then rejects any query outside those grants, whatever SQL the model generates. You can also pass role= to config.set_clickhouse() to run the agent under a specific ClickHouse role.
Message History & Summarization
Pass message_history between calls for multi-turn conversations. When the conversation's context size (the latest response's token usage) exceeds summarize_config.token_limit, the history is replaced by a short summary written by a separate summarizer agent. The summarizer can use a different provider from the main agent; give it its own key, or summarization is skipped with a warning. The default limit is 50,000 tokens:
summarize_config.set_token_limit(20000) summarize_config.set_ai_model("google:gemini-3.1-flash-lite") summarize_config.set_model_api_key("google", "your_key") Output
Each call to ClickHouseAgent.run() returns a RunResult:
All errors raise from a typed hierarchy so you can catch at the right level:
from agent.exceptions import ClickHouseMCPError, MCPConnectionError, AgentExecutionError try: result = await agent.run(query="...") except MCPConnectionError: # MCP subprocess failed to start or connection dropped ... except AgentExecutionError: # Agent logic failed during the run ... except ClickHouseMCPError: # Any library error ... Requirements
An AI provider API key (Google, OpenAI, Anthropic, Grok, Groq, Mistral, or Cohere)
All dependencies are managed via pyproject.toml.
MCP integration via pydantic_ai.mcp.MCPServerStdio
SQL generation/execution via MCP tools
Schema inspection (databases/tables/columns)
Config-driven connections (playground/local/custom)
Discovery scoping via per-call allow-lists (allowed_tables, allowed_databases)
Runtime provider/model selection and API key management
Structured outputs (ClickHouseOutput) and RunResult with sql_used
Message history pruning/summarization
Streaming results via run_stream()
Persistent MCP server via async with ClickHouseAgent()
Local development via Docker (docker compose up -d)
ruff linting, Python 3.13 support, CI hardened
Async batch queries via run_batch()
reset() for lifecycle control
Query result cache (enable_cache=True)
structlog optional dep (pip install ".[logging]")
API locked — no breaking changes without a major version
py.typed check added to CI
mypy agent/ added to CI matrix
Updated to mcp-clickhouse 0.4.0; list_databases tool now enforced by allowed_databases allow-list
Default model updated to google:gemini-3.1-flash-lite
Allow-list filtering now works against real mcp-clickhouse responses (previously bypassed)
Contract tests against the real mcp-clickhouse server, and live tests against ClickHouse in CI
Grok (xAI) and Groq provider setup corrected
✅ 0.13 — Fixes and connection options
Multi-turn history summarization fixed (it previously wiped the conversation); default token_limit raised to 50,000
role, database, verify and timeout options passed to mcp-clickhouse (ClickHouse-enforced access control)
config.use_connection() presets, run_batch(return_exceptions=True), last_sql_used
Provider derived from the model prefix; explicit API keys override env vars
Wire tests against a fake OpenAI-compatible server; live tests for roles and timeouts
Migrate to pydantic-ai 2.x (MCPToolset) and mcp-clickhouse 0.7
FastAPI standalone deployment option
Open an issue or pull request for features or fixes.
Both files in this release have provenance metadata.
clickhouse mcp ai database analysis
Development Status 4 - Beta
Intended Audience Developers
License OSI Approved :: MIT License
Operating System OS Independent
Programming Language Python :: 3
Scientific/Engineering :: Artificial Intelligence
Release files for clickhouse-mcp-agent 0.13.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
Built distribution (wheel)
Total release size: 52.3 kB
Release files / clickhouse_mcp_agent-0.13.0.tar.gz
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
PyPI verified that this artifact, at this checksum, originated from the publisher listed below.
Signed by GitHub Actions, verified by PyPI on Nov 21, 2026.
Security for clickhouse-mcp-agent 0.13.0
Both files in this release have been uploaded with provenance metadata.
With provenance clickhouse_mcp_agent-0.13.0.tar.gz Nov 21, 2026
Attestation for clickhouse_mcp_agent-0.13.0.tar.gz
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.
Release history Release notifications | RSS feed
Nov 21, 2026 2 release files Full provenance
Oct 28, 2026 2 release files Full provenance
Jun 7, 2026 2 release files Full provenance
May 25, 2026 2 release files Full provenance
May 24, 2026 2 release files Full provenance
Sep 5, 2025 2 release files Full provenance
Aug 29, 2025 2 release files Full provenance
Aug 15, 2025 2 release files Full provenance
Aug 13, 2025 2 release files Full provenance
Jul 31, 2025 2 release files Full provenance
Jul 30, 2025 2 release files Full provenance
Jul 29, 2025 2 release files Full provenance
Jul 28, 2025 2 release files Full provenance
"PyPI", "Python Package Index", and the blocks logos are registered trademarks of the Python Software Foundation.
© 2026 Python Software Foundation




