Free-AI Gateway MCP Server
Exposes free-tier AI APIs as MCP tools for AI agents, enabling text generation, web search, embeddings, and vision analysis with automatic failover and capability routing.
README
<div align="center">
<img src="art/free-ai-gateaway.png" alt="Free-AI Gateway Architecture" width="100%" />
β‘ Free-AI Gateway
Enterprise-grade capability-routed AI Gateway monorepo aggregating free-tier AI APIs into reusable libraries, Model Context Protocol (MCP) servers, and OpenAI-compatible HTTP proxies.
</div>
π New to Free-AI Gateway? Check out the comprehensive Architecture & Developer Guide (LEARN.md) for detailed deep dives, tutorials, and integration patterns.
π Architecture & Monorepo Overview
free-ai-gateway is organized as an enterprise monorepo separating pure AI orchestration infrastructure from protocol-specific delivery mechanisms (HTTP Fastify Proxy & MCP Server):
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
Monorepo Workspaces Matrix
| Package / App | Location | Purpose | Dependencies |
|---|---|---|---|
@free-ai-gateway/core |
packages/core |
Protocol-neutral capability router, resilience engine, and 19 provider adapters. | ajv, dotenv (Zero HTTP server) |
@free-ai-gateway/mcp |
packages/mcp |
Model Context Protocol server exposing capability tools to AI agents (Claude Desktop, Cursor). | @free-ai-gateway/core |
@free-ai-gateway/skills |
packages/skills |
Agentic IDE skills (SKILL.md) and installer CLI for Antigravity, Claude, Cursor, and Copilot. |
Standalone CLI & API |
@free-ai-gateway/cli |
packages/cli |
Terminal AI assistant, interactive chat REPL, model catalog, and diagnostics tool. | @free-ai-gateway/core, @free-ai-gateway/skills |
@free-ai-gateway/gateway |
apps/gateway |
High-throughput Fastify HTTP proxy serving OpenAI-compatible endpoints with auto-discovery. | @free-ai-gateway/core, fastify |
β¨ Key Capabilities
- π― Capability-Based Routing: Request what you need (
model: "auto:tool_calling+structured_output"), and let the router choose the fastest healthy free provider. - π Strategy Pattern Engine: Pluggable load balancing strategies (
AdaptiveHealthStrategy,LowestLatencyStrategy, or customIRoutingStrategy). - π Autonomous Failover: Transparently cycles through ranked candidate providers until success upon encountering upstream
429(Rate Limit) or5xxerrors. - π‘οΈ Circuit Breaker: Detects failing providers and enters exponential cooldown backoff to prevent cascade failures.
- β±οΈ Sliding-Window Quota Tracking: In-memory accounting of RPM, TPM, and RPD with proactive limit protection.
- π Dynamic Provider Autoloader: Add new providers by dropping a class extending
BaseProviderintopackages/core/src/providers/. - π‘ Typed Event Bus: Lifecycle events (
request:start,request:success,request:fallback,provider:rate_limited) for OpenTelemetry and Prometheus observability. - π€ Model Context Protocol (MCP) Ready: Use directly in Claude Desktop, Cursor, or agent workflows.
π§© Supported Providers Matrix (19 Adapters)
| Provider | Modalities / Capabilities | Authentication | Limit Scope |
|---|---|---|---|
| Google AI Studio | text, tool_calling, vision, structured_output, embedding, tts |
GOOGLE_API_KEY |
Per Model |
| Groq | text, tool_calling, structured_output, reasoning, speech_to_text |
GROQ_API_KEY |
Account |
| SambaNova Cloud | text, tool_calling, reasoning, vision |
SAMBANOVA_API_KEY |
Account |
| NVIDIA NIM | text, tool_calling, reasoning, vision, embedding, rerank, moderation |
NVIDIA_API_KEY |
Account |
| Cohere | text, tool_calling, structured_output, reasoning, embedding, rerank |
COHERE_API_KEY |
Account |
| OpenRouter | text, tool_calling, vision, reasoning, embedding, tts, moderation |
OPENROUTER_API_KEY |
Account |
| OpenCode Zen | code, tool_calling, reasoning, text |
OPENCODE_API_KEY |
Account |
| Bazaarlink.ai | text, code |
BAZAARLINK_API_KEY |
Account |
| aimlapi.com | text |
AIMLAPI_API_KEY |
Account |
| OVHcloud AI | text |
OVHCLOUD_API_KEY |
Per Model |
| Voyage AI | embedding |
VOYAGE_API_KEY |
Account |
| Jina AI | embedding, rerank |
JINA_API_KEY |
Account |
| Hugging Face | text, tool_calling, image_gen |
HUGGINGFACE_API_KEY |
Shared Pool |
| Cloudflare Workers AI | image_gen, embedding |
CLOUDFLARE_API_TOKEN |
Shared Pool |
| Google Cloud Platform | translation, speech_to_text, text_to_speech, vision |
GCP_API_KEY |
Account |
| MyMemory | translation |
MYMEMORY_API_KEY |
Account |
| Unstructured.io | document_processing |
UNSTRUCTURED_API_KEY |
Account |
| Exa AI | web_search |
EXA_API_KEY |
Account |
| Tavily | web_search |
TAVILY_API_KEY |
Account |
π Quick Start
1. Installation
# 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. Configure Environment
Copy .env.example to .env and provide keys for the providers you wish to enable:
cp .env.example .env
PORT=3000
GROQ_API_KEY=gsk_...
GOOGLE_API_KEY=AIza...
NVIDIA_API_KEY=nvapi-...
COHERE_API_KEY=...
3. Build & Run
# 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
π» Usage Modalities
Option A: HTTP Gateway (OpenAI Compatible)
Call the local proxy with any OpenAI SDK or 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);
Option B: Embedding @free-ai-gateway/core as a TypeScript Library
Embed the capability router directly into your application without launching an HTTP server:
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);
Option C: Model Context Protocol (MCP) Server
Connect Free-AI Gateway to Claude Desktop or 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..."
}
}
}
}
Exposed MCP Tools:
freeai_generate: Generate text, reasoning, or code with automatic failover.freeai_search: Web search queries via Exa / Tavily.freeai_embed: Generate vector embeddings via Voyage, Jina, Gemini.freeai_rerank: Rerank documents for retrieval augmented generation (RAG).freeai_analyze_image: Multimodal vision analysis.
Option D: Agentic IDE Skills (@free-ai-gateway/skills)
Install Free-AI Gateway agent skills directly into your IDE or autonomous coding assistant:
# 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
Option E: Terminal CLI Tool (@free-ai-gateway/cli)
Use Free-AI directly from your terminal or command-line scripts:
# 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
ποΈ Monorepo Structure
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
π€ Community & Governance
- π Architecture Blueprint: Deep dive into the internal system design and data flow.
- π Developer & Learning Guide: Tutorials, programmatic usage, and SDK patterns.
- πΊοΈ Product Roadmap: Planned milestones, distributed state, and upcoming features.
- π¬ Support Guide: Troubleshooting, community discussions, and help channels.
- ποΈ Project Governance: Decision-making process, maintainer roles, and release policies.
- βοΈ Contributing Guide: Step-by-step instructions for adding new provider adapters.
- π Security Policy: Vulnerability disclosure guidelines.
- π Code of Conduct: Community standards and expectations.
π€ Author
Created and maintained with β€οΈ by Md. Mahedi Zaman Zaber.
π License
This project is open source and available under the MIT License.
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.
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.
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.
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.