Skip to main content
Glama
cgrdavies

mcp-clickhouse-long-running

by cgrdavies

run_select_query

Execute SELECT queries in a ClickHouse database to retrieve specific data, leveraging the mcp-clickhouse-long-running server for optimized query performance.

Instructions

Run a SELECT query in a ClickHouse database

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYes

Implementation Reference

  • The primary handler function for the 'run_select_query' MCP tool. It manages query execution asynchronously with timeout handling, error catching, and structured responses.
    @mcp.tool()
    def run_select_query(query: str):
        """Run a SELECT query in a ClickHouse database"""
        logger.info(f"Executing SELECT query: {query}")
        try:
            future = QUERY_EXECUTOR.submit(execute_query, query)
            try:
                result = future.result(timeout=SELECT_QUERY_TIMEOUT_SECS)
                # Check if we received an error structure from execute_query
                if isinstance(result, dict) and "error" in result:
                    logger.warning(f"Query failed: {result['error']}")
                    # MCP requires structured responses; string error messages can cause
                    # serialization issues leading to BrokenResourceError
                    return {
                        "status": "error",
                        "message": f"Query failed: {result['error']}",
                    }
                return result
            except concurrent.futures.TimeoutError:
                logger.warning(
                    f"Query timed out after {SELECT_QUERY_TIMEOUT_SECS} seconds: {query}"
                )
                future.cancel()
                # Return a properly structured response for timeout errors
                return {
                    "status": "error",
                    "message": f"Query timed out after {SELECT_QUERY_TIMEOUT_SECS} seconds",
                }
        except Exception as e:
            logger.error(f"Unexpected error in run_select_query: {str(e)}")
            # Catch all other exceptions and return them in a structured format
            # to prevent MCP serialization failures
            return {"status": "error", "message": f"Unexpected error: {str(e)}"}
  • Supporting helper function that performs the actual ClickHouse query execution, processes results into a list of dictionaries, and returns structured errors if any occur.
    def execute_query(query: str):
        client = create_clickhouse_client()
        try:
            read_only = get_readonly_setting(client)
            res = client.query(query, settings={"readonly": read_only})
            column_names = res.column_names
            rows = []
            for row in res.result_rows:
                row_dict = {}
                for i, col_name in enumerate(column_names):
                    row_dict[col_name] = row[i]
                rows.append(row_dict)
            logger.info(f"Query returned {len(rows)} rows")
            return rows
        except Exception as err:
            logger.error(f"Error executing query: {err}")
            # Return a structured dictionary rather than a string to ensure proper serialization
            # by the MCP protocol. String responses for errors can cause BrokenResourceError.
            return {"error": str(err)}
  • Helper function to create and test a ClickHouse client connection using configuration from mcp_env.py, used by query execution.
    def create_clickhouse_client():
        client_config = get_config().get_client_config()
        logger.info(
            f"Creating ClickHouse client connection to {client_config['host']}:{client_config['port']} "
            f"as {client_config['username']} "
            f"(secure={client_config['secure']}, verify={client_config['verify']}, "
            f"connect_timeout={client_config['connect_timeout']}s, "
            f"send_receive_timeout={client_config['send_receive_timeout']}s)"
        )
    
        try:
            client = clickhouse_connect.get_client(**client_config)
            # Test the connection
            version = client.server_version
            logger.info(f"Successfully connected to ClickHouse server version {version}")
            return client
        except Exception as e:
            logger.error(f"Failed to connect to ClickHouse: {str(e)}")
            raise
  • Package __init__ exports the run_select_query tool function for import in tests and other modules.
    from .mcp_server import (
        create_clickhouse_client,
        list_databases,
        list_tables,
        run_select_query,
    )
    
    __all__ = [
        "list_databases",
        "list_tables",
        "run_select_query",
        "create_clickhouse_client",
    ]
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden of behavioral disclosure. It states the action but doesn't cover critical aspects like required permissions, potential impacts (e.g., read-only vs. mutations), rate limits, or response format. This is a significant gap for a database query tool.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, efficient sentence with zero waste, clearly front-loading the core purpose. It's appropriately sized for the tool's complexity, making it easy to parse.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's complexity (database querying), lack of annotations, no output schema, and 0% schema coverage, the description is incomplete. It doesn't address behavioral traits, parameter details, or return values, leaving critical gaps for effective agent use.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters2/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The schema description coverage is 0%, with one parameter 'query' undocumented in the schema. The description adds no details about parameter semantics, such as query syntax, supported SQL features, or constraints, failing to compensate for the coverage gap.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the action ('Run a SELECT query') and the target resource ('in a ClickHouse database'), which provides a specific verb+resource combination. However, it doesn't differentiate from sibling tools like 'list_databases' or 'list_tables' beyond the SELECT query specificity, keeping it from a perfect score.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives. It doesn't mention prerequisites, limitations, or comparisons to sibling tools, leaving the agent with no explicit usage context or exclusions.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Related Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/cgrdavies/mcp-clickhouse'

If you have feedback or need assistance with the MCP directory API, please join our Discord server