### Full Configuration Setup Example Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/_autodocs/api-reference-env.md Loads and checks all available configurations (ClickHouse, chDB, MCP Server) and prints relevant settings based on their enabled status and transport type. ```python from mcp_clickhouse.mcp_env import get_config, get_chdb_config, get_mcp_config # Load all configurations clickhouse_config = get_config() chdb_config = get_chdb_config() mcp_config = get_mcp_config() # Check what's enabled if clickhouse_config.enabled: print(f"ClickHouse: {clickhouse_config.host}:{clickhouse_config.port}") if chdb_config.enabled: print(f"chDB: {chdb_config.data_path}") # Server transport settings print(f"Transport: {mcp_config.server_transport}") if mcp_config.server_transport in ("http", "sse"): print(f"Binding to: {mcp_config.bind_host}:{mcp_config.bind_port}") ``` -------------------------------- ### Start MCP Server for Development Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/README.md Run the MCP server for local development and testing with the MCP Inspector. Ensure dependencies are installed using `uv` and the virtual environment is activated. ```bash fastmcp dev mcp_clickhouse/mcp_server.py ``` -------------------------------- ### Example: Loading Middleware Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/_autodocs/api-reference-middleware.md This example demonstrates how to import and use the `setup_middleware` function to load middleware from the environment. ```python from mcp_clickhouse.mcp_middleware_hook import setup_middleware from mcp_clickhouse.mcp_server import mcp # Load middleware from environment setup_middleware(mcp) ``` -------------------------------- ### Get chDB Initial Prompt Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/_autodocs/api-reference-public-functions.md Retrieves the chDB usage guide and documentation in Markdown format, including a reference for table functions. ```python from mcp_clickhouse import chdb_initial_prompt help_text = chdb_initial_prompt() print(help_text) ``` -------------------------------- ### Get MCP Server Configuration Example Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/_autodocs/types.md Retrieves the singleton MCP server configuration. This example shows how to check the transport type and print server details if using HTTP. ```python from mcp_clickhouse.mcp_env import get_mcp_config, TransportType config = get_mcp_config() if config.server_transport == TransportType.HTTP.value: print(f"HTTP server on {config.bind_host}:{config.bind_port}") if config.auth_token: print("Using bearer token authentication") ``` -------------------------------- ### Starting the CLI Server Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/_autodocs/api-reference-main.md Start the mcp-clickhouse server directly from the command line using the registered entry point. ```bash mcp-clickhouse ``` -------------------------------- ### List Tables and Print Column Details Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/_autodocs/types.md Demonstrates how to list tables in a database and iterate through their columns, printing each column's name, type, and comment. This example requires the mcp_clickhouse library to be installed. ```python import json from mcp_clickhouse import list_tables result = json.loads(list_tables('my_db', include_detailed_columns=True)) table = result['tables'][0] for column in table['columns']: print(f"{column['name']}: {column['column_type']}") if column['comment']: print(f" Comment: {column['comment']}") ``` -------------------------------- ### Get ChDB Configuration Example Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/_autodocs/types.md Retrieves the singleton chDB configuration instance. Check the 'enabled' flag before accessing other properties like 'data_path'. ```python from mcp_clickhouse.mcp_env import get_chdb_config config = get_chdb_config() if config.enabled: print(f"chDB data path: {config.data_path}") ``` -------------------------------- ### Enable Example Middleware Module Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/README.md To use the provided example middleware, set the MCP_MIDDLEWARE_MODULE environment variable to 'example_middleware'. This module demonstrates logging requests and measuring processing time. ```json "env": { "MCP_MIDDLEWARE_MODULE": "example_middleware" } ``` -------------------------------- ### Install Dev Dependencies and Run Linting Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/README.md Commands to install development dependencies using uv and run linting checks with ruff. ```bash uv sync --all-extras --dev # install dev dependencies uv run ruff check . # run linting ``` -------------------------------- ### Starting Server with Custom Middleware Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/_autodocs/api-reference-main.md Start the mcp-clickhouse server with a custom middleware module loaded. The MCP_MIDDLEWARE_MODULE environment variable specifies the Python module containing the middleware setup function. ```bash MCP_MIDDLEWARE_MODULE=my_middleware \ python -m mcp_clickhouse.main ``` -------------------------------- ### Run chDB SELECT Query Examples Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/_autodocs/tools.md Python examples demonstrating how to use the `run_chdb_select_query` tool to query local CSV files, remote Parquet files, S3 data, and join data from multiple sources. ```python # Query local CSV file query = "SELECT * FROM file('/data/users.csv', 'CSV') LIMIT 10" result = json.loads(run_chdb_select_query(query)) ``` ```python # Query remote Parquet query = "SELECT * FROM url('https://example.com/data.parquet') WHERE id > 100" result = json.loads(run_chdb_select_query(query)) ``` ```python # Query S3 query = "SELECT COUNT(*) FROM s3('s3://my-bucket/events/*.parquet')" result = json.loads(run_chdb_select_query(query)) ``` ```python # Join multiple sources query = """ SELECT u.id, u.name, e.event_count FROM file('/data/users.csv', 'CSV') u JOIN s3('s3://bucket/events.parquet') e ON u.id = e.user_id """ result = json.loads(run_chdb_select_query(query)) ``` -------------------------------- ### Install mcp-clickhouse Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/_autodocs/index.md Install the mcp-clickhouse package. Use the `[chdb]` extra for chDB support. ```bash # Basic ClickHouse support pip install mcp-clickhouse # With chDB support (embedded ClickHouse) pip install 'mcp-clickhouse[chdb]' ``` -------------------------------- ### Example: Request Logging Middleware Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/_autodocs/api-reference-middleware.md This example implements a middleware that logs all incoming requests and their completion. It demonstrates how to use the `on_request` hook. ```python # logging_middleware.py import logging from fastmcp.server.middleware import Middleware, MiddlewareContext, CallNext logger = logging.getLogger("mcp-logging") class RequestLoggingMiddleware(Middleware): """Log all incoming MCP requests.""" async def on_request(self, context: MiddlewareContext, call_next: CallNext): logger.info(f"Request: {context.method}") result = await call_next(context) logger.info(f"Response: {context.method} completed") return result def setup_middleware(mcp): mcp.add_middleware(RequestLoggingMiddleware()) ``` -------------------------------- ### Install MCP ClickHouse with Pip Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/README.md Install the mcp-clickhouse package using pip. For chDB support, install with the optional dependency. Use --upgrade to get the latest version. ```bash python3 -m pip install mcp-clickhouse ``` ```bash python3 -m pip install 'mcp-clickhouse[chdb]' ``` ```bash python3 -m pip install --upgrade mcp-clickhouse ``` -------------------------------- ### chdb_initial_prompt Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/_autodocs/api-reference-public-functions.md Retrieves the chDB usage guide and documentation, formatted as markdown, including a reference to supported table functions. ```APIDOC ## chdb_initial_prompt ### Description Retrieves the chDB usage guide and documentation, formatted as markdown, including a reference to supported table functions. ### Signature ```python def chdb_initial_prompt() -> str ``` ### Parameters None ### Returns - `str`: Markdown-formatted guide with table functions reference ### Examples ```python from mcp_clickhouse import chdb_initial_prompt help_text = chdb_initial_prompt() print(help_text) ``` ``` -------------------------------- ### Minimal ClickHouse Connection Setup Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/_autodocs/README.md Configure the essential environment variables for connecting to a local ClickHouse instance. ```bash CLICKHOUSE_HOST=localhost CLICKHOUSE_USER=default CLICKHOUSE_PASSWORD=clickhouse ``` -------------------------------- ### main() Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/_autodocs/api-reference-main.md Initializes and starts the MCP server with configured transport and middleware. This function is the primary entry point for the server and is typically invoked from the command line. ```APIDOC ## main() ### Description Initializes and starts the MCP server with configured transport and middleware. This function is the primary entry point for the server and is typically invoked from the command line. ### Method Python Function ### Parameters None (all configuration from environment variables) ### Behavior 1. Loads MCP server configuration via `get_mcp_config()` 2. Sets up any custom middleware via `setup_middleware(mcp)` 3. Determines transport type (stdio, http, or sse) 4. For HTTP/SSE: starts server with `host` and `port` parameters 5. For stdio: starts server without network binding ### Raises - `ValueError`: If authentication is misconfigured for HTTP/SSE transports - `ImportError`: If custom middleware module fails to import - Other exceptions propagated from FastMCP startup ### Example ```python # Run the server (typically called from CLI) from mcp_clickhouse.main import main main() ``` ### Environment Variables Used: - `CLICKHOUSE_MCP_SERVER_TRANSPORT` - Transport type (default: `stdio`) - `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`) - `MCP_MIDDLEWARE_MODULE` - Custom middleware module name (optional) - `CLICKHOUSE_MCP_AUTH_*` - Authentication settings (for HTTP/SSE) ### Example with Different Transports: ```python # stdio (default - Claude Desktop) # No environment setup needed # HTTP transport (development with MCP Inspector) import os os.environ['CLICKHOUSE_MCP_SERVER_TRANSPORT'] = 'http' os.environ['CLICKHOUSE_MCP_BIND_HOST'] = '127.0.0.1' os.environ['CLICKHOUSE_MCP_BIND_PORT'] = '8000' os.environ['CLICKHOUSE_MCP_AUTH_DISABLED'] = 'true' # SSE transport (production) os.environ['CLICKHOUSE_MCP_SERVER_TRANSPORT'] = 'sse' os.environ['CLICKHOUSE_MCP_BIND_HOST'] = '0.0.0.0' os.environ['CLICKHOUSE_MCP_AUTH_TOKEN'] = 'secure-token-here' main() ``` ``` -------------------------------- ### Error: Middleware Setup Function Failure Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/_autodocs/api-reference-middleware.md This error signifies a failure within the `setup_middleware` function itself. Review the middleware implementation for any errors or exceptions. ```text ERROR: Failed to load middleware: AttributeError: ... ``` -------------------------------- ### Setup Middleware Function Signature Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/_autodocs/api-reference-middleware.md This is the function signature for setting up middleware. It takes the FastMCP server instance as a parameter. ```python def setup_middleware(mcp) ``` -------------------------------- ### Start ClickHouse Services and Run Tests Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/README.md Commands to start ClickHouse services using Docker Compose and execute tests with pytest. Includes options for ClickHouse-only and chDB tests. ```bash docker compose up -d test_services # start ClickHouse uv run pytest -v tests uv run pytest -v tests/test_tool.py # ClickHouse only CHDB_ENABLED=true uv run --extra chdb pytest -v tests/test_chdb_tool.py # chDB only ``` -------------------------------- ### Fetch and Print Database Names Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/_autodocs/types.md Example of calling `list_databases` and printing the resulting list of database names. Ensure `mcp_clickhouse` is imported. ```python import json from mcp_clickhouse import list_databases databases = json.loads(list_databases()) print(databases) # ['default', 'system', 'my_db', ...] ``` -------------------------------- ### Configure chDB Data Path Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/_autodocs/tools.md Bash examples showing how to configure the `CHDB_DATA_PATH` environment variable for in-memory or persistent storage. ```bash # In-memory (default) CHDB_ENABLED=true CHDB_DATA_PATH=:memory: ``` ```bash # Persistent storage CHDB_ENABLED=true CHDB_DATA_PATH=/var/lib/chdb/data ``` -------------------------------- ### Setup Multiple Middleware in Order Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/_autodocs/api-reference-middleware.md Demonstrates how to register multiple middleware components, such as LoggingMiddleware and ValidationMiddleware, in a specific order during MCP server initialization. This ensures proper request processing flow. ```python # my_middleware.py import logging from fastmcp.server.middleware import Middleware, MiddlewareContext, CallNext logger = logging.getLogger("mcp-custom") class LoggingMiddleware(Middleware): async def on_message(self, context: MiddlewareContext, call_next: CallNext): logger.info(f"Message: {context.method}") return await call_next(context) class ValidationMiddleware(Middleware): async def on_call_tool(self, context: MiddlewareContext, call_next: CallNext): tool_name = getattr(context.message, 'name', None) if not tool_name: raise ValueError("Tool name required") return await call_next(context) def setup_middleware(mcp): """Setup multiple middleware in order.""" mcp.add_middleware(LoggingMiddleware()) mcp.add_middleware(ValidationMiddleware()) logger.info("All middleware registered") ``` -------------------------------- ### ClickHouseConfig Usage Example Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/_autodocs/types.md Shows how to retrieve ClickHouse configuration and access connection details. Used to establish a connection or log connection parameters. ```python from mcp_clickhouse.mcp_env import get_config config = get_config() if config.enabled: client_cfg = config.get_client_config() print(f"Connection: {config.username}@{config.host}:{config.port}") ``` -------------------------------- ### chDB Output Example Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/_autodocs/tools.md This is an example of the JSON output format returned by chDB queries. ```json [ { "column1": "value1", "column2": "value2" }, { "column1": "value3", "column2": "value4" } ] ``` -------------------------------- ### chdb_initial_prompt Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/_autodocs/api-reference-mcp-server.md Retrieves the chDB usage guide and reference in markdown format. This function is intended for internal use to provide system prompts. ```APIDOC ## chdb_initial_prompt ### Description Returns the chDB usage guide and reference, formatted as markdown. ### Method Python Function ### Signature `def chdb_initial_prompt() -> str` ### Returns - `str`: Markdown-formatted chDB system prompt with table functions reference ``` -------------------------------- ### Error Response: Database Not Found Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/_autodocs/tools.md An example of an error message returned when the specified database does not exist. ```text Query execution failed: Unknown database: nonexistent ``` -------------------------------- ### Load Middleware from Installed Package Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/_autodocs/api-reference-middleware.md Specifies the middleware module to be loaded from an installed Python package. The package must be installed via pip or a similar tool. ```bash # Installed package pip install my-mcp-middleware MCP_MIDDLEWARE_MODULE=my_mcp_middleware python -m mcp_clickhouse.main ``` -------------------------------- ### Example JSON Output for list_tables Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/_autodocs/tools.md This is an example of the JSON output structure returned by the list_tables tool, showing table metadata and pagination information. ```json { "tables": [ { "database": "default", "name": "users", "engine": "MergeTree", "create_table_query": "CREATE TABLE users (id UInt32, name String) ENGINE = MergeTree() ORDER BY id", "dependencies_database": "", "dependencies_table": "", "engine_full": "MergeTree() ORDER BY id", "sorting_key": "id", "primary_key": "id", "total_rows": 10000, "total_bytes": 51200, "total_bytes_uncompressed": 102400, "parts": 2, "active_parts": 2, "total_marks": 10, "comment": "User accounts", "columns": [ { "database": "default", "table": "users", "name": "id", "column_type": "UInt32", "default_kind": null, "default_expression": null, "comment": "User ID" }, { "database": "default", "table": "users", "name": "name", "column_type": "String", "default_kind": "DEFAULT", "default_expression": "''", "comment": null } ] } ], "next_page_token": "550e8400-e29b-41d4-a716-446655440000", "total_tables": 45 } ``` -------------------------------- ### Run MCP ClickHouse with Middleware Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/_autodocs/index.md Start the MCP ClickHouse server with custom middleware enabled by setting the MCP_MIDDLEWARE_MODULE environment variable. ```bash MCP_MIDDLEWARE_MODULE=my_middleware python -m mcp_clickhouse.main ``` -------------------------------- ### Configure MCP ClickHouse Using Installed Script Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/README.md Configure MCP ClickHouse to run directly using the installed 'mcp-clickhouse' command. Ensure the command is in your system's PATH. Set necessary ClickHouse connection environment variables. ```json { "mcpServers": { "mcp-clickhouse": { "command": "mcp-clickhouse", "env": { "CLICKHOUSE_HOST": "", "CLICKHOUSE_PORT": "", "CLICKHOUSE_USER": "", "CLICKHOUSE_PASSWORD": "", "CLICKHOUSE_SECURE": "true", "CLICKHOUSE_VERIFY": "true", "CLICKHOUSE_CONNECT_TIMEOUT": "30", "CLICKHOUSE_SEND_RECEIVE_TIMEOUT": "30" } } } } ``` -------------------------------- ### CLI Entry Point Registration Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/_autodocs/api-reference-main.md Register the main function as a CLI entry point in pyproject.toml. This allows the server to be started directly from the command line. ```toml [project.scripts] mcp-clickhouse = "mcp_clickhouse.main:main" ``` -------------------------------- ### Implement Logging Middleware Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/_autodocs/index.md Create a custom middleware class that logs tool calls. Add this middleware to the MCP server during setup. ```python # my_middleware.py from fastmcp.server.middleware import Middleware, MiddlewareContext, CallNext import logging logger = logging.getLogger("my-middleware") class LoggingMiddleware(Middleware): async def on_call_tool(self, context: MiddlewareContext, call_next: CallNext): logger.info(f"Tool: {context.message.name}") return await call_next(context) def setup_middleware(mcp): mcp.add_middleware(LoggingMiddleware()) ``` -------------------------------- ### Get MCP Server Configuration Instance Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/_autodocs/api-reference-env.md Retrieves the singleton MCPServerConfig instance. It is instantiated upon its first call. ```python from mcp_clickhouse.mcp_env import get_mcp_config config = get_mcp_config() print(f"Transport: {config.server_transport}") print(f"Bind: {config.bind_host}:{config.bind_port}") ``` -------------------------------- ### Running mcp-clickhouse with Example Middleware Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/_autodocs/api-reference-middleware.md Execute the mcp-clickhouse main module using environment variables to specify the middleware module and transport protocol. Ensure the middleware is accessible via the Python path. ```bash # Use the example MCP_MIDDLEWARE_MODULE=example_middleware \ CLICKHOUSE_MCP_SERVER_TRANSPORT=http \ python -m mcp_clickhouse.main ``` -------------------------------- ### Custom Middleware Module Structure Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/_autodocs/api-reference-middleware.md This example shows the basic structure of a custom middleware module, including defining a middleware class that extends `Middleware` and a `setup_middleware` function to register it. ```python # my_middleware.py from fastmcp.server.middleware import Middleware, MiddlewareContext, CallNext import logging logger = logging.getLogger("my-middleware") class MyMiddleware(Middleware): async def on_call_tool(self, context: MiddlewareContext, call_next: CallNext): tool_name = getattr(context.message, 'name', 'unknown') logger.info(f"Tool called: {tool_name}") return await call_next(context) def setup_middleware(mcp): """Called by the MCP server to register middleware.""" mcp.add_middleware(MyMiddleware()) logger.info("MyMiddleware registered") ``` -------------------------------- ### Enable chDB Engine Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/_autodocs/configuration.md Set `CHDB_ENABLED` to `true` to enable the chDB engine. This requires the optional `chdb` dependency to be installed. ```bash CHDB_ENABLED=true ``` -------------------------------- ### Execute and Parse Query Results Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/_autodocs/types.md Example of calling `run_query` and parsing the JSON response to access columns and rows. Ensure the `mcp_clickhouse` library is imported. ```python import json from mcp_clickhouse import run_query result = json.loads(run_query("SELECT id, name FROM users LIMIT 2")) print(result['columns']) # ['id', 'name'] print(result['rows']) # [[1, 'Alice'], [2, 'Bob']] ``` -------------------------------- ### Dynamic Configuration Middleware Example Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/_autodocs/api-reference-middleware.md This Python middleware overrides ClickHouse client settings per request, demonstrated by increasing timeouts for the 'run_query' tool. Ensure necessary imports are included. ```python # dynamic_config_middleware.py from fastmcp.server.dependencies import get_context from mcp_clickhouse.mcp_server import CLIENT_CONFIG_OVERRIDES_KEY from fastmcp.server.middleware import Middleware, MiddlewareContext, CallNext import logging logger = logging.getLogger("dynamic-config") class DynamicConfigMiddleware(Middleware): """Override ClickHouse connection settings per request.""" async def on_call_tool(self, context: MiddlewareContext, call_next: CallNext): # Example: Increase timeout for specific tools tool_name = getattr(context.message, 'name', None) if tool_name == "run_query": ctx = get_context() ctx.set_state(CLIENT_CONFIG_OVERRIDES_KEY, { "connect_timeout": 60, "send_receive_timeout": 300 # 5 minutes for heavy queries }) logger.info("Applied increased timeout for run_query") return await call_next(context) def setup_middleware(mcp): mcp.add_middleware(DynamicConfigMiddleware()) ``` -------------------------------- ### MCP ClickHouse Server Initialization Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/_autodocs/api-reference-main.md This function initializes and starts the MCP server. It loads configuration, sets up middleware, and determines the transport type. Use this function when running the server, typically invoked from the command line. ```python def main() ``` ```python # Run the server (typically called from CLI) from mcp_clickhouse.main import main main() ``` -------------------------------- ### Custom Middleware Implementation Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/_autodocs/api-reference-main.md Example of a custom middleware 'LoggingMiddleware' that logs when a tool is called. It demonstrates how to extend the Middleware class and add it to the mcp server instance. ```python import logging from fastmcp.server.middleware import Middleware, MiddlewareContext, CallNext logger = logging.getLogger("my-middleware") class LoggingMiddleware(Middleware): async def on_call_tool(self, context: MiddlewareContext, call_next: CallNext): tool_name = context.message.name if hasattr(context.message, 'name') else 'unknown' logger.info(f"Tool called: {tool_name}") return await call_next(context) def setup_middleware(mcp): mcp.add_middleware(LoggingMiddleware()) logger.info("Middleware setup complete") ``` -------------------------------- ### Create chDB Client Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/_autodocs/api-reference-public-functions.md Creates and returns a chDB client connection. Requires the 'chdb' extra to be installed. It returns a cached global instance and registers a cleanup hook. ```python from mcp_clickhouse import create_chdb_client client = create_chdb_client() ``` ```python import os import json # Enable chDB os.environ['CHDB_ENABLED'] = 'true' from mcp_clickhouse import create_chdb_client try: client = create_chdb_client() result = client.query("SELECT 1", "JSON") print(result.data()) except RuntimeError as e: print(f"chDB not available: {e}") # Check if chDB is available before using from mcp_clickhouse.mcp_env import get_chdb_config if get_chdb_config().enabled: client = create_chdb_client() else: print("chDB is disabled") ``` -------------------------------- ### Define Custom Middleware for MCP Server Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/README.md Create a Python module with middleware classes inheriting from 'Middleware' and a 'setup_middleware' function to register them. This example demonstrates logging tool calls. ```python # my_middleware.py import logging from fastmcp.server.middleware import Middleware, MiddlewareContext, CallNext logger = logging.getLogger("my-middleware") class LoggingMiddleware(Middleware): """Log all tool calls.""" async def on_call_tool(self, context: MiddlewareContext, call_next: CallNext): tool_name = context.message.name if hasattr(context.message, 'name') else 'unknown' logger.info(f"Calling tool: {tool_name}") result = await call_next(context) logger.info(f"Tool {tool_name} completed") return result def setup_middleware(mcp): """Register middleware with the MCP server.""" mcp.add_middleware(LoggingMiddleware()) ``` -------------------------------- ### Claude Desktop Configuration (stdio transport) Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/_autodocs/api-reference-main.md Configuration for Claude Desktop to use mcp-clickhouse with stdio transport. Claude Desktop automatically invokes main() with this setup. ```json { "mcpServers": { "mcp-clickhouse": { "command": "python3", "args": ["-m", "mcp_clickhouse.main"], "env": { "CLICKHOUSE_HOST": "localhost", "CLICKHOUSE_USER": "default", "CLICKHOUSE_PASSWORD": "password" } } } } ``` -------------------------------- ### Create chDB Client Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/_autodocs/api-reference-mcp-server.md Creates and returns a chDB client connection. Requires the 'chdb' extra to be installed and CHDB_ENABLED=true environment variable to be set. Returns a cached global instance and registers a cleanup hook. ```python import os os.environ['CHDB_ENABLED'] = 'true' from mcp_clickhouse import create_chdb_client client = create_chdb_client() result = client.query("SELECT 1", "JSON") print(result.data()) ``` -------------------------------- ### ClickHouse Connection Error Example Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/_autodocs/api-reference-main.md This error occurs if ClickHouse is enabled but unreachable. Verify that ClickHouse is running and the connection parameters are correct. ```text Error establishing ClickHouse connection: ... ``` -------------------------------- ### Warning: Missing setup_middleware Function Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/_autodocs/api-reference-middleware.md This warning indicates that the loaded middleware module does not contain the required `setup_middleware` function. Add this function to your module to properly initialize the middleware. ```text WARNING: Middleware module 'my_middleware' does not have a 'setup_middleware' function ``` -------------------------------- ### create_chdb_client Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/_autodocs/api-reference-public-functions.md Creates and returns a chDB client connection. It returns a cached global instance and requires the 'chdb' extra to be installed. Cleanup hooks are registered to close the session on exit. ```APIDOC ## create_chdb_client ### Description Creates and returns a chDB client connection. It returns a cached global instance and requires the 'chdb' extra to be installed. Cleanup hooks are registered to close the session on exit. ### Signature ```python def create_chdb_client() -> chdb.session.Session ``` ### Parameters None ### Returns - `chdb.session.Session`: Connected session instance ### Raises - `ValueError`: chDB not enabled - `RuntimeError`: chDB initialization failed or module not installed ### Behavior - Returns cached global instance created at module load - Requires `chdb` extra: `pip install 'mcp-clickhouse[chdb]'` - Registers cleanup hook to close on exit - Raises error if chDB is disabled or unavailable ### Configuration - Loaded from environment variables via `get_chdb_config()` - Data path: `CHDB_DATA_PATH` (default: `:memory:`) ### Examples ```python import os # Enable chDB os.environ['CHDB_ENABLED'] = 'true' from mcp_clickhouse import create_chdb_client try: client = create_chdb_client() result = client.query("SELECT 1", "JSON") print(result.data()) except RuntimeError as e: print(f"chDB not available: {e}") # Check if chDB is available before using from mcp_clickhouse.mcp_env import get_chdb_config if get_chdb_config().enabled: client = create_chdb_client() else: print("chDB is disabled") ``` ``` -------------------------------- ### Get chDB Enabled Status Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/_autodocs/api-reference-env.md Check if chDB is enabled. The default value is false. Requires optional dependency 'pip install "mcp-clickhouse[chdb]"'. ```python @property def enabled(self) -> bool: ``` -------------------------------- ### create_chdb_client Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/_autodocs/api-reference-mcp-server.md Creates and returns a chDB client connection. It requires the 'chdb' extra to be installed and ensures a cached global instance is used, registering a cleanup hook for session closure. ```APIDOC ## create_chdb_client ### Description Create and return a chDB client connection. ### Method ```python def create_chdb_client() ``` ### Parameters None ### Returns - `chdb.session.Session`: Connected chDB session instance ### Raises - `ValueError`: If chDB is not enabled (`CHDB_ENABLED=true` not set) - `RuntimeError`: If chDB initialization failed or module not installed ### Behavior - Requires `chdb` extra installed: `pip install 'mcp-clickhouse[chdb]'` - Returns cached global instance created at module load time. - Registers cleanup hook to close session on exit. ### Example ```python import os os.environ['CHDB_ENABLED'] = 'true' from mcp_clickhouse import create_chdb_client client = create_chdb_client() result = client.query("SELECT 1", "JSON") print(result.data()) ``` ``` -------------------------------- ### Get Paginated Table Data Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/_autodocs/api-reference-public-functions.md Fetches detailed metadata for a specific page of tables. It requires a client, database, list of table names, start index, and page size. Optionally includes detailed column metadata. ```python from mcp_clickhouse import ( create_clickhouse_client, fetch_table_names_from_system, get_paginated_table_data, ) client = create_clickhouse_client() # Get all table names all_names = fetch_table_names_from_system(client, 'default') # Paginate page_size = 10 tables, end_idx, has_more = get_paginated_table_data( client, 'default', all_names, 0, page_size ) print(f"Got {len(tables)} tables, has_more={has_more}") # Get next page if has_more: next_tables, next_end, still_more = get_paginated_table_data( client, 'default', all_names, end_idx, page_size ) ``` -------------------------------- ### Health Check Example Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/_autodocs/api-reference-mcp-server.md Example of how to call the health check endpoint using curl. ```bash curl http://localhost:8000/health # Response: OK ``` -------------------------------- ### Initialize MCPServerConfig Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/_autodocs/api-reference-env.md Creates a new instance of MCPServerConfig with default values. ```python config = MCPServerConfig() ``` -------------------------------- ### chDB Error Response Example Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/_autodocs/tools.md Example JSON error responses from chDB queries, including general failures and timeouts. ```json { "status": "error", "message": "chDB query failed: Error message details" } ``` ```json { "status": "error", "message": "chDB query timed out after 30 seconds" } ``` -------------------------------- ### Required Environment Variables for mcp-clickhouse Setup Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/_autodocs/00-START-HERE.md These environment variables are necessary for any mcp-clickhouse setup to connect to the ClickHouse database. Ensure these are set before running the application. ```bash CLICKHOUSE_HOST=... CLICKHOUSE_USER=... CLICKHOUSE_PASSWORD=... ``` -------------------------------- ### Set Connection Timeout Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/_autodocs/configuration.md Configure the connection establishment timeout in seconds. The default is 30 seconds. ```bash CLICKHOUSE_CONNECT_TIMEOUT=60 # 60 second timeout ``` -------------------------------- ### setup_middleware(mcp) Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/_autodocs/api-reference-middleware.md Loads and registers custom middleware from a user-provided Python module. It checks the MCP_MIDDLEWARE_MODULE environment variable, dynamically imports the specified module, and calls its setup_middleware function if it exists. This function is crucial for injecting custom logic into the MCP server's request handling pipeline. ```APIDOC ## setup_middleware(mcp) ### Description Loads and registers custom middleware from a user-provided Python module. It checks the `MCP_MIDDLEWARE_MODULE` environment variable, dynamically imports the specified module, and calls its `setup_middleware` function if it exists. This function is crucial for injecting custom logic into the MCP server's request handling pipeline. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Method None (Python function) ### Endpoint None (Python function) ### Environment Variable - **MCP_MIDDLEWARE_MODULE** (string) - Optional - Python module name (without `.py` extension). If not set, no middleware is loaded. ### Raises - `ImportError`: If the module name specified in `MCP_MIDDLEWARE_MODULE` is invalid or cannot be imported. - `Exception`: If the `setup_middleware` function within the custom module fails during execution. ### Request Example ```python from mcp_clickhouse.mcp_middleware_hook import setup_middleware from mcp_clickhouse.mcp_server import mcp # Load middleware from environment setup_middleware(mcp) ``` ### Response None (This function modifies the MCP server instance in place and does not return a value.) ### Success Response (200) None ### Response Example None ``` -------------------------------- ### ClickHouseConfig.connect_timeout Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/_autodocs/api-reference-env.md Gets the connection establishment timeout in seconds. This is controlled by the CLICKHOUSE_CONNECT_TIMEOUT environment variable. ```APIDOC ## ClickHouseConfig.connect_timeout ### Description Connection establishment timeout in seconds. ### Property `connect_timeout` (int) ### Environment Variable `CLICKHOUSE_CONNECT_TIMEOUT` (Default: 30) ``` -------------------------------- ### Conditional Client Creation Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/_autodocs/api-reference-env.md Demonstrates how to conditionally create ClickHouse and chDB clients based on their respective configuration settings being enabled. ```python from mcp_clickhouse.mcp_env import get_config, get_chdb_config import clickhouse_connect import chdb.session as chs clickhouse_cfg = get_config() chdb_cfg = get_chdb_config() # ClickHouse client if clickhouse_cfg.enabled: ch_client = clickhouse_connect.get_client(**clickhouse_cfg.get_client_config()) # chDB client if chdb_cfg.enabled: chdb_client = chs.Session(**chdb_cfg.get_client_config()) ``` -------------------------------- ### GET /health Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/_autodocs/README.md Liveness probe endpoint to check the operational status of the MCP ClickHouse service. ```APIDOC ## GET /health ### Description Liveness probe endpoint to check the operational status of the MCP ClickHouse service. ### Method GET ### Endpoint /health ### Parameters None. ### Request Example None provided. ### Response #### Success Response (200) Details of the response are not specified in the source. ``` -------------------------------- ### Get ClickHouse Configuration Instance Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/_autodocs/api-reference-env.md Retrieves the singleton ClickHouseConfig instance. It is instantiated upon its first call. ```python from mcp_clickhouse.mcp_env import get_config config = get_config() print(f"Host: {config.host}") print(f"Port: {config.port}") ``` -------------------------------- ### Create and Use ClickHouse Client Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/_autodocs/index.md Instantiate a ClickHouse client, execute a query, and ensure the client is closed properly using a try-finally block. ```python from mcp_clickhouse import create_clickhouse_client client = create_clickhouse_client() try: result = client.query("SELECT 1") print(result.first_item) finally: client.close() ``` -------------------------------- ### List and Display Table Information Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/_autodocs/types.md Demonstrates calling `list_tables` and printing the number of tables per page, the total count, and the next page token if available. Requires `mcp_clickhouse` import. ```python import json from mcp_clickhouse import list_tables result = json.loads(list_tables('default', page_size=10)) print(f"Page has {len(result['tables'])} tables") print(f"Total: {result['total_tables']} tables") if result['next_page_token']: print(f"Next token: {result['next_page_token']}") ``` -------------------------------- ### Get Connection Timeout Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/_autodocs/api-reference-env.md Retrieve the timeout in seconds for establishing a connection to ClickHouse. The default value is 30 seconds. ```python @property def connect_timeout(self) -> int: ``` -------------------------------- ### chDB Initial Prompt Function Signature Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/_autodocs/api-reference-mcp-server.md Defines the function signature for retrieving the chDB usage guide and reference. ```python def chdb_initial_prompt() -> str ``` -------------------------------- ### ChDBConfig.enabled Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/_autodocs/api-reference-env.md Checks if chDB is enabled. This setting is controlled by the CHDB_ENABLED environment variable and requires the optional 'mcp-clickhouse[chdb]' installation. ```APIDOC ## ChDBConfig.enabled ### Description Whether chDB is enabled. ### Property `enabled` (bool) ### Environment Variable `CHDB_ENABLED` (Default: false) ### Values `true` or `false` ### Requires Optional dependency `pip install 'mcp-clickhouse[chdb]'` ``` -------------------------------- ### Generate ClickHouse Client Configuration Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/_autodocs/api-reference-env.md Generate a configuration dictionary suitable for initializing a clickhouse_connect client. This includes connection details, timeouts, and proxy settings. ```python from mcp_clickhouse.mcp_env import ClickHouseConfig import clickhouse_connect config = ClickHouseConfig() client_config = config.get_client_config() client = clickhouse_connect.get_client(**client_config) ``` -------------------------------- ### ClickHouseConfig.proxy_path Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/_autodocs/api-reference-env.md Gets the path that is appended to the server URL for HTTP proxy connections. This is set using the CLICKHOUSE_PROXY_PATH environment variable. ```APIDOC ## ClickHouseConfig.proxy_path ### Description Path appended to server URL for HTTP proxy connections. ### Property `proxy_path` (str) ### Environment Variable `CLICKHOUSE_PROXY_PATH` (Default: None) ``` -------------------------------- ### Development with Middleware Enabled Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/_autodocs/configuration.md Configuration for development, enabling HTTP transport, disabling authentication, and loading a custom middleware module. ```bash CLICKHOUSE_HOST=localhost CLICKHOUSE_USER=default CLICKHOUSE_PASSWORD=clickhouse CLICKHOUSE_MCP_SERVER_TRANSPORT=http CLICKHOUSE_MCP_AUTH_DISABLED=true MCP_MIDDLEWARE_MODULE=example_middleware ``` -------------------------------- ### Validate Transport Type Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/_autodocs/api-reference-env.md Example of how to use the TransportType.values() method to validate a given transport string. Raises a ValueError if the transport is not supported. ```python from mcp_clickhouse.mcp_env import TransportType valid = TransportType.values() # ["stdio", "http", "sse"] transport = "http" if transport not in valid: raise ValueError(f"Invalid transport: {transport}") ``` -------------------------------- ### Configure and Run mcp-clickhouse Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/_autodocs/index.md Set environment variables for ClickHouse connection details and run the mcp_clickhouse CLI. ```bash export CLICKHOUSE_HOST=localhost export CLICKHOUSE_USER=default export CLICKHOUSE_PASSWORD=clickhouse python -m mcp_clickhouse.main ``` -------------------------------- ### List ClickHouse Databases Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/_autodocs/api-reference-mcp-server.md Retrieves a JSON-encoded list of all available database names from ClickHouse. Use this to get an overview of the ClickHouse schema. ```python from mcp_clickhouse import list_databases import json result_json = list_databases() databases = json.loads(result_json) print(databases) # ['default', 'system', 'my_database', ...] ``` -------------------------------- ### Create ClickHouse Client Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/_autodocs/api-reference-public-functions.md Creates and returns a ClickHouse client connection. Configuration is loaded from environment variables and can be overridden. The connection is verified by fetching the server version. ```python from mcp_clickhouse import create_clickhouse_client client = create_clickhouse_client() ``` ```python from mcp_clickhouse import create_clickhouse_client # Basic usage client = create_clickhouse_client() result = client.query("SELECT version()") version = result.first_item print(f"Server version: {version}") ``` ```python from mcp_clickhouse import create_clickhouse_client # Execute multiple queries client = create_clickhouse_client() try: r1 = client.query("SELECT COUNT(*) FROM system.tables") r2 = client.query("SELECT COUNT(*) FROM system.columns") print(f"Tables: {r1.first_item}, Columns: {r2.first_item}") finally: client.close() ``` ```python import os try: client = create_clickhouse_client() except ValueError as e: print(f"Configuration error: {e}") except Exception as e: print(f"Connection failed: {e}") ``` ```python from mcp_clickhouse import create_clickhouse_client # Query with settings client = create_clickhouse_client() result = client.query( "SELECT * FROM table", settings={'max_rows_to_read': 1000000} ) ``` -------------------------------- ### Get Proxy Path Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/_autodocs/api-reference-env.md Retrieve the path appended to the server URL for HTTP proxy connections. This is used when connecting through an HTTP proxy. ```python @property def proxy_path(self) -> str: ``` -------------------------------- ### ClickHouse SQL Playground Configuration Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/_autodocs/configuration.md Configuration for connecting to the ClickHouse SQL Playground. ```bash CLICKHOUSE_HOST=sql-clickhouse.clickhouse.com CLICKHOUSE_USER=demo CLICKHOUSE_PASSWORD= CLICKHOUSE_SECURE=true ``` -------------------------------- ### Get Send/Receive Timeout Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/_autodocs/api-reference-env.md Retrieve the timeout in seconds for sending and receiving query data with ClickHouse. The default value is 300 seconds. ```python @property def send_receive_timeout(self) -> int: ``` -------------------------------- ### TransportType Enum Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/_autodocs/api-reference-env.md Enum of supported MCP server transport types. Use `TransportType.values()` to get all valid transport values as strings. ```APIDOC ## Enum TransportType ### Description Enum of supported MCP server transport types. ### Values | Value | Description | |-------|-------------| | `stdio` | Standard input/output (Claude Desktop native) | | `http` | HTTP long-polling | | `sse` | Server-Sent Events | ### Methods #### values() Get all valid transport values as strings. **Returns:** `list[str]` **Example:** ```python from mcp_clickhouse.mcp_env import TransportType valid = TransportType.values() # ["stdio", "http", "sse"] transport = "http" if transport not in valid: raise ValueError(f"Invalid transport: {transport}") ``` ``` -------------------------------- ### Import Configuration Access Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/_autodocs/index.md Import configuration access functions and classes from mcp_clickhouse.mcp_env. ```python from mcp_clickhouse.mcp_env import ( get_config, # ClickHouseConfig singleton get_chdb_config, # ChDBConfig singleton get_mcp_config, # MCPServerConfig singleton ClickHouseConfig, ChDBConfig, MCPServerConfig, TransportType, ) ``` -------------------------------- ### Module Imports Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/_autodocs/api-reference-main.md Imports for the main module, including the FastMCP server, configuration loading, and middleware setup. All imports are completed before main() is called. ```python from .mcp_server import mcp # FastMCP server singleton from .mcp_env import get_mcp_config, TransportType # Config loading from .mcp_middleware_hook import setup_middleware # Middleware injection ``` -------------------------------- ### List Databases with list_databases Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/_autodocs/tools.md Use the `list_databases` tool to retrieve a list of all available databases on the ClickHouse cluster. The result is a JSON array of database names. ```python # List all databases result = list_databases() databases = json.loads(result) print(databases) # ['default', 'system', 'my_database'] ``` ```python # Check if database exists if 'analytics' in databases: print("Analytics database found") ``` -------------------------------- ### Get All Transport Values Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/_autodocs/api-reference-env.md Retrieves a list of all valid transport type strings. Use this to validate user-provided transport values against the supported options. ```python @classmethod def values(cls) -> list[str]: return [t.value for t in cls] ``` -------------------------------- ### MCP ClickHouse Server with Different Transports Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/_autodocs/api-reference-main.md Demonstrates how to configure and run the MCP ClickHouse server using different transport mechanisms by setting environment variables. This includes stdio (default), http for development with MCP Inspector, and sse for production environments. ```python # stdio (default - Claude Desktop) # No environment setup needed # HTTP transport (development with MCP Inspector) import os os.environ['CLICKHOUSE_MCP_SERVER_TRANSPORT'] = 'http' os.environ['CLICKHOUSE_MCP_BIND_HOST'] = '127.0.0.1' os.environ['CLICKHOUSE_MCP_BIND_PORT'] = '8000' os.environ['CLICKHOUSE_MCP_AUTH_DISABLED'] = 'true' # SSE transport (production) os.environ['CLICKHOUSE_MCP_SERVER_TRANSPORT'] = 'sse' os.environ['CLICKHOUSE_MCP_BIND_HOST'] = '0.0.0.0' os.environ['CLICKHOUSE_MCP_AUTH_TOKEN'] = 'secure-token-here' main() ``` -------------------------------- ### ChDBConfig.get_client_config() Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/_autodocs/api-reference-env.md Generates a configuration dictionary for initializing a chDB client, primarily using the data_path setting. ```APIDOC ## ChDBConfig.get_client_config() ### Description Generate configuration dictionary for chDB client. ### Returns `dict` with key: - `data_path`: Path from `self.data_path` ### Example ```python from mcp_clickhouse.mcp_env import ChDBConfig import chdb.session as chs config = ChDBConfig() client_config = config.get_client_config() client = chs.Session(**client_config) ``` ``` -------------------------------- ### Public Python API Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/_autodocs/README.md This section details the function-by-function reference for the public Python API, including import locations, usage examples, and error handling. ```APIDOC ## Public API (`mcp_clickhouse`) ### Description Detailed function-by-function reference for the public Python API, covering import locations, usage examples, and error handling. ### Core Functions #### `run_query(query: str) -> str` - **Description**: Executes a SQL query against ClickHouse and returns the result as a string. - **Usage**: Import `run_query` and pass your SQL query. - **Example**: `run_query('SELECT count() FROM my_table')` #### `list_databases() -> str` - **Description**: Returns a string representation of all available ClickHouse databases. - **Usage**: Import `list_databases` and call it without arguments. - **Example**: `list_databases()` #### `list_tables(...)` - **Description**: Returns metadata for tables, supporting various parameter combinations for filtering and pagination. - **Usage**: Import `list_tables` and call with desired parameters. #### `create_clickhouse_client()` - **Description**: Creates and returns a ClickHouse client instance. - **Usage**: Import `create_clickhouse_client` to establish a connection. - **Example**: `client = create_clickhouse_client()` #### `create_chdb_client()` - **Description**: Creates and returns a chDB client instance. - **Usage**: Import `create_chdb_client` to establish a connection. - **Example**: `chdb_client = create_chdb_client()` #### `run_chdb_select_query(query: str) -> str` - **Description**: Executes a SELECT query against chDB and returns the result as a string. - **Usage**: Import `run_chdb_select_query` and pass your chDB query. - **Example**: `run_chdb_select_query('SELECT * FROM my_chdb_table')` ### Error Handling - **Description**: Comprehensive examples of error handling for all public API functions are provided, demonstrating how to manage potential issues during execution. ``` -------------------------------- ### Middleware Import Error Example Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/_autodocs/api-reference-main.md This error occurs if a custom middleware module cannot be imported. Verify the module name is correct and the module is in the Python path. ```text ImportError: Failed to import middleware module 'my_middleware': ... ``` -------------------------------- ### Authentication Error Example Source: https://github.com/clickhouse/mcp-clickhouse/blob/main/_autodocs/api-reference-main.md This error occurs if HTTP/SSE transport is configured without valid authentication. Set exactly one authentication option for HTTP/SSE. ```text ValueError: Authentication is required for HTTP/SSE transports. Configure exactly one of: - CLICKHOUSE_MCP_AUTH_TOKEN= (static bearer token) - FASTMCP_SERVER_AUTH= (FastMCP auth provider) - CLICKHOUSE_MCP_AUTH_DISABLED=true (development only) ```