FastMCP Gateway
by 4human-ai
README.md
# FastMCP Gateway
> **Enterprise API to MCP Server Gateway** - Convierte automáticamente especificaciones OpenAPI en servidores MCP usando FastMCP
Un gateway empresarial tipo LiteLLM pero para Model Context Protocol (MCP), que te permite exponer cualquier API REST como un servidor MCP sin escribir código.
## 🎯 ¿Qué es FastMCP Gateway?
FastMCP Gateway es un sistema que convierte automáticamente APIs REST (definidas con OpenAPI/Swagger) en servidores [Model Context Protocol (MCP)](https://modelcontextprotocol.io/). Esto permite que herramientas como Claude Desktop puedan interactuar directamente con tus APIs empresariales a través de un protocolo estándar.
**Piensa en ello como LiteLLM, pero para MCP en lugar de LLMs.**
## ✨ Características Principales
- 🔄 **Conversión Automática**: Convierte especificaciones OpenAPI en servidores MCP usando FastMCP
- 🔐 **Autenticación Empresarial**: Soporte para Bearer tokens, API keys, Basic Auth y OAuth2
- 👥 **Gestión de Equipos**: Control de acceso granular por equipos y APIs
- 🚀 **Recarga en Caliente**: Agrega nuevas APIs sin reiniciar usando el endpoint `/admin/reload`
- 📊 **Observabilidad**: Métricas Prometheus integradas y logging estructurado
- 🎛️ **Rate Limiting**: Control de tasa por equipo y API
- 🐳 **Docker Ready**: Containerización completa con Docker Compose
- 📝 **Configuración Declarativa**: Todo se configura mediante YAML simple
## 📋 Requisitos Previos
- **Python 3.9+** o **Docker** + **Docker Compose**
- Especificaciones OpenAPI de las APIs que quieres exponer
- Tokens de autenticación para los backends (si son privados)
## 🚀 Instalación Rápida
### Opción 1: Usando el Script de Inicio (Recomendado)
```bash
# 1. Clonar o descargar el proyecto
cd fastmcp-gateway
# 2. Configurar variables de entorno
cp .env.example .env
nano .env # Edita con tus tokens
# 3. Ejecutar el script de inicio
./start.sh
```
El script `start.sh` automáticamente:
- ✅ Verifica la versión de Python
- ✅ Crea y activa un virtualenv
- ✅ Instala todas las dependencias
- ✅ Valida la configuración
- ✅ Inicia el servidor
### Opción 2: Usando Docker Compose
```bash
# 1. Configurar variables de entorno
cp .env.example .env
nano .env
# 2. Iniciar con Docker
docker-compose up -d
# 3. Ver logs
docker-compose logs -f
# 4. Verificar estado
curl http://localhost:4000/health
```
### Opción 3: Instalación Manual
```bash
# 1. Crear entorno virtual
python3 -m venv venv
source venv/bin/activate
# 2. Instalar dependencias
pip install -r requirements.txt
# 3. Configurar variables de entorno
cp .env.example .env
# 4. Iniciar servidor
python gateway.py
```
## ⚙️ Configuración
### Estructura del config.yaml
El archivo `config.yaml` es el corazón del gateway. Aquí defines todas tus APIs:
```yaml
gateway:
name: "FastMCP Enterprise Gateway"
host: "0.0.0.0"
port: 4000
log_level: "INFO"
master_key: "${GATEWAY_MASTER_KEY}"
require_auth: true
apis:
- name: "crm"
display_name: "CRM System API"
description: "Sistema de gestión de clientes"
enabled: true
# Fuente de la especificación OpenAPI
openapi:
path: "./specs/crm-openapi.yaml"
# O desde URL:
# url: "https://api.crm.com/openapi.json"
# Configuración del backend
backend:
base_url: "https://crm.example.com/api/v1"
timeout: 30
auth:
type: "bearer" # bearer, api_key, basic, oauth2
token: "${CRM_API_TOKEN}"
# Control de acceso
access:
teams: ["sales", "marketing", "admin"]
rate_limit:
requests_per_minute: 100
# Opciones de conversión
conversion:
exclude_paths:
- "/admin/*"
include_methods: ["GET", "POST", "PUT", "DELETE"]
teams:
- name: "sales"
api_key: "sk-team-sales-abc123"
allowed_apis: ["crm"]
description: "Equipo de ventas"
- name: "admin"
api_key: "sk-team-admin-xyz"
allowed_apis: ["*"] # Acceso a todas las APIs
description: "Administradores"
```
### Tipos de Autenticación Soportados
#### 1. Bearer Token
```yaml
backend:
auth:
type: "bearer"
token: "${API_TOKEN}"
```
#### 2. API Key (Header personalizado)
```yaml
backend:
auth:
type: "api_key"
api_key: "${API_KEY}"
header_name: "X-API-Key"
```
#### 3. Basic Auth
```yaml
backend:
auth:
type: "basic"
username: "${API_USERNAME}"
password: "${API_PASSWORD}"
```
#### 4. OAuth2 (Experimental)
```yaml
backend:
auth:
type: "oauth2"
token: "${OAUTH_TOKEN}"
```
### Variables de Entorno
Crea un archivo `.env` basado en `.env.example`:
```bash
# Gateway
GATEWAY_MASTER_KEY=sk-master-tu-clave-segura
# API Backends
CRM_API_TOKEN=tu-token-crm
INVENTORY_API_KEY=tu-key-inventario
WEATHER_API_KEY=tu-key-clima
```
Las variables se reemplazan automáticamente usando la sintaxis `${VAR_NAME}` en el `config.yaml`.
## 📡 Endpoints de la API
### Health Check
```bash
curl http://localhost:4000/health
```
**Respuesta:**
```json
{
"status": "healthy",
"timestamp": "2025-01-15T10:30:00Z",
"apis_loaded": 3,
"gateway": "FastMCP Enterprise Gateway"
}
```
### Listar APIs Disponibles
```bash
curl -H "Authorization: Bearer sk-team-sales-abc123" \
http://localhost:4000/v1/apis
```
**Respuesta:**
```json
{
"team": "sales",
"apis": [
{
"name": "crm",
"display_name": "CRM System API",
"description": "Sistema de gestión de clientes",
"enabled": true,
"base_url": "https://crm.example.com/api/v1"
}
],
"total": 1
}
```
### Listar Todas las Herramientas MCP
```bash
# Todas las herramientas
curl -H "Authorization: Bearer sk-team-admin-xyz" \
http://localhost:4000/v1/tools
# Filtrar por API
curl -H "Authorization: Bearer sk-team-admin-xyz" \
http://localhost:4000/v1/tools?api=crm
```
### Obtener Información de un Servidor MCP
```bash
curl -H "Authorization: Bearer sk-team-sales-abc123" \
http://localhost:4000/v1/mcp/crm
```
### Métricas Prometheus
```bash
curl http://localhost:4000/metrics
```
## 🔄 Agregar Nueva API Sin Reiniciar
Una de las características más potentes es la recarga dinámica:
### Paso 1: Agregar la API al config.yaml
```yaml
apis:
# ... APIs existentes ...
- name: "nueva-api"
display_name: "Nueva API"
enabled: true
openapi:
url: "https://api.nueva.com/openapi.json"
backend:
base_url: "https://api.nueva.com"
auth:
type: "bearer"
token: "${NUEVA_API_TOKEN}"
access:
teams: ["admin"]
```
### Paso 2: Agregar el Token al .env (si es necesario)
```bash
echo "NUEVA_API_TOKEN=tu-token-aqui" >> .env
```
### Paso 3: Recargar Configuración
```bash
curl -X POST \
-H "Authorization: Bearer ${GATEWAY_MASTER_KEY}" \
http://localhost:4000/admin/reload
```
**Respuesta:**
```json
{
"status": "reloaded",
"timestamp": "2025-01-15T10:35:00Z",
"apis_loaded": 4,
"teams_configured": 3
}
```
¡Listo! La nueva API está disponible sin haber reiniciado el servidor.
## 🖥️ Integración con Claude Desktop
Para usar el gateway con Claude Desktop, agrega esto a tu configuración de MCP:
### macOS: `~/Library/Application Support/Claude/claude_desktop_config.json`
### Windows: `%APPDATA%\Claude\claude_desktop_config.json`
```json
{
"mcpServers": {
"crm-api": {
"command": "curl",
"args": [
"-H", "Authorization: Bearer sk-team-sales-abc123",
"http://localhost:4000/v1/mcp/crm"
]
},
"inventory-api": {
"command": "curl",
"args": [
"-H", "Authorization: Bearer sk-team-operations-ghi789",
"http://localhost:4000/v1/mcp/inventory"
]
}
}
}
```
**Nota:** Esto es un ejemplo básico. Para producción, considera implementar un cliente MCP dedicado.
## 📊 Métricas y Observabilidad
El gateway expone métricas Prometheus en el puerto 9090:
### Métricas Disponibles
- `gateway_requests_total` - Total de requests por endpoint, método y status
- `gateway_apis_loaded` - Número de APIs cargadas
- `gateway_teams_configured` - Número de equipos configurados
- `gateway_request_duration_seconds` - Histograma de duración de requests
- `gateway_api_calls_total` - Total de llamadas a APIs backend
### Configurar Prometheus
```yaml
# prometheus.yml
scrape_configs:
- job_name: 'fastmcp-gateway'
static_configs:
- targets: ['localhost:9090']
```
### Logs Estructurados
Los logs se generan en formato JSON para fácil parsing:
```json
{
"timestamp": "2025-01-15T10:30:00Z",
"level": "INFO",
"message": "[gateway:load_apis] - API loaded successfully [api=crm]",
"module": "fastmcp_gateway"
}
```
## 🔧 Troubleshooting
### Problema: El gateway no inicia
**Solución:**
```bash
# Verificar Python
python3 --version # Debe ser 3.9+
# Verificar dependencias
pip install -r requirements.txt
# Ver logs detallados
LOG_LEVEL=DEBUG python gateway.py
```
### Problema: API no carga correctamente
**Solución:**
```bash
# Verificar que el archivo OpenAPI existe
ls -la specs/
# Validar sintaxis del OpenAPI
# Usa herramientas como https://editor.swagger.io/
# Ver logs específicos
grep "load_apis" logs/gateway.log
```
### Problema: Error de autenticación
**Solución:**
```bash
# Verificar que la variable de entorno está definida
echo $CRM_API_TOKEN
# Verificar que el .env está cargado
source .env
# Probar autenticación manualmente
curl -H "Authorization: Bearer ${CRM_API_TOKEN}" \
https://crm.example.com/api/v1/health
```
### Problema: Rate limit errors
**Solución:**
Ajusta los límites en `config.yaml`:
```yaml
access:
rate_limit:
requests_per_minute: 200 # Aumentar límite
```
### Problema: Timeout en requests
**Solución:**
Aumenta el timeout en la configuración del backend:
```yaml
backend:
base_url: "https://api.lenta.com"
timeout: 60 # Aumentar a 60 segundos
```
## 🛠️ Desarrollo
### Estructura del Proyecto
```
fastmcp-gateway/
├── gateway.py # Código principal del gateway
├── config.yaml # Configuración
├── requirements.txt # Dependencias Python
├── start.sh # Script de inicio
├── Dockerfile # Imagen Docker
├── docker-compose.yml # Orquestación
├── .env.example # Template de variables
├── .gitignore # Exclusiones de Git
├── specs/ # Especificaciones OpenAPI
└── logs/ # Archivos de log
```
### Ejecutar Tests (TODO)
```bash
# Instalar dependencias de desarrollo
pip install pytest pytest-cov httpx-mock
# Ejecutar tests
pytest tests/ -v
# Con coverage
pytest tests/ --cov=gateway --cov-report=html
```
### Contribuir
1. Fork el repositorio
2. Crea una rama para tu feature (`git checkout -b feature/amazing-feature`)
3. Commit tus cambios (`git commit -m 'Add amazing feature'`)
4. Push a la rama (`git push origin feature/amazing-feature`)
5. Abre un Pull Request
### Roadmap
- [ ] Implementar caché de respuestas
- [ ] Soporte completo para OAuth2
- [ ] Rate limiting distribuido con Redis
- [ ] Interfaz web para gestión
- [ ] Webhooks para notificaciones
- [ ] Hot reload de OpenAPI specs
- [ ] Tests automatizados
- [ ] Cliente MCP dedicado para Claude Desktop
- [ ] Soporte para GraphQL APIs
## 📚 Recursos
- [FastMCP Documentation](https://github.com/jlowin/fastmcp)
- [Model Context Protocol](https://modelcontextprotocol.io/)
- [OpenAPI Specification](https://swagger.io/specification/)
- [Claude Desktop](https://claude.ai/desktop)
## 🙏 Agradecimientos
- [FastMCP](https://github.com/jlowin/fastmcp) - Framework base para servidores MCP
- [LiteLLM](https://github.com/BerriAI/litellm) - Inspiración para el diseño del gateway
- [FastAPI](https://fastapi.tiangolo.com/) - Framework web utilizado
## 📄 Licencia
MIT License - ver el archivo [LICENSE](LICENSE) para más detalles.
---
**¿Preguntas?** Abre un issue en GitHub o consulta la documentación de FastMCP.
**¿Encontraste un bug?** Por favor reporta en el issue tracker.
**¿Quieres contribuir?** ¡Las pull requests son bienvenidas!
This server cannot be deployed
Maintenance
ActivityInactive
ResponsivenessNo issues