@@ -9,6 +9,7 @@ import { Telemetry } from "./telemetry/telemetry.js";
99import { UserConfig } from "./common/config.js" ;
1010import { type ServerEvent } from "./telemetry/types.js" ;
1111import { type ServerCommand } from "./telemetry/types.js" ;
12+ import ConnectionString from "mongodb-connection-string-url" ;
1213import {
1314 CallToolRequestSchema ,
1415 CallToolResult ,
@@ -17,6 +18,7 @@ import {
1718} from "@modelcontextprotocol/sdk/types.js" ;
1819import assert from "assert" ;
1920import { ToolBase } from "./tools/tool.js" ;
21+ import { validateConnectionString } from "./helpers/connectionOptions.js" ;
2022
2123export interface ServerOptions {
2224 session : Session ;
@@ -106,6 +108,9 @@ export class Server {
106108 } ) ;
107109
108110 this . emitServerEvent ( "start" , Date . now ( ) - this . startTime ) ;
111+
112+ // Placed here to start the connection to the config connection string as soon as the server is initialized.
113+ this . connectToConfigConnectionString ( ) ;
109114 } ;
110115
111116 this . mcpServer . server . onclose = ( ) : void => {
@@ -188,20 +193,17 @@ export class Server {
188193 }
189194
190195 private async validateConfig ( ) : Promise < void > {
196+ // Validate connection string
191197 if ( this . userConfig . connectionString ) {
192198 try {
193- await this . session . connectToMongoDB ( {
194- connectionString : this . userConfig . connectionString ,
195- } ) ;
199+ await validateConnectionString ( this . userConfig . connectionString , false ) ;
196200 } catch ( error ) {
197- console . error (
198- "Failed to connect to MongoDB instance using the connection string from the config: " ,
199- error
200- ) ;
201- throw new Error ( "Failed to connect to MongoDB instance using the connection string from the config" ) ;
201+ console . error ( "Connection string validation failed with error: " , error ) ;
202+ throw new Error ( "Connection string validation failed with error: " + error ) ;
202203 }
203204 }
204205
206+ // Validate API client credentials
205207 if ( this . userConfig . apiClientId && this . userConfig . apiClientSecret ) {
206208 try {
207209 await this . session . apiClient . validateAccessToken ( ) ;
@@ -219,4 +221,20 @@ export class Server {
219221 }
220222 }
221223 }
224+
225+ private async connectToConfigConnectionString ( ) : Promise < void > {
226+ if ( this . userConfig . connectionString ) {
227+ try {
228+ await this . session . connectToMongoDB ( {
229+ connectionString : this . userConfig . connectionString ,
230+ } ) ;
231+ } catch ( error ) {
232+ console . error (
233+ "Failed to connect to MongoDB instance using the connection string from the config: " ,
234+ error
235+ ) ;
236+ throw new Error ( "Failed to connect to MongoDB instance using the connection string from the config" ) ;
237+ }
238+ }
239+ }
222240}
0 commit comments