Skip to content
Back to search

mcp-clickhouse

Connect ClickHouse to your AI assistants.

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today

Check it deeper on your machine

It has changed since its scan on 11 Nov 2026.

As a Claude Code plugin, install it and then ask Claude Code:

/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/ClickHouse/mcp-clickhouse with scanskillsafety

Or from a terminal, clone it and run it:

git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/ClickHouse/mcp-clickhouse'

It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.

Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/clickhouse--mcp-clickhouse/badge.svg)](/listings/clickhouse--mcp-clickhouse)

HTML

<a href="/listings/clickhouse--mcp-clickhouse"><img src="/api/listings/clickhouse--mcp-clickhouse/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md · README · 1,209 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.

  1. # ClickHouse MCP Server
  2. <!-- mcp-name: io.github.ClickHouse/mcp-clickhouse -->
  3. [![PyPI - Version](https://img.shields.io/pypi/v/mcp-clickhouse)](https://pypi.org/project/mcp-clickhouse)
  4. An MCP server for ClickHouse.
  5. <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>
  6. The server implements MCP `2026-07-28` and supports legacy initialize handshakes from
  7. `2024-11-05` through `2025-11-25`. Modern clients use sessionless requests and
  8. `server/discover`. Existing clients can continue to negotiate the legacy protocol.
  9. > [!NOTE]
  10. > HTTP requests without `MCP-Protocol-Version` are routed through legacy handling so
  11. > clients from before `2025-06-18` can continue to connect. MCP `2026-07-28` permits
  12. > this behavior on servers that support those clients. Modern clients should send the
  13. > header on every POST request.
  14. ## Features
  15. ### ClickHouse Tools
  16. ClickHouse tool responses are JSON-encoded strings. Integers outside
  17. `[-9007199254740991, 9007199254740991]` are returned as decimal strings to preserve exact
  18. values in JavaScript clients. This applies to query rows and integer table metadata. Safe-range
  19. integers and booleans keep their JSON types.
  20. * `run_query`
  21. * Execute SQL queries on your ClickHouse cluster.
  22. * Input: `query` (string): The SQL query to execute.
  23. * Optional input: `params` (object): Named values for ClickHouse `{name:Type}` placeholders. See [Query parameters](#query-parameters).
  24. * Queries run in read-only mode by default (`CLICKHOUSE_ALLOW_WRITE_ACCESS=false`), but writes can be enabled explicitly if needed.
  25. * `DESCRIBE (<query>)` and `EXPLAIN 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](#checking-a-query-before-running-it).
  26. * `list_databases`
  27. * List all databases on your ClickHouse cluster.
  28. * `list_tables`
  29. * List tables in a database with pagination.
  30. * Required input: `database` (string).
  31. * Optional inputs:
  32. * `like` / `not_like` (string): Apply `LIKE` or `NOT LIKE` filters to table names.
  33. * `page_token` (string): Single-use token returned by a previous call. It is retained for up to one hour.
  34. * `page_size` (int, default `50`): Number of tables returned per page; must be greater than `0`.
  35. * `include_detailed_columns` (bool, default `true`): When `false`, omits column metadata for lighter responses while keeping the full `create_table_query`.
  36. * Response shape:
  37. * `tables`: Array of table objects for the current page.
  38. * `next_page_token`: Pass this single-use value back before it expires to fetch the next page, or `null` when there are no more tables.
  39. * `total_tables`: Total count of tables that match the supplied filters.
  40. #### Agents Schema discovery
  41. The server instructions suggest reading [Agents Schema](https://github.com/dbt-labs/agents_schema)'s
  42. canonical `AGENTS.ROOT` through `run_query` when `list_databases` reveals an `AGENTS`
  43. database, before writing analytical SQL. This is guidance for the agent: no metadata
  44. is fetched automatically, tool results are unchanged, and existing ClickHouse
  45. permissions still apply. If `AGENTS.ROOT` is missing or inaccessible, normal discovery
  46. and queries remain available.
  47. #### Query parameters
  48. Pass values separately from SQL through the optional `params` object:
  49. ```json
  50. {
  51. "query": "SELECT {id:UInt32} AS id, {name:String} AS name",
  52. "params": {"id": 13, "name": "O'Reilly"}
  53. }
  54. ```
  55. Use ClickHouse's `{name:Type}` placeholders without quoting them. Keep the opening
  56. brace, name, and colon adjacent, as in `{id:UInt32}`. Spaces after the colon and
  57. within the type are supported, as in `{id: UInt32}` and `{amount:Decimal(18, 4)}`.
  58. For compatibility across supported driver versions, start names with a letter or
  59. underscore and use only letters, digits, and underscores.
  60. Python-style `%s` or `%(name)s` formatting and the driver's `$name$` raw binary
  61. parameters are not supported. Calls with only `query` still work. Omitting `params`,
  62. passing `null`, or passing an empty object leaves the query unbound.
  63. Parameter values can be JSON strings, numbers, booleans, `null`, or arrays, provided
  64. they match the declared ClickHouse type:
  65. - Use `null` with a `Nullable(...)` type.
  66. - Pass exact integers outside JavaScript's safe range as decimal strings, for
  67. example `"18446744073709551615"` with `{id:UInt64}`. Dates, timestamps, and exact
  68. decimals can also be passed as strings with the corresponding ClickHouse type.
  69. - Bind vectors as one array, for example `{vector:Array(Float32)}` with
  70. `"params": {"vector": [0.25, 0.5, 0.75]}`.
  71. - Nulls inside arrays depend on the installed driver. They work with
  72. clickhouse-connect 1.8.0 but fail with the supported minimum 1.0.0.
  73. - JSON lists and objects cannot bind to ClickHouse `Tuple` and `Map` types.
  74. Missing values and incompatible types return query errors. With non-empty `params`,
  75. a query carrying many unterminated `{name:` placeholder starts is rejected, including
  76. placeholder-like text in comments or string literals.
  77. Parameterized queries use the same write protection, timeouts, cancellation, and
  78. JSON result encoding as other queries.
  79. Parameter values stay out of the MCP server's normal SQL log messages, but remain
  80. in MCP tool arguments and may appear in backend errors. ClickHouse 26.3.20.7
  81. substitutes values into the query text in `system.query_log`, `system.processes`,
  82. and `system.text_log`. Parameter binding is not a privacy feature and does not
  83. reduce the number of vector values sent in a tool call.
  84. #### Checking a query before running it
  85. `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.
  86. `DESCRIBE (<query>)` inspects the result schema and returns the same output-column metadata as `DESCRIBE TABLE`:
  87. ```sql
  88. DESCRIBE (SELECT user, sum(amt) FROM events WHERE ts > now() - INTERVAL 30 DAY GROUP BY user)
  89. ```
  90. ```text
  91. user String
  92. sum(amt) Decimal(38, 2)
  93. ```
  94. ClickHouse has to analyze the query to answer, so analysis errors surface here, with ClickHouse's own message, instead of part way through execution:
  95. ```text
  96. DESCRIBE (SELECT usr FROM events) -> Code: 47. Unknown expression identifier `usr` ... Maybe you meant: ['user']
  97. DESCRIBE (SELECT * FROM nosuch) -> Code: 60. Unknown table expression identifier 'nosuch'
  98. ```
  99. 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.
  100. `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:
  101. ```sql
  102. EXPLAIN ESTIMATE SELECT count() FROM events WHERE id = 42
  103. ```
  104. ```text
  105. database table parts rows marks
  106. default events 1 8192 1
  107. ```
  108. Those are estimated reads from [MergeTree](https://clickhouse.com/docs/engines/table-engines/mergetree-family/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.
  109. 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](https://clickhouse.com/docs/sql-reference/statements/explain#explain-estimate) and [DESCRIBE](https://clickhouse.com/docs/sql-reference/statements/describe-table).
  110. ### chDB Tools
  111. * `run_chdb_select_query`
  112. * Execute SQL queries using [chDB](https://github.com/chdb-io/chdb)'s embedded ClickHouse engine.
  113. * Input: `query` (string): The SQL query to execute.
  114. * Integers outside `[-9007199254740991, 9007199254740991]` are returned as decimal strings.
  115. * Query data directly from various sources (files, URLs, databases) without ETL processes.
  116. * Requires the optional `chdb` extra: `pip install 'mcp-clickhouse[chdb]'`
  117. ### Health Check Endpoint
  118. When running with HTTP or SSE transport, a health check endpoint is available at `/health`. This endpoint:
  119. - Returns `200 OK` (body: `OK`) if the server is healthy and can connect to ClickHouse
  120. - Returns `503 Service Unavailable` with a generic error message if the server cannot connect to ClickHouse
  121. - Returns `503` if a ClickHouse probe does not finish within two seconds. Concurrent requests share one in-flight probe
  122. - 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
  123. 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.
  124. Example:
  125. ```bash
  126. curl http://localhost:8000/health
  127. # Response: OK
  128. ```
  129. ## Security
  130. ### Authentication for HTTP/SSE Transports
  131. 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.
  132. Three authentication modes are supported. Pick one:
  133. | Mode | When to use | Env var |
  134. |----------------------------|-------------------------------------------|------------------------------------------------------------------------------------------------|
  135. | Static bearer token | Simple deployments, internal services | `CLICKHOUSE_MCP_AUTH_TOKEN` |
  136. | OAuth / OIDC (via FastMCP) | Azure Entra, Google, GitHub, WorkOS, etc. | `FASTMCP_SERVER_AUTH=<provider-class-path>` (+ provider-specific `FASTMCP_SERVER_AUTH_*` vars) |
  137. | Disabled | Local development only | `CLICKHOUSE_MCP_AUTH_DISABLED=true` |
  138. Startup fails if none of these are configured for HTTP/SSE transports.
  139. #### Setting Up Authentication
  140. 1. Generate a secure token (can be any random string):
  141. ```bash
  142. # Using uuidgen (macOS/Linux)
  143. uuidgen
  144. # Using openssl
  145. openssl rand -hex 32
  146. ```
  147. 2. Configure the server with the token:
  148. ```bash
  149. export CLICKHOUSE_MCP_AUTH_TOKEN="your-generated-token"
  150. ```
  151. 3. Configure your MCP client to include the token in requests:
  152. For Claude Desktop with HTTP/SSE transport:
  153. ```json
  154. {
  155. "mcpServers": {
  156. "mcp-clickhouse": {
  157. "url": "http://127.0.0.1:8000",
  158. "headers": {
  159. "Authorization": "Bearer your-generated-token"
  160. }
  161. }
  162. }
  163. }
  164. ```
  165. Note: the `/health` endpoint is intentionally unauthenticated (see [Health Check Endpoint](#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 `/mcp` with and without the `Authorization` header and confirming the unauthenticated call returns `401`.
  166. #### OAuth / OIDC via FastMCP
  167. For production deployments with identity providers (Azure Entra, Google, GitHub, WorkOS, etc.), delegate authentication to [FastMCP's built-in auth providers](https://gofastmcp.com/servers/auth) 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.
  168. Example (Azure Entra):
  169. ```bash
  170. export FASTMCP_SERVER_AUTH=fastmcp.server.auth.providers.azure.AzureProvider
  171. export FASTMCP_SERVER_AUTH_AZURE_TENANT_ID="<tenant-id>"
  172. export FASTMCP_SERVER_AUTH_AZURE_CLIENT_ID="<client-id>"
  173. export FASTMCP_SERVER_AUTH_AZURE_CLIENT_SECRET="<client-secret>"
  174. export FASTMCP_SERVER_AUTH_AZURE_BASE_URL="https://mcp.example.com"
  175. export FASTMCP_SERVER_AUTH_AZURE_REQUIRED_SCOPES="read access_as_user"
  176. ```
  177. mcp-clickhouse retains these FastMCP 2.14.7 environment prefixes for the FastMCP 4.0.0
  178. built-in providers:
  179. | Provider class path | Provider variable prefix |
  180. |---------------------|--------------------------|
  181. | `fastmcp.server.auth.providers.auth0.Auth0Provider` | `FASTMCP_SERVER_AUTH_AUTH0_` |
  182. | `fastmcp.server.auth.providers.aws.AWSCognitoProvider` | `FASTMCP_SERVER_AUTH_AWS_COGNITO_` |
  183. | `fastmcp.server.auth.providers.azure.AzureProvider` | `FASTMCP_SERVER_AUTH_AZURE_` |
  184. | `fastmcp.server.auth.providers.descope.DescopeProvider` | `FASTMCP_SERVER_AUTH_DESCOPEPROVIDER_` |
  185. | `fastmcp.server.auth.providers.discord.DiscordProvider` | `FASTMCP_SERVER_AUTH_DISCORD_` |
  186. | `fastmcp.server.auth.providers.github.GitHubProvider` | `FASTMCP_SERVER_AUTH_GITHUB_` |
  187. | `fastmcp.server.auth.providers.google.GoogleProvider` | `FASTMCP_SERVER_AUTH_GOOGLE_` |
  188. | `fastmcp.server.auth.providers.introspection.IntrospectionTokenVerifier` | `FASTMCP_SERVER_AUTH_INTROSPECTION_` |
  189. | `fastmcp.server.auth.providers.jwt.JWTVerifier` | `FASTMCP_SERVER_AUTH_JWT_` |
  190. | `fastmcp.server.auth.providers.oci.OCIProvider` | `FASTMCP_SERVER_AUTH_OCI_` |
  191. | `fastmcp.server.auth.providers.scalekit.ScalekitProvider` | `FASTMCP_SERVER_AUTH_SCALEKITPROVIDER_` |
  192. | `fastmcp.server.auth.providers.supabase.SupabaseProvider` | `FASTMCP_SERVER_AUTH_SUPABASE_` |
  193. | `fastmcp.server.auth.providers.workos.WorkOSProvider` | `FASTMCP_SERVER_AUTH_WORKOS_` |
  194. | `fastmcp.server.auth.providers.workos.AuthKitProvider` | `FASTMCP_SERVER_AUTH_AUTHKITPROVIDER_` |
  195. mcp-clickhouse also configures `fastmcp.server.auth.providers.azure.AzureJWTVerifier`
  196. from the `FASTMCP_SERVER_AUTH_AZUREJWT_` prefix. FastMCP 2 had no environment contract
  197. for this verifier. A `TENANT_ID` of `common`, `organizations`, or `consumers` skips the
  198. issuer check, so tokens issued for the app by any Entra tenant are accepted.
  199. Append the uppercase provider field name to the prefix. See the
  200. [FastMCP docs](https://gofastmcp.com/servers/auth) for each provider's configuration
  201. requirements.
  202. ##### Accepting tokens from more than one source
  203. Some deployments serve two kinds of callers from one endpoint, for example interactive
  204. MCP clients that sign in through an OAuth proxy and a backend that sends access tokens
  205. it obtained itself. Set `FASTMCP_SERVER_AUTH_VERIFIERS` to a comma-separated list of
  206. token verifier class paths to accept their tokens in addition to the
  207. `FASTMCP_SERVER_AUTH` provider. mcp-clickhouse combines them with FastMCP's
  208. [`MultiAuth`](https://gofastmcp.com/servers/auth/multi-auth).
  209. Example (Entra OAuth proxy for MCP clients, plus Entra access tokens such as
  210. On-Behalf-Of tokens from a backend, both for one app registration):
  211. ```bash
  212. export FASTMCP_SERVER_AUTH=fastmcp.server.auth.providers.azure.AzureProvider
  213. export FASTMCP_SERVER_AUTH_AZURE_TENANT_ID="<tenant-id>"
  214. export FASTMCP_SERVER_AUTH_AZURE_CLIENT_ID="<client-id>"
  215. export FASTMCP_SERVER_AUTH_AZURE_CLIENT_SECRET="<client-secret>"
  216. export FASTMCP_SERVER_AUTH_AZURE_BASE_URL="https://mcp.example.com"
  217. export FASTMCP_SERVER_AUTH_AZURE_REQUIRED_SCOPES="mcp.read"
  218. export FASTMCP_SERVER_AUTH_VERIFIERS=fastmcp.server.auth.providers.azure.AzureJWTVerifier
  219. export FASTMCP_SERVER_AUTH_AZUREJWT_TENANT_ID="<tenant-id>"
  220. export FASTMCP_SERVER_AUTH_AZUREJWT_CLIENT_ID="<client-id>"
  221. export FASTMCP_SERVER_AUTH_AZUREJWT_REQUIRED_SCOPES="mcp.read"
  222. ```
  223. - The `FASTMCP_SERVER_AUTH` provider is tried first, then each verifier in the listed
  224. order. The first one that accepts the token wins, so every entry is a trust source:
  225. a token valid for any of them reaches the tools.
  226. - The `FASTMCP_SERVER_AUTH` provider's required scopes apply to tokens from every
  227. source, whether the primary provider is an OAuth provider or a token verifier.
  228. An OAuth primary keeps its routes and discovery metadata. A token-verifier primary
  229. serves no OAuth routes.
  230. - Each entry must be a `TokenVerifier` subclass and is configured from its own prefix,
  231. exactly as it would be under `FASTMCP_SERVER_AUTH`. A class can therefore appear only
  232. once across `FASTMCP_SERVER_AUTH` and `FASTMCP_SERVER_AUTH_VERIFIERS`.
  233. - `FASTMCP_SERVER_AUTH_VERIFIERS` extends the FastMCP provider mode only. It is rejected
  234. together with `CLICKHOUSE_MCP_AUTH_TOKEN` or `CLICKHOUSE_MCP_AUTH_DISABLED=true`.
  235. Auth values set directly in the process environment take precedence case-insensitively.
  236. The default `.env` load starts at the installed `mcp_clickhouse` package directory,
  237. resolves symlinks first, and walks upward to the filesystem root. It loads the first
  238. `.env` it finds and loads nothing if there is none. It never reads the working
  239. directory, regardless of how the server is launched. A source checkout normally finds
  240. the repository root `.env`. That file may also provide `FASTMCP_SERVER_AUTH` and its
  241. provider fields. Its values take precedence over the explicit or compatibility auth
  242. file.
  243. For FastMCP 2 compatibility, mcp-clickhouse reads missing provider fields from `.env`
  244. in the working directory, but that compatibility fallback cannot select
  245. `FASTMCP_SERVER_AUTH` or `FASTMCP_SERVER_AUTH_VERIFIERS`. A process-set `FASTMCP_ENV_FILE` replaces that compatibility
  246. fallback and may provide both the selector and provider fields. Set it before startup.
  247. The mcp-clickhouse compatibility loader reads only `FASTMCP_SERVER_AUTH` and
  248. `FASTMCP_SERVER_AUTH_*` from that file, so it cannot inject `CLICKHOUSE_*` settings.
  249. FastMCP 4 may use the same file for its own broader settings. A custom provider receives
  250. no environment-derived constructor arguments and must support no-argument construction.
  251. Treat both discovered and working-directory `.env` files as trusted authentication
  252. configuration. Anyone who can create or write a `.env` in any directory from the package
  253. directory up to the filesystem root can control which file is discovered, select the
  254. provider, and set its fields. Anyone who can write the working-directory file controls every provider
  255. field absent from the process and discovered configuration, including signing keys,
  256. issuers and endpoints, and client secrets. A process-set `FASTMCP_ENV_FILE` that points
  257. to an operator-owned file disables the working-directory fallback.
  258. FastMCP 4 changed the default OAuth proxy client store. Deployments that relied on
  259. FastMCP 2's default OAuth proxy storage must have clients register and authorize again.
  260. Compatible custom storage, static bearer tokens, and JWT verification are unaffected.
  261. #### Development Mode (Disabling Authentication)
  262. For local development and testing only, you can disable authentication by setting:
  263. ```bash
  264. export CLICKHOUSE_MCP_AUTH_DISABLED=true
  265. export CLICKHOUSE_MCP_ALLOWED_HOSTS=127.0.0.1:8000,localhost:8000
  266. ```
  267. **WARNING:** Only use this for local development. Do not disable authentication when the server is exposed to any network.
  268. ## Configuration
  269. This MCP server supports both ClickHouse and chDB. You can enable either or both depending on your needs.
  270. Python 3.10 through 3.15 are supported. Python 3.12 is recommended for local launches.
  271. chDB supports Python 3.10 through 3.14. On Python 3.15, the `chdb` extra skips
  272. installing chDB through a dependency marker. Python 3.15 installs currently build
  273. `lz4` and `PyYAML` from source, with or without the `chdb` extra. A C compiler is
  274. required for `lz4`.
  275. 1. Open the Claude Desktop configuration file located at:
  276. * On macOS: `~/Library/Application Support/Claude/claude_desktop_config.json`
  277. * On Windows: `%APPDATA%/Claude/claude_desktop_config.json`
  278. 2. Add the following:
  279. ```json
  280. {
  281. "mcpServers": {
  282. "mcp-clickhouse": {
  283. "command": "uv",
  284. "args": [
  285. "run",
  286. "--with",
  287. "mcp-clickhouse",
  288. "--python",
  289. "3.12",
  290. "mcp-clickhouse"
  291. ],
  292. "env": {
  293. "CLICKHOUSE_HOST": "<clickhouse-host>",
  294. "CLICKHOUSE_PORT": "<clickhouse-port>",
  295. "CLICKHOUSE_USER": "<clickhouse-user>",
  296. "CLICKHOUSE_PASSWORD": "<clickhouse-password>",
  297. "CLICKHOUSE_ROLE": "<clickhouse-role>",
  298. "CLICKHOUSE_SECURE": "true",
  299. "CLICKHOUSE_VERIFY": "true",
  300. "CLICKHOUSE_CONNECT_TIMEOUT": "30"
  301. }
  302. }
  303. }
  304. }
  305. ```
  306. Update the environment variables to point to your own ClickHouse service.
  307. Or, if you'd like to try it out with the [ClickHouse SQL Playground](https://sql.clickhouse.com/), you can use the following config:
  308. ```json
  309. {
  310. "mcpServers": {
  311. "mcp-clickhouse": {
  312. "command": "uv",
  313. "args": [
  314. "run",
  315. "--with",
  316. "mcp-clickhouse",
  317. "--python",
  318. "3.12",
  319. "mcp-clickhouse"
  320. ],
  321. "env": {
  322. "CLICKHOUSE_HOST": "sql-clickhouse.clickhouse.com",
  323. "CLICKHOUSE_PORT": "8443",
  324. "CLICKHOUSE_USER": "demo",
  325. "CLICKHOUSE_PASSWORD": "",
  326. "CLICKHOUSE_SECURE": "true",
  327. "CLICKHOUSE_VERIFY": "true",
  328. "CLICKHOUSE_CONNECT_TIMEOUT": "30"
  329. }
  330. }
  331. }
  332. }
  333. ```
  334. For chDB (embedded ClickHouse engine), add the following configuration:
  335. ```json
  336. {
  337. "mcpServers": {
  338. "mcp-clickhouse": {
  339. "command": "uv",
  340. "args": [
  341. "run",
  342. "--with",
  343. "mcp-clickhouse[chdb]",
  344. "--python",
  345. "3.12",
  346. "mcp-clickhouse"
  347. ],
  348. "env": {
  349. "CHDB_ENABLED": "true",
  350. "CLICKHOUSE_ENABLED": "false",
  351. "CHDB_DATA_PATH": "/path/to/chdb/data"
  352. }
  353. }
  354. }
  355. }
  356. ```
  357. You can also enable both ClickHouse and chDB simultaneously:
  358. ```json
  359. {
  360. "mcpServers": {
  361. "mcp-clickhouse": {
  362. "command": "uv",
  363. "args": [
  364. "run",
  365. "--with",
  366. "mcp-clickhouse[chdb]",
  367. "--python",
  368. "3.12",
  369. "mcp-clickhouse"
  370. ],
  371. "env": {
  372. "CLICKHOUSE_HOST": "<clickhouse-host>",
  373. "CLICKHOUSE_PORT": "<clickhouse-port>",
  374. "CLICKHOUSE_USER": "<clickhouse-user>",
  375. "CLICKHOUSE_PASSWORD": "<clickhouse-password>",
  376. "CLICKHOUSE_SECURE": "true",
  377. "CLICKHOUSE_VERIFY": "true",
  378. "CLICKHOUSE_CONNECT_TIMEOUT": "30",
  379. "CHDB_ENABLED": "true",
  380. "CHDB_DATA_PATH": "/path/to/chdb/data"
  381. }
  382. }
  383. }
  384. }
  385. ```
  386. 3. 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`.
  387. 4. Restart Claude Desktop to apply the changes.
  388. ### Optional Write Access
  389. 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.
  390. 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.
  391. ### Destructive Operation Protection
  392. 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.
  393. 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.
  394. For write mode, give the MCP server a dedicated ClickHouse user with only the privileges it needs:
  395. ```sql
  396. CREATE USER mcp_agent IDENTIFIED BY '...';
  397. GRANT SELECT, INSERT, CREATE TABLE, ALTER ADD COLUMN ON mydb.* TO mcp_agent;
  398. ```
  399. 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.
  400. To enable destructive operations, set both flags:
  401. ```json
  402. "env": {
  403. "CLICKHOUSE_ALLOW_WRITE_ACCESS": "true",
  404. "CLICKHOUSE_ALLOW_DROP": "true"
  405. }
  406. ```
  407. This two-tier approach makes accidental deletion difficult:
  408. - **Write operations** (INSERT, CREATE, ALTER ADD COLUMN) require `CLICKHOUSE_ALLOW_WRITE_ACCESS=true`
  409. - **Destructive operations** (DROP, TRUNCATE, DELETE, UPDATE, and the rest of the list above) additionally require `CLICKHOUSE_ALLOW_DROP=true`
  410. ### Running Without uv (Using System Python)
  411. If you prefer to use the system Python installation instead of uv, you can install the package from PyPI and run it directly:
  412. 1. Install the package using pip:
  413. ```bash
  414. python3 -m pip install mcp-clickhouse
  415. ```
  416. To install chDB support as well:
  417. ```bash
  418. python3 -m pip install 'mcp-clickhouse[chdb]'
  419. ```
  420. To upgrade to the latest version:
  421. ```bash
  422. python3 -m pip install --upgrade mcp-clickhouse
  423. ```
  424. 2. Update your Claude Desktop configuration to use Python directly:
  425. ```json
  426. {
  427. "mcpServers": {
  428. "mcp-clickhouse": {
  429. "command": "python3",
  430. "args": [
  431. "-m",
  432. "mcp_clickhouse.main"
  433. ],
  434. "env": {
  435. "CLICKHOUSE_HOST": "<clickhouse-host>",
  436. "CLICKHOUSE_PORT": "<clickhouse-port>",
  437. "CLICKHOUSE_USER": "<clickhouse-user>",
  438. "CLICKHOUSE_PASSWORD": "<clickhouse-password>",
  439. "CLICKHOUSE_SECURE": "true",
  440. "CLICKHOUSE_VERIFY": "true",
  441. "CLICKHOUSE_CONNECT_TIMEOUT": "30"
  442. }
  443. }
  444. }
  445. }
  446. ```
  447. Alternatively, you can use the installed script directly:
  448. ```json
  449. {
  450. "mcpServers": {
  451. "mcp-clickhouse": {
  452. "command": "mcp-clickhouse",
  453. "env": {
  454. "CLICKHOUSE_HOST": "<clickhouse-host>",
  455. "CLICKHOUSE_PORT": "<clickhouse-port>",
  456. "CLICKHOUSE_USER": "<clickhouse-user>",
  457. "CLICKHOUSE_PASSWORD": "<clickhouse-password>",
  458. "CLICKHOUSE_SECURE": "true",
  459. "CLICKHOUSE_VERIFY": "true",
  460. "CLICKHOUSE_CONNECT_TIMEOUT": "30"
  461. }
  462. }
  463. }
  464. }
  465. ```
  466. 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:
  467. - `which python3` for the Python executable
  468. - `which mcp-clickhouse` for the installed script
  469. ## Custom Middleware
  470. 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.).
  471. ### How to Use
  472. 1. Create a Python module with middleware classes extending `Middleware` and a `setup_middleware(mcp)` function:
  473. ```python
  474. # my_middleware.py
  475. import logging
  476. from fastmcp.server.middleware import Middleware, MiddlewareContext, CallNext
  477. logger = logging.getLogger("my-middleware")
  478. class LoggingMiddleware(Middleware):
  479. """Log all tool calls."""
  480. async def on_call_tool(self, context: MiddlewareContext, call_next: CallNext):
  481. tool_name = context.message.name if hasattr(context.message, 'name') else 'unknown'
  482. logger.info(f"Calling tool: {tool_name}")
  483. result = await call_next(context)
  484. logger.info(f"Tool {tool_name} completed")
  485. return result
  486. def setup_middleware(mcp):
  487. """Register middleware with the MCP server."""
  488. mcp.add_middleware(LoggingMiddleware())
  489. ```
  490. 2. Set the `MCP_MIDDLEWARE_MODULE` environment variable to the module name (without `.py` extension):
  491. ```json
  492. {
  493. "mcpServers": {
  494. "mcp-clickhouse": {
  495. "command": "uv",
  496. "args": ["run", "--with", "mcp-clickhouse", "--python", "3.12", "mcp-clickhouse"],
  497. "env": {
  498. "CLICKHOUSE_HOST": "<clickhouse-host>",
  499. "CLICKHOUSE_USER": "<clickhouse-user>",
  500. "CLICKHOUSE_PASSWORD": "<clickhouse-password>",
  501. "MCP_MIDDLEWARE_MODULE": "my_middleware"
  502. }
  503. }
  504. }
  505. }
  506. ```
  507. 3. 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).
  508. ### Example Middleware
  509. An example middleware module is provided in `example_middleware.py` showing common patterns:
  510. - Logging all MCP requests
  511. - Logging tool calls specifically
  512. - Measuring request processing time
  513. To use the example:
  514. ```json
  515. "env": {
  516. "MCP_MIDDLEWARE_MODULE": "example_middleware"
  517. }
  518. ```
  519. ### Middleware Capabilities
  520. The `Middleware` base class provides hooks for different MCP operations:
  521. - `on_message(context, call_next)` - Called for all messages
  522. - `on_request(context, call_next)` - Called for all requests
  523. - `on_notification(context, call_next)` - Called for all notifications
  524. - `on_call_tool(context, call_next)` - Called when a tool is executed
  525. - `on_read_resource(context, call_next)` - Called when a resource is read
  526. - `on_get_prompt(context, call_next)` - Called when a prompt is retrieved
  527. - `on_list_tools(context, call_next)` - Called when listing tools
  528. - `on_list_resources(context, call_next)` - Called when listing resources
  529. - `on_list_resource_templates(context, call_next)` - Called when listing resource templates
  530. - `on_list_prompts(context, call_next)` - Called when listing prompts
  531. Each hook receives a `MiddlewareContext` object containing the message and metadata, and a `call_next` function to continue the pipeline.
  532. ### Dynamic Client Configuration via Context State
  533. 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.
  534. ```python
  535. from fastmcp.server.dependencies import get_context
  536. from fastmcp.server.middleware import CallNext, Middleware, MiddlewareContext
  537. from mcp_clickhouse.mcp_server import CLIENT_CONFIG_OVERRIDES_KEY
  538. class ClientConfigMiddleware(Middleware):
  539. async def on_call_tool(self, context: MiddlewareContext, call_next: CallNext):
  540. ctx = get_context()
  541. await ctx.set_state(
  542. CLIENT_CONFIG_OVERRIDES_KEY,
  543. {
  544. "connect_timeout": 60,
  545. "send_receive_timeout": 120,
  546. },
  547. serializable=False,
  548. )
  549. return await call_next(context)
  550. ```
  551. This enables advanced use cases like dynamic timeout adjustments, tenant-specific routing, or per-user connection settings.
  552. The state value must be a dictionary. Nested `settings` and `generic_args` values must be
  553. mappings and are merged with the base configuration. Invalid values fail the tool call before
  554. a ClickHouse client is created. `CLICKHOUSE_ROLE` remains active unless the override explicitly
  555. supplies `settings.role`. Top-level `role` and `ch_role` keys, plus the same keys under
  556. `generic_args`, are rejected.
  557. Set `verify`, `ca_cert`, `client_cert`, `client_cert_key`, `tls_mode`, `server_host_name`,
  558. and `pool_mgr` only as top-level overrides. They cannot be nested under `generic_args`. A
  559. custom `pool_mgr` cannot be combined with managed CA or client certificate settings. DSN query
  560. parameters cannot set these keys, and a DSN cannot select the chdb backend. Use explicit
  561. top-level `host`, `port`, `username`, `password`, `database`, and `secure` overrides to change
  562. the connection. A forwarded DSN does not replace populated base connection fields or select
  563. TLS. It can fill empty fields and supply supported query parameters such as `query_limit`.
  564. `secure` and `verify` overrides accept booleans or the strings `true` and `false`.
  565. `verify` also accepts `proxy`, which behaves as
  566. `tls_mode: proxy` when `tls_mode` is unset and therefore uses Basic authentication with the
  567. environment password. A `secure` override selects the matching `https` or `http` interface and
  568. does not change the port. An explicit `interface` override must be `http` or `https` and agree
  569. with `secure`. After merging overrides, default and `mutual` client certificate modes omit the
  570. password. `proxy` and `strict` modes use Basic authentication with the environment password
  571. unless the override supplies its own credentials.
  572. Treat these overrides as trusted middleware input. Middleware must authenticate and authorize
  573. request-derived values before setting them. Use `serializable=False` so FastMCP keeps the
  574. value in request-local state. The default `serializable=True` stores session state and is
  575. rejected by the server. The server snapshots the value before dispatching blocking database
  576. work. Do not store tenant data in session-scoped Context state. A rejected session-scoped
  577. override remains attached to a legacy MCP session and causes later tool calls in that session
  578. to fail until the client reconnects. A per-request ClickHouse role is connection configuration,
  579. not a tenant authorization boundary. Enforce tenant isolation with ClickHouse users, roles,
  580. and grants.
  581. ## Development
  582. 1. In `test-services` directory run `docker compose up -d` to start the ClickHouse cluster.
  583. 2. Add the following variables to a `.env` file in the root of the repository.
  584. *Note: The use of the `default` user in this context is intended solely for local development purposes.*
  585. ```bash
  586. CLICKHOUSE_HOST=localhost
  587. CLICKHOUSE_PORT=8123
  588. CLICKHOUSE_USER=default
  589. CLICKHOUSE_PASSWORD=clickhouse
  590. ```
  591. 3. Run `uv sync --locked --extra dev` to install the dependencies. On Python 3.10 through 3.14, add `--extra chdb` for chDB development. To install `uv` follow the instructions [here](https://docs.astral.sh/uv/). Then do `source .venv/bin/activate`.
  592. 4. For easy testing with the MCP Inspector, run `uv run fastmcp dev inspector mcp_clickhouse/mcp_server.py:mcp` to start the MCP server.
  593. 5. To test with HTTP transport and the health check endpoint:
  594. ```bash
  595. # For development, disable authentication
  596. 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
  597. # Or with authentication (generate a token first)
  598. CLICKHOUSE_MCP_SERVER_TRANSPORT=http CLICKHOUSE_MCP_AUTH_TOKEN="your-token" python -m mcp_clickhouse.main
  599. # Then in another terminal:
  600. curl http://localhost:8000/health
  601. ```
  602. ### Code layout
  603. The package uses a flat module layout. Start with [mcp_server.py](mcp_clickhouse/mcp_server.py)
  604. for server assembly and registration, then follow the implementation into its owning module.
  605. | Module | Responsibility |
  606. |--------|----------------|
  607. | [mcp_server.py](mcp_clickhouse/mcp_server.py), [main.py](mcp_clickhouse/main.py) | Startup assembly, tool and prompt registration, shutdown coordination, and CLI startup |
  608. | [clients.py](mcp_clickhouse/clients.py) | Request configuration, cached ClickHouse connections, and client leases |
  609. | [queries.py](mcp_clickhouse/queries.py) | Query execution, cancellation, and destructive-operation guards |
  610. | [metadata.py](mcp_clickhouse/metadata.py) | Database and table discovery, metadata models, and pagination |
  611. | [chdb_backend.py](mcp_clickhouse/chdb_backend.py), [chdb_prompt.py](mcp_clickhouse/chdb_prompt.py) | Optional chDB initialization, query execution, and prompt content |
  612. | [health.py](mcp_clickhouse/health.py), [executors.py](mcp_clickhouse/executors.py) | Health probes and caching, and the worker pools used by server operations |
  613. | [auth.py](mcp_clickhouse/auth.py), [transport.py](mcp_clickhouse/transport.py), [http_security.py](mcp_clickhouse/http_security.py) | Dotenv loading, authentication, HTTP/SSE app construction, and Host/Origin validation |
  614. | [mcp_env.py](mcp_clickhouse/mcp_env.py), [serialization.py](mcp_clickhouse/serialization.py) | Environment configuration and JSON result encoding |
  615. | [mcp_middleware_hook.py](mcp_clickhouse/mcp_middleware_hook.py), [skills_advisor.py](mcp_clickhouse/skills_advisor.py) | Custom middleware loading and server instructions |
  616. Each server assembly owns its worker pools, client cache, active queries, pagination cache,
  617. health state, and chDB backend. Worker and client cleanup runs at process exit. Package imports
  618. initialize the default server, including when first importing an extracted module.
  619. In tests, patch the module or owner instance where the code reads a dependency. For example,
  620. patch `mcp_clickhouse.clients.clickhouse_connect.get_client` for client creation. Compatibility
  621. imports in `mcp_server.py` can be separate bindings from the ones an implementation uses.
  622. ### Environment Variables
  623. Configuration is split into **independent** groups. Mixing them up is a common cause of hard-to-debug connection failures:
  624. | Group | Variables | Controls |
  625. |-------|-----------|----------|
  626. | **ClickHouse database connection** | `CLICKHOUSE_HOST`, `CLICKHOUSE_PORT`, `CLICKHOUSE_SECURE`, `CLICKHOUSE_VERIFY`, certificate variables | How **this MCP server** connects to your ClickHouse cluster over the **HTTP interface** |
  627. | **MCP server / transport** | `CLICKHOUSE_MCP_*`, `FASTMCP_SERVER_AUTH`, `FASTMCP_SERVER_AUTH_*`, `FASTMCP_ENV_FILE` | MCP transport, authentication, and query-tool execution limits |
  628. | **Middleware / chDB** | `MCP_MIDDLEWARE_MODULE`, `CHDB_*` | Optional extensions |
  629. > [!IMPORTANT]
  630. > `CLICKHOUSE_SECURE`, `CLICKHOUSE_VERIFY`, `CLICKHOUSE_CA_CERT`, `CLICKHOUSE_CLIENT_CERT`, `CLICKHOUSE_CLIENT_CERT_KEY`, `CLICKHOUSE_TLS_MODE`, and `CLICKHOUSE_PORT` apply to the outbound **ClickHouse database** connection only. They do **not** configure TLS, client certificates, ports, or authentication for the inbound MCP HTTP/SSE endpoint.
  631. >
  632. > Example: if the MCP server runs in Kubernetes behind an ingress that terminates TLS, that is an **MCP transport** concern. Keep `CLICKHOUSE_SECURE` aligned with how the pod reaches ClickHouse itself (HTTPS → `true`, plain HTTP → `false`). Setting `CLICKHOUSE_SECURE=false` because the MCP server is behind an ingress will make the server dial ClickHouse over HTTP—often against an HTTPS-only port—and produce opaque HTTP/TLS errors in the server logs.
  633. #### ClickHouse database connection
  634. These variables configure the [clickhouse-connect](https://clickhouse.com/docs/en/integrations/python) HTTP client and the behavior of ClickHouse-backed tools such as `run_query`, `list_databases`, and `list_tables`.
  635. mcp-clickhouse requires clickhouse-connect 1.x, starting with 1.0.0.
  636. ##### Required Variables
  637. * `CLICKHOUSE_HOST`: The hostname of your ClickHouse server (database endpoint, not the MCP server bind address)
  638. * `CLICKHOUSE_USER`: The username for **ClickHouse** authentication
  639. * `CLICKHOUSE_PASSWORD`: The password for **ClickHouse** authentication
  640. * Required unless `CLICKHOUSE_CLIENT_CERT` uses the default or `"mutual"` TLS mode
  641. * In default or `"mutual"` mode, certificate authentication is used and the password is not sent
  642. > [!CAUTION]
  643. > 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.
  644. ##### Optional Variables
  645. * `CLICKHOUSE_PORT`: HTTP interface port of your ClickHouse server
  646. * Default: `8443` if `CLICKHOUSE_SECURE=true`, `8123` if `CLICKHOUSE_SECURE=false`
  647. * Usually doesn't need to be set unless using a non-standard port
  648. * **Must be an HTTP interface port**, not the native TCP protocol port used by `clickhouse-client`
  649. * Common values:
  650. * HTTP: `8123` (plain) / `8443` (TLS) — used by this server and ClickHouse Cloud HTTPS
  651. * Native TCP (not supported here): `9000` (plain) / `9440` (TLS) — used by `clickhouse-client`
  652. * If the server responds with `Port 9000 is for clickhouse-client program`, you are pointed at the native protocol; switch to the HTTP port (`8123`/`8443` or your deployment's HTTP mapping)
  653. * `CLICKHOUSE_ROLE`: The ClickHouse role to use for authentication
  654. * Default: None
  655. * Set this if your user requires a specific role
  656. * `CLICKHOUSE_SECURE`: Enable HTTPS **for the ClickHouse database connection** (not for MCP clients)
  657. * Default: `"true"`
  658. * Set to `"false"` only when the MCP server reaches ClickHouse over plain HTTP (typical for local Docker Compose on port `8123`)
  659. * Leave `"true"` for ClickHouse Cloud and any HTTPS database endpoint—even if the MCP server itself is exposed via HTTP, stdio, or an ingress that terminates TLS separately
  660. * Mismatching this flag with the database port (e.g. `CLICKHOUSE_SECURE=false` against port `8443`) is a frequent setup mistake and usually surfaces as confusing HTTP client errors rather than a clear "wrong scheme" message
  661. * `CLICKHOUSE_VERIFY`: Enable/disable SSL certificate verification for the **ClickHouse** HTTPS connection
  662. * Default: `"true"`
  663. * Set to `"false"` to disable certificate verification (not recommended for production)
  664. * TLS certificates: The package uses your operating system trust store via `truststore.inject_into_ssl()` at startup. Python's default SSL handling is used if injection is disabled with `MCP_CLICKHOUSE_TRUSTSTORE_DISABLE=1` or fails.
  665. * `MCP_CLICKHOUSE_TRUSTSTORE_DISABLE`: Disable the process-wide operating system trust store integration for TLS
  666. * Default: unset (trust store integration is enabled)
  667. * Set to exactly `"1"` before startup to skip `truststore.inject_into_ssl()` and use Python's default SSL certificate handling. Other values do not disable the integration.
  668. * This does not disable certificate verification. `CLICKHOUSE_VERIFY` still controls verification for the ClickHouse HTTPS connection.
  669. * `CLICKHOUSE_CA_CERT`: Path to a PEM CA certificate bundle for the **ClickHouse** HTTPS connection
  670. * Default: None (uses the operating system trust store unless truststore injection is disabled or fails)
  671. * Use this by itself when a ClickHouse server or private proxy presents a certificate signed by a private CA. This changes server certificate verification and does not enable client certificate authentication.
  672. * Requires `CLICKHOUSE_SECURE=true` and `CLICKHOUSE_VERIFY=true`
  673. * `CLICKHOUSE_CLIENT_CERT`: Path to a PEM client certificate for the **ClickHouse** HTTPS connection
  674. * Default: None
  675. * The file may also contain the private key. Otherwise set `CLICKHOUSE_CLIENT_CERT_KEY`.
  676. * The ClickHouse user still comes from `CLICKHOUSE_USER`.
  677. * `CLICKHOUSE_CLIENT_CERT_KEY`: Path to the PEM private key for `CLICKHOUSE_CLIENT_CERT`
  678. * Default: None
  679. * Optional when the private key is included in the client certificate file
  680. * Cannot be used without `CLICKHOUSE_CLIENT_CERT`
  681. * `CLICKHOUSE_TLS_MODE`: How clickhouse-connect uses `CLICKHOUSE_CLIENT_CERT`
  682. * Default: None, which behaves as `"mutual"` when a client certificate is set
  683. * `"mutual"`: Use the client certificate for ClickHouse X.509 user authentication. `CLICKHOUSE_PASSWORD` is optional and is not sent.
  684. * `"proxy"`: Present the client certificate to a TLS-terminating proxy, then use ClickHouse Basic authentication. `CLICKHOUSE_PASSWORD` is required.
  685. * `"strict"`: Present the client certificate because the ClickHouse server requires one at the TLS layer, then use ClickHouse Basic authentication. `CLICKHOUSE_PASSWORD` is required. This mode does not strengthen server certificate verification. `CLICKHOUSE_VERIFY` controls that verification.
  686. * clickhouse-connect treats `"proxy"` and `"strict"` identically. The two names document intent.
  687. * Values are trimmed and case-insensitive. A blank value is treated as unset. Other values are rejected before a ClickHouse client is created, on the first ClickHouse tool call or `/health` probe.
  688. * Requires `CLICKHOUSE_CLIENT_CERT`. All client certificate options require `CLICKHOUSE_SECURE=true`.
  689. * `CLICKHOUSE_SERVER_HOST_NAME`: Server hostname for SNI override and certificate validation on the **ClickHouse** connection
  690. * Default: None (uses the connection hostname)
  691. * This is useful when connecting through proxies or load balancers where the certificate hostname differs from the connection hostname. When set, this hostname will be used for both SNI (Server Name Indication) during the TLS handshake and for certificate hostname validation.
  692. * `CLICKHOUSE_PROXY_PATH`: URL path prefix for the ClickHouse HTTP endpoint
  693. * Default: None
  694. * Set this when the ClickHouse HTTP interface is exposed behind a reverse proxy under a path prefix (for example, `/clickhouse`)
  695. * `CLICKHOUSE_CONNECT_TIMEOUT`: Connection timeout in seconds for the **ClickHouse** client
  696. * Default: `"30"`
  697. * Increase this value if you experience connection timeouts
  698. * `CLICKHOUSE_SEND_RECEIVE_TIMEOUT`: Send/receive timeout in seconds for the **ClickHouse** client
  699. * Default: the lower of `300` or `CLICKHOUSE_MCP_QUERY_TIMEOUT + 5`, so worker threads unblock shortly after a query timeout
  700. * If explicitly set, the value is used as-is (e.g. `"300"` for long-running queries)
  701. * `CLICKHOUSE_DATABASE`: Default ClickHouse database to use
  702. * Default: None (uses server default)
  703. * Set this to automatically connect to a specific database
  704. * `CLICKHOUSE_ENABLED`: Enable/disable ClickHouse database tools
  705. * Default: `"true"`
  706. * Set to `"false"` to disable ClickHouse tools when using chDB only
  707. * `CLICKHOUSE_ALLOW_WRITE_ACCESS`: Allow write operations (DDL and DML) against ClickHouse
  708. * Default: `"false"`
  709. * Set to `"true"` to allow non-destructive DDL and DML (CREATE, INSERT, ALTER ADD COLUMN). Destructive statements additionally need `CLICKHOUSE_ALLOW_DROP=true`
  710. * When disabled (default), queries run with `readonly=1` setting to prevent data modifications
  711. * `CLICKHOUSE_ALLOW_DROP`: Allow destructive operations (any `DROP` or `TRUNCATE`, `DELETE` and `UPDATE` including the `ALTER TABLE` variants, `REPLACE TABLE` / `REPLACE PARTITION` / `CREATE OR REPLACE`, `CLEAR COLUMN` / `CLEAR INDEX` / `CLEAR PROJECTION`, `OPTIMIZE ... DEDUPLICATE`, `MODIFY TTL` / `MATERIALIZE TTL`, `MODIFY/ALTER COLUMN` with `TTL` including `MODIFY COLUMN c REMOVE TTL`, and `DETACH ... PERMANENTLY`)
  712. * Default: `"false"`
  713. * Only takes effect when `CLICKHOUSE_ALLOW_WRITE_ACCESS=true` is also set
  714. * This gate is a best-effort accident guard in the MCP server, not a security boundary. Restrict the ClickHouse user's grants for real enforcement (see [Destructive Operation Protection](#destructive-operation-protection))
  715. ##### ClickHouse TLS certificate files
  716. The certificate variables contain file paths, not PEM contents. mcp-clickhouse passes these
  717. paths to clickhouse-connect. For Docker or Kubernetes, mount the certificate and private key
  718. as read-only files and use their paths inside the container. Do not bake a private key into an
  719. image, commit it to source control, or put its contents in an environment variable.
  720. In `mutual` mode, the configured client certificate identifies this mcp-clickhouse process as
  721. `CLICKHOUSE_USER`. It does not authenticate inbound MCP clients or pass their identities to
  722. ClickHouse. Configure MCP transport authentication separately.
  723. Restart mcp-clickhouse after replacing a certificate or key at the same path when immediate
  724. rotation or revocation is required. Cached clients can retain existing TLS connections, and
  725. the cache does not track file contents or modification times.
  726. ClickHouse Cloud does not support X.509 client certificate authentication for database users.
  727. Use `CLICKHOUSE_USER` and `CLICKHOUSE_PASSWORD` for ClickHouse Cloud. A CA certificate can
  728. still be useful when a private proxy in front of an endpoint presents a certificate signed by
  729. a private CA.
  730. #### MCP server and transport
  731. These variables control the MCP process itself, including transport, authentication, and query-tool execution limits. They are independent of the ClickHouse database settings above. See also [Authentication for HTTP/SSE Transports](#authentication-for-httpsse-transports).
  732. * `CLICKHOUSE_MCP_SERVER_TRANSPORT`: Sets the transport method for the MCP server
  733. * Default: `"stdio"`
  734. * Valid options: `"stdio"`, `"http"`, `"sse"`. This is useful for local development with tools like MCP Inspector.
  735. * `stdio` is typical for Claude Desktop; `http`/`sse` expose a network listener (bind host/port below)
  736. * `"sse"` selects the deprecated standalone HTTP+SSE transport and logs a warning. Use `"http"` for Streamable HTTP in new deployments.
  737. * `CLICKHOUSE_MCP_BIND_HOST`: Host to bind the MCP server to when using HTTP or SSE transport
  738. * Default: `"127.0.0.1"`
  739. * Set to `"0.0.0.0"` to bind to all network interfaces (useful for Docker or remote access)
  740. * Only used when transport is `"http"` or `"sse"` — not related to `CLICKHOUSE_HOST`
  741. * `CLICKHOUSE_MCP_BIND_PORT`: Port to bind the MCP server to when using HTTP or SSE transport
  742. * Default: `"8000"`
  743. * Only used when transport is `"http"` or `"sse"` — not related to `CLICKHOUSE_PORT`
  744. * `CLICKHOUSE_MCP_QUERY_TIMEOUT`: Timeout in seconds for query tool calls
  745. * Default: `"30"`
  746. * Increase this if you see `Query timed out after ...` errors for heavy queries
  747. * When a query times out, the server attempts to cancel it with `KILL QUERY`
  748. * Unless `CLICKHOUSE_SEND_RECEIVE_TIMEOUT` is explicitly set, the HTTP read timeout is capped at this value plus five seconds
  749. * `CLICKHOUSE_MCP_MAX_WORKERS`: Maximum number of concurrent query worker threads
  750. * Default: `"10"`
  751. * Increase if your workload requires many concurrent tool calls
  752. * Metadata tools use a separate pool with `min(4, CLICKHOUSE_MCP_MAX_WORKERS)` threads so schema discovery cannot delay queries
  753. * `CLICKHOUSE_MCP_AUTH_TOKEN`: Static bearer token for HTTP/SSE transports
  754. * Default: None
  755. * One of `CLICKHOUSE_MCP_AUTH_TOKEN`, `FASTMCP_SERVER_AUTH`, or `CLICKHOUSE_MCP_AUTH_DISABLED=true` is **required** for HTTP/SSE transports
  756. * Generate using `uuidgen` or `openssl rand -hex 32`
  757. * Clients must send this token in the `Authorization: Bearer <token>` header
  758. * `FASTMCP_SERVER_AUTH`: Delegate authentication to a [FastMCP auth provider](https://gofastmcp.com/servers/auth)
  759. * Default: None
  760. * Value is the **full class path** of an AuthProvider subclass, e.g. `fastmcp.server.auth.providers.azure.AzureProvider` or `fastmcp.server.auth.providers.google.GoogleProvider`
  761. * When set, mcp-clickhouse loads the provider from the existing `FASTMCP_SERVER_AUTH_*` environment variables; leave `CLICKHOUSE_MCP_AUTH_TOKEN` unset in this mode
  762. * Custom providers receive no environment-derived constructor arguments and must support no-argument construction
  763. * FastMCP 4 no longer supports Supabase HS256 verification. Supabase deployments must use RS256 or ES256.
  764. * `FASTMCP_SERVER_AUTH_VERIFIERS`: Additional token verifiers accepted alongside the `FASTMCP_SERVER_AUTH` provider
  765. * Default: None
  766. * Value is a comma-separated list of **full class paths** of TokenVerifier subclasses, e.g. `fastmcp.server.auth.providers.azure.AzureJWTVerifier` or `fastmcp.server.auth.providers.jwt.JWTVerifier`
  767. * Requires `FASTMCP_SERVER_AUTH`. The provider and the verifiers are combined with FastMCP's `MultiAuth`: the provider is tried first, then each verifier in order
  768. * Each verifier loads from its own `FASTMCP_SERVER_AUTH_*` prefix, so a class can appear only once across both variables
  769. * Like `FASTMCP_SERVER_AUTH`, it is not read from the working-directory `.env` fallback
  770. * `FASTMCP_ENV_FILE`: Optional file containing `FASTMCP_SERVER_AUTH` and provider-specific environment variables
  771. * Default: None. When unset, the compatibility loader reads missing provider fields from `.env` in the working directory. It does not read `FASTMCP_SERVER_AUTH` from that fallback
  772. * Set it in the process environment before startup. A value loaded from the default `.env` cannot redirect the compatibility loader
  773. * If process-set, this file may provide both `FASTMCP_SERVER_AUTH` and provider fields and replaces the working-directory fallback
  774. * Process environment values take precedence case-insensitively
  775. * The mcp-clickhouse compatibility loader reads this file only when building HTTP/SSE authentication and reads only `FASTMCP_SERVER_AUTH` and `FASTMCP_SERVER_AUTH_*` entries. FastMCP 4 may read the same file for its broader settings
  776. * The default `.env` load is separate. It starts at the installed `mcp_clickhouse` package directory, resolves symlinks, walks upward to the filesystem root, and loads the first `.env` found or nothing. It never reads the working directory, regardless of launch method. That file may provide `FASTMCP_SERVER_AUTH` and provider fields along with other server settings. A source checkout normally finds the repository root `.env`
  777. * `CLICKHOUSE_MCP_AUTH_DISABLED`: Disable authentication for HTTP/SSE transports
  778. * Default: `"false"` (authentication is enabled)
  779. * Set to `"true"` to disable authentication for local development/testing only
  780. * **WARNING:** Only use for local development. Do not disable when exposed to networks
  781. * `CLICKHOUSE_MCP_ALLOWED_HOSTS`: Comma separated `Host` header values the HTTP/SSE server answers for
  782. * Default for a loopback bind: bare and any-port forms of `127.0.0.1`, `localhost`, and `[::1]`
  783. * If set, the value must contain at least one Host entry.
  784. * A concrete non-loopback bind address defaults to that address and the configured port. A wildcard bind such as `0.0.0.0` or `::` requires an explicit non-empty value because the public Host cannot be inferred.
  785. * Host validation is a defense in depth against DNS rebinding. Origin validation below is required separately by MCP.
  786. * Entries are exact (`localhost:8000`) or accept any port (`localhost:*`). Example: `CLICKHOUSE_MCP_ALLOWED_HOSTS=127.0.0.1:8000,localhost:8000`
  787. * The `host:*` form matches only values that carry a port. A port-less Host (a standard-port deployment where the client omits `:80`/`:443`) must be listed as a bare exact entry (`example.com`) as well.
  788. * Requests with a non-matching or missing `Host` header get `421 Misdirected Request`. GET and HEAD requests to `/health` are exempt from Host and Origin validation so orchestrator probes keep working.
  789. * Behind a reverse proxy, prefer preserving the original `Host` header. You can instead list the upstream `Host` value the proxy sends. Set an explicit list when a launcher such as `fastmcp run` overrides the bind address for remote access.
  790. * mcp-clickhouse forces FastMCP's separate Host and Origin guard off. `FASTMCP_HTTP_HOST_ORIGIN_PROTECTION`, `FASTMCP_HTTP_ALLOWED_HOSTS`, and `FASTMCP_HTTP_ALLOWED_ORIGINS` do not apply. `CLICKHOUSE_MCP_ALLOWED_HOSTS` and `CLICKHOUSE_MCP_ALLOWED_ORIGINS` are authoritative.
  791. * `CLICKHOUSE_MCP_TRUSTED_PROXIES`: Proxy IP addresses or CIDR networks whose `X-Forwarded-*` headers are trusted
  792. * Default: None. `X-Forwarded-Host` is ignored. Existing Uvicorn handling of `X-Forwarded-For` and `X-Forwarded-Proto` is unchanged.
  793. * Entries must be IP addresses or CIDR networks, such as `127.0.0.1,10.20.0.0/24,2001:db8::1`. CIDRs must use their network address, so `10.20.0.1/24` is rejected. Host names, scoped IPv6 addresses, `*`, `0.0.0.0/0`, and `::/0` are also rejected.
  794. * Trust is based on the immediate raw socket peer. A request from any other peer, or a request without a client address, ignores `X-Forwarded-Host` and validates `Host`.
  795. * A trusted peer may send exactly one `X-Forwarded-Host` header containing one non-empty value. Duplicate fields, empty values, and comma separated lists get `421 Misdirected Request`. If the header is absent, `Host` is validated.
  796. * Use the narrowest possible address or network. The MCP server must only be reachable through proxies in the configured ranges. Every trusted proxy must strip and overwrite client supplied `X-Forwarded-Host` and `X-Forwarded-Proto` values, and construct `X-Forwarded-For` from the verified connection peer.
  797. * The built-in server and `fastmcp run` disable Uvicorn's outer proxy-header handling, validate Host from the raw peer, then apply `X-Forwarded-For` and `X-Forwarded-Proto`. Explicitly enabling `uvicorn_config["proxy_headers"]` fails startup in this mode.
  798. * Direct ASGI embedding must disable proxy-header handling in the outer ASGI server and call `mcp.http_app(raw_client_address_preserved=True)`. Without that explicit assertion, app construction fails when trusted proxies are configured.
  799. * `CLICKHOUSE_MCP_ALLOWED_ORIGINS`: Comma separated `Origin` header values accepted on HTTP/SSE
  800. * Default: None, which rejects every request that carries an `Origin` header
  801. * MCP requires Origin validation for HTTP/SSE transport connections. Requests without an Origin are accepted because non-browser MCP clients normally omit it. A non-matching Origin gets `403 Forbidden`. The `/health` endpoint is exempt as described above.
  802. * Entries are exact (`http://localhost:3000`) or accept any port (`http://localhost:*`). As with hosts, the any-port form matches only origins that carry a port; a standard-port origin (`https://app.example.com`) must be listed exactly.
  803. ##### Reverse proxy Host handling
  804. Preserve `Host` when possible. This keeps forwarded Host trust disabled:
  805. ```nginx
  806. location / {
  807. proxy_pass http://mcp-clickhouse:8000;
  808. proxy_set_header Host $http_host;
  809. proxy_set_header X-Forwarded-Host "";
  810. proxy_set_header X-Forwarded-For $remote_addr;
  811. proxy_set_header X-Forwarded-Proto $scheme;
  812. }
  813. ```
  814. Sanitize `X-Forwarded-For` and `X-Forwarded-Proto` independently of `X-Forwarded-Host` trust. Uvicorn may trust those headers based on the proxy peer even when `CLICKHOUSE_MCP_TRUSTED_PROXIES` is unset.
  815. ```env
  816. CLICKHOUSE_MCP_ALLOWED_HOSTS=mcp.example.com
  817. ```
  818. Stock nginx changes `Host` to the upstream name for proxied requests. It does not create or overwrite `X-Forwarded-Host`. If preserving `Host` is not possible, overwrite the forwarded header at the trusted edge:
  819. ```nginx
  820. location / {
  821. proxy_pass http://mcp-clickhouse:8000;
  822. proxy_set_header X-Forwarded-Host $http_host;
  823. proxy_set_header X-Forwarded-For $remote_addr;
  824. proxy_set_header X-Forwarded-Proto $scheme;
  825. }
  826. ```
  827. ```env
  828. CLICKHOUSE_MCP_ALLOWED_HOSTS=mcp.example.com
  829. CLICKHOUSE_MCP_TRUSTED_PROXIES=10.20.0.8
  830. ```
  831. The second configuration is safe only when `10.20.0.8` is the proxy's immediate source address, the server port is isolated from other clients, and nginx overwrites the incoming forwarding headers as shown. For a proxy chain, each trusted hop must discard unverified incoming values before constructing the new forwarding headers.
  832. On an IPv6 or dual-stack bind, IPv4 proxies may appear as IPv4-mapped addresses such as `::ffff:10.20.0.8`; these are matched against IPv4 entries automatically. Envoy's `append_x_forwarded_host` appends to an existing `X-Forwarded-Host` rather than overwriting it, producing a comma separated list that is rejected, so configure the trusted hop to overwrite the header instead. On Kubernetes with source NAT (for example `externalTrafficPolicy: Cluster`) the observed peer may be a node IP rather than the proxy pod, so trust the pod or node CIDR as appropriate; ingress-nginx overwrites both `Host` and `X-Forwarded-Host` itself.
  833. #### Middleware Variables
  834. * `MCP_MIDDLEWARE_MODULE`: Python module name containing custom middleware to inject into the MCP server
  835. * Default: None (no middleware loaded)
  836. * Set to the module name (without `.py` extension) of your middleware module
  837. * The module must provide a `setup_middleware(mcp)` function
  838. * See [Custom Middleware](#custom-middleware) for details and examples
  839. #### chDB Variables
  840. * `CHDB_ENABLED`: Enable/disable chDB functionality
  841. * Default: `"false"`
  842. * Set to `"true"` to enable chDB tools
  843. * Requires installing the optional extra: `mcp-clickhouse[chdb]`
  844. * On Python 3.15, an independently installed chDB can terminate the process when `CHDB_ENABLED=true`.
  845. * `CHDB_DATA_PATH`: The path to the chDB data directory
  846. * Default: `":memory:"` (in-memory database)
  847. * Use `:memory:` for in-memory database
  848. * Use a file path for persistent storage (e.g., `/path/to/chdb/data`)
  849. #### Common configuration pitfalls
  850. * **`CLICKHOUSE_SECURE` vs MCP / ingress TLS** — Turning off `CLICKHOUSE_SECURE` because the MCP server sits behind Kubernetes ingress, a reverse proxy, or is reached over plain HTTP does not disable database TLS; it only changes how this process connects to ClickHouse. Configure ingress TLS separately from the database client settings.
  851. * **Native protocol ports** — `CLICKHOUSE_PORT` must target ClickHouse's HTTP interface (`8123`/`8443` by default). Ports `9000`/`9440` are for the native TCP protocol (`clickhouse-client`) and will not work with this server.
  852. * **Host confusion** — `CLICKHOUSE_HOST` is the database hostname. `CLICKHOUSE_MCP_BIND_HOST` is only the address the MCP HTTP/SSE server listens on.
  853. #### Example Configurations
  854. For local development with Docker:
  855. ```env
  856. # Required variables
  857. CLICKHOUSE_HOST=localhost
  858. CLICKHOUSE_USER=default
  859. CLICKHOUSE_PASSWORD=clickhouse
  860. # Optional: Override defaults for local development
  861. CLICKHOUSE_SECURE=false # Uses port 8123 automatically
  862. CLICKHOUSE_VERIFY=false
  863. ```
  864. For ClickHouse Cloud:
  865. ```env
  866. # Required variables
  867. CLICKHOUSE_HOST=your-instance.clickhouse.cloud
  868. CLICKHOUSE_USER=default
  869. CLICKHOUSE_PASSWORD=your-password
  870. # Optional: These use secure defaults
  871. # CLICKHOUSE_SECURE=true # Uses port 8443 automatically
  872. # CLICKHOUSE_DATABASE=your_database
  873. ```
  874. For ClickHouse SQL Playground:
  875. ```env
  876. CLICKHOUSE_HOST=sql-clickhouse.clickhouse.com
  877. CLICKHOUSE_USER=demo
  878. CLICKHOUSE_PASSWORD=
  879. # Uses secure defaults (HTTPS on port 8443)
  880. ```
  881. For a private server CA without client certificate authentication:
  882. ```env
  883. CLICKHOUSE_HOST=your-secure-clickhouse.example.com
  884. CLICKHOUSE_USER=your-user
  885. CLICKHOUSE_PASSWORD=your-password
  886. CLICKHOUSE_SECURE=true
  887. CLICKHOUSE_VERIFY=true
  888. CLICKHOUSE_CA_CERT=/run/secrets/clickhouse-ca.pem
  889. ```
  890. For ClickHouse X.509 client certificate authentication:
  891. ```env
  892. CLICKHOUSE_HOST=your-secure-clickhouse.example.com
  893. CLICKHOUSE_USER=your-certificate-user
  894. CLICKHOUSE_SECURE=true
  895. CLICKHOUSE_CLIENT_CERT=/run/secrets/clickhouse-client.pem
  896. CLICKHOUSE_CLIENT_CERT_KEY=/run/secrets/clickhouse-client-key.pem
  897. # CLICKHOUSE_CA_CERT=/run/secrets/clickhouse-ca.pem # Only for a private server CA
  898. # CLICKHOUSE_TLS_MODE=mutual # Optional. This is the default with a client certificate.
  899. ```
  900. For a client certificate required by a strict TLS server while ClickHouse uses Basic
  901. authentication:
  902. ```env
  903. CLICKHOUSE_HOST=your-secure-clickhouse.example.com
  904. CLICKHOUSE_USER=your-user
  905. CLICKHOUSE_PASSWORD=your-password
  906. CLICKHOUSE_SECURE=true
  907. CLICKHOUSE_CLIENT_CERT=/run/secrets/clickhouse-client.pem
  908. CLICKHOUSE_CLIENT_CERT_KEY=/run/secrets/clickhouse-client-key.pem
  909. CLICKHOUSE_TLS_MODE=strict
  910. ```
  911. Use `CLICKHOUSE_TLS_MODE=proxy` instead when a TLS-terminating proxy requires the client
  912. certificate and ClickHouse still uses Basic authentication.
  913. For chDB only (in-memory):
  914. ```env
  915. # chDB configuration
  916. CHDB_ENABLED=true
  917. CLICKHOUSE_ENABLED=false
  918. # CHDB_DATA_PATH defaults to :memory:
  919. ```
  920. For chDB with persistent storage:
  921. ```env
  922. # chDB configuration
  923. CHDB_ENABLED=true
  924. CLICKHOUSE_ENABLED=false
  925. CHDB_DATA_PATH=/path/to/chdb/data
  926. ```
  927. For MCP Inspector or remote access with HTTP transport:
  928. ```env
  929. CLICKHOUSE_HOST=localhost
  930. CLICKHOUSE_USER=default
  931. CLICKHOUSE_PASSWORD=clickhouse
  932. CLICKHOUSE_MCP_SERVER_TRANSPORT=http
  933. CLICKHOUSE_MCP_BIND_HOST=0.0.0.0 # Bind to all interfaces
  934. CLICKHOUSE_MCP_BIND_PORT=4200 # Custom port (default: 8000)
  935. CLICKHOUSE_MCP_AUTH_TOKEN=your-generated-token # One auth mode required for HTTP/SSE (or FASTMCP_SERVER_AUTH, or CLICKHOUSE_MCP_AUTH_DISABLED=true)
  936. CLICKHOUSE_MCP_ALLOWED_HOSTS=127.0.0.1:4200,localhost:4200,mcp.example.com:4200 # Include every Host value clients and proxies send
  937. ```
  938. For local development with HTTP transport (authentication disabled):
  939. ```env
  940. CLICKHOUSE_HOST=localhost
  941. CLICKHOUSE_USER=default
  942. CLICKHOUSE_PASSWORD=clickhouse
  943. CLICKHOUSE_MCP_SERVER_TRANSPORT=http
  944. CLICKHOUSE_MCP_AUTH_DISABLED=true # Only for local development!
  945. CLICKHOUSE_MCP_ALLOWED_HOSTS=127.0.0.1:8000,localhost:8000
  946. ```
  947. When using HTTP transport, the server will run on the configured port (default 8000). For example, with the above configuration:
  948. - MCP endpoint: `http://localhost:8000/mcp`
  949. - Health check: `http://localhost:8000/health`
  950. You can set these variables in your environment, in a `.env` file, or in the Claude Desktop configuration:
  951. ```json
  952. {
  953. "mcpServers": {
  954. "mcp-clickhouse": {
  955. "command": "uv",
  956. "args": [
  957. "run",
  958. "--with",
  959. "mcp-clickhouse",
  960. "--python",
  961. "3.12",
  962. "mcp-clickhouse"
  963. ],
  964. "env": {
  965. "CLICKHOUSE_HOST": "<clickhouse-host>",
  966. "CLICKHOUSE_USER": "<clickhouse-user>",
  967. "CLICKHOUSE_PASSWORD": "<clickhouse-password>",
  968. "CLICKHOUSE_DATABASE": "<optional-database>",
  969. "CLICKHOUSE_MCP_SERVER_TRANSPORT": "stdio",
  970. "CLICKHOUSE_MCP_BIND_HOST": "127.0.0.1",
  971. "CLICKHOUSE_MCP_BIND_PORT": "8000"
  972. }
  973. }
  974. }
  975. }
  976. ```
  977. Note: The bind host and port settings are only used when transport is set to "http" or "sse".
  978. ### Running tests
  979. ```bash
  980. uv sync --locked --extra dev # install dev dependencies
  981. uv run ruff check . # run linting
  982. docker compose -f test-services/docker-compose.yaml up -d # start ClickHouse
  983. uv run pytest -v tests
  984. uv run pytest -v tests/test_tool.py # ClickHouse only
  985. # Python 3.10 through 3.14 only:
  986. CHDB_ENABLED=true uv run --extra chdb pytest -v tests/test_chdb_tool.py # chDB only
  987. ```
  988. ## YouTube Overview
  989. [![YouTube](http://i.ytimg.com/vi/y9biAm_Fkqw/hqdefault.jpg)](https://www.youtube.com/watch?v=y9biAm_Fkqw)

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.