# ClickHouse MCP

```json
{
  "name": "ClickHouse MCP",
  "slug": "clickhouse_mcp",
  "url": "https://composio.dev/toolkits/clickhouse_mcp",
  "markdown_url": "https://composio.dev/toolkits/clickhouse_mcp.md",
  "logo_url": "https://logos.composio.dev/api/clickhouse_mcp",
  "categories": [
    "analytics & data"
  ],
  "is_composio_managed": false,
  "updated_at": "2026-08-24T07:21:03.937Z"
}
```

![ClickHouse MCP logo](https://logos.composio.dev/api/clickhouse_mcp)

## Description

Securely connect your AI agents and chatbots (Claude, ChatGPT, Cursor, etc) with ClickHouse MCP or direct API to run SQL queries, aggregate observability metrics, filter logs, and export query results through natural language.

## Summary

ClickHouse MCP is ClickHouse Cloud's managed observability query service via the ClickStack MCP server.
Use it to run fast analytical queries against observability data with managed access.

## Categories

- analytics & data

## Toolkit Details

- Tools: 32

## Images

- Logo: https://logos.composio.dev/api/clickhouse_mcp

## Authentication

- **Dcr Oauth**
  - Type: `custom`
  - Description: Dcr Oauth authentication for ClickHouse MCP.
  - Setup:
    - Configure Dcr Oauth credentials for ClickHouse MCP.
    - Use the credentials when creating an auth config in Composio.

## Suggested Prompts

- List top 10 slow queries last hour
- Aggregate error rates by service today
- Create materialized view for cpu metrics

## Supported Tools

| Tool slug | Name | Description |
|---|---|---|
| `CLICKHOUSE_MCP_CLICKSTACK_DELETE_DASHBOARD` | Clickstack delete dashboard | Permanently delete a dashboard by ID. Also removes any alerts attached to its tiles. Use clickstack_get_dashboard (without an ID) to list available dashboard IDs. |
| `CLICKHOUSE_MCP_CLICKSTACK_DELETE_SOURCE` | Clickstack delete source | Permanently delete a data source by ID. Other sources may reference it (e.g. a trace source linked to a log source) — those links are left dangling, so check dependencies first. Use clickstack_list_sources to find available source IDs. |
| `CLICKHOUSE_MCP_CLICKSTACK_DELETE_WEBHOOK` | Clickstack delete webhook | Permanently delete a webhook by ID. Blocked while any alert still references it — reassign or delete those alerts first. Use clickstack_get_webhook to list available webhook IDs. |
| `CLICKHOUSE_MCP_CLICKSTACK_DESCRIBE_METRIC` | Clickstack describe metric | DRILL-DOWN: Use after clickstack_list_metrics (or after a clickstack_describe_source sample) to get attribute keys, sampled values, unit, and description for a specific (metricName, kind) pair. Attribute keys vary per metric — not per source — so always call this before clickstack_timeseries / clickstack_table for any metric you've never queried. REQUIRES `kind` — pass the gauge/sum/histogram/exponential histogram/summary value emitted alongside the metric name by clickstack_list_metrics or clickstack_describe_source. A metric name can legitimately live in more than one kind (e.g. "container.cpu.usage" appears in both gauge and sum); call this tool once per kind you care about. kind:"summary" is accepted for discovery (attribute keys, sampled values, unit, description), but summary metrics cannot be queried with clickstack_timeseries / clickstack_table — use clickstack_sql against the table in the source's metricTables.summary. attributeValuesMeta on each kind reports sampledKeys (queried for values) and truncatedKeys (skipped by the per-call sampling cap) — a key in truncatedKeys was never queried, so query it directly if you need its values. Workflow: clickstack_list_sources → clickstack_list_metrics → clickstack_describe_metric → clickstack_timeseries\|clickstack_table. |
| `CLICKHOUSE_MCP_CLICKSTACK_DESCRIBE_SOURCE` | Clickstack describe source | CALL THIS BEFORE WRITING QUERIES — prevents unknown-column errors. Returns the full column schema, map-attribute keys, and sampled low-cardinality values (e.g. SeverityText, StatusCode, ServiceName) for a single data source. Workflow: call clickstack_list_sources first to get source IDs, then call this tool for each source you plan to query. Returns: - columns[]: column name, ClickHouse type, and JS type - mapAttributeKeys: discovered keys in Map columns (e.g. SpanAttributes, ResourceAttributes) - lowCardinalityValues: sampled values for LowCardinality(String) columns (SeverityText, StatusCode, ServiceName, etc.) — use these in filters instead of guessing - mapAttributeValues: sampled top values for the most common map attribute keys (e.g. ResourceAttributes['service.name'] top values) — requires rollup tables - requiredSourceFilters: when present, every query against this source MUST pass `sourceFilters` for each listed column. Sample values for each are returned as `sourceFilterValues` (capped); use clickstack_get_source_filter_values for the full paginated list. Cost: one describe call prevents 3–5 exploratory queries against non-existent columns. |
| `CLICKHOUSE_MCP_CLICKSTACK_EMERGING_SIGNALS` | Clickstack emerging signals | Detect what is NEW or GONE between an earlier baseline window and a current window — log/event patterns that emerged, ramped up, or stopped. This answers "what changed / what is novel?" — NOT "what attribute value differs?". USE THIS for status checks, health reports, post-deploy diffs, and any "call out anything new or worth a closer look" question. It mines event patterns (Drain) in BOTH windows and set-differences them: - emerging: patterns whose share of the window is >= minShareRatio× higher now than in baseline (includes brand-new templates absent from baseline) - disappeared: patterns that were common in baseline but >= minShareRatio× rarer (or absent) now WHY NOT clickstack_event_deltas: event_deltas compares ATTRIBUTE VALUE DISTRIBUTIONS between two row groups (e.g. "region shifted toward eu-west"). It CANNOT surface a brand-new log template or a new endpoint that simply did not exist before — a novel signal has no baseline distribution to shift. Use emerging_signals for novelty/emergence (set membership over time); use event_deltas for "what is different about these rows" (distribution shift within a shared population). Requires sourceId — call clickstack_list_sources / clickstack_describe_source first. Provide two non-overlapping windows: the current window to characterize and an earlier baseline. Typically baselineEndTime == currentStartTime. CALIBRATION: routine variance is not novelty. A pattern that merely wobbled in volume is NOT emerging; only report shifts past minShareRatio. An empty emerging list is a valid, informative answer ("nothing novel") — do not manufacture findings. |
| `CLICKHOUSE_MCP_CLICKSTACK_EVENT_DELTAS` | Clickstack event deltas | Rank the properties of two row groups (logs or trace spans) by how much their value distributions differ. Same algorithm as the in-app Event Deltas view (DBDeltaChart). High-cardinality fields (IDs, request IDs, timestamps) are filtered out by default so the ranking surfaces the categorical attributes that actually separate the two groups. Score is computed after normalizing each group to 100% so it's robust to different group sizes. USE THIS INSTEAD OF MANUAL PIVOTS. When two row sets visibly differ and you don't know which attribute(s) separate them, the standard agentic move is to run a GROUP BY for each candidate attribute and compare. event_deltas does this for ALL attributes in one call, ranked by signal strength — usually 1 call instead of 5–20. NARROW the target to the specific outlier rows. A broad target mostly contains healthy rows, so the ranking comes back noisy. The narrower target — the sharper the ranking. TYPICAL USES (any source — logs or traces): - Slow vs fast spans (MOST COMMON for latency triage): target = {where: AND Duration > }, baseline = {where: AND Duration } Scope BOTH to the same operation/endpoint via ``; the ranked attribute(s) are then what discriminates the slow invocations of THAT operation from the fast ones. Skipping the op-filter gives a noisy "which operation is slow" answer instead of "which sub-set of one operation is slow". - Before vs after a deploy / incident onset: target = {window: after onset}, baseline = {window: before onset} - Failing vs succeeding rows: target = {where: }, baseline = {where: } - One service / endpoint vs the rest: target = {where: ServiceName=X}, baseline = {where: ServiceName != X} Any pair of row sets over the same source works — the tool just asks "what is statistically different about target vs baseline". WHEN NOT TO USE: when the question is already known to be about a specific attribute (use clickstack_table groupBy), when you want raw rows (use clickstack_search), or when you need a time-series shape (use clickstack_timeseries). PREFER THIS over clickstack_sql. Only drop to raw SQL for things the builder tools cannot express — JOINs, sub-queries, CTEs, window functions, tables not registered as sources, or summary-type metrics (the metricTables.summary table on a metric source, which the builder tools cannot query). OUTPUT SHAPE: an array of properties, each with rank, key, score, semanticBoost (true for well-known OTel attrs like service.name / http.method / error.type / status), targetCount and baselineCount (sample sizes), and topDeltas — the values whose share shifted most, each with `value`, `targetPct`, `baselinePct`, and `diffPct`. topDeltas already contains the full per-value comparison for that attribute, so there is no separate target/baseline distribution to consult. IMPORTANT — DO NOT STOP AT RANK 1. The top ~5 ranked properties are often INDEPENDENT axes that together explain the population shift (e.g. a regression localized on the intersection of two attributes). Scan down the list until the score visibly drops to noise level; any property well above that floor is a candidate axis to combine with the others. |
| `CLICKHOUSE_MCP_CLICKSTACK_EVENT_PATTERNS` | Clickstack event patterns | Discover the most common log messages and event patterns. Samples random events, clusters them using the Drain algorithm, and returns patterns sorted by frequency with estimated counts and time trends. PREFER THIS TOOL over clickstack_search or clickstack_table when the goal is to understand what kinds of messages, errors, or events exist — e.g. "sample logs", "what errors are happening", "show me common messages", "what does this service log". It returns frequency-ranked patterns instead of raw rows, giving a much better overview. Also use when asked about "top patterns", "common logs", "noisy services", "recurring messages", or log noise analysis. Each pattern includes a "whereSnippet" — use it as the "where" parameter in a follow-up clickstack_search call to browse matching raw events. Requires sourceId — call clickstack_list_sources then clickstack_describe_source first. PREFER THIS over clickstack_sql. Only drop to raw SQL for things the builder tools cannot express — JOINs, sub-queries, CTEs, window functions, tables not registered as sources, or summary-type metrics (the metricTables.summary table on a metric source, which the builder tools cannot query). When to use which tool: - clickstack_event_patterns: clustering / recurring shapes / noise analysis - clickstack_search: raw individual rows - clickstack_table: aggregated metrics / counts / top-N |
| `CLICKHOUSE_MCP_CLICKSTACK_GET_ALERT` | Clickstack get alert | Without an ID: list all alerts as a high-level summary (id, name, state, source, interval). Optionally filter by state (e.g. state="ALERT" for firing alerts). With an ID: get full alert detail including configuration and recent evaluation history. |
| `CLICKHOUSE_MCP_CLICKSTACK_GET_DASHBOARD` | Clickstack get dashboard | Without an ID: list all dashboards (returns IDs, names, tags). With an ID: get full dashboard detail including all tiles and configuration. |
| `CLICKHOUSE_MCP_CLICKSTACK_GET_DASHBOARD_TILE` | Clickstack get dashboard tile | Retrieve a single tile from a dashboard by tileId. Useful for inspecting one tile without loading the full dashboard. Use clickstack_get_dashboard (without an ID) to list dashboards, then clickstack_get_dashboard (with an ID) to see all tile IDs. |
| `CLICKHOUSE_MCP_CLICKSTACK_GET_SAVED_SEARCH` | Clickstack get saved search | Without an ID: list all saved searches as a high-level summary (id, name, tags). With an ID: get full saved search detail including query, source, filters, and configuration. |
| `CLICKHOUSE_MCP_CLICKSTACK_GET_SOURCE_FILTER_VALUES` | Clickstack get source filter values | List the available values for the required source filter columns on a single source. Use this BEFORE calling any query tool against a source whose configuration declares `requiredSourceFilters`. ONLY use this for sources that have `requiredSourceFilters`. Every such source requires values for every declared column on every query call, and this tool tells you which values exist. Workflow: 1. clickstack_list_sources or clickstack_describe_source to see whether a source declares requiredSourceFilters and which columns it requires. 2. clickstack_get_source_filter_values to fetch the values for those columns. 3. Call your query tool with the sourceFilters parameter set, e.g. sourceFilters: { "": ["val1"], "": ["val2"] } CROSS-FILTER PRUNING: pass `selectedFilters` with the values you have already chosen for some columns to narrow the option list for the others. PAGINATION: each column reports `totalAvailable`, `truncated`, and (when truncated) `nextOffset`. Use `limit` + `offset` to step through high-cardinality columns instead of pulling everything at once. |
| `CLICKHOUSE_MCP_CLICKSTACK_GET_WEBHOOK` | Clickstack get webhook | List available webhook destinations (id, name, service type). Use the returned id as the webhookId when creating alerts with clickstack_save_alert. |
| `CLICKHOUSE_MCP_CLICKSTACK_LIST_METRICS` | Clickstack list metrics | DISCOVERY: Use this after clickstack_describe_source when you need more metric names than the per-kind sample shows, or when you want to narrow by kind / name pattern / time window. Returns paginated metric names per kind (gauge/sum/histogram/exponential histogram/summary) with optional unit and description (when the OTel-default columns are present). Pass the returned `nextCursor` back unchanged to fetch the next page. Summary metrics are listed for discovery only — they cannot be passed to clickstack_timeseries / clickstack_table; query them with clickstack_sql against the table in the source's metricTables.summary. Workflow: clickstack_list_sources → clickstack_describe_source → clickstack_list_metrics → clickstack_describe_metric → clickstack_timeseries\|clickstack_table. |
| `CLICKHOUSE_MCP_CLICKSTACK_LIST_SOURCES` | Clickstack list sources | List all data sources (logs, metrics, traces) and database connections available to this team. Returns source IDs, names, kinds, and connection IDs as a lightweight catalog. NEXT STEP: After identifying the source(s) you need, call clickstack_describe_source with the sourceId to get the full column schema, attribute keys, and sampled values. This two-step approach avoids fetching expensive schema details for sources you do not need. REQUIRED SOURCE FILTERS: when a source has `requiredSourceFilters`, every query against it MUST supply values for every column in `requiredSourceFilters` via the `sourceFilters` parameter. Call clickstack_get_source_filter_values to discover the available values, or check the sampled `sourceFilterValues` returned by clickstack_describe_source. NOTE: For most queries, use source IDs with clickstack_timeseries, clickstack_table, clickstack_search, or clickstack_event_patterns. Connection IDs are only needed for clickstack_sql (raw ClickHouse SQL). Metric sources may list a "summary" table in metricTables. Summary metrics are not supported by the builder tools — use clickstack_sql to look at them. |
| `CLICKHOUSE_MCP_CLICKSTACK_LIST_TEAMS` | Clickstack list teams | List all teams the current user belongs to and identify which team is active for this session. Use this to discover available teams when the user works across multiple teams. To switch teams, the MCP client must include the `x-hdx-team` HTTP header set to the target team ID on subsequent requests. The header is validated against the user’s team memberships — requests for teams the user does not belong to will be rejected. |
| `CLICKHOUSE_MCP_CLICKSTACK_PATCH_DASHBOARD` | Clickstack patch dashboard | Make targeted updates to a dashboard without resubmitting the full object. You can update dashboard-level fields (name, tags) and/or replace a single tile by tileId — all in one call. Unmentioned tiles and fields are preserved. Use clickstack_get_dashboard_tile to inspect a tile before patching it. IMPORTANT: After patching a tile, run clickstack_query_tile to confirm the query still works. |
| `CLICKHOUSE_MCP_CLICKSTACK_QUERY_TILE` | Clickstack query tile | Execute the query for a specific tile on an existing dashboard. Useful for validating that a tile returns data or for spot-checking results without rebuilding the query from scratch. Use clickstack_get_dashboard with an ID to find tile IDs. SOURCE FILTERS: when the tile reads a source that declares `requiredSourceFilters` (core filters) but carries no tile-level `sourceFilters` of its own (which is the recommended default), pass `sourceFilters` here to stand in for the dropdown selection so the validation query has values to run with. The values you pass are used only for this query and are NOT persisted on the tile. If the tile already pins its own tile-level `sourceFilters`, do NOT pass `sourceFilters` here: omit it so the validation runs with the tile's own values. Anything you pass here takes precedence over the tile-level values (the two are never merged), so passing a different set would validate something other than what the tile will actually use. |
| `CLICKHOUSE_MCP_CLICKSTACK_QUERY_TILES` | Clickstack query tiles | Run the queries for many tiles of a dashboard in ONE call and return a compact per-tile success/failure summary. This is the efficient way to validate an entire dashboard after clickstack_save_dashboard — prefer it over calling clickstack_query_tile once per tile. Accepts a dashboard ID and an optional list of tile IDs. Markdown tiles are excluded by default; a markdown tile passed explicitly in tileIds is returned with status "skipped". A tile that fails is reported inline with its error and the overall call still succeeds, so one broken tile does not hide the rest, and unrecognized tile IDs come back as unknownTileIds rather than failing. At most 50 tiles run per call; any beyond that are returned as unrunTileIds — call again with those as tileIds to run the remainder. Drill into a specific failing tile with clickstack_query_tile. |
| `CLICKHOUSE_MCP_CLICKSTACK_SAVE_ALERT` | Clickstack save alert | Create a new alert (omit id) or update an existing one (provide id). Alerts monitor a saved search or dashboard tile and fire when the metric crosses a threshold. A webhook notification channel is required. |
| `CLICKHOUSE_MCP_CLICKSTACK_SAVE_DASHBOARD` | Clickstack save dashboard | Create a new dashboard (omit id) or update an existing one (provide id). Call clickstack_list_sources first to obtain sourceId and connectionId values. IMPORTANT: After saving a dashboard, always run clickstack_query_tiles to validate every tile in one call (or clickstack_query_tile for a single tile) and confirm the queries work and return expected data. Tiles can silently fail due to incorrect filter syntax, missing attributes, or wrong column names. TIP: To update a single tile without resubmitting all tiles, use clickstack_patch_dashboard instead. |
| `CLICKHOUSE_MCP_CLICKSTACK_SAVE_SAVED_SEARCH` | Clickstack save saved search | Create a new saved search (omit id) or update an existing one (provide id). A saved search stores a reusable query against a data source. Use clickstack_list_sources to find the sourceId. |
| `CLICKHOUSE_MCP_CLICKSTACK_SAVE_SOURCE` | Clickstack save source | Create a new data source (omit id) or update an existing one (provide id) so shipped telemetry becomes queryable. Update is a full replace of the source definition. Required for all kinds: kind, name, connection, databaseName, tableName, timestampValueExpression. Kind-specific requirements: log & trace need defaultTableSelectExpression; trace also needs durationExpression, traceIdExpression, spanIdExpression, parentSpanIdExpression, spanNameExpression, spanKindExpression; session needs traceSourceId; metric needs metricTables and resourceAttributesExpression. Get connection and source IDs from clickstack_list_sources. |
| `CLICKHOUSE_MCP_CLICKSTACK_SAVE_WEBHOOK` | Clickstack save webhook | Create a new webhook (omit id) or update an existing one (provide id). Use the returned id as the webhookId when creating alerts with clickstack_save_alert. Required: name, service (slack, generic, or incidentio), and url. For the slack service the url host must end in slack.com and headers/queryParams/body are not supported. On update, readable fields (description, body) are a full replace while write-only headers/queryParams are preserved when omitted (send {} to clear); changing the destination clears omitted write-only secrets. |
| `CLICKHOUSE_MCP_CLICKSTACK_SEARCH` | Clickstack search | Browse individual log/event/trace rows. Use this when you need to see raw events, investigate specific log lines, or drill into individual records matching a filter. PREFER THIS over clickstack_sql. Only drop to raw SQL for things the builder tools cannot express — JOINs, sub-queries, CTEs, window functions, tables not registered as sources, or summary-type metrics (the metricTables.summary table on a metric source, which the builder tools cannot query). Requires sourceId — call clickstack_list_sources then clickstack_describe_source first. For aggregated metrics, use clickstack_table instead. For pattern discovery, use clickstack_event_patterns instead. Set denoise=true to automatically filter out high-frequency repetitive patterns, surfacing only unusual or interesting events. Column naming: top-level columns are PascalCase (Duration, StatusCode). Map attributes use bracket syntax: SpanAttributes['http.method']. SOURCE FILTERS: when the source declares `requiredSourceFilters` (see clickstack_describe_source / clickstack_list_sources), you MUST pass `sourceFilters` with at least one value for every required column. |
| `CLICKHOUSE_MCP_CLICKSTACK_SEARCH_DASHBOARDS` | Clickstack search dashboards | Search dashboards by name and/or tags. Returns matching dashboards with their IDs, names, and tags. More targeted than clickstack_get_dashboard (which lists all dashboards). At least one of query or tags must be provided. |
| `CLICKHOUSE_MCP_CLICKSTACK_SQL` | Clickstack sql | Execute raw ClickHouse SQL. LAST-RESORT TOOL — do NOT reach for this first. Default to the builder tools for querying; they are more reliable and produce richer, structured results: • clickstack_table — aggregations, top-N, single-value KPIs, breakdowns • clickstack_timeseries — trends / metrics over time • clickstack_search — browsing individual log/trace rows • clickstack_event_patterns — recurring log/event pattern discovery • clickstack_event_deltas — attributes that differ between two row groups • clickstack_emerging_signals — patterns new or gone vs a baseline window • clickstack_trace_waterfall — one trace as a parent/child span tree • clickstack_trace_top_time_consuming_operations — slowest child operations in a trace ONLY use raw SQL when the query genuinely cannot be expressed by a builder tool — i.e. it requires JOINs, sub-queries, CTEs, window functions, tables not registered as sources, or summary-type metrics (the metricTables.summary table on a metric source, which the builder tools cannot query). A single-table aggregation, top-N, time-series, or row browse is ALWAYS a builder-tool job, never raw SQL. If you are unsure, try the builder tool first and only fall back to SQL if it cannot express what you need. Requires connectionId — call clickstack_list_sources to find connections. Call clickstack_describe_source to discover column names before writing SQL. SOURCE FILTERS: when querying a table backed by a registered source, pass `sourceId` so the `$__sourceTable` and `$__filters` macros resolve. If that source declares `requiredSourceFilters`, you MUST also pass `sourceFilters` AND include `$__filters` in your WHERE clause. Source filter values are rendered as ` IN (, , ...)` conditions. Results are always returned as table rows — for time-series semantics, include a time column and ORDER BY it in your SQL. |
| `CLICKHOUSE_MCP_CLICKSTACK_TABLE` | Clickstack table | Compute aggregated metrics as a table, single number, pie chart, or bar chart. Use this for grouped aggregations, top-N queries, single-value KPIs, or proportional breakdowns. PREFER THIS over clickstack_sql. Only drop to raw SQL for things the builder tools cannot express — JOINs, sub-queries, CTEs, window functions, tables not registered as sources, or summary-type metrics (the metricTables.summary table on a metric source, which the builder tools cannot query). Requires sourceId — call clickstack_list_sources then clickstack_describe_source first. Use the top-level "where" to scope the entire query (e.g. filter by service). Each select item can also have its own "where" for per-metric cohort comparisons (compiles to If(...)). Both can be used together. Column naming: top-level columns are PascalCase (Duration, StatusCode). Map attributes use bracket syntax: SpanAttributes['http.method']. Map attributes work in groupBy and valueExpression, including toFloat64OrZero(SpanAttributes['key']). Shape auto-upgrade: if shape is "number", "pie", or "bar" but select has >1 item, it is transparently upgraded to "table". ── METRIC SOURCES ── When sourceId is a metric source, each select item MUST set metricType ("gauge"\|"sum"\|"histogram"\|"exponential histogram") and metricName (the OTel metric name). valueExpression defaults to "Value" — set it explicitly only to transform the value. Discovery: clickstack_describe_source returns a per-kind metric-name sample; clickstack_list_metrics paginates the full catalog; clickstack_describe_metric returns attribute keys + sampled values for a single metric. Per kind: gauge uses last_value/avg/min/max; sum uses aggFn:"increase" for counter increase (top-N capped at 20 groups when combined with groupBy), or sum/avg on the rate; histogram and exponential histogram use aggFn:"quantile" + level for percentiles, or aggFn:"count" for total bucket count. summary metrics are not supported by the query renderer — query them with clickstack_sql against the table in the source's metricTables.summary. SOURCE FILTERS: when the source declares `requiredSourceFilters` (see clickstack_describe_source / clickstack_list_sources), you MUST pass `sourceFilters` with at least one value for every required column. |
| `CLICKHOUSE_MCP_CLICKSTACK_TIMESERIES` | Clickstack timeseries | Plot metrics over time as a line or stacked bar chart. Use this when you need to visualize trends, compare time-series, or monitor metric changes over a time window. PREFER THIS over clickstack_sql. Only drop to raw SQL for things the builder tools cannot express — JOINs, sub-queries, CTEs, window functions, tables not registered as sources, or summary-type metrics (the metricTables.summary table on a metric source, which the builder tools cannot query). Requires sourceId — call clickstack_list_sources then clickstack_describe_source first. Each select item defines one plotted series. Column naming: top-level columns are PascalCase (Duration, StatusCode). Map attributes use bracket syntax: SpanAttributes['http.method']. ── METRIC SOURCES ── When sourceId is a metric source, each select item MUST set metricType ("gauge"\|"sum"\|"histogram"\|"exponential histogram") and metricName (the OTel metric name). valueExpression defaults to "Value" — set it explicitly only to transform the value. Discovery: clickstack_describe_source returns a per-kind metric-name sample; clickstack_list_metrics paginates the full catalog; clickstack_describe_metric returns attribute keys + sampled values for a single metric. Per kind: gauge uses last_value/avg/min/max (or aggFn:any + isDelta:true for Prometheus-style delta); sum uses aggFn:"increase" for the counter increase, or sum/avg on the computed rate; histogram and exponential histogram use aggFn:"quantile" + level for percentiles, or aggFn:"count" for total bucket count. TOP-N CAP: aggFn:"increase" + groupBy is capped at 20 groups by the renderer (top by max bucket sum). Narrow with where/groupBy to see other groups. summary metrics are not supported by the query renderer — query them with clickstack_sql against the table in the source's metricTables.summary. SOURCE FILTERS: when the source declares `requiredSourceFilters` (see clickstack_describe_source / clickstack_list_sources), you MUST pass `sourceFilters` with at least one value for every required column. |
| `CLICKHOUSE_MCP_CLICKSTACK_TRACE_TOP_TIME_CONSUMING_OPERATIONS` | Clickstack trace top time consuming operations | Given a parent-span filter and a time window, return the child operations contributing the most cumulative time across all traces matching the parent filter. Same algorithm as the in-app "Top Most Time Consuming Operations" chart on the service dashboard. WHAT IT DOES (two-stage, runs as one SQL): 1. Pick distinct TraceIds where the parent span matches `parentFilter` in the window. Optionally restrict to `minParentDurationMs` to focus on slow parents. 2. Aggregate ALL spans across those traces (excluding the matching root span itself) by (ServiceName, SpanName), ranked by `total_time_ms` DESC. USE WHEN: investigating "where is the time going" for a slow operation. Filter to a specific (ServiceName, SpanName) pair and set `minParentDurationMs` to the threshold above which a parent span counts as "slow" for your investigation. MULTIPLE OPERATIONS SLOW: when more than one operation shows elevated latency, call this tool ONCE PER (service, operation) and compare the top child rows across the result sets. Operations with the same top child likely share a cause; operations with different top children are independent regressions that happen to co-occur. DO NOT merge multiple operations into a single parentFilter — the cumulative rank then conflates independent investigations into one noisy answer. RANKING METRIC: `total_time_ms = sum(Duration)` across all matching child spans. This captures the true contribution to elapsed time — a fast-but-frequent child can dominate the latency even if its p99 is unremarkable. RETURNS: array of rows, each with `service`, `operation`, `total_time_ms`, `calls`, `in_parents` (how many parent traces contained at least one such span), `p50_ms`, `p99_ms`. Plus a `summary` block with the matched-parent count. NEXT STEP after this tool: once a dominant slow child operation is identified, the canonical follow-up is clickstack_event_deltas with slow-vs-fast spans of THAT child operation as target/baseline (target = {where: SpanName='' AND Duration > X}, baseline = {where: SpanName='' AND Duration <= Y}). The ranked attributes surface what distinguishes slow invocations of the child operation from fast ones. CROSS-SERVICE BREAKDOWN: this tool does NOT scope children to the parent's service. Slow cross-service calls (database, cache, upstream HTTP) surface naturally — useful for triage. PAIR TOOL: clickstack_trace_waterfall returns ONE concrete trace as a parent/child tree. Use it for an example after this tool's aggregate breakdown has pointed you at the slow downstream operation. |
| `CLICKHOUSE_MCP_CLICKSTACK_TRACE_WATERFALL` | Clickstack trace waterfall | Fetch all spans in ONE trace and return them as a parent/child waterfall, pre-ordered for human-readable display. Use this for "show me a concrete example trace" or "what happened in trace X" investigations — the tool walks the cascade for you instead of forcing the model to write self-JOINs in raw SQL. NOT THE RIGHT TOOL when the question is "where does the time go across MANY slow traces of operation X" — that is the aggregate question, and the answer is clickstack_trace_top_time_consuming_operations (called per affected (service, operation) with `minParentDurationMs`). Use this tool only when you want a single concrete example to inspect, or after the aggregate breakdown has already identified a suspicious operation. Two modes: 1. Specific trace: pass `traceId`. Returns every span in that trace. 2. Auto-pick: pass `pickFilter` + `pickBy`. The tool finds one matching trace (slowest / first_error / most_recent) and returns its full tree. Each returned span has: depth (root=0), spanId, parentSpanId, serviceName, spanName, spanKind, durationMs, statusCode, statusMessage, timestamp, and spanAttributes. Spans are pre-order DFS — child spans follow their parent in execution order. The tool also surfaces a `summary` section with the picked TraceId, total span count, and root span info. When the trace source has a linked logSourceId (the standard config), the response also includes a `logs[]` array of correlated log rows that share the same TraceId — sorted by timestamp, each carrying its `spanId` so the agent can attribute messages to specific spans. Disable with `includeLogs:false`. If the log source declares `requiredSourceFilters`, include its columns in `sourceFilters` too (one map shared with the trace source, matched by column name). Prefer this over running raw SQL with JOINs on TraceId — it uses the source's configured traceIdExpression / parentSpanIdExpression / spanIdExpression so attribute extraction stays consistent with the rest of the platform. PAIR TOOL: clickstack_trace_top_time_consuming_operations is the aggregate counterpart — given a parent-span filter, it ranks child operations by total time across MANY matching traces. Use that when the question is "where does time go in slow X" (aggregate), and use THIS tool when the question is "show me one example of a slow X" (single trace). |

## Supported Triggers

None listed.

## Installation and MCP Setup

### Path 1: SDK Installation

#### Path 1, Step 1: Install Composio

Install the Composio SDK
```python
pip install composio_openai
```

```typescript
npm install @composio/openai
```

#### Path 1, Step 2: Initialize Composio and Create Tool Router Session

Import and initialize Composio client, then create a Tool Router session
```python
from openai import OpenAI
from composio import Composio
from composio_openai import OpenAIResponsesProvider

composio = Composio(provider=OpenAIResponsesProvider())
openai = OpenAI()
session = composio.create(user_id='your-user-id')
```

```typescript
import OpenAI from 'openai';
import { Composio } from '@composio/core';
import { OpenAIResponsesProvider } from '@composio/openai';

const composio = new Composio({
  provider: new OpenAIResponsesProvider(),
});
const openai = new OpenAI({});
const session = await composio.create('your-user-id');
```

#### Path 1, Step 3: Execute ClickHouse MCP Tools via Tool Router with Your Agent

Get tools from Tool Router session and execute ClickHouse MCP actions with your Agent
```python
tools = session.tools
response = openai.responses.create(
  model='gpt-4.1',
  tools=tools,
  input=[{
    'role': 'user',
    'content': 'YOUR_SPECIFIC_PROMPT_HERE'
  }]
)
result = composio.provider.handle_tool_calls(
  response=response,
  user_id='your-user-id'
)
print(result)
```

```typescript
const tools = session.tools;
const response = await openai.responses.create({
  model: 'gpt-4.1',
  tools: tools,
  input: [{
    role: 'user',
    content: 'YOUR_SPECIFIC_PROMPT_HERE'
  }],
});
const result = await composio.provider.handleToolCalls(
  'your-user-id',
  response.output
);
console.log(result);
```

### Path 2: MCP Server Setup

#### Path 2, Step 1: Install Composio

Install the Composio SDK for Python or TypeScript
```python
pip install composio claude-agent-sdk
```

```typescript
npm install @composio/core ai @ai-sdk/openai @ai-sdk/mcp
```

#### Path 2, Step 2: Initialize Client and Create Tool Router Session

Import and initialize the Composio client, then create a Tool Router session for ClickHouse MCP
```python
from composio import Composio
from claude_agent_sdk import ClaudeSDKClient, ClaudeAgentOptions

composio = Composio(api_key='your-composio-api-key')
session = composio.create(user_id='your-user-id')
url = session.mcp.url
```

```typescript
import { Composio } from '@composio/core';

const composio = new Composio({ apiKey: 'your-api-key' });
const session = await composio.create('your-user-id');
console.log(`Tool Router session created: ${session.mcp.url}`);
```

#### Path 2, Step 3: Connect to AI Agent

Use the MCP server with your AI agent (Anthropic Claude or Mastra)
```python
import asyncio

options = ClaudeAgentOptions(
    permission_mode='bypassPermissions',
    mcp_servers={
        'tool_router': {
            'type': 'http',
            'url': url,
            'headers': {
                'x-api-key': 'your-composio-api-key'
            }
        }
    },
    system_prompt='You are a helpful assistant with access to ClickHouse MCP tools.',
    max_turns=10
)

async def main():
    async with ClaudeSDKClient(options=options) as client:
        await client.query('YOUR_SPECIFIC_PROMPT_HERE')
        async for message in client.receive_response():
            if hasattr(message, 'content'):
                for block in message.content:
                    if hasattr(block, 'text'):
                        print(block.text)

asyncio.run(main())
```

```typescript
import { openai } from '@ai-sdk/openai';
import { experimental_createMCPClient as createMCPClient } from '@ai-sdk/mcp';
import { generateText } from 'ai';

const client = await createMCPClient({
  transport: {
    type: 'http',
    url: session.mcp.url,
    headers: {
      'x-api-key': 'your-composio-api-key',
    },
  },
});

const tools = await client.tools();
const { text } = await generateText({
  model: openai('gpt-4o'),
  tools,
  messages: [{
    role: 'user',
    content: 'YOUR_SPECIFIC_PROMPT_HERE'
  }],
  maxSteps: 5,
});

console.log(`Agent: ${text}`);
```

## Why Use Composio?

### 1. AI Native ClickHouse MCP Integration

- Supports both ClickHouse MCP and direct API based integrations
- Structured, LLM-friendly schemas for reliable tool execution
- Rich coverage for reading, writing, and querying your ClickHouse MCP data

### 2. Managed Auth

- Built-in OAuth handling with automatic token refresh and rotation
- Central place to manage, scope, and revoke ClickHouse MCP access
- Per user and per environment credentials instead of hard-coded keys

### 3. Agent Optimized Design

- Tools are tuned using real error and success rates to improve reliability over time
- Comprehensive execution logs so you always know what ran, when, and on whose behalf

### 4. Enterprise Grade Security

- Fine-grained RBAC so you control which agents and users can access ClickHouse MCP
- Scoped, least privilege access to ClickHouse MCP resources
- Full audit trail of agent actions to support review and compliance

## Use ClickHouse MCP with any AI Agent Framework

Choose a framework you want to connect ClickHouse MCP with:

- [ChatGPT Work](https://composio.dev/toolkits/clickhouse_mcp/framework/chatgpt)
- [Claude Cowork](https://composio.dev/toolkits/clickhouse_mcp/framework/claude-cowork)
- [Hermes](https://composio.dev/toolkits/clickhouse_mcp/framework/hermes-agent)

## Related Toolkits

- [Firecrawl](https://composio.dev/toolkits/firecrawl) - Firecrawl automates large-scale web crawling and data extraction. It helps organizations efficiently gather, index, and analyze content from online sources.
- [Tavily](https://composio.dev/toolkits/tavily) - Tavily offers powerful search and data retrieval from documents, databases, and the web. It helps teams locate and filter information instantly, saving hours on research.
- [Exa](https://composio.dev/toolkits/exa) - Exa is a data extraction and search platform for gathering and analyzing information from websites, APIs, or databases. It helps teams quickly surface insights and automate data-driven workflows.
- [Serpapi](https://composio.dev/toolkits/serpapi) - SerpApi is a real-time API for structured search engine results. It lets you automate SERP data collection, parsing, and analysis for SEO and research.
- [Peopledatalabs](https://composio.dev/toolkits/peopledatalabs) - Peopledatalabs delivers B2B data enrichment and identity resolution APIs. Supercharge your apps with accurate, up-to-date business and contact data.
- [Snowflake](https://composio.dev/toolkits/snowflake) - Snowflake is a cloud data warehouse built for elastic scaling, secure data sharing, and fast SQL analytics across major clouds.
- [Posthog](https://composio.dev/toolkits/posthog) - PostHog is an open-source analytics platform for tracking user interactions and product metrics. It helps teams refine features, analyze funnels, and reduce churn with actionable insights.
- [Ahrefs MCP](https://composio.dev/toolkits/ahrefs_mcp) - Ahrefs MCP is Ahrefs' hosted MCP server for SEO data and insights. Use it to access backlinks, organic metrics, keyword research, and competitor analysis.
- [Amplitude](https://composio.dev/toolkits/amplitude) - Amplitude is a digital analytics platform for product and behavioral data insights. It helps teams analyze user journeys and make data-driven decisions quickly.
- [Audioscrape MCP](https://composio.dev/toolkits/audioscrape_mcp) - Audioscrape MCP lets agents search and retrieve speaker-attributed audio, transcripts, entities, and citations from public and workspace content. Use it to surface searchable, speaker-labeled audio and rich metadata for research, meetings, and content discovery.
- [Baremetrics](https://composio.dev/toolkits/baremetrics) - Baremetrics is a subscription analytics platform for recurring-revenue businesses. It helps teams track MRR, churn, customers, and revenue trends in one place.
- [Bing Webmaster Tools](https://composio.dev/toolkits/bing_webmaster_tools) - Bing Webmaster Tools is Microsoft's search console for site performance, crawling, indexing, URL submission, and verified site management. It helps site owners understand Bing Search visibility and fix issues that affect organic traffic.
- [Bread & Butter](https://composio.dev/toolkits/bread_butter) - Bread & Butter is a lead-intelligence and identity platform for website visitor tracking, user profiles, attribution, authentication, and conversion workflows. It helps teams understand who is visiting, where leads come from, and how users convert.
- [Bright Data MCP](https://composio.dev/toolkits/brightdata_mcp) - Bright Data MCP is an AI-powered web scraping and data collection platform. Instantly access public web data in real time with advanced scraping tools.
- [Browseai](https://composio.dev/toolkits/browseai) - Browseai is a web automation and data extraction platform that turns any website into an API. It's perfect for monitoring websites and retrieving structured data without manual scraping.
- [BSC Designer](https://composio.dev/toolkits/bsc_designer) - BSC Designer is a strategy execution platform for balanced scorecards, KPIs, dashboards, and strategy maps. It helps teams turn goals into measurable performance plans they can track over time.
- [Chameleon](https://composio.dev/toolkits/chameleon) - Chameleon is a product adoption platform for building in-app experiences, managing customer data, and analyzing user engagement. It helps teams improve onboarding, feature discovery, and product adoption with targeted user experiences.
- [Chartly](https://composio.dev/toolkits/chartly) - Chartly renders Chart.js configurations as PNG or SVG images and creates permanent chart URLs for sharing and embedding. Share and embed charts easily with stable image URLs and downloadable vector graphics.
- [ClickHouse](https://composio.dev/toolkits/clickhouse) - ClickHouse is an open-source, column-oriented database for real-time analytics and big data processing using SQL. Its lightning-fast query performance makes it ideal for handling large datasets and delivering instant insights.
- [CoinGecko](https://composio.dev/toolkits/coingecko) - CoinGecko is a cryptocurrency data platform that provides prices, market metrics, exchange, NFT, and onchain data. Use it for comprehensive, up-to-date crypto market insights and metadata.

## Frequently Asked Questions

### Do I need my own developer credentials to use ClickHouse MCP with Composio?

Yes, ClickHouse MCP requires you to configure your own Dcr Oauth credentials. Once set up, Composio handles secure credential storage and management for you.

### Can I use multiple toolkits together?

Yes! Composio's Tool Router enables agents to use multiple toolkits. [Learn more](https://docs.composio.dev/tool-router/overview).

### Is Composio secure?

Composio is SOC 2 and ISO 27001 compliant with all data encrypted in transit and at rest. [Learn more](https://trust.composio.dev).

### What if the API changes?

Composio maintains and updates all toolkit integrations automatically, so your agents always work with the latest API versions.

---
[See all toolkits](https://composio.dev/toolkits) · [Composio docs](https://docs.composio.dev/llms.txt)
