---
title: "Troubleshooting Guide"
description: "Common issues and solutions for MCP configuration"
author: "Onli Platform"
date: "2024-01-01"
tags: ["mcp", "troubleshooting", "debugging", "issues"]
---

# MCP Configuration Troubleshooting

This guide helps diagnose and resolve common issues with MCP configuration and connectivity.

## Quick Diagnostics

### Connection Test

Run this quick test to verify your MCP configuration:

```bash
# Test basic connectivity
curl -H "User-Id: your_user_id" \
     -H "App-Key: your_app_key" \
     -H "App-Symbol: ENGMA" \
     https://stg.onli.app/health
```

Expected response:
```json
{
  "status": "healthy",
  "timestamp": "2024-01-01T12:00:00Z",
  "version": "1.0.0"
}
```

### Configuration Validation

```javascript
function validateMCPConfig(config) {
  const issues = [];
  
  // Check required fields
  if (!config.url) issues.push("Missing 'url' field");
  if (!config.headers) issues.push("Missing 'headers' object");
  if (!config.headers['User-Id']) issues.push("Missing 'User-Id' header");
  if (!config.headers['App-Key']) issues.push("Missing 'App-Key' header");
  if (!config.headers['App-Symbol']) issues.push("Missing 'App-Symbol' header");
  
  // Check URL format
  if (config.url && !config.url.startsWith('https://')) {
    issues.push("URL must use HTTPS protocol");
  }
  
  return issues.length === 0 ? { valid: true } : { valid: false, issues };
}
```

## Common Issues and Solutions

### 1. Authentication Errors

#### Issue: 401 Unauthorized

**Symptoms:**
```json
{
  "error": "Unauthorized",
  "code": 401,
  "message": "Invalid or missing authentication credentials"
}
```

**Possible Causes:**
- Incorrect User ID or App Key
- Expired credentials
- Missing authentication headers

**Solutions:**

1. **Verify Credentials**
   ```bash
   # Check if credentials are properly set
   echo "User ID: $ONLI_USER_ID"
   echo "App Key: $ONLI_APP_KEY"
   echo "App Symbol: $ONLI_APP_SYMBOL"
   ```

2. **Regenerate API Keys**
   - Log into Onli Platform dashboard
   - Navigate to API Settings > MCP Configuration
   - Generate new App Key
   - Update your configuration

3. **Check Header Format**
   ```json
       {
      "headers": {
        "User-Id": "user_12345",        // Correct format
        "App-Key": "ak_abcd1234...",    // Correct format
        "App-Symbol": "ENGMA"           // Correct format
      }
    }
   ```

#### Issue: 403 Forbidden

**Symptoms:**
```json
{
  "error": "Forbidden",
  "code": 403,
  "message": "Insufficient permissions for requested operation"
}
```

**Solutions:**

1. **Check Account Permissions**
   - Verify your account has MCP access enabled
   - Contact administrator to check permission levels

2. **Verify App Symbol**
   ```javascript
   // Ensure App Symbol matches your account configuration
   const validSymbols = ['ENGMA', 'OTHER_SYMBOL'];
   if (!validSymbols.includes(config.headers['App-Symbol'])) {
     console.error('Invalid App Symbol');
   }
   ```

### 2. Connection Issues

#### Issue: Network Timeouts

**Symptoms:**
```
Error: ETIMEDOUT - Connection timed out
Error: ECONNREFUSED - Connection refused
```

**Solutions:**

1. **Check Network Connectivity**
   ```bash
   # Test basic connectivity
   ping api.onli.app
   
   # Test HTTPS connectivity
   curl -I https://api.onli.app
   ```

2. **Adjust Timeout Settings**
   ```json
   {
     "onli-mcp": {
       "url": "https://api.onli.app",
       "options": {
         "timeout": 30000,           // Increase timeout
         "connectionTimeout": 10000, // Connection-specific timeout
         "retries": 3               // Enable retries
       }
     }
   }
   ```

3. **Check Firewall/Proxy Settings**
   ```bash
   # If behind corporate firewall, check proxy settings
   export HTTPS_PROXY=http://proxy.company.com:8080
   export HTTP_PROXY=http://proxy.company.com:8080
   ```

#### Issue: SSL/TLS Errors

**Symptoms:**
```
Error: DEPTH_ZERO_SELF_SIGNED_CERT
Error: CERT_HAS_EXPIRED
Error: UNABLE_TO_VERIFY_LEAF_SIGNATURE
```

**Solutions:**

1. **Update Certificate Store**
   ```bash
   # On Ubuntu/Debian
   sudo apt-get update && sudo apt-get install ca-certificates
   
   # On macOS
   brew update && brew upgrade
   ```

2. **Check System Time**
   ```bash
   # Ensure system time is correct
   date
   ```

3. **Verify Certificate Chain**
   ```bash
   openssl s_client -connect api.onli.app:443 -servername api.onli.app
   ```

### 3. Configuration Issues

#### Issue: Invalid Configuration Format

**Symptoms:**
```
Error: Configuration validation failed
Error: Invalid JSON format
```

**Solutions:**

1. **Validate JSON Format**
   ```bash
   # Use jq to validate JSON
   cat config.json | jq .
   ```

2. **Check Required Fields**
   ```javascript
   const requiredFields = [
     'url',
     'headers.User-Id',
     'headers.App-Key', 
     'headers.App-Symbol'
   ];
   
   function checkRequired(config) {
     return requiredFields.every(field => {
       const value = field.split('.').reduce((obj, key) => obj?.[key], config);
       return value !== undefined && value !== null && value !== '';
     });
   }
   ```

3. **Use Configuration Template**
   ```json
   {
     "onli-mcp": {
       "url": "https://stg.onli.app",
       "headers": {
         "User-Id": "${ONLI_USER_ID}",
         "App-Key": "${ONLI_APP_KEY}",
         "App-Symbol": "${ONLI_APP_SYMBOL}"
       },
       "options": {
         "timeout": 15000,
         "retries": 3,
         "debug": false
       }
     }
   }
   ```

### 4. Environment-Specific Issues

#### Issue: Environment Variable Not Found

**Symptoms:**
```
Error: Environment variable ONLI_USER_ID is not defined
Error: Cannot read property of undefined
```

**Solutions:**

1. **Check Environment Variables**
   ```bash
   # List all ONLI-related environment variables
   env | grep ONLI
   
   # Check specific variables
   echo "User ID: ${ONLI_USER_ID:-'NOT SET'}"
   echo "App Key: ${ONLI_APP_KEY:-'NOT SET'}"
   echo "App Symbol: ${ONLI_APP_SYMBOL:-'NOT SET'}"
   ```

2. **Load Environment File**
   ```bash
   # Load from .env file
   source .env
   
   # Or use dotenv in Node.js
   require('dotenv').config();
   ```

3. **Set Variables Manually**
   ```bash
   export ONLI_USER_ID="your_user_id"
   export ONLI_APP_KEY="your_app_key"
   export ONLI_APP_SYMBOL="ENGMA"
   ```

#### Issue: Wrong Environment Endpoint

**Symptoms:**
- Development code hitting production endpoints
- Production errors in development environment

**Solutions:**

1. **Environment-Specific Configuration**
   ```javascript
   const environments = {
     development: {
       url: 'https://stg.onli.app',
       debug: true
     },
     production: {
       url: 'https://api.onli.app',
       debug: false
     }
   };
   
   const config = environments[process.env.NODE_ENV] || environments.development;
   ```

2. **Validate Environment**
   ```javascript
   function validateEnvironment() {
     const env = process.env.NODE_ENV;
     const url = config.url;
     
     if (env === 'production' && url.includes('stg.')) {
       throw new Error('Production environment using staging URL');
     }
     
     if (env === 'development' && url.includes('api.') && !url.includes('stg.')) {
       console.warn('Development environment using production URL');
     }
   }
   ```

## Debugging Tools

### 1. Enable Debug Logging

```javascript
const config = {
  "onli-mcp": {
    "url": "https://stg.onli.app",
    "headers": {
      "User-Id": "${ONLI_USER_ID}",
      "App-Key": "${ONLI_APP_KEY}",
      "App-Symbol": "ENGMA"
    },
    "options": {
      "debug": true,          // Enable debug logging
      "logRequests": true,    // Log outgoing requests
      "logResponses": true    // Log incoming responses
    }
  }
};
```

### 2. Network Debugging

```bash
# Monitor network traffic
tcpdump -i any host api.onli.app

# Use curl with verbose output
curl -v -H "User-Id: your_user_id" \
     -H "App-Key: your_app_key" \
     -H "App-Symbol: ENGMA" \
     https://stg.onli.app/health
```

### 3. Application Debugging

```javascript
class MCPDebugger {
  static logRequest(config, request) {
    console.log('MCP Request:', {
      timestamp: new Date().toISOString(),
      url: config.url,
      headers: this.sanitizeHeaders(request.headers),
      method: request.method,
      body: request.body
    });
  }

  static logResponse(response, duration) {
    console.log('MCP Response:', {
      timestamp: new Date().toISOString(),
      status: response.status,
      duration: `${duration}ms`,
      headers: response.headers,
      body: response.body
    });
  }

  static sanitizeHeaders(headers) {
    // Remove sensitive information from logs
    const sanitized = { ...headers };
    if (sanitized['App-Key']) {
      sanitized['App-Key'] = `${sanitized['App-Key'].substring(0, 4)}...`;
    }
    return sanitized;
  }
}
```

## Error Codes Reference

| Code | Error | Description | Solution |
|------|-------|-------------|----------|
| 400 | Bad Request | Invalid request format | Check request structure and parameters |
| 401 | Unauthorized | Invalid credentials | Verify User-Id and App-Key |
| 403 | Forbidden | Insufficient permissions | Check account permissions and App-Symbol |
| 404 | Not Found | Endpoint not found | Verify URL and endpoint path |
| 429 | Rate Limited | Too many requests | Implement rate limiting and retries |
| 500 | Internal Error | Server error | Check server status, contact support |
| 503 | Service Unavailable | Service temporarily down | Check status page, implement retries |

## Health Check Endpoints

Use these endpoints to verify service health:

| Environment | Health Check URL |
|-------------|------------------|
| Development | `https://stg.onli.app/health` |
| Production | `https://api.onli.app/health` |

## Getting Additional Help

### 1. Collect Diagnostic Information

Before contacting support, gather:

```bash
# System information
uname -a
node --version
npm --version

# Network connectivity
curl -I https://api.onli.app

# Configuration (sanitized)
cat config.json | jq 'del(.headers["App-Key"])'

# Recent logs
tail -n 50 application.log
```

### 2. Contact Support

- **Email**: [support@onli.one](mailto:support@onli.one)
- **Subject**: "MCP Configuration Issue - [Brief Description]"
- **Include**: Diagnostic information, error messages, configuration (without sensitive data)

### 3. Community Resources

- **Documentation**: [Configuration Guides](/mcp-configuration/guides)
- **Best Practices**: [MCP Best Practices](/mcp-configuration/best-practices)
- **Forum**: [Onli Developer Community](https://forum.onli.app)
- **Status Page**: [Onli Platform Status](https://status.onli.app)

## Preventive Measures

### 1. Regular Health Checks

```javascript
setInterval(async () => {
  try {
    await client.healthCheck();
    console.log('MCP health check: OK');
  } catch (error) {
    console.error('MCP health check failed:', error);
    // Implement alerting logic
  }
}, 5 * 60 * 1000); // Every 5 minutes
```

### 2. Monitoring and Alerting

```javascript
class MCPMonitor {
  setupAlerts() {
    // Alert on authentication failures
    this.on('auth_error', () => {
      this.sendAlert('Authentication failure detected');
    });
    
    // Alert on high error rates
    this.on('high_error_rate', (rate) => {
      this.sendAlert(`Error rate exceeded threshold: ${rate}%`);
    });
    
    // Alert on service downtime
    this.on('service_down', () => {
      this.sendAlert('MCP service appears to be down');
    });
  }
}
```

### 3. Configuration Backup

```bash
# Backup configuration (without secrets)
cp config.json config.json.backup.$(date +%Y%m%d)

# Version control (excluding secrets)
git add config.json
git commit -m "Update MCP configuration"
``` 