Skip to main content
Glama
burakdirin

clickhouse-mcp-server

execute_query

Execute SQL queries on ClickHouse databases securely through the MCP server, enabling efficient data retrieval and interaction with structured datasets.

Instructions

Execute ClickHouse queries

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYes

Implementation Reference

  • The primary handler function for the 'execute_query' tool. It retrieves a QueryExecutor from the context, executes the query (handling multiple statements), formats results as JSON, and handles errors.
    def execute_query(query: str, ctx: Context) -> str:
        """Execute ClickHouse queries"""
        try:
            executor = _get_executor(ctx)
            results = executor.execute_multiple_queries(query)
    
            if len(results) == 1:
                return json.dumps(results[0], indent=2)
            return json.dumps(results, indent=2)
        except (ConnectionError, QueryError) as e:
            return str(e)
  • The @mcp.tool() decorator registers the execute_query function as an MCP tool with the FastMCP server.
    @mcp.tool()
  • Helper function that extracts the ClickHouseContext from the MCP Context and returns a QueryExecutor instance.
    def _get_executor(ctx: Context) -> QueryExecutor:
        """Helper function to get QueryExecutor from context"""
        clickhouse_ctx = ctx.request_context.lifespan_context
        return QueryExecutor(clickhouse_ctx)
  • Key helper method in QueryExecutor that splits semicolon-separated queries, executes each via execute_single_query, and collects results or errors.
    def execute_multiple_queries(self, query: str) -> List[Dict[str, Any]]:
        """Execute multiple queries and return results"""
        queries = [q.strip() for q in query.split(';') if q.strip()]
        results = []
    
        for single_query in queries:
            try:
                result = self.execute_single_query(single_query)
                results.append(result)
            except QueryError as e:
                results.append({"error": str(e)})
    
        return results
  • Core helper method that executes a single ClickHouse query, handles USE statements, processes results into formatted dictionaries, and raises QueryError on failure.
    def execute_single_query(self, query: str) -> Dict[str, Any]:
        """Execute a single query and return results"""
        self.context.ensure_connected()
    
        try:
            # Handle USE statements
            if self._is_use_statement(query):
                db_name = query.strip().split()[-1].strip('`').strip()
                self.context.database = db_name
                self.context.client.execute(f'USE {db_name}')
                return {"message": f"Switched to database: {db_name}"}
    
            # Execute query
            result = self.context.client.execute(query, with_column_types=True)
    
            if not result:
                return {"affected_rows": 0}
    
            rows, columns = result
            if not rows:
                return {"affected_rows": 0}
    
            # Convert rows to dictionaries
            column_names = [col[0] for col in columns]
            results = []
            for row in rows:
                row_dict = dict(zip(column_names, row))
                results.append(self._process_row(row_dict))
    
            return results if len(results) > 0 else {"affected_rows": 0}
    
        except Exception as e:
            raise QueryError(f"Error executing query: {str(e)}")
Behavior1/5

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

No annotations are provided, so the description carries full burden for behavioral disclosure. It only states the action without any details on traits like permissions needed, whether it's read-only or destructive, rate limits, error handling, or output format. This is inadequate for a tool that likely interacts with a database and could have significant side effects.

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 extremely concise with just three words, making it front-loaded and free of unnecessary details. Every word ('Execute ClickHouse queries') directly contributes to stating the tool's function, though it lacks depth. This efficiency in length is appropriate for conciseness, even if it sacrifices completeness.

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

Completeness1/5

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

Given the complexity of database query execution, no annotations, no output schema, and low parameter coverage, the description is incomplete. It doesn't address key aspects like return values, error conditions, safety implications, or how it relates to the sibling tool. For a tool with potential high impact, this minimal description is insufficient for effective agent use.

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

Parameters1/5

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

The input schema has 1 parameter with 0% description coverage, and the tool description provides no additional information about the 'query' parameter. It doesn't explain what constitutes a valid ClickHouse query, syntax examples, or constraints. With low schema coverage, the description fails to compensate, leaving the parameter's meaning unclear.

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

Purpose3/5

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

The description 'Execute ClickHouse queries' clearly states the action (execute) and target (ClickHouse queries), which is better than a tautology. However, it doesn't differentiate from the sibling tool 'connect_database' or specify what type of queries (e.g., SELECT, INSERT, DDL). The purpose is understandable but lacks specificity about scope or resource differentiation.

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?

There is no guidance on when to use this tool versus the sibling 'connect_database' or other alternatives. The description implies usage for executing queries but doesn't mention prerequisites (e.g., requires an established connection), exclusions, or contextual cues. This leaves the agent with minimal direction on appropriate invocation scenarios.

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/burakdirin/clickhouse-mcp-server'

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