# CLAUDE.md - MCP Server ROI Development Guide
## Project Overview
This is an MCP (Model Context Protocol) server for AI ROI prediction and tracking, built with TypeScript, Supabase, and advanced financial modeling capabilities including Monte Carlo simulations and real-time industry benchmarks.
## Recent Improvements (2025-07-01)
### 🎉 Major User Experience Enhancements
1. **Input Flexibility**
- Accept natural language inputs for all tools
- Smart defaults reduce required fields by 80%
- Fuzzy matching for enums (e.g., "tech" → "technology")
- Support for various formats ("$50k", "85%", "6 months")
2. **Natural Language Processing**
- All tools now support conversational input
- Intent detection automatically routes to correct tool
- Context awareness for follow-up questions
- Entity extraction from unstructured text
3. **User-Friendly Errors**
- Technical errors transformed to helpful guidance
- "Did you mean?" suggestions
- Examples included in error messages
- Auto-correction for common mistakes
4. **LLM Integration**
- Self-documenting tools with embedded examples
- New `help` and `get_examples` utility tools
- Structured responses optimized for LLM parsing
- Comprehensive prompt engineering guide
See `IMPROVEMENTS_SUMMARY.md` for full details.
## Current Implementation Status (as of 2025-06-24)
### ✅ Completed Features
1. **Core Architecture**
- TypeScript project with full type safety
- MCP SDK integration for protocol compliance
- Supabase PostgreSQL for cloud persistence (with admin access support)
- Piscina worker threads for parallel Monte Carlo simulations
- Zod schemas for runtime validation
- Comprehensive error handling with retry logic and transaction management
2. **Financial Calculators**
- NPV (Net Present Value) calculation
- IRR (Internal Rate of Return) using Newton's method
- Payback period with linear interpolation
- 5-year ROI projections
- Cash flow generation with implementation and ramp-up periods
- Break-even date calculation
3. **MCP Tools Implemented**
- `predict_roi`: Full ROI projection with use case aggregation
- Transaction management with rollback capabilities
- Retry logic with exponential backoff
- Real-time benchmark integration
- `compare_projects`: Multi-project comparative analysis
- ML-powered insights and predictions
- Industry benchmark comparisons
- Synergy identification between projects
- `quick_assessment`: Rapid evaluation with industry benchmarks
- Natural language input processing
- Voice output generation for accessibility
- Scenario generation based on industry patterns
4. **Data Models**
- Project schema with industry classification
- Use case modeling (current state → future state)
- Financial projections with confidence intervals
- Monte Carlo simulation results
- Metrics tracking for actual vs projected
5. **Industry Benchmarks**
- **Perplexity Sonar API Integration**: Real-time industry data
- **Financial Modeling Prep API**: Financial market benchmarks
- **Static Benchmarks**: Fallback data for 7 industries
- **Benchmark Aggregator**: Consensus calculation from multiple sources
6. **ML & AI Features**
- **ML Comparison Engine**: Pattern recognition across projects
- **Success probability prediction**: Based on historical patterns
- **Risk scoring**: Multi-factor risk assessment
- **Synergy detection**: Identifies value-add opportunities
- **Natural Language Processing**: Parse requirements from text
7. **Production Features**
- **Database Access**: Admin client support for server-side operations
- **Environment Configuration**: Comprehensive .env setup
- **Logging**: Structured logging with context
- **Error Handling**: Graceful degradation and user-friendly messages
- **Caching**: In-memory caching for benchmark data
### 🚧 Features Not Yet Implemented
1. **Additional MCP Tools**
- `run_monte_carlo_simulation`: Standalone Monte Carlo analysis
- `track_roi_metrics`: Actual metrics tracking
- `generate_roi_dashboard`: Executive dashboard generation
- `calculate_payback_period`: Quick payback calculation
2. **Advanced Features**
- Real-time metric ingestion from external systems
- Dashboard export (HTML, PDF, PowerPoint)
- Detailed sensitivity analysis
- Attribution engine for variance analysis
3. **Integrations**
- PowerBI connector
- Tableau data source
- Google Sheets automation
- Slack notifications
## Development Guidelines
### 📁 File Organization
All development progress and improvements MUST be documented in the following files:
1. **`/DEVELOPMENT_LOG.md`** - Chronological log of all changes
2. **`/FEATURES.md`** - Detailed feature documentation
3. **`/API_REFERENCE.md`** - Tool specifications and examples
4. **`/ARCHITECTURE.md`** - Technical design decisions
### 📝 Documentation Requirements
When making ANY changes or improvements:
1. **Before Starting Work**:
```markdown
## [Date] - [Feature/Fix Name]
### Objective
[Clear description of what needs to be done]
### Approach
[Technical approach and rationale]
```
2. **After Completing Work**:
```markdown
### Changes Made
- [List all files modified/created]
- [Key code changes]
### Testing
- [How it was tested]
- [Results]
### Next Steps
- [Any follow-up needed]
```
### 🔧 Technical Standards
1. **TypeScript Best Practices**
- Always use Zod schemas for validation
- Export types alongside schemas
- Use strict typing (no `any` unless necessary)
- Implement proper error types
2. **Error Handling**
- Wrap all async operations in try-catch
- Provide meaningful error messages
- Log errors with context
- Use custom error classes
3. **Performance**
- Use worker threads for CPU-intensive tasks
- Implement timeouts for long operations (30s default)
- Cache calculations where appropriate
- Batch database operations
4. **Security**
- Never commit `.env` files
- Validate all inputs with Zod
- Use Supabase admin client for server operations
- Sanitize error messages for users
## Current Technical Stack
### Dependencies
```json
{
"@modelcontextprotocol/sdk": "^1.12.3",
"@supabase/supabase-js": "^2.50.0",
"dotenv": "^16.5.0",
"piscina": "^5.1.0",
"zod": "^3.25.64"
}
```
### Environment Variables Required
```bash
# Required
SUPABASE_URL=your_supabase_project_url
SUPABASE_ANON_KEY=your_supabase_anon_key
# Required for full functionality
SUPABASE_SERVICE_KEY=your_supabase_service_key
PERPLEXITY_API_KEY=your_perplexity_api_key
# Optional
FMP_API_KEY=your_fmp_api_key
LOG_LEVEL=info
WORKER_POOL_SIZE=4
MAX_SIMULATION_ITERATIONS=100000
```
### Database Schema
The application uses Supabase PostgreSQL with the following main tables:
- `projects`: Core project information
- `use_cases`: Individual use cases with ROI calculations
- `projections`: Financial projections and Monte Carlo results
- `metrics`: Actual performance tracking (future)
### Key Architectural Decisions
1. **MCP Server Architecture**
- Uses admin client (`mcpDb`) for all database operations
- No user authentication required (server-side tool)
- All operations are atomic with rollback support
2. **Transaction Management**
- Custom `TransactionManager` class for atomic operations
- Rollback stack for cleanup on failures
- Retry logic with exponential backoff
3. **Benchmark Integration**
- Multiple data sources with fallback hierarchy
- Consensus calculation with confidence weighting
- 5-minute cache TTL for external APIs
4. **ML Integration**
- Simplified ML models for quick predictions
- Pattern matching across similar projects
- Risk factors based on industry patterns
## Testing & Quality Assurance
### Test Coverage
- ✅ Unit tests for financial calculators
- ✅ Integration tests for all MCP tools
- ✅ End-to-end test suite (`test-comprehensive.ts`)
- ✅ Database connection tests
- ✅ Error handling validation
### Performance Benchmarks
- Tool execution: 1-3 seconds average
- Perplexity API: ~15 seconds for complex queries
- Database operations: < 500ms
- Monte Carlo (100k iterations): < 5 seconds
## Recent Changes (2025-06-24)
1. **Removed Redis Implementation**
- Caching now handled in-memory
- Simplified architecture for MCP use case
2. **Enhanced Tools Promoted to Standard**
- Removed old tool versions
- Enhanced versions now the default implementation
3. **Database Access Fixed**
- Implemented `mcpDb` export for admin access
- All tools now use service key when available
4. **Comprehensive Testing**
- All features tested and verified working
- Graceful fallback for missing API keys
## Maintenance Notes
1. **Monte Carlo Worker**: Located at `/src/workers/monte-carlo-worker.ts`
- Uses simple Linear Congruential Generator
- Supports normal, uniform, and beta distributions
- Processes in batches for efficiency
2. **Financial Engine**: Core logic in `/src/core/calculators/`
- All calculations assume monthly periods
- Default discount rate: 10% annual (0.83% monthly)
- Implementation + ramp-up typically 6 months
3. **Benchmark Data**:
- Perplexity Sonar: Real-time data (when API key provided)
- Static fallbacks: Conservative estimates
- Cache duration: 5 minutes
## Production Deployment
### Prerequisites
1. Supabase project with all tables created
2. Service key for admin operations
3. Perplexity API key for real-time benchmarks
4. Node.js 18+ environment
### Quick Start
```bash
# Clone and install
git clone https://github.com/SPAIK-io/mcp-server-roi.git
cd mcp-server-roi
npm install
# Configure environment
cp .env.example .env
# Edit .env with your keys
# Build and start
npm run build
npm start
```
### Claude Desktop Integration
Add to `~/Library/Application Support/Claude/claude_desktop_config.json`:
```json
{
"mcpServers": {
"roi": {
"command": "node",
"args": ["/path/to/mcp-server-roi/dist/index.js"],
"env": {
"SUPABASE_URL": "your_url",
"SUPABASE_ANON_KEY": "your_key",
"SUPABASE_SERVICE_KEY": "your_service_key",
"PERPLEXITY_API_KEY": "your_perplexity_key"
}
}
}
}
```
## Contact & Support
- Repository: https://github.com/SPAIK-io/mcp-server-roi
- Issues: https://github.com/SPAIK-io/mcp-server-roi/issues
---
**IMPORTANT**: This file should be updated with EVERY significant change to the codebase. It serves as the primary reference for understanding the system's current state and development history.