# Railway Deployment Guide for DcisionAI MCP Server

## Overview

Deploy the DcisionAI MCP Server to Railway alongside your existing FastAPI backend.

**Why Railway:**
- ✅ Already using Railway for backend
- ✅ Same infrastructure = easier management
- ✅ FastMCP templates available
- ✅ Git-based deployments
- ✅ Environment variable management

---

## Option 1: FastMCP Template (Easiest)

### Step 1: Create New Service

1. Go to Railway Dashboard
2. Click "New Project" or add service to existing project
3. Select "Deploy from GitHub repo"
4. Choose `dcisionai-mcp-platform` repository
5. Select "FastMCP" template OR "Empty Service"

### Step 2: Configure Service

**If using FastMCP template:**
- Template will auto-detect FastMCP server
- Set entrypoint: `dcisionai_mcp_server.fastmcp_server:mcp`

**If using Empty Service:**
- Railway will auto-detect Python
- Set start command: `python -m dcisionai_mcp_server.fastmcp_server`

### Step 3: Set Environment Variables

In Railway dashboard → Variables:

```bash
# Backend API URL
DCISIONAI_API_URL=https://dcisionai-mcp-platform-production.up.railway.app

# Domain Filter (optional)
DCISIONAI_DOMAIN_FILTER=ria  # or "all" for generic

# Request Timeout
DCISIONAI_REQUEST_TIMEOUT=300

# Async Support
DCISIONAI_ASYNC_ENABLED=true

# Logging
DCISIONAI_LOG_LEVEL=INFO
```

### Step 4: Deploy

Railway will automatically:
1. Detect Python project
2. Install dependencies from `dcisionai_mcp_server/requirements.txt`
3. Start the FastMCP server
4. Provide public URL

---

## Option 2: Custom Dockerfile (More Control)

### Step 1: Create Dockerfile for MCP Server

Create `Dockerfile.mcp`:

```dockerfile
FROM python:3.12-slim

WORKDIR /app

# Copy MCP server package
COPY dcisionai_mcp_server/ /app/dcisionai_mcp_server/
COPY requirements.txt /app/requirements.txt

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

# Expose port (Railway sets PORT env var)
EXPOSE 8080

# Start FastMCP server
CMD ["python", "-m", "dcisionai_mcp_server.fastmcp_server"]
```

### Step 2: Configure Railway

1. Create new service in Railway
2. Connect GitHub repo
3. Set Dockerfile path: `Dockerfile.mcp`
4. Set environment variables (same as Option 1)
5. Deploy

---

## Option 3: Same Service as Backend (Simplest)

### Deploy MCP Server in Same Railway Service

**Pros:**
- ✅ One service = one URL
- ✅ Shared environment variables
- ✅ Lower cost
- ✅ Easier management

**Cons:**
- ⚠️ MCP server runs on same port as backend
- ⚠️ Need to route requests properly

### Implementation

Add MCP server endpoint to existing FastAPI backend:

```python
# In api/fastapi_app.py

from fastmcp import FastMCP
from dcisionai_mcp_server.fastmcp_server import mcp as mcp_server

@app.post("/mcp")
async def mcp_endpoint(request: Request):
    """MCP protocol endpoint"""
    # Forward requests to FastMCP server
    return await mcp_server.handle_request(request)
```

**Benefits:**
- Same URL as backend
- Shared infrastructure
- No separate service needed

---

## Configuration Files

### railway.toml (for MCP service)

```toml
[build]
builder = "nixpacks"

[deploy]
startCommand = "python -m dcisionai_mcp_server.fastmcp_server"
healthcheckPath = "/health"
healthcheckTimeout = 100
restartPolicyType = "on_failure"
```

### Environment Variables

Set in Railway dashboard:

| Variable | Value | Required |
|----------|-------|----------|
| `DCISIONAI_API_URL` | Backend URL | ✅ Yes |
| `DCISIONAI_DOMAIN_FILTER` | `ria` or `all` | ❌ No |
| `DCISIONAI_REQUEST_TIMEOUT` | `300` | ❌ No |
| `DCISIONAI_ASYNC_ENABLED` | `true` | ❌ No |
| `DCISIONAI_LOG_LEVEL` | `INFO` | ❌ No |

---

## Deployment Workflow

### Automatic Deployment

1. **Push to GitHub:**
   ```bash
   git push origin prod
   ```

2. **Railway Auto-Deploys:**
   - Detects changes
   - Builds new image
   - Deploys to production
   - Health check runs

3. **Verify Deployment:**
   ```bash
   curl https://your-mcp-server.railway.app/health
   ```

### Manual Deployment

1. Go to Railway Dashboard
2. Select MCP server service
3. Click "Deploy" → "Redeploy"

---

## Testing Deployment

### Test MCP Server

```bash
# Test tools list
curl https://your-mcp-server.railway.app/mcp \
  -H "Content-Type: application/json" \
  -d '{"method": "tools/list"}'

# Should return:
# {
#   "tools": [
#     {"name": "dcisionai_solve", ...},
#     {"name": "dcisionai_solve_with_model", ...}
#   ]
# }
```

### Test Tool Call

```bash
curl https://your-mcp-server.railway.app/mcp \
  -H "Content-Type: application/json" \
  -d '{
    "method": "tools/call",
    "params": {
      "name": "dcisionai_solve",
      "arguments": {
        "problem_description": "Optimize a portfolio"
      }
    }
  }'
```

---

## Monitoring

### Railway Dashboard

- **Logs**: Real-time log streaming
- **Metrics**: CPU, RAM, requests
- **Deployments**: History and rollback
- **Environment**: Variable management

### Health Checks

Railway automatically checks:
- `/health` endpoint (if configured)
- Process is running
- Port is accessible

---

## Troubleshooting

### Build Fails

**Issue:** Module not found
**Fix:** Ensure `dcisionai_mcp_server/requirements.txt` includes all dependencies

**Issue:** Import error
**Fix:** Check absolute imports in `fastmcp_server.py`

### Server Not Starting

**Issue:** Port binding error
**Fix:** Railway sets `PORT` env var automatically, ensure server uses it

**Issue:** Environment variables missing
**Fix:** Check Railway dashboard → Variables

### Tools Not Appearing

**Issue:** FastMCP server not loading
**Fix:** Check logs for import errors

---

## Cost Estimate

**Railway Pricing:**
- **Hobby Plan**: $5/month + usage
- **Pro Plan**: $20/month + usage

**MCP Server Usage:**
- Low traffic: ~$5-10/month
- Medium traffic: ~$10-20/month
- High traffic: ~$20-50/month

**Total (Backend + MCP Server):**
- Low: ~$10-15/month
- Medium: ~$25-40/month
- High: ~$50-100/month

---

## Comparison: Railway vs FastMCP Cloud

| Feature | Railway | FastMCP Cloud |
|---------|---------|---------------|
| **Setup** | ⭐⭐⭐⭐ Easy | ⭐⭐⭐⭐⭐ Easier |
| **Control** | ⭐⭐⭐⭐ More | ⭐⭐ Less |
| **Cost** | $$ Pay for usage | $ Free tier |
| **Reliability** | ⭐⭐⭐⭐⭐ Proven | ⭐⭐⭐ Newer |
| **Your Experience** | ✅ Backend working | ❌ Build failing |
| **Infrastructure** | ✅ Same as backend | ❌ Separate |

**Recommendation:** Use Railway - you're already using it successfully!

---

## Next Steps

1. **Create Railway Service:**
   - New service → GitHub repo → FastMCP template

2. **Configure:**
   - Set environment variables
   - Set entrypoint: `dcisionai_mcp_server.fastmcp_server:mcp`

3. **Deploy:**
   - Railway auto-deploys on push to `prod`

4. **Test:**
   - Verify MCP server is accessible
   - Test tools and resources

5. **Monitor:**
   - Check Railway dashboard for logs
   - Monitor usage and costs

---

## References

- Railway Docs: https://docs.railway.app/
- Railway FastMCP: https://railway.com/deploy/fastmcp
- FastMCP Docs: https://fastmcp.wiki/
- Your Backend: https://dcisionai-mcp-platform-production.up.railway.app

