|
| 1 | +import z from "zod"; |
| 2 | +import { type CallToolResult } from "@modelcontextprotocol/sdk/types.js"; |
| 3 | + |
| 4 | +import { MongoDBToolBase } from "../mongodbTool.js"; |
| 5 | +import { type ToolArgs, type OperationType, type ToolConstructorParams } from "../../tool.js"; |
| 6 | +import type { Server } from "../../../server.js"; |
| 7 | + |
| 8 | +export class SwitchConnectionTool extends MongoDBToolBase { |
| 9 | + public override name = "switch-connection"; |
| 10 | + protected override description = |
| 11 | + "Switch to a different MongoDB connection. If the user has configured a connection string or has previously called the connect tool, a connection is already established and there's no need to call this tool unless the user has explicitly requested to switch to a new instance."; |
| 12 | + |
| 13 | + protected override argsShape = { |
| 14 | + connectionString: z |
| 15 | + .string() |
| 16 | + .optional() |
| 17 | + .describe( |
| 18 | + "MongoDB connection string to switch to (in the mongodb:// or mongodb+srv:// format). If a connection string is not provided, the connection string from the config will be used." |
| 19 | + ), |
| 20 | + }; |
| 21 | + |
| 22 | + public override operationType: OperationType = "connect"; |
| 23 | + |
| 24 | + constructor({ session, config, telemetry, elicitation }: ToolConstructorParams) { |
| 25 | + super({ session, config, telemetry, elicitation }); |
| 26 | + session.on("connect", () => { |
| 27 | + this.enable(); |
| 28 | + }); |
| 29 | + |
| 30 | + session.on("disconnect", () => { |
| 31 | + this.disable(); |
| 32 | + }); |
| 33 | + } |
| 34 | + |
| 35 | + public override register(server: Server): boolean { |
| 36 | + const registrationSuccessful = super.register(server); |
| 37 | + /** |
| 38 | + * When connected to mongodb we want to swap connect with |
| 39 | + * switch-connection tool. |
| 40 | + */ |
| 41 | + if (registrationSuccessful && !this.session.isConnectedToMongoDB) { |
| 42 | + this.disable(); |
| 43 | + } |
| 44 | + return registrationSuccessful; |
| 45 | + } |
| 46 | + |
| 47 | + protected override async execute({ connectionString }: ToolArgs<typeof this.argsShape>): Promise<CallToolResult> { |
| 48 | + if (typeof connectionString !== "string") { |
| 49 | + await this.session.connectToConfiguredConnection(); |
| 50 | + } else { |
| 51 | + await this.session.connectToMongoDB({ connectionString }); |
| 52 | + } |
| 53 | + |
| 54 | + return { |
| 55 | + content: [{ type: "text", text: "Successfully connected to MongoDB." }], |
| 56 | + }; |
| 57 | + } |
| 58 | +} |
0 commit comments