From d91acfd70c988bc864cf5748620a6235bc31be2f Mon Sep 17 00:00:00 2001 From: Nikola Irinchev Date: Mon, 28 Apr 2025 13:56:06 +0200 Subject: [PATCH 1/4] chore: disable the connect tool --- src/common/atlas/apiClient.ts | 7 +- src/config.ts | 3 +- src/index.ts | 1 + src/server.ts | 30 ++++++- src/session.ts | 4 +- src/tools/mongodb/mongodbTool.ts | 36 ++++---- src/tools/mongodb/tools.ts | 6 +- tests/integration/helpers.ts | 2 +- tests/integration/server.test.ts | 10 +-- tests/integration/tools/atlas/atlasHelpers.ts | 8 +- .../tools/mongodb/metadata/connect.test.ts | 84 ++++++++++--------- .../tools/mongodb/mongodbHelpers.ts | 27 +++--- 12 files changed, 136 insertions(+), 82 deletions(-) diff --git a/src/common/atlas/apiClient.ts b/src/common/atlas/apiClient.ts index 2cda1ffc5..34e1a0e73 100644 --- a/src/common/atlas/apiClient.ts +++ b/src/common/atlas/apiClient.ts @@ -15,7 +15,7 @@ export interface ApiClientCredentials { export interface ApiClientOptions { credentials?: ApiClientCredentials; - baseUrl?: string; + baseUrl: string; userAgent?: string; } @@ -63,12 +63,11 @@ export class ApiClient { }, }; - constructor(options?: ApiClientOptions) { + constructor(options: ApiClientOptions) { this.options = { ...options, - baseUrl: options?.baseUrl || "https://cloud.mongodb.com/", userAgent: - options?.userAgent || + options.userAgent || `AtlasMCP/${packageInfo.version} (${process.platform}; ${process.arch}; ${process.env.HOSTNAME || "unknown"})`, }; diff --git a/src/config.ts b/src/config.ts index 676247a52..b47d8c5a7 100644 --- a/src/config.ts +++ b/src/config.ts @@ -7,7 +7,7 @@ import { ReadConcernLevel, ReadPreferenceMode, W } from "mongodb"; // If we decide to support non-string config options, we'll need to extend the mechanism for parsing // env variables. export interface UserConfig { - apiBaseUrl?: string; + apiBaseUrl: string; apiClientId?: string; apiClientSecret?: string; telemetry?: "enabled" | "disabled"; @@ -24,6 +24,7 @@ export interface UserConfig { } const defaults: UserConfig = { + apiBaseUrl: "https://cloud.mongodb.com/", logPath: getLogPath(), connectOptions: { readConcern: "local", diff --git a/src/index.ts b/src/index.ts index ef496e5da..9ab92038d 100644 --- a/src/index.ts +++ b/src/index.ts @@ -18,6 +18,7 @@ try { name: packageInfo.mcpServerName, version: packageInfo.version, }); + const server = new Server({ mcpServer, session, diff --git a/src/server.ts b/src/server.ts index 3d4802f39..14b34ae37 100644 --- a/src/server.ts +++ b/src/server.ts @@ -11,6 +11,7 @@ import { type ServerEvent } from "./telemetry/types.js"; import { type ServerCommand } from "./telemetry/types.js"; import { CallToolRequestSchema, CallToolResult } from "@modelcontextprotocol/sdk/types.js"; import assert from "assert"; +import { connectToMongoDB } from "./tools/mongodb/mongodbTool.js"; export interface ServerOptions { session: Session; @@ -33,7 +34,7 @@ export class Server { this.userConfig = userConfig; } - async connect(transport: Transport) { + async connect(transport: Transport): Promise { this.mcpServer.server.registerCapabilities({ logging: {} }); this.registerTools(); @@ -88,6 +89,8 @@ export class Server { const closeTime = Date.now(); this.emitServerEvent("stop", Date.now() - closeTime, error); }; + + await this.validateConfig(); } async close(): Promise { @@ -183,4 +186,29 @@ export class Server { ); } } + + private async validateConfig(): Promise { + const isAtlasConfigured = this.userConfig.apiClientId && this.userConfig.apiClientSecret; + const isMongoDbConfigured = this.userConfig.connectionString; + if (!isAtlasConfigured && !isMongoDbConfigured) { + console.error( + "Either Atlas Client Id or a MongoDB connection string must be configured - you can provide them as environment variables or as startup arguments. \n" + + "Provide the Atlas credentials as `MDB_MCP_API_CLIENT_ID` and `MDB_MCP_API_CLIENT_SECRET` environment variables or as `--apiClientId` and `--apiClientSecret` startup arguments. \n" + + "Provide the MongoDB connection string as `MDB_MCP_CONNECTION_STRING` environment variable or as `--connectionString` startup argument." + ); + throw new Error("Either Atlas Client Id or a MongoDB connection string must be configured"); + } + + if (this.userConfig.connectionString) { + try { + await connectToMongoDB(this.userConfig.connectionString, this.userConfig, this.session); + } catch (error) { + console.error( + "Failed to connect to MongoDB instance using the connection string from the config: ", + error + ); + throw new Error("Failed to connect to MongoDB instance using the connection string from the config"); + } + } + } } diff --git a/src/session.ts b/src/session.ts index 17357d6cf..6f4044cde 100644 --- a/src/session.ts +++ b/src/session.ts @@ -4,7 +4,7 @@ import { Implementation } from "@modelcontextprotocol/sdk/types.js"; import EventEmitter from "events"; export interface SessionOptions { - apiBaseUrl?: string; + apiBaseUrl: string; apiClientId?: string; apiClientSecret?: string; } @@ -20,7 +20,7 @@ export class Session extends EventEmitter<{ version: string; }; - constructor({ apiBaseUrl, apiClientId, apiClientSecret }: SessionOptions = {}) { + constructor({ apiBaseUrl, apiClientId, apiClientSecret }: SessionOptions) { super(); const credentials: ApiClientCredentials | undefined = diff --git a/src/tools/mongodb/mongodbTool.ts b/src/tools/mongodb/mongodbTool.ts index 7e067e0fd..845fa22d7 100644 --- a/src/tools/mongodb/mongodbTool.ts +++ b/src/tools/mongodb/mongodbTool.ts @@ -4,12 +4,31 @@ import { NodeDriverServiceProvider } from "@mongosh/service-provider-node-driver import { CallToolResult } from "@modelcontextprotocol/sdk/types.js"; import { ErrorCodes, MongoDBError } from "../../errors.js"; import logger, { LogId } from "../../logger.js"; +import { UserConfig } from "../../config.js"; +import { Session } from "../../session.js"; export const DbOperationArgs = { database: z.string().describe("Database name"), collection: z.string().describe("Collection name"), }; +export async function connectToMongoDB(connectionString: string, config: UserConfig, session: Session): Promise { + const provider = await NodeDriverServiceProvider.connect(connectionString, { + productDocsLink: "https://docs.mongodb.com/todo-mcp", + productName: "MongoDB MCP", + readConcern: { + level: config.connectOptions.readConcern, + }, + readPreference: config.connectOptions.readPreference, + writeConcern: { + w: config.connectOptions.writeConcern, + }, + timeoutMS: config.connectOptions.timeoutMS, + }); + + session.serviceProvider = provider; +} + export abstract class MongoDBToolBase extends ToolBase { protected category: ToolCategory = "mongodb"; @@ -70,20 +89,7 @@ export abstract class MongoDBToolBase extends ToolBase { return super.handleError(error, args); } - protected async connectToMongoDB(connectionString: string): Promise { - const provider = await NodeDriverServiceProvider.connect(connectionString, { - productDocsLink: "https://docs.mongodb.com/todo-mcp", - productName: "MongoDB MCP", - readConcern: { - level: this.config.connectOptions.readConcern, - }, - readPreference: this.config.connectOptions.readPreference, - writeConcern: { - w: this.config.connectOptions.writeConcern, - }, - timeoutMS: this.config.connectOptions.timeoutMS, - }); - - this.session.serviceProvider = provider; + protected connectToMongoDB(connectionString: string): Promise { + return connectToMongoDB(connectionString, this.config, this.session); } } diff --git a/src/tools/mongodb/tools.ts b/src/tools/mongodb/tools.ts index d64d53ea7..523f45ca0 100644 --- a/src/tools/mongodb/tools.ts +++ b/src/tools/mongodb/tools.ts @@ -1,4 +1,5 @@ -import { ConnectTool } from "./metadata/connect.js"; +// TODO: https://github.com/mongodb-js/mongodb-mcp-server/issues/141 - reenable when the connect tool is reenabled +// import { ConnectTool } from "./metadata/connect.js"; import { ListCollectionsTool } from "./metadata/listCollections.js"; import { CollectionIndexesTool } from "./read/collectionIndexes.js"; import { ListDatabasesTool } from "./metadata/listDatabases.js"; @@ -20,7 +21,8 @@ import { CreateCollectionTool } from "./create/createCollection.js"; import { LogsTool } from "./metadata/logs.js"; export const MongoDbTools = [ - ConnectTool, + // TODO: https://github.com/mongodb-js/mongodb-mcp-server/issues/141 - reenable when the connect tool is reenabled + // ConnectTool, ListCollectionsTool, ListDatabasesTool, CollectionIndexesTool, diff --git a/tests/integration/helpers.ts b/tests/integration/helpers.ts index 98c8b9705..c4b675da7 100644 --- a/tests/integration/helpers.ts +++ b/tests/integration/helpers.ts @@ -20,7 +20,7 @@ export interface IntegrationTest { mcpServer: () => Server; } -export function setupIntegrationTest(getUserConfig: () => UserConfig = () => config): IntegrationTest { +export function setupIntegrationTest(getUserConfig: () => UserConfig): IntegrationTest { let mcpClient: Client | undefined; let mcpServer: Server | undefined; diff --git a/tests/integration/server.test.ts b/tests/integration/server.test.ts index b9072dcac..be8abb033 100644 --- a/tests/integration/server.test.ts +++ b/tests/integration/server.test.ts @@ -1,14 +1,9 @@ import { expectDefined, setupIntegrationTest } from "./helpers.js"; import { config } from "../../src/config.js"; +import { describeWithMongoDB } from "./tools/mongodb/mongodbHelpers.js"; describe("Server integration test", () => { - describe("without atlas", () => { - const integration = setupIntegrationTest(() => ({ - ...config, - apiClientId: undefined, - apiClientSecret: undefined, - })); - + describeWithMongoDB("without atlas", (integration) => { it("should return positive number of tools and have no atlas tools", async () => { const tools = await integration.mcpClient().listTools(); expectDefined(tools); @@ -18,6 +13,7 @@ describe("Server integration test", () => { expect(atlasTools.length).toBeLessThanOrEqual(0); }); }); + describe("with atlas", () => { const integration = setupIntegrationTest(() => ({ ...config, diff --git a/tests/integration/tools/atlas/atlasHelpers.ts b/tests/integration/tools/atlas/atlasHelpers.ts index f015b2b24..76ba157eb 100644 --- a/tests/integration/tools/atlas/atlasHelpers.ts +++ b/tests/integration/tools/atlas/atlasHelpers.ts @@ -2,6 +2,7 @@ import { ObjectId } from "mongodb"; import { Group } from "../../../../src/common/atlas/openapi.js"; import { ApiClient } from "../../../../src/common/atlas/apiClient.js"; import { setupIntegrationTest, IntegrationTest } from "../../helpers.js"; +import { config } from "../../../../src/config.js"; export type IntegrationTestFunction = (integration: IntegrationTest) => void; @@ -11,7 +12,12 @@ export function sleep(ms: number) { export function describeWithAtlas(name: string, fn: IntegrationTestFunction) { const testDefinition = () => { - const integration = setupIntegrationTest(); + const integration = setupIntegrationTest(() => ({ + ...config, + apiClientId: process.env.MDB_MCP_API_CLIENT_ID, + apiClientSecret: process.env.MDB_MCP_API_CLIENT_SECRET, + })); + describe(name, () => { fn(integration); }); diff --git a/tests/integration/tools/mongodb/metadata/connect.test.ts b/tests/integration/tools/mongodb/metadata/connect.test.ts index ca1389449..d742e7e80 100644 --- a/tests/integration/tools/mongodb/metadata/connect.test.ts +++ b/tests/integration/tools/mongodb/metadata/connect.test.ts @@ -2,6 +2,8 @@ import { describeWithMongoDB } from "../mongodbHelpers.js"; import { getResponseContent, validateThrowsForInvalidArguments, validateToolMetadata } from "../../../helpers.js"; import { config } from "../../../../../src/config.js"; +// These tests are temporarily skipped because the connect tool is disabled for the initial release. +// TODO: https://github.com/mongodb-js/mongodb-mcp-server/issues/141 - reenable when the connect tool is reenabled describeWithMongoDB( "switchConnection tool", (integration) => { @@ -75,50 +77,56 @@ describeWithMongoDB( (mdbIntegration) => ({ ...config, connectionString: mdbIntegration.connectionString(), - }) + }), + describe.skip ); -describeWithMongoDB("Connect tool", (integration) => { - validateToolMetadata(integration, "connect", "Connect to a MongoDB instance", [ - { - name: "connectionString", - description: "MongoDB connection string (in the mongodb:// or mongodb+srv:// format)", - type: "string", - required: true, - }, - ]); +describeWithMongoDB( + "Connect tool", + (integration) => { + validateToolMetadata(integration, "connect", "Connect to a MongoDB instance", [ + { + name: "connectionString", + description: "MongoDB connection string (in the mongodb:// or mongodb+srv:// format)", + type: "string", + required: true, + }, + ]); - validateThrowsForInvalidArguments(integration, "connect", [{}, { connectionString: 123 }]); + validateThrowsForInvalidArguments(integration, "connect", [{}, { connectionString: 123 }]); - it("doesn't have the switch-connection tool registered", async () => { - const { tools } = await integration.mcpClient().listTools(); - const tool = tools.find((tool) => tool.name === "switch-connection"); - expect(tool).toBeUndefined(); - }); + it("doesn't have the switch-connection tool registered", async () => { + const { tools } = await integration.mcpClient().listTools(); + const tool = tools.find((tool) => tool.name === "switch-connection"); + expect(tool).toBeUndefined(); + }); - describe("with connection string", () => { - it("connects to the database", async () => { - const response = await integration.mcpClient().callTool({ - name: "connect", - arguments: { - connectionString: integration.connectionString(), - }, + describe("with connection string", () => { + it("connects to the database", async () => { + const response = await integration.mcpClient().callTool({ + name: "connect", + arguments: { + connectionString: integration.connectionString(), + }, + }); + const content = getResponseContent(response.content); + expect(content).toContain("Successfully connected"); }); - const content = getResponseContent(response.content); - expect(content).toContain("Successfully connected"); }); - }); - describe("with invalid connection string", () => { - it("returns error message", async () => { - const response = await integration.mcpClient().callTool({ - name: "connect", - arguments: { connectionString: "mongodb://localhost:12345" }, - }); - const content = getResponseContent(response.content); - expect(content).toContain("Error running connect"); + describe("with invalid connection string", () => { + it("returns error message", async () => { + const response = await integration.mcpClient().callTool({ + name: "connect", + arguments: { connectionString: "mongodb://localhost:12345" }, + }); + const content = getResponseContent(response.content); + expect(content).toContain("Error running connect"); - // Should not suggest using the config connection string (because we don't have one) - expect(content).not.toContain("Your config lists a different connection string"); + // Should not suggest using the config connection string (because we don't have one) + expect(content).not.toContain("Your config lists a different connection string"); + }); }); - }); -}); + }, + () => config, + describe.skip +); diff --git a/tests/integration/tools/mongodb/mongodbHelpers.ts b/tests/integration/tools/mongodb/mongodbHelpers.ts index 807b0d206..2b4ea6a04 100644 --- a/tests/integration/tools/mongodb/mongodbHelpers.ts +++ b/tests/integration/tools/mongodb/mongodbHelpers.ts @@ -14,24 +14,30 @@ interface MongoDBIntegrationTest { export function describeWithMongoDB( name: string, fn: (integration: IntegrationTest & MongoDBIntegrationTest & { connectMcpClient: () => Promise }) => void, - getUserConfig: (mdbIntegration: MongoDBIntegrationTest) => UserConfig = () => config + getUserConfig: (mdbIntegration: MongoDBIntegrationTest) => UserConfig = () => config, + describeFn = describe ) { - describe(name, () => { + describeFn(name, () => { const mdbIntegration = setupMongoDBIntegrationTest(); - const integration = setupIntegrationTest(() => getUserConfig(mdbIntegration)); + const integration = setupIntegrationTest(() => ({ + ...getUserConfig(mdbIntegration), + connectionString: mdbIntegration.connectionString(), + })); - afterEach(() => { - integration.mcpServer().userConfig.connectionString = undefined; + beforeEach(() => { + integration.mcpServer().userConfig.connectionString = mdbIntegration.connectionString(); }); fn({ ...integration, ...mdbIntegration, connectMcpClient: async () => { - await integration.mcpClient().callTool({ - name: "connect", - arguments: { connectionString: mdbIntegration.connectionString() }, - }); + // TODO: https://github.com/mongodb-js/mongodb-mcp-server/issues/141 - reenable when + // the connect tool is reenabled + // await integration.mcpClient().callTool({ + // name: "connect", + // arguments: { connectionString: mdbIntegration.connectionString() }, + // }); }, }); }); @@ -132,7 +138,8 @@ export function validateAutoConnectBehavior( }, beforeEachImpl?: () => Promise ): void { - describe("when not connected", () => { + // TODO: https://github.com/mongodb-js/mongodb-mcp-server/issues/141 - reenable when the connect tool is reenabled + describe.skip("when not connected", () => { if (beforeEachImpl) { beforeEach(() => beforeEachImpl()); } From 55f1ddf39237e221b56520e14e2dc4f049171747 Mon Sep 17 00:00:00 2001 From: Nikola Irinchev Date: Mon, 28 Apr 2025 14:06:38 +0200 Subject: [PATCH 2/4] fix lint --- .github/workflows/code_health.yaml | 2 +- tests/integration/helpers.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/code_health.yaml b/.github/workflows/code_health.yaml index 265d10506..55f485d82 100644 --- a/.github/workflows/code_health.yaml +++ b/.github/workflows/code_health.yaml @@ -63,7 +63,7 @@ jobs: path: coverage/lcov.info coverage: - name: Run MongoDB tests + name: Report Coverage if: always() && github.event.pull_request.user.login != 'dependabot[bot]' && github.event.pull_request.head.repo.full_name == github.repository runs-on: ubuntu-latest needs: [run-tests, run-atlas-tests] diff --git a/tests/integration/helpers.ts b/tests/integration/helpers.ts index c4b675da7..c57deda82 100644 --- a/tests/integration/helpers.ts +++ b/tests/integration/helpers.ts @@ -1,7 +1,7 @@ import { Client } from "@modelcontextprotocol/sdk/client/index.js"; import { InMemoryTransport } from "./inMemoryTransport.js"; import { Server } from "../../src/server.js"; -import { config, UserConfig } from "../../src/config.js"; +import { UserConfig } from "../../src/config.js"; import { McpError } from "@modelcontextprotocol/sdk/types.js"; import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; import { Session } from "../../src/session.js"; From 4a02ecf12411712f5a0af87543193c0659dacddf Mon Sep 17 00:00:00 2001 From: Nikola Irinchev Date: Mon, 28 Apr 2025 15:50:33 +0200 Subject: [PATCH 3/4] undefine the api client id and secret --- tests/integration/server.test.ts | 26 +++++++++++++++++--------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/tests/integration/server.test.ts b/tests/integration/server.test.ts index be8abb033..aec15add0 100644 --- a/tests/integration/server.test.ts +++ b/tests/integration/server.test.ts @@ -3,16 +3,24 @@ import { config } from "../../src/config.js"; import { describeWithMongoDB } from "./tools/mongodb/mongodbHelpers.js"; describe("Server integration test", () => { - describeWithMongoDB("without atlas", (integration) => { - it("should return positive number of tools and have no atlas tools", async () => { - const tools = await integration.mcpClient().listTools(); - expectDefined(tools); - expect(tools.tools.length).toBeGreaterThan(0); + describeWithMongoDB( + "without atlas", + (integration) => { + it("should return positive number of tools and have no atlas tools", async () => { + const tools = await integration.mcpClient().listTools(); + expectDefined(tools); + expect(tools.tools.length).toBeGreaterThan(0); - const atlasTools = tools.tools.filter((tool) => tool.name.startsWith("atlas-")); - expect(atlasTools.length).toBeLessThanOrEqual(0); - }); - }); + const atlasTools = tools.tools.filter((tool) => tool.name.startsWith("atlas-")); + expect(atlasTools.length).toBeLessThanOrEqual(0); + }); + }, + () => ({ + ...config, + apiClientId: undefined, + apiClientSecret: undefined, + }) + ); describe("with atlas", () => { const integration = setupIntegrationTest(() => ({ From 6e9b58684a4c3615f3f6e2c59d0c56dcc8a3d23a Mon Sep 17 00:00:00 2001 From: Nikola Irinchev Date: Mon, 28 Apr 2025 17:49:34 +0200 Subject: [PATCH 4/4] CR comments - move connectToMongoDB to the session --- src/config.ts | 14 ++++++++------ src/server.ts | 3 +-- src/session.ts | 18 ++++++++++++++++++ src/tools/mongodb/mongodbTool.ts | 21 +-------------------- 4 files changed, 28 insertions(+), 28 deletions(-) diff --git a/src/config.ts b/src/config.ts index b47d8c5a7..aa0be9db1 100644 --- a/src/config.ts +++ b/src/config.ts @@ -4,6 +4,13 @@ import argv from "yargs-parser"; import { ReadConcernLevel, ReadPreferenceMode, W } from "mongodb"; +export interface ConnectOptions { + readConcern: ReadConcernLevel; + readPreference: ReadPreferenceMode; + writeConcern: W; + timeoutMS: number; +} + // If we decide to support non-string config options, we'll need to extend the mechanism for parsing // env variables. export interface UserConfig { @@ -13,12 +20,7 @@ export interface UserConfig { telemetry?: "enabled" | "disabled"; logPath: string; connectionString?: string; - connectOptions: { - readConcern: ReadConcernLevel; - readPreference: ReadPreferenceMode; - writeConcern: W; - timeoutMS: number; - }; + connectOptions: ConnectOptions; disabledTools: Array; readOnly?: boolean; } diff --git a/src/server.ts b/src/server.ts index 14b34ae37..a105b33f4 100644 --- a/src/server.ts +++ b/src/server.ts @@ -11,7 +11,6 @@ import { type ServerEvent } from "./telemetry/types.js"; import { type ServerCommand } from "./telemetry/types.js"; import { CallToolRequestSchema, CallToolResult } from "@modelcontextprotocol/sdk/types.js"; import assert from "assert"; -import { connectToMongoDB } from "./tools/mongodb/mongodbTool.js"; export interface ServerOptions { session: Session; @@ -201,7 +200,7 @@ export class Server { if (this.userConfig.connectionString) { try { - await connectToMongoDB(this.userConfig.connectionString, this.userConfig, this.session); + await this.session.connectToMongoDB(this.userConfig.connectionString, this.userConfig.connectOptions); } catch (error) { console.error( "Failed to connect to MongoDB instance using the connection string from the config: ", diff --git a/src/session.ts b/src/session.ts index 6f4044cde..4b8c7fafc 100644 --- a/src/session.ts +++ b/src/session.ts @@ -2,6 +2,7 @@ import { NodeDriverServiceProvider } from "@mongosh/service-provider-node-driver import { ApiClient, ApiClientCredentials } from "./common/atlas/apiClient.js"; import { Implementation } from "@modelcontextprotocol/sdk/types.js"; import EventEmitter from "events"; +import { ConnectOptions } from "./config.js"; export interface SessionOptions { apiBaseUrl: string; @@ -58,4 +59,21 @@ export class Session extends EventEmitter<{ this.emit("close"); } } + + async connectToMongoDB(connectionString: string, connectOptions: ConnectOptions): Promise { + const provider = await NodeDriverServiceProvider.connect(connectionString, { + productDocsLink: "https://docs.mongodb.com/todo-mcp", + productName: "MongoDB MCP", + readConcern: { + level: connectOptions.readConcern, + }, + readPreference: connectOptions.readPreference, + writeConcern: { + w: connectOptions.writeConcern, + }, + timeoutMS: connectOptions.timeoutMS, + }); + + this.serviceProvider = provider; + } } diff --git a/src/tools/mongodb/mongodbTool.ts b/src/tools/mongodb/mongodbTool.ts index 845fa22d7..d0e59b8b5 100644 --- a/src/tools/mongodb/mongodbTool.ts +++ b/src/tools/mongodb/mongodbTool.ts @@ -4,31 +4,12 @@ import { NodeDriverServiceProvider } from "@mongosh/service-provider-node-driver import { CallToolResult } from "@modelcontextprotocol/sdk/types.js"; import { ErrorCodes, MongoDBError } from "../../errors.js"; import logger, { LogId } from "../../logger.js"; -import { UserConfig } from "../../config.js"; -import { Session } from "../../session.js"; export const DbOperationArgs = { database: z.string().describe("Database name"), collection: z.string().describe("Collection name"), }; -export async function connectToMongoDB(connectionString: string, config: UserConfig, session: Session): Promise { - const provider = await NodeDriverServiceProvider.connect(connectionString, { - productDocsLink: "https://docs.mongodb.com/todo-mcp", - productName: "MongoDB MCP", - readConcern: { - level: config.connectOptions.readConcern, - }, - readPreference: config.connectOptions.readPreference, - writeConcern: { - w: config.connectOptions.writeConcern, - }, - timeoutMS: config.connectOptions.timeoutMS, - }); - - session.serviceProvider = provider; -} - export abstract class MongoDBToolBase extends ToolBase { protected category: ToolCategory = "mongodb"; @@ -90,6 +71,6 @@ export abstract class MongoDBToolBase extends ToolBase { } protected connectToMongoDB(connectionString: string): Promise { - return connectToMongoDB(connectionString, this.config, this.session); + return this.session.connectToMongoDB(connectionString, this.config.connectOptions); } }