|
| 1 | +import { z } from "zod"; |
| 2 | +import { CallToolResult, McpError } from "@modelcontextprotocol/sdk/types.js"; |
| 3 | +import { NodeDriverServiceProvider } from "@mongosh/service-provider-node-driver"; |
| 4 | +import { DbOperationType, MongoDBToolBase } from "./mongodbTool.js"; |
| 5 | +import { ToolArgs } from "../tool"; |
| 6 | +import { ErrorCodes } from "../../errors.js"; |
| 7 | + |
| 8 | +export class ConnectTool extends MongoDBToolBase { |
| 9 | + protected name = "connect"; |
| 10 | + protected description = "Connect to a MongoDB instance"; |
| 11 | + protected argsShape = { |
| 12 | + connectionStringOrClusterName: z |
| 13 | + .string() |
| 14 | + .optional() |
| 15 | + .describe("MongoDB connection string (in the mongodb:// or mongodb+srv:// format) or cluster name"), |
| 16 | + }; |
| 17 | + |
| 18 | + protected operationType: DbOperationType = "metadata"; |
| 19 | + |
| 20 | + protected async execute({ |
| 21 | + connectionStringOrClusterName, |
| 22 | + }: ToolArgs<typeof this.argsShape>): Promise<CallToolResult> { |
| 23 | + if (!connectionStringOrClusterName) { |
| 24 | + // TODO: try reconnecting to the default connection |
| 25 | + return { |
| 26 | + content: [ |
| 27 | + { type: "text", text: "No connection details provided." }, |
| 28 | + { type: "text", text: "Please provide either a connection string or a cluster name" }, |
| 29 | + { |
| 30 | + type: "text", |
| 31 | + text: "Alternatively, you can use the default deployment at mongodb://localhost:27017", |
| 32 | + }, |
| 33 | + ], |
| 34 | + }; |
| 35 | + } |
| 36 | + |
| 37 | + let connectionString: string; |
| 38 | + |
| 39 | + if (typeof connectionStringOrClusterName === "string") { |
| 40 | + if ( |
| 41 | + connectionStringOrClusterName.startsWith("mongodb://") || |
| 42 | + connectionStringOrClusterName.startsWith("mongodb+srv://") |
| 43 | + ) { |
| 44 | + connectionString = connectionStringOrClusterName; |
| 45 | + } else { |
| 46 | + // TODO: |
| 47 | + return { |
| 48 | + content: [ |
| 49 | + { |
| 50 | + type: "text", |
| 51 | + text: `Connecting via cluster name not supported yet. Please provide a connection string.`, |
| 52 | + }, |
| 53 | + ], |
| 54 | + }; |
| 55 | + } |
| 56 | + } else { |
| 57 | + throw new McpError(ErrorCodes.InvalidParams, "Invalid connection options"); |
| 58 | + } |
| 59 | + |
| 60 | + await this.connect(connectionString); |
| 61 | + |
| 62 | + return { |
| 63 | + content: [{ type: "text", text: `Successfully connected to ${connectionString}.` }], |
| 64 | + }; |
| 65 | + } |
| 66 | + |
| 67 | + private async connect(connectionString: string): Promise<void> { |
| 68 | + const provider = await NodeDriverServiceProvider.connect(connectionString, { |
| 69 | + productDocsLink: "https://docs.mongodb.com/todo-mcp", |
| 70 | + productName: "MongoDB MCP", |
| 71 | + }); |
| 72 | + |
| 73 | + this.mongodbState.serviceProvider = provider; |
| 74 | + } |
| 75 | +} |
0 commit comments