Server data from the Official MCP Registry
Official ClickHouse MCP server for querying and exploring ClickHouse clusters and chDB.
About
Official ClickHouse MCP server for querying and exploring ClickHouse clusters and chDB.
Security Report
Valid MCP server (1 strong, 2 medium validity signals). 1 known CVE in dependencies Package registry verified. Imported from the Official MCP Registry.
5 files analyzed · 2 issues found
Security scores are indicators to help you make informed decisions, not guarantees. Always review permissions before connecting any MCP server.
Permissions Required
This plugin requests these system permissions. Most are normal for its category.
What You'll Need
Set these up before or after installing:
Environment variable: CLICKHOUSE_HOST
Environment variable: CLICKHOUSE_USER
Environment variable: CLICKHOUSE_PASSWORD
Environment variable: CLICKHOUSE_PORT
Environment variable: CLICKHOUSE_SECURE
Environment variable: CLICKHOUSE_VERIFY
Environment variable: CLICKHOUSE_CA_CERT
Environment variable: CLICKHOUSE_CLIENT_CERT
Environment variable: CLICKHOUSE_CLIENT_CERT_KEY
Environment variable: CLICKHOUSE_TLS_MODE
Environment variable: CLICKHOUSE_DATABASE
Environment variable: CLICKHOUSE_ROLE
Environment variable: CLICKHOUSE_ALLOW_WRITE_ACCESS
Environment variable: CLICKHOUSE_ALLOW_DROP
Environment variable: CLICKHOUSE_MCP_QUERY_TIMEOUT
Environment variable: CLICKHOUSE_MCP_MAX_WORKERS
How to Install
Add this to your MCP configuration file:
{
"mcpServers": {
"mcp-clickhouse": {
"command": "uvx",
"args": [
"mcp-clickhouse==0.8.0"
],
"env": {
"CLICKHOUSE_HOST": "your-clickhouse-host-here",
"CLICKHOUSE_PORT": "your-clickhouse-port-here",
"CLICKHOUSE_ROLE": "your-clickhouse-role-here",
"CLICKHOUSE_USER": "your-clickhouse-user-here",
"CLICKHOUSE_SECURE": "your-clickhouse-secure-here",
"CLICKHOUSE_VERIFY": "your-clickhouse-verify-here",
"CLICKHOUSE_CA_CERT": "your-clickhouse-ca-cert-here",
"CLICKHOUSE_DATABASE": "your-clickhouse-database-here",
"CLICKHOUSE_PASSWORD": "your-clickhouse-password-here",
"CLICKHOUSE_TLS_MODE": "your-clickhouse-tls-mode-here",
"CLICKHOUSE_ALLOW_DROP": "your-clickhouse-allow-drop-here",
"CLICKHOUSE_CLIENT_CERT": "your-clickhouse-client-cert-here",
"CLICKHOUSE_CLIENT_CERT_KEY": "your-clickhouse-client-cert-key-here",
"CLICKHOUSE_MCP_MAX_WORKERS": "your-clickhouse-mcp-max-workers-here",
"CLICKHOUSE_MCP_QUERY_TIMEOUT": "your-clickhouse-mcp-query-timeout-here",
"CLICKHOUSE_ALLOW_WRITE_ACCESS": "your-clickhouse-allow-write-access-here"
}
}
}
}Some servers take additional arguments. See the repository for details.
Documentation
View on GitHubFrom the project's GitHub README.
ClickHouse MCP Server
An MCP server for ClickHouse.
The server implements MCP 2026-07-28 and supports legacy initialize handshakes from
2024-11-05 through 2025-11-25. Modern clients use sessionless requests and
server/discover. Existing clients can continue to negotiate the legacy protocol.
[!NOTE] HTTP requests without
MCP-Protocol-Versionare routed through legacy handling so clients from before2025-06-18can continue to connect. MCP2026-07-28permits this behavior on servers that support those clients. Modern clients should send the header on every POST request.
Features
ClickHouse Tools
ClickHouse tool responses are JSON-encoded strings. Integers outside
[-9007199254740991, 9007199254740991] are returned as decimal strings to preserve exact
values in JavaScript clients. This applies to query rows and integer table metadata. Safe-range
integers and booleans keep their JSON types.
-
run_query- Execute SQL queries on your ClickHouse cluster.
- Input:
query(string): The SQL query to execute. - Optional input:
params(object): Named values for ClickHouse{name:Type}placeholders. See Query parameters. - Queries run in read-only mode by default (
CLICKHOUSE_ALLOW_WRITE_ACCESS=false), but writes can be enabled explicitly if needed. - Do not end a query with a
FORMATclause. The tool appendsFORMAT Native, so a second one is a syntax error. Withreadonly=1, the default, aSETTINGSclause fails with code 164 (Cannot modify '<setting>' setting in readonly mode) or, in a subquery, has no effect. DESCRIBE (<query>)andEXPLAIN ESTIMATE <query>run here too and are optional ways to inspect a query's result schema or its estimated reads. See Checking a query before running it.
-
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): ApplyLIKEorNOT LIKEfilters to table names.page_token(string): Single-use token returned by a previous call. It is retained for up to one hour.page_size(int, default50): Number of tables returned per page; must be greater than0.include_detailed_columns(bool, defaulttrue): Whenfalse, omits column metadata for lighter responses while keeping the fullcreate_table_query.
- Response shape:
tables: Array of table objects for the current page.next_page_token: Pass this single-use value back before it expires to fetch the next page, ornullwhen there are no more tables.total_tables: Total count of tables that match the supplied filters.
Agents Schema discovery
The server instructions suggest reading Agents Schema's
canonical AGENTS.ROOT through run_query when list_databases reveals an AGENTS
database, before writing analytical SQL. This is guidance for the agent: no metadata
is fetched automatically, tool results are unchanged, and existing ClickHouse
permissions still apply. If AGENTS.ROOT is missing or inaccessible, normal discovery
and queries remain available.
Query parameters
Pass values separately from SQL through the optional params object:
{
"query": "SELECT {id:UInt32} AS id, {name:String} AS name",
"params": {"id": 13, "name": "O'Reilly"}
}
Use ClickHouse's {name:Type} placeholders without quoting them. Keep the opening
brace, name, and colon adjacent, as in {id:UInt32}. Spaces after the colon and
within the type are supported, as in {id: UInt32} and {amount:Decimal(18, 4)}.
For compatibility across supported driver versions, start names with a letter or
underscore and use only letters, digits, and underscores.
Python-style %s or %(name)s formatting and the driver's $name$ raw binary
parameters are not supported. Calls with only query still work. Omitting params,
passing null, or passing an empty object leaves the query unbound.
Parameter values can be JSON strings, numbers, booleans, null, or arrays, provided
they match the declared ClickHouse type:
- Use
nullwith aNullable(...)type. - Pass exact integers outside JavaScript's safe range as decimal strings, for
example
"18446744073709551615"with{id:UInt64}. Dates, timestamps, and exact decimals can also be passed as strings with the corresponding ClickHouse type. - Bind vectors as one array, for example
{vector:Array(Float32)}with"params": {"vector": [0.25, 0.5, 0.75]}. - Nulls inside arrays depend on the installed driver. They work with clickhouse-connect 1.8.0 but fail with the supported minimum 1.0.0.
- JSON lists and objects cannot bind to ClickHouse
TupleandMaptypes.
Missing values and incompatible types return query errors. With non-empty params,
a query carrying many unterminated {name: placeholder starts is rejected, including
placeholder-like text in comments or string literals.
Parameterized queries use the same write protection, timeouts, cancellation, and
JSON result encoding as other queries.
Parameter values stay out of the MCP server's normal SQL log messages, but remain
in MCP tool arguments and may appear in backend errors. ClickHouse 26.3.20.7
substitutes values into the query text in system.query_log, system.processes,
and system.text_log. Parameter binding is not a privacy feature and does not
reduce the number of vector values sent in a tool call.
Checking a query before running it
run_query also runs DESCRIBE and EXPLAIN ESTIMATE. Both are optional checks: reach for DESCRIBE when you need a query's output columns and types, and for EXPLAIN ESTIMATE before a SELECT that could be expensive.
DESCRIBE (<query>) inspects the result schema and returns the same output-column metadata as DESCRIBE TABLE:
DESCRIBE (SELECT user, sum(amt) FROM events WHERE ts > now() - INTERVAL 30 DAY GROUP BY user)
user String
sum(amt) Decimal(38, 2)
ClickHouse has to analyze the query to answer, so analysis errors surface here, with ClickHouse's own message, instead of part way through execution:
DESCRIBE (SELECT usr FROM events) -> Code: 47. Unknown expression identifier `usr` ... Maybe you meant: ['user']
DESCRIBE (SELECT * FROM nosuch) -> Code: 60. Unknown table expression identifier 'nosuch'
A query that describes cleanly can still fail when it runs, on a memory limit or a remote server error, and it says nothing about cost.
EXPLAIN ESTIMATE <query> returns the parts, rows and marks the query would read, one row per table, which is what separates a primary key lookup from a full scan:
EXPLAIN ESTIMATE SELECT count() FROM events WHERE id = 42
database table parts rows marks
default events 1 8192 1
Those are estimated reads from MergeTree family tables, after primary key and partition pruning. They are not run time and not result size, and other table engines are not covered.
Neither statement runs the query body, but analysis is not always free: DESCRIBE (SELECT (SELECT sleep(1))) executes the scalar subquery while analyzing. Both are read-only and work under the default CLICKHOUSE_ALLOW_WRITE_ACCESS=false. See the ClickHouse documentation for EXPLAIN ESTIMATE and DESCRIBE.
chDB Tools
run_chdb_select_query- Execute SQL queries using chDB's embedded ClickHouse engine.
- Input:
query(string): The SQL query to execute. - Integers outside
[-9007199254740991, 9007199254740991]are returned as decimal strings. - Query data directly from various sources (files, URLs, databases) without ETL processes.
- Requires the optional
chdbextra:pip install 'mcp-clickhouse[chdb]'
Health Check Endpoint
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 Unavailablewith a generic error message if the server cannot connect to ClickHouse - Returns
503if a ClickHouse probe does not finish within two seconds. Concurrent requests share one in-flight probe - Reuses a completed probe result for one second, so probes that arrive in quick succession do not each connect to ClickHouse. A failure or a recovery can therefore be reported up to a second late
GET and HEAD requests to the endpoint are intentionally unauthenticated and exempt from Host and Origin validation so orchestrator probes (e.g. Kubernetes liveness/readiness, load balancers) can use runtime-assigned pod or target IPs without extra configuration. /health is reserved and cannot be used as the MCP transport path. The response body is deliberately minimal to avoid leaking backend version strings or error details; debug failures via the server logs.
Example:
curl http://localhost:8000/health
# Response: OK
Security
Authentication for HTTP/SSE Transports
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:
| Mode | When to use | Env var |
|---|---|---|
| Static bearer token | Simple deployments, internal services | CLICKHOUSE_MCP_AUTH_TOKEN |
| OAuth / OIDC (via FastMCP) | Azure Entra, Google, GitHub, WorkOS, etc. | FASTMCP_SERVER_AUTH=<provider-class-path> (+ provider-specific FASTMCP_SERVER_AUTH_* vars) |
| Disabled | Local development only | CLICKHOUSE_MCP_AUTH_DISABLED=true |
Startup fails if none of these are configured for HTTP/SSE transports.
Setting Up Authentication
-
Generate a secure token (can be any random string):
# Using uuidgen (macOS/Linux) uuidgen # Using openssl openssl rand -hex 32 -
Configure the server with the token:
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
/healthendpoint is intentionally unauthenticated (see Health Check Endpoint above). 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/mcpwith and without theAuthorizationheader and confirming the unauthenticated call returns401.
OAuth / OIDC via FastMCP
For production deployments with identity providers (Azure Entra, Google, GitHub, WorkOS, etc.), delegate authentication to FastMCP's built-in auth providers instead 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.
Example (Azure Entra):
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>"
export FASTMCP_SERVER_AUTH_AZURE_BASE_URL="https://mcp.example.com"
export FASTMCP_SERVER_AUTH_AZURE_REQUIRED_SCOPES="read access_as_user"
mcp-clickhouse retains these FastMCP 2.14.7 environment prefixes for the FastMCP 4.0.0 built-in providers:
| Provider class path | Provider variable prefix |
|---|---|
fastmcp.server.auth.providers.auth0.Auth0Provider | FASTMCP_SERVER_AUTH_AUTH0_ |
fastmcp.server.auth.providers.aws.AWSCognitoProvider | FASTMCP_SERVER_AUTH_AWS_COGNITO_ |
fastmcp.server.auth.providers.azure.AzureProvider | FASTMCP_SERVER_AUTH_AZURE_ |
fastmcp.server.auth.providers.descope.DescopeProvider | FASTMCP_SERVER_AUTH_DESCOPEPROVIDER_ |
fastmcp.server.auth.providers.discord.DiscordProvider | FASTMCP_SERVER_AUTH_DISCORD_ |
fastmcp.server.auth.providers.github.GitHubProvider | FASTMCP_SERVER_AUTH_GITHUB_ |
fastmcp.server.auth.providers.google.GoogleProvider | FASTMCP_SERVER_AUTH_GOOGLE_ |
fastmcp.server.auth.providers.introspection.IntrospectionTokenVerifier | FASTMCP_SERVER_AUTH_INTROSPECTION_ |
fastmcp.server.auth.providers.jwt.JWTVerifier | FASTMCP_SERVER_AUTH_JWT_ |
fastmcp.server.auth.providers.oci.OCIProvider | FASTMCP_SERVER_AUTH_OCI_ |
fastmcp.server.auth.providers.scalekit.ScalekitProvider | FASTMCP_SERVER_AUTH_SCALEKITPROVIDER_ |
fastmcp.server.auth.providers.supabase.SupabaseProvider | FASTMCP_SERVER_AUTH_SUPABASE_ |
fastmcp.server.auth.providers.workos.WorkOSProvider | FASTMCP_SERVER_AUTH_WORKOS_ |
fastmcp.server.auth.providers.workos.AuthKitProvider | FASTMCP_SERVER_AUTH_AUTHKITPROVIDER_ |
mcp-clickhouse also configures fastmcp.server.auth.providers.azure.AzureJWTVerifier
from the FASTMCP_SERVER_AUTH_AZUREJWT_ prefix. FastMCP 2 had no environment contract
for this verifier. A TENANT_ID of common, organizations, or consumers skips the
issuer check, so tokens issued for the app by any Entra tenant are accepted.
mcp-clickhouse also configures fastmcp.server.auth.providers.keycloak.KeycloakAuthProvider
from the FASTMCP_SERVER_AUTH_KEYCLOAK_ prefix. FastMCP 2 had no Keycloak provider.
REALM_URL, BASE_URL, and AUDIENCE are required. AUDIENCE takes one value or a JSON
list. REQUIRED_SCOPES defaults to openid, also when it is set to an empty value.
export FASTMCP_SERVER_AUTH=fastmcp.server.auth.providers.keycloak.KeycloakAuthProvider
export FASTMCP_SERVER_AUTH_KEYCLOAK_REALM_URL="https://keycloak.example.com/realms/<realm>"
export FASTMCP_SERVER_AUTH_KEYCLOAK_BASE_URL="https://mcp.example.com"
export FASTMCP_SERVER_AUTH_KEYCLOAK_AUDIENCE="https://mcp.example.com"
The provider checks access tokens against the realm's signing keys and publishes
protected resource metadata that names the realm as the authorization server, so MCP
clients can start the login on their own. It does not proxy the OAuth flow: clients
register with Keycloak through dynamic client registration or use a pre-registered
client. FastMCP requires Keycloak 26.6.0 or later for dynamic client registration with
MCP clients. Access tokens must carry one of the AUDIENCE values in aud. Keycloak does
not add this server to aud by default. Set AUDIENCE to a fixed value that names this
server, for example its BASE_URL, and add an Audience protocol mapper with that value as
included custom audience to a client scope that the MCP clients get. For clients that
register dynamically, make it a realm default client scope before they register. Do not
use account, because Keycloak puts it in aud by default. Tokens must also carry every
required scope, so if your access tokens do not carry openid in their scope claim, set
REQUIRED_SCOPES to scopes they do carry.
Append the uppercase provider field name to the prefix. See the FastMCP docs for each provider's configuration requirements.
Accepting tokens from more than one source
Some deployments serve two kinds of callers from one endpoint, for example interactive
MCP clients that sign in through an OAuth proxy and a backend that sends access tokens
it obtained itself. Set FASTMCP_SERVER_AUTH_VERIFIERS to a comma-separated list of
token verifier class paths to accept their tokens in addition to the
FASTMCP_SERVER_AUTH provider. mcp-clickhouse combines them with FastMCP's
MultiAuth.
Example (Entra OAuth proxy for MCP clients, plus Entra access tokens such as On-Behalf-Of tokens from a backend, both for one app registration):
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>"
export FASTMCP_SERVER_AUTH_AZURE_BASE_URL="https://mcp.example.com"
export FASTMCP_SERVER_AUTH_AZURE_REQUIRED_SCOPES="mcp.read"
export FASTMCP_SERVER_AUTH_VERIFIERS=fastmcp.server.auth.providers.azure.AzureJWTVerifier
export FASTMCP_SERVER_AUTH_AZUREJWT_TENANT_ID="<tenant-id>"
export FASTMCP_SERVER_AUTH_AZUREJWT_CLIENT_ID="<client-id>"
export FASTMCP_SERVER_AUTH_AZUREJWT_REQUIRED_SCOPES="mcp.read"
- The
FASTMCP_SERVER_AUTHprovider is tried first, then each verifier in the listed order. The first one that accepts the token wins, so every entry is a trust source: a token valid for any of them reaches the tools. - The
FASTMCP_SERVER_AUTHprovider's required scopes apply to tokens from every source, whether the primary provider is an OAuth provider or a token verifier. An OAuth primary keeps its routes and discovery metadata. A token-verifier primary serves no OAuth routes. - Each entry must be a
TokenVerifiersubclass and is configured from its own prefix, exactly as it would be underFASTMCP_SERVER_AUTH. A class can therefore appear only once acrossFASTMCP_SERVER_AUTHandFASTMCP_SERVER_AUTH_VERIFIERS. FASTMCP_SERVER_AUTH_VERIFIERSextends the FastMCP provider mode only. It is rejected together withCLICKHOUSE_MCP_AUTH_TOKENorCLICKHOUSE_MCP_AUTH_DISABLED=true.
Auth values set directly in the process environment take precedence case-insensitively.
The default .env load starts at the installed mcp_clickhouse package directory,
resolves symlinks first, and walks upward to the filesystem root. It loads the first
.env it finds and loads nothing if there is none. It never reads the working
directory, regardless of how the server is launched. A source checkout normally finds
the repository root .env. That file may also provide FASTMCP_SERVER_AUTH and its
provider fields. Its values take precedence over the explicit or compatibility auth
file.
For FastMCP 2 compatibility, mcp-clickhouse reads missing provider fields from .env
in the working directory, but that compatibility fallback cannot select
FASTMCP_SERVER_AUTH or FASTMCP_SERVER_AUTH_VERIFIERS. A process-set FASTMCP_ENV_FILE replaces that compatibility
fallback and may provide both the selector and provider fields. Set it before startup.
The mcp-clickhouse compatibility loader reads only FASTMCP_SERVER_AUTH and
FASTMCP_SERVER_AUTH_* from that file, so it cannot inject CLICKHOUSE_* settings.
FastMCP 4 may use the same file for its own broader settings. A custom provider receives
no environment-derived constructor arguments and must support no-argument construction.
Treat both discovered and working-directory .env files as trusted authentication
configuration. Anyone who can create or write a .env in any directory from the package
directory up to the filesystem root can control which file is discovered, select the
provider, and set its fields. Anyone who can write the working-directory file controls every provider
field absent from the process and discovered configuration, including signing keys,
issuers and endpoints, and client secrets. A process-set FASTMCP_ENV_FILE that points
to an operator-owned file disables the working-directory fallback.
FastMCP 4 changed the default OAuth proxy client store. Deployments that relied on FastMCP 2's default OAuth proxy storage must have clients register and authorize again. Compatible custom storage, static bearer tokens, and JWT verification are unaffected.
Development Mode (Disabling Authentication)
For local development and testing only, you can disable authentication by setting:
export CLICKHOUSE_MCP_AUTH_DISABLED=true
export CLICKHOUSE_MCP_ALLOWED_HOSTS=127.0.0.1:8000,localhost:8000
WARNING: Only use this for local development. Do not disable authentication when the server is exposed to any network.
Configuration
This MCP server supports both ClickHouse and chDB. You can enable either or both depending on your needs.
Python 3.10 through 3.15 are supported. Python 3.12 is recommended for local launches.
chDB supports Python 3.10 through 3.14. On Python 3.15, the chdb extra skips
installing chDB through a dependency marker. Python 3.15 installs currently build
lz4 and PyYAML from source, with or without the chdb extra. A C compiler is
required for lz4.
-
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
- On macOS:
-
Add the following:
{
"mcpServers": {
"mcp-clickhouse": {
"command": "uv",
"args": [
"run",
"--with",
"mcp-clickhouse",
"--python",
"3.12",
"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"
}
}
}
}
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": [
"run",
"--with",
"mcp-clickhouse",
"--python",
"3.12",
"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"
}
}
}
}
For chDB (embedded ClickHouse engine), add the following configuration:
{
"mcpServers": {
"mcp-clickhouse": {
"command": "uv",
"args": [
"run",
"--with",
"mcp-clickhouse[chdb]",
"--python",
"3.12",
"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.12",
"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",
"CHDB_ENABLED": "true",
"CHDB_DATA_PATH": "/path/to/chdb/data"
}
}
}
}
-
Locate the command entry for
uvand 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.
Optional Write Access
By default, this MCP enforces read-only queries so that accidental mutations cannot happen during exploration. To allow DDL or INSERT 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.
Read-only mode still permits the ClickHouse user to cancel its own queries, including queries from other connections using the same user. Use a dedicated ClickHouse user even in read-only mode. Use separate ClickHouse users for workloads that must not cancel each other's queries.
Destructive Operation Protection
Even when write access is enabled (CLICKHOUSE_ALLOW_WRITE_ACCESS=true), destructive operations require an additional opt-in flag for safety. The check covers any DROP statement (including the ALTER TABLE ... DROP PARTITION / DROP PART / DROP COLUMN clauses), any TRUNCATE, DELETE and UPDATE (both the lightweight statements and the ALTER TABLE ... DELETE / ALTER TABLE ... UPDATE mutations), REPLACE TABLE, CREATE OR REPLACE, ALTER TABLE ... REPLACE PARTITION, ALTER TABLE ... CLEAR COLUMN / CLEAR INDEX / CLEAR PROJECTION, OPTIMIZE ... DEDUPLICATE, ALTER TABLE ... MODIFY TTL / MATERIALIZE TTL, MODIFY/ALTER COLUMN with TTL, and DETACH ... PERMANENTLY. This also blocks MODIFY COLUMN c REMOVE TTL. Keywords inside string literals, quoted identifiers, SQL comments, and {name:Type} parameter names are ignored, so they neither trigger the check nor hide a statement from it.
This check runs in the MCP server and is a best-effort guard against accidents. It is not a security boundary. The security boundary is the ClickHouse user's grants. Read-only mode (the default) is enforced server-side via readonly=1. The destructive-operation gate is not server-enforced.
For write mode, give the MCP server a dedicated ClickHouse user with only the privileges it needs:
CREATE USER mcp_agent IDENTIFIED BY '...';
GRANT SELECT, INSERT, CREATE TABLE, ALTER ADD COLUMN ON mydb.* TO mcp_agent;
Data-changing operations that require privileges outside these grants fail server-side with ACCESS_DENIED, regardless of MCP flags. The server settings max_table_size_to_drop and max_partition_size_to_drop can also cap blast radius if pinned with settings constraints.
To enable destructive operations, set both flags:
"env": {
"CLICKHOUSE_ALLOW_WRITE_ACCESS": "true",
"CLICKHOUSE_ALLOW_DROP": "true"
}
This two-tier approach makes accidental deletion difficult:
- Write operations (INSERT, CREATE, ALTER ADD COLUMN) require
CLICKHOUSE_ALLOW_WRITE_ACCESS=true - Destructive operations (DROP, TRUNCATE, DELETE, UPDATE, and the rest of the list above) 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:
-
Install the package using pip:
python3 -m pip install mcp-clickhouseTo install chDB support as well:
python3 -m pip install 'mcp-clickhouse[chdb]'To upgrade to the latest version:
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"
}
}
}
}
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"
}
}
}
}
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 python3for the Python executablewhich mcp-clickhousefor the installed script
Custom Middleware
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.).
How to Use
- Create a Python module with middleware classes extending
Middlewareand 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 the
MCP_MIDDLEWARE_MODULEenvironment variable to the module name (without.pyextension):
{
"mcpServers": {
"mcp-clickhouse": {
"command": "uv",
"args": ["run", "--with", "mcp-clickhouse", "--python", "3.12", "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).
Example Middleware
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
To use the example:
"env": {
"MCP_MIDDLEWARE_MODULE": "example_middleware"
}
Middleware Capabilities
The Middleware base class provides hooks for different MCP operations:
on_message(context, call_next)- Called for all messageson_request(context, call_next)- Called for all requestson_notification(context, call_next)- Called for all notificationson_call_tool(context, call_next)- Called when a tool is executedon_read_resource(context, call_next)- Called when a resource is readon_get_prompt(context, call_next)- Called when a prompt is retrievedon_list_tools(context, call_next)- Called when listing toolson_list_resources(context, call_next)- Called when listing resourceson_list_resource_templates(context, call_next)- Called when listing resource templateson_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 fastmcp.server.middleware import CallNext, Middleware, MiddlewareContext
from mcp_clickhouse.mcp_server import CLIENT_CONFIG_OVERRIDES_KEY
class ClientConfigMiddleware(Middleware):
async def on_call_tool(self, context: MiddlewareContext, call_next: CallNext):
ctx = get_context()
await ctx.set_state(
CLIENT_CONFIG_OVERRIDES_KEY,
{
"connect_timeout": 60,
"send_receive_timeout": 120,
},
serializable=False,
)
return await call_next(context)
This enables advanced use cases like dynamic timeout adjustments, tenant-specific routing, or per-user connection settings.
The state value must be a dictionary. Nested settings and generic_args values must be
mappings and are merged with the base configuration. Invalid values fail the tool call before
a ClickHouse client is created. CLICKHOUSE_ROLE remains active unless the override explicitly
supplies settings.role. Top-level role and ch_role keys, plus the same keys under
generic_args, are rejected.
Set verify, ca_cert, client_cert, client_cert_key, tls_mode, server_host_name,
and pool_mgr only as top-level overrides. They cannot be nested under generic_args. A
custom pool_mgr cannot be combined with managed CA or client certificate settings. DSN query
parameters cannot set these keys, and a DSN cannot select the chdb backend. Use explicit
top-level host, port, username, password, database, and secure overrides to change
the connection. A forwarded DSN does not replace populated base connection fields or select
TLS. It can fill empty fields and supply supported query parameters such as query_limit.
secure and verify overrides accept booleans or the strings true and false.
verify also accepts proxy, which behaves as
tls_mode: proxy when tls_mode is unset and therefore uses Basic authentication with the
environment password. A secure override selects the matching https or http interface and
does not change the port. An explicit interface override must be http or https and agree
with secure. After merging overrides, default and mutual client certificate modes omit the
password. proxy and strict modes use Basic authentication with the environment password
unless the override supplies its own credentials.
Treat these overrides as trusted middleware input. Middleware must authenticate and authorize
request-derived values before setting them. Use serializable=False so FastMCP keeps the
value in request-local state. The default serializable=True stores session state and is
rejected by the server. The server snapshots the value before dispatching blocking database
work. Do not store tenant data in session-scoped Context state. A rejected session-scoped
override remains attached to a legacy MCP session and causes later tool calls in that session
to fail until the client reconnects. A per-request ClickHouse role is connection configuration,
not a tenant authorization boundary. Enforce tenant isolation with ClickHouse users, roles,
and grants.
Development
-
In
test-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 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 --locked --extra devto install the dependencies. On Python 3.10 through 3.14, add--extra chdbfor chDB development. To installuvfollow the instructions here. Then dosource .venv/bin/activate. -
For easy testing with the MCP Inspector, run
uv run fastmcp dev inspector mcp_clickhouse/mcp_server.py:mcpto 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 CLICKHOUSE_MCP_ALLOWED_HOSTS=127.0.0.1:8000,localhost:8000 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
Code layout
The package uses a flat module layout. Start with mcp_server.py for server assembly and registration, then follow the implementation into its owning module.
| Module | Responsibility |
|---|---|
| mcp_server.py, main.py | Startup assembly, tool and prompt registration, shutdown coordination, and CLI startup |
| clients.py | Request configuration, cached ClickHouse connections, and client leases |
| queries.py | Query execution, cancellation, and destructive-operation guards |
| metadata.py | Database and table discovery, metadata models, and pagination |
| chdb_backend.py, chdb_prompt.py | Optional chDB initialization, query execution, and prompt content |
| health.py, executors.py | Health probes and caching, and the worker pools used by server operations |
| auth.py, transport.py, http_security.py | Dotenv loading, authentication, HTTP/SSE app construction, and Host/Origin validation |
| mcp_env.py, serialization.py | Environment configuration and JSON result encoding |
| mcp_middleware_hook.py, skills_advisor.py | Custom middleware loading and server instructions |
Each server assembly owns its worker pools, client cache, active queries, pagination cache, health state, and chDB backend. Worker and client cleanup runs at process exit. Package imports initialize the default server, including when first importing an extracted module.
In tests, patch the module or owner instance where the code reads a dependency. For example,
patch mcp_clickhouse.clients.clickhouse_connect.get_client for client creation. Compatibility
imports in mcp_server.py can be separate bindings from the ones an implementation uses.
Environment Variables
Configuration is split into independent groups. Mixing them up is a common cause of hard-to-debug connection failures:
Documentation truncated — see the full README on GitHub.
Reviews
No reviews yet
Be the first to review this server!
More Data & Analytics MCP Servers
Toleno
Freeby Toleno · Developer Tools
Toleno Network MCP Server — Manage your Toleno mining account with Claude AI using natural language.
MCP Marketplace
Freeby mcp-marketplace · Developer Tools
Search and install MCP servers from inside your AI client.
mcp-creator-python
Freeby mcp-marketplace · Developer Tools
Create, build, and publish Python MCP servers to PyPI — conversationally.
by Lharries · Communication
Read, search, and send WhatsApp messages through your AI assistant
FinAgent
Freeby mcp-marketplace · Finance
Free stock data and market news for any MCP-compatible AI assistant.
Memory
Freeby Modelcontextprotocol · Productivity
Knowledge graph-based persistent memory across sessions
