|
| 1 | +import { CallToolResult } from "@modelcontextprotocol/sdk/types.js"; |
| 2 | +import { DbOperationArgs, DbOperationType, MongoDBToolBase } from "../mongodbTool.js"; |
| 3 | +import { ToolArgs } from "../../tool.js"; |
| 4 | +import { parseSchema, SchemaField } from "mongodb-schema"; |
| 5 | +import { z } from "zod"; |
| 6 | +import { NodeDriverServiceProvider } from "@mongosh/service-provider-node-driver"; |
| 7 | +import { ExplainVerbosity } from "mongodb"; |
| 8 | + |
| 9 | +export class CollectionExplainTool extends MongoDBToolBase { |
| 10 | + protected name = "collection-explain"; |
| 11 | + protected description = "Returns statistics describing the execution of the winning plan for the evaluated method"; |
| 12 | + |
| 13 | + static supportedOperations = [ |
| 14 | + "aggregate", |
| 15 | + "count", |
| 16 | + "distinct", |
| 17 | + "find", |
| 18 | + "findAndModify", |
| 19 | + "delete", |
| 20 | + "mapReduce", |
| 21 | + "update", |
| 22 | + ] as const; |
| 23 | + |
| 24 | + protected argsShape = { |
| 25 | + ...DbOperationArgs, |
| 26 | + operation: z.enum(CollectionExplainTool.supportedOperations).describe("Method to explain"), |
| 27 | + operationsArguments: z.any().describe("Arguments used by the method to be explained"), |
| 28 | + }; |
| 29 | + |
| 30 | + protected operationType: DbOperationType = "metadata"; |
| 31 | + |
| 32 | + protected async execute({ |
| 33 | + database, |
| 34 | + collection, |
| 35 | + operation, |
| 36 | + operationsArguments, |
| 37 | + }: ToolArgs<typeof this.argsShape>): Promise<CallToolResult> { |
| 38 | + const provider = this.ensureConnected(); |
| 39 | + |
| 40 | + const documents = await provider.runCommand(database, { |
| 41 | + explain: operation, |
| 42 | + verbosity: ExplainVerbosity.queryPlanner, |
| 43 | + }); |
| 44 | + |
| 45 | + return { |
| 46 | + content: [ |
| 47 | + { |
| 48 | + text: `Found ${schema.fields.length} fields in the schema for \`${database}.${collection}\``, |
| 49 | + type: "text", |
| 50 | + }, |
| 51 | + { |
| 52 | + text: this.formatFieldOutput(schema.fields), |
| 53 | + type: "text", |
| 54 | + }, |
| 55 | + ], |
| 56 | + }; |
| 57 | + } |
| 58 | + |
| 59 | + private formatFieldOutput(fields: SchemaField[]): string { |
| 60 | + let result = "| Field | Type | Confidence |\n"; |
| 61 | + result += "|-------|------|-------------|\n"; |
| 62 | + for (const field of fields) { |
| 63 | + result += `| ${field.name} | \`${field.type}\` | ${(field.probability * 100).toFixed(0)}% |\n`; |
| 64 | + } |
| 65 | + return result; |
| 66 | + } |
| 67 | +} |
0 commit comments