> ## Documentation Index
> Fetch the complete documentation index at: https://finance.chiefpriest.design/llms.txt
> Use this file to discover all available pages before exploring further.

# Troubleshooting

> Common issues and solutions for the Financial MCP Server

## Common Issues

### Server Startup Issues

<AccordionGroup>
  <Accordion title="Port Already in Use">
    **Error**: `[Errno 48] error while attempting to bind on address ('0.0.0.0', 8001): [errno 48] address already in use`

    **Cause**: Another process is using port 8001

    **Solutions**:

    ```bash theme={null}
    # Find process using the port
    lsof -i :8001

    # Kill the process
    kill -9 <PID>

    # Or use a different port
    export PORT=8002
    python3 main.py
    ```
  </Accordion>

  <Accordion title="Python Module Not Found">
    **Error**: `ModuleNotFoundError: No module named 'fastapi'`

    **Cause**: Dependencies not installed

    **Solutions**:

    ```bash theme={null}
    # Install dependencies
    pip install -r requirements.txt

    # Or install specific package
    pip install fastapi uvicorn

    # Check virtual environment
    which python
    pip list
    ```
  </Accordion>

  <Accordion title="Permission Denied">
    **Error**: `PermissionError: [Errno 13] Permission denied`

    **Cause**: Insufficient permissions or port restrictions

    **Solutions**:

    ```bash theme={null}
    # Use port above 1024 (non-privileged)
    export PORT=8001

    # Or run with sudo (not recommended)
    sudo python3 main.py

    # Check file permissions
    ls -la main.py
    chmod +x main.py
    ```
  </Accordion>
</AccordionGroup>

### API Key Issues

<AccordionGroup>
  <Accordion title="FMP API Key Not Working">
    **Error**: `401 Unauthorized` or `Invalid API key`

    **Debugging Steps**:

    ```bash theme={null}
    # 1. Verify environment variable is set
    echo $FMP_API_KEY

    # 2. Check for extra spaces or characters
    echo "$FMP_API_KEY" | wc -c  # Should be 32 characters + newline

    # 3. Test API key directly
    curl "https://financialmodelingprep.com/api/v3/quote/AAPL?apikey=$FMP_API_KEY"

    # 4. Check server logs
    python3 main.py 2>&1 | grep -i "api\|key\|401"
    ```

    **Solutions**:

    * Copy API key exactly from FMP dashboard
    * Restart server after setting environment variable
    * Check FMP account status and usage limits
  </Accordion>

  <Accordion title="Rate Limit Exceeded">
    **Error**: `429 Too Many Requests`

    **Symptoms**: Requests failing after working initially

    **Solutions**:

    ```python theme={null}
    # Check current usage
    response = requests.get("/api/v1/health")
    print(response.json())

    # Use YFinance endpoints as fallback
    response = requests.get("/api/v1/stock/AAPL/yfinance")

    # Implement caching to reduce API calls
    from functools import lru_cache

    @lru_cache(maxsize=100)
    def cached_stock_quote(symbol):
        return get_stock_quote(symbol)
    ```
  </Accordion>

  <Accordion title="Environment Variables Not Loading">
    **Error**: Server uses "demo" key despite setting FMP\_API\_KEY

    **Debugging**:

    ```bash theme={null}
    # Check if variable is exported
    printenv | grep FMP

    # Check shell configuration
    echo $SHELL
    source ~/.bashrc  # or ~/.zshrc

    # Verify in Python
    python3 -c "import os; print(os.getenv('FMP_API_KEY', 'NOT_SET'))"
    ```

    **Solutions**:

    * Export variables properly: `export FMP_API_KEY="your_key"`
    * Restart terminal after setting variables
    * Use absolute paths in environment files
    * Check for typos in variable names
  </Accordion>
</AccordionGroup>

### Network & Connection Issues

<AccordionGroup>
  <Accordion title="Connection Timeouts">
    **Error**: `TimeoutError` or `ConnectTimeout`

    **Causes**: Network issues, firewall, or API downtime

    **Solutions**:

    ```python theme={null}
    # Increase timeout values
    import requests

    response = requests.get(url, timeout=30)  # 30 second timeout

    # Check network connectivity
    ping google.com
    ping financialmodelingprep.com

    # Test different endpoints
    curl -I https://financialmodelingprep.com/api/v3/quote/AAPL
    ```
  </Accordion>

  <Accordion title="SSL Certificate Errors">
    **Error**: `SSLError` or certificate verification failed

    **Solutions**:

    ```python theme={null}
    # Temporary workaround (not recommended for production)
    import requests
    from requests.packages.urllib3.exceptions import InsecureRequestWarning

    requests.packages.urllib3.disable_warnings(InsecureRequestWarning)
    response = requests.get(url, verify=False)

    # Better solution: Update certificates
    # On macOS:
    brew install ca-certificates

    # On Ubuntu:
    sudo apt-get update && sudo apt-get install ca-certificates
    ```
  </Accordion>

  <Accordion title="DNS Resolution Issues">
    **Error**: `Name or service not known`

    **Solutions**:

    ```bash theme={null}
    # Check DNS resolution
    nslookup financialmodelingprep.com

    # Try different DNS servers
    echo "nameserver 8.8.8.8" | sudo tee /etc/resolv.conf

    # Flush DNS cache
    # macOS:
    sudo dscacheutil -flushcache

    # Linux:
    sudo systemctl restart systemd-resolved
    ```
  </Accordion>
</AccordionGroup>

### Data Quality Issues

<AccordionGroup>
  <Accordion title="Missing or Null Data">
    **Issue**: Some fields return `null` or are missing

    **Causes**:

    * Stock not traded today
    * Data not available for that symbol
    * API source limitations

    **Solutions**:

    ```python theme={null}
    # Handle missing data gracefully
    def safe_get_price(data):
        return data.get("price") or data.get("regularMarketPrice", 0)

    # Validate responses
    def validate_stock_data(data):
        required_fields = ["symbol", "price"]
        for field in required_fields:
            if field not in data or data[field] is None:
                raise ValueError(f"Missing required field: {field}")
    ```
  </Accordion>

  <Accordion title="Stale Data">
    **Issue**: Data appears outdated

    **Causes**:

    * Market closed
    * Caching issues
    * API delays

    **Solutions**:

    ```python theme={null}
    # Check market hours
    from datetime import datetime
    import pytz

    def is_market_open():
        ny_tz = pytz.timezone('America/New_York')
        now = datetime.now(ny_tz)
        # Market open 9:30 AM - 4:00 PM ET, Mon-Fri
        return (now.weekday() < 5 and 
                now.time() >= datetime.strptime("09:30", "%H:%M").time() and
                now.time() <= datetime.strptime("16:00", "%H:%M").time())

    # Add timestamp validation
    def is_data_fresh(timestamp, max_age_minutes=5):
        from datetime import datetime, timedelta
        data_time = datetime.fromisoformat(timestamp.replace('Z', '+00:00'))
        return datetime.now(data_time.tzinfo) - data_time < timedelta(minutes=max_age_minutes)
    ```
  </Accordion>

  <Accordion title="Inconsistent Data Between Sources">
    **Issue**: YFinance and FMP return different values

    **Causes**:

    * Different data sources
    * Update timing differences
    * Currency conversions

    **Solutions**:

    ```python theme={null}
    # Compare data sources
    def compare_sources(symbol):
        yf_data = get_yfinance_quote(symbol)
        fmp_data = get_fmp_quote(symbol)
        
        price_diff = abs(yf_data["price"] - fmp_data["price"])
        tolerance = 0.01  # 1 cent
        
        if price_diff > tolerance:
            print(f"Price difference detected: YF=${yf_data['price']}, FMP=${fmp_data['price']}")

    # Use primary source with fallback
    def get_reliable_quote(symbol):
        try:
            return get_fmp_quote(symbol)  # Primary: FMP
        except Exception:
            return get_yfinance_quote(symbol)  # Fallback: YFinance
    ```
  </Accordion>
</AccordionGroup>

### Performance Issues

<AccordionGroup>
  <Accordion title="Slow Response Times">
    **Issue**: API responses taking too long

    **Causes**:

    * Network latency
    * High server load
    * Inefficient queries

    **Solutions**:

    ```python theme={null}
    # Implement caching
    import time
    from functools import lru_cache

    @lru_cache(maxsize=1000)
    def cached_request(url, timestamp_minute):
        # Cache for 1-minute intervals
        return make_request(url)

    # Use connection pooling
    import requests
    from requests.adapters import HTTPAdapter

    session = requests.Session()
    adapter = HTTPAdapter(pool_connections=10, pool_maxsize=20)
    session.mount('https://', adapter)

    # Parallel requests
    import asyncio
    import aiohttp

    async def fetch_multiple_quotes(symbols):
        async with aiohttp.ClientSession() as session:
            tasks = [fetch_quote(session, symbol) for symbol in symbols]
            return await asyncio.gather(*tasks)
    ```
  </Accordion>

  <Accordion title="Memory Usage Issues">
    **Issue**: High memory consumption

    **Solutions**:

    ```python theme={null}
    # Monitor memory usage
    import psutil
    import os

    def check_memory():
        process = psutil.Process(os.getpid())
        memory_mb = process.memory_info().rss / 1024 / 1024
        print(f"Memory usage: {memory_mb:.2f} MB")

    # Clear caches periodically
    import gc

    def cleanup_memory():
        gc.collect()
        # Clear custom caches if needed
        cached_request.cache_clear()

    # Limit cache sizes
    @lru_cache(maxsize=100)  # Smaller cache
    def limited_cache_function():
        pass
    ```
  </Accordion>
</AccordionGroup>

## Debugging Tools

### Health Check Endpoint

```bash theme={null}
# Check server health
curl "http://localhost:8001/api/v1/health"

# Expected healthy response
{
  "status": "healthy",
  "tools_available": 32,
  "data_sources": ["YFinance", "FMP"],
  "timestamp": "2025-06-28T18:42:12.471731"
}
```

### Logging Configuration

```python theme={null}
# Enable debug logging
import logging

logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)

# Log API requests
logger = logging.getLogger(__name__)

def log_api_request(url, response_time, status_code):
    logger.info(f"API Request: {url} - {status_code} - {response_time:.2f}s")
```

### Testing Individual Components

<CodeGroup>
  ```python Test YFinance theme={null}
  import yfinance as yf

  # Test basic functionality
  ticker = yf.Ticker("AAPL")
  info = ticker.info
  print(f"Symbol: {info.get('symbol')}")
  print(f"Price: {info.get('regularMarketPrice')}")
  ```

  ```python Test FMP API theme={null}
  import requests
  import os

  api_key = os.getenv("FMP_API_KEY")
  url = f"https://financialmodelingprep.com/api/v3/quote/AAPL?apikey={api_key}"

  response = requests.get(url)
  print(f"Status: {response.status_code}")
  print(f"Data: {response.json()}")
  ```

  ```bash Test Server Endpoints theme={null}
  # Test each endpoint individually
  curl "http://localhost:8001/api/v1/stock/AAPL"
  curl "http://localhost:8001/api/v1/market/gainers"
  curl "http://localhost:8001/api/v1/crypto"
  ```
</CodeGroup>

## Performance Monitoring

### Server Metrics

```python theme={null}
# Monitor response times
import time
from functools import wraps

def monitor_performance(func):
    @wraps(func)
    async def wrapper(*args, **kwargs):
        start_time = time.time()
        result = await func(*args, **kwargs)
        end_time = time.time()
        
        logger.info(f"{func.__name__} took {end_time - start_time:.2f}s")
        return result
    return wrapper

@monitor_performance
async def get_stock_quote(symbol):
    # Your function implementation
    pass
```

### Resource Usage

```bash theme={null}
# Monitor system resources
top -p $(pgrep -f "python.*main.py")

# Check network connections
netstat -an | grep :8001

# Monitor disk usage
df -h

# Check memory usage
free -h
```

## Getting Help

### Log Collection

```bash theme={null}
# Collect comprehensive logs
echo "=== System Info ===" > debug.log
uname -a >> debug.log
python3 --version >> debug.log

echo "=== Environment ===" >> debug.log
printenv | grep -E "(FMP|PORT)" >> debug.log

echo "=== Server Logs ===" >> debug.log
python3 main.py 2>&1 | head -50 >> debug.log

echo "=== Network Test ===" >> debug.log
curl -I https://financialmodelingprep.com >> debug.log 2>&1
```

### Support Channels

<CardGroup cols={2}>
  <Card title="GitHub Issues" icon="github" href="https://github.com/your-repo/issues">
    Report bugs and request features
  </Card>

  <Card title="Documentation" icon="book" href="/introduction">
    Check the complete documentation
  </Card>

  <Card title="API Status" icon="activity" href="https://status.financialmodelingprep.com">
    Check FMP service status
  </Card>

  <Card title="Community" icon="users" href="/guides/configuration">
    Join the developer community
  </Card>
</CardGroup>

## Prevention Tips

### Best Practices

1. **Always use environment variables** for API keys
2. **Implement proper error handling** for all API calls
3. **Monitor your API usage** to avoid rate limits
4. **Use caching** to improve performance and reduce API calls
5. **Keep dependencies updated** for security and bug fixes
6. **Test thoroughly** before deploying to production
7. **Monitor server health** and set up alerts
8. **Have fallback strategies** for when primary data sources fail

### Regular Maintenance

```bash theme={null}
# Weekly maintenance script
#!/bin/bash

# Update dependencies
pip install --upgrade -r requirements.txt

# Clear logs older than 7 days
find /var/log/financial-mcp -name "*.log" -mtime +7 -delete

# Restart service
sudo systemctl restart financial-mcp

# Check health
curl -f http://localhost:8001/api/v1/health || echo "Health check failed"
```
