npm package: @spaik/mcp-server-roi
Description: MCP server for AI ROI prediction and tracking with Monte Carlo simulations
Author: SPAIK
Latest version: 1.3.1

# @spaik/mcp-server-roi

[![npm version](https://badge.fury.io/js/@spaik%2Fmcp-server-roi.svg)](https://www.npmjs.com/package/@spaik/mcp-server-roi)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

A Model Context Protocol (MCP) server for AI ROI prediction and tracking with Monte Carlo simulations, real-time industry benchmarks, and ML-powered insights. Now with **mandatory Dutch market validation** and **natural language support**!

## 🆕 What's New in v1.3.1

### Bug Fixes
- Fixed critical "Cannot read properties of undefined (reading 'industry')" error
- Enhanced input validation for all tools
- Improved error messages for better user experience

## What's New in v1.3.0

### Breaking Changes
- **Removed quick-assessment tool**: Replaced by enhanced predict_roi with Dutch validation
- **PERPLEXITY_API_KEY now required**: Mandatory for Dutch market validation

### New Features
- **Dutch Market Validation**: All predictions validated against Dutch industry averages
- **Automatic Value Adjustment**: Unrealistic values (>3x industry average) are intelligently adjusted
- **Market-Specific Insights**: Dutch trends and patterns incorporated in analysis
- **Enhanced Confidence Scoring**: Based on alignment with Dutch market data

### From v1.2.0
- **Natural Language Input**: Use conversational text instead of complex JSON
- **Smart Defaults**: 80% reduction in required fields
- **Flexible Formats**: Accept "$50k", "85%", "6 months" formats

## Key Features

### 🎯 Core Capabilities
- **ROI Predictions**: Generate detailed 5-year financial projections with Dutch market validation
- **Monte Carlo Simulations**: Advanced risk analysis with multiple distribution models
- **Multi-Project Comparison**: Compare up to 10 projects with ML-powered insights
- **Dutch Market Validation**: Mandatory validation against Dutch industry benchmarks
- **Industry Benchmarks**: Real-time data via Perplexity API integration

### 🤖 AI & ML Features
- **Universal NLP**: All tools support natural language input
- **Intent Detection**: Automatically routes to the correct tool
- **Context Awareness**: Maintains conversation history
- **ML Comparison Engine**: Pattern recognition and success prediction
- **Voice Output**: Accessibility-friendly summaries
- **Synergy Detection**: Identify value-add opportunities between projects
- **Risk Scoring**: Multi-factor risk assessment with confidence levels

### 💼 Financial Metrics
- **NPV** (Net Present Value) with customizable discount rates
- **IRR** (Internal Rate of Return) using Newton's method
- **Payback Period** with linear interpolation
- **Break-even Analysis** with monthly precision
- **Cash Flow Projections** with ramp-up modeling

### 🔄 Production Features
- **Transaction Management**: Atomic operations with rollback
- **Retry Logic**: Exponential backoff for resilience
- **Real-time Benchmarks**: Perplexity Sonar API integration
- **Graceful Degradation**: Fallback to static data when APIs unavailable
- **Comprehensive Logging**: Structured logs with context

## Installation

### From npm
```bash
npm install @spaik/mcp-server-roi
```

### From source
```bash
git clone https://github.com/SPAIK-io/mcp-server-roi.git
cd mcp-server-roi
npm install
npm run build
```

## Quick Start

### Simple Natural Language Example

Instead of complex JSON, just describe what you need:

```javascript
// Using natural language
await predictROI({
  natural_language_input: "Help ACME Corp automate their customer service. They're in retail, handle 5000 emails monthly taking 15 minutes each. Budget is around $100k and we need this done in 6 months."
});

// Or use the simplified format
await predictROI({
  client: "ACME Corp",
  project: "Customer Service Automation",
  industry: "retail",
  budget: "$100k",
  timeline: "6 months"
});
```

### Get Help Anytime

```javascript
// Get examples for any tool
await getExamples({ tool_name: "predict_roi" });

// Get interactive help
await help({ query: "How do I calculate ROI for a healthcare project?" });
```

## Configuration

### 1. Environment Setup

Create a `.env` file based on `.env.example`:

```bash
cp .env.example .env
```

### 2. Required Environment Variables

```env
# Required - Supabase Configuration
SUPABASE_URL=https://xxxxxxxxxxxxx.supabase.co
SUPABASE_ANON_KEY=your_supabase_anon_key

# Required for full functionality
SUPABASE_SERVICE_KEY=your_service_key  # Admin access
PERPLEXITY_API_KEY=your_perplexity_key # Real-time benchmarks

# Optional - Enhanced Features
FMP_API_KEY=your_fmp_key              # Financial market data
LOG_LEVEL=info                        # debug|info|warn|error
WORKER_POOL_SIZE=4                    # CPU cores
MAX_SIMULATION_ITERATIONS=100000      # Monte Carlo precision
```

### 3. Database Setup

Run these SQL scripts in your Supabase SQL editor (in order):

1. `database/schema.sql` - Core tables and indexes
2. `database/001_security_update.sql` - Security and RLS policies
3. `database/002_transactional_functions.sql` - Transaction functions

## Usage with Claude Desktop

1. **Database Setup** (Required):
   ```bash
   # Apply required database functions
   # See database/APPLY_FUNCTIONS.md for detailed instructions
   
   # Option 1: Via Supabase Dashboard
   # Copy contents of database/002_transactional_functions.sql
   # Paste into SQL Editor and run
   
   # Option 2: Using npm script (requires service key)
   npm run apply-db-functions
   ```

2. **Claude Desktop Configuration**:
   
   Add to your configuration file (`~/Library/Application Support/Claude/claude_desktop_config.json`):

   ```json
   {
     "mcpServers": {
       "roi": {
         "command": "node",
         "args": ["/absolute/path/to/mcp-server-roi/dist/index.js"],
         "env": {
           "SUPABASE_URL": "your_supabase_url",
           "SUPABASE_ANON_KEY": "your_anon_key",
           "SUPABASE_SERVICE_KEY": "your_service_key",
           "PERPLEXITY_API_KEY": "your_perplexity_key",
           "LOG_LEVEL": "info"
         }
       }
     }
   }
   ```

## Available Tools

### 1. predict_roi
Generate comprehensive ROI predictions with Monte Carlo simulations.

**🆕 Natural Language Example:**
```
"Help ACME Bank reduce fraud losses. They process 1M transactions monthly with 0.5% fraud rate and $500 average loss. Need real-time detection system. Budget is $200k plus training."
```

**Simplified JSON Example:**
```json
{
  "client": "ACME Bank",
  "project": "Fraud Detection System",
  "industry": "finance",  // or "financial_services" 
  "budget": "$200k",
  "timeline": "6 months"
}
```

**Traditional Example (still supported):**
```
"Create an ROI prediction for ACME Corp's fraud detection system:
- Industry: Financial Services
- Use Case: Transaction monitoring
  - Current: 1M transactions/month, 0.5% fraud rate, $500 avg loss
  - Future: 95% detection rate, real-time processing
- Implementation: $200k software, 1000 dev hours, $50k training
- Timeline: 6 months"
```

**Key Parameters:**
- `organization_id`: Organization identifier
- `project`: Project details with industry classification
- `use_cases`: Array of current → future state transformations
- `implementation_costs`: Comprehensive cost breakdown
- `timeline_months`: 1-120 months
- `enable_benchmarks`: Use real-time industry data

### 2. compare_projects
Compare multiple projects with ML-powered insights and visualizations.

**🆕 Natural Language Example:**
```
"Compare customer service automation vs inventory optimization vs predictive maintenance projects for ACME Corp"
```

**Simplified Example:**
```json
{
  "projects": ["Customer Service Bot", "Smart Inventory", "Machine Monitoring"],
  "focus": "roi and risk"
}
```

**Traditional Example:**
```
"Compare these three AI projects:
- Project A: Customer service automation (ID: xxx)
- Project B: Inventory optimization (ID: yyy)  
- Project C: Predictive maintenance (ID: zzz)
Include risk analysis and synergy opportunities"
```

**Key Parameters:**
- `project_ids` or `project_names`: Projects to compare
- `comparison_metrics`: ['roi', 'npv', 'payback_period', 'risk_score']
- `enable_ml_insights`: ML predictions and pattern matching
- `natural_language_input`: Describe what to compare

### 3. get_examples (🆕)
Get relevant usage examples for any tool.

**Usage:**
```json
{
  "tool_name": "predict_roi",
  "category": "healthcare"  // optional
}
```

### 4. help (🆕)
Get interactive help and tool recommendations.

**Usage:**
```json
{
  "query": "How do I calculate ROI for a hospital automation project?"
}
```

## Industry Support

Pre-configured benchmarks and calculations for:
- 🏦 Financial Services (fraud detection, compliance, trading)
- 🏥 Healthcare (patient records, diagnostics, scheduling)
- 🛍️ Retail (inventory, customer service, personalization)
- 🏭 Manufacturing (predictive maintenance, quality control)
- 💻 Technology (DevOps, security, analytics)
- 🎓 Education (grading, admissions, tutoring)
- 🏛️ Government (document processing, citizen services)

## Advanced Features

### Real-time Benchmarks
When Perplexity API key is provided:
- Current industry ROI ranges
- Implementation timelines
- Success rates by company size
- Technology adoption trends

### ML-Powered Insights
- Success probability prediction (0-100%)
- Risk factor identification
- Synergy opportunities between projects
- Industry-specific pattern matching

### Natural Language Processing
- Parse requirements from conversational input
- Extract metrics and volumes automatically
- Generate structured use cases
- Support for voice-friendly outputs

## LLM Usage Guide

### Optimized for AI Agents

This MCP server has been specifically optimized for use with LLMs and AI agents, featuring:

#### 1. **Semantic-Rich Responses**
All tools return multi-layered responses with progressive disclosure:
```json
{
  "executive_summary": { /* High-level insights */ },
  "insights": { /* Detailed analysis */ },
  "recommendations": { /* Actionable next steps */ },
  "narrative": { /* Natural language explanation */ },
  "metadata": { /* Context and confidence */ }
}
```

#### 2. **Natural Language Elements**
- Pre-generated summaries and explanations
- Voice-ready output for accessibility
- Conversational tone options
- Context-aware recommendations

#### 3. **Token Optimization**
- Hierarchical data structure for selective parsing
- Summary-first approach reduces token usage
- Optional detail levels based on agent needs
- Efficient JSON structure with clear semantics

#### 4. **Multi-Agent Coordination**
The server implements three internal optimization agents:
- **Context Optimizer**: Transforms raw data into semantic layers
- **Intelligence Amplifier**: Adds ML insights and predictions  
- **Experience Harmonizer**: Adapts output format for optimal consumption

### Best Practices for LLM Integration

1. **Progressive Information Retrieval**
   ```python
   # Start with executive summary
   response.executive_summary
   
   # Drill down as needed
   if needs_details:
       response.insights.primary
       response.financial_metrics.expected
   ```

2. **Conversation Memory**
   - Tools maintain context across calls
   - Reference previous analyses for consistency
   - Build on prior insights

3. **Format Preferences**
   ```json
   {
     "preferred_format": "executive_only",  // For quick summaries
     "detail_level": "comprehensive",       // For full analysis
     "include_visuals": true,              // For chart-ready data
     "max_response_tokens": 1000           // For token limits
   }
   ```

4. **Error Handling**
   - All errors include actionable guidance
   - Graceful degradation with fallbacks
   - Clear validation messages for corrections

### Response Structure Example

```typescript
// predict_roi response optimized for LLMs
{
  summary: {
    expected_roi: 8500,        // Key metric upfront
    confidence: "high",        // Natural language
    recommendation: "PROCEED"  // Clear action
  },
  narrative: {
    executive_briefing: "This AI investment will deliver 8,500% ROI...",
    key_insights: ["Automation will save 10,000 hours monthly", ...],
    risk_assessment: "Low risk with proven technology"
  },
  details: { /* Full calculations available if needed */ }
}
```

## Performance Benchmarks

- **Tool Execution**: 1-3 seconds average
- **Perplexity API**: ~15 seconds for complex queries
- **Database Operations**: < 500ms
- **Monte Carlo (100k iterations)**: < 5 seconds
- **ML Predictions**: < 1 second
- **LLM Response Generation**: < 100ms

## Development

```bash
# Install dependencies
npm install

# Run in development mode
npm run dev

# Build for production
npm run build

# Run comprehensive tests
npm test

# Type checking
npm run typecheck

# Linting
npm run lint
```

## Testing

The project includes comprehensive test coverage:

```bash
# Run all tests
npm test

# Test database connection
npx tsx test-db-connection.ts

# Run comprehensive integration tests
npx tsx test-comprehensive.ts
```

## Security Considerations

1. **Database Access**: Uses Supabase service key for admin operations
2. **Input Validation**: All inputs validated with Zod schemas
3. **Error Handling**: Sensitive information sanitized in error messages
4. **API Keys**: Store securely, never commit to repository

## Troubleshooting

### Common Issues

1. **"Permission denied for table projects"**
   - Ensure `SUPABASE_SERVICE_KEY` is set in environment
   - Check RLS policies in Supabase dashboard

2. **"Perplexity API error"**
   - Verify API key is valid
   - Check API rate limits
   - System falls back to static benchmarks automatically

3. **"Transaction timeout"**
   - Increase `DEFAULT_TRANSACTION_TIMEOUT` in .env
   - Reduce number of use cases per request

## Architecture

```
┌─────────────────┐     ┌──────────────────┐     ┌─────────────────┐
│  Claude Desktop │────▶│   MCP Server     │────▶│    Supabase     │
└─────────────────┘     └──────────────────┘     └─────────────────┘
                               │                           │
                               ▼                           ▼
                        ┌──────────────┐           ┌──────────────┐
                        │ Worker Pool  │           │  PostgreSQL  │
                        │(Monte Carlo) │           └──────────────┘
                        └──────────────┘
                               │
                               ▼
                        ┌──────────────────────────────┐
                        │   External APIs              │
                        ├──────────────────────────────┤
                        │ • Perplexity Sonar          │
                        │ • Financial Modeling Prep   │
                        └──────────────────────────────┘
```

## License

MIT © [SPAIK](https://github.com/SPAIK-io)

## Support

- **Issues**: https://github.com/SPAIK-io/mcp-server-roi/issues
- **Documentation**: See [CLAUDE.md](./CLAUDE.md) for detailed development guide
- **Examples**: Check `/examples` directory for usage patterns

## Contributing

Contributions are welcome! Please:
1. Fork the repository
2. Create a feature branch
3. Add tests for new functionality
4. Ensure all tests pass
5. Submit a pull request

## Changelog

### v1.3.0 (2025-07-03)
- **Breaking**: Removed quick-assessment tool
- **Breaking**: PERPLEXITY_API_KEY now required
- 🆕 Mandatory Dutch market validation for all predictions
- 🆕 Automatic adjustment of unrealistic values
- 🆕 Market-specific insights based on Dutch trends
- 🆕 Enhanced confidence scoring aligned with market data

### v1.2.0 (2025-07-01)
- 🆕 Universal natural language support for all tools
- 🆕 Smart defaults reduce required fields by 80%
- 🆕 Flexible input formats ("$50k", "85%", "6 months")
- 🆕 User-friendly error messages with suggestions
- 🆕 New utility tools: `get_examples` and `help`
- 🆕 Intent detection automatically routes to correct tool
- 🆕 Context awareness for conversation history
- 🆕 Self-documenting tools with embedded examples
- 🆕 LLM-optimized response structure
- 🆕 Comprehensive prompt engineering guide

### v1.1.1 (2025-06-30)
- Bug fixes and performance improvements

### v1.0.0 (2025-06-24)
- Initial release with full MCP implementation
- Real-time benchmark integration
- ML-powered project comparison
- Natural language input support
- Comprehensive transaction management