Skip to main content
Glama
burakdirin

clickhouse-mcp-server

execute_query

Execute SQL queries on ClickHouse databases. Run any valid ClickHouse query and retrieve results.

Instructions

Execute ClickHouse queries

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYes

Implementation Reference

  • The 'execute_query' tool handler function, registered via @mcp.tool() decorator. It calls executor.execute_multiple_queries() and returns results as JSON.
    @mcp.tool()
    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 'execute_query' as an MCP tool on the FastMCP server instance.
    @mcp.tool()
    def execute_query(query: str, ctx: Context) -> str:
  • QueryExecutor.execute_multiple_queries() - splits input by semicolons and executes each query via execute_single_query().
    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
  • QueryExecutor.execute_single_query() - executes a single ClickHouse query and processes results into dictionaries.
    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)}")
  • _get_executor(ctx) helper that retrieves the ClickHouseContext from the request context and creates a QueryExecutor.
    def _get_executor(ctx: Context) -> QueryExecutor:
        """Helper function to get QueryExecutor from context"""
        clickhouse_ctx = ctx.request_context.lifespan_context
        return QueryExecutor(clickhouse_ctx)
Behavior2/5

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

No annotations provided. The description does not disclose whether queries are read-only, safe, or have side effects. Important behavioral details like result handling or error behavior are missing.

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

Conciseness3/5

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

The description is a single sentence, which is concise but at the expense of necessary detail for a query execution tool. It is too minimal to be considered well-structured.

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?

With one parameter and no output schema, the description fails to explain what the tool returns or if it just executes. Lacks context about execution environment and limitations.

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?

Schema coverage is 0%, and the description adds no information about the 'query' parameter beyond its name. Does not specify expected format (e.g., SQL dialect) or constraints.

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 (Execute) and resource (ClickHouse queries). It distinguishes from the sibling tool connect_database, which implies connection setup vs query execution.

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?

No guidance on when to use this tool versus alternatives. Does not mention prerequisites like a prior connection or whether it is for read or write operations.

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

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