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

# Authentication

> API key setup and authentication methods for the Financial MCP Server

## Overview

The Financial MCP Server uses a hybrid authentication model depending on the data source and deployment method. Understanding the authentication requirements is crucial for proper setup and usage.

<Info>
  **YFinance tools require no authentication**, while **FMP tools require an API key** for full functionality.
</Info>

## Authentication Methods

### 1. No Authentication (YFinance)

YFinance tools work immediately without any setup:

```bash theme={null}
# Works without any API keys
curl "http://localhost:8001/api/v1/stock/AAPL/yfinance"
```

**Available without authentication:**

* Basic stock quotes
* Company information
* Historical data
* Symbol search
* Analyst recommendations
* Insider transactions

### 2. FMP API Key (Professional Tools)

FMP tools require a valid API key for access:

```bash theme={null}
# Requires FMP_API_KEY environment variable
curl "http://localhost:8001/api/v1/stock/AAPL"
```

## Getting FMP API Key

### Step 1: Create Account

1. Visit [Financial Modeling Prep](https://financialmodelingprep.com/developer/docs)
2. Click "Sign Up" to create a free account
3. Verify your email address
4. Complete the registration process

### Step 2: Access Dashboard

1. Log in to your FMP account
2. Navigate to the API Dashboard
3. Find your API key in the "API Key" section
4. Copy the key for use in your application

### Step 3: Choose Plan

| Plan             | Requests/Day | Price      | Features                            |
| ---------------- | ------------ | ---------- | ----------------------------------- |
| **Free**         | 250          | \$0        | Basic data, perfect for development |
| **Starter**      | 1,000        | \$15/month | Production-ready for small apps     |
| **Professional** | 10,000       | \$50/month | High-volume applications            |
| **Enterprise**   | Custom       | Custom     | Unlimited with premium support      |

## Environment Configuration

### Local Development

<CodeGroup>
  ```bash Environment Variables theme={null}
  # Set environment variables
  export FMP_API_KEY="your_actual_api_key_here"
  export PORT=8001

  # Start the server
  python3 main.py
  ```

  ```bash .env File theme={null}
  # Create .env file in project root
  echo "FMP_API_KEY=your_actual_api_key_here" > .env
  echo "PORT=8001" >> .env

  # Load and start
  source .env
  python3 main.py
  ```

  ```bash Windows theme={null}
  # Windows Command Prompt
  set FMP_API_KEY=your_actual_api_key_here
  set PORT=8001
  python main.py

  # Windows PowerShell
  $env:FMP_API_KEY="your_actual_api_key_here"
  $env:PORT=8001
  python main.py
  ```
</CodeGroup>

### Production Deployment

<CodeGroup>
  ```bash Railway theme={null}
  # Set environment variables in Railway dashboard
  FMP_API_KEY=your_actual_api_key_here
  PORT=$PORT
  ```

  ```bash Heroku theme={null}
  # Set config vars
  heroku config:set FMP_API_KEY=your_actual_api_key_here
  heroku config:set PORT=8001
  ```

  ```yaml Docker Compose theme={null}
  version: '3.8'
  services:
    financial-mcp:
      build: .
      environment:
        - FMP_API_KEY=your_actual_api_key_here
        - PORT=8001
      ports:
        - "8001:8001"
  ```

  ```bash VPS/Cloud theme={null}
  # Add to systemd service file
  Environment=FMP_API_KEY=your_actual_api_key_here
  Environment=PORT=8001
  ```
</CodeGroup>

## API Key Validation

### Testing Your Setup

<CodeGroup>
  ```bash Test FMP Connection theme={null}
  # Test FMP API key
  curl "http://localhost:8001/api/v1/stock/AAPL"

  # Expected: Stock data with "source": "FMP"
  ```

  ```bash Test YFinance Fallback theme={null}
  # Test YFinance (no API key needed)
  curl "http://localhost:8001/api/v1/stock/AAPL/yfinance"

  # Expected: Stock data from Yahoo Finance
  ```

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

  # Expected: Server health and tool availability
  ```
</CodeGroup>

### Server Response Indicators

#### Valid FMP API Key

```json theme={null}
{
  "symbol": "AAPL",
  "price": 201.08,
  "source": "FMP",
  "timestamp": "2025-06-28T18:42:12.471731"
}
```

#### Invalid/Missing FMP API Key

```json theme={null}
{
  "error": "FMP API key required. Set FMP_API_KEY environment variable.",
  "setup_instructions": "Get a free API key at: https://financialmodelingprep.com/developer/docs"
}
```

#### YFinance Fallback Active

```json theme={null}
{
  "symbol": "AAPL",
  "price": 201.08,
  "currency": "USD",
  "timestamp": "2025-06-28T18:42:12.471731"
}
```

## Rate Limiting & Quotas

### FMP Rate Limits

Rate limits are enforced per API key:

| Plan         | Daily Limit | Per-Minute Limit | Overage         |
| ------------ | ----------- | ---------------- | --------------- |
| Free         | 250         | 5                | Blocked         |
| Starter      | 1,000       | 20               | \$0.01/request  |
| Professional | 10,000      | 100              | \$0.005/request |

### Rate Limit Headers

FMP responses include rate limit information:

```http theme={null}
X-RateLimit-Limit: 250
X-RateLimit-Remaining: 247
X-RateLimit-Reset: 1640995200
X-RateLimit-Used: 3
```

### Handling Rate Limits

The server automatically handles rate limiting:

```python theme={null}
# Automatic rate limit detection
if "rate limit" in response.get("error", "").lower():
    # Fallback to YFinance if available
    # Or return rate limit error with retry information
```

## Security Best Practices

### 1. API Key Protection

<AccordionGroup>
  <Accordion title="Environment Variables">
    **✅ DO**: Store API keys in environment variables

    ```bash theme={null}
    export FMP_API_KEY="your_key"
    ```

    **❌ DON'T**: Hardcode keys in source code

    ```python theme={null}
    # NEVER DO THIS
    FMP_API_KEY = "your_actual_key_here"
    ```
  </Accordion>

  <Accordion title="Version Control">
    **✅ DO**: Add .env to .gitignore

    ```bash theme={null}
    echo ".env" >> .gitignore
    ```

    **❌ DON'T**: Commit API keys to repositories
  </Accordion>

  <Accordion title="Production Deployment">
    **✅ DO**: Use platform environment variable systems

    * Railway: Environment Variables tab
    * Heroku: Config Vars
    * Docker: Environment variables

    **❌ DON'T**: Include keys in Docker images or config files
  </Accordion>
</AccordionGroup>

### 2. Access Control

```python theme={null}
# Optional: Add API key validation for your endpoints
@app.middleware("http")
async def validate_access(request: Request, call_next):
    # Add your own authentication logic here
    response = await call_next(request)
    return response
```

### 3. Monitoring & Alerting

```python theme={null}
# Monitor API usage
@app.middleware("http")
async def log_requests(request: Request, call_next):
    start_time = time.time()
    response = await call_next(request)
    process_time = time.time() - start_time
    
    logger.info("Request processed", extra={
        "path": request.url.path,
        "method": request.method,
        "process_time": process_time,
        "status_code": response.status_code
    })
    
    return response
```

## Troubleshooting

### Common Issues

<AccordionGroup>
  <Accordion title="Invalid API Key">
    **Symptoms**: 401 Unauthorized errors

    **Solutions**:

    * Verify API key is correct (copy-paste from FMP dashboard)
    * Check environment variable is set: `echo $FMP_API_KEY`
    * Restart server after setting environment variables
    * Ensure no extra spaces or characters in the key
  </Accordion>

  <Accordion title="Rate Limit Exceeded">
    **Symptoms**: 429 Too Many Requests errors

    **Solutions**:

    * Check your FMP dashboard for usage statistics
    * Implement caching to reduce API calls
    * Upgrade to higher tier plan
    * Use YFinance endpoints for basic data
  </Accordion>

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

    **Solutions**:

    * Restart terminal/shell after setting variables
    * Use `printenv | grep FMP` to verify variables are set
    * Check .env file is in correct directory
    * Ensure proper syntax in environment files
  </Accordion>
</AccordionGroup>

### Debugging Commands

<CodeGroup>
  ```bash Check Environment theme={null}
  # Verify environment variables
  echo "FMP API Key: $FMP_API_KEY"
  echo "Port: $PORT"

  # Check if variables are exported
  printenv | grep FMP
  ```

  ```bash Test API Key theme={null}
  # Direct API test
  curl "https://financialmodelingprep.com/api/v3/quote/AAPL?apikey=$FMP_API_KEY"

  # Should return AAPL data if key is valid
  ```

  ```bash Server Logs theme={null}
  # Check server logs for authentication issues
  python3 main.py 2>&1 | grep -i "api\|auth\|key"
  ```
</CodeGroup>

## Migration Guide

### From Demo to Production

1. **Get Production API Key**
   ```bash theme={null}
   # Replace demo key with production key
   export FMP_API_KEY="your_production_key"
   ```

2. **Update Deployment Configuration**
   ```bash theme={null}
   # Update your deployment platform
   # Railway: Environment Variables
   # Heroku: heroku config:set FMP_API_KEY=new_key
   ```

3. **Test Production Setup**
   ```bash theme={null}
   # Verify production key works
   curl "http://your-domain.com/api/v1/stock/AAPL"
   ```

4. **Monitor Usage**
   * Check FMP dashboard regularly
   * Set up usage alerts
   * Plan for scaling if needed

## Next Steps

<CardGroup cols={2}>
  <Card title="Get FMP API Key" icon="key" href="https://financialmodelingprep.com/developer/docs">
    Sign up for free FMP account
  </Card>

  <Card title="Installation Guide" icon="download" href="/installation">
    Complete server setup instructions
  </Card>

  <Card title="API Reference" icon="book" href="/api-reference/introduction">
    Explore all available endpoints
  </Card>

  <Card title="Deployment Guide" icon="rocket" href="/guides/deployment">
    Deploy to production platforms
  </Card>
</CardGroup>
