Skip to main content
Glama
voducdan

metabase-mcp

by voducdan

execute_mongodb_query

Run MongoDB native queries against a Metabase database by specifying database ID, collection, and query. Supports aggregation pipelines and optional parameters.

Instructions

Execute a MongoDB native query against a Metabase database.

Args: database_id: The ID of the MongoDB database to query. collection: The MongoDB collection name. query: The MongoDB query (aggregation pipeline array or query object). native_parameters: Optional parameters for the query.

Returns: Query execution results.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
database_idYes
collectionYes
queryYes
native_parametersNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • The actual implementation of the 'execute_mongodb_query' tool. It executes a MongoDB native query against a Metabase database by building a payload with the collection and query, converting the query to JSON if needed, then POSTing to /dataset endpoint.
    @mcp.tool
    async def execute_mongodb_query(
        database_id: int,
        collection: str,
        query: Any,
        ctx: Context,
        native_parameters: list[dict[str, Any]] | None = None
    ) -> dict[str, Any]:
        """
        Execute a MongoDB native query against a Metabase database.
    
        Args:
            database_id: The ID of the MongoDB database to query.
            collection: The MongoDB collection name.
            query: The MongoDB query (aggregation pipeline array or query object).
            native_parameters: Optional parameters for the query.
    
        Returns:
            Query execution results.
        """
        try:
            import json
    
            await ctx.info(f"Executing MongoDB query on database {database_id}, collection {collection}")
    
            # Convert query to JSON string if it's not already a string
            if isinstance(query, (list, dict)):
                query_string = json.dumps(query)
                await ctx.debug(f"Converted query object to JSON string")
            else:
                query_string = str(query)
    
            payload = {
                "database": database_id,
                "type": "native",
                "native": {
                    "query": query_string,
                    "collection": collection
                }
            }
    
            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"MongoDB query executed successfully, returned {row_count} rows")
    
            return result
        except Exception as e:
            error_msg = f"Error executing MongoDB query: {e}"
            await ctx.error(error_msg)
            raise ToolError(error_msg) from e
  • server.py:366-367 (registration)
    The tool is registered via the @mcp.tool decorator on the execute_mongodb_query async function. This is the registration mechanism for the FastMCP framework.
    @mcp.tool
    async def execute_mongodb_query(

Schema Changelog

Changes observed during successful MCP inspections.

  1. First observedv1.0.0

TDQS

A3.7/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 says 'Execute' and returns results, but omits behavioral traits such as whether the query is read-only (likely safe), mutability, side effects, error handling, or performance considerations.

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 concise, using a clear docstring format with Args and Returns sections. It front-loads the main purpose and avoids unnecessary words.

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 MongoDB native queries and the presence of an output schema, the description covers basic parameters and return value. However, it lacks details on the query format, native_parameters usage, and typical response structure, which are important for correct invocation.

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?

Schema coverage is 0%, so the description's parameter explanations add value. Each parameter (database_id, collection, query, native_parameters) is described in the docstring. However, the 'query' parameter format (aggregation pipeline or query object) is mentioned but could be more precise.

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 'Execute a MongoDB native query against a Metabase database,' specifying the verb (execute), resource (query), and context (MongoDB/ Metabase). This distinguishes it from siblings like execute_query (likely SQL) and execute_card (card execution).

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 defines parameters but does not explicitly state when to use this tool over alternatives like execute_query or create_mongodb_card. It implies MongoDB usage but lacks explicit when-to-use or when-not-to-use guidance.

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