Skip to main content
Glama
zaber-dev

Free-AI Gateway MCP Server

by zaber-dev

⚡ Free-AI Gateway

Monorepositorio de puerta de enlace de IA con enrutamiento por capacidades de nivel empresarial que agrega APIs de IA gratuitas en bibliotecas reutilizables, servidores de Protocolo de Contexto de Modelo (MCP) y proxies HTTP compatibles con OpenAI.

Licencia: MIT TypeScript Node.js Fastify Docker Guía de aprendizaje PRs bienvenidos

📚 ¿Nuevo en Free-AI Gateway? Consulta la completa Guía de Arquitectura y Desarrollo (LEARN.md) para inmersiones detalladas, tutoriales y patrones de integración.


📖 Descripción general de la Arquitectura y el Monorepositorio

free-ai-gateway está organizado como un monorepositorio empresarial que separa la infraestructura de orquestación de IA pura de los mecanismos de entrega específicos del protocolo (Proxy HTTP Fastify y Servidor MCP):

flowchart TD
    subgraph CoreLayer ["@free-ai-gateway/core (Standalone npm package)"]
        Router["CapabilityRouter & Strategy Engine"]
        Providers["19 Provider Adapters & Dynamic Registry"]
        Resilience["QuotaTracker & CircuitBreaker"]
        Observability["EventBus & MetricsTracker"]
        Transport["HttpClient with Exponential Backoff"]
    end

    subgraph Consumers ["Consumer Applications"]
        GatewayApp["apps/gateway (@free-ai-gateway/gateway)<br/>Fastify HTTP OpenAI Proxy"]
        McpApp["packages/mcp (@free-ai-gateway/mcp)<br/>Model Context Protocol Server"]
        SkillsPkg["packages/skills (@free-ai-gateway/skills)<br/>Agentic IDE Skills & CLI"]
        CliApp["packages/cli (@free-ai-gateway/cli)<br/>Terminal Assistant & Diagnostics"]
        ClientApp["Custom Node.js / TypeScript App<br/>Direct Library Import"]
    end

    GatewayApp -->|consumes| CoreLayer
    McpApp -->|consumes| CoreLayer
    SkillsPkg -->|integrates with| CoreLayer
    CliApp -->|consumes| CoreLayer
    ClientApp -->|consumes| CoreLayer

Matriz de Espacios de Trabajo del Monorepositorio

Paquete / Aplicación

Ubicación

Propósito

Dependencias

@free-ai-gateway/core

packages/core

Enrutador de capacidades neutro en cuanto al protocolo, motor de resiliencia y 19 adaptadores de proveedores.

ajv, dotenv (Sin servidor HTTP)

@free-ai-gateway/mcp

packages/mcp

Servidor de Protocolo de Contexto de Modelo que expone herramientas de capacidad a agentes de IA (Claude Desktop, Cursor).

@free-ai-gateway/core

@free-ai-gateway/skills

packages/skills

Habilidades IDE para agentes (SKILL.md) y CLI de instalación para Antigravity, Claude, Cursor y Copilot.

CLI y API independientes

@free-ai-gateway/cli

packages/cli

Asistente de IA en terminal, chat interactivo REPL, catálogo de modelos y herramienta de diagnóstico.

@free-ai-gateway/core, @free-ai-gateway/skills

@free-ai-gateway/gateway

apps/gateway

Proxy HTTP Fastify de alto rendimiento que sirve endpoints compatibles con OpenAI con autodescubrimiento.

@free-ai-gateway/core, fastify


✨ Capacidades Clave

  • 🎯 Enrutamiento Basado en Capacidades: Solicita lo que necesitas (model: "auto:tool_calling+structured_output"), y deja que el enrutador elija el proveedor gratuito saludable más rápido.

  • 📐 Motor de Patrón de Estrategia: Estrategias de balanceo de carga conectables (AdaptiveHealthStrategy, LowestLatencyStrategy, o IRoutingStrategy personalizada).

  • 🔄 Failover Autónomo: Recorre de forma transparente los proveedores candidatos clasificados hasta tener éxito al encontrar errores 429 (Límite de tasa) o 5xx ascendentes.

  • 🛡️ Interruptor de Circuito: Detecta proveedores que fallan y entra en un retroceso de enfriamiento exponencial para evitar fallos en cascada.

  • ⏱️ Seguimiento de Cuotas con Ventana Deslizante: Contabilidad en memoria de RPM, TPM y RPD con protección proactiva de límites.

  • 🔌 Cargador Automático de Proveedores Dinámico: Añade nuevos proveedores colocando una clase que extienda BaseProvider en packages/core/src/providers/.

  • 📡 Bus de Eventos Tipados: Eventos del ciclo de vida (request:start, request:success, request:fallback, provider:rate_limited) para observabilidad con OpenTelemetry y Prometheus.

  • 🤖 Listo para Protocolo de Contexto de Modelo (MCP): Úsalo directamente en Claude Desktop, Cursor o flujos de trabajo de agentes.


🧩 Matriz de Proveedores Soportados (19 Adaptadores)

Proveedor

Modalidades / Capacidades

Autenticación

Ámbito de Límite

Google AI Studio

text, tool_calling, vision, structured_output, embedding, tts

GOOGLE_API_KEY

Por Modelo

Groq

text, tool_calling, structured_output, reasoning, speech_to_text

GROQ_API_KEY

Cuenta

SambaNova Cloud

text, tool_calling, reasoning, vision

SAMBANOVA_API_KEY

Cuenta

NVIDIA NIM

text, tool_calling, reasoning, vision, embedding, rerank, moderation

NVIDIA_API_KEY

Cuenta

Cohere

text, tool_calling, structured_output, reasoning, embedding, rerank

COHERE_API_KEY

Cuenta

OpenRouter

text, tool_calling, vision, reasoning, embedding, tts, moderation

OPENROUTER_API_KEY

Cuenta

OpenCode Zen

code, tool_calling, reasoning, text

OPENCODE_API_KEY

Cuenta

Bazaarlink.ai

text, code

BAZAARLINK_API_KEY

Cuenta

aimlapi.com

text

AIMLAPI_API_KEY

Cuenta

OVHcloud AI

text

OVHCLOUD_API_KEY

Por Modelo

Voyage AI

embedding

VOYAGE_API_KEY

Cuenta

Jina AI

embedding, rerank

JINA_API_KEY

Cuenta

Hugging Face

text, tool_calling, image_gen

HUGGINGFACE_API_KEY

Pool Compartido

Cloudflare Workers AI

image_gen, embedding

CLOUDFLARE_API_TOKEN

Pool Compartido

Google Cloud Platform

translation, speech_to_text, text_to_speech, vision

GCP_API_KEY

Cuenta

MyMemory

translation

MYMEMORY_API_KEY

Cuenta

Unstructured.io

document_processing

UNSTRUCTURED_API_KEY

Cuenta

Exa AI

web_search

EXA_API_KEY

Cuenta

Tavily

web_search

TAVILY_API_KEY

Cuenta


🚀 Inicio Rápido

1. Instalación

# Clone the repository
git clone https://github.com/zaber-dev/free-ai-gateway.git
cd free-ai-gateway

# Install dependencies across all monorepo workspaces
npm install

2. Configurar el Entorno

Copia .env.example a .env y proporciona las claves para los proveedores que desees habilitar:

cp .env.example .env
PORT=3000
GROQ_API_KEY=gsk_...
GOOGLE_API_KEY=AIza...
NVIDIA_API_KEY=nvapi-...
COHERE_API_KEY=...

3. Compilar y Ejecutar

# Compile all workspace packages
npm run build

# Run all 31 automated tests across all packages
npm test

# Start the Fastify HTTP Gateway (Dev mode)
npm run dev

# Start the Gateway in Production
npm start

💻 Modalidades de Uso

Opción A: Gateway HTTP (Compatible con OpenAI)

Llama al proxy local con cualquier SDK de OpenAI o curl:

curl http://localhost:3000/v1/chat/completions \
  -H "Content-Type: application/json" \
  -d '{
    "model": "auto:tool_calling+structured_output",
    "messages": [
      { "role": "user", "content": "Extract name and age from: Alice is 30 years old." }
    ]
  }'
import OpenAI from "openai";

const client = new OpenAI({
  baseURL: "http://localhost:3000/v1",
  apiKey: "not-needed",
});

const completion = await client.chat.completions.create({
  model: "auto:reasoning",
  messages: [{ role: "user", content: "Solve: How many r's in strawberry?" }],
});

console.log(completion.choices[0].message.content);

Opción B: Integrar @free-ai-gateway/core como Biblioteca TypeScript

Integra el enrutador de capacidades directamente en tu aplicación sin iniciar un servidor HTTP:

import {
  CapabilityRouter,
  Registry,
  QuotaTracker,
  CircuitBreaker,
  EventBus,
  LowestLatencyStrategy,
} from "@free-ai-gateway/core";

const registry = new Registry();
const quota = new QuotaTracker();
const breaker = new CircuitBreaker();
const eventBus = new EventBus();

// Listen to lifecycle telemetry
eventBus.on("request:fallback", (evt) => {
  console.warn(`[Fallback] Failed on ${evt.attemptedProvider}: ${evt.error}`);
});

const router = new CapabilityRouter(
  registry,
  quota,
  breaker,
  undefined,
  eventBus,
  new LowestLatencyStrategy()
);

const response = await router.route({
  capabilities: ["text", "tool_calling"],
  payload: {
    messages: [{ role: "user", content: "Hello AI!" }],
  },
});

console.log("Served by:", response.servedBy);
console.log("Data:", response.data);

Opción C: Servidor de Protocolo de Contexto de Modelo (MCP)

Conecta Free-AI Gateway a Claude Desktop o Cursor:

{
  "mcpServers": {
    "free-ai-gateway": {
      "command": "node",
      "args": ["/path/to/free-ai-gateway/packages/mcp/dist/index.js"],
      "env": {
        "GROQ_API_KEY": "gsk_...",
        "GOOGLE_API_KEY": "AIza..."
      }
    }
  }
}

Herramientas MCP Expuestas:

  • freeai_generate: Genera texto, razonamiento o código con failover automático.

  • freeai_search: Consultas de búsqueda web a través de Exa / Tavily.

  • freeai_embed: Genera embeddings vectoriales a través de Voyage, Jina, Gemini.

  • freeai_rerank: Reordena documentos para generación aumentada por recuperación (RAG).

  • freeai_analyze_image: Análisis de visión multimodal.


Opción D: Habilidades IDE para Agentes (@free-ai-gateway/skills)

Instala las habilidades de agente de Free-AI Gateway directamente en tu IDE o asistente de codificación autónomo:

# Install to Google Antigravity (.agents/skills)
npx @free-ai-gateway/skills install --target=antigravity

# Install to Cursor (.cursor/skills)
npx @free-ai-gateway/skills install --target=cursor

# Install to Claude Code (.claude/skills)
npx @free-ai-gateway/skills install --target=claude

# Install to all supported AI assistants
npx @free-ai-gateway/skills install --target=all

Opción E: Herramienta CLI de Terminal (@free-ai-gateway/cli)

Usa Free-AI directamente desde tu terminal o scripts de línea de comandos:

# One-off prompt execution with auto-routing
npx @free-ai-gateway/cli "Explain MapReduce in simple terms"

# Interactive chat REPL in terminal
npx @free-ai-gateway/cli chat --capability=reasoning

# Check model catalog across all 19 providers
npx @free-ai-gateway/cli models

# Run system diagnostics
npx @free-ai-gateway/cli doctor

🏛️ Estructura del Monorepositorio

free-ai-gateway/
├── packages/
│   ├── core/                        # @free-ai-gateway/core
│   │   ├── AGENTS.md                # Agentic guidelines for @free-ai-gateway/core
│   │   ├── src/
│   │   │   ├── capabilities/        # Capability definitions & parsing
│   │   │   ├── config/              # providers.json, schema, config sources
│   │   │   ├── errors/              # ProviderError, NoProviderAvailableError
│   │   │   ├── observability/       # EventBus, MetricsTracker
│   │   │   ├── providers/           # 19 Provider Adapters + Registry + Loader
│   │   │   ├── resilience/          # QuotaTracker, CircuitBreaker
│   │   │   ├── router/              # CapabilityRouter & Strategy Pattern
│   │   │   ├── transport/           # HttpClient with exponential backoff
│   │   │   ├── types/               # Unified contracts & response schemas
│   │   │   └── index.ts             # Public Core API
│   │   ├── tests/                   # 20 Core unit tests
│   │   └── package.json
│   │
│   ├── mcp/                         # @free-ai-gateway/mcp
│   │   ├── AGENTS.md                # Agentic guidelines for @free-ai-gateway/mcp
│   │   ├── src/
│   │   │   ├── tools/               # generate, search, embed, rerank, analyze-image
│   │   │   ├── resources/           # capabilities, models catalog
│   │   │   ├── server.ts            # FreeAiMcpServer handler
│   │   │   └── index.ts
│   │   ├── tests/                   # 3 MCP server tests
│   │   └── package.json
│   │
│   ├── skills/                      # @free-ai-gateway/skills
│   │   ├── AGENTS.md                # Agentic guidelines for @free-ai-gateway/skills
│   │   ├── src/
│   │   │   ├── skills/              # Built-in skills (free-ai-gateway, scaffolding, mcp)
│   │   │   ├── installer.ts         # Multi-target installer
│   │   │   ├── cli.ts               # CLI executable (free-ai-skills)
│   │   │   └── index.ts
│   │   ├── tests/                   # 4 Skills tests
│   │   └── package.json
│   │
│   └── cli/                         # @free-ai-gateway/cli
│       ├── AGENTS.md                # Agentic guidelines for @free-ai-gateway/cli
│       ├── src/
│       │   ├── commands/            # prompt, chat, models, doctor, skills
│       │   ├── cli.ts               # Argument parsing & dispatcher
│       │   ├── bin.ts               # CLI executable (free-ai, freeai)
│       │   └── index.ts
│       ├── tests/                   # 4 CLI tests
│       └── package.json
│
├── apps/
│   └── gateway/                     # @free-ai-gateway/gateway (HTTP App)
│       ├── AGENTS.md                # Agentic guidelines for @free-ai-gateway/gateway
│       ├── src/
│       │   ├── adapters/            # OpenAI chat response normalizer
│       │   ├── api/
│       │   │   ├── routes/          # Fastify route modules & RouteLoader
│       │   │   └── server.ts        # Server factory, timing hooks, 404 handler
│       │   ├── jobs/                # Background JobScheduler & reverify worker
│       │   └── index.ts
│       ├── tests/                   # 5 Gateway HTTP tests
│       ├── Dockerfile               # Monorepo container builder
│       └── package.json
│
├── tests/
│   └── e2e/                         # 5 Cross-package E2E integration tests
│
├── AGENTS.md                        # Monorepo Root Agentic Guidelines
├── CLAUDE.md                        # Claude Code Instructions
├── .agents/                         # Workspace Skills Directory
├── .github/workflows/ci.yml         # Matrix CI workflow
├── docker-compose.yml
├── package.json                     # Root workspace definition
├── tsconfig.base.json               # Shared TypeScript compiler settings
└── README.md


🤝 Comunidad y Gobernanza


👤 Autor

Creado y mantenido con ❤️ por Md. Mahedi Zaman Zaber.


📄 Licencia

Este proyecto es de código abierto y está disponible bajo la Licencia MIT.

-
license - not tested
-
quality - not tested
B
maintenance

Maintenance

Maintainers
Response time
Release cycle
Releases (12mo)
Commit activity

Resources

Unclaimed servers have limited discoverability.

Looking for Admin?

If you are the server author, to access and configure the admin panel.

Related MCP Connectors

  • Free public MCP for AI agents — 193 tools, 44 workflows. No API key.

  • OCR, transcription, file extraction, and image generation for AI agents via MCP.

  • Hosted MCP with 91 agent tools: X, domains, SEO, Maps, Trends, Search, YouTube, TikTok, and more.

View all MCP Connectors

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/zaber-dev/free-ai-gateway'

If you have feedback or need assistance with the MCP directory API, please join our Discord server