Skip to main content
Glama
dubin555

ClickHouse MCP Server

by dubin555

execute_sql

Execute SQL queries against ClickHouse databases to retrieve, analyze, or modify data through a secure interface.

Instructions

Execute a query against the ClickHouse database

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYesThe SQL query to be executed

Implementation Reference

  • The primary handler for the 'execute_sql' tool. Extracts the SQL query from arguments, performs a dangerous query check, executes the query using ClickHouseClient, formats the result as JSON, and returns it as TextContent or an error message.
    async def _handle_execute_sql(self, arguments: Dict[str, str]) -> List[TextContent]:
        """Handle execute_sql tool"""
        self.logger.debug("Handling execute_sql tool")
        # Get query
        query = arguments.get("query")
        if not query:
            self.logger.error("Query is required")
            return []
    
        # Check query
        is_dangerous, pattern = dangerous_check(query)
        if is_dangerous:
            self.logger.error(f"Dangerous query detected: {pattern}")
            return [TextContent(value=f"Error: Dangerous query detected: {pattern}")]
    
        try:
            # Execute query
            result = self.client.execute_query(query)
            json_result = json.dumps(result, default=str, indent=2)
            return [
                TextContent(
                    type='text',
                    text=json_result,
                    mimeType='application/json'
                )
            ]
        except Exception as e:
            self.logger.error(f"Failed to execute query: {e}")
            return [TextContent(type='text', text=f"Error executing query: {str(e)}")]
  • Defines the input schema for the 'execute_sql' tool in the list_tools method, specifying an object with a required 'query' string property.
        Tool(
            name="execute_sql",
            description="Execute a query against the ClickHouse database",
            inputSchema={
                "type": "object",
                "properties": {
                    "query": {
                        "type": "string",
                        "description": "The SQL query to be executed"
                    }
                },
                "required": ["query"],
            }
        )
    ]
  • Registers the '_handle_execute_sql' method as the handler for the 'execute_sql' tool within the call_tool method's tool_handlers dictionary.
    tool_handlers = {
        "execute_sql": self._handle_execute_sql
    }
  • Helper method in ClickHouseClient class that executes the SQL query on the ClickHouse database, converts results to list of dictionaries, and handles errors.
    def execute_query(self, query: str, readonly: bool = True):
        """Execute a query against the ClickHouse database"""
        try:
            client = self.get_client()
            settings = {"readonly": 1} if readonly else {}
            res = client.query(query, settings=settings)
    
            # convert result to list of dicts
            rows = []
            for row in res.result_rows:
                row_dict = {}
                for i, col_name in enumerate(res.column_names):
                    row_dict[col_name] = row[i]
                rows.append(row_dict)
                
            self.logger.debug(f"Query executed successfully: {query}")
            return rows
        except Exception as e:
            self.logger.error(f"Failed to execute query: {e}")
            raise
  • Utility function that checks the SQL query for dangerous keywords like INSERT, UPDATE, etc., to prevent potential SQL injection or destructive operations.
    def dangerous_check(query: str) -> tuple[bool, str]:
        """
        Perform a security check on the query to prevent SQL injection attacks.
        This function checks for the presence of potentially dangerous keywords and patterns 
        that could be used to inject malicious code.
    
        Args:
            query (str): The SQL query to be checked.
        Returns:
            tuple[bool, str]: A tuple containing a boolean indicating whether the query is dangerous
                              and a string with the detected dangerous pattern, if any.
        """
    
        # List of dangerous keywords and patterns
        dangerous_keywords = [
            "insert", "update", "delete", "drop", "truncate", "alter" 
        ]
    
        # Check for dangerous keywords
        for keyword in dangerous_keywords:
            if re.search(rf"\b{re.escape(keyword)}\b", query, re.IGNORECASE):
                logger.warning(f"Dangerous keyword '{keyword}' detected in query: {query}")
                return True, f"Query contains dangerous keyword '{keyword}'"
        return False, "Query is safe"
Behavior2/5

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

With no annotations provided, the description carries full burden for behavioral disclosure. It mentions execution but fails to describe critical traits like whether this is read-only or destructive, authentication requirements, rate limits, error handling, or response format. For a database query tool with zero annotation coverage, this leaves significant gaps in understanding its behavior.

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 wasted words. It directly states the tool's purpose without unnecessary elaboration, making it appropriately sized and front-loaded for quick comprehension.

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 complexity of a database execution tool with no annotations and no output schema, the description is insufficient. It lacks information about behavioral traits, return values, error conditions, and usage constraints, leaving the agent poorly equipped to use this tool effectively in real scenarios.

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

Parameters3/5

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

Schema description coverage is 100%, with the single parameter 'query' fully documented in the schema. The description adds no additional meaning about parameters beyond what the schema already provides, so it meets the baseline of 3 where the schema does the heavy lifting.

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 a query') and target resource ('against the ClickHouse database'), providing a specific verb+resource combination. However, with no sibling tools mentioned, there's no opportunity to distinguish from alternatives, so it cannot achieve the highest score of 5.

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, prerequisites, or limitations. It simply states what the tool does without context about appropriate scenarios or constraints, leaving the agent with no usage direction.

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/dubin555/clickhouse_mcp_server'

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