An MCP server for ClickHouse. Execute SQL queries on your ClickHouse cluster. Input: query (string): The SQL query to execute. Queries run in read-only mode by default (CLICKHOUSEALLOWWRITEACCESS=false), but writes can be enabled explicitly if needed. listdatabases List all databases on your ClickHouse cluster. List tables in a database with pagination. Required input: database (string). Optional
Add this skill
npx mdskills install ClickHouse/mcp-clickhouseComprehensive MCP server with well-documented ClickHouse and chDB tools, strong security features, and flexible configuration
1# ClickHouse MCP Server23[](https://pypi.org/project/mcp-clickhouse)45An MCP server for ClickHouse.67<a href="https://glama.ai/mcp/servers/yvjy4csvo1"><img width="380" height="200" src="https://glama.ai/mcp/servers/yvjy4csvo1/badge" alt="mcp-clickhouse MCP server" /></a>89## Features1011### ClickHouse Tools1213* `run_query`14 * Execute SQL queries on your ClickHouse cluster.15 * Input: `query` (string): The SQL query to execute.16 * Queries run in read-only mode by default (`CLICKHOUSE_ALLOW_WRITE_ACCESS=false`), but writes can be enabled explicitly if needed.1718* `list_databases`19 * List all databases on your ClickHouse cluster.2021* `list_tables`22 * List tables in a database with pagination.23 * Required input: `database` (string).24 * Optional inputs:25 * `like` / `not_like` (string): Apply `LIKE` or `NOT LIKE` filters to table names.26 * `page_token` (string): Token returned by a previous call for fetching the next page.27 * `page_size` (int, default `50`): Number of tables returned per page.28 * `include_detailed_columns` (bool, default `true`): When `false`, omits column metadata for lighter responses while keeping the full `create_table_query`.29 * Response shape:30 * `tables`: Array of table objects for the current page.31 * `next_page_token`: Pass this value back to fetch the next page, or `null` when there are no more tables.32 * `total_tables`: Total count of tables that match the supplied filters.3334### chDB Tools3536* `run_chdb_select_query`37 * Execute SQL queries using [chDB](https://github.com/chdb-io/chdb)'s embedded ClickHouse engine.38 * Input: `query` (string): The SQL query to execute.39 * Query data directly from various sources (files, URLs, databases) without ETL processes.4041### Health Check Endpoint4243When running with HTTP or SSE transport, a health check endpoint is available at `/health`. This endpoint:44- Returns `200 OK` with the ClickHouse version if the server is healthy and can connect to ClickHouse45- Returns `503 Service Unavailable` if the server cannot connect to ClickHouse4647Example:48```bash49curl http://localhost:8000/health50# Response: OK - Connected to ClickHouse 24.3.151```5253## Security5455### Authentication for HTTP/SSE Transports5657When using HTTP or SSE transport, authentication is **required by default**. The `stdio` transport (default) does not require authentication as it only communicates via standard input/output.5859#### Setting Up Authentication60611. Generate a secure token (can be any random string):62 ```bash63 # Using uuidgen (macOS/Linux)64 uuidgen6566 # Using openssl67 openssl rand -hex 3268 ```69702. Configure the server with the token:71 ```bash72 export CLICKHOUSE_MCP_AUTH_TOKEN="your-generated-token"73 ```74753. Configure your MCP client to include the token in requests:7677 For Claude Desktop with HTTP/SSE transport:78 ```json79 {80 "mcpServers": {81 "mcp-clickhouse": {82 "url": "http://127.0.0.1:8000",83 "headers": {84 "Authorization": "Bearer your-generated-token"85 }86 }87 }88 }89 ```9091 For command-line tools:92 ```bash93 curl -H "Authorization: Bearer your-generated-token" http://localhost:8000/health94 ```9596#### Development Mode (Disabling Authentication)9798For local development and testing only, you can disable authentication by setting:99```bash100export CLICKHOUSE_MCP_AUTH_DISABLED=true101```102103**WARNING:** Only use this for local development. Do not disable authentication when the server is exposed to any network.104105## Configuration106107This MCP server supports both ClickHouse and chDB. You can enable either or both depending on your needs.1081091. Open the Claude Desktop configuration file located at:110 * On macOS: `~/Library/Application Support/Claude/claude_desktop_config.json`111 * On Windows: `%APPDATA%/Claude/claude_desktop_config.json`1121132. Add the following:114115```json116{117 "mcpServers": {118 "mcp-clickhouse": {119 "command": "uv",120 "args": [121 "run",122 "--with",123 "mcp-clickhouse",124 "--python",125 "3.10",126 "mcp-clickhouse"127 ],128 "env": {129 "CLICKHOUSE_HOST": "<clickhouse-host>",130 "CLICKHOUSE_PORT": "<clickhouse-port>",131 "CLICKHOUSE_USER": "<clickhouse-user>",132 "CLICKHOUSE_PASSWORD": "<clickhouse-password>",133 "CLICKHOUSE_ROLE": "<clickhouse-role>",134 "CLICKHOUSE_SECURE": "true",135 "CLICKHOUSE_VERIFY": "true",136 "CLICKHOUSE_CONNECT_TIMEOUT": "30",137 "CLICKHOUSE_SEND_RECEIVE_TIMEOUT": "30"138 }139 }140 }141}142```143144Update the environment variables to point to your own ClickHouse service.145146Or, if you'd like to try it out with the [ClickHouse SQL Playground](https://sql.clickhouse.com/), you can use the following config:147148```json149{150 "mcpServers": {151 "mcp-clickhouse": {152 "command": "uv",153 "args": [154 "run",155 "--with",156 "mcp-clickhouse",157 "--python",158 "3.10",159 "mcp-clickhouse"160 ],161 "env": {162 "CLICKHOUSE_HOST": "sql-clickhouse.clickhouse.com",163 "CLICKHOUSE_PORT": "8443",164 "CLICKHOUSE_USER": "demo",165 "CLICKHOUSE_PASSWORD": "",166 "CLICKHOUSE_SECURE": "true",167 "CLICKHOUSE_VERIFY": "true",168 "CLICKHOUSE_CONNECT_TIMEOUT": "30",169 "CLICKHOUSE_SEND_RECEIVE_TIMEOUT": "30"170 }171 }172 }173}174```175176For chDB (embedded ClickHouse engine), add the following configuration:177178```json179{180 "mcpServers": {181 "mcp-clickhouse": {182 "command": "uv",183 "args": [184 "run",185 "--with",186 "mcp-clickhouse",187 "--python",188 "3.10",189 "mcp-clickhouse"190 ],191 "env": {192 "CHDB_ENABLED": "true",193 "CLICKHOUSE_ENABLED": "false",194 "CHDB_DATA_PATH": "/path/to/chdb/data"195 }196 }197 }198}199```200201You can also enable both ClickHouse and chDB simultaneously:202203```json204{205 "mcpServers": {206 "mcp-clickhouse": {207 "command": "uv",208 "args": [209 "run",210 "--with",211 "mcp-clickhouse",212 "--python",213 "3.10",214 "mcp-clickhouse"215 ],216 "env": {217 "CLICKHOUSE_HOST": "<clickhouse-host>",218 "CLICKHOUSE_PORT": "<clickhouse-port>",219 "CLICKHOUSE_USER": "<clickhouse-user>",220 "CLICKHOUSE_PASSWORD": "<clickhouse-password>",221 "CLICKHOUSE_SECURE": "true",222 "CLICKHOUSE_VERIFY": "true",223 "CLICKHOUSE_CONNECT_TIMEOUT": "30",224 "CLICKHOUSE_SEND_RECEIVE_TIMEOUT": "30",225 "CHDB_ENABLED": "true",226 "CHDB_DATA_PATH": "/path/to/chdb/data"227 }228 }229 }230}231```2322333. Locate the command entry for `uv` and replace it with the absolute path to the `uv` executable. This ensures that the correct version of `uv` is used when starting the server. On a mac, you can find this path using `which uv`.2342354. Restart Claude Desktop to apply the changes.236237### Optional Write Access238239By default, this MCP enforces read-only queries so that accidental mutations cannot happen during exploration. To allow DDL or INSERT/UPDATE statements, set the `CLICKHOUSE_ALLOW_WRITE_ACCESS` environment variable to `true`. The server keeps enforcing read-only mode if the ClickHouse instance itself disallows writes.240241### Destructive Operation Protection242243Even when write access is enabled (`CLICKHOUSE_ALLOW_WRITE_ACCESS=true`), destructive operations (DROP TABLE, DROP DATABASE, DROP VIEW, DROP DICTIONARY, TRUNCATE TABLE) require an additional opt-in flag for safety. This prevents accidental data deletion during AI exploration.244245To enable destructive operations, set both flags:246```json247"env": {248 "CLICKHOUSE_ALLOW_WRITE_ACCESS": "true",249 "CLICKHOUSE_ALLOW_DROP": "true"250}251```252253This two-tier approach ensures that accidental drops are very difficult:254- **Write operations** (INSERT, UPDATE, CREATE) require `CLICKHOUSE_ALLOW_WRITE_ACCESS=true`255- **Destructive operations** (DROP, TRUNCATE) additionally require `CLICKHOUSE_ALLOW_DROP=true`256257### Running Without uv (Using System Python)258259If you prefer to use the system Python installation instead of uv, you can install the package from PyPI and run it directly:2602611. Install the package using pip:262 ```bash263 python3 -m pip install mcp-clickhouse264 ```265266 To upgrade to the latest version:267 ```bash268 python3 -m pip install --upgrade mcp-clickhouse269 ```2702712. Update your Claude Desktop configuration to use Python directly:272273```json274{275 "mcpServers": {276 "mcp-clickhouse": {277 "command": "python3",278 "args": [279 "-m",280 "mcp_clickhouse.main"281 ],282 "env": {283 "CLICKHOUSE_HOST": "<clickhouse-host>",284 "CLICKHOUSE_PORT": "<clickhouse-port>",285 "CLICKHOUSE_USER": "<clickhouse-user>",286 "CLICKHOUSE_PASSWORD": "<clickhouse-password>",287 "CLICKHOUSE_SECURE": "true",288 "CLICKHOUSE_VERIFY": "true",289 "CLICKHOUSE_CONNECT_TIMEOUT": "30",290 "CLICKHOUSE_SEND_RECEIVE_TIMEOUT": "30"291 }292 }293 }294}295```296297Alternatively, you can use the installed script directly:298299```json300{301 "mcpServers": {302 "mcp-clickhouse": {303 "command": "mcp-clickhouse",304 "env": {305 "CLICKHOUSE_HOST": "<clickhouse-host>",306 "CLICKHOUSE_PORT": "<clickhouse-port>",307 "CLICKHOUSE_USER": "<clickhouse-user>",308 "CLICKHOUSE_PASSWORD": "<clickhouse-password>",309 "CLICKHOUSE_SECURE": "true",310 "CLICKHOUSE_VERIFY": "true",311 "CLICKHOUSE_CONNECT_TIMEOUT": "30",312 "CLICKHOUSE_SEND_RECEIVE_TIMEOUT": "30"313 }314 }315 }316}317```318319Note: Make sure to use the full path to the Python executable or the `mcp-clickhouse` script if they are not in your system PATH. You can find the paths using:320- `which python3` for the Python executable321- `which mcp-clickhouse` for the installed script322323## Custom Middleware324325You can add custom middleware to the MCP server without modifying the source code. FastMCP provides a middleware system that allows you to intercept and process MCP protocol messages (tool calls, resource reads, prompts, etc.).326327### How to Use3283291. Create a Python module with middleware classes extending `Middleware` and a `setup_middleware(mcp)` function:330331```python332# my_middleware.py333import logging334from fastmcp.server.middleware import Middleware, MiddlewareContext, CallNext335336logger = logging.getLogger("my-middleware")337338class LoggingMiddleware(Middleware):339 """Log all tool calls."""340341 async def on_call_tool(self, context: MiddlewareContext, call_next: CallNext):342 tool_name = context.message.name if hasattr(context.message, 'name') else 'unknown'343 logger.info(f"Calling tool: {tool_name}")344 result = await call_next(context)345 logger.info(f"Tool {tool_name} completed")346 return result347348def setup_middleware(mcp):349 """Register middleware with the MCP server."""350 mcp.add_middleware(LoggingMiddleware())351```3523532. Set the `MCP_MIDDLEWARE_MODULE` environment variable to the module name (without `.py` extension):354355```json356{357 "mcpServers": {358 "mcp-clickhouse": {359 "command": "uv",360 "args": ["run", "--with", "mcp-clickhouse", "--python", "3.10", "mcp-clickhouse"],361 "env": {362 "CLICKHOUSE_HOST": "<clickhouse-host>",363 "CLICKHOUSE_USER": "<clickhouse-user>",364 "CLICKHOUSE_PASSWORD": "<clickhouse-password>",365 "MCP_MIDDLEWARE_MODULE": "my_middleware"366 }367 }368 }369}370```3713723. Ensure your middleware module is in Python's import path (e.g., in the same directory where the MCP server runs, or installed as a package).373374### Example Middleware375376An example middleware module is provided in `example_middleware.py` showing common patterns:377- Logging all MCP requests378- Logging tool calls specifically379- Measuring request processing time380381To use the example:382```json383"env": {384 "MCP_MIDDLEWARE_MODULE": "example_middleware"385}386```387388### Middleware Capabilities389390The `Middleware` base class provides hooks for different MCP operations:391392- `on_message(context, call_next)` - Called for all messages393- `on_request(context, call_next)` - Called for all requests394- `on_notification(context, call_next)` - Called for all notifications395- `on_call_tool(context, call_next)` - Called when a tool is executed396- `on_read_resource(context, call_next)` - Called when a resource is read397- `on_get_prompt(context, call_next)` - Called when a prompt is retrieved398- `on_list_tools(context, call_next)` - Called when listing tools399- `on_list_resources(context, call_next)` - Called when listing resources400- `on_list_resource_templates(context, call_next)` - Called when listing resource templates401- `on_list_prompts(context, call_next)` - Called when listing prompts402403Each hook receives a `MiddlewareContext` object containing the message and metadata, and a `call_next` function to continue the pipeline.404405## Development4064071. In `test-services` directory run `docker compose up -d` to start the ClickHouse cluster.4084092. Add the following variables to a `.env` file in the root of the repository.410411*Note: The use of the `default` user in this context is intended solely for local development purposes.*412413```bash414CLICKHOUSE_HOST=localhost415CLICKHOUSE_PORT=8123416CLICKHOUSE_USER=default417CLICKHOUSE_PASSWORD=clickhouse418```4194203. Run `uv sync` to install the dependencies. To install `uv` follow the instructions [here](https://docs.astral.sh/uv/). Then do `source .venv/bin/activate`.4214224. For easy testing with the MCP Inspector, run `fastmcp dev mcp_clickhouse/mcp_server.py` to start the MCP server.4234245. To test with HTTP transport and the health check endpoint:425 ```bash426 # For development, disable authentication427 CLICKHOUSE_MCP_SERVER_TRANSPORT=http CLICKHOUSE_MCP_AUTH_DISABLED=true python -m mcp_clickhouse.main428429 # Or with authentication (generate a token first)430 CLICKHOUSE_MCP_SERVER_TRANSPORT=http CLICKHOUSE_MCP_AUTH_TOKEN="your-token" python -m mcp_clickhouse.main431432 # Then in another terminal:433 # Without auth (if disabled):434 curl http://localhost:8000/health435436 # With auth:437 curl -H "Authorization: Bearer your-token" http://localhost:8000/health438 ```439440### Environment Variables441442The following environment variables are used to configure the ClickHouse and chDB connections:443444#### ClickHouse Variables445446##### Required Variables447448* `CLICKHOUSE_HOST`: The hostname of your ClickHouse server449* `CLICKHOUSE_USER`: The username for authentication450* `CLICKHOUSE_PASSWORD`: The password for authentication451452> [!CAUTION]453> It is important to treat your MCP database user as you would any external client connecting to your database, granting only the minimum necessary privileges required for its operation. The use of default or administrative users should be strictly avoided at all times.454455##### Optional Variables456457* `CLICKHOUSE_PORT`: The port number of your ClickHouse server458 * Default: `8443` if HTTPS is enabled, `8123` if disabled459 * Usually doesn't need to be set unless using a non-standard port460* `CLICKHOUSE_ROLE`: The role to use for authentication461 * Default: None462 * Set this if your user requires a specific role463* `CLICKHOUSE_SECURE`: Enable/disable HTTPS connection464 * Default: `"true"`465 * Set to `"false"` for non-secure connections466* `CLICKHOUSE_VERIFY`: Enable/disable SSL certificate verification467 * Default: `"true"`468 * Set to `"false"` to disable certificate verification (not recommended for production)469 * TLS certificates: The package uses your operating system trust store for TLS certificate verification via `truststore`. We call `truststore.inject_into_ssl()` at startup to ensure proper certificate handling. Python’s default SSL behavior is used as a fallback only if an unexpected error occurs.470* `CLICKHOUSE_CONNECT_TIMEOUT`: Connection timeout in seconds471 * Default: `"30"`472 * Increase this value if you experience connection timeouts473* `CLICKHOUSE_SEND_RECEIVE_TIMEOUT`: Send/receive timeout in seconds474 * Default: `"300"`475 * Increase this value for long-running queries476* `CLICKHOUSE_DATABASE`: Default database to use477 * Default: None (uses server default)478 * Set this to automatically connect to a specific database479* `CLICKHOUSE_MCP_SERVER_TRANSPORT`: Sets the transport method for the MCP server.480 * Default: `"stdio"`481 * Valid options: `"stdio"`, `"http"`, `"sse"`. This is useful for local development with tools like MCP Inspector.482* `CLICKHOUSE_MCP_BIND_HOST`: Host to bind the MCP server to when using HTTP or SSE transport483 * Default: `"127.0.0.1"`484 * Set to `"0.0.0.0"` to bind to all network interfaces (useful for Docker or remote access)485 * Only used when transport is `"http"` or `"sse"`486* `CLICKHOUSE_MCP_BIND_PORT`: Port to bind the MCP server to when using HTTP or SSE transport487 * Default: `"8000"`488 * Only used when transport is `"http"` or `"sse"`489* `CLICKHOUSE_MCP_QUERY_TIMEOUT`: Timeout in seconds for SELECT tools490 * Default: `"30"`491 * Increase this if you see `Query timed out after ...` errors for heavy queries492* `CLICKHOUSE_MCP_AUTH_TOKEN`: Authentication token for HTTP/SSE transports493 * Default: None494 * **Required** when using HTTP or SSE transport (unless `CLICKHOUSE_MCP_AUTH_DISABLED=true`)495 * Generate using `uuidgen` or `openssl rand -hex 32`496 * Clients must send this token in the `Authorization: Bearer <token>` header497* `CLICKHOUSE_MCP_AUTH_DISABLED`: Disable authentication for HTTP/SSE transports498 * Default: `"false"` (authentication is enabled)499 * Set to `"true"` to disable authentication for local development/testing only500 * **WARNING:** Only use for local development. Do not disable when exposed to networks501* `CLICKHOUSE_ENABLED`: Enable/disable ClickHouse functionality502 * Default: `"true"`503 * Set to `"false"` to disable ClickHouse tools when using chDB only504* `CLICKHOUSE_ALLOW_WRITE_ACCESS`: Allow write operations (DDL and DML)505 * Default: `"false"`506 * Set to `"true"` to allow DDL (CREATE, ALTER, DROP) and DML (INSERT, UPDATE, DELETE) operations507 * When disabled (default), queries run with `readonly=1` setting to prevent data modifications508* `CLICKHOUSE_ALLOW_DROP`: Allow destructive operations (DROP TABLE, DROP DATABASE, DROP VIEW, DROP DICTIONARY, TRUNCATE TABLE)509 * Default: `"false"`510 * Only takes effect when `CLICKHOUSE_ALLOW_WRITE_ACCESS=true` is also set511 * Set to `"true"` to explicitly allow destructive DROP and TRUNCATE operations512 * This is a safety feature to prevent accidental data deletion during AI exploration513514#### Middleware Variables515516* `MCP_MIDDLEWARE_MODULE`: Python module name containing custom middleware to inject into the MCP server517 * Default: None (no middleware loaded)518 * Set to the module name (without `.py` extension) of your middleware module519 * The module must provide a `setup_middleware(mcp)` function520 * See [Custom Middleware](#custom-middleware) for details and examples521522#### chDB Variables523524* `CHDB_ENABLED`: Enable/disable chDB functionality525 * Default: `"false"`526 * Set to `"true"` to enable chDB tools527* `CHDB_DATA_PATH`: The path to the chDB data directory528 * Default: `":memory:"` (in-memory database)529 * Use `:memory:` for in-memory database530 * Use a file path for persistent storage (e.g., `/path/to/chdb/data`)531532#### Example Configurations533534For local development with Docker:535536```env537# Required variables538CLICKHOUSE_HOST=localhost539CLICKHOUSE_USER=default540CLICKHOUSE_PASSWORD=clickhouse541542# Optional: Override defaults for local development543CLICKHOUSE_SECURE=false # Uses port 8123 automatically544CLICKHOUSE_VERIFY=false545```546547For ClickHouse Cloud:548549```env550# Required variables551CLICKHOUSE_HOST=your-instance.clickhouse.cloud552CLICKHOUSE_USER=default553CLICKHOUSE_PASSWORD=your-password554555# Optional: These use secure defaults556# CLICKHOUSE_SECURE=true # Uses port 8443 automatically557# CLICKHOUSE_DATABASE=your_database558```559560For ClickHouse SQL Playground:561562```env563CLICKHOUSE_HOST=sql-clickhouse.clickhouse.com564CLICKHOUSE_USER=demo565CLICKHOUSE_PASSWORD=566# Uses secure defaults (HTTPS on port 8443)567```568569For chDB only (in-memory):570571```env572# chDB configuration573CHDB_ENABLED=true574CLICKHOUSE_ENABLED=false575# CHDB_DATA_PATH defaults to :memory:576```577578For chDB with persistent storage:579580```env581# chDB configuration582CHDB_ENABLED=true583CLICKHOUSE_ENABLED=false584CHDB_DATA_PATH=/path/to/chdb/data585```586587For MCP Inspector or remote access with HTTP transport:588589```env590CLICKHOUSE_HOST=localhost591CLICKHOUSE_USER=default592CLICKHOUSE_PASSWORD=clickhouse593CLICKHOUSE_MCP_SERVER_TRANSPORT=http594CLICKHOUSE_MCP_BIND_HOST=0.0.0.0 # Bind to all interfaces595CLICKHOUSE_MCP_BIND_PORT=4200 # Custom port (default: 8000)596CLICKHOUSE_MCP_AUTH_TOKEN=your-generated-token # Required for HTTP/SSE597```598599For local development with HTTP transport (authentication disabled):600601```env602CLICKHOUSE_HOST=localhost603CLICKHOUSE_USER=default604CLICKHOUSE_PASSWORD=clickhouse605CLICKHOUSE_MCP_SERVER_TRANSPORT=http606CLICKHOUSE_MCP_AUTH_DISABLED=true # Only for local development!607```608609When using HTTP transport, the server will run on the configured port (default 8000). For example, with the above configuration:610- MCP endpoint: `http://localhost:4200/mcp`611- Health check: `http://localhost:4200/health`612613You can set these variables in your environment, in a `.env` file, or in the Claude Desktop configuration:614615```json616{617 "mcpServers": {618 "mcp-clickhouse": {619 "command": "uv",620 "args": [621 "run",622 "--with",623 "mcp-clickhouse",624 "--python",625 "3.10",626 "mcp-clickhouse"627 ],628 "env": {629 "CLICKHOUSE_HOST": "<clickhouse-host>",630 "CLICKHOUSE_USER": "<clickhouse-user>",631 "CLICKHOUSE_PASSWORD": "<clickhouse-password>",632 "CLICKHOUSE_DATABASE": "<optional-database>",633 "CLICKHOUSE_MCP_SERVER_TRANSPORT": "stdio",634 "CLICKHOUSE_MCP_BIND_HOST": "127.0.0.1",635 "CLICKHOUSE_MCP_BIND_PORT": "8000"636 }637 }638 }639}640```641642Note: The bind host and port settings are only used when transport is set to "http" or "sse".643644### Running tests645646```bash647uv sync --all-extras --dev # install dev dependencies648uv run ruff check . # run linting649650docker compose up -d test_services # start ClickHouse651uv run pytest -v tests652uv run pytest -v tests/test_tool.py # ClickHouse only653uv run pytest -v tests/test_chdb_tool.py # chDB only654```655656## YouTube Overview657658[](https://www.youtube.com/watch?v=y9biAm_Fkqw)659
Full transparency — inspect the skill content before installing.