Skip to main content
Glama
jonfreeland

MongoDB MCP Server

by jonfreeland

explain_query

Analyze MongoDB query execution plans to identify performance bottlenecks, understand index usage, and optimize slow database queries.

Instructions

Get the execution plan for a query.

Helps understand:

  • How MongoDB will execute the query

  • Which indexes will be used

  • Number of documents examined

  • Execution stages and timing

Use this to optimize slow queries.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
databaseNoDatabase name (optional if default database is configured)
collectionYesCollection name
filterYesMongoDB query filter to explain
projectionNoMongoDB projection (optional)
sortNoMongoDB sort specification (optional)

Implementation Reference

  • Handler for the 'explain_query' tool. Builds a MongoDB find query based on provided filter, projection, and sort, then executes .explain() to retrieve the query execution plan, and returns it as formatted JSON.
    case 'explain_query': {
      const { database, collection, filter, projection, sort } = request.params
        .arguments as {
        database?: string;
        collection: string;
        filter: object;
        projection?: object;
        sort?: Sort;
      };
      const dbName = database || this.defaultDatabase;
      if (!dbName) {
        throw new McpError(
          ErrorCode.InvalidRequest,
          'Database name is required when no default database is configured'
        );
      }
    
      const db = client.db(dbName);
      let query = db.collection(collection).find(filter);
    
      if (projection) {
        query = query.project(projection);
      }
      if (sort) {
        query = query.sort(sort);
      }
    
      const explanation = await query.explain();
      return {
        content: [
          {
            type: 'text',
            text: JSON.stringify(explanation, null, 2),
          },
        ],
      };
    }
  • src/index.ts:600-637 (registration)
    Registration of the 'explain_query' tool in the ListToolsRequestSchema handler. Includes the tool name, description, and input schema definition.
            {
              name: 'explain_query',
              description: `Get the execution plan for a query.
    
    Helps understand:
    - How MongoDB will execute the query
    - Which indexes will be used
    - Number of documents examined
    - Execution stages and timing
    
    Use this to optimize slow queries.`,
              inputSchema: {
                type: 'object',
                properties: {
                  database: {
                    type: 'string',
                    description: 'Database name (optional if default database is configured)',
                  },
                  collection: {
                    type: 'string',
                    description: 'Collection name',
                  },
                  filter: {
                    type: 'object',
                    description: 'MongoDB query filter to explain',
                  },
                  projection: {
                    type: 'object',
                    description: 'MongoDB projection (optional)',
                  },
                  sort: {
                    type: 'object',
                    description: 'MongoDB sort specification (optional)',
                  },
                },
                required: ['collection', 'filter'],
              },
            },
  • Input schema definition for the 'explain_query' tool, specifying parameters like database, collection, filter, projection, and sort.
      inputSchema: {
        type: 'object',
        properties: {
          database: {
            type: 'string',
            description: 'Database name (optional if default database is configured)',
          },
          collection: {
            type: 'string',
            description: 'Collection name',
          },
          filter: {
            type: 'object',
            description: 'MongoDB query filter to explain',
          },
          projection: {
            type: 'object',
            description: 'MongoDB projection (optional)',
          },
          sort: {
            type: 'object',
            description: 'MongoDB sort specification (optional)',
          },
        },
        required: ['collection', 'filter'],
      },
    },
Behavior3/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. It describes the tool's output (execution plan details) but lacks behavioral details like whether it executes the query, potential performance impact, or error handling. It mentions what the tool helps understand but not how it behaves operationally.

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 front-loaded with the core purpose, followed by bullet points for clarity and a concluding usage guideline. Every sentence earns its place by adding value, with no redundant or vague language. It's efficiently structured for quick comprehension.

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) and lack of annotations or output schema, the description is adequate but incomplete. It covers purpose and usage but omits details like output format, potential side effects, or limitations. For a diagnostic tool with no structured output, more context would be beneficial.

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 already documents all parameters. The description does not add any parameter-specific semantics beyond what the schema provides, such as explaining how 'filter' relates to query optimization. Baseline 3 is appropriate when the schema handles parameter documentation.

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 tool's purpose with specific verbs ('get the execution plan for a query') and distinguishes it from siblings by focusing on query analysis rather than data retrieval or schema inspection. It explicitly mentions what the tool helps understand, making its purpose unambiguous.

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

Usage Guidelines5/5

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

The description provides explicit usage guidance: 'Use this to optimize slow queries.' This directly tells the agent when to use this tool versus alternatives like 'query' or 'aggregate', which execute queries rather than analyze them. The context is clear and actionable.

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

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