|
| 1 | +import { CallToolResult } from "@modelcontextprotocol/sdk/types.js"; |
| 2 | +import { DbOperationArgs, DbOperationType, MongoDBToolBase } from "../mongodbTool.js"; |
| 3 | +import { ToolArgs } from "../../tool.js"; |
| 4 | +import { z } from "zod"; |
| 5 | +import { ExplainVerbosity, Document } from "mongodb"; |
| 6 | + |
| 7 | +export class ExplainTool extends MongoDBToolBase { |
| 8 | + protected name = "explain"; |
| 9 | + protected description = |
| 10 | + "Returns statistics describing the execution of the winning plan chosen by the query optimizer for the evaluated method"; |
| 11 | + |
| 12 | + protected argsShape = { |
| 13 | + ...DbOperationArgs, |
| 14 | + method: z.enum(["aggregate", "find"]).describe("The method to run"), |
| 15 | + methodArguments: z |
| 16 | + .object({ |
| 17 | + aggregatePipeline: z |
| 18 | + .array(z.object({}).passthrough()) |
| 19 | + .optional() |
| 20 | + .describe("aggregate - array of aggregation stages to execute"), |
| 21 | + |
| 22 | + findQuery: z.object({}).passthrough().optional().describe("find - The query to run"), |
| 23 | + findProjection: z.object({}).passthrough().optional().describe("find - The projection to apply"), |
| 24 | + }) |
| 25 | + .describe("The arguments for the method"), |
| 26 | + }; |
| 27 | + |
| 28 | + protected operationType: DbOperationType = "metadata"; |
| 29 | + |
| 30 | + protected async execute({ |
| 31 | + database, |
| 32 | + collection, |
| 33 | + method, |
| 34 | + methodArguments, |
| 35 | + }: ToolArgs<typeof this.argsShape>): Promise<CallToolResult> { |
| 36 | + const provider = this.ensureConnected(); |
| 37 | + |
| 38 | + let result: Document; |
| 39 | + switch (method) { |
| 40 | + case "aggregate": { |
| 41 | + result = await provider.aggregate(database, collection).explain(); |
| 42 | + break; |
| 43 | + } |
| 44 | + case "find": { |
| 45 | + const query = methodArguments.findQuery ?? {}; |
| 46 | + const projection = methodArguments.findProjection ?? {}; |
| 47 | + result = await provider |
| 48 | + .find(database, collection, query, { projection }) |
| 49 | + .explain(ExplainVerbosity.queryPlanner); |
| 50 | + break; |
| 51 | + } |
| 52 | + default: |
| 53 | + throw new Error(`Unsupported method: ${method}`); |
| 54 | + } |
| 55 | + |
| 56 | + return { |
| 57 | + content: [ |
| 58 | + { |
| 59 | + text: `Here is some information about the winning plan chosen by the query optimizer for running the given \`${method}\` operation in \`${database}\`. This information can be used to understand how the query was executed and to optimize the query performance.`, |
| 60 | + type: "text", |
| 61 | + }, |
| 62 | + { |
| 63 | + text: JSON.stringify(result), |
| 64 | + type: "text", |
| 65 | + }, |
| 66 | + ], |
| 67 | + }; |
| 68 | + } |
| 69 | +} |
0 commit comments