Skip to main content

Common Issues

Server Startup Issues

Error: [Errno 48] error while attempting to bind on address ('0.0.0.0', 8001): [errno 48] address already in useCause: Another process is using port 8001Solutions:
# 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
Error: ModuleNotFoundError: No module named 'fastapi'Cause: Dependencies not installedSolutions:
# Install dependencies
pip install -r requirements.txt

# Or install specific package
pip install fastapi uvicorn

# Check virtual environment
which python
pip list
Error: PermissionError: [Errno 13] Permission deniedCause: Insufficient permissions or port restrictionsSolutions:
# 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

API Key Issues

Error: 401 Unauthorized or Invalid API keyDebugging Steps:
# 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
Error: 429 Too Many RequestsSymptoms: Requests failing after working initiallySolutions:
# 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)
Error: Server uses “demo” key despite setting FMP_API_KEYDebugging:
# 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

Network & Connection Issues

Error: TimeoutError or ConnectTimeoutCauses: Network issues, firewall, or API downtimeSolutions:
# 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
Error: SSLError or certificate verification failedSolutions:
# 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
Error: Name or service not knownSolutions:
# 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

Data Quality Issues

Issue: Some fields return null or are missingCauses:
  • Stock not traded today
  • Data not available for that symbol
  • API source limitations
Solutions:
# 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}")
Issue: Data appears outdatedCauses:
  • Market closed
  • Caching issues
  • API delays
Solutions:
# 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)
Issue: YFinance and FMP return different valuesCauses:
  • Different data sources
  • Update timing differences
  • Currency conversions
Solutions:
# 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

Performance Issues

Issue: API responses taking too longCauses:
  • Network latency
  • High server load
  • Inefficient queries
Solutions:
# 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)
Issue: High memory consumptionSolutions:
# 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

Debugging Tools

Health Check Endpoint

# 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

# 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

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')}")

Performance Monitoring

Server Metrics

# 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

# 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

# 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

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

# 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"