# BZZZ MCP Server Deployment Guide

Complete deployment guide for the BZZZ MCP Server in various environments.

## Table of Contents

- [Prerequisites](#prerequisites)
- [Environment Configuration](#environment-configuration)
- [Development Deployment](#development-deployment)
- [Production Deployment](#production-deployment)
- [Docker Deployment](#docker-deployment)
- [Systemd Service](#systemd-service)
- [Monitoring and Health Checks](#monitoring-and-health-checks)
- [Backup and Recovery](#backup-and-recovery)
- [Troubleshooting](#troubleshooting)

## Prerequisites

### System Requirements

**Minimum Requirements:**
- Node.js 18.0 or higher
- 2 CPU cores
- 4GB RAM
- 10GB disk space
- Network access to OpenAI API
- Network access to BZZZ Go service

**Recommended Requirements:**
- Node.js 20.0 or higher
- 4 CPU cores
- 8GB RAM
- 50GB disk space
- High-speed internet connection
- Load balancer for multiple instances

### External Dependencies

1. **OpenAI API Access**
   - Valid OpenAI API key
   - GPT-5 model access
   - Sufficient API credits

2. **BZZZ Go Service**
   - Running BZZZ Go service instance
   - Network connectivity to BZZZ service
   - Compatible BZZZ API version

3. **Network Configuration**
   - Outbound HTTPS access (port 443) for OpenAI
   - HTTP/WebSocket access to BZZZ service
   - Optionally: Inbound access for health checks

## Environment Configuration

### Environment Variables

Create a `.env` file or set system environment variables:

```bash
# OpenAI Configuration
OPENAI_MODEL=gpt-5
OPENAI_MAX_TOKENS=4000
OPENAI_TEMPERATURE=0.7

# BZZZ Configuration
BZZZ_NODE_URL=http://localhost:8080
BZZZ_NETWORK_ID=bzzz-production

# Cost Management
DAILY_COST_LIMIT=100.0
MONTHLY_COST_LIMIT=1000.0
COST_WARNING_THRESHOLD=0.8

# Performance Settings
MAX_ACTIVE_THREADS=10
MAX_AGENTS=5
THREAD_TIMEOUT=3600

# Logging
LOG_LEVEL=info
LOG_FILE=/var/log/bzzz-mcp/server.log

# Node.js Settings
NODE_ENV=production
```

### Security Configuration

1. **API Key Management**
```bash
# Create secure directory
sudo mkdir -p /opt/bzzz-mcp/secrets
sudo chown bzzz:bzzz /opt/bzzz-mcp/secrets
sudo chmod 700 /opt/bzzz-mcp/secrets

# Store OpenAI API key
echo "your-openai-api-key" | sudo tee /opt/bzzz-mcp/secrets/openai-api-key.txt
sudo chown bzzz:bzzz /opt/bzzz-mcp/secrets/openai-api-key.txt
sudo chmod 600 /opt/bzzz-mcp/secrets/openai-api-key.txt
```

2. **Network Security**
```bash
# Configure firewall (Ubuntu/Debian)
sudo ufw allow out 443/tcp  # OpenAI API
sudo ufw allow out 8080/tcp # BZZZ Go service
sudo ufw allow in 3000/tcp  # Health checks (optional)
```

## Development Deployment

### Local Development Setup

1. **Clone and Install**
```bash
cd /path/to/BZZZ/mcp-server
npm install
```

2. **Configure Development Environment**
```bash
# Copy example environment file
cp .env.example .env

# Edit configuration
nano .env
```

3. **Start Development Server**
```bash
# With hot reload
npm run dev

# Or build and run
npm run build
npm start
```

### Development Docker Setup

```dockerfile
# Dockerfile.dev
FROM node:20-alpine

WORKDIR /app

# Install dependencies
COPY package*.json ./
RUN npm ci

# Copy source
COPY . .

# Development command
CMD ["npm", "run", "dev"]
```

```bash
# Build and run development container
docker build -f Dockerfile.dev -t bzzz-mcp:dev .
docker run -p 3000:3000 -v $(pwd):/app bzzz-mcp:dev
```

## Production Deployment

### Manual Production Setup

1. **Create Application User**
```bash
sudo useradd -r -s /bin/false bzzz
sudo mkdir -p /opt/bzzz-mcp
sudo chown bzzz:bzzz /opt/bzzz-mcp
```

2. **Install Application**
```bash
# Copy built application
sudo cp -r dist/ /opt/bzzz-mcp/
sudo cp package*.json /opt/bzzz-mcp/
sudo chown -R bzzz:bzzz /opt/bzzz-mcp

# Install production dependencies
cd /opt/bzzz-mcp
sudo -u bzzz npm ci --only=production
```

3. **Configure Logging**
```bash
sudo mkdir -p /var/log/bzzz-mcp
sudo chown bzzz:bzzz /var/log/bzzz-mcp
sudo chmod 755 /var/log/bzzz-mcp

# Setup log rotation
sudo tee /etc/logrotate.d/bzzz-mcp << EOF
/var/log/bzzz-mcp/*.log {
    daily
    rotate 30
    compress
    delaycompress
    missingok
    notifempty
    create 644 bzzz bzzz
    postrotate
        systemctl reload bzzz-mcp
    endscript
}
EOF
```

## Docker Deployment

### Production Dockerfile

```dockerfile
FROM node:20-alpine AS builder

WORKDIR /app

# Copy package files
COPY package*.json ./

# Install all dependencies
RUN npm ci

# Copy source code
COPY . .

# Build application
RUN npm run build

# Production stage
FROM node:20-alpine AS production

# Create app user
RUN addgroup -g 1001 -S bzzz && \
    adduser -S bzzz -u 1001

# Create app directory
WORKDIR /opt/bzzz-mcp

# Copy built application
COPY --from=builder --chown=bzzz:bzzz /app/dist ./dist
COPY --from=builder --chown=bzzz:bzzz /app/package*.json ./

# Install only production dependencies
RUN npm ci --only=production && npm cache clean --force

# Create directories
RUN mkdir -p /var/log/bzzz-mcp && \
    chown bzzz:bzzz /var/log/bzzz-mcp

# Switch to app user
USER bzzz

# Health check
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
  CMD node dist/health-check.js || exit 1

EXPOSE 3000

CMD ["node", "dist/index.js"]
```

### Docker Compose Setup

```yaml
version: '3.8'

services:
  bzzz-mcp:
    build: .
    container_name: bzzz-mcp-server
    restart: unless-stopped
    environment:
      - NODE_ENV=production
      - LOG_LEVEL=info
      - BZZZ_NODE_URL=http://bzzz-go:8080
      - DAILY_COST_LIMIT=100.0
      - MONTHLY_COST_LIMIT=1000.0
    volumes:
      - ./secrets:/opt/bzzz-mcp/secrets:ro
      - bzzz-mcp-logs:/var/log/bzzz-mcp
    networks:
      - bzzz-network
    depends_on:
      - bzzz-go
    labels:
      - "traefik.enable=true"
      - "traefik.http.routers.bzzz-mcp.rule=Host(`bzzz-mcp.local`)"
      - "traefik.http.services.bzzz-mcp.loadbalancer.server.port=3000"

  bzzz-go:
    image: bzzz-go:latest
    container_name: bzzz-go-service
    restart: unless-stopped
    ports:
      - "8080:8080"
    networks:
      - bzzz-network

volumes:
  bzzz-mcp-logs:

networks:
  bzzz-network:
    driver: bridge
```

### Deployment Commands

```bash
# Build and start services
docker-compose up -d

# View logs
docker-compose logs -f bzzz-mcp

# Update application
docker-compose pull
docker-compose up -d --force-recreate

# Stop services
docker-compose down
```

## Systemd Service

### Service Configuration

```ini
# /etc/systemd/system/bzzz-mcp.service
[Unit]
Description=BZZZ MCP Server
Documentation=https://docs.bzzz.local/mcp-server
After=network-online.target
Wants=network-online.target

[Service]
Type=simple
User=bzzz
Group=bzzz
WorkingDirectory=/opt/bzzz-mcp

# Environment
Environment=NODE_ENV=production
Environment=LOG_LEVEL=info
EnvironmentFile=-/etc/bzzz-mcp/environment

# Execution
ExecStart=/usr/bin/node dist/index.js
ExecReload=/bin/kill -HUP $MAINPID

# Process management
Restart=always
RestartSec=10
KillMode=mixed
KillSignal=SIGTERM
TimeoutSec=30

# Security
NoNewPrivileges=yes
ProtectSystem=strict
ProtectHome=yes
ReadWritePaths=/var/log/bzzz-mcp
PrivateTmp=yes

# Logging
StandardOutput=journal
StandardError=journal
SyslogIdentifier=bzzz-mcp

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

### Service Management

```bash
# Install and enable service
sudo systemctl daemon-reload
sudo systemctl enable bzzz-mcp
sudo systemctl start bzzz-mcp

# Service status and logs
sudo systemctl status bzzz-mcp
sudo journalctl -u bzzz-mcp -f

# Service control
sudo systemctl stop bzzz-mcp
sudo systemctl restart bzzz-mcp
sudo systemctl reload bzzz-mcp
```

### Environment File

```bash
# /etc/bzzz-mcp/environment
OPENAI_MODEL=gpt-5
BZZZ_NODE_URL=http://localhost:8080
BZZZ_NETWORK_ID=bzzz-production
DAILY_COST_LIMIT=100.0
MONTHLY_COST_LIMIT=1000.0
LOG_FILE=/var/log/bzzz-mcp/server.log
```

## Monitoring and Health Checks

### Health Check Script

```javascript
// health-check.js
const http = require('http');

function healthCheck() {
  return new Promise((resolve, reject) => {
    const req = http.request({
      hostname: 'localhost',
      port: 3000,
      path: '/health',
      method: 'GET',
      timeout: 3000
    }, (res) => {
      if (res.statusCode === 200) {
        resolve('healthy');
      } else {
        reject(new Error(`Health check failed: ${res.statusCode}`));
      }
    });

    req.on('error', reject);
    req.on('timeout', () => reject(new Error('Health check timeout')));
    req.end();
  });
}

healthCheck()
  .then(() => process.exit(0))
  .catch(() => process.exit(1));
```

### Monitoring Script

```bash
#!/bin/bash
# /usr/local/bin/bzzz-mcp-monitor.sh

LOG_FILE="/var/log/bzzz-mcp/monitor.log"
SERVICE_NAME="bzzz-mcp"

log() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') $1" >> $LOG_FILE
}

# Check if service is running
if ! systemctl is-active --quiet $SERVICE_NAME; then
    log "ERROR: Service $SERVICE_NAME is not running"
    systemctl restart $SERVICE_NAME
    log "INFO: Attempted to restart $SERVICE_NAME"
    exit 1
fi

# Check memory usage
MEMORY_USAGE=$(ps -o pid,ppid,cmd,%mem --sort=-%mem -C node | grep bzzz-mcp | awk '{print $4}')
if [[ -n "$MEMORY_USAGE" ]] && (( $(echo "$MEMORY_USAGE > 80" | bc -l) )); then
    log "WARNING: High memory usage: ${MEMORY_USAGE}%"
fi

# Check log file size
LOG_SIZE=$(du -m /var/log/bzzz-mcp/server.log 2>/dev/null | cut -f1)
if [[ -n "$LOG_SIZE" ]] && (( LOG_SIZE > 100 )); then
    log "WARNING: Large log file: ${LOG_SIZE}MB"
fi

log "INFO: Health check completed"
```

### Cron Job Setup

```bash
# Add to crontab
sudo crontab -e

# Check every 5 minutes
*/5 * * * * /usr/local/bin/bzzz-mcp-monitor.sh
```

## Backup and Recovery

### Configuration Backup

```bash
#!/bin/bash
# /usr/local/bin/backup-bzzz-mcp.sh

BACKUP_DIR="/backup/bzzz-mcp"
DATE=$(date +%Y%m%d_%H%M%S)

mkdir -p $BACKUP_DIR

# Backup configuration
tar -czf $BACKUP_DIR/config-$DATE.tar.gz \
  /etc/bzzz-mcp/ \
  /opt/bzzz-mcp/secrets/ \
  /etc/systemd/system/bzzz-mcp.service

# Backup logs (last 7 days)
find /var/log/bzzz-mcp/ -name "*.log" -mtime -7 -exec \
  tar -czf $BACKUP_DIR/logs-$DATE.tar.gz {} +

# Cleanup old backups (keep 30 days)
find $BACKUP_DIR -name "*.tar.gz" -mtime +30 -delete

echo "Backup completed: $DATE"
```

### Recovery Procedure

1. **Stop Service**
```bash
sudo systemctl stop bzzz-mcp
```

2. **Restore Configuration**
```bash
cd /backup/bzzz-mcp
tar -xzf config-YYYYMMDD_HHMMSS.tar.gz -C /
```

3. **Verify Permissions**
```bash
sudo chown -R bzzz:bzzz /opt/bzzz-mcp
sudo chmod 600 /opt/bzzz-mcp/secrets/*
```

4. **Restart Service**
```bash
sudo systemctl start bzzz-mcp
sudo systemctl status bzzz-mcp
```

## Troubleshooting

### Common Issues

**1. Service Won't Start**
```bash
# Check logs
sudo journalctl -u bzzz-mcp -n 50

# Common causes:
# - Missing API key file
# - Permission issues
# - Port conflicts
# - Missing dependencies
```

**2. High Memory Usage**
```bash
# Monitor memory usage
ps aux | grep node
htop

# Possible solutions:
# - Reduce MAX_AGENTS
# - Decrease MAX_ACTIVE_THREADS
# - Restart service periodically
```

**3. OpenAI API Errors**
```bash
# Check API key validity
curl -H "Authorization: Bearer $OPENAI_API_KEY" \
  https://api.openai.com/v1/models

# Common issues:
# - Invalid or expired API key
# - Rate limit exceeded
# - Insufficient credits
```

**4. BZZZ Connection Issues**
```bash
# Test BZZZ service connectivity
curl http://localhost:8080/api/v1/health

# Check network configuration
netstat -tulpn | grep 8080
```

### Performance Tuning

**Node.js Optimization:**
```bash
# Add to service environment
NODE_OPTIONS="--max-old-space-size=4096 --optimize-for-size"
```

**System Optimization:**
```bash
# Increase file descriptor limits
echo "bzzz soft nofile 65536" >> /etc/security/limits.conf
echo "bzzz hard nofile 65536" >> /etc/security/limits.conf

# Optimize network settings
echo 'net.core.somaxconn = 1024' >> /etc/sysctl.conf
sysctl -p
```

### Debug Mode

Enable debug logging for troubleshooting:

```bash
# Temporary debug mode
sudo systemctl edit bzzz-mcp

# Add:
[Service]
Environment=LOG_LEVEL=debug

# Reload and restart
sudo systemctl daemon-reload
sudo systemctl restart bzzz-mcp
```

### Log Analysis

```bash
# Real-time log monitoring
sudo journalctl -u bzzz-mcp -f

# Error analysis
grep -i error /var/log/bzzz-mcp/server.log | tail -20

# Performance analysis
grep -i "response time" /var/log/bzzz-mcp/server.log | tail -10
```

This completes the comprehensive deployment guide. Follow the appropriate section based on your deployment environment and requirements.