@@ -202,7 +202,7 @@ const extractDbNameFromConnectionString = (uri) => {
202202}
203203
204204const resolveMongoUri = ( uriOrAlias ) => {
205- if ( uriOrAlias . includes ( '://' ) || uriOrAlias . includes ( '/' ) || uriOrAlias . includes ( ' @') ) {
205+ if ( uriOrAlias . includes ( '://' ) || uriOrAlias . includes ( '@' ) ) {
206206 return uriOrAlias
207207 }
208208
@@ -213,7 +213,7 @@ const resolveMongoUri = (uriOrAlias) => {
213213 return uri
214214 }
215215
216- return uriOrAlias
216+ throw new Error ( `" ${ uriOrAlias } " is not a valid MongoDB URI or connection alias.` )
217217}
218218
219219const obfuscateMongoUri = ( uri ) => {
@@ -1293,6 +1293,17 @@ const registerTools = (server) => {
12931293 async ( { uri, validateConnection } ) => {
12941294 return withErrorHandling ( async ( ) => {
12951295 try {
1296+ if ( ! uri . includes ( '://' ) && ! uri . includes ( '@' ) && ! mongoUriMap . has ( uri . toLowerCase ( ) ) ) {
1297+ if ( await isDatabaseName ( uri ) ) {
1298+ return {
1299+ content : [ {
1300+ type : 'text' ,
1301+ text : `It seems you're trying to switch to database "${ uri } " rather than connect to a new MongoDB instance. Please use the "use-database" tool instead.`
1302+ } ]
1303+ }
1304+ }
1305+ }
1306+
12961307 const resolvedUri = resolveMongoUri ( uri )
12971308 await changeConnection ( resolvedUri , validateConnection === 'true' )
12981309 return {
@@ -3160,6 +3171,29 @@ const withErrorHandling = async (operation, errorMessage, defaultValue = null) =
31603171 }
31613172}
31623173
3174+ const isDatabaseName = async ( name ) => {
3175+ try {
3176+ const dbs = await listDatabases ( )
3177+ if ( dbs . some ( db => db . name === name ) ) return true
3178+
3179+ if ( name . length > 0 && name . length < 64 &&
3180+ ! name . includes ( '/' ) && ! name . includes ( ':' ) ) {
3181+ const dbPatterns = [
3182+ / ^ s a m p l e _ / ,
3183+ / ^ t e s t / ,
3184+ / ^ d b / ,
3185+ / ^ a d m i n $ | ^ l o c a l $ | ^ c o n f i g $ /
3186+ ]
3187+
3188+ if ( dbPatterns . some ( pattern => pattern . test ( name ) ) ) return true
3189+ }
3190+
3191+ return false
3192+ } catch ( error ) {
3193+ return false
3194+ }
3195+ }
3196+
31633197const listDatabases = async ( ) => {
31643198 log ( 'DB Operation: Listing databases…' )
31653199 const adminDb = mongoClient . db ( 'admin' )
0 commit comments