Skip to main content
Glama
mongodb-js

MongoDB MCP Server

Official
by mongodb-js

explain

Read-only

Analyze MongoDB query execution plans to understand how the database processes find, aggregate, or count operations and identify optimization opportunities.

Instructions

Returns statistics describing the execution of the winning plan chosen by the query optimizer for the evaluated method

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
databaseYesDatabase name
collectionYesCollection name
methodYesThe method and its arguments to run
verbosityNoThe verbosity of the explain plan, defaults to queryPlanner. If the user wants to know how fast is a query in execution time, use executionStats. It supports all verbosities as defined in the MongoDB Driver.queryPlanner

Implementation Reference

  • The handler function that executes the 'explain' tool. It supports explaining 'aggregate', 'find', and 'count' operations with specified verbosity and returns formatted execution plan information.
    protected async execute({
        database,
        collection,
        method: methods,
        verbosity,
    }: ToolArgs<typeof this.argsShape>): Promise<CallToolResult> {
        const provider = await this.ensureConnected();
        const method = methods[0];
    
        if (!method) {
            throw new Error("No method provided. Expected one of the following: `aggregate`, `find`, or `count`");
        }
    
        let result: Document;
        switch (method.name) {
            case "aggregate": {
                const { pipeline } = method.arguments;
                result = await provider
                    .aggregate(
                        database,
                        collection,
                        pipeline,
                        {},
                        {
                            writeConcern: undefined,
                        }
                    )
                    .explain(verbosity);
                break;
            }
            case "find": {
                const { filter, ...rest } = method.arguments;
                result = await provider.find(database, collection, filter as Document, { ...rest }).explain(verbosity);
                break;
            }
            case "count": {
                const { query } = method.arguments;
                result = await provider.runCommandWithCheck(database, {
                    explain: {
                        count: collection,
                        query,
                    },
                    verbosity,
                });
                break;
            }
        }
    
        return {
            content: formatUntrustedData(
                `Here is some information about the winning plan chosen by the query optimizer for running the given \`${method.name}\` operation in "${database}.${collection}". The execution plan was run with the following verbosity: "${verbosity}". This information can be used to understand how the query was executed and to optimize the query performance.`,
                JSON.stringify(result)
            ),
        };
    }
  • Zod schema defining the input shape for the 'explain' tool, including database/collection operations and verbosity.
    protected argsShape = {
        ...DbOperationArgs,
        method: z
            .array(
                z.discriminatedUnion("name", [
                    z.object({
                        name: z.literal("aggregate"),
                        arguments: z.object(getAggregateArgs(this.isFeatureEnabled("search"))),
                    }),
                    z.object({
                        name: z.literal("find"),
                        arguments: z.object(FindArgs),
                    }),
                    z.object({
                        name: z.literal("count"),
                        arguments: z.object(CountArgs),
                    }),
                ])
            )
            .describe("The method and its arguments to run"),
        verbosity: z
            .enum(["queryPlanner", "queryPlannerExtended", "executionStats", "allPlansExecution"])
            .optional()
            .default("queryPlanner")
            .describe(
                "The verbosity of the explain plan, defaults to queryPlanner. If the user wants to know how fast is a query in execution time, use executionStats. It supports all verbosities as defined in the MongoDB Driver."
            ),
    };
  • Central registration of all tools, including MongoDB tools (MongoDbTools) which provide the ExplainTool.
    export const AllTools: ToolClass[] = Object.values({
        ...MongoDbTools,
        ...AtlasTools,
        ...AtlasLocalTools,
    });
  • Export of the ExplainTool class for inclusion in MongoDB tools module.
    export { ExplainTool } from "./metadata/explain.js";
  • Class definition with tool name 'explain'.
    export class ExplainTool extends MongoDBToolBase {
        public name = "explain";
Behavior3/5

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

Annotations indicate readOnlyHint=true and destructiveHint=false, so the agent knows this is a safe read operation. The description adds that it 'returns statistics,' which aligns with annotations. However, it doesn't disclose additional behavioral traits like performance impact (e.g., whether running explain affects database load), output format details (since no output schema exists), or any rate limits. With annotations covering safety, the description adds minimal context beyond them.

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, well-structured sentence that efficiently conveys the core functionality: 'Returns statistics describing the execution of the winning plan chosen by the query optimizer for the evaluated method.' It's front-loaded with the main action ('returns statistics') and avoids unnecessary words, making it highly concise and easy to parse.

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 tool's complexity (analyzing query execution with multiple method types) and rich schema (100% coverage, detailed parameter docs), the description is adequate but minimal. It lacks output details (no output schema provided), doesn't explain the relationship to sibling tools like 'export' for full results, and omits practical use cases. For a tool with no output schema and moderate complexity, it should provide more context on what 'statistics' entail and when to use it.

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%, so the schema fully documents all 4 parameters (database, collection, method, verbosity) with detailed descriptions. The description doesn't add any parameter-specific information beyond what's in the schema, such as clarifying how 'method' relates to query execution or examples of use. Baseline 3 is appropriate when 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 tool's purpose: 'Returns statistics describing the execution of the winning plan chosen by the query optimizer for the evaluated method.' It specifies the verb ('returns statistics'), resource ('execution of the winning plan'), and scope ('for the evaluated method'), making it clear this is an analysis tool. However, it doesn't explicitly differentiate from sibling tools like 'atlas-get-performance-advisor' or 'mongodb-logs' which might also provide performance insights.

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. It doesn't mention prerequisites (e.g., needing an existing query to analyze), compare it to sibling tools like 'export' (referenced in the schema) for full results, or specify scenarios where explain plans are useful (e.g., query optimization, debugging). Usage is implied but not explicitly stated.

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/mongodb-js/mongodb-mcp-server'

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