FFFF Refactor server internals into focused modules by joe-clickhouse · Pull Request #240 · ClickHouse/mcp-clickhouse · GitHub
[go: up one dir, main page]

Skip to content
Merged
10 changes: 5 additions & 5 deletions .claude/agents/docs-drift-reviewer.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
---
name: docs-drift-reviewer
description: Checks whether README.md, server.json, fastmcp.json, and CHANGELOG.md still match the code on the current branch, and updates them where they do not. Use once implementation work is done, right before opening a PR, to catch drift in the environment variable tables, tool descriptions, response shapes, security guidance, or registry metadata.
description: "Checks whether README.md, server.json, fastmcp.json, and CHANGELOG.md still match the code on the current branch, and updates them where they do not. Use once implementation work is done, right before opening a PR, to catch drift in the environment variable tables, tool descriptions, response shapes, security guidance, or registry metadata."
tools: Read, Write, Edit, Bash, Grep, Glob
model: inherit
---
Expand Down Expand Up @@ -41,19 +41,19 @@ Do not report these. They look like drift and are not.

## Workflow

1. Determine the diff. Default to `git diff main...HEAD`, plus `git status` and `git diff` for anything uncommitted. Use whatever range the caller specified instead, if they gave one.
1. Determine the diff. Default to `git diff main...HEAD`, plus `git status --short`, `git diff`, and `git diff --cached` for anything uncommitted. Read relevant untracked files separately. Use whatever range the caller specified instead, if they gave one.
2. Read the actual diff, not the commit messages. Commit messages and changelog entries can be incomplete or wrong; the diff is ground truth.
3. Filter it down to user-visible surface:
- New, renamed, or removed environment variables, and any change to a default, to parsing, or to validation.
- New, renamed, or removed tools and prompts. Changed tool arguments, argument defaults, or result shapes.
- Changed error behavior a user would see.
- Changed security behavior: auth mode handling, the write and DROP gates, what `/health` returns, bind host defaults.
- Changed security behavior: auth selection at HTTP/SSE app construction, Host/Origin validation, trusted-proxy handling, the write and DROP gates, what `/health` returns, and bind defaults.
- Changed startup or transport behavior, which can also touch the Dockerfile and the CLI entry point.
- Ignore internal refactors, private helpers, and test-only changes. They have nothing for docs to reflect.
4. For each user-visible change, find every place the docs describe it. Environment variables in particular appear in several places in the README: a configuration table, one or more example blocks, and sometimes the security or development sections. Fixing one occurrence and missing the others is the most common way this job gets done badly. Grep for the variable name and check every hit.
5. Verify the registered reality rather than trusting the README. Tool names, argument names, and docstrings become the exposed MCP schema through FastMCP introspection, so read the decorated functions in `mcp_server.py` and confirm the README describes what is actually registered. When it matters, list the tools through an in-memory `fastmcp.Client` and compare.
5. Verify the registered reality rather than trusting the README. Tool names, argument names, and docstrings become the exposed MCP schema through FastMCP introspection, so trace registration from the server assembly to the owning modules and confirm the README describes what is actually registered. Do not assume every tool, serializer, or auth helper still lives in `mcp_server.py`. When it matters, list the tools through an in-memory `fastmcp.Client` and compare.
6. Edit the affected sections directly. Keep edits minimal and consistent with the surrounding page: same heading depth, same code fence style, same tone. A doc page describes current behavior, so do not add "recently changed" framing.
7. When you touch a code sample, confirm it would actually run against the current API rather than assuming the old version still works.
7. When you touch a code sample, confirm it would actually run against the current API rather than assuming the old version still works. Read dependency bounds from `pyproject.toml`, pins from `uv.lock`, and CI versions from `.github/workflows/ci.yaml`. Use `importlib.metadata` through `uv run --no-sync python` when installed versions matter. Do not infer them from a hardcoded site-packages path. Use `rg --hidden --no-ignore` for dependency source inside an ignored environment.
8. If a change is genuinely internal, leave the docs alone. Do not invent documentation for something a user cannot observe.
9. If you cannot tell whether something is user-visible, or where it belongs, say so in your report rather than editing speculatively.

Expand Down
16 changes: 13 additions & 3 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,17 @@ Act like an experienced maintainer of a public Python MCP server and database in

## Project Map

- `mcp_clickhouse/mcp_server.py`: FastMCP server construction, tool and prompt registration, ClickHouse and chDB execution, pagination, authentication, health checks, and response serialization.
- `mcp_clickhouse/mcp_server.py`: Startup assembly, FastMCP server construction, tool and prompt registration, and shutdown coordination.
- `mcp_clickhouse/auth.py`: Default dotenv loading, HTTP/SSE authentication, and FastMCP provider environment compatibility.
- `mcp_clickhouse/transport.py`: FastMCP HTTP/SSE app construction and trusted proxy integration.
- `mcp_clickhouse/executors.py`: Per-server query, metadata, cancellation, and health worker pools.
- `mcp_clickhouse/chdb_backend.py`: Per-server chDB state, lazy client initialization, query execution, and result processing.
- `mcp_clickhouse/clients.py`: Request configuration, connection diagnostics, readonly settings, and per-server ClickHouse client caches and leases.
- `mcp_clickhouse/queries.py`: Per-server ClickHouse query execution, active-query state, cancellation, and destructive-operation guards.
- `mcp_clickhouse/metadata.py`: Database and table discovery, metadata models, and per-server pagination state.
- `mcp_clickhouse/health.py`: Per-server health probes, result caching, and the public health route.
- `mcp_clickhouse/serialization.py`: JSON tool-result encoding and exact integer handling.
- `mcp_clickhouse/http_security.py`: Host and Origin validation and trusted proxy handling.
- `mcp_clickhouse/mcp_env.py`: environment-backed configuration and validation. Treat this as the source of truth for configuration semantics.
- `mcp_clickhouse/main.py`: runtime entry point and transport startup.
- `mcp_clickhouse/mcp_middleware_hook.py`: optional user-provided middleware loading.
Expand All @@ -40,9 +50,9 @@ Act like an experienced maintainer of a public Python MCP server and database in

## Architecture And MCP Contract

This module has meaningful import-time behavior. `mcp_server.py` loads `.env`, resolves transport authentication, constructs the `FastMCP` instance, and conditionally registers ClickHouse and chDB tools. Account for that when changing configuration or writing tests. Environment changes made after import may not affect server construction or tool registration.
This module has meaningful import-time behavior. `mcp_server.py` loads `.env`, creates executors, constructs the `FastMCP` instance, and conditionally registers ClickHouse and chDB tools. HTTP/SSE authentication resolves when the transport app is constructed. Account for that when changing configuration or writing tests. Environment changes made after import may not affect server construction or tool registration.

- Keep blocking ClickHouse and chDB work off the event loop. MCP-facing query tools are async wrappers around work submitted to `QUERY_EXECUTOR`.
- Keep blocking ClickHouse and chDB work off the event loop. MCP-facing query tools are async wrappers around work submitted to the query executor.
- When changing query execution, consider the synchronous helper, the async MCP wrapper, timeout handling, cancellation, logging, and error conversion together.
- Registered tool functions must remain compatible with FastMCP introspection. Preserve useful type annotations and docstrings because they contribute to the exposed schema.
- Tool results are deliberately JSON-encoded strings. Do not return raw dictionaries or lists without verifying FastMCP protocol behavior and updating all affected tests and documentation.
Expand Down
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@ All notable changes to this project will be documented in this file.
- Request-scoped client overrides are now validated for TLS consistency before client creation. `verify`, `ca_cert`, `client_cert`, `client_cert_key`, `tls_mode`, `server_host_name`, and `pool_mgr` must be top-level overrides and are rejected under `generic_args` and as DSN query parameters. Previously `generic_args.verify` and a DSN `verify` parameter reached clickhouse-connect. DSN overrides cannot select the chdb backend.
- A `secure` override now switches the client interface between `https` and `http`, and an explicit `interface` override must be `http` or `https` and agree with `secure`. Previously a `secure` override alone left the base interface in place. `secure` and `verify` override values must be booleans or the strings `true` or `false`. `verify` also accepts `proxy`.

### Compatibility

- Some undocumented imports from `mcp_clickhouse.mcp_server`, including `Table`, `execute_query`, and `QUERY_EXECUTOR`, have been removed. See [Code layout](README.md#code-layout) for the owning modules. Query execution methods and worker pools now belong to per-server instances. The exports in `mcp_clickhouse.__all__` and the documented `mcp_server.CLIENT_CONFIG_OVERRIDES_KEY` import remain available. MCP tool and prompt contracts are unchanged.

## 0.6.0 - 2026-09-03

### Added
Expand Down
25 changes: 25 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -688,6 +688,31 @@ CLICKHOUSE_PASSWORD=clickhouse
curl http://localhost:8000/health
```

### Code layout

The package uses a flat module layout. Start with [mcp_server.py](mcp_clickhouse/mcp_server.py)
for server assembly and registration, then follow the implementation into its owning module.

| Module | Responsibility |
|--------|----------------|
| [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 |
| [clients.py](mcp_clickhouse/clients.py) | Request configuration, cached ClickHouse connections, and client leases |
| [queries.py](mcp_clickhouse/queries.py) | Query execution, cancellation, and destructive-operation guards |
| [metadata.py](mcp_clickhouse/metadata.py) | Database and table discovery, metadata models, and pagination |
| [chdb_backend.py](mcp_clickhouse/chdb_backend.py), [chdb_prompt.py](mcp_clickhouse/chdb_prompt.py) | Optional chDB initialization, query execution, and prompt content |
| [health.py](mcp_clickhouse/health.py), [executors.py](mcp_clickhouse/executors.py) | Health probes and caching, and the worker pools used by server operations |
| [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 |
| [mcp_env.py](mcp_clickhouse/mcp_env.py), [serialization.py](mcp_clickhouse/serialization.py) | Environment configuration and JSON result encoding |
| [mcp_middleware_hook.py](mcp_clickhouse/mcp_middleware_hook.py), [skills_advisor.py](mcp_clickhouse/skills_advisor.py) | Custom middleware loading and server instructions |

Each server assembly owns its worker pools, client cache, active queries, pagination cache,
health state, and chDB backend. Worker and client cleanup runs at process exit. Package imports
initialize the default server, including when first importing an extracted module.

In tests, patch the module or owner instance where the code reads a dependency. For example,
patch `mcp_clickhouse.clients.clickhouse_connect.get_client` for client creation. Compatibility
imports in `mcp_server.py` can be separate bindings from the ones an implementation uses.

### Environment Variables

Configuration is split into **independent** groups. Mixing them up is a common cause of hard-to-debug connection failures:
Expand Down
Loading
Loading
0