- 
                Notifications
    You must be signed in to change notification settings 
- Fork 153
chore: extend library interfaces to allow injecting a custom connection error handler MCP-132 #502
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
          
     Merged
      
      
            himanshusinghs
  merged 5 commits into
  main
from
chore/MCP-132-injectable-connection-error-handler
  
      
      
   
  Sep 3, 2025 
      
    
  
     Merged
                    Changes from 4 commits
      Commits
    
    
            Show all changes
          
          
            5 commits
          
        
        Select commit
          Hold shift + click to select a range
      
      2c7351f
              
                chore: allows injecting a connection error handler
              
              
                himanshusinghs b607231
              
                Apply suggestion from @Copilot
              
              
                himanshusinghs c83c4db
              
                chore: expose ConnectionErrorHandler type through lib
              
              
                himanshusinghs 2b725e7
              
                chore: export types for lib
              
              
                himanshusinghs ed6adc6
              
                chore: PR feedback
              
              
                himanshusinghs File filter
Filter by extension
Conversations
          Failed to load comments.   
        
        
          
      Loading
        
  Jump to
        
          Jump to file
        
      
      
          Failed to load files.   
        
        
          
      Loading
        
  Diff view
Diff view
There are no files selected for viewing
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,82 @@ | ||
| import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js"; | ||
| import { ErrorCodes, type MongoDBError } from "./errors.js"; | ||
| import type { AnyConnectionState } from "./connectionManager.js"; | ||
| import type { ToolBase } from "../tools/tool.js"; | ||
|  | ||
| export type ConnectionErrorHandler = ( | ||
| error: MongoDBError<ErrorCodes.NotConnectedToMongoDB | ErrorCodes.MisconfiguredConnectionString>, | ||
| additionalContext: ConnectionErrorHandlerContext | ||
| ) => ConnectionErrorUnhandled | ConnectionErrorHandled; | ||
|  | ||
| export type ConnectionErrorHandlerContext = { availableTools: ToolBase[]; connectionState: AnyConnectionState }; | ||
| export type ConnectionErrorUnhandled = { errorHandled: false }; | ||
| export type ConnectionErrorHandled = { errorHandled: true; result: CallToolResult }; | ||
|  | ||
| export const connectionErrorHandler: ConnectionErrorHandler = (error, { availableTools, connectionState }) => { | ||
| const connectTools = availableTools | ||
| .filter((t) => t.operationType === "connect") | ||
| .sort((a, b) => a.category.localeCompare(b.category)); // Sort Atlas tools before MongoDB tools | ||
|  | ||
| // Find the first Atlas connect tool if available and suggest to the LLM to use it. | ||
| // Note: if we ever have multiple Atlas connect tools, we may want to refine this logic to select the most appropriate one. | ||
| const atlasConnectTool = connectTools?.find((t) => t.category === "atlas"); | ||
| const llmConnectHint = atlasConnectTool | ||
| ? `Note to LLM: prefer using the "${atlasConnectTool.name}" tool to connect to an Atlas cluster over using a connection string. Make sure to ask the user to specify a cluster name they want to connect to or ask them if they want to use the "list-clusters" tool to list all their clusters. Do not invent cluster names or connection strings unless the user has explicitly specified them. If they've previously connected to MongoDB using MCP, you can ask them if they want to reconnect using the same cluster/connection.` | ||
| : "Note to LLM: do not invent connection strings and explicitly ask the user to provide one. If they have previously connected to MongoDB using MCP, you can ask them if they want to reconnect using the same connection string."; | ||
|  | ||
| const connectToolsNames = connectTools?.map((t) => `"${t.name}"`).join(", "); | ||
| const additionalPromptForConnectivity: { type: "text"; text: string }[] = []; | ||
|  | ||
| if (connectionState.tag === "connecting" && connectionState.oidcConnectionType) { | ||
| additionalPromptForConnectivity.push({ | ||
| type: "text", | ||
| text: `The user needs to finish their OIDC connection by opening '${connectionState.oidcLoginUrl}' in the browser and use the following user code: '${connectionState.oidcUserCode}'`, | ||
| }); | ||
| } else { | ||
| additionalPromptForConnectivity.push({ | ||
| type: "text", | ||
| text: connectToolsNames | ||
| ? `Please use one of the following tools: ${connectToolsNames} to connect to a MongoDB instance or update the MCP server configuration to include a connection string. ${llmConnectHint}` | ||
| : "There are no tools available to connect. Please update the configuration to include a connection string and restart the server.", | ||
| }); | ||
| } | ||
|  | ||
| switch (error.code) { | ||
| case ErrorCodes.NotConnectedToMongoDB: | ||
| return { | ||
| errorHandled: true, | ||
| result: { | ||
| content: [ | ||
| { | ||
| type: "text", | ||
| text: "You need to connect to a MongoDB instance before you can access its data.", | ||
| }, | ||
| ...additionalPromptForConnectivity, | ||
| ], | ||
| isError: true, | ||
| }, | ||
| }; | ||
| case ErrorCodes.MisconfiguredConnectionString: | ||
| return { | ||
| errorHandled: true, | ||
| result: { | ||
| content: [ | ||
| { | ||
| type: "text", | ||
| text: "The configured connection string is not valid. Please check the connection string and confirm it points to a valid MongoDB instance.", | ||
| }, | ||
| { | ||
| type: "text", | ||
| text: connectTools | ||
| ? `Alternatively, you can use one of the following tools: ${connectToolsNames} to connect to a MongoDB instance. ${llmConnectHint}` | ||
| : "Please update the configuration to use a valid connection string and restart the server.", | ||
| }, | ||
| ], | ||
| isError: true, | ||
| }, | ||
| }; | ||
|  | ||
| default: | ||
| return { errorHandled: false }; | ||
| } | ||
| }; | ||
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
      
      Oops, something went wrong.
        
    
  
      
      Oops, something went wrong.
        
    
  
  Add this suggestion to a batch that can be applied as a single commit.
  This suggestion is invalid because no changes were made to the code.
  Suggestions cannot be applied while the pull request is closed.
  Suggestions cannot be applied while viewing a subset of changes.
  Only one suggestion per line can be applied in a batch.
  Add this suggestion to a batch that can be applied as a single commit.
  Applying suggestions on deleted lines is not supported.
  You must change the existing code in this line in order to create a valid suggestion.
  Outdated suggestions cannot be applied.
  This suggestion has been applied or marked resolved.
  Suggestions cannot be applied from pending reviews.
  Suggestions cannot be applied on multi-line comments.
  Suggestions cannot be applied while the pull request is queued to merge.
  Suggestion cannot be applied right now. Please check back later.
  
    
  
    
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This entire file is a cut of existing logic in MongodbToolBase.