Skip to main content
Glama

ClickHouse MCP starter for Aiven Runtime

Run the official ClickHouse MCP server on Aiven Runtime with Aiven for ClickHouse. AI assistants such as Claude can then explore your schemas and query your data in plain language. An optional extension shows results as interactive charts and tables, with the rows ClickHouse read and how long it took.

This is a demo template. It ships with a loader for public NYC taxi data (up to 340 million trips) and a materialized view that pre-aggregates it. Use it on data you are comfortable showing to everyone who has the token or can sign in. See Security.

What starts up

MCP client --HTTPS--> Aiven Runtime :8000 (mcp-clickhouse)
                          |  bearer token or Google sign-in
                          |  tools: run_query, list_databases, list_tables, ...
                          |       + visualize_query, taxi_dashboard (optional)
                          |
                          +--TLS, read-only user--> Aiven for ClickHouse
                                                     nyc_taxi.trips          one row per trip
                                                     nyc_taxi.trips_hourly   rollup kept up to date
                                                                             by a materialized view

The server is the upstream mcp-clickhouse package, unmodified. The MCP endpoint is /mcp (streamable HTTP). /health answers without credentials and reports whether the server can reach ClickHouse.

Related MCP server: clickhouse

Deploy on Aiven Runtime

1. Create an Aiven for ClickHouse service

Create it in the Aiven Console first; Runtime does not create it for you. A startup-8 plan (2 vCPU, 8 GB RAM, 100 GB disk) holds the full dataset. Note the service host and its ClickHouse HTTPS port from the connection information. The MCP server needs the HTTPS port, not the native-protocol port.

2. Load the sample data (optional)

You need uv. From a clone of this repository, with the service's admin credentials:

export CLICKHOUSE_HOST=<service-host> CLICKHOUSE_PORT=<https-port> CLICKHOUSE_SECURE=true
export CLICKHOUSE_USER=avnadmin CLICKHOUSE_PASSWORD=<admin-password>
NYC_TAXI_MONTHS=12 uv run --frozen python -m loader.nyc_taxi

ClickHouse reads the Parquet files directly from ClickHouse's public dataset bucket, about 12 seconds per month on startup-8. After each month the loader checks that the rows arrived in both tables before recording the month as loaded.

NYC_TAXI_MONTHS

Months

Rows

Disk

1

2009-01

14,092,413

about 0.6 GiB

12 (default)

all of 2009

170,896,055

about 7 GiB

24 (maximum)

2009 and 2010

339,897,217

about 14 GiB

Re-running skips months that are already loaded, and clears and reloads a month that was interrupted. After an interrupted load, wait a minute before re-running, so ClickHouse finishes or cancels the old insert first. Nine rows in the 2010-12 file have pickup times in 2011-02; they are kept as published, and because they sit outside that month's partition, reloading an interrupted 2010-12 adds them again. To use your own data instead, skip this step, grant the read-only user access to your database as described in step 3, and change CLICKHOUSE_DATABASE in step 4.

3. Create the read-only user

With the same admin variables still set:

export MCP_READONLY_PASSWORD=$(openssl rand -hex 32)
echo "$MCP_READONLY_PASSWORD"   # you need it in step 4
uv run --frozen python -m loader.readonly_user

Afterwards mcp_readonly has exactly one direct grant, SELECT on nyc_taxi, and the setting readonly = 2, even if it existed before with other settings. Re-running sets the password to the current MCP_READONLY_PASSWORD. The database name nyc_taxi is fixed in the loader and the dashboard. To serve your own database as well, run this script, then GRANT SELECT ON <database>.* TO mcp_readonly yourself; re-running the script revokes that grant again.

4. Create the Runtime application

Create a Runtime application from this repository using the Dockerfile, with HTTP port 8000 and one replica. One replica, because the server keeps MCP sessions and registered OAuth clients in memory and on local disk. Fill the fields on the deploy screen:

Variable

Value

CLICKHOUSE_HOST

Service host from step 1.

CLICKHOUSE_PORT

The ClickHouse HTTPS port from step 1.

CLICKHOUSE_USER

mcp_readonly (prefilled).

CLICKHOUSE_PASSWORD

The password from step 3. Mark it as a secret.

CLICKHOUSE_SECURE

true (prefilled). Must be true or false.

CLICKHOUSE_DATABASE

nyc_taxi (prefilled).

CLICKHOUSE_MCP_ALLOWED_HOSTS

The application's public hostname, without https://.

CLICKHOUSE_MCP_AUTH_TOKEN

Output of openssl rand -hex 32. Mark it as a secret. For Google sign-in, see Authentication.

MCP_MIDDLEWARE_MODULE

visual_tools (prefilled) to enable the visual tools, or empty for upstream tools only.

CLICKHOUSE_HOST, CLICKHOUSE_PORT, CLICKHOUSE_USER, CLICKHOUSE_PASSWORD, and CLICKHOUSE_MCP_ALLOWED_HOSTS are required, and so is one way to authenticate: the token or Google sign-in. If one is empty or invalid, the container stops at once and its log names it.

The application's public hostname is only known after it is created. Put any placeholder such as pending in CLICKHOUSE_MCP_ALLOWED_HOSTS for the first deploy, then set it to the hostname and redeploy; until then the server answers every MCP request with an error.

Do not connect the ClickHouse service to the application. The application's Connect service dialog pre-fills exactly these variable names, but it fills them with the service's admin account and the default database, replacing mcp_readonly and nyc_taxi, and its port may not be the HTTPS port the server needs. Set the variables yourself as in the table above.

taxi_dashboard is registered when the server starts, and only if nyc_taxi.trips_hourly exists and ClickHouse is reachable. If you load data after deploying, or ClickHouse was unreachable at startup (the log says "taxi_dashboard not registered"), redeploy.

The Dockerfile's HEALTHCHECK is ignored by OCI-format builds such as Runtime's, so do not rely on it there.

5. Connect a client

Claude Code:

claude mcp add --transport http clickhouse https://<application-url>/mcp \
  --header "Authorization: Bearer <CLICKHOUSE_MCP_AUTH_TOKEN>"

Clients that read mcp.json:

{
  "mcpServers": {
    "clickhouse": {
      "url": "https://<application-url>/mcp",
      "headers": { "Authorization": "Bearer <CLICKHOUSE_MCP_AUTH_TOKEN>" }
    }
  }
}

Then ask, for example: "Which hour of the day has the most taxi trips?" or "Show the taxi dashboard."

Authentication

Bearer token (default)

Everyone shares the token in CLICKHOUSE_MCP_AUTH_TOKEN. To rotate it, set a new value, redeploy, and update every client.

Google sign-in

mcp-clickhouse can run the MCP OAuth flow with Google, so each person signs in with their own account. MCP clients that support MCP OAuth discover the login from the server and start it themselves.

  1. In the Google Cloud Console, create an OAuth client of type Web application with the redirect URI https://<application-url>/auth/callback.

  2. In Runtime, add these variables and redeploy:

    Variable

    Value

    FASTMCP_SERVER_AUTH

    fastmcp.server.auth.providers.google.GoogleProvider

    FASTMCP_SERVER_AUTH_GOOGLE_CLIENT_ID

    The OAuth client ID.

    FASTMCP_SERVER_AUTH_GOOGLE_CLIENT_SECRET

    The client secret. Mark it as a secret.

    FASTMCP_SERVER_AUTH_GOOGLE_BASE_URL

    https://<application-url>

  3. Leave CLICKHOUSE_MCP_AUTH_TOKEN empty.

The server keeps registered OAuth clients inside the container, so after a redeploy or restart people sign in again.

Limit sign-in to your Google Workspace. The server accepts any Google account by default. To allow only your organization, create the OAuth client in a Google Cloud project that belongs to your Workspace organization and set the consent screen's user type to Internal. Google then refuses accounts outside the organization. The hd parameter alone only pre-selects an account in the picker; it does not enforce anything.

Visual tools

The optional visual_tools extension adds two tools that answer with interactive UIs, built with Prefab (prefab-ui, by PrefectHQ, Apache-2.0). FastMCP uses Prefab to return MCP Apps: charts and tables that the client renders inside the conversation.

  • visualize_query: runs one read-only SELECT and shows a bar, line, area, or pie chart (or just a table), a sortable table of up to 5,000 rows, and the rows and bytes ClickHouse read with the query time. That last strip is what makes the speed visible: grouping 340 million raw trips takes 1 to 2 seconds on startup-8.

  • taxi_dashboard: trips by hour, tips as % of fares by payment type, trips by month and by weekday, with combined statistics, answered from the materialized view described below.

Materialized view. The loader also creates nyc_taxi.trips_hourly, a SummingMergeTree rollup by day, hour, and payment type, and a materialized view, nyc_taxi.trips_hourly_mv, that adds every inserted batch of trips to it. taxi_dashboard reads the rollup. On startup-8 with 340 million trips, its five queries read 318,095 rows (3.76 MiB) in 17 ms; the same charts from the raw table read 1.36 billion rows (7.91 GiB) in 7 s. To show the difference live, ask the same question twice:

  • "Using visualize_query, chart trips by hour of day from nyc_taxi.trips."

  • "Now chart the same thing from nyc_taxi.trips_hourly (it is pre-aggregated; use sum(trips))."

Compare the "Rows read" and "Query time" tiles. Rows in the rollup may not be merged yet, so always aggregate it with sum(). Cash tips are not recorded in this data, so tip rates are meaningful for card payments only. Table comments tell the model both of these.

How it is added. mcp-clickhouse loads the module named in MCP_MIDDLEWARE_MODULE at startup through its supported extension hook. The upstream server is not forked or patched; with the variable empty, the server is exactly upstream.

Which clients show the UI. Claude (claude.ai), Claude Desktop, VS Code GitHub Copilot, Microsoft 365 Copilot, Goose, Postman, MCPJam, and Archestra.AI support MCP Apps. Other clients, including Claude Code, receive a text summary with the same statistics and a preview of the rows.

Versions. prefab-ui is pinned to 0.21.1 because Prefab is under very active development.

Security

  • Use the read-only user. Its only direct grant is SELECT on nyc_taxi (roles granted to it earlier are kept); ClickHouse also lets every user read some system tables (next point). Every query runs read-only and stops after CLICKHOUSE_MCP_QUERY_TIMEOUT (default 30 s): upstream tools cancel it from the server side, and the visual tools also send readonly (never below 1) and a matching max_execution_time. A query can raise its own limits with a SETTINGS clause, so the grants are the hard limit.

  • Use readonly = 2 for your own users too. A user whose profile has readonly = 1 may not change any setting, so the visual tools' max_execution_time is skipped for it and only its profile limits apply. If a settings profile constrains max_execution_time (for example max = 10), set CLICKHOUSE_MCP_QUERY_TIMEOUT within that range, or ClickHouse rejects every query.

  • The read-only user can read some ClickHouse system tables, including system.query_log, which holds the text of recent queries from every user. ClickHouse masks passwords in CREATE USER and ALTER USER statements there. Do not point this template at a service where query text is sensitive.

  • Bearer mode cannot tell users apart. Give the token only to people who may read the whole database.

  • Google sign-in admits any Google account unless you use an Internal consent screen.

Local demo

Requires Docker Compose v2 or podman compose, and uv.

  1. cp .env.example .env and fill each value with openssl rand -hex 32.

  2. Start ClickHouse, load one month, and create the read-only user:

    set -a; . ./.env; set +a
    docker compose up -d --wait clickhouse
    export CLICKHOUSE_HOST=localhost CLICKHOUSE_PORT=8123 CLICKHOUSE_SECURE=false
    export CLICKHOUSE_USER=admin CLICKHOUSE_PASSWORD="$CLICKHOUSE_ADMIN_PASSWORD"
    NYC_TAXI_MONTHS=1 uv run --frozen python -m loader.nyc_taxi
    uv run --frozen python -m loader.readonly_user
  3. docker compose up -d --build mcp, then connect to http://localhost:8000/mcp with the token from .env.

With Podman, use podman compose in place of docker compose; --wait and the mcp service's wait for a healthy ClickHouse both work there, although podman compose ps does not print "(healthy)".

docker compose down keeps the data. docker compose down -v deletes it.

Tests

uv run --frozen pytest            # unit tests, no network
uv run --frozen pytest -m smoke   # against the local demo
MCP_URL=https://<application-url> CLICKHOUSE_MCP_AUTH_TOKEN=<deployed token> uv run --frozen pytest -m smoke

The smoke tests need the server's bearer token. Locally it comes from .env, which mcp-clickhouse loads on import; against a deployment, export that deployment's token explicitly. Against a server using Google sign-in, only the two tests that need no token apply: run them with -k 'health or rejects'.

Upgrade

mcp-clickhouse is pinned to a commit of its main branch, because the 0.8.0 release requires a FastMCP version without the OAuth fix that Google sign-in needs. To upgrade, change the URL in pyproject.toml, run uv lock, and run the tests. When upgrading clickhouse-connect (pinned below 2), also run the smoke tests with a readonly = 1 user: the visual tools rely on its per-setting readonly flag to skip the query timeout for such users.

License

The template code is licensed under the MIT License. mcp-clickhouse, Prefab, ClickHouse, and other third-party components retain their own licenses.

Available Tools

3 tools
list_databasesList DatabasesA
Read-only

List available ClickHouse databases

Inputs: no named parameters. Returns: result

list_tablesList TablesA
Read-only

List available ClickHouse tables in a database, including schema, comment, row count, and column count.

Integers outside [-9007199254740991, 9007199254740991] in table metadata are returned as decimal strings. Pagination tokens are single-use and retained for up to one hour.

Inputs: database (required), like, not_like, page_size, +2 more. Returns: result

run_queryRun QueryA
Read-only

Execute SQL queries in ClickHouse. Queries run in read-only mode by default. Bind optional params by name with {name:Type} placeholders, such as {name:String} or {vector:Array(Float32)}. Values may be JSON scalars, nulls, or arrays. Pass exact large integers as decimal strings. JSON lists and objects cannot bind to Tuple and Map types. Python percent formatting and $name$ raw binary parameters are not supported. Parameter values stay out of the MCP server's normal SQL log lines, but may appear in errors and backend logs. Set CLICKHOUSE_ALLOW_WRITE_ACCESS=true to allow DDL and DML operations. Set CLICKHOUSE_ALLOW_DROP=true to additionally allow destructive operations (DROP, TRUNCATE, DELETE, UPDATE, REPLACE TABLE/PARTITION, CREATE OR REPLACE, CLEAR COLUMN/INDEX/PROJECTION, OPTIMIZE DEDUPLICATE, MODIFY/MATERIALIZE TTL, MODIFY/ALTER COLUMN with TTL, DETACH PERMANENTLY). That gate is a best-effort accident guard, not a security boundary. Integers outside [-9007199254740991, 9007199254740991] are returned as decimal strings. Do not end a query with a FORMAT clause, because this tool appends FORMAT Native. With readonly=1, the default, a SETTINGS clause fails with code 164 or is ignored. Two optional checks also run through this tool. Use DESCRIBE () when you need a query's output columns and types; it inspects the result schema and surfaces analysis errors such as an unknown column, but a query that describes cleanly can still fail at runtime. Consider EXPLAIN ESTIMATE before a SELECT that could be expensive; it returns the estimated parts, rows and marks read from MergeTree family tables, which is not run time and not result size. Neither runs the query body, though analysis can execute scalar subqueries.

Inputs: query (required), params. Returns: result

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    A4.1/5.0

    Scored across 3 tools

    Disambiguation5/5

    Each tool has a clearly distinct role: list_databases enumerates databases, list_tables enumerates tables within a database, and run_query executes SQL. Although run_query could technically be used to list databases or tables, the dedicated listing tools are unambiguous and preferable for those tasks.

    Naming Consistency5/5

    All three tools follow a consistent verb_noun snake_case pattern: list_databases, list_tables, run_query. The naming is predictable and readable throughout.

    Tool Count5/5

    Three tools is a well-scoped surface for a ClickHouse server: discovery of databases, discovery of tables, and query execution. Each tool earns its place, and the small set avoids unnecessary overlap.

    Completeness4/5

    The core lifecycle is covered: agents can discover databases, inspect tables with schema metadata, and run read-only or gated write queries. Minor gaps exist, such as no dedicated table-schema or connection-status tool, but list_tables and run_query with DESCRIBE provide workarounds.

    Maintenance

    ActivityMaintained
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      A
      quality
      D
      maintenance
      Enables AI assistants to query and interact with CockroachDB clusters through natural language, supporting schema discovery, CRUD operations, transactions, cluster monitoring, and data export with configurable safety controls.
      30
      Apache 2.0
    • A
      license
      A
      quality
      D
      maintenance
      Enables AI assistants to query and manage ClickHouse databases, supporting SELECT queries, DDL/DML statements, and metadata listing.
      5
      7 npm
      MIT
    • F
      license
      Not graded
      quality
      D
      maintenance
      Enables AI agents to build ClickHouse dashboards and reports through live schema introspection, a semantic layer, and rendering to Grafana or HTML, adapting to database changes without code updates.
      -