Repository navigation
Client connection reuse and server-side query cancellation - #152
Merged
Merged
Conversation
Contributor
There was a problem hiding this comment.
Pull request overview
This PR hardens the mcp_clickhouse MCP server for sustained/high-concurrency usage by reusing ClickHouse clients across tool calls, implementing true server-side query cancellation, and aligning network timeouts to prevent worker exhaustion.
Changes:
- Added a cached
clickhouse_connectclient layer keyed by resolved client config, with eviction on liveness/connection failures and limited retries for safe metadata tools. - Implemented query ID tracking and server-side cancellation via
KILL QUERYon MCP timeouts. - Introduced
CLICKHOUSE_MCP_MAX_WORKERSand alignedsend_receive_timeouttoquery_timeout + 5unless explicitly overridden.
Reviewed changes
Copilot reviewed 7 out of 7 changed files in this pull request and generated 6 comments.
Show a summary per file
| File | Description |
|---|---|
mcp_clickhouse/mcp_server.py |
Implements client caching, active query tracking, cancellation via KILL QUERY, timeout alignment, and worker pool sizing/logging. |
mcp_clickhouse/mcp_env.py |
Adds CLICKHOUSE_MCP_MAX_WORKERS configuration property. |
mcp_clickhouse/__init__.py |
Exposes additional helpers at package level via imports/__all__. |
README.md |
Documents the updated timeout behavior, cancellation semantics, and new max-workers config. |
tests/test_client_cache.py |
Adds coverage for caching behavior, eviction, and timeout alignment. |
tests/test_query_cancellation.py |
Adds coverage for query_id propagation, active query tracking, and timeout-triggered cancellation. |
tests/test_context_config_override.py |
Ensures test isolation by clearing the client cache around config override tests. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
peter-leonov-ch
approved these changes
Apr 30, 2026
Contributor
There was a problem hiding this comment.
Not sure if this PR has integration tests, if not, that'd be nice to add.
4 tasks done
ForisKuang
pushed a commit
to ForisKuang/cbioportal-mcp
that referenced
this pull request
Sep 4, 2026
mcp-clickhouse 0.5.0 (ClickHouse/mcp-clickhouse#152) added its own config-keyed client cache with refcounted leases, server-side query cancellation, and stale-client eviction -- a strictly better version of what clickhouse_pool.py did by hand via monkey-patching, including real query cancellation and eviction that the custom patch never had. Delete the patch and bump the pin. 0.1.11 -> 0.5.0 (staying off 0.6.0, which moves to FastMCP 4) crosses two breaking changes for this repo's call sites: - 0.3.0 renamed run_select_query -> run_query. - 0.4.0 made tool responses JSON-encoded strings instead of raw dicts, and 0.5.0's execute_query additionally requires query_id/client_config args this repo never had -- so the two direct execute_query() calls (list_tables, list_table_columns) and permissions.py's CHECK GRANT helper now go through run_query() + json.loads() instead. The fastmcp upper bound (<2.14) was only there because 0.1.11 passed a dependencies= kwarg to FastMCP() that 2.14 removed; 0.5.0 doesn't do that, so it's lifted to match what mcp-clickhouse 0.5.0 itself requires (>=2.12.3,<3.0.0). Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
inodb
added a commit
to cBioPortal/cbioportal-mcp
that referenced
this pull request
Sep 4, 2026
* Pool the ClickHouse client instead of creating one per query mcp_clickhouse.mcp_server.create_clickhouse_client() runs on every tool call today (execute_query, run_select_query, list_databases, list_tables), each paying a full clickhouse_connect handshake -- TLS setup plus a version/timezone round trip -- before the actual query starts. Monkey-patch it at runtime to return one shared, reused client instead, without touching the vendored package's source. Two things had to be verified against the installed package/library rather than assumed, both confirmed live against the real ClickHouse Cloud instance: - Patch target: mcp_clickhouse/__init__.py re-exports create_clickhouse_client from .mcp_server, but every internal call site resolves the bare name against mcp_server.py's own globals, not the package-level re-export. Patching the re-export is a verified no-op -- the patch is simply never called by anything internal. - Session concurrency: clickhouse_connect stamps every client with a random session_id by default and refuses concurrent queries within one session. This server runs SELECTs from mcp_clickhouse's own multi-worker thread pool over HTTP transport, so a naively shared client breaks under real concurrent load (verified: ProgrammingError under 10 concurrent queries) until autogenerate_session_id is disabled globally. A 30-minute TTL rebuilds the pooled client periodically as a coarse safety net for staleness clickhouse_connect's own connection-level recycling doesn't cover (e.g. credential rotation) -- not a retry-on-error mechanism. A startup assertion that create_clickhouse_client still exists on the vendored module makes a future mcp-clickhouse version bump that restructures client creation fail loudly at import time instead of silently falling back to the unpooled path. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> * Replace custom client pooling with mcp-clickhouse's native client cache mcp-clickhouse 0.5.0 (ClickHouse/mcp-clickhouse#152) added its own config-keyed client cache with refcounted leases, server-side query cancellation, and stale-client eviction -- a strictly better version of what clickhouse_pool.py did by hand via monkey-patching, including real query cancellation and eviction that the custom patch never had. Delete the patch and bump the pin. 0.1.11 -> 0.5.0 (staying off 0.6.0, which moves to FastMCP 4) crosses two breaking changes for this repo's call sites: - 0.3.0 renamed run_select_query -> run_query. - 0.4.0 made tool responses JSON-encoded strings instead of raw dicts, and 0.5.0's execute_query additionally requires query_id/client_config args this repo never had -- so the two direct execute_query() calls (list_tables, list_table_columns) and permissions.py's CHECK GRANT helper now go through run_query() + json.loads() instead. The fastmcp upper bound (<2.14) was only there because 0.1.11 passed a dependencies= kwarg to FastMCP() that 2.14 removed; 0.5.0 doesn't do that, so it's lifted to match what mcp-clickhouse 0.5.0 itself requires (>=2.12.3,<3.0.0). Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> --------- Co-authored-by: Foris Kuang <foriskuang@kathryns-air.mynetworksettings.com> Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com> Co-authored-by: Ino de Bruijn <ino@ino.bio>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
8000
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
The goal of this PR is to harden the MCP server for heavy, sustained usage by reusing client connections, adding real server-side query cancellation, and preventing worker thread pool exhaustion from zombie queries.
clickhouse_connectclients by config key instead of creating a new client on every tool call. Eliminates hundreds of ms of overhead per call that a significant contributor to intermittent timeouts under sustained use.query_idto every query and issueKILL QUERYon timeout instead of the no-opfuture.cancel(). Timed-out queries no longer continue running as zombies consuming worker threads and ClickHouse server resources.send_receive_timeouttoquery_timeout+ 5, unless explicitly overridden so worker threads unblock shortly after the MCP timeout fires, preventing thread pool exhaustion.list_databasesandlist_tablesretry once with a fresh client.run_queryevicts but does not retry because writes could duplicate.ContextVaris available before dispatching to the worker thread, fixing a latent bug where PR Client config override support via MCP Context Session states #115 overrides were silently missed inside the executor.