# MCP Server ROI - Deployment Guide

## Table of Contents
1. [Prerequisites](#prerequisites)
2. [Environment Setup](#environment-setup)
3. [Database Setup](#database-setup)
4. [Local Development](#local-development)
5. [Production Deployment](#production-deployment)
6. [Claude Desktop Integration](#claude-desktop-integration)
7. [Docker Deployment](#docker-deployment)
8. [Monitoring & Health Checks](#monitoring--health-checks)
9. [Troubleshooting](#troubleshooting)
10. [Security Considerations](#security-considerations)

## Prerequisites

### Required Software
- Node.js 18.0.0 or higher
- npm 9.0.0 or higher
- Git
- Supabase account (free tier works)
- Perplexity API key (required for Dutch market validation)

### Optional Software
- Docker & Docker Compose (for containerized deployment)
- Claude Desktop (for MCP integration)
- PM2 (for production process management)

## Environment Setup

### 1. Clone the Repository
```bash
git clone https://github.com/SPAIK-io/mcp-server-roi.git
cd mcp-server-roi
```

### 2. Install Dependencies
```bash
npm install
```

### 3. Environment Variables
Create a `.env` file in the root directory:

```bash
# Required - Supabase Configuration
SUPABASE_URL=https://your-project.supabase.co
SUPABASE_ANON_KEY=your-anon-key-here

# Required - Perplexity API for Dutch validation
PERPLEXITY_API_KEY=your-perplexity-api-key

# Highly Recommended - For full functionality
SUPABASE_SERVICE_KEY=your-service-key-here

# Optional - External APIs
FMP_API_KEY=your-financial-modeling-prep-key

# Optional - Configuration
NODE_ENV=production              # or development
LOG_LEVEL=INFO                   # ERROR, WARN, INFO, DEBUG, TRACE
WORKER_POOL_SIZE=4              # Number of worker threads
MAX_SIMULATION_ITERATIONS=100000 # Monte Carlo iterations
RATE_LIMIT_REQUESTS_PER_MINUTE=60
CIRCUIT_BREAKER_THRESHOLD=5
```

### 4. Validate Configuration
```bash
npm run validate-config
```

## Database Setup

### 1. Create Supabase Project
1. Go to [https://supabase.com](https://supabase.com)
2. Create a new project
3. Note your project URL and keys

### 2. Apply Database Schema
Run the SQL files in order in your Supabase SQL Editor:

```sql
-- 1. Main schema
-- Copy contents of database/schema.sql

-- 2. Security update
-- Copy contents of database/001_security_update.sql

-- 3. Transactional functions
-- Copy contents of database/002_transactional_functions.sql
```

### 3. Verify Database Setup
```bash
npm run test:db
```

## Local Development

### 1. Build the Project
```bash
npm run build
```

### 2. Run Tests
```bash
# All tests
npm test

# Unit tests only
npm run test:unit

# Integration tests
npm run test:integration

# With coverage
npm run test:coverage
```

### 3. Start Development Server
```bash
npm run dev
```

### 4. Watch Mode
```bash
npm run watch
```

## Production Deployment

### Option 1: Direct Node.js Deployment

#### 1. Build for Production
```bash
npm run build
npm prune --production
```

#### 2. Using PM2 (Recommended)
```bash
# Install PM2 globally
npm install -g pm2

# Start with PM2
pm2 start ecosystem.config.js

# Save PM2 configuration
pm2 save
pm2 startup
```

**ecosystem.config.js:**
```javascript
module.exports = {
  apps: [{
    name: 'mcp-server-roi',
    script: './dist/index.js',
    instances: 1,
    autorestart: true,
    watch: false,
    max_memory_restart: '1G',
    env: {
      NODE_ENV: 'production'
    },
    error_file: './logs/err.log',
    out_file: './logs/out.log',
    log_file: './logs/combined.log',
    time: true
  }]
}
```

#### 3. Using systemd (Linux)
Create `/etc/systemd/system/mcp-server-roi.service`:

```ini
[Unit]
Description=MCP Server ROI
After=network.target

[Service]
Type=simple
User=nodejs
WorkingDirectory=/opt/mcp-server-roi
ExecStart=/usr/bin/node /opt/mcp-server-roi/dist/index.js
Restart=on-failure
RestartSec=10
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=mcp-server-roi
Environment=NODE_ENV=production

[Install]
WantedBy=multi-user.target
```

Enable and start:
```bash
sudo systemctl enable mcp-server-roi
sudo systemctl start mcp-server-roi
sudo systemctl status mcp-server-roi
```

### Option 2: Docker Deployment

#### 1. Build Docker Image
```bash
docker build -t mcp-server-roi .
```

#### 2. Run with Docker Compose
Create `docker-compose.yml`:

```yaml
version: '3.8'

services:
  mcp-server-roi:
    image: mcp-server-roi
    container_name: mcp-server-roi
    restart: unless-stopped
    environment:
      - NODE_ENV=production
      - SUPABASE_URL=${SUPABASE_URL}
      - SUPABASE_ANON_KEY=${SUPABASE_ANON_KEY}
      - SUPABASE_SERVICE_KEY=${SUPABASE_SERVICE_KEY}
      - PERPLEXITY_API_KEY=${PERPLEXITY_API_KEY}
    volumes:
      - ./logs:/app/logs
    healthcheck:
      test: ["CMD", "node", "healthcheck.js"]
      interval: 30s
      timeout: 10s
      retries: 3
    deploy:
      resources:
        limits:
          cpus: '2'
          memory: 2G
        reservations:
          cpus: '1'
          memory: 1G
```

Start the service:
```bash
docker-compose up -d
```

### Option 3: Cloud Deployment

#### AWS EC2
1. Launch EC2 instance (t3.medium recommended)
2. Install Node.js 18+
3. Clone repository
4. Set up environment variables
5. Use PM2 or systemd for process management

#### Google Cloud Run
```bash
# Build and push to GCR
gcloud builds submit --tag gcr.io/PROJECT-ID/mcp-server-roi

# Deploy to Cloud Run
gcloud run deploy mcp-server-roi \
  --image gcr.io/PROJECT-ID/mcp-server-roi \
  --platform managed \
  --region us-central1 \
  --set-env-vars NODE_ENV=production \
  --set-env-vars SUPABASE_URL=$SUPABASE_URL \
  --set-env-vars SUPABASE_ANON_KEY=$SUPABASE_ANON_KEY \
  --set-env-vars PERPLEXITY_API_KEY=$PERPLEXITY_API_KEY
```

#### Heroku
```bash
# Create Heroku app
heroku create mcp-server-roi

# Set environment variables
heroku config:set NODE_ENV=production
heroku config:set SUPABASE_URL=your-url
heroku config:set SUPABASE_ANON_KEY=your-key
heroku config:set PERPLEXITY_API_KEY=your-key

# Deploy
git push heroku main
```

## Claude Desktop Integration

### 1. Locate Configuration File
- **macOS**: `~/Library/Application Support/Claude/claude_desktop_config.json`
- **Windows**: `%APPDATA%\Claude\claude_desktop_config.json`
- **Linux**: `~/.config/Claude/claude_desktop_config.json`

### 2. Add MCP Server Configuration
```json
{
  "mcpServers": {
    "roi": {
      "command": "node",
      "args": ["/absolute/path/to/mcp-server-roi/dist/index.js"],
      "env": {
        "SUPABASE_URL": "your-project-url",
        "SUPABASE_ANON_KEY": "your-anon-key",
        "SUPABASE_SERVICE_KEY": "your-service-key",
        "PERPLEXITY_API_KEY": "your-perplexity-key",
        "NODE_ENV": "production",
        "LOG_LEVEL": "INFO"
      }
    }
  }
}
```

### 3. Restart Claude Desktop
The server will automatically start when Claude Desktop launches.

## Monitoring & Health Checks

### 1. Built-in Health Check Endpoint
The server includes a health check system accessible via MCP tools.

### 2. Logging
Logs are written to stderr in structured format:
- Development: Human-readable format
- Production: JSON format for log aggregation

### 3. Metrics
Monitor these key metrics:
- Circuit breaker states (Perplexity, FMP APIs)
- Rate limiting metrics
- Database connection health
- Worker thread utilization
- Monte Carlo simulation performance

### 4. Alerting Setup (Production)
```bash
# Example using PM2
pm2 install pm2-slack
pm2 set pm2-slack:slack_url https://hooks.slack.com/services/YOUR/SLACK/WEBHOOK
```

## Troubleshooting

### Common Issues

#### 1. Database Connection Failed
```bash
Error: Database connection failed
```
**Solution:**
- Verify SUPABASE_URL and SUPABASE_ANON_KEY
- Check network connectivity
- Ensure Supabase project is active

#### 2. Perplexity API Errors
```bash
Error: Dutch validation failed
```
**Solution:**
- Verify PERPLEXITY_API_KEY is set
- Check API rate limits
- Circuit breaker may be open - wait 1 minute

#### 3. Worker Thread Errors
```bash
Error: Worker thread failed
```
**Solution:**
- Check WORKER_POOL_SIZE setting
- Verify sufficient memory available
- Reduce MAX_SIMULATION_ITERATIONS

#### 4. MCP Protocol Errors
```bash
Error: Invalid MCP message
```
**Solution:**
- Ensure latest version of Claude Desktop
- Check tool parameter formats
- Review logs for validation errors

### Debug Mode
Enable detailed logging:
```bash
LOG_LEVEL=TRACE node dist/index.js
```

### Test Individual Components
```bash
# Test database connection
npm run test:db

# Test external APIs
npm run test:apis

# Test worker threads
npm run test:workers
```

## Security Considerations

### 1. Environment Variables
- Never commit `.env` files
- Use secret management systems in production
- Rotate API keys regularly

### 2. Database Security
- Use service keys only on server-side
- Enable Row Level Security (RLS) in Supabase
- Audit database access logs

### 3. API Security
- Rate limiting is enforced (60 req/min default)
- Circuit breakers prevent cascade failures
- All external API calls use HTTPS

### 4. Process Security
- Run with minimal privileges
- Use non-root user in Docker
- Enable security headers if exposing HTTP

### 5. Compliance
- GDPR compliant data handling
- Dutch privacy law considerations
- Financial data encryption at rest

## Performance Tuning

### 1. Worker Threads
```bash
# Optimal for CPU cores
WORKER_POOL_SIZE=4  # Set to number of CPU cores
```

### 2. Monte Carlo Simulations
```bash
# Balance accuracy vs performance
MAX_SIMULATION_ITERATIONS=50000  # Reduce for faster results
```

### 3. Database Connections
- Supabase handles connection pooling
- Batch operations implemented for efficiency

### 4. Memory Management
- Default heap size usually sufficient
- For large simulations: `node --max-old-space-size=4096`

## Maintenance

### Regular Tasks
1. **Weekly**: Review error logs
2. **Monthly**: Update dependencies
3. **Quarterly**: Rotate API keys
4. **Annually**: Security audit

### Backup Strategy
1. Supabase automatic backups (Pro plan)
2. Export critical data regularly
3. Version control for code changes

### Update Process
```bash
# 1. Backup current version
cp -r /opt/mcp-server-roi /opt/mcp-server-roi-backup

# 2. Pull latest changes
git pull origin main

# 3. Install dependencies
npm install

# 4. Run tests
npm test

# 5. Build
npm run build

# 6. Restart service
pm2 restart mcp-server-roi
```

## Support

- **GitHub Issues**: https://github.com/SPAIK-io/mcp-server-roi/issues
- **Documentation**: https://github.com/SPAIK-io/mcp-server-roi/wiki
- **Email**: support@spaik.io

---

Last updated: 2025-07-03