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

# Deployment Guide

> Deploy the Financial MCP Server to production environments

## Overview

The Financial MCP Server can be deployed to various platforms, from simple cloud services to enterprise Kubernetes clusters. This guide covers the most popular deployment options with step-by-step instructions.

<CardGroup cols={2}>
  <Card title="Railway" icon="train" color="#0D1117">
    **Recommended for beginners**

    * Zero-config deployment
    * Automatic scaling
    * Built-in monitoring
  </Card>

  <Card title="Docker" icon="docker" color="#2496ED">
    **Flexible containerization**

    * Platform independent
    * Easy scaling
    * Production ready
  </Card>
</CardGroup>

## Railway Deployment (Recommended)

Railway offers the simplest deployment experience with automatic builds and scaling.

### Prerequisites

* GitHub account
* Railway account (free tier available)
* FMP API key (optional but recommended)

### Step 1: Fork the Repository

1. Visit the [GitHub repository](https://github.com/your-username/yfi-deployment)
2. Click "Fork" to create your own copy
3. Clone your fork locally for any customizations

### Step 2: Connect to Railway

<Steps>
  <Step title="Create Railway Project">
    1. Go to [Railway](https://railway.app)
    2. Sign up/login with GitHub
    3. Click "New Project"
    4. Select "Deploy from GitHub repo"
    5. Choose your forked repository
  </Step>

  <Step title="Configure Environment Variables">
    1. In Railway dashboard, go to your project
    2. Click "Variables" tab
    3. Add the following variables:

    ```
    FMP_API_KEY=your_actual_api_key_here
    PORT=$PORT
    ```
  </Step>

  <Step title="Deploy">
    Railway automatically detects the Python app and deploys it using the `Procfile`.

    The deployment process:

    * Detects Python runtime
    * Installs dependencies from `requirements.txt`
    * Runs the command from `Procfile`
    * Assigns a public URL
  </Step>
</Steps>

### Step 3: Verify Deployment

```bash theme={null}
# Test your deployed server
curl "https://your-app-name.railway.app/api/v1/health"

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

### Railway Configuration

<CodeGroup>
  ```toml railway.json theme={null}
  {
    "build": {
      "builder": "NIXPACKS"
    },
    "deploy": {
      "restartPolicyType": "ON_FAILURE",
      "restartPolicyMaxRetries": 10
    }
  }
  ```

  ```text Procfile theme={null}
  web: python main.py
  ```

  ```txt requirements.txt theme={null}
  fastapi==0.104.1
  uvicorn==0.24.0
  yfinance==0.2.18
  requests==2.31.0
  python-dotenv==1.0.0
  mcp==0.9.0
  ```
</CodeGroup>

## Docker Deployment

Docker provides a consistent deployment environment across different platforms.

### Prerequisites

* Docker installed
* Docker Hub account (for image hosting)
* Basic Docker knowledge

### Step 1: Build Docker Image

<CodeGroup>
  ```dockerfile Dockerfile theme={null}
  FROM python:3.11-slim

  # Set working directory
  WORKDIR /app

  # Copy requirements first for better caching
  COPY requirements.txt .

  # Install dependencies
  RUN pip install --no-cache-dir -r requirements.txt

  # Copy application code
  COPY . .

  # Expose port
  EXPOSE 8001

  # Health check
  HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
    CMD curl -f http://localhost:8001/api/v1/health || exit 1

  # Run the application
  CMD ["python", "main.py"]
  ```

  ```bash Build Commands theme={null}
  # Build the image
  docker build -t financial-mcp-server .

  # Run locally
  docker run -p 8001:8001 \
    -e FMP_API_KEY=your_api_key \
    financial-mcp-server

  # Test the container
  curl "http://localhost:8001/api/v1/health"
  ```
</CodeGroup>

### Step 2: Docker Compose (Recommended)

<CodeGroup>
  ```yaml docker-compose.yml theme={null}
  version: '3.8'

  services:
    financial-mcp:
      build: .
      ports:
        - "8001:8001"
      environment:
        - FMP_API_KEY=${FMP_API_KEY}
        - PORT=8001
      restart: unless-stopped
      healthcheck:
        test: ["CMD", "curl", "-f", "http://localhost:8001/api/v1/health"]
        interval: 30s
        timeout: 10s
        retries: 3
        start_period: 40s

    # Optional: Add reverse proxy
    nginx:
      image: nginx:alpine
      ports:
        - "80:80"
        - "443:443"
      volumes:
        - ./nginx.conf:/etc/nginx/nginx.conf
      depends_on:
        - financial-mcp
      restart: unless-stopped
  ```

  ```bash Docker Compose Commands theme={null}
  # Create .env file
  echo "FMP_API_KEY=your_actual_api_key" > .env

  # Start services
  docker-compose up -d

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

  # Stop services
  docker-compose down
  ```
</CodeGroup>

### Step 3: Production Docker Setup

<CodeGroup>
  ```bash Multi-stage Build theme={null}
  # Optimized Dockerfile for production
  FROM python:3.11-slim as builder

  WORKDIR /app
  COPY requirements.txt .
  RUN pip install --user --no-cache-dir -r requirements.txt

  FROM python:3.11-slim

  # Create non-root user
  RUN useradd --create-home --shell /bin/bash app

  # Copy installed packages
  COPY --from=builder /root/.local /home/app/.local
  COPY --chown=app:app . /home/app/

  WORKDIR /home/app
  USER app

  # Make sure scripts are in PATH
  ENV PATH=/home/app/.local/bin:$PATH

  EXPOSE 8001
  CMD ["python", "main.py"]
  ```

  ```bash Docker Hub Deployment theme={null}
  # Tag for Docker Hub
  docker tag financial-mcp-server username/financial-mcp-server:latest

  # Push to Docker Hub
  docker push username/financial-mcp-server:latest

  # Deploy anywhere
  docker run -d \
    --name financial-mcp \
    -p 8001:8001 \
    -e FMP_API_KEY=your_key \
    --restart unless-stopped \
    username/financial-mcp-server:latest
  ```
</CodeGroup>

## Heroku Deployment

Heroku provides a simple platform-as-a-service solution.

### Prerequisites

* Heroku account
* Heroku CLI installed
* Git repository

### Deployment Steps

<Steps>
  <Step title="Prepare Application">
    Ensure your repository has the required files:

    ```
    ├── main.py
    ├── requirements.txt
    ├── Procfile
    └── runtime.txt (optional)
    ```
  </Step>

  <Step title="Create Heroku App">
    ```bash theme={null}
    # Login to Heroku
    heroku login

    # Create new app
    heroku create your-financial-mcp-server

    # Set environment variables
    heroku config:set FMP_API_KEY=your_actual_api_key
    ```
  </Step>

  <Step title="Deploy">
    ```bash theme={null}
    # Add Heroku remote
    heroku git:remote -a your-financial-mcp-server

    # Deploy
    git push heroku main

    # Open in browser
    heroku open
    ```
  </Step>
</Steps>

### Heroku Configuration

<CodeGroup>
  ```text Procfile theme={null}
  web: python main.py
  ```

  ```text runtime.txt theme={null}
  python-3.11.6
  ```

  ```bash Heroku Commands theme={null}
  # View logs
  heroku logs --tail

  # Scale dynos
  heroku ps:scale web=1

  # Check status
  heroku ps

  # Set config vars
  heroku config:set FMP_API_KEY=new_key
  ```
</CodeGroup>

## VPS/Cloud Server Deployment

Deploy to any cloud server (AWS EC2, DigitalOcean, Linode, etc.).

### Prerequisites

* Ubuntu/Debian server
* SSH access
* Domain name (optional)

### Step 1: Server Setup

<CodeGroup>
  ```bash Initial Setup theme={null}
  # Update system
  sudo apt update && sudo apt upgrade -y

  # Install Python and dependencies
  sudo apt install python3 python3-pip python3-venv nginx git -y

  # Create application user
  sudo useradd -m -s /bin/bash financial-mcp
  sudo su - financial-mcp
  ```

  ```bash Application Setup theme={null}
  # Clone repository
  git clone https://github.com/your-username/yfi-deployment.git
  cd yfi-deployment

  # Create virtual environment
  python3 -m venv venv
  source venv/bin/activate

  # Install dependencies
  pip install -r requirements.txt

  # Set environment variables
  echo "export FMP_API_KEY='your_actual_api_key'" >> ~/.bashrc
  echo "export PORT=8001" >> ~/.bashrc
  source ~/.bashrc
  ```
</CodeGroup>

### Step 2: Process Management

<CodeGroup>
  ```ini systemd Service theme={null}
  # Create /etc/systemd/system/financial-mcp.service
  [Unit]
  Description=Financial MCP Server
  After=network.target

  [Service]
  Type=simple
  User=financial-mcp
  WorkingDirectory=/home/financial-mcp/yfi-deployment
  Environment=PATH=/home/financial-mcp/yfi-deployment/venv/bin
  Environment=FMP_API_KEY=your_actual_api_key
  Environment=PORT=8001
  ExecStart=/home/financial-mcp/yfi-deployment/venv/bin/python main.py
  Restart=always
  RestartSec=3

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

  ```bash Service Management theme={null}
  # Enable and start service
  sudo systemctl enable financial-mcp
  sudo systemctl start financial-mcp

  # Check status
  sudo systemctl status financial-mcp

  # View logs
  sudo journalctl -u financial-mcp -f
  ```
</CodeGroup>

### Step 3: Reverse Proxy (Nginx)

<CodeGroup>
  ```nginx Nginx Configuration theme={null}
  # /etc/nginx/sites-available/financial-mcp
  server {
      listen 80;
      server_name your-domain.com;

      location / {
          proxy_pass http://127.0.0.1:8001;
          proxy_set_header Host $host;
          proxy_set_header X-Real-IP $remote_addr;
          proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
          proxy_set_header X-Forwarded-Proto $scheme;
      }
  }
  ```

  ```bash Nginx Setup theme={null}
  # Enable site
  sudo ln -s /etc/nginx/sites-available/financial-mcp /etc/nginx/sites-enabled/

  # Test configuration
  sudo nginx -t

  # Restart nginx
  sudo systemctl restart nginx

  # Optional: Setup SSL with Let's Encrypt
  sudo apt install certbot python3-certbot-nginx -y
  sudo certbot --nginx -d your-domain.com
  ```
</CodeGroup>

## Kubernetes Deployment

For enterprise deployments requiring high availability and scaling.

### Prerequisites

* Kubernetes cluster
* kubectl configured
* Basic Kubernetes knowledge

### Deployment Manifests

<CodeGroup>
  ```yaml Deployment theme={null}
  apiVersion: apps/v1
  kind: Deployment
  metadata:
    name: financial-mcp-server
    labels:
      app: financial-mcp
  spec:
    replicas: 3
    selector:
      matchLabels:
        app: financial-mcp
    template:
      metadata:
        labels:
          app: financial-mcp
      spec:
        containers:
        - name: financial-mcp
          image: username/financial-mcp-server:latest
          ports:
          - containerPort: 8001
          env:
          - name: FMP_API_KEY
            valueFrom:
              secretKeyRef:
                name: financial-mcp-secret
                key: fmp-api-key
          - name: PORT
            value: "8001"
          livenessProbe:
            httpGet:
              path: /api/v1/health
              port: 8001
            initialDelaySeconds: 30
            periodSeconds: 10
          readinessProbe:
            httpGet:
              path: /api/v1/health
              port: 8001
            initialDelaySeconds: 5
            periodSeconds: 5
  ```

  ```yaml Service & Ingress theme={null}
  ---
  apiVersion: v1
  kind: Service
  metadata:
    name: financial-mcp-service
  spec:
    selector:
      app: financial-mcp
    ports:
      - protocol: TCP
        port: 80
        targetPort: 8001
    type: ClusterIP

  ---
  apiVersion: networking.k8s.io/v1
  kind: Ingress
  metadata:
    name: financial-mcp-ingress
    annotations:
      kubernetes.io/ingress.class: nginx
      cert-manager.io/cluster-issuer: letsencrypt-prod
  spec:
    tls:
    - hosts:
      - api.your-domain.com
      secretName: financial-mcp-tls
    rules:
    - host: api.your-domain.com
      http:
        paths:
        - path: /
          pathType: Prefix
          backend:
            service:
              name: financial-mcp-service
              port:
                number: 80
  ```
</CodeGroup>

### Kubernetes Commands

<CodeGroup>
  ```bash Secret Management theme={null}
  # Create secret for API key
  kubectl create secret generic financial-mcp-secret \
    --from-literal=fmp-api-key=your_actual_api_key

  # Apply manifests
  kubectl apply -f k8s/
  ```

  ```bash Monitoring theme={null}
  # Check deployment
  kubectl get deployments

  # View pods
  kubectl get pods

  # Check logs
  kubectl logs -l app=financial-mcp

  # Scale deployment
  kubectl scale deployment financial-mcp-server --replicas=5
  ```
</CodeGroup>

## Monitoring & Maintenance

### Health Monitoring

<CodeGroup>
  ```bash Health Checks theme={null}
  # Basic health check
  curl -f https://your-domain.com/api/v1/health

  # Detailed monitoring script
  #!/bin/bash
  ENDPOINT="https://your-domain.com/api/v1/health"
  RESPONSE=$(curl -s $ENDPOINT)
  STATUS=$(echo $RESPONSE | jq -r '.status')

  if [ "$STATUS" != "healthy" ]; then
      echo "Server unhealthy: $RESPONSE"
      # Send alert (email, Slack, etc.)
  fi
  ```

  ```python Uptime Monitoring theme={null}
  # Simple Python monitoring script
  import requests
  import time
  import logging

  def check_health():
      try:
          response = requests.get("https://your-domain.com/api/v1/health", timeout=10)
          if response.status_code == 200:
              data = response.json()
              logging.info(f"Server healthy: {data['tools_available']} tools available")
              return True
          else:
              logging.error(f"Health check failed: {response.status_code}")
              return False
      except Exception as e:
          logging.error(f"Health check exception: {e}")
          return False

  # Run every 5 minutes
  while True:
      check_health()
      time.sleep(300)
  ```
</CodeGroup>

### Log Management

<CodeGroup>
  ```bash Log Rotation theme={null}
  # Setup logrotate for application logs
  sudo cat > /etc/logrotate.d/financial-mcp << EOF
  /var/log/financial-mcp/*.log {
      daily
      missingok
      rotate 14
      compress
      delaycompress
      notifempty
      create 644 financial-mcp financial-mcp
      postrotate
          systemctl reload financial-mcp
      endscript
  }
  EOF
  ```

  ```python Structured Logging theme={null}
  import logging
  import json
  from datetime import datetime

  class JSONFormatter(logging.Formatter):
      def format(self, record):
          log_entry = {
              "timestamp": datetime.utcnow().isoformat(),
              "level": record.levelname,
              "message": record.getMessage(),
              "module": record.module,
              "function": record.funcName,
              "line": record.lineno
          }
          return json.dumps(log_entry)

  # Configure logging
  handler = logging.StreamHandler()
  handler.setFormatter(JSONFormatter())
  logger = logging.getLogger()
  logger.addHandler(handler)
  logger.setLevel(logging.INFO)
  ```
</CodeGroup>

## Troubleshooting

### Common Deployment 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`

    **Solutions**:

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

    # Kill process
    kill -9 <PID>

    # Or use different port
    export PORT=8002
    ```
  </Accordion>

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

    **Solutions**:

    ```bash theme={null}
    # Verify environment variables
    printenv | grep FMP

    # Restart service after setting variables
    sudo systemctl restart financial-mcp

    # Check service environment
    sudo systemctl show financial-mcp --property=Environment
    ```
  </Accordion>

  <Accordion title="Docker Container Exits">
    **Error**: Container exits immediately after starting

    **Solutions**:

    ```bash theme={null}
    # Check container logs
    docker logs container-name

    # Run interactively for debugging
    docker run -it --entrypoint /bin/bash financial-mcp-server

    # Check if all dependencies are installed
    docker run financial-mcp-server pip list
    ```
  </Accordion>
</AccordionGroup>

## Performance Optimization

### Production Optimizations

<CodeGroup>
  ```python Async Optimization theme={null}
  # Use connection pooling
  import aiohttp
  import asyncio

  # Global session with connection pooling
  session = aiohttp.ClientSession(
      connector=aiohttp.TCPConnector(
          limit=100,
          limit_per_host=30,
          keepalive_timeout=30
      )
  )

  # Implement caching
  from functools import lru_cache
  import time

  @lru_cache(maxsize=1000)
  def get_cached_data(symbol: str, minute: int):
      # Cache data for 1-minute intervals
      return fetch_data(symbol)
  ```

  ```bash Resource Limits theme={null}
  # Docker resource limits
  docker run -d \
    --name financial-mcp \
    --memory=512m \
    --cpus=1.0 \
    -p 8001:8001 \
    financial-mcp-server

  # Kubernetes resource limits
  resources:
    limits:
      memory: "512Mi"
      cpu: "500m"
    requests:
      memory: "256Mi"
      cpu: "250m"
  ```
</CodeGroup>

## Next Steps

<CardGroup cols={2}>
  <Card title="Monitoring Setup" icon="chart-line" href="/guides/configuration">
    Set up comprehensive monitoring and alerting
  </Card>

  <Card title="Security Guide" icon="shield" href="/api-reference/authentication">
    Implement security best practices
  </Card>

  <Card title="Scaling Guide" icon="arrows-maximize" href="/guides/troubleshooting">
    Handle high-traffic scenarios
  </Card>

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