8000 Client connection reuse and server-side query cancellation by joe-clickhouse · Pull Request #152 · ClickHouse/mcp-clickhouse · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions CHANGELOG.md
8000
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,14 @@ All notable changes to this project will be documented in this file.
## Unreleased

### Added
- Client connection reuse across tool calls via a config-keyed cache, eliminating per-call connection overhead. ([#152](https://github.com/ClickHouse/mcp-clickhouse/pull/152))
- Best-effort server-side query cancellation: timed-out queries now attempt `KILL QUERY` on the ClickHouse server so workers and server resources can be released. ([#152](https://github.com/ClickHouse/mcp-clickhouse/pull/152))
- `CLICKHOUSE_MCP_MAX_WORKERS` environment variable to configure the query worker thread pool size (default: `10`). ([#152](https://github.com/ClickHouse/mcp-clickhouse/pull/152))
- DNS rebinding protection for every HTTP and SSE launch path, including `fastmcp run` and `fastmcp.json`. `Host` and `Origin` headers are validated via the new `CLICKHOUSE_MCP_ALLOWED_HOSTS` and `CLICKHOUSE_MCP_ALLOWED_ORIGINS` variables: a present `Origin` that is not allow-listed is rejected with `403`, and an unknown `Host` with `421`. Authentication is now enforced whenever `fastmcp run` selects HTTP or SSE, independently of `CLICKHOUSE_MCP_SERVER_TRANSPORT`, closing a launch path that previously served unauthenticated. ([#218](https://github.com/ClickHouse/mcp-clickhouse/issues/218))
- With `CLICKHOUSE_ALLOW_WRITE_ACCESS=true` and `CLICKHOUSE_ALLOW_DROP` unset, the server now runs `SHOW GRANTS` once at first connection and logs a warning if the ClickHouse user holds `ALL`, `DROP`, `TRUNCATE`, `DELETE`, `UPDATE`, or `ALTER` (beyond `ALTER ADD`) privileges, since the destructive-operation gate is not server-enforced. The check is fail-open and never blocks startup or queries. Grants held via roles are not expanded, so the advisory only flags direct grants.

### Changed
- `CLICKHOUSE_SEND_RECEIVE_TIMEOUT` is now auto-capped to `CLICKHOUSE_MCP_QUERY_TIMEOUT + 5` unless explicitly set, so HTTP reads unblock shortly after an MCP timeout fires. ([#152](https://github.com/ClickHouse/mcp-clickhouse/pull/152))
- **Breaking:** HTTP/SSE transports now validate `Host` and `Origin` by default, so existing deployments can change behavior on upgrade:
- A wildcard bind (`CLICKHOUSE_MCP_BIND_HOST=0.0.0.0` or `::`) now refuses to start unless `CLICKHOUSE_MCP_ALLOWED_HOSTS` is set, because the public host cannot be inferred. Migration: set `CLICKHOUSE_MCP_ALLOWED_HOSTS` to the `host:port` values clients and reverse proxies use.
- A request whose `Host` is not the bind address or a loopback default is rejected with `421`, and any request carrying an `Origin` not listed in `CLICKHOUSE_MCP_ALLOWED_ORIGINS` is rejected with `403`. Migration: set `CLICKHOUSE_MCP_ALLOWED_ORIGINS` for browser-based clients; non-browser clients that send no `Origin` are unaffected.
Expand All @@ -17,6 +21,9 @@ All notable changes to this project will be documented in this file.
- Connection failures now log actionable hints for common misconfigurations (native TCP port used instead of the HTTP interface, TLS/`CLICKHOUSE_SECURE` mismatches), and a warning is logged when `CLICKHOUSE_PORT` is set to a native protocol port (9000/9440). ([#102](https://github.com/ClickHouse/mcp-clickhouse/issues/102))

### Fixed
- `/health` now runs ClickHouse probes outside the event loop and shares one probe across concurrent requests. A stalled probe returns `503` after two seconds instead of blocking the HTTP server.
- The exported `create_clickhouse_client` helper again preserves clickhouse-connect session ID behavior. Cache-owned MCP clients still disable autogenerated session IDs.
- `list_databases` and `list_tables` now evict stale cached clients and retry once after connection errors. `run_query` is not retried because a write may already have succeeded.
- Per-request ClickHouse client configuration overrides now reach `run_query` worker threads. Invalid override state and role aliases fail closed, nested settings preserve the configured role, and opaque client objects remain supported.
- Destructive-operation protection no longer misses `TRUNCATE` statements that omit the `TABLE` keyword (`TRUNCATE db.name` is valid ClickHouse syntax), `TRUNCATE DATABASE`, `TRUNCATE ALL TABLES FROM`, `ALTER TABLE ... DROP PARTITION` / `DROP PART` / `DROP COLUMN`, or `DROP` of object types outside `TABLE`/`DATABASE`/`VIEW`/`DICTIONARY`. With `CLICKHOUSE_ALLOW_WRITE_ACCESS=true` and `CLICKHOUSE_ALLOW_DROP` unset, these statements previously ran and deleted data.
- Destructive-operation protection no longer rejects safe statements that merely contain `drop` or `truncate` inside a string literal, a quoted identifier, or a SQL comment, such as `INSERT INTO logs VALUES ('drop the table')`. Comments can no longer hide a destructive statement from the check either.
Expand Down
25 changes: 13 additions & 12 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ An MCP server for ClickHouse.
When running with HTTP or SSE transport, a health check endpoint is available at `/health`. This endpoint:
- Returns `200 OK` (body: `OK`) if the server is healthy and can connect to ClickHouse
- Returns `503 Service Unavailable` with a generic error message if the server cannot connect to ClickHouse
- Returns `503` if a ClickHouse probe does not finish within two seconds. Concurrent requests share one in-flight probe

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.

Expand Down Expand Up @@ -161,8 +162,7 @@ This MCP server supports both ClickHouse and chDB. You can enable either or both
"CLICKHOUSE_ROLE": "<clickhouse-role>",
"CLICKHOUSE_SECURE": "true",
"CLICKHOUSE_VERIFY": "true",
"CLICKHOUSE_CONNECT_TIMEOUT": "30",
"CLICKHOUSE_SEND_RECEIVE_TIMEOUT": "30"
"CLICKHOUSE_CONNECT_TIMEOUT": "30"
}
}
}
Expand Down Expand Up @@ -193,8 +193,7 @@ Or, if you'd like to try it out with the [ClickHouse SQL Playground](https://sql
"CLICKHOUSE_PASSWORD": "",
"CLICKHOUSE_SECURE": "true",
"CLICKHOUSE_VERIFY": "true",
"CLICKHOUSE_CONNECT_TIMEOUT": "30",
"CLICKHOUSE_SEND_RECEIVE_TIMEOUT": "30"
"CLICKHOUSE_CONNECT_TIMEOUT": "30"
}
}
}
Expand Down Expand Up @@ -249,7 +248,6 @@ You can also enable both ClickHouse and chDB simultaneously:
"CLICKHOUSE_SECURE": "true",
"CLICKHOUSE_VERIFY": "true",
"CLICKHOUSE_CONNECT_TIMEOUT": "30",
"CLICKHOUSE_SEND_RECEIVE_TIMEOUT": "30",
"CHDB_ENABLED": "true",
"CHDB_DATA_PATH": "/path/to/chdb/data"
}
Expand Down Expand Up @@ -330,8 +328,7 @@ If you prefer to use the system Python installation instead of uv, you can insta
"CLICKHOUSE_PASSWORD": "<clickhouse-password>",
"CLICKHOUSE_SECURE": "true",
"CLICKHOUSE_VERIFY": "true",
"CLICKHOUSE_CONNECT_TIMEOUT": "30",
"CLICKHOUSE_SEND_RECEIVE_TIMEOUT": "30"
"CLICKHOUSE_CONNECT_TIMEOUT": "30"
}
}
}
Expand All @@ -352,8 +349,7 @@ Alternatively, you can use the installed script directly:
"CLICKHOUSE_PASSWORD": "<clickhouse-password>",
"CLICKHOUSE_SECURE": "true",
"CLICKHOUSE_VERIFY": "true",
"CLICKHOUSE_CONNECT_TIMEOUT": "30",
"CLICKHOUSE_SEND_RECEIVE_TIMEOUT": "30"
"CLICKHOUSE_CONNECT_TIMEOUT": "30"
}
}
}
Expand Down Expand Up @@ -565,8 +561,8 @@ These variables configure the [clickhouse-connect](https://clickhouse.com/docs/e
* Default: `"30"`
* Increase this value if you experience connection timeouts
* `CLICKHOUSE_SEND_RECEIVE_TIMEOUT`: Send/receive timeout in seconds for the **ClickHouse** client
* Default: `"300"`
* Increase this value for long-running queries
* Default: the lower of `300` or `CLICKHOUSE_MCP_QUERY_TIMEOUT + 5`, so worker threads unblock shortly after a query timeout
* If explicitly set, the value is used as-is (e.g. `"300"` for long-running queries)
* `CLICKHOUSE_DATABASE`: Default ClickHouse database to use
* Default: None (uses server default)
* Set this to automatically connect to a specific database
Expand Down Expand Up @@ -597,9 +593,14 @@ These variables control the MCP process itself, including transport, authenticat
* `CLICKHOUSE_MCP_BIND_PORT`: Port to bind the MCP server to when using HTTP or SSE transport
* Default: `"8000"`
* Only used when transport is `"http"` or `"sse"` — not related to `CLICKHOUSE_PORT`
* `CLICKHOUSE_MCP_QUERY_TIMEOUT`: Timeout in seconds for query tools
* `CLICKHOUSE_MCP_QUERY_TIMEOUT`: Timeout in seconds for query tool calls
* Default: `"30"`
* Increase this if you see `Query timed out after ...` errors for heavy queries
* When a query times out, the server attempts to cancel it with `KILL QUERY`
* Unless `CLICKHOUSE_SEND_RECEIVE_TIMEOUT` is explicitly set, the HTTP read timeout is capped at this value plus five seconds
* `CLICKHOUSE_MCP_MAX_WORKERS`: Maximum number of concurrent query worker threads
* Default: `"10"`
* Increase if your workload requires many concurrent tool calls
* `CLICKHOUSE_MCP_AUTH_TOKEN`: Static bearer token for HTTP/SSE transports
* Default: None
* One of `CLICKHOUSE_MCP_AUTH_TOKEN`, `FASTMCP_SERVER_AUTH`, or `CLICKHOUSE_MCP_AUTH_DISABLED=true` is **required** for HTTP/SSE transports
Expand Down
9 changes: 9 additions & 0 deletions mcp_clickhouse/mcp_env.py
Original file line number Diff line number Diff line change
Expand Up @@ -316,6 +316,7 @@ class MCPServerConfig:
CLICKHOUSE_MCP_BIND_HOST: Bind host for HTTP/SSE (default: 127.0.0.1)
CLICKHOUSE_MCP_BIND_PORT: Bind port for HTTP/SSE (default: 8000)
CLICKHOUSE_MCP_QUERY_TIMEOUT: SELECT tool timeout in seconds (default: 30)
CLICKHOUSE_MCP_MAX_WORKERS: Maximum thread pool workers for query execution (default: 10)
Comment thread
joe-clickhouse marked this conversation as resolved.
Resolved
CLICKHOUSE_MCP_ALLOWED_HOSTS: Comma separated Host header values accepted on
HTTP/SSE (default: derived from a concrete bind host and port)
CLICKHOUSE_MCP_ALLOWED_ORIGINS: Comma separated Origin header values accepted on
Expand Down Expand Up @@ -348,6 +349,14 @@ def bind_port(self) -> int:
def query_timeout(self) -> int:
return int(os.getenv("CLICKHOUSE_MCP_QUERY_TIMEOUT", "30"))

@property
def max_workers(self) -> int:
"""Maximum thread pool workers for query execution.

Default: 10
"""
return int(os.getenv("CLICKHOUSE_MCP_MAX_WORKERS", "10"))

@property
def allowed_hosts(self) -> List[str]:
"""Host header values the HTTP/SSE transports answer for.
Expand Down
Loading
Loading
0