Skip to main content
Glama
mongodb-js

MongoDB MCP Server

Official
by mongodb-js

atlas-get-performance-advisor

Read-only

Retrieve MongoDB Atlas performance advisor recommendations to optimize database operations. Get suggested indexes, drop index suggestions, schema improvements, and slow query logs for enhanced query performance.

Instructions

Get MongoDB Atlas performance advisor recommendations, which includes the operations: suggested indexes, drop index suggestions, schema suggestions, and a sample of the most recent (max 50) slow query logs

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
projectIdYesAtlas project ID to get performance advisor recommendations. The project ID is a hexadecimal identifier of 24 characters. If the user has only specified the name, use the `atlas-list-projects` tool to retrieve the user's projects with their ids.
clusterNameYesAtlas cluster name to get performance advisor recommendations
operationsNoOperations to get performance advisor recommendations
sinceNoDate to get slow query logs since. Must be a string in ISO 8601 format. Only relevant for the slowQueryLogs operation.
namespacesNoNamespaces to get slow query logs. Only relevant for the slowQueryLogs operation.

Implementation Reference

  • The execute method that implements the core logic of the tool. It fetches performance advisor data (suggested indexes, drop index suggestions, slow query logs, schema suggestions) based on the specified operations using Atlas API calls via helper utilities, checks if data exists, formats it into markdown sections, and returns it or an error message.
    protected async execute({
        projectId,
        clusterName,
        operations,
        since,
        namespaces,
    }: ToolArgs<typeof this.argsShape>): Promise<CallToolResult> {
        try {
            const [suggestedIndexesResult, dropIndexSuggestionsResult, slowQueryLogsResult, schemaSuggestionsResult] =
                await Promise.allSettled([
                    operations.includes("suggestedIndexes")
                        ? getSuggestedIndexes(this.session.apiClient, projectId, clusterName)
                        : Promise.resolve(undefined),
                    operations.includes("dropIndexSuggestions")
                        ? getDropIndexSuggestions(this.session.apiClient, projectId, clusterName)
                        : Promise.resolve(undefined),
                    operations.includes("slowQueryLogs")
                        ? getSlowQueries(
                              this.session.apiClient,
                              projectId,
                              clusterName,
                              since ? new Date(since) : undefined,
                              namespaces
                          )
                        : Promise.resolve(undefined),
                    operations.includes("schemaSuggestions")
                        ? getSchemaAdvice(this.session.apiClient, projectId, clusterName)
                        : Promise.resolve(undefined),
                ]);
    
            const hasSuggestedIndexes =
                suggestedIndexesResult.status === "fulfilled" &&
                suggestedIndexesResult.value?.suggestedIndexes &&
                suggestedIndexesResult.value.suggestedIndexes.length > 0;
            const hasDropIndexSuggestions =
                dropIndexSuggestionsResult.status === "fulfilled" &&
                dropIndexSuggestionsResult.value?.hiddenIndexes &&
                dropIndexSuggestionsResult.value?.redundantIndexes &&
                dropIndexSuggestionsResult.value?.unusedIndexes &&
                (dropIndexSuggestionsResult.value.hiddenIndexes.length > 0 ||
                    dropIndexSuggestionsResult.value.redundantIndexes.length > 0 ||
                    dropIndexSuggestionsResult.value.unusedIndexes.length > 0);
            const hasSlowQueryLogs =
                slowQueryLogsResult.status === "fulfilled" &&
                slowQueryLogsResult.value?.slowQueryLogs &&
                slowQueryLogsResult.value.slowQueryLogs.length > 0;
            const hasSchemaSuggestions =
                schemaSuggestionsResult.status === "fulfilled" &&
                schemaSuggestionsResult.value?.recommendations &&
                schemaSuggestionsResult.value.recommendations.length > 0;
    
            // Inserts the performance advisor data with the relevant section header if it exists
            const performanceAdvisorData = [
                `## Suggested Indexes\n${
                    hasSuggestedIndexes
                        ? `${SUGGESTED_INDEXES_COPY}\n${JSON.stringify(suggestedIndexesResult.value?.suggestedIndexes)}`
                        : "No suggested indexes found."
                }`,
                `## Drop Index Suggestions\n${hasDropIndexSuggestions ? JSON.stringify(dropIndexSuggestionsResult.value) : "No drop index suggestions found."}`,
                `## Slow Query Logs\n${hasSlowQueryLogs ? `${SLOW_QUERY_LOGS_COPY}\n${JSON.stringify(slowQueryLogsResult.value?.slowQueryLogs)}` : "No slow query logs found."}`,
                `## Schema Suggestions\n${hasSchemaSuggestions ? JSON.stringify(schemaSuggestionsResult.value?.recommendations) : "No schema suggestions found."}`,
            ];
    
            if (performanceAdvisorData.length === 0) {
                return {
                    content: [{ type: "text", text: "No performance advisor recommendations found." }],
                };
            }
    
            return {
                content: formatUntrustedData("Performance advisor data", performanceAdvisorData.join("\n\n")),
            };
        } catch (error) {
            return {
                content: [
                    {
                        type: "text",
                        text: `Error retrieving performance advisor data: ${error instanceof Error ? error.message : String(error)}`,
                    },
                ],
            };
        }
    }
  • Zod schema definition for the tool's input arguments: projectId, clusterName, operations (array of enums), since (optional datetime), namespaces (optional array).
    protected argsShape = {
        projectId: AtlasArgs.projectId().describe(
            "Atlas project ID to get performance advisor recommendations. The project ID is a hexadecimal identifier of 24 characters. If the user has only specified the name, use the `atlas-list-projects` tool to retrieve the user's projects with their ids."
        ),
        clusterName: AtlasArgs.clusterName().describe("Atlas cluster name to get performance advisor recommendations"),
        operations: z
            .array(PerformanceAdvisorOperationType)
            .default(PerformanceAdvisorOperationType.options)
            .describe("Operations to get performance advisor recommendations"),
        since: z
            .string()
            .datetime()
            .describe(
                "Date to get slow query logs since. Must be a string in ISO 8601 format. Only relevant for the slowQueryLogs operation."
            )
            .optional(),
        namespaces: z
            .array(z.string())
            .describe("Namespaces to get slow query logs. Only relevant for the slowQueryLogs operation.")
            .optional(),
    };
  • Re-export of the GetPerformanceAdvisorTool class from its implementation file, making it available for higher-level registration.
    export { GetPerformanceAdvisorTool } from "./read/getPerformanceAdvisor.js";
  • Central registration of all tools into the AllTools array, including AtlasTools which encompasses the GetPerformanceAdvisorTool.
    export const AllTools: ToolClass[] = Object.values({
        ...MongoDbTools,
        ...AtlasTools,
        ...AtlasLocalTools,
    });
  • Supporting utility functions called by the handler: getSuggestedIndexes (lines 26-51), getDropIndexSuggestions (53-84), getSchemaAdvice (86-109), getSlowQueries (111-156) which interact with Atlas API to retrieve specific performance data.
    export async function getSuggestedIndexes(
        apiClient: ApiClient,
        projectId: string,
        clusterName: string
    ): Promise<{ suggestedIndexes: Array<SuggestedIndex> }> {
        try {
            const response = await apiClient.listClusterSuggestedIndexes({
                params: {
                    path: {
                        groupId: projectId,
                        clusterName,
                    },
                },
            });
            return {
                suggestedIndexes: (response as SuggestedIndexesResponse).content.suggestedIndexes ?? [],
            };
        } catch (err) {
            apiClient.logger.debug({
                id: LogId.atlasPaSuggestedIndexesFailure,
                context: "performanceAdvisorUtils",
                message: `Failed to list suggested indexes: ${err instanceof Error ? err.message : String(err)}`,
            });
            throw new Error(`Failed to list suggested indexes: ${err instanceof Error ? err.message : String(err)}`);
        }
    }
    
    export async function getDropIndexSuggestions(
        apiClient: ApiClient,
        projectId: string,
        clusterName: string
    ): Promise<{
        hiddenIndexes: Array<DropIndexSuggestion>;
        redundantIndexes: Array<DropIndexSuggestion>;
        unusedIndexes: Array<DropIndexSuggestion>;
    }> {
        try {
            const response = await apiClient.listDropIndexSuggestions({
                params: {
                    path: {
                        groupId: projectId,
                        clusterName,
                    },
                },
            });
            return {
                hiddenIndexes: (response as DropIndexesResponse).content.hiddenIndexes ?? [],
                redundantIndexes: (response as DropIndexesResponse).content.redundantIndexes ?? [],
                unusedIndexes: (response as DropIndexesResponse).content.unusedIndexes ?? [],
            };
        } catch (err) {
            apiClient.logger.debug({
                id: LogId.atlasPaDropIndexSuggestionsFailure,
                context: "performanceAdvisorUtils",
                message: `Failed to list drop index suggestions: ${err instanceof Error ? err.message : String(err)}`,
            });
            throw new Error(`Failed to list drop index suggestions: ${err instanceof Error ? err.message : String(err)}`);
        }
    }
    
    export async function getSchemaAdvice(
        apiClient: ApiClient,
        projectId: string,
        clusterName: string
    ): Promise<{ recommendations: Array<SchemaRecommendation> }> {
        try {
            const response = await apiClient.listSchemaAdvice({
                params: {
                    path: {
                        groupId: projectId,
                        clusterName,
                    },
                },
            });
            return { recommendations: (response as SchemaAdviceResponse).content.recommendations ?? [] };
        } catch (err) {
            apiClient.logger.debug({
                id: LogId.atlasPaSchemaAdviceFailure,
                context: "performanceAdvisorUtils",
                message: `Failed to list schema advice: ${err instanceof Error ? err.message : String(err)}`,
            });
            throw new Error(`Failed to list schema advice: ${err instanceof Error ? err.message : String(err)}`);
        }
    }
    
    export async function getSlowQueries(
        apiClient: ApiClient,
        projectId: string,
        clusterName: string,
        since?: Date,
        namespaces?: Array<string>
    ): Promise<{ slowQueryLogs: Array<SlowQueryLog> }> {
        try {
            const processIds = await getProcessIdsFromCluster(apiClient, projectId, clusterName);
    
            if (processIds.length === 0) {
                return { slowQueryLogs: [] };
            }
    
            const slowQueryPromises = processIds.map((processId) =>
                apiClient.listSlowQueryLogs({
                    params: {
                        path: {
                            groupId: projectId,
                            processId,
                        },
                        query: {
                            ...(since && { since: since.getTime() }),
                            ...(namespaces && { namespaces: namespaces }),
                            nLogs: DEFAULT_SLOW_QUERY_LOGS_LIMIT,
                        },
                    },
                })
            );
    
            const responses = await Promise.allSettled(slowQueryPromises);
    
            const allSlowQueryLogs = responses.reduce((acc, response) => {
                return acc.concat(response.status === "fulfilled" ? (response.value.slowQueries ?? []) : []);
            }, [] as Array<SlowQueryLog>);
    
            return { slowQueryLogs: allSlowQueryLogs };
        } catch (err) {
            apiClient.logger.debug({
                id: LogId.atlasPaSlowQueryLogsFailure,
                context: "performanceAdvisorUtils",
                message: `Failed to list slow query logs: ${err instanceof Error ? err.message : String(err)}`,
            });
            throw new Error(`Failed to list slow query logs: ${err instanceof Error ? err.message : String(err)}`);
        }
    }
Behavior3/5

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

Annotations already declare readOnlyHint=true and destructiveHint=false, so the agent knows this is a safe read operation. The description adds useful behavioral context by specifying that slow query logs are limited to 'max 50' most recent entries, which isn't captured in annotations. However, it doesn't describe rate limits, authentication requirements, or other operational constraints beyond what annotations provide.

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 communicates the tool's purpose and scope. It front-loads the main action ('Get MongoDB Atlas performance advisor recommendations') and then specifies what's included without unnecessary elaboration. Every word serves a purpose with zero waste.

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

Completeness4/5

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

For a read-only tool with comprehensive schema documentation (100% coverage) and clear annotations, the description provides adequate context. It explains what the tool returns (performance advisor recommendations with specific operation types) and the limitation on slow query logs. The main gap is the lack of output schema, but the description gives reasonable indication of what to expect in the response.

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?

With 100% schema description coverage, the schema already documents all 5 parameters thoroughly. The description mentions the operations parameter values (suggested indexes, drop index suggestions, etc.) but doesn't add significant semantic meaning beyond what's in the schema. The description's mention of 'max 50' for slow query logs provides some additional context not in the schema, but this is minimal enhancement.

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 verb 'Get' and resource 'MongoDB Atlas performance advisor recommendations' with specific details about what operations are included (suggested indexes, drop index suggestions, schema suggestions, slow query logs). It distinguishes this tool from siblings like 'atlas-list-clusters' or 'explain' by focusing specifically on performance advisor functionality rather than general cluster listing or query explanation.

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 implies usage context (when performance advisor recommendations are needed) but doesn't explicitly state when to use this tool versus alternatives. It mentions the tool retrieves 'performance advisor recommendations' but doesn't specify scenarios where this would be preferred over other diagnostic tools like 'explain' or 'mongodb-logs'. No explicit exclusions or alternative tool recommendations are provided.

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