# Architecture Documentation - MCP Server ROI
## System Architecture
```
┌─────────────────────────────────────────────────────────────┐
│ Claude Desktop │
│ (MCP Client) │
└────────────────────────┬────────────────────────────────────┘
│ JSON-RPC over stdio
┌────────────────────────┴────────────────────────────────────┐
│ MCP Server ROI │
│ ┌────────────────────────────────────────────────────────┐ │
│ │ MCP Protocol Layer │ │
│ │ (Request/Response Handler) │ │
│ └────────────────────────┬───────────────────────────────┘ │
│ ┌────────────────────────┴───────────────────────────────┐ │
│ │ Tool Layer │ │
│ │ ┌─────────────┐ ┌──────────────┐ ┌─────────────────┐ │ │
│ │ │ predict_roi │ │compare_projects│ │quick_assessment│ │ │
│ │ └─────────────┘ └──────────────┘ └─────────────────┘ │ │
│ └────────────────────────┬───────────────────────────────┘ │
│ ┌────────────────────────┴───────────────────────────────┐ │
│ │ Business Logic Layer │ │
│ │ ┌────────────┐ ┌────────────┐ ┌───────────────────┐ │ │
│ │ │ROI Engine │ │Monte Carlo │ │Industry Benchmarks│ │ │
│ │ │ │ │Simulator │ │ │ │ │
│ │ └────────────┘ └──────┬─────┘ └───────────────────┘ │ │
│ │ │ │ │
│ │ ┌────┴─────┐ │ │
│ │ │ Piscina │ │ │
│ │ │ Worker │ │ │
│ │ │ Pool │ │ │
│ │ └──────────┘ │ │
│ └────────────────────────┬───────────────────────────────┘ │
│ ┌────────────────────────┴───────────────────────────────┐ │
│ │ Data Access Layer │ │
│ │ (Supabase Client + Types) │ │
│ └────────────────────────┬───────────────────────────────┘ │
└───────────────────────────┼─────────────────────────────────┘
│ HTTPS
┌──────────┴──────────┐
│ Supabase Cloud │
│ (PostgreSQL) │
└─────────────────────┘
```
## Component Architecture
### 1. MCP Protocol Layer
**Location**: `/src/index.ts`
**Responsibilities**:
- Handle MCP protocol communication
- Route tool calls to appropriate handlers
- Manage request/response lifecycle
- Error handling and formatting
**Key Components**:
```typescript
- Server instance (MCP SDK)
- StdioServerTransport
- Request handlers for ListTools and CallTool
- Tool definitions and schemas
```
### 2. Tool Layer
**Location**: `/src/tools/`
**Components**:
- `predict-roi.ts`: Full ROI projections
- `compare-projects.ts`: Multi-project analysis
- `quick-assessment.ts`: Rapid evaluations
**Responsibilities**:
- Input validation using Zod schemas
- Orchestrate business logic calls
- Format responses for MCP protocol
- Handle tool-specific errors
### 3. Business Logic Layer
**Location**: `/src/core/`
#### ROI Engine (`/src/core/calculators/`)
- Financial calculations (NPV, IRR, payback)
- Use case aggregation
- Cash flow modeling
- Scenario generation (conservative/expected/optimistic)
#### Monte Carlo Simulator (`/src/core/simulation/`)
- Parallel simulation execution
- Statistical analysis
- Risk factor identification
- Result aggregation
#### Industry Benchmarks (`/src/core/benchmarks/`)
- Static benchmark data
- Industry-specific adjustments
- Confidence factors
### 4. Worker Pool Architecture
**Technology**: Piscina
**Configuration**:
```typescript
{
maxThreads: 4, // Configurable via env
idleTimeout: 60000, // 1 minute
filename: 'monte-carlo-worker.js'
}
```
**Worker Design**:
- Stateless simulation execution
- Linear Congruential Generator for randomness
- Supports multiple probability distributions
- Returns raw results for aggregation
### 5. Data Access Layer
**Location**: `/src/db/`
**Components**:
- `supabase.ts`: Client initialization
- `types/database.ts`: TypeScript types
- Row-level security ready
- Connection pooling handled by Supabase
## Data Flow
### 1. Prediction Flow
```
User Request → MCP Tool → Validation → Create Project →
Create Use Cases → ROI Engine → Financial Calculations →
Save to DB → Format Response → Return to User
```
### 2. Monte Carlo Flow
```
Simulation Request → Create Worker Tasks → Distribute to Pool →
Parallel Execution → Collect Results → Statistical Analysis →
Risk Identification → Save Results → Return Analysis
```
### 3. Comparison Flow
```
Project IDs → Fetch Projects → Fetch Projections →
Calculate Metrics → Rank Projects → Generate Insights →
Create Recommendations → Return Comparison
```
## Database Schema Design
### Design Principles
1. **Normalization**: Separate tables for projects, use cases, projections
2. **JSONB Usage**: Flexible schema for complex nested data
3. **Referential Integrity**: Foreign key constraints
4. **Indexing**: On commonly queried fields
### Key Tables
- `projects`: Core project information
- `use_cases`: Individual automation use cases
- `projections`: Financial projections and scenarios
- `simulation_results`: Monte Carlo output
- `actual_metrics`: Tracking real outcomes
## Security Architecture
### Input Validation
- All inputs validated with Zod schemas
- Type checking at compile time
- Runtime validation for API calls
- Bounds checking for numerical inputs
### Data Isolation
- Organization ID scoping
- Prepared for row-level security
- No cross-tenant data access
- Audit trail capability
### Secret Management
- Environment variables for credentials
- No secrets in code
- Supabase handles auth tokens
- Service keys optional
## Performance Considerations
### Optimization Strategies
1. **Worker Pooling**: Reuse threads for Monte Carlo
2. **Batch Processing**: Aggregate database operations
3. **Caching**: Industry benchmarks in memory
4. **Lazy Loading**: Load data as needed
### Scalability Points
1. **Horizontal**: Multiple server instances
2. **Vertical**: Increase worker pool size
3. **Database**: Supabase auto-scaling
4. **Caching**: Add Redis for hot data
### Performance Metrics
- Monte Carlo: ~100ms per 1000 iterations
- ROI Calculation: <50ms per use case
- Database queries: <100ms average
- Worker spawn time: ~200ms (pooled)
## Error Handling Strategy
### Error Categories
1. **Validation Errors**: Return detailed field errors
2. **Database Errors**: Log and return generic message
3. **Calculation Errors**: Fallback to conservative estimates
4. **Timeout Errors**: Kill long-running workers
### Error Response Format
```typescript
{
error: {
type: string,
message: string,
details?: object
}
}
```
## Deployment Architecture
### Local Development
```bash
npm run dev # Uses tsx watch mode
```
### Production Build
```bash
npm run build # TypeScript compilation
npm start # Run compiled code
```
### Claude Desktop Integration
- Configured via JSON file
- Communicates over stdio
- Environment variables for config
- No network exposure needed
## Future Architecture Considerations
### Potential Enhancements
1. **Event Sourcing**: Track all projection changes
2. **CQRS**: Separate read/write models
3. **GraphQL**: Alternative API layer
4. **WebSockets**: Real-time updates
### Scaling Considerations
1. **Queue System**: Add job queue for long operations
2. **Microservices**: Split if complexity grows
3. **CDN**: For dashboard delivery
4. **API Gateway**: For external integrations
## Technology Stack Summary
| Component | Technology | Rationale |
|-----------|------------|-----------|
| Language | TypeScript | Type safety, IDE support |
| Runtime | Node.js | JavaScript ecosystem |
| Protocol | MCP (stdio) | Claude Desktop integration |
| Database | Supabase/PostgreSQL | Managed, scalable, real-time |
| Validation | Zod | Runtime + compile-time safety |
| Workers | Piscina | Best-in-class thread pool |
| Build | tsc | Native TypeScript compiler |
## Monitoring & Observability
### Logging Strategy
- Console errors for development
- Structured logging ready
- Error aggregation capability
- Performance timing hooks
### Metrics to Track
- Tool usage frequency
- Calculation performance
- Database query times
- Worker pool utilization
- Error rates by type
### Health Checks
- Database connectivity
- Worker pool status
- Memory usage
- Response times