FastMCP Gateway
Automatically converts OpenAPI specifications into MCP servers, allowing tools like Claude Desktop to interact with your REST APIs through a standard protocol.
README
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). 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)
# 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
# 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
# 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:
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
backend:
auth:
type: "bearer"
token: "${API_TOKEN}"
2. API Key (Header personalizado)
backend:
auth:
type: "api_key"
api_key: "${API_KEY}"
header_name: "X-API-Key"
3. Basic Auth
backend:
auth:
type: "basic"
username: "${API_USERNAME}"
password: "${API_PASSWORD}"
4. OAuth2 (Experimental)
backend:
auth:
type: "oauth2"
token: "${OAUTH_TOKEN}"
Variables de Entorno
Crea un archivo .env basado en .env.example:
# 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
curl http://localhost:4000/health
Respuesta:
{
"status": "healthy",
"timestamp": "2025-01-15T10:30:00Z",
"apis_loaded": 3,
"gateway": "FastMCP Enterprise Gateway"
}
Listar APIs Disponibles
curl -H "Authorization: Bearer sk-team-sales-abc123" \
http://localhost:4000/v1/apis
Respuesta:
{
"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
# 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
curl -H "Authorization: Bearer sk-team-sales-abc123" \
http://localhost:4000/v1/mcp/crm
Métricas Prometheus
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
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)
echo "NUEVA_API_TOKEN=tu-token-aqui" >> .env
Paso 3: Recargar Configuración
curl -X POST \
-H "Authorization: Bearer ${GATEWAY_MASTER_KEY}" \
http://localhost:4000/admin/reload
Respuesta:
{
"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
{
"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 statusgateway_apis_loaded- Número de APIs cargadasgateway_teams_configured- Número de equipos configuradosgateway_request_duration_seconds- Histograma de duración de requestsgateway_api_calls_total- Total de llamadas a APIs backend
Configurar Prometheus
# 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:
{
"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:
# 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:
# 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:
# 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:
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:
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)
# 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
- Fork el repositorio
- Crea una rama para tu feature (
git checkout -b feature/amazing-feature) - Commit tus cambios (
git commit -m 'Add amazing feature') - Push a la rama (
git push origin feature/amazing-feature) - 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
🙏 Agradecimientos
- FastMCP - Framework base para servidores MCP
- LiteLLM - Inspiración para el diseño del gateway
- FastAPI - Framework web utilizado
📄 Licencia
MIT License - ver el archivo 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!
Recommended Servers
playwright-mcp
A Model Context Protocol server that enables LLMs to interact with web pages through structured accessibility snapshots without requiring vision models or screenshots.
Magic Component Platform (MCP)
An AI-powered tool that generates modern UI components from natural language descriptions, integrating with popular IDEs to streamline UI development workflow.
Audiense Insights MCP Server
Enables interaction with Audiense Insights accounts via the Model Context Protocol, facilitating the extraction and analysis of marketing insights and audience data including demographics, behavior, and influencer engagement.
VeyraX MCP
Single MCP tool to connect all your favorite tools: Gmail, Calendar and 40 more.
graphlit-mcp-server
The Model Context Protocol (MCP) Server enables integration between MCP clients and the Graphlit service. Ingest anything from Slack to Gmail to podcast feeds, in addition to web crawling, into a Graphlit project - and then retrieve relevant contents from the MCP client.
Kagi MCP Server
An MCP server that integrates Kagi search capabilities with Claude AI, enabling Claude to perform real-time web searches when answering questions that require up-to-date information.
E2B
Using MCP to run code via e2b.
Neon Database
MCP server for interacting with Neon Management API and databases
Exa Search
A Model Context Protocol (MCP) server lets AI assistants like Claude use the Exa AI Search API for web searches. This setup allows AI models to get real-time web information in a safe and controlled way.
Qdrant Server
This repository is an example of how to create a MCP server for Qdrant, a vector search engine.