Details
# ClickHouse Agent Skills
The official Agent Skills for [ClickHouse](https://clickhouse.com/). These skills help LLMs and agents to adopt best practices when working with ClickHouse and [chdb](https://clickhouse.com/docs/chdb) (in-process ClickHouse for Python).
You can use these skills with open-source ClickHouse and managed ClickHouse Cloud. [Try ClickHouse Cloud with $300 in free credits](https://clickhouse.com/cloud?utm_medium=github&utm_source=github&utm_ref=agent-skills).
## Installation
### npx
```bash
npx skills add clickhouse/agent-skills
```
The CLI auto-detects installed agents and prompts you to select where to install.
### clickhousectl
Use the ClickHouse CLI [`clickhousectl`](https://github.com/ClickHouse/clickhousectl) to install the agent skills:
```bash
clickhousectl skills
```
## What is this?
Agent Skills are packaged instructions that extend AI coding agents (Claude Code, Cursor, Copilot, etc.) with domain-specific expertise. This repository provides skills for ClickHouse databases and chdb — covering schema design, query optimization, data ingestion patterns, and in-process analytics with Python.
When an agent loads these skills, it gains knowledge of ClickHouse best practices and chdb APIs, and can apply them while helping you design tables, write queries, analyze data, or troubleshoot performance issues.
Skills follow the open specification at [agentskills.io](https://agentskills.io).
## Available Skills
### ClickHouse Best Practices
**28 rules** covering schema design, query optimization, and data ingestion—prioritized by impact.
| Category | Rules | Impact |
|----------|-------|--------|
| Primary Key Selection | 4 | CRITICAL |
| Data Type Selection | 5 | CRITICAL |
| JOIN Optimization | 5 | CRITICAL |
| Insert Batching | 1 | CRITICAL |
| Mutation Avoidance | 2 | CRITICAL |
| Partitioning Strategy | 4 | HIGH |
| Skipping Indices | 1 | HIGH |
| Materialized Views | 2 | HIGH |
| Async Inserts | 2 | HIGH |
| OPTIMIZE Avoidance | 1 | HIGH |
| JSON Usage | 1 | MEDIUM |
**Location:** [`skills/clickhouse-best-practices/`](./skills/clickhouse-best-practices/)
**For humans:** Read [SKILL.md](./skills/clickhouse-best-practices/SKILL.md) for an overview, or [AGENTS.md](./skills/clickhouse-best-practices/AGENTS.md) for the complete compiled guide.
**For agents:** The skill activates automatically when you work with ClickHouse—creating tables, writing queries, or designing data pipelines.
### ClickHouse Architecture Advisor
**5 decision frameworks** covering workload-aware architecture decisions for real-time ClickHouse deployments.
| Decision Area | Impact |
|---------------|--------|
| Ingestion Strategy | CRITICAL |
| Join & Enrichment Patterns | CRITICAL |
| Late-Arriving Data & Upserts | CRITICAL |
| Time-Series Partitioning | HIGH |
| Real-Time Pre-Aggregation | HIGH |
Complements `clickhouse-best-practices` by answering *when*, *why*, and *how* — not just *what*. All recommendations are explicitly classified as `official`, `derived`, or `field` guidance.
**Location:** [`skills/clickhouse-architecture-advisor/`](./skills/clickhouse-architecture-advisor/)
**For humans:** Read [SKILL.md](./skills/clickhouse-architecture-advisor/SKILL.md) for an overview, or [AGENTS.md](./skills/clickhouse-architecture-advisor/AGENTS.md) for the compiled guide.
**For agents:** The skill activates during architecture design sessions — when choosing ingestion patterns, designing time-series schemas, selecting enrichment strategies, or handling mutable state.
### ClickHouse JS Node Troubleshooting
**Troubleshooting guide** for the ClickHouse Node.js client (`@clickhouse/client`). Covers common failure modes including socket hang-up / `ECONNRESET`, Keep-Alive misconfiguration, data type mismatches, read-only user restrictions, proxy / pathname URL confusion, TLS certificate errors, compression issues, logging setup, and query parameter interpolation.
**Location:** [`skills/clickhouse-js-node-troubleshooting/`](./skills/clickhouse-js-node-troubleshooting/)
**For agents:** The skill activates when users report errors, unexpected behavior, or configuration questions involving the ClickHouse Node.js client — including vague symptoms like "my inserts keep failing" or "connection drops randomly" in a Node.js context. Not used for browser/Web client issues.
### chdb DataStore
**Pandas-compatible API** for chdb — drop-in pandas replacement backed by ClickHouse. Write `import chdb.datastore as pd` and use the same pandas API, 10-100x faster. Supports 16+ data sources (MySQL, PostgreSQL, S3, MongoDB, Iceberg, Delta Lake, etc.) with cross-source joins.
**Location:** [`skills/chdb-datastore/`](./skills/chdb-datastore/)
**For agents:** The skill activates when you analyze data with pandas-style syntax, speed up slow pandas code, query remote databases as DataFrames, or join data across different sources.
### chdb SQL
**In-process ClickHouse SQL** for Python — run SQL queries on local files, remote databases, and cloud storage without a server. Covers `chdb.query()`, Session, DB-API 2.0, parametrized queries, UDFs, streaming, and all ClickHouse table functions.
**Location:** [`skills/chdb-sql/`](./skills/chdb-sql/)
**For agents:** The skill activates when you write SQL queries against files, use ClickHouse table functions, build stateful analytical pipelines, or use advanced ClickHouse SQL features.
### Infra ClickHouse
**Local and cloud workflows** for running ClickHouse with [`clickhousectl`](https://github.com/ClickHouse/clickhousectl). The top-level `SKILL.md` is a decision tree that routes to the right reference: [`ref/local.md`](./skills/infra-clickhouse/ref/local.md) for local development (install ClickHouse, start a server, create schemas, seed data) and [`ref/cloud.md`](./skills/infra-clickhouse/ref/cloud.md) for ClickHouse Cloud (authenticate, create a service, migrate schemas, connect an application). The local workflow hands off to cloud when going to production. Supersedes `clickhousectl-local-dev` and `clickhousectl-cloud-deploy`.
**Location:** [`skills/infra-clickhouse/`](./skills/infra-clickhouse/)
**For agents:** The skill activates when a user wants to build an application with ClickHouse, set up a local development environment, deploy to production, or manage a ClickHouse Cloud service.
### Infra Postgres
**Local and cloud workflows** for running Postgres with [`clickhousectl`](https://github.com/ClickHouse/clickhousectl). The top-level `SKILL.md` is a decision tree that routes to the right reference: [`ref/local.md`](./skills/infra-postgres/ref/local.md) for local Docker-backed Postgres development (start, psql client, `.env` wiring, lifecycle) and [`ref/cloud.md`](./skills/infra-postgres/ref/cloud.md) for managed ClickHouse Cloud Postgres services (beta) — authentication, service creation, connections and TLS, runtime configuration, read replicas, failover, and point-in-time restore. [`ref/migrate.md`](./skills/infra-postgres/ref/migrate.md) migrates an existing Postgres (Neon, Supabase, RDS, ...) into ClickHouse Cloud Postgres with `pg_dump`/`pg_restore`. The local workflow hands off to cloud when going to production.
**Location:** [`skills/infra-postgres/`](./skills/infra-postgres/)
**For agents:** The skill activates when a user wants to set up a local Postgres for development, connect an application to Postgres, or create and manage a managed Postgres service in ClickHouse Cloud.
### ClickStack OTel Collector
**Step-by-step workflow** for wiring an OpenTelemetry collector into a Managed ClickStack service on ClickHouse Cloud. Covers deploying a new local collector (Docker run or Docker Compose) or configuring an existing collector, creating a dedicated ingest SQL user, sending rich synthetic telemetry, and verifying the data is visible in ClickStack.
**Location:** [`skills/clickstack-otel-collector/`](./skills/clickstack-otel-collector/)
**For agents:** The skill activates when a user wants to connect an OpenTelemetry collector to a Managed ClickStack service, send telemetry (logs, traces, metrics) into ClickStack, or verify their observability data pipeline end-to-end.
## Quick Start
After installation, your AI agent will reference these skills when:
- Creating new tables with `CREATE TABLE`
- Choosing `ORDER BY` / `PRIMARY KEY` columns
- Selecting data types for columns
- Optimizing slow queries
- Writing or tuning JOINs
- Designing data ingestion pipelines
- Handling updates or deletes
- Analyzing data with pandas-style DataStore API
- Querying files or databases with chdb SQL
- Joining data across different sources (MySQL + S3 + local files)
- Setting up a local ClickHouse development environment or deploying to ClickHouse Cloud with `clickhousectl`
- Setting up a local Postgres or a managed ClickHouse Cloud Postgres service with `clickhousectl`
- Wiring an OpenTelemetry collector into Managed ClickStack
Example prompts:
> "Create a table for storing user events with fields for user_id, event_type, properties (JSON), and timestamp"
The agent will apply relevant ClickHouse best practices rules.
> "Load this Parquet file and group by country, show top 10 by revenue"
The agent will use chdb DataStore or SQL to query the file directly.
> "Join my MySQL customers table with this local orders.parquet file"
The agent will use chdb's cross-source join capabilities.
## Supported Agents
Skills are **agent-agnostic**—the same skill works across all supported AI coding assistants:
| Agent | Config Directory |
|-------|------------------|
| [Claude Code](https://claude.ai/code) | `.claude/skills/` |
| [Cursor](https://cursor.sh) | `.cursor/skills/` |
| [Windsurf](https://codeium.com/windsurf) | `.windsurf/skills/` |
| [GitHub Copilot](https://github.com/features/copilot) | `.github/skills/` |
| [Gemini CLI](https://github.com/google-gemini/gemini-cli) | `.gemini/skills/` |
| [Cline](https://github.com/cline/cline) | `.cline/skills/` |
| [Codex](https://openai.com/codex) | `.codex/skills/` |
| [Goose](https://github.com/block/goose) | `.goose/skills/` |
| [Roo Code](https://roo.ai) | `.roo/skills/` |
| [OpenHands](https://github.com/All-Hands-AI/OpenHands) | `.openhands/skills/` |
And 13 more including Amp, Kiro CLI, Trae, Zencoder, and others.
The installer detects which agents you have by checking for their configuration directories. If an agent isn't listed, either install it first or create its config directory manually (e.g., `mkdir -p ~/.cursor`).
## License
Apache 2.0 — see [LICENSE](./LICENSE) for details.
## skills/chdb-datastore/SKILL.md
---
name: chdb-datastore
description: >-
Use when the user has tabular data (pandas DataFrame, parquet, csv,
Arrow, json) and wants to filter, group, aggregate, join, or speed
up slow pandas. Provides chDB DataStore — same pandas API,
ClickHouse engine underneath. Also handles reading from S3, MySQL,
PostgreSQL, MongoDB, ClickHouse Cloud, Iceberg, Delta Lake as
DataFrames and joining across sources.
TRIGGER when: user mentions DataFrame, parquet, csv, "fast pandas",
"speed up pandas", or cross-source DataFrame joins; user imports
`chdb.datastore` or `from datastore import DataStore`.
SKIP this skill for raw SQL syntax (use chdb-sql instead),
ClickHouse server administration, or non-Python DataStore API work.
license: Apache-2.0
compatibility: Requires Python 3.9+, macOS or Linux. pip install chdb.
metadata:
author: chdb-io
version: "4.1"
homepage: https://clickhouse.com/docs/chdb
---
# chdb DataStore — It's Just Faster Pandas
## The Key Insight
```python
# Change this:
import pandas as pd
# To this:
import chdb.datastore as pd
# Everything else stays the same.
```
DataStore is a **lazy, ClickHouse-backed pandas replacement**. Your existing pandas code works unchanged — but operations compile to optimized SQL and execute only when results are needed (e.g., `print()`, `len()`, iteration).
```bash
pip install chdb
```
## Decision Tree: Pick the Right Approach
```
1. "I have a file/database and want to analyze it with pandas"
→ DataStore.from_file() / from_mysql() / from_s3() etc.
→ See references/connectors.md
2. "I need to join data from different sources"
→ Create DataStores from each source, use .join()
→ See examples/examples.md #3-5
3. "My pandas code is too slow"
→ import chdb.datastore as pd — change one line, keep the rest
4. "I need raw SQL queries"
→ Use the chdb-sql skill instead
```
## Connect to Any Data Source — One Pattern
```python
from datastore import DataStore
# Local file (auto-detects .parquet, .csv, .json, .arrow, .orc, .avro, .tsv, .xml)
ds = DataStore.from_file("sales.parquet")
# Database
ds = DataStore.from_mysql(host="db:3306", database="shop", table="orders", user="root", password="pass")
# Cloud storage
ds = DataStore.from_s3("s3://bucket/data.parquet", nosign=True)
# URI shorthand — auto-detects source type
ds = DataStore.uri("mysql://root:pass@db:3306/shop/orders")
```
All 16+ sources and URI schemes → [connectors.md](references/connectors.md)
## After Connecting — Full Pandas API
```python
result = ds[ds["age"] > 25] # filter
result = ds[["name", "city"]] # select columns
result = ds.sort_values("revenue", ascending=False) # sort
result = ds.groupby("dept")["salary"].mean() # groupby
result = ds.assign(margin=lambda x: x["profit"] / x["revenue"]) # computed column
ds["name"].str.upper() # string accessor
ds["date"].dt.year # datetime accessor
result = ds1.join(ds2, on="id") # join
result = ds.head(10) # preview
print(ds.to_sql()) # see generated SQL
```
209 DataFrame methods supported. Full API → [api-reference.md](references/api-reference.md)
## Cross-Source Join — The Killer Feature
```python
from datastore import DataStore
customers = DataStore.from_mysql(host="db:3306", database="crm", table="customers", user="root", password="pass")
orders = DataStore.from_file("orders.parquet")
result = (orders
.join(customers, left_on="customer_id", right_on="id")
.groupby("country")
.agg({"amount": "sum", "rating": "mean"})
.sort_values("sum", ascending=False))
print(result)
```
More join examples → [examples.md](examples/examples.md)
## Writing Data
```python
source = DataStore.from_mysql(host="db:3306", database="shop", table="orders", user="root", password="pass")
target = DataStore("file", path="summary.parquet", format="Parquet")
target.insert_into("category", "total", "count").select_from(
source.groupby("category").select("category", "sum(amount) AS total", "count() AS count")
).execute()
```
## Troubleshooting
| Problem | Fix |
|---------|-----|
| `ImportError: No module named 'chdb'` | `pip install chdb` |
| `ImportError: cannot import 'DataStore'` | Use `from datastore import DataStore` or `from chdb.datastore import DataStore` |
| Database connection timeout | Include port in host: `host="db:3306"` not `host="db"` |
| Join returns empty result | Check key types match (both int or both string); use `.to_sql()` to inspect |
| Unexpected results | Call `ds.to_sql()` to see the generated SQL and debug |
| Environment check | Run `python scripts/verify_install.py` (from skill directory) |
## References
- [API Reference](references/api-reference.md) — Full DataStore method signatures
- [Connectors](references/connectors.md) — All 16+ data source connection methods
- [Examples](examples/examples.md) — 10+ runnable examples with expected output
- [Verify Install](scripts/verify_install.py) — Environment verification script
- [Official Docs](https://clickhouse.com/docs/chdb)
> Note: This skill teaches how to *use* chdb DataStore.
> For raw SQL queries, use the `chdb-sql` skill.
> For contributing to chdb source code, see CLAUDE.md in the project root.
## skills/chdb-sql/SKILL.md
---
name: chdb-sql
description: >-
Use when the user wants to run SQL — especially analytical SQL — on
local files (parquet/csv/json), URLs, S3 paths, or remote databases
(Postgres, MySQL, MongoDB, ClickHouse Cloud, Iceberg, Delta Lake)
without setting up a server. Provides chDB — embedded ClickHouse SQL
in Python with 1000+ functions, Session for stateful multi-step
pipelines, parametrized queries, and cross-source joins via `s3()`,
`mysql()`, `postgresql()`, `iceberg()`, `deltaLake()`, `remoteSecure()`
table functions.
TRIGGER when: user wants SQL on parquet/csv/files or across remote
analytical sources; uses ClickHouse SQL features (window functions,
windowFunnel, geoToH3, JSON path ops, Session, parametrized queries);
imports `chdb` or calls `chdb.query()`.
SKIP this skill for pandas-style DataFrame method-chaining (use
chdb-datastore instead) or ClickHouse server administration.
license: Apache-2.0
compatibility: Requires Python 3.9+, macOS or Linux. pip install chdb.
metadata:
author: chdb-io
version: "4.1"
homepage: https://clickhouse.com/docs/chdb
---
# chdb SQL — ClickHouse in Your Python Process
Run ClickHouse SQL directly in Python — no server needed. Query local files, remote databases, and cloud storage with full ClickHouse SQL power.
```bash
pip install chdb
```
## Decision Tree: Pick the Right API
```
1. One-off query on files or databases → chdb.query()
2. Multi-step analysis with tables → Session
3. DB-API 2.0 connection → chdb.connect()
4. Pandas-style DataFrame operations → Use chdb-datastore skill instead
```
## chdb.query() — One Line, Any Data
```python
import chdb
chdb.query("SELECT * FROM file('data.parquet', Parquet) WHERE price > 100 LIMIT 10") # local files
chdb.query("SELECT * FROM mysql('db:3306', 'shop', 'orders', 'root', 'pass')") # databases
chdb.query("SELECT * FROM s3('s3://bucket/data.parquet', NOSIGN) LIMIT 10") # cloud storage
chdb.query("SELECT * FROM deltaLake('s3://bucket/delta/table', NOSIGN) LIMIT 10") # data lakes
# Cross-source join
chdb.query("""
SELECT u.name, o.amount FROM mysql('db:3306', 'crm', 'users', 'root', 'pass') AS u
JOIN file('orders.parquet', Parquet) AS o ON u.id = o.user_id ORDER BY o.amount DESC
""")
data = {"name": ["Alice", "Bob"], "score": [95, 87]}
chdb.query("SELECT * FROM Python(data) ORDER BY score DESC") # Python data
df = chdb.query("SELECT * FROM numbers(10)", "DataFrame") # output formats
chdb.query("SELECT toDate({d:String}) + number FROM numbers({n:UInt64})",
"DataFrame", params={"d": "2025-01-01", "n": 30}) # parametrized
```
Table functions → [table-functions.md](references/table-functions.md) | SQL functions → [sql-functions.md](references/sql-functions.md) | Full API → [api-reference.md](references/api-reference.md)
## Session — Stateful Analysis Pipelines
```python
from chdb import session as chs
sess = chs.Session("./analytics_db") # persistent; Session() for in-memory
sess.query("CREATE TABLE users ENGINE=MergeTree() ORDER BY id AS SELECT * FROM mysql('db:3306','crm','users','root','pass')")
sess.query("CREATE TABLE events ENGINE=MergeTree() ORDER BY (ts,user_id) AS SELECT * FROM s3('s3://logs/events/*.parquet',NOSIGN)")
sess.query("""
SELECT u.country, count() AS cnt, uniqExact(e.user_id) AS users
FROM events e JOIN users u ON e.user_id = u.id
WHERE e.ts >= today() - 7 GROUP BY u.country ORDER BY cnt DESC
""", "Pretty").show()
sess.close()
```
## Connection API (DB-API 2.0)
```python
from chdb import dbapi
conn = dbapi.connect()
cur = conn.cursor()
cur.execute("SELECT * FROM file('data.parquet', Parquet) WHERE value > 100")
print(cur.fetchall())
cur.close()
conn.close()
```
## Troubleshooting
| Problem | Fix |
|---------|-----|
| `ImportError: No module named 'chdb'` | `pip install chdb` |
| `DB::Exception: FILE_NOT_FOUND` | Check file path; use absolute path or verify cwd |
| `DB::Exception: Unknown table function` | Check function name spelling (e.g., `deltaLake` not `deltalake`) |
| Connection refused to remote DB | Check host:port format; ensure remote DB allows connections |
| Environment check | Run `python scripts/verify_install.py` (from skill directory) |
## References
- [API Reference](references/api-reference.md) — query/Session/connect signatures
- [Table Functions](references/table-functions.md) — All ClickHouse table functions
- [SQL Functions](references/sql-functions.md) — Commonly used SQL functions
- [Examples](examples/examples.md) — 9 runnable examples with expected output
- [Official Docs](https://clickhouse.com/docs/chdb)
> Note: This skill teaches how to *use* chdb SQL.
> For pandas-style operations, use the `chdb-datastore` skill.
> For contributing to chdb source code, see CLAUDE.md in the project root.
## skills/clickhouse-architecture-advisor/SKILL.md
---
name: clickhouse-architecture-advisor
description: MUST USE when designing ClickHouse architectures, selecting between ingestion or modeling patterns, or translating best practices into workload-specific system designs. Complements clickhouse-best-practices with decision frameworks and explicit provenance labels.
license: Apache-2.0
metadata:
author: ClickHouse Inc
version: "0.1.0"
---
# ClickHouse Architecture Advisor
This skill adds workload-aware architecture decisioning on top of `clickhouse-best-practices`.
> **Official docs remain the source of truth.**
> This skill must always prefer official ClickHouse documentation when available.
## Required behavior
Before producing recommendations:
1. Identify the workload shape
- observability
- security / SIEM
- product analytics
- IoT / telemetry
- market data / financial services
- mixed OLAP with point-lookups
2. Read the relevant decision rule files in `rules/`
3. Use `mappings/doc_links.yaml` to attach official documentation
4. Classify every recommendation as:
- `official`
- `derived`
- `field`
5. Never present field guidance as official guidance
6. If a recommendation is uncertain, say so explicitly
## Provenance rules
### `official`
Use this when the recommendation is directly backed by official docs.
### `derived`
Use this when the recommendation is not stated verbatim in docs but follows logically from documented ClickHouse behavior.
### `field`
Use this only for experience-based guidance that may be situational.
When using `field`, include:
- a disclaimer that the advice is heuristic
- a relevant official doc if one partially applies
- the reason the advice depends on workload context
## Read these rule files by scenario
### Real-time ingestion design
1. `rules/decision-ingestion-strategy.md`
2. `rules/decision-real-time-preaggregation.md`
3. Relevant best-practices insert rules
### Time-series and retention design
1. `rules/decision-partitioning-timeseries.md`
2. Relevant best-practices schema partition rules
### Enrichment and dimension lookups
1. `rules/decision-join-enrichment.md`
2. Relevant best-practices query join rules
### Mutable state / late-arriving events
1. `rules/decision-late-arriving-upserts.md`
2. Relevant best-practices mutation avoidance rules
## Output format
Structure responses like this:
```markdown
## Workload Summary
- workload:
- latency target:
- data shape:
- primary query patterns:
- operational constraints:
## Key Decisions
- ...
- ...
## Recommendations
### <Recommendation title>
**What**
...
**Why**
...
**How**
...
**Category**
official | derived | field
**Confidence**
high | medium | heuristic
**Source**
- doc link(s)
**Validation**
- concrete SQL, metric, or smoke test
```
## Architecture-specific guidance
Prefer decision frameworks over generic advice. Good responses should:
- explain tradeoffs
- identify the likely operating bottleneck
- separate immediate actions from structural redesign
- provide target architecture patterns, not just isolated settings
## Full reference
See `AGENTS.md` for the compiled version and `examples/` for sample outputs.
## skills/clickhouse-best-practices/SKILL.md
---
name: clickhouse-best-practices
description: MUST USE when reviewing ClickHouse schemas, queries, or configurations. Contains 31 rules that MUST be checked before providing recommendations. Always read relevant rule files and cite specific rules in responses.
license: Apache-2.0
metadata:
author: ClickHouse Inc
version: "0.4.0"
---
# ClickHouse Best Practices
Comprehensive guidance for ClickHouse covering schema design, query optimization, data ingestion, and AI agent connectivity. Contains 31 rules across 4 main categories (schema, query, insert, agent), prioritized by impact.
> **Official docs:** [ClickHouse Best Practices](https://clickhouse.com/docs/best-practices)
## IMPORTANT: How to Apply This Skill
**Before answering ClickHouse questions, follow this priority order:**
1. **Check for applicable rules** in the `rules/` directory
2. **If rules exist:** Apply them and cite them in your response using "Per `rule-name`..."
3. **If no rule exists:** Use the LLM's ClickHouse knowledge or search documentation
4. **If uncertain:** Use web search for current best practices
5. **Always cite your source:** rule name, "general ClickHouse guidance", or URL
**Why rules take priority:** ClickHouse has specific behaviors (columnar storage, sparse indexes, merge tree mechanics) where general database intuition can be misleading. The rules encode validated, ClickHouse-specific guidance.
---
## Agent Connectivity & Query Workflow
Before querying ClickHouse, agents must establish a connection and follow the discovery workflow:
1. `rules/agent-connect-mcp.md` - Connection setup (MCP + CLI), credential discovery, output format selection
2. `rules/agent-discovery-schema.md` - **CRITICAL**: 7-step schema discovery workflow
3. `rules/agent-query-safety.md` - **CRITICAL**: LIMIT, timeouts, progressive exploration
**Every agent session should follow this sequence:**
1. **Connect** — establish connection via MCP or CLI (see `agent-connect-mcp`)
2. **Discover** — databases → tables → columns + comments → sort keys → skip indexes → sample → EXPLAIN
3. **Plan** — use sort key and skip index knowledge to write efficient WHERE clauses
4. **Execute** — run queries with LIMIT and timeouts
5. **Recover** — on timeout/memory errors, narrow filters and retry (see `agent-query-safety`)
### Subagent architecture notes
If your system dispatches ClickHouse tasks to specialized subagents:
- **Schema discovery + query execution**: any model — the steps are procedural
- **EXPLAIN analysis + query optimization**: benefits from mid-tier reasoning
- **Schema design review against all 28 rules**: benefits from mid-tier reasoning
---
## Review Procedures
### For Schema Reviews (CREATE TABLE, ALTER TABLE)
**Read these rule files in order:**
1. `rules/schema-pk-plan-before-creation.md` - ORDER BY is immutable
2. `rules/schema-pk-cardinality-order.md` - Column ordering in keys
3. `rules/schema-pk-prioritize-filters.md` - Filter column inclusion
4. `rules/schema-types-native-types.md` - Proper type selection
5. `rules/schema-types-minimize-bitwidth.md` - Numeric type sizing
6. `rules/schema-types-lowcardinality.md` - LowCardinality usage
7. `rules/schema-types-avoid-nullable.md` - Nullable vs DEFAULT
8. `rules/schema-partition-low-cardinality.md` - Partition count limits
9. `rules/schema-partition-lifecycle.md` - Partitioning purpose
**Check for:**
- [ ] PRIMARY KEY / ORDER BY column order (low-to-high cardinality)
- [ ] Data types match actual data ranges
- [ ] LowCardinality applied to appropriate string columns
- [ ] Partition key cardinality bounded (100-1,000 values)
- [ ] ReplacingMergeTree has version column if used
### For Query Reviews (SELECT, JOIN, aggregations)
**Read these rule files:**
1. `rules/query-join-choose-algorithm.md` - Algorithm selection
2. `rules/query-join-filter-before.md` - Pre-join filtering
3. `rules/query-join-use-any.md` - ANY vs regular JOIN
4. `rules/query-index-skipping-indices.md` - Secondary index usage
5. `rules/schema-pk-filter-on-orderby.md` - Filter alignment with ORDER BY
**Check for:**
- [ ] Filters use ORDER BY prefix columns
- [ ] JOINs filter tables before joining (not after)
- [ ] Correct JOIN algorithm for table sizes
- [ ] Skipping indices for non-ORDER BY filter columns
### For Insert Strategy Reviews (data ingestion, updates, deletes)
**Read these rule files:**
1. `rules/insert-batch-size.md` - Batch sizing requirements
2. `rules/insert-mutation-avoid-update.md` - UPDATE alternatives
3. `rules/insert-mutation-avoid-delete.md` - DELETE alternatives
4. `rules/insert-async-small-batches.md` - Async insert usage
5. `rules/insert-optimize-avoid-final.md` - OPTIMIZE TABLE risks
**Check for:**
- [ ] Batch size 10K-100K rows per INSERT
- [ ] No ALTER TABLE UPDATE for frequent changes
- [ ] ReplacingMergeTree or CollapsingMergeTree for update patterns
- [ ] Async inserts enabled for high-frequency small batches
---
## Output Format
Structure your response as follows:
```
## Rules Checked
- `rule-name-1` - Compliant / Violation found
- `rule-name-2` - Compliant / Violation found
...
## Findings
### Violations
- **`rule-name`**: Description of the issue
- Current: [what the code does]
- Required: [what it should do]
- Fix: [specific correction]
### Compliant
- `rule-name`: Brief note on why it's correct
## Recommendations
[Prioritized list of changes, citing rules]
```
---
## Rule Categories by Priority
| Priority | Category | Impact | Prefix | Rule Count |
|----------|----------|--------|--------|------------|
| 1 | Primary Key Selection | CRITICAL | `schema-pk-` | 4 |
| 2 | Data Type Selection | CRITICAL | `schema-types-` | 5 |
| 3 | JOIN Optimization | CRITICAL | `query-join-` | 5 |
| 4 | Insert Batching | CRITICAL | `insert-batch-` | 1 |
| 5 | Mutation Avoidance | CRITICAL | `insert-mutation-` | 2 |
| 6 | Partitioning Strategy | HIGH | `schema-partition-` | 4 |
| 7 | Skipping Indices | HIGH | `query-index-` | 1 |
| 8 | Materialized Views | HIGH | `query-mv-` | 2 |
| 9 | Async Inserts | HIGH | `insert-async-` | 2 |
| 10 | OPTIMIZE Avoidance | HIGH | `insert-optimize-` | 1 |
| 11 | JSON Usage | MEDIUM | `schema-json-` | 1 |
| 12 | Agent Schema Discovery | CRITICAL | `agent-discovery-` | 1 |
| 13 | Agent Query Safety | CRITICAL | `agent-query-` | 1 |
| 14 | Agent Connectivity + Formats | HIGH | `agent-connect-` | 1 |
---
## Quick Reference
### Schema Design - Primary Key (CRITICAL)
- `schema-pk-plan-before-creation` - Plan ORDER BY before table creation (immutable)
- `schema-pk-cardinality-order` - Order columns low-to-high cardinality
- `schema-pk-prioritize-filters` - Include frequently filtered columns
- `schema-pk-filter-on-orderby` - Query filters must use ORDER BY prefix
### Schema Design - Data Types (CRITICAL)
- `schema-types-native-types` - Use native types, not String for everything
- `schema-types-minimize-bitwidth` - Use smallest numeric type that fits
- `schema-types-lowcardinality` - LowCardinality for <10K unique strings
- `schema-types-enum` - Enum for finite value sets with validation
- `schema-types-avoid-nullable` - Avoid Nullable; use DEFAULT instead
### Schema Design - Partitioning (HIGH)
- `schema-partition-low-cardinality` - Keep partition count 100-1,000
- `schema-partition-lifecycle` - Use partitioning for data lifecycle, not queries
- `schema-partition-query-tradeoffs` - Understand partition pruning trade-offs
- `schema-partition-start-without` - Consider starting without partitioning
### Schema Design - JSON (MEDIUM)
- `schema-json-when-to-use` - JSON for dynamic schemas; typed columns for known
### Query Optimization - JOINs (CRITICAL)
- `query-join-choose-algorithm` - Select algorithm based on table sizes
- `query-join-use-any` - ANY JOIN when only one match needed
- `query-join-filter-before` - Filter tables before joining
- `query-join-consider-alternatives` - Dictionaries/denormalization vs JOIN
- `query-join-null-handling` - join_use_nulls=0 for default values
### Query Optimization - Indices (HIGH)
- `query-index-skipping-indices` - Skipping indices for non-ORDER BY filters
### Query Optimization - Materialized Views (HIGH)
- `query-mv-incremental` - Incremental MVs for real-time aggregations
- `query-mv-refreshable` - Refreshable MVs for complex joins
### Insert Strategy - Batching (CRITICAL)
- `insert-batch-size` - Batch 10K-100K rows per INSERT
### Insert Strategy - Async (HIGH)
- `insert-async-small-batches` - Async inserts for high-frequency small batches
- `insert-format-native` - Native format for best performance
### Insert Strategy - Mutations (CRITICAL)
- `insert-mutation-avoid-update` - ReplacingMergeTree instead of ALTER UPDATE
- `insert-mutation-avoid-delete` - Lightweight DELETE or DROP PARTITION
### Insert Strategy - Optimization (HIGH)
- `insert-optimize-avoid-final` - Let background merges work
### Agent Integration - Discovery (CRITICAL)
- `agent-discovery-schema` - Always discover schema before querying
### Agent Integration - Safety (CRITICAL)
- `agent-query-safety` - LIMIT, timeouts, progressive exploration
### Agent Integration - Connectivity + Formats (HIGH)
- `agent-connect-mcp` - MCP + CLI setup, credential discovery, output format selection
---
## When to Apply
This skill activates when you encounter:
- AI agent connecting to ClickHouse (MCP, CLI, HTTP)
- Agent workflow design for ClickHouse
- Schema discovery or exploration requests
- `CREATE TABLE` statements
- `ALTER TABLE` modifications
- `ORDER BY` or `PRIMARY KEY` discussions
- Data type selection questions
- Slow query troubleshooting
- JOIN optimization requests
- Data ingestion pipeline design
- Update/delete strategy questions
- ReplacingMergeTree or other specialized engine usage
- Partitioning strategy decisions
---
## Rule File Structure
Each rule file in `rules/` contains:
- **YAML frontmatter**: title, impact level, tags
- **Brief explanation**: Why this rule matters
- **Incorrect example**: Anti-pattern with explanation
- **Correct example**: Best practice with explanation
- **Additional context**: Trade-offs, when to apply, references
---
## Full Compiled Document
For the complete guide with all rules expanded inline: `AGENTS.md`
Use `AGENTS.md` when you need to check multiple rules quickly without reading individual files.
## skills/clickhouse-js-node-coding/SKILL.md
---
name: clickhouse-js-node-coding
description: >
Write idiomatic application code with the ClickHouse Node.js client
(`@clickhouse/client`). Use this skill whenever a user is *building* against
the Node.js client — configuring the client, pinging, inserting rows in JSON
or raw formats, selecting and parsing results, binding query parameters,
managing sessions and temporary tables, working with data types or
customizing JSON parsing. Do NOT use for browser/Web client code.
---
# ClickHouse Node.js Client — Coding
Reference: https://clickhouse.com/docs/integrations/javascript
> **⚠️ Node.js runtime only.** This skill covers the `@clickhouse/client`
> package running in a **Node.js runtime** exclusively — including **Next.js
> Node runtime** API routes, React Server Components, Server Actions, and
> standard Node.js processes. Do **not** apply this skill to browser client
> components, Web Workers, **Next.js Edge runtime**, Cloudflare Workers, or
> any usage of `@clickhouse/client-web`. For browser/edge environments, the
> correct package is `@clickhouse/client-web`.
---
## How to Use This Skill
1. **Match the user's intent** to a row in the Task Index below and read the
corresponding reference file before writing code. After reading it, scan any
**Answer checklist** in that reference and make sure the final answer covers
each relevant item; those checklists capture details users usually need but
are easy to omit in short answers.
2. **Always import from `@clickhouse/client`** (never `@clickhouse/client-web`)
and create a client with `createClient({ url })` or rely on
supported defaults when appropriate. Close it with `await client.close()`
preferably when it's no longer needed or during graceful shutdown for global resources.
3. **Prefer `JSONEachRow` for typical row inserts/selects** unless the user
has already chosen another format or is streaming raw bytes (CSV / TSV /
Parquet — see `examples/node/performance/`).
**Note on `clickhouse_settings`:** settings passed to `createClient` are
defaults for every request; they can be overridden per-call by passing
`clickhouse_settings` directly to `insert()`, `query()`, or `command()`.
Always mention this when the user configures settings at the client level.
4. **Always use `query_params` for user-supplied values** — never template-
literal-interpolate them into SQL. See `reference/query-parameters.md`.
**When answering a parameter-binding question, your response must
explicitly name template-literal interpolation as a "SQL injection
risk"** — even when the user only asked about syntax and did not raise
security. The literal phrase "SQL injection" needs to appear; this is
the most common mistake from PostgreSQL/MySQL users and the security
framing is part of the correct answer, not an optional aside.
5. **Pick the right method for the job:**
- `client.insert()` — write rows.
- `client.query()` + `resultSet.json()` / `.text()` / `.stream()` — read
rows that return data.
- `client.command()` — DDL and other statements that don't return rows
(`CREATE`, `DROP`, `TRUNCATE`, `ALTER`, `SET` in a session, etc.).
- `client.exec()` — when you need the raw response stream of an arbitrary
statement (rare in coding scenarios).
- `client.ping()` — health check; returns `{ success, error? }`, never
throws on connection failure.
6. **Note version constraints** when relevant. Examples:
- `pathname` config option: client `>= 1.0.0`.
- `BigInt` values in `query_params`: client `>= 1.15.0`.
- `TupleParam` and JS `Map` in `query_params`: client `>= 1.9.0`.
- Configurable `json.parse` / `json.stringify`: client `>= 1.14.0`.
- `Time` / `Time64` data types: ClickHouse server `>= 25.6`.
- `QBit` data type: ClickHouse server `>= 25.10` (GA on `26.x`).
- `Dynamic` / `Variant` / new `JSON` types: ClickHouse server `>= 24.1` /
`24.5` / `24.8` (no longer experimental since `25.3`).
---
## Task Index
Identify the user's task and read the matching reference file.
| Task | Triggers / symptoms | Reference file |
| -------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------- |
| **Configure / connect the client** | Building a `createClient` call, URL parameters, `clickhouse_settings`, default format, custom HTTP headers | `reference/client-configuration.md` |
| **Compress requests / responses** | `compression`, gzip vs `zstd`, `{ codec }` option shape, Node version requirements, web limitations