# Implementation Plan: Automatic Re-authentication with MFA ## Problem The Monarch Money API token expires periodically. Currently, there is no automatic refresh mechanism, causing the MCP server to fail until manually re-authenticated. ## Objective Implement automatic re-authentication functionality that detects expired tokens and transparently re-authenticates using stored credentials and an MFA secret (TOTP). ## Proposed Solution Use `pyotp` to generate MFA codes programmatically and wrap API calls with retry logic that handles authentication failures. ## Prerequisites - `pyotp` library (Installed) - User needs to add `MONARCH_MFA_SECRET` to their environment variables. ## Implementation Steps ### 1. Update `auth.py` - Add logic to handle re-authentication using `pyotp`. - Implement a `login_with_mfa()` function that: - Uses `MONARCH_EMAIL` and `MONARCH_PASSWORD`. - Uses `MONARCH_MFA_SECRET` with `pyotp` to generate a TOTP code if MFA is requested. - Updates the active client session. ### 2. Create Re-authentication Decorator/Wrapper - Create a Python decorator (e.g., `@retry_on_auth_error`) in `auth.py` or a new utility module. - This decorator will: 1. Execute the decorated function (API call). 2. Catch specific exceptions indicating authentication failure (e.g., `LoginFailedException`, `RequestFailedException` with 401/403 status). 3. Call the re-authentication logic. 4. Retry the original function. ### 3. Apply Wrapper in `server.py` - Apply the decorator to the MCP tool implementations (`get_accounts`, `get_transactions`, etc.) or wrap the client calls to ensure they auto-recover from expired tokens. ### 4. Update `login_setup.py` - Modify the setup script to display the MFA Secret (seed) to the user during the initial login process. - Instruct the user to save this as `MONARCH_MFA_SECRET` in their `.env` file alongside `MONARCH_TOKEN`. ## Verification - Test by simulating an expired token and verifying that the system automatically logs in using the MFA secret and completes the request.