[hypequery](https://hypequery.com/) › ClickHouse AI: Add AI Analytics Chat to Your App (Vercel AI SDK) | hypequery
Index for agents: https://hypequery.com/llms.txt
Canonical page: https://hypequery.com/clickhouse-ai

> Let users chat with their ClickHouse data inside your product. The model calls governed dataset tools from the Vercel AI SDK, Anthropic SDK or OpenAI Agents SDK, never raw SQL, and each customer only sees their own rows.

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

ClickHouse AI

# AI analytics chat for ClickHouse, with tools your model can't misuse

Add a chat-with-your-data assistant to your product. @hypequery/agent gives the Vercel AI SDK, the Anthropic SDK or the OpenAI Agents SDK typed tools over your ClickHouse datasets. The model asks for named measures and dimensions, never writes SQL, and only ever sees the signed-in customer's rows.

[Build the chat app ](https://hypequery.com/blog/clickhouse-ai-chat-vercel-ai-sdk)[AI SDK docs](https://hypequery.com/docs/agents/ai-sdk)

Works with

AI SDK, Anthropic, OpenAI Agents

Model surface

Datasets, not SQL

Tenant

From the token, never the prompt

Quickstart

## A ClickHouse chat in a Next.js route

Define what the model may query, serve it as MCP tools, and hand those tools to streamText. useChat on the client needs nothing hypequery-specific.

1. Step 1

   ### Install the packages

   In a Next.js app. You need Node.js 20 or newer.

   terminal

   ```
   npm install ai @ai-sdk/react @ai-sdk/anthropic @hypequery/agent
   npm install @hypequery/clickhouse @hypequery/datasets @hypequery/serve @hypequery/mcp
   npm install -D @hypequery/cli
   ```

2. Step 2

   ### Define what the model may query

   Save a dataset in analytics/api.ts and register it with Serve, as in the MCP quickstart. Labels and descriptions are what the model reads to pick fields.

   analytics/api.ts

   ```
   // analytics/api.ts
   import { dataset, dimension, measure } from '@hypequery/datasets';

   export const Orders = dataset('orders', {
     source: 'orders',
     tenantKey: 'tenant_id',
     description: 'One row per order.',
     dimensions: {
       country: dimension.string({ label: 'Country' }),
       status: dimension.string({
         label: 'Status',
         description: 'completed, refunded or pending',
       }),
     },
     measures: {
       revenue: measure.sum('amount', { label: 'Revenue' }),
       orders: measure.count('id', { label: 'Orders' }),
     },
   });
   ```

3. Step 3

   ### Serve it as MCP tools

   The endpoint holds the ClickHouse connection; your app only holds the key. The dataset is tenant-scoped, so a shared key serves one trusted tenant, named with --tenant. In production, serve it with your API's own auth instead, so each caller gets their own tenant.

   terminal

   ```
   export HYPEQUERY_MCP_KEY=$(openssl rand -hex 32)
   npx hypequery mcp --http --tenant acme
   # hypequery MCP listening on http://127.0.0.1:3333/mcp
   ```

4. Step 4

   ### Give the tools to the AI SDK

   hypequeryTools() lists the endpoint's tools once and returns an AI SDK tool set, with the server's schemas unchanged.

   app/api/chat/route.ts

   ```
   // app/api/chat/route.ts
   import { anthropic } from '@ai-sdk/anthropic';
   import { convertToModelMessages, isStepCount, streamText, type UIMessage } from 'ai';
   import { hypequeryTools } from '@hypequery/agent/ai-sdk';

   export async function POST(req: Request) {
     const { messages }: { messages: UIMessage[] } = await req.json();

     // list_datasets, get_dataset_schema, query_dataset: no SQL tool.
     const tools = await hypequeryTools({
       url: process.env.HYPEQUERY_MCP_URL!,
       token: process.env.HYPEQUERY_MCP_KEY!,
     });

     const result = streamText({
       model: anthropic('claude-sonnet-5-5'),
       messages: await convertToModelMessages(messages),
       tools,
       stopWhen: isStepCount(8),
     });

     return result.toUIMessageStreamResponse();
   }
   ```

On AI SDK 5 or 6, use `system` and `stepCountIs` instead of `instructions` and `isStepCount`. The full walkthrough, with the chat component, is in the Vercel AI SDK tutorial.

Why text-to-SQL breaks

## Letting the model write SQL against ClickHouse goes wrong in specific ways

### ClickHouse semantics are easy to get wrong

A ReplacingMergeTree read without FINAL counts rows twice, uniq and uniqExact disagree, and UTC DateTime columns shift day boundaries. Generated SQL gets these wrong without raising an error.

### The chat disagrees with your dashboards

If the model writes its own revenue query on every question, its number drifts from the one in your product and your finance reports.

### A prompt is not a tenant boundary

Nothing in a generated SQL string stops a read of another customer's rows. In a multi-tenant product, the tenant has to come from your auth layer, never from the model.

Governed tools

## Give the model a semantic layer instead of a SQL console

You define datasets once in TypeScript or Python. The model discovers them, reads their schemas and queries them through three small tools, and every query is validated before it reaches ClickHouse.

- The model can only ask for dimensions, measures and filters your datasets declare
- A wrong field comes back as a correctable error listing the valid ones, so the model retries
- Measures mean the same thing in the chat, your APIs and your React dashboards
- SQL and ClickHouse credentials never enter the model context
- Tenant-scoped datasets refuse to run without a trusted tenant

Vercel AI SDK

### streamText with hypequery tools

app/api/chat/route.ts

```
// app/api/chat/route.ts
import { anthropic } from '@ai-sdk/anthropic';
import { convertToModelMessages, isStepCount, streamText, type UIMessage } from 'ai';
import { hypequeryTools } from '@hypequery/agent/ai-sdk';

export async function POST(req: Request) {
  const { messages }: { messages: UIMessage[] } = await req.json();

  // list_datasets, get_dataset_schema, query_dataset: no SQL tool.
  const tools = await hypequeryTools({
    url: process.env.HYPEQUERY_MCP_URL!,
    token: process.env.HYPEQUERY_MCP_KEY!,
  });

  const result = streamText({
    model: anthropic('claude-sonnet-5-5'),
    messages: await convertToModelMessages(messages),
    tools,
    stopWhen: isStepCount(8),
  });

  return result.toUIMessageStreamResponse();
}
```

Any AI SDK provider works. Tool calls stream to useChat as message parts, so users can open an answer and see the exact query behind it.

Any agent SDK

## The same tools for the Anthropic SDK and the OpenAI Agents SDK

@hypequery/agent reads the tools your MCP endpoint serves and adapts them to the SDK you already use. You don't need an MCP client, and you don't write any tools.

Each adapter keeps the input schemas the server lists, so the model sees enums of your real field names. Tool errors reach the model as hypequery's error envelope, with a code, a hint and a request id.

Failures the model can't fix, like a refused token or an unreachable endpoint, throw HypequeryToolsError in your code instead.

Anthropic SDK

### Tool definitions and tool_result helpers

agent.ts

```
import Anthropic from '@anthropic-ai/sdk';
import { hypequeryTools } from '@hypequery/agent/anthropic';

const anthropic = new Anthropic();
const hq = await hypequeryTools({ url: mcpUrl, token });
const response = await anthropic.messages.create({
  model, max_tokens: 1024, tools: hq.tools, messages,
});
messages.push({ role: 'assistant', content: response.content });
messages.push({ role: 'user', content: await hq.toolResults(response.content) });
```

hq.toolResults() answers the model's tool_use blocks for hypequery's tools.

OpenAI Agents SDK

### Function tools for an Agent

agent.ts

```
import { Agent, run } from '@openai/agents';
import { hypequeryTools } from '@hypequery/agent/openai-agents';

const agent = new Agent({
  name: 'Analyst',
  tools: await hypequeryTools({ url: mcpUrl, token }),
});
const result = await run(agent, 'Which countries grew fastest last quarter?');
```

Pass them straight to new Agent({ tools }).

Multi-tenant

## One customer per conversation

The token decides whose data the model sees. Your route reads it from the signed-in user, so a prompt asking for another customer's data has nothing to change.

- Self-hosted: run hypequery mcp --http with your API's own auth, and pass the user's credential as the token
- hypequery Cloud (not live yet): mint a 15-minute token per session with mintAgentToken(), locally, with no network call
- Every tool result carries a request id, so you can trace an answer back to its query

Where teams usually get stuck

## Questions teams ask

### Chat with ClickHouse data

Put a natural-language analytics assistant in your product without giving the model database access.

### Vercel AI SDK and ClickHouse

hypequeryTools() returns AI SDK tools for streamText, generateText and useChat, on ai 5, 6 and 7.

### Text-to-SQL alternative

Named measures and dimensions instead of generated SQL, so answers match your dashboards and can be checked.

### AI analytics for multi-tenant SaaS

The tenant comes from a signed token or your app's auth, never from the conversation.

FAQ

## Frequently asked questions

### Can I use OpenAI, Gemini or a local model instead of Claude?

Yes. hypequeryTools() returns standard AI SDK tools, so any AI SDK provider with tool calling works. There are also adapters for the Anthropic SDK and the OpenAI Agents SDK.

### Does the model ever see SQL or my ClickHouse credentials?

No. The credentials stay in the MCP endpoint, and generated SQL is redacted from tool results by default.

### Do I need hypequery Cloud?

No. Run the MCP endpoint yourself with npx hypequery mcp --http and point hypequeryTools() at it. hypequery Cloud, which is not live yet, will host the endpoint and mint per-tenant tokens for you.

### Which AI SDK versions are supported?

ai 5, 6 and 7. @hypequery/agent declares them as optional peer dependencies.

Further reading

## Go deeper where it actually helps

### [The typed query builder underneath](https://hypequery.com/docs/query-building/setup)

[Datasets are built on hypequery's ClickHouse query builder. Use it directly for the one-off queries in your app code.](https://hypequery.com/docs/query-building/setup)

[Open guide](https://hypequery.com/docs/query-building/setup)

### [Build an AI analytics chat with the Vercel AI SDK](https://hypequery.com/blog/clickhouse-ai-chat-vercel-ai-sdk)

[The full Next.js walkthrough: dataset, MCP endpoint, route handler and useChat component.](https://hypequery.com/blog/clickhouse-ai-chat-vercel-ai-sdk)

[Open guide](https://hypequery.com/blog/clickhouse-ai-chat-vercel-ai-sdk)

### [Vercel AI SDK docs](https://hypequery.com/docs/agents/ai-sdk)

[streamText, generateText, useChat and every hypequeryTools() option.](https://hypequery.com/docs/agents/ai-sdk)

[Open guide](https://hypequery.com/docs/agents/ai-sdk)

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

[The Anthropic SDK and OpenAI Agents SDK adapters.](https://hypequery.com/docs/agents/tools)

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

### [Stop an AI agent leaking data between tenants](https://hypequery.com/blog/ai-agent-multi-tenant-data-isolation)

[Row policies, scoped tools and scoped tokens, with tests you can run.](https://hypequery.com/blog/ai-agent-multi-tenant-data-isolation)

[Open guide](https://hypequery.com/blog/ai-agent-multi-tenant-data-isolation)

### [Text-to-SQL vs a semantic layer](https://hypequery.com/blog/text-to-sql-vs-semantic-layer)

[Where NL2SQL agents go wrong, where they are the right tool, and how to combine them.](https://hypequery.com/blog/text-to-sql-vs-semantic-layer)

[Open guide](https://hypequery.com/blog/text-to-sql-vs-semantic-layer)

### [hypequery vs ClickHouse Agents](https://hypequery.com/compare/hypequery-vs-clickhouse-agents)

[An agent for your team, or an agent in your product.](https://hypequery.com/compare/hypequery-vs-clickhouse-agents)

[Open guide](https://hypequery.com/compare/hypequery-vs-clickhouse-agents)

### [Semantic layer for AI agents](https://hypequery.com/semantic-layer/ai-agents)

[Why agents need named metrics instead of raw text-to-SQL, and how the options compare.](https://hypequery.com/semantic-layer/ai-agents)

[Open guide](https://hypequery.com/semantic-layer/ai-agents)

### [Official ClickHouse MCP vs governed MCP](https://hypequery.com/blog/clickhouse-mcp-servers-compared)

[When a raw SQL tool is fine, and when it becomes a problem.](https://hypequery.com/blog/clickhouse-mcp-servers-compared)

[Open guide](https://hypequery.com/blog/clickhouse-mcp-servers-compared)

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

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

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

Related pillars

[ClickHouse MCP](https://hypequery.com/clickhouse-mcp)[ClickHouse Semantic Layer](https://hypequery.com/clickhouse-semantic-layer)[ClickHouse Next.js](https://hypequery.com/clickhouse-nextjs)[Multi-Tenant Analytics](https://hypequery.com/clickhouse-multi-tenant-analytics)[Embedded Analytics for SaaS](https://hypequery.com/clickhouse-saas-analytics)

Next step

## Ship a ClickHouse chat in an afternoon

Follow the tutorial with the public ClickHouse playground, then point the dataset at your own tables.

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

[Open the tutorial ](https://hypequery.com/blog/clickhouse-ai-chat-vercel-ai-sdk)[MCP quickstart](https://hypequery.com/docs/mcp/quickstart)
