# Spend Analyzer MCP - Deployment Guide This guide covers deploying the Spend Analyzer MCP to Modal.com with Claude and SambaNova Cloud API integration. ## Prerequisites 1. **Modal Account**: Sign up at [modal.com](https://modal.com) 2. **API Keys**: - Anthropic API key for Claude - SambaNova Cloud API key 3. **Email Credentials**: App-specific passwords for email access ## Setup Instructions ### 1. Install Modal CLI ```bash pip install modal ``` ### 2. Authenticate with Modal ```bash modal token new ``` ### 3. Create Modal Secrets Create the required secrets in your Modal dashboard or via CLI: #### Anthropic API Key ```bash modal secret create anthropic-api-key ANTHROPIC_API_KEY=your_claude_api_key_here ``` #### SambaNova API Key ```bash modal secret create sambanova-api-key SAMBANOVA_API_KEY=your_sambanova_api_key_here ``` #### Email Credentials ```bash modal secret create email-credentials \ EMAIL_USER=your_email@gmail.com \ EMAIL_PASS=your_app_password \ IMAP_SERVER=imap.gmail.com ``` ### 4. Deploy to Modal ```bash # Deploy the application modal deploy modal_deployment.py # Or run locally for testing modal run modal_deployment.py ``` ## API Providers ### Claude (Anthropic) - **Model**: claude-3-sonnet-20240229 - **Features**: Advanced reasoning, financial analysis - **Setup**: Get API key from [console.anthropic.com](https://console.anthropic.com) ### SambaNova Cloud - **Model**: Meta-Llama-3.1-8B-Instruct - **Features**: Fast inference, cost-effective - **Setup**: Get API key from [cloud.sambanova.ai](https://cloud.sambanova.ai) - **API Format**: OpenAI-compatible ## Available Modal Functions ### 1. `process_bank_statements` Process bank statements from email attachments. **Parameters:** - `email_config`: Email configuration dict - `days_back`: Number of days to look back (default: 30) - `passwords`: Optional PDF passwords dict **Returns:** - Processed statements list - Transaction analysis - Error handling for password-protected PDFs ### 2. `analyze_uploaded_statements` Analyze directly uploaded PDF statements. **Parameters:** - `pdf_contents`: Dict of filename -> PDF bytes - `passwords`: Optional PDF passwords dict **Returns:** - Analysis results - Transaction categorization - Financial insights ### 3. `get_ai_analysis` Get AI-powered financial analysis. **Parameters:** - `analysis_data`: Financial data dict - `user_question`: Optional specific question - `provider`: "claude" or "sambanova" (default: "claude") **Returns:** - AI analysis text - Usage statistics - Provider information ### 4. `save_user_data` / `load_user_data` Persistent storage for user analysis data. **Features:** - User-specific data isolation - Timestamp tracking - JSON serialization ### 5. `mcp_webhook` MCP protocol endpoint for external integrations. **Features:** - Tool registration - Resource management - Error handling ## Environment Variables The following environment variables are automatically available in Modal functions: ```bash ANTHROPIC_API_KEY=your_claude_key SAMBANOVA_API_KEY=your_sambanova_key EMAIL_USER=your_email EMAIL_PASS=your_app_password IMAP_SERVER=your_imap_server ``` ## Usage Examples ### Basic Deployment Test ```python import modal # Test the deployment app = modal.App.lookup("spend-analyzer-mcp-bmt") get_ai_analysis = app["get_ai_analysis"] # Test with sample data test_data = { "spending_insights": [ { "category": "Food & Dining", "total_amount": 500.0, "transaction_count": 15 } ], "recommendations": ["Consider reducing dining expenses"] } result = get_ai_analysis.remote( analysis_data=test_data, user_question="How can I save money on food?", provider="claude" ) print(result) ``` ### Email Processing ```python email_config = { "email": "your_email@gmail.com", "password": "your_app_password", "imap_server": "imap.gmail.com" } result = process_bank_statements.remote( email_config=email_config, days_back=30 ) print(f"Processed {result['total_transactions']} transactions") ``` ### PDF Analysis ```python # Read PDF file with open("statement.pdf", "rb") as f: pdf_content = f.read() pdf_contents = {"statement.pdf": pdf_content} result = analyze_uploaded_statements.remote( pdf_contents=pdf_contents, passwords={"statement.pdf": "optional_password"} ) print(result['analysis']) ``` ## Monitoring and Logs ### View Logs ```bash modal logs spend-analyzer-mcp-bmt ``` ### Monitor Functions ```bash modal stats spend-analyzer-mcp-bmt ``` ### View Volumes ```bash modal volume list ``` ## Troubleshooting ### Common Issues 1. **Import Errors**: Ensure all dependencies are in the Modal image 2. **Secret Access**: Verify secrets are created with correct names 3. **PDF Processing**: Check file permissions and password requirements 4. **API Limits**: Monitor usage for both Claude and SambaNova ### Debug Mode Enable debug logging in Modal functions: ```python import logging logging.basicConfig(level=logging.DEBUG) ``` ### Local Testing Test functions locally before deployment: ```bash modal run modal_deployment.py::main ``` ## Security Considerations 1. **API Keys**: Store in Modal secrets, never in code 2. **Email Passwords**: Use app-specific passwords 3. **PDF Data**: Processed in memory, not stored permanently 4. **User Data**: Isolated by user ID in persistent storage ## Cost Optimization 1. **Function Timeouts**: Set appropriate timeouts for each function 2. **Memory Allocation**: Adjust based on PDF processing needs 3. **API Provider**: Choose between Claude (quality) and SambaNova (cost) 4. **Batch Processing**: Process multiple PDFs in single function call ## Scaling Modal automatically handles scaling based on demand: - **Cold Starts**: ~2-3 seconds for new containers - **Warm Containers**: Sub-second response times - **Concurrent Requests**: Automatically scaled - **Resource Limits**: Configurable per function ## Integration with MCP The deployment includes a webhook endpoint for MCP integration: ``` POST https://your-modal-app.modal.run/mcp_webhook ``` This enables integration with Claude Desktop and other MCP clients. ## Support For deployment issues: 1. Check Modal logs and documentation 2. Verify API key permissions 3. Test with minimal examples 4. Contact Modal support for platform issues ## Next Steps After successful deployment: 1. Test all functions with real data 2. Set up monitoring and alerts 3. Configure backup strategies 4. Implement additional security measures 5. Scale based on usage patterns