Skip to main content
Glama
GreptimeTeam

GreptimeDB MCP Server

Official
by GreptimeTeam

execute_sql

Execute SQL queries in GreptimeDB using MySQL dialect to retrieve, analyze, and manage data efficiently through a secure Model Context Protocol server interface.

Instructions

Execute SQL query against GreptimeDB. Please use MySQL dialect when generating SQL queries.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYesThe SQL query to execute (using MySQL dialect)

Implementation Reference

  • The main handler function for tool calls, which executes the SQL query for the 'execute_sql' tool after validation and security checks.
    async def call_tool(self, name: str, arguments: dict) -> list[TextContent]:
        """Execute SQL commands."""
        logger = self.logger
        config = self.db_config
    
        logger.info(f"Calling tool: {name} with arguments: {arguments}")
    
        if name != "execute_sql":
            raise ValueError(f"Unknown tool: {name}")
    
        query = arguments.get("query")
        if not query:
            raise ValueError("Query is required")
    
        # Check if query is dangerous
        is_dangerous, reason = security_gate(query=query)
        if is_dangerous:
            return [
                TextContent(
                    type="text",
                    text="Error: Contain dangerous operations, reason:" + reason,
                )
            ]
    
        try:
            with connect(**config) as conn:
                with conn.cursor() as cursor:
                    cursor.execute(query)
    
                    stmt = query.strip().upper()
                    # Special handling for SHOW DATABASES
                    if stmt.startswith("SHOW DATABASES"):
                        dbs = cursor.fetchall()
                        result = ["Databases"]  # Header
                        result.extend([db[0] for db in dbs])
                        return [TextContent(type="text", text="\n".join(result))]
                    # Special handling for SHOW TABLES
                    if stmt.startswith("SHOW TABLES"):
                        tables = cursor.fetchall()
                        result = ["Tables_in_" + config["database"]]  # Header
                        result.extend([table[0] for table in tables])
                        return [TextContent(type="text", text="\n".join(result))]
                    # Regular queries
                    elif any(
                        stmt.startswith(cmd)
                        for cmd in ["SELECT", "SHOW", "DESC", "TQL", "EXPLAIN"]
                    ):
                        columns = [desc[0] for desc in cursor.description]
                        rows = cursor.fetchall()
                        result = [",".join(map(str, row)) for row in rows]
                        return [
                            TextContent(
                                type="text",
                                text="\n".join([",".join(columns)] + result),
                            )
                        ]
    
                    # Non-SELECT queries
                    else:
                        conn.commit()
                        return [
                            TextContent(
                                type="text",
                                text=f"Query executed successfully. Rows affected: {cursor.rowcount}",
                            )
                        ]
    
        except Error as e:
            logger.error(f"Error executing SQL '{query}': {e}")
            return [TextContent(type="text", text=f"Error executing query: {str(e)}")]
  • Registers the 'execute_sql' tool, including its name, description, and input schema.
    async def list_tools(self) -> list[Tool]:
        """List available GreptimeDB tools."""
        logger = self.logger
    
        logger.info("Listing tools...")
        return [
            Tool(
                name="execute_sql",
                description="Execute SQL query against GreptimeDB. Please use MySQL dialect when generating SQL queries.",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "query": {
                            "type": "string",
                            "description": "The SQL query to execute (using MySQL dialect)",
                        }
                    },
                    "required": ["query"],
                },
            )
        ]
  • The input schema definition for the 'execute_sql' tool, specifying the required 'query' parameter.
            inputSchema={
                "type": "object",
                "properties": {
                    "query": {
                        "type": "string",
                        "description": "The SQL query to execute (using MySQL dialect)",
                    }
                },
                "required": ["query"],
            },
        )
    ]
  • Helper function used in the handler to detect and block dangerous SQL operations like DROP, DELETE, etc.
    def security_gate(query: str) -> tuple[bool, str]:
        """
        Simple security check for SQL queries.
        Args:
            query: The SQL query to check
        Returns:
            tuple: A boolean indicating if the query is dangerous, and a reason message
        """
        if not query or not query.strip():
            return True, "Empty query not allowed"
    
        # Remove comments and normalize whitespace
        clean_query = re.sub(r"/\*.*?\*/", " ", query, flags=re.DOTALL)  # Remove /* */
        clean_query = re.sub(r"--.*", "", clean_query)  # Remove --
        clean_query = re.sub(r"\s+", " ", clean_query).strip().upper()  # Normalize spaces
    
        # Check for dangerous patterns
        dangerous_patterns = [
            (r"\bDROP\b", "Forbided `DROP` operation"),
            (r"\bDELETE\b", "Forbided `DELETE` operation"),
            (r"\bREVOKE\b", "Forbided `REVOKE` operation"),
            (r"\bTRUNCATE\b", "Forbided `TRUNCATE` operation"),
            (r"\bUPDATE\b", "Forbided `UPDATE` operation"),
            (r"\bINSERT\b", "Forbided `INSERT` operation"),
            (r"\bALTER\b", "Forbided `ALTER` operation"),
            (r"\bCREATE\b", "Forbided `CREATE` operation"),
            (r"\bGRANT\b", "Forbided `GRANT` operation"),
            (r";\s*\w+", "Forbided multiple statements"),
        ]
    
        for pattern, reason in dangerous_patterns:
            if re.search(pattern, clean_query):
                logger.warning(f"Dangerous pattern detected: {query[:50]}...")
                return True, reason
    
        return False, ""
Behavior2/5

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

No annotations are provided, so the description carries the full burden of behavioral disclosure. It mentions the SQL dialect but fails to describe critical traits like whether queries are read-only or can mutate data, authentication requirements, error handling, or rate limits. This leaves significant gaps for an agent to understand the tool's 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 extremely concise with two sentences that are front-loaded and waste no words. Every sentence provides essential information (the action and dialect requirement), making it efficient and 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?

Given the complexity of executing SQL queries (which can involve reads, writes, or schema changes) and the lack of annotations and output schema, the description is incomplete. It doesn't address behavioral aspects like safety, permissions, or result formats, leaving the agent with insufficient context for reliable use.

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?

The schema description coverage is 100%, with the single parameter 'query' fully documented in the schema. The description adds minimal value by reiterating the MySQL dialect requirement, which is already implied in the schema's parameter description. This meets the baseline for high schema coverage.

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 SQL query') and target resource ('against GreptimeDB'), making the purpose unambiguous. It doesn't need sibling differentiation since there are no sibling tools, but it could be more specific about what types of queries are supported (e.g., SELECT, INSERT, etc.).

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

Usage Guidelines3/5

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

The description provides implied usage context by specifying 'use MySQL dialect when generating SQL queries,' which guides how to formulate queries. However, it lacks explicit guidance on when to use this tool versus alternatives (though none exist) or any prerequisites/limitations.

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/GreptimeTeam/greptimedb-mcp-server'

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