[hypequery](https://hypequery.com/) › ClickHouse with Pydantic AI: Analytics Tools for Python Agents | hypequery
Index for agents: https://hypequery.com/llms.txt
Canonical page: https://hypequery.com/clickhouse-pydantic

> Give a Pydantic AI agent typed ClickHouse analytics tools instead of a SQL console. Datasets are Pydantic models; the agent queries named measures, and the tenant comes from your API, never the prompt.

[Open sourceApache 2.0](https://github.com/hypequery/hypequery)

Pydantic AI

# Give your Pydantic AI agent ClickHouse analytics tools, not a SQL console

Define ClickHouse datasets as Pydantic models, then pass `hypequery_tools()` to a Pydantic AI `Agent`. The agent picks named measures and dimensions; hypequery validates the call, writes the SQL and applies the signed-in user's tenant.

[Add AI chat to your app ](https://hypequery.com/docs/agents/quickstart#python)[See every tool](https://hypequery.com/docs/agents/tools)

Agent input

Measures and dimensions

SQL

Written by hypequery

Tenant

From your API auth

## A run_sql tool hands the model your database

Giving a Pydantic AI agent a SQL tool, or a database MCP server, lets it choose tables, joins and result sizes. That works for an analyst exploring; it is not a permission system for customers.

## The tenant filter lives in the prompt

If the model has to remember `WHERE tenant_id = …`, a user can ask it to forget. The filter has to come from the server, where the model cannot change it.

## The agent defines revenue a second time

An agent that writes its own query gets a number that disagrees with your API and dashboards. The agent should use the same definition as your API and dashboards.

Datasets

## ClickHouse datasets are Pydantic models

A hypequery dataset names the table, the fields an agent may group and filter by, and the measures it may ask for. Datasets are immutable Pydantic models, validated when you create them, and importing `hypequery.datasets` needs only `pydantic`.

- A wrong column type or a measure over an unknown field fails at import, before anyone asks a question
- `tenant_key` makes the dataset fail closed: it will not run without a tenant, and every query is filtered to it
- The same definition serves your REST API, your React dashboard and the agent
- No database driver or web framework is loaded until you serve or query

datasets.py

### One reviewed definition of each number

datasets.py

```
from hypequery.datasets import dataset, dimension, measure

orders = dataset(
    "orders",
    source="orders",
    tenant_key="tenant_id",
    time_key="created_at",
    dimensions={
        "status": dimension.string(),
        "country": dimension.string(),
        "createdAt": dimension.timestamp(column="created_at"),
    },
    measures={
        "revenue": measure.sum("amount"),
        "orderCount": measure.count("id"),
    },
)
```

The agent can ask for `revenue` by `country`. It cannot redefine either.

Pydantic AI

## Pass the tools to your Agent

`hypequery_tools()` returns a list of Pydantic AI `Tool` objects built from your API’s own contract. The executor runs your `hypequery.serve` API in process, as the user whose credential you forward.

The agent gets `list_datasets`, `get_dataset_schema` and `query_dataset`. Each tool’s JSON Schema comes from the dataset, so arguments are validated by hypequery against what the caller may query. A bad call returns an error with a code and a hint, so the model corrects itself instead of looping.

Your API’s authentication resolves the tenant from the forwarded credential, exactly as it does over REST, and applies each endpoint’s policy, scopes and rate limits on every tool call. The agent can never query more than that user could.

chat.py

### A FastAPI chat route with a Pydantic AI agent

chat.py

```
from fastapi import FastAPI, Request
from pydantic import BaseModel
from pydantic_ai import Agent

from hypequery.agent.pydantic_ai import hypequery_tools
from hypequery.mcp import ApiContractBackend, ClientContractExecutor

from app import api  # with add_client_contract_endpoint(api)

chat = FastAPI()

class Question(BaseModel):
    message: str

@chat.post("/chat")
async def answer(question: Question, request: Request) -> dict[str, str]:
    # Forward the signed-in user's credential: the API decides their tenant.
    executor = await ClientContractExecutor.create(
        ApiContractBackend(
            api, headers={"Authorization": request.headers["authorization"]}
        )
    )
    agent = Agent(
        "anthropic:claude-opus-5-5",
        tools=await hypequery_tools(executor=executor),
    )
    result = await agent.run(question.message)
    return {"answer": result.output}
```

Install with `pip install "hypequery[clickhouse]" "pydantic-ai-slim[anthropic]"`.

Over MCP

## Or call a hypequery MCP endpoint

When the tools should run in another service, point `hypequery_tools()` at its MCP URL instead of an executor. The agent sees the same tools, schemas and errors, so your chat code does not change.

`token` is a function, called before every request, so short-lived tokens refresh. With your API’s own auth on the server, each user’s token carries their own tenant.

chat.py

### The same tools from a URL

chat.py

```
pip install "hypequery[mcp]"

# chat.py
from hypequery.agent.pydantic_ai import hypequery_tools

tools = await hypequery_tools(
    url="https://mcp.example.com/mcp",  # http is allowed for localhost only
    token=lambda: get_user_token(session),  # asked for before every request
)
```

Calling an MCP endpoint needs the `mcp` extra.

Where teams usually get stuck

## Questions teams ask

### Pydantic AI with ClickHouse

Pass `hypequery_tools()` to `Agent(tools=…)`. The agent queries your datasets by name and never writes or sees SQL.

### Pydantic models for ClickHouse

Datasets, dimensions and measures are immutable Pydantic models, validated when they are created.

### Multi-tenant Pydantic AI agents

The tenant comes from the credential your API verifies. A filter on the tenant field is refused.

### Text-to-SQL or typed tools

Text-to-SQL lets the model choose the query. Typed tools let it choose from measures you defined and reviewed.

FAQ

## Frequently asked questions

### Does hypequery work with Pydantic AI?

Yes. \`hypequery.agent.pydantic_ai.hypequery_tools()\` returns a list of Pydantic AI \`Tool\` objects you pass to \`Agent(tools=…)\`. It needs \`pydantic-ai\` or \`pydantic-ai-slim\` installed. The same tools are also available for the Anthropic SDK and the OpenAI Agents SDK.

### Does the Pydantic AI agent write ClickHouse SQL?

No. The agent sends a dataset name with measures, dimensions and filters. hypequery validates that against the dataset, compiles the ClickHouse SQL and runs it. The model never writes or receives SQL.

### Are hypequery datasets Pydantic models?

Yes. Datasets are immutable Pydantic models, validated when you create them. Importing \`hypequery.datasets\` needs only \`pydantic\`; no database driver or web framework is loaded.

### How does the agent know which tenant to query?

It does not choose. You forward the signed-in user’s credential to the executor, and your API’s authentication resolves the tenant from it, as it does over REST. A dataset with \`tenant_key\` refuses to run without a tenant.

### Can I use the ClickHouse MCP server with Pydantic AI instead?

Yes. Pydantic AI can connect to any MCP server, including ClickHouse’s own, which gives the model SQL access to the database. That suits internal exploration by people who can read SQL. For an agent that answers customers, hypequery gives the model named datasets and measures, with the tenant enforced by the server.

Further reading

## Go deeper where it actually helps

### [Add AI chat to your app](https://hypequery.com/docs/agents/quickstart#python)

[The full quick start, with the Python tab for Pydantic AI.](https://hypequery.com/docs/agents/quickstart#python)

[Open guide](https://hypequery.com/docs/agents/quickstart#python)

### [Tools for your agent](https://hypequery.com/docs/agents/tools)

[Every tool, its errors, and how to restrict which ones the agent gets.](https://hypequery.com/docs/agents/tools)

[Open guide](https://hypequery.com/docs/agents/tools)

### [Defining datasets in Python](https://hypequery.com/docs/python/datasets/defining-datasets)

[Dimensions, measures, tenant keys and validation.](https://hypequery.com/docs/python/datasets/defining-datasets)

[Open guide](https://hypequery.com/docs/python/datasets/defining-datasets)

### [Serve an API and a dashboard](https://hypequery.com/docs/quick-start/api-and-dashboard#python)

[The API the agent’s executor runs against.](https://hypequery.com/docs/quick-start/api-and-dashboard#python)

[Open guide](https://hypequery.com/docs/quick-start/api-and-dashboard#python)

### [MCP safety model](https://hypequery.com/docs/mcp/safety)

[Credentials, limits, and tenant isolation.](https://hypequery.com/docs/mcp/safety)

[Open guide](https://hypequery.com/docs/mcp/safety)

Related pillars

[ClickHouse with Python](https://hypequery.com/clickhouse-python)[MCP for Python backends](https://hypequery.com/clickhouse-python-mcp)[ClickHouse with FastAPI](https://hypequery.com/clickhouse-fastapi)[Python multi-tenancy](https://hypequery.com/clickhouse-python-multi-tenant)[Python semantic layer](https://hypequery.com/python-semantic-layer)[Semantic layer for AI agents](https://hypequery.com/semantic-layer/ai-agents)

Next step

## Give one dataset to your Pydantic AI agent

Add the client contract route to your API, then pass `hypequery_tools(executor=executor)` to your agent.

Open source, and it runs in your own backend. Want it hosted?

[Open the quick start ](https://hypequery.com/docs/agents/quickstart#python)[Define a dataset](https://hypequery.com/docs/python/datasets/defining-datasets)
