ClickHouse

by clickhouse

818 stars
899 downloads
Not rated
GitHub

About

Integrates with ClickHouse to enable natural language querying and exploration of large datasets while maintaining read-only safeguards.

Details

Author
clickhouse
Repository
ClickHouse/mcp-clickhouse
GitHub stars
818
Downloads
899
License
Apache License 2.0
Categories
Developer Tools, Database, Other, Productivity, AI, Design, Search, Knowledge Base, Frontend
Tags
#sql, #analytics

- Execute SQL queries on ClickHouse (read‑only by default)
- List all databases in your ClickHouse cluster
- List tables with pagination, filtering (LIKE/NOT LIKE)
- Support for chDB embedded ClickHouse engine
- Health check endpoint for HTTP/SSE transports
- Authentication via static bearer token or OAuth/OIDC

Setting up with Highlight

This MCP is not yet compatible with Highlight’s one-click setup. However, you can still use it with Highlight by following these steps:

  1. Download and install Highlight from highlightai.com/download
  2. Navigate to the plugins tab and select "Add Custom Plugin"
  3. Configure the plugin with the settings below
    Plugin Name ClickHouse
    Command (node, npx, python, etc.) uv
    Arguments
    • Argument 1 run
    • Argument 2 --with
    • Argument 3 mcp-clickhouse
    • Argument 4 --python
    • Argument 5 3.10
    • Argument 6 mcp-clickhouse
    Environment
    • CLICKHOUSE_HOST <clickhouse-host>
    • CLICKHOUSE_PORT <clickhouse-port>
    • CLICKHOUSE_ROLE <clickhouse-role>
    • CLICKHOUSE_USER <clickhouse-user>
    • CLICKHOUSE_SECURE true
    • CLICKHOUSE_VERIFY true
    • CLICKHOUSE_PASSWORD <clickhouse-password>
    • CLICKHOUSE_CONNECT_TIMEOUT 30
    • CLICKHOUSE_SEND_RECEIVE_TIMEOUT 30

    Please refer to the README for specific instructions on how to obtain API keys or other required environment variables.

  4. Enable "Start Automatically" if you want the plugin to start when Highlight launches

From the repository

Development Mode Disabling Authentication

For local development and testing only, you can disable authentication by setting:

export CLICKHOUSE_MCP_AUTH_DISABLED=true

WARNING:Only use this for local development. Do not disable authentication when the server is exposed to any network.

This MCP server supports both ClickHouse and chDB. You can enable either or both depending on your needs.
-

Open the Claude Desktop configuration file located at:

- On macOS:~/Library/Application Support/Claude/claude_desktop_config.json
- On Windows:%APPDATA%/Claude/claude_desktop_config.json

{ "mcpServers": { "mcp-clickhouse": { "command": "uv", "args": ](https://gofastmcp.com/servers/auth)[ "run", "--with", "mcp-clickhouse", "--python", "3.10", "mcp-clickhouse" ], "env": { "CLICKHOUSE_HOST": "<clickhouse-host>", "CLICKHOUSE_PORT": "<clickhouse-port>", "CLICKHOUSE_USER": "<clickhouse-user>", "CLICKHOUSE_PASSWORD": "<clickhouse-password>", "CLICKHOUSE_ROLE": "<clickhouse-role>", "CLICKHOUSE_SECURE": "true", "CLICKHOUSE_VERIFY": "true", "CLICKHOUSE_CONNECT_TIMEOUT": "30", "CLICKHOUSE_SEND_RECEIVE_TIMEOUT": "30" } } } }

Update the environment variables to point to your own ClickHouse service.

Or, if you'd like to try it out with theClickHouse SQL Playground, you can use the following config:

{ "mcpServers": { "mcp-clickhouse": { "command": "uv", "args": [ "run", "--with", "mcp-clickhouse", "--python", "3.10", "mcp-clickhouse" ], "env": { "CLICKHOUSE_HOST": "sql-clickhouse.clickhouse.com", "CLICKHOUSE_PORT": "8443", "CLICKHOUSE_USER": "demo", "CLICKHOUSE_PASSWORD": "", "CLICKHOUSE_SECURE": "true", "CLICKHOUSE_VERIFY": "true", "CLICKHOUSE_CONNECT_TIMEOUT": "30", "CLICKHOUSE_SEND_RECEIVE_TIMEOUT": "30" } } } }

For chDB (embedded ClickHouse engine), add the following configuration:

{ "mcpServers": { "mcp-clickhouse": { "command": "uv", "args": [ "run", "--with", "mcp-clickhouse[chdb]", "--python", "3.10", "mcp-clickhouse" ], "env": { "CHDB_ENABLED": "true", "CLICKHOUSE_ENABLED": "false", "CHDB_DATA_PATH": "/path/to/chdb/data" } } } }

You can also enable both ClickHouse and chDB simultaneously:

{ "mcpServers": { "mcp-clickhouse": { "command": "uv", "args": [ "run", "--with", "mcp-clickhouse[chdb]", "--python", "3.10", "mcp-clickhouse" ], "env": { "CLICKHOUSE_HOST": "<clickhouse-host>", "CLICKHOUSE_PORT": "<clickhouse-port>", "CLICKHOUSE_USER": "<clickhouse-user>", "CLICKHOUSE_PASSWORD": "<clickhouse-password>", "CLICKHOUSE_SECURE": "true", "CLICKHOUSE_VERIFY": "true", "CLICKHOUSE_CONNECT_TIMEOUT": "30", "CLICKHOUSE_SEND_RECEIVE_TIMEOUT": "30", "CHDB_ENABLED": "true", "CHDB_DATA_PATH": "/path/to/chdb/data" } } } }

-

Locate the command entry foruvand replace it with the absolute path to theuvexecutable. This ensures that the correct version ofuvis used when starting the server. On a mac, you can find this path usingwhich uv.

Restart Claude Desktop to apply the changes.

By default, this MCP enforces read-only queries so that accidental mutations cannot happen during exploration. To allow DDL or INSERT/UPDATE statements, set theCLICKHOUSE_ALLOW_WRITE_ACCESSenvironment variable totrue. The server keeps enforcing read-only mode if the ClickHouse instance itself disallows writes.

Even 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.

To enable destructive operations, set both flags:

"env": { "CLICKHOUSE_ALLOW_WRITE_ACCESS": "true", "CLICKHOUSE_ALLOW_DROP": "true" }

This two-tier approach ensures that accidental drops are very difficult:

- Write operations(INSERT, UPDATE, CREATE) requireCLICKHOUSE_ALLOW_WRITE_ACCESS=true
- Destructive operations(DROP, TRUNCATE) additionally requireCLICKHOUSE_ALLOW_DROP=true

Running Without Uv Using System Python

If you prefer to use the system Python installation instead of uv, you can install the package from PyPI and run it directly:

python3 -m pip install 'mcp-clickhouse[chdb]'
python3 -m pip install --upgrade mcp-clickhouse

Update your Claude Desktop configuration to use Python directly:

{ "mcpServers": { "mcp-clickhouse": { "command": "python3", "args": [ "-m", "mcp_clickhouse.main" ], "env": { "CLICKHOUSE_HOST": "<clickhouse-host>", "CLICKHOUSE_PORT": "<clickhouse-port>", "CLICKHOUSE_USER": "<clickhouse-user>", "CLICKHOUSE_PASSWORD": "<clickhouse-password>", "CLICKHOUSE_SECURE": "true", "CLICKHOUSE_VERIFY": "true", "CLICKHOUSE_CONNECT_TIMEOUT": "30", "CLICKHOUSE_SEND_RECEIVE_TIMEOUT": "30" } } } }

Alternatively, you can use the installed script directly:

{ "mcpServers": { "mcp-clickhouse": { "command": "mcp-clickhouse", "env": { "CLICKHOUSE_HOST": "<clickhouse-host>", "CLICKHOUSE_PORT": "<clickhouse-port>", "CLICKHOUSE_USER": "<clickhouse-user>", "CLICKHOUSE_PASSWORD": "<clickhouse-password>", "CLICKHOUSE_SECURE": "true", "CLICKHOUSE_VERIFY": "true", "CLICKHOUSE_CONNECT_TIMEOUT": "30", "CLICKHOUSE_SEND_RECEIVE_TIMEOUT": "30" } } } }

Note: Make sure to use the full path to the Python executable or themcp-clickhousescript if they are not in your system PATH. You can find the paths using:

- which python3for the Python executable
- which mcp-clickhousefor the installed script

You 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.).
- Create a Python module with middleware classes extendingMiddlewareand asetup_middleware(mcp)function:

# my_middleware.py import logging from fastmcp.server.middleware import Middleware, MiddlewareContext, CallNext logger = logging.getLogger("my-middleware") class LoggingMiddleware(Middleware): """Log all tool calls.""" async def on_call_tool(self, context: MiddlewareContext, call_next: CallNext): tool_name = context.message.name if hasattr(context.message, 'name') else 'unknown' logger.info(f"Calling tool: {tool_name}") result = await call_next(context) logger.info(f"Tool {tool_name} completed") return result def setup_middleware(mcp): """Register middleware with the MCP server.""" mcp.add_middleware(LoggingMiddleware())

- Set theMCP_MIDDLEWARE_MODULEenvironment variable to the module name (without.pyextension):

{ "mcpServers": { "mcp-clickhouse": { "command": "uv", "args": ["run", "--with", "mcp-clickhouse", "--python", "3.10", "mcp-clickhouse"], "env": { "CLICKHOUSE_HOST": "<clickhouse-host>", "CLICKHOUSE_USER": "<clickhouse-user>", "CLICKHOUSE_PASSWORD": "<clickhouse-password>", "MCP_MIDDLEWARE_MODULE": "my_middleware" } } } }

- 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).

An example middleware module is provided inexample_middleware.pyshowing common patterns:

- Logging all MCP requests
- Logging tool calls specifically
- Measuring request processing time

"env": { "MCP_MIDDLEWARE_MODULE": "example_middleware" }

TheMiddlewarebase class provides hooks for different MCP operations:

- on_message(context, call_next)- Called for all messages
- on_request(context, call_next)- Called for all requests
- on_notification(context, call_next)- Called for all notifications
- on_call_tool(context, call_next)- Called when a tool is executed
- on_read_resource(context, call_next)- Called when a resource is read
- on_get_prompt(context, call_next)- Called when a prompt is retrieved
- on_list_tools(context, call_next)- Called when listing tools
- on_list_resources(context, call_next)- Called when listing resources
- on_list_resource_templates(context, call_next)- Called when listing resource templates
- on_list_prompts(context, call_next)- Called when listing prompts

Each hook receives aMiddlewareContextobject containing the message and metadata, and acall_nextfunction to continue the pipeline.

Dynamic Client Configuration Via Context State

Middleware can override ClickHouse client configuration on a per-request basis using theCLIENT_CONFIG_OVERRIDES_KEYcontext state key. The server merges these overrides with the base configuration from environment variables.

from fastmcp.server.dependencies import get_context from mcp_clickhouse.mcp_server import CLIENT_CONFIG_OVERRIDES_KEY ctx = get_context() ctx.set_state(CLIENT_CONFIG_OVERRIDES_KEY, { "connect_timeout": 60, "send_receive_timeout": 120 })

This enables advanced use cases like dynamic timeout adjustments, tenant-specific routing, or per-user connection settings.
-

Intest-servicesdirectory rundocker compose up -dto start the ClickHouse cluster.

Add the following variables to a.envfile in the root of the repository.

Note: The use of thedefaultuser in this context is intended solely for local development purposes.

CLICKHOUSE_HOST=localhost CLICKHOUSE_PORT=8123 CLICKHOUSE_USER=default CLICKHOUSE_PASSWORD=clickhouse

-

Runuv syncto install the dependencies. To installuvfollow the instructionshere. Then dosource .venv/bin/activate.

For easy testing with the MCP Inspector, runfastmcp dev mcp_clickhouse/mcp_server.pyto start the MCP server.

To test with HTTP transport and the health check endpoint:

# For development, disable authentication CLICKHOUSE_MCP_SERVER_TRANSPORT=http CLICKHOUSE_MCP_AUTH_DISABLED=true python -m mcp_clickhouse.main # Or with authentication (generate a token first) CLICKHOUSE_MCP_SERVER_TRANSPORT=http CLICKHOUSE_MCP_AUTH_TOKEN="your-token" python -m mcp_clickhouse.main # Then in another terminal: curl http://localhost:8000/health

run_query

Execute SQL queries on your ClickHouse cluster. Input: query (string): The SQL query to execute.

list_databases

List all databases on your ClickHouse cluster.

list_tables

List tables in a database with pagination. Required input: database (string). Optional inputs: like / not_like (string): Apply LIKE or NOT LIKE filters to table names, page_token (string): Token returned by a previous call for fetching the next page, page_size (int, default 50): Number of tables returned per page, include_detailed_columns (bool, default true): When false, omits column metadata for lighter responses while keeping the full create_table_query.

run_chdb_select_query

Execute SQL queries using chDB's embedded ClickHouse engine. Input: query (string): The SQL query to execute.

Claude Desktop / Cursor

Paste into your MCP client config file to install this server.

{
    "mcpServers": {
        "clickhouse": {
            "env": {
                "CLICKHOUSE_HOST": "<clickhouse-host>",
                "CLICKHOUSE_PORT": "<clickhouse-port>",
                "CLICKHOUSE_ROLE": "<clickhouse-role>",
                "CLICKHOUSE_USER": "<clickhouse-user>",
                "CLICKHOUSE_SECURE": "true",
                "CLICKHOUSE_VERIFY": "true",
                "CLICKHOUSE_PASSWORD": "<clickhouse-password>",
                "CLICKHOUSE_CONNECT_TIMEOUT": "30",
                "CLICKHOUSE_SEND_RECEIVE_TIMEOUT": "30"
            },
            "args": [
                "run",
                "--with",
                "mcp-clickhouse",
                "--python",
                "3.10",
                "mcp-clickhouse"
            ],
            "command": "uv"
        }
    }
}

Linux

{
    "env": {
        "CLICKHOUSE_HOST": "<clickhouse-host>",
        "CLICKHOUSE_PORT": "<clickhouse-port>",
        "CLICKHOUSE_ROLE": "<clickhouse-role>",
        "CLICKHOUSE_USER": "<clickhouse-user>",
        "CLICKHOUSE_SECURE": "true",
        "CLICKHOUSE_VERIFY": "true",
        "CLICKHOUSE_PASSWORD": "<clickhouse-password>",
        "CLICKHOUSE_CONNECT_TIMEOUT": "30",
        "CLICKHOUSE_SEND_RECEIVE_TIMEOUT": "30"
    },
    "args": [
        "run",
        "--with",
        "mcp-clickhouse",
        "--python",
        "3.10",
        "mcp-clickhouse"
    ],
    "command": "uv"
}

Macos

{
    "env": {
        "CLICKHOUSE_HOST": "<clickhouse-host>",
        "CLICKHOUSE_PORT": "<clickhouse-port>",
        "CLICKHOUSE_ROLE": "<clickhouse-role>",
        "CLICKHOUSE_USER": "<clickhouse-user>",
        "CLICKHOUSE_SECURE": "true",
        "CLICKHOUSE_VERIFY": "true",
        "CLICKHOUSE_PASSWORD": "<clickhouse-password>",
        "CLICKHOUSE_CONNECT_TIMEOUT": "30",
        "CLICKHOUSE_SEND_RECEIVE_TIMEOUT": "30"
    },
    "args": [
        "run",
        "--with",
        "mcp-clickhouse",
        "--python",
        "3.10",
        "mcp-clickhouse"
    ],
    "command": "uv"
}

Windows

{
    "env": {
        "CLICKHOUSE_HOST": "<clickhouse-host>",
        "CLICKHOUSE_PORT": "<clickhouse-port>",
        "CLICKHOUSE_ROLE": "<clickhouse-role>",
        "CLICKHOUSE_USER": "<clickhouse-user>",
        "CLICKHOUSE_SECURE": "true",
        "CLICKHOUSE_VERIFY": "true",
        "CLICKHOUSE_PASSWORD": "<clickhouse-password>",
        "CLICKHOUSE_CONNECT_TIMEOUT": "30",
        "CLICKHOUSE_SEND_RECEIVE_TIMEOUT": "30"
    },
    "args": [
        "run",
        "--with",
        "mcp-clickhouse",
        "--python",
        "3.10",
        "mcp-clickhouse"
    ],
    "command": "uv"
}
- Execute SQL queries on your ClickHouse cluster. - Input:`query`(string): The SQL query to execute. - Queries run in read-only mode by default (`CLICKHOUSE_ALLOW_WRITE_ACCESS=false`), but writes can be enabled explicitly if needed. - List all databases on your ClickHouse cluster. - List tables in a database with pagination. - Required input:`database`(string). - Optional inputs: - `like`/`not_like`(string): Apply`LIKE`or`NOT LIKE`filters to table names. - `page_token`(string): Token returned by a previous call for fetching the next page. - `page_size`(int, default`50`): Number of tables returned per page. - `include_detailed_columns`(bool, default`true`): When`false`, omits column metadata for lighter responses while keeping the full`create_table_query`. - `tables`: Array of table objects for the current page. - `next_page_token`: Pass this value back to fetch the next page, or`null`when there are no more tables. - `total_tables`: Total count of tables that match the supplied filters. - `run_chdb_select_query` - Execute SQL queries using[chDB's embedded ClickHouse engine. - Input:`query`(string): The SQL query to execute. - Query data directly from various sources (files, URLs, databases) without ETL processes. - Requires the optional`chdb`extra:`pip install 'mcp-clickhouse](https://github.com/chdb-io/chdb)[chdb]'` When running with HTTP or SSE transport, a health check endpoint is available at`/health`. This endpoint: - Returns`200 OK`(body:`OK`) if the server is healthy and can connect to ClickHouse - Returns`503 Service Unavailable`with a generic error message if the server cannot connect to ClickHouse The endpoint is intentionally unauthenticated so orchestrator probes (e.g. Kubernetes liveness/readiness, load balancers) can reach it without credentials. The response body is deliberately minimal to avoid leaking backend version strings or error details; debug failures via the server logs. ``` `curl http://localhost:8000/health # Response: OK` ``` When 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. Three authentication modes are supported. Pick one: Startup fails if none of these are configured for HTTP/SSE transports. - Generate a secure token (can be any random string): ``` `# Using uuidgen (macOS/Linux) uuidgen # Using openssl openssl rand -hex 32` ``` ``` `export CLICKHOUSE_MCP_AUTH_TOKEN="your-generated-token"` ``` Configure your MCP client to include the token in requests: For Claude Desktop with HTTP/SSE transport: ``` `{ "mcpServers": { "mcp-clickhouse": { "url": "http://127.0.0.1:8000", "headers": { "Authorization": "Bearer your-generated-token" } } } }` ``` Note: the`/health`endpoint is intentionally unauthenticated (see[Health Check Endpointabove). To verify that bearer-token auth is actually rejecting unauthenticated requests, hit the MCP endpoint itself e.g. with the MCP Inspector, or by POSTing a JSON-RPC request to`/mcp`with and without the`Authorization`header and confirming the unauthenticated call returns`401`. For production deployments with identity providers (Azure Entra, Google, GitHub, WorkOS, etc.), delegate authentication to](#health-check-endpoint)[FastMCP's built-in auth providersinstead of using a static token. Set`FASTMCP_SERVER_AUTH`to the**full class path**of a FastMCP auth provider, along with the provider-specific`FASTMCP_SERVER_AUTH_*`variables, and leave`CLICKHOUSE_MCP_AUTH_TOKEN`unset. ``` `export FASTMCP_SERVER_AUTH=fastmcp.server.auth.providers.azure.AzureProvider export FASTMCP_SERVER_AUTH_AZURE_TENANT_ID="<tenant-id>" export FASTMCP_SERVER_AUTH_AZURE_CLIENT_ID="<client-id>" export FASTMCP_SERVER_AUTH_AZURE_CLIENT_SECRET="<client-secret>"` ``` See the](https://gofastmcp.com/servers/auth)[FastMCP docsfor the full list of providers and their required environment variables. #### Development Mode (Disabling Authentication) For local development and testing only, you can disable authentication by setting: ``` `export CLICKHOUSE_MCP_AUTH_DISABLED=true` ``` **WARNING:**Only use this for local development. Do not disable authentication when the server is exposed to any network. This MCP server supports both ClickHouse and chDB. You can enable either or both depending on your needs. - Open the Claude Desktop configuration file located at: - On macOS:`~/Library/Application Support/Claude/claude_desktop_config.json` - On Windows:`%APPDATA%/Claude/claude_desktop_config.json` ``` `{ "mcpServers": { "mcp-clickhouse": { "command": "uv", "args": ](https://gofastmcp.com/servers/auth)[ "run", "--with", "mcp-clickhouse", "--python", "3.10", "mcp-clickhouse" ], "env": { "CLICKHOUSE_HOST": "<clickhouse-host>", "CLICKHOUSE_PORT": "<clickhouse-port>", "CLICKHOUSE_USER": "<clickhouse-user>", "CLICKHOUSE_PASSWORD": "<clickhouse-password>", "CLICKHOUSE_ROLE": "<clickhouse-role>", "CLICKHOUSE_SECURE": "true", "CLICKHOUSE_VERIFY": "true", "CLICKHOUSE_CONNECT_TIMEOUT": "30", "CLICKHOUSE_SEND_RECEIVE_TIMEOUT": "30" } } } }` ``` Update the environment variables to point to your own ClickHouse service. Or, if you'd like to try it out with the[ClickHouse SQL Playground, you can use the following config: ``` `{ "mcpServers": { "mcp-clickhouse": { "command": "uv", "args": ](https://sql.clickhouse.com/)[ "run", "--with", "mcp-clickhouse", "--python", "3.10", "mcp-clickhouse" ], "env": { "CLICKHOUSE_HOST": "sql-clickhouse.clickhouse.com", "CLICKHOUSE_PORT": "8443", "CLICKHOUSE_USER": "demo", "CLICKHOUSE_PASSWORD": "", "CLICKHOUSE_SECURE": "true", "CLICKHOUSE_VERIFY": "true", "CLICKHOUSE_CONNECT_TIMEOUT": "30", "CLICKHOUSE_SEND_RECEIVE_TIMEOUT": "30" } } } }` ``` For chDB (embedded ClickHouse engine), add the following configuration: ``` `{ "mcpServers": { "mcp-clickhouse": { "command": "uv", "args": [ "run", "--with", "mcp-clickhouse[chdb]", "--python", "3.10", "mcp-clickhouse" ], "env": { "CHDB_ENABLED": "true", "CLICKHOUSE_ENABLED": "false", "CHDB_DATA_PATH": "/path/to/chdb/data" } } } }` ``` You can also enable both ClickHouse and chDB simultaneously: ``` `{ "mcpServers": { "mcp-clickhouse": { "command": "uv", "args": [ "run", "--with", "mcp-clickhouse[chdb]", "--python", "3.10", "mcp-clickhouse" ], "env": { "CLICKHOUSE_HOST": "<clickhouse-host>", "CLICKHOUSE_PORT": "<clickhouse-port>", "CLICKHOUSE_USER": "<clickhouse-user>", "CLICKHOUSE_PASSWORD": "<clickhouse-password>", "CLICKHOUSE_SECURE": "true", "CLICKHOUSE_VERIFY": "true", "CLICKHOUSE_CONNECT_TIMEOUT": "30", "CLICKHOUSE_SEND_RECEIVE_TIMEOUT": "30", "CHDB_ENABLED": "true", "CHDB_DATA_PATH": "/path/to/chdb/data" } } } }` ``` - 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`. Restart Claude Desktop to apply the changes. By 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. Even 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. To enable destructive operations, set both flags: ``` `"env": { "CLICKHOUSE_ALLOW_WRITE_ACCESS": "true", "CLICKHOUSE_ALLOW_DROP": "true" }` ``` This two-tier approach ensures that accidental drops are very difficult: - **Write operations**(INSERT, UPDATE, CREATE) require`CLICKHOUSE_ALLOW_WRITE_ACCESS=true` - **Destructive operations**(DROP, TRUNCATE) additionally require`CLICKHOUSE_ALLOW_DROP=true` ### Running Without uv (Using System Python) If you prefer to use the system Python installation instead of uv, you can install the package from PyPI and run it directly: ``` `python3 -m pip install 'mcp-clickhouse[chdb]'` ``` ``` `python3 -m pip install --upgrade mcp-clickhouse` ``` Update your Claude Desktop configuration to use Python directly: ``` `{ "mcpServers": { "mcp-clickhouse": { "command": "python3", "args": [ "-m", "mcp_clickhouse.main" ], "env": { "CLICKHOUSE_HOST": "<clickhouse-host>", "CLICKHOUSE_PORT": "<clickhouse-port>", "CLICKHOUSE_USER": "<clickhouse-user>", "CLICKHOUSE_PASSWORD": "<clickhouse-password>", "CLICKHOUSE_SECURE": "true", "CLICKHOUSE_VERIFY": "true", "CLICKHOUSE_CONNECT_TIMEOUT": "30", "CLICKHOUSE_SEND_RECEIVE_TIMEOUT": "30" } } } }` ``` Alternatively, you can use the installed script directly: ``` `{ "mcpServers": { "mcp-clickhouse": { "command": "mcp-clickhouse", "env": { "CLICKHOUSE_HOST": "<clickhouse-host>", "CLICKHOUSE_PORT": "<clickhouse-port>", "CLICKHOUSE_USER": "<clickhouse-user>", "CLICKHOUSE_PASSWORD": "<clickhouse-password>", "CLICKHOUSE_SECURE": "true", "CLICKHOUSE_VERIFY": "true", "CLICKHOUSE_CONNECT_TIMEOUT": "30", "CLICKHOUSE_SEND_RECEIVE_TIMEOUT": "30" } } } }` ``` Note: 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: - `which python3`for the Python executable - `which mcp-clickhouse`for the installed script You 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.). - Create a Python module with middleware classes extending`Middleware`and a`setup_middleware(mcp)`function: ``` `# my_middleware.py import logging from fastmcp.server.middleware import Middleware, MiddlewareContext, CallNext logger = logging.getLogger("my-middleware") class LoggingMiddleware(Middleware): """Log all tool calls.""" async def on_call_tool(self, context: MiddlewareContext, call_next: CallNext): tool_name = context.message.name if hasattr(context.message, 'name') else 'unknown' logger.info(f"Calling tool: {tool_name}") result = await call_next(context) logger.info(f"Tool {tool_name} completed") return result def setup_middleware(mcp): """Register middleware with the MCP server.""" mcp.add_middleware(LoggingMiddleware())` ``` - Set the`MCP_MIDDLEWARE_MODULE`environment variable to the module name (without`.py`extension): ``` `{ "mcpServers": { "mcp-clickhouse": { "command": "uv", "args": ["run", "--with", "mcp-clickhouse", "--python", "3.10", "mcp-clickhouse"], "env": { "CLICKHOUSE_HOST": "<clickhouse-host>", "CLICKHOUSE_USER": "<clickhouse-user>", "CLICKHOUSE_PASSWORD": "<clickhouse-password>", "MCP_MIDDLEWARE_MODULE": "my_middleware" } } } }` ``` - 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). An example middleware module is provided in`example_middleware.py`showing common patterns: - Logging all MCP requests - Logging tool calls specifically - Measuring request processing time ``` `"env": { "MCP_MIDDLEWARE_MODULE": "example_middleware" }` ``` The`Middleware`base class provides hooks for different MCP operations: - `on_message(context, call_next)`- Called for all messages - `on_request(context, call_next)`- Called for all requests - `on_notification(context, call_next)`- Called for all notifications - `on_call_tool(context, call_next)`- Called when a tool is executed - `on_read_resource(context, call_next)`- Called when a resource is read - `on_get_prompt(context, call_next)`- Called when a prompt is retrieved - `on_list_tools(context, call_next)`- Called when listing tools - `on_list_resources(context, call_next)`- Called when listing resources - `on_list_resource_templates(context, call_next)`- Called when listing resource templates - `on_list_prompts(context, call_next)`- Called when listing prompts Each hook receives a`MiddlewareContext`object containing the message and metadata, and a`call_next`function to continue the pipeline. ### Dynamic Client Configuration via Context State Middleware can override ClickHouse client configuration on a per-request basis using the`CLIENT_CONFIG_OVERRIDES_KEY`context state key. The server merges these overrides with the base configuration from environment variables. ``` `from fastmcp.server.dependencies import get_context from mcp_clickhouse.mcp_server import CLIENT_CONFIG_OVERRIDES_KEY ctx = get_context() ctx.set_state(CLIENT_CONFIG_OVERRIDES_KEY, { "connect_timeout": 60, "send_receive_timeout": 120 })` ``` This enables advanced use cases like dynamic timeout adjustments, tenant-specific routing, or per-user connection settings. - In`test-services`directory run`docker compose up -d`to start the ClickHouse cluster. Add the following variables to a`.env`file in the root of the repository. *Note: The use of the`default`user in this context is intended solely for local development purposes.* ``` `CLICKHOUSE_HOST=localhost CLICKHOUSE_PORT=8123 CLICKHOUSE_USER=default CLICKHOUSE_PASSWORD=clickhouse` ``` - Run`uv sync`to install the dependencies. To install`uv`follow the instructions[here. Then do`source .venv/bin/activate`. For easy testing with the MCP Inspector, run`fastmcp dev mcp_clickhouse/mcp_server.py`to start the MCP server. To test with HTTP transport and the health check endpoint: ``` `# For development, disable authentication CLICKHOUSE_MCP_SERVER_TRANSPORT=http CLICKHOUSE_MCP_AUTH_DISABLED=true python -m mcp_clickhouse.main # Or with authentication (generate a token first) CLICKHOUSE_MCP_SERVER_TRANSPORT=http CLICKHOUSE_MCP_AUTH_TOKEN="your-token" python -m mcp_clickhouse.main # Then in another terminal: curl http://localhost:8000/health` ``` ](https://docs.astral.sh/uv/)
No reviews yet — be the first

Sign in to leave a review

Use Google, GitHub, or an email account so ratings stay tied to real people.

Email sign in

No reviews posted yet.