Error Handling Mechanisms
Relevant source files
The following files were used as context for generating this wiki page:
Error handling in the mbbank-mcp project is designed to ensure robust communication between the Model Context Protocol (MCP) server and the underlying MBBank API. The mechanisms range from early validation of environment variables and credentials to managing transient states during multi-step financial transactions.
The system utilizes a combination of explicit validation checks, try-except blocks for runtime exceptions, and state-based timeout management. These ensure that the server provides descriptive feedback to the client while maintaining internal consistency.
Sources: mbbank_mcp/core.py, mbbank_mcp/main.py
Startup and Configuration Validation
Before the MCP server starts, the entry point performs critical checks on the provided credentials and environment configuration. If requirements are not met, the process terminates early to prevent unauthenticated or broken states.
- Credential Verification: The application checks for
usernameandpasswordfrom either CLI arguments or environment variables (MBBANK_USERNAME,MBBANK_PASSWORD). - Authentication Check: An explicit
_authenticate()call is made during startup. If this fails, the server does not proceed to run. - Stdio/SSE Mode Handling: The server supports different transport layers (Stdio and SSE). Configuration errors related to ports or hosts are handled via
uvicornandclickdefaults and validation.
The diagram shows the sequential validation of credentials and authentication before the server enters its operational loop.
Sources: mbbank_mcp/main.py:36-50, README.md:15-32
Transactional Error Handling
The most complex error handling occurs within the money transfer tools, which involve a two-step process: initiating a transfer (start_transfer) and verifying it with an OTP (verify_transfer).
Session State and Expiration
To prevent memory leaks and handle abandoned transactions, the server implements a timeout mechanism for transfer sessions.
- Session Validity: Sessions are stored in a
transfer_managerdictionary with a 120-second expiration. - Automatic Cleanup: An asynchronous background task
_remove_expired_transfersis spawned to delete expired session IDs after a buffer period (130 seconds). - Validation Checks: The
verify_transfertool explicitly checks if the session ID (sid) exists and if it has exceeded the 120-second window.
Runtime Exception Management
During the execution of the transfer method, any exceptions raised by the underlying mbbank-lib are caught within a try...except block to return a human-readable error message rather than crashing the tool call.
| Error Scenario | Action taken | Response Message |
|---|---|---|
| Missing Session ID | Immediate return | "The transfer session has expired or is invalid..." |
| Expired Session ID | Delete SID from manager | "The transfer session has expired. Please start a new transfer." |
| Library Exception | Delete SID from manager | "Transfer failed: {error_details}" |
Sources: mbbank_mcp/core.py:87-108
Data Consistency and Type Safety
The project uses Pydantic models in modals.py to act as a proxy for raw API responses. This provides a layer of error resilience against upstream API changes by defining expected structures and handling optional fields.
- Optional Fields: Many fields in the data models are marked as
Optional, allowing the server to handle missing data from the MBBank API without failing during object instantiation. - Error Fields in Models: Certain models like
SavingDetailsModelinclude an expliciterrorfield to capture and transport domain-specific error messages from the bank's response.
This diagram illustrates how the SavingDetailsModel incorporates an optional error field to handle cases where details cannot be retrieved.
Sources: mbbank_mcp/modals.py:73-90
Logging and Diagnostics
The application distinguishes between standard output and diagnostic messages to ensure compatibility with the MCP Stdio transport, which uses stdout for protocol messages.
- Stderr for Logs: A dedicated
eprintfunction is used to route diagnostic information (like "Authenticated successfully") tosys.stderr, preventing interference with the JSON-RPC stream onstdout. - Uvicorn Logging: In SSE mode, the server uses
uvicorn's internal logging, which is configurable via theFastMCPsettings.
Sources: mbbank_mcp/main.py:19-24, mbbank_mcp/main.py:53
Summary of Error Codes and Conditions
| Component | Error Condition | Handling Logic |
|---|---|---|
| CLI | Missing --username/--password | System exit with code 1 |
| Core | sid collision | Loop and regenerate os.urandom(4).hex() |
| Tools | Invalid Date Format | strptime will raise ValueError (bubble up to FastMCP) |
| Tools | Account Not Found | Library exception caught in verify_transfer |
| Tools | Inactive Cards | Filtered out in get_cards (card.stsCard != "New Card") |
Sources: mbbank_mcp/core.py:65-68, mbbank_mcp/core.py:126-127, mbbank_mcp/core.py:168, mbbank_mcp/main.py:39-41