Skip to main content
Glama
voducdan

metabase-mcp

by voducdan

execute_query

Execute native SQL queries against a Metabase database to retrieve and manipulate data directly. Provide the database ID, SQL query, and optional parameters for targeted analytics and reporting.

Instructions

Execute a native SQL query against a Metabase database.

Args: database_id: The ID of the database to query. query: The SQL query to execute. native_parameters: Optional parameters for the query.

Returns: Query execution results.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
database_idYes
queryYes
native_parametersNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • The execute_query tool handler function that executes a native SQL query against a Metabase database. It takes database_id, query string, and optional native_parameters, constructs a Metabase API payload, and sends a POST request to /dataset endpoint. The function logs query execution info and handles errors via ToolError.
    @mcp.tool
    async def execute_query(
        database_id: int,
        query: str,
        ctx: Context,
        native_parameters: list[dict[str, Any]] | None = None
    ) -> dict[str, Any]:
        """
        Execute a native SQL query against a Metabase database.
    
        Args:
            database_id: The ID of the database to query.
            query: The SQL query to execute.
            native_parameters: Optional parameters for the query.
    
        Returns:
            Query execution results.
        """
        try:
            await ctx.info(f"Executing query on database {database_id}")
            await ctx.debug(f"Query: {query[:100]}...")  # Log first 100 chars
    
            payload = {
                "database": database_id,
                "type": "native",
                "native": {"query": query}
            }
    
            if native_parameters:
                payload["native"]["parameters"] = native_parameters
                await ctx.debug(f"Query parameters: {len(native_parameters)} parameters provided")
    
            result = await metabase_client.request("POST", "/dataset", json=payload)
    
            row_count = len(result.get("data", {}).get("rows", []))
            await ctx.info(f"Query executed successfully, returned {row_count} rows")
    
            return result
        except Exception as e:
            error_msg = f"Error executing query: {e}"
            await ctx.error(error_msg)
            raise ToolError(error_msg) from e
  • The function signature defines the input schema for execute_query: database_id (int, required), query (str, required), native_parameters (list[dict] optional), and ctx (Context). The return type is dict[str, Any].
    @mcp.tool
    async def execute_query(
        database_id: int,
        query: str,
        ctx: Context,
        native_parameters: list[dict[str, Any]] | None = None
    ) -> dict[str, Any]:
  • server.py:140-141 (registration)
    The tool is registered via the @mcp.tool decorator at line 140 (the first tool decorated similarly). All tools in this file use the @mcp.tool decorator pattern for registration with the FastMCP server instance 'mcp'. The execute_query tool specifically is registered at line 322 with @mcp.tool.
    @mcp.tool
    async def list_databases(ctx: Context) -> dict[str, Any]:

Schema Changelog

Changes observed during successful MCP inspections.

  1. First observedv1.0.0

TDQS

A3.5/5.0
Behavior2/5

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

With no annotations, the description carries full burden. It only states it executes SQL and returns results, without disclosing potential side effects (e.g., whether write operations are allowed), security implications, authentication needs, or rate limits. Critical behavioral context is missing.

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: a one-line purpose, then clearly labeled Args and Returns sections. Every sentence adds value, and there is no redundancy. It is well-structured and easily parsed.

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

Completeness3/5

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

Given the complexity of executing arbitrary SQL (3 parameters, potential write operations), the description lacks completeness. It does not explain return value structure (though output schema exists), error handling, or preconditions. However, it covers the basic purpose and parameters adequately for a simple tool.

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

Parameters4/5

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

The schema has 0% description coverage, so the description compensates by providing plain-language explanations for each parameter: database_id as 'The ID of the database to query', query as 'The SQL query to execute', and native_parameters as 'Optional parameters for the query'. This adds meaning beyond the bare types, though native_parameters could be more specific.

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

Purpose5/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 native SQL query') and the resource ('Metabase database'), distinguishing it from siblings like execute_card (executes a saved card) and execute_mongodb_query (executes MongoDB queries).

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 (e.g., execute_card, or specific query tools). It does not mention constraints, prerequisites, or typical use cases, leaving the agent to infer context.

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