Skip to main content
Glama
zaber-dev

Free-AI Gateway MCP Server

by zaber-dev

⚡ Free-AI Gateway

エンタープライズグレードの機能ベースルーティングAI Gatewayモノレポ。無料階層のAI APIを再利用可能なライブラリ、Model Context Protocol (MCP) サーバー、OpenAI互換のHTTPプロキシに集約します。

ライセンス: MIT TypeScript Node.js Fastify Docker 学習ガイド PR歓迎

📚 Free-AI Gatewayに初めての方は? 詳細な深掘り解説、チュートリアル、統合パターンについては、包括的な アーキテクチャ&開発者ガイド (LEARN.md) をご覧ください。


📖 アーキテクチャとモノレポ概要

free-ai-gateway は、純粋なAIオーケストレーション基盤と、プロトコル固有の配信メカニズム (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

モノレポワークスペースマトリックス

パッケージ / アプリ

場所

目的

依存関係

@free-ai-gateway/core

packages/core

プロトコルに依存しない機能ルーター、レジリエンスエンジン、19のプロバイダアダプター。

ajv, dotenv (HTTPサーバーなし)

@free-ai-gateway/mcp

packages/mcp

AIエージェント (Claude Desktop, Cursor) に機能ツールを公開するModel Context Protocolサーバー。

@free-ai-gateway/core

@free-ai-gateway/skills

packages/skills

Antigravity、Claude、Cursor、Copilot向けのエージェンシックIDEスキル (SKILL.md) とインストーラCLI。

スタンドアロンCLI & API

@free-ai-gateway/cli

packages/cli

ターミナルAIアシスタント、対話型チャットREPL、モデルカタログ、診断ツール。

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

@free-ai-gateway/gateway

apps/gateway

自動検出機能を備えたOpenAI互換エンドポイントを提供する高スループットFastify HTTPプロキシ。

@free-ai-gateway/core, fastify


Related MCP server: agentforge

✨ 主要機能

  • 🎯 機能ベースルーティング: 必要なものをリクエスト (model: "auto:tool_calling+structured_output") し、ルーターが最速の正常な無料プロバイダを選択します。

  • 📐 ストラテジパターンエンジン: プラグイン可能なロードバランシング戦略 (AdaptiveHealthStrategy, LowestLatencyStrategy、またはカスタム IRoutingStrategy)。

  • 🔄 自律フェイルオーバー: アップストリームの 429 (レート制限) や 5xx エラーが発生した場合、ランク付けされた候補プロバイダを透過的に巡回し、成功するまで試行します。

  • 🛡️ サーキットブレーカー: 障害が発生しているプロバイダを検出し、指数的なクールダウンバックオフを実行してカスケード障害を防止します。

  • ⏱️ スライディングウィンドウクォータトラッキング: RPM、TPM、RPDのインメモリ追跡と、予防的な制限保護機能。

  • 🔌 動的プロバイダオートローダー: packages/core/src/providers/ に BaseProvider を拡張するクラスを追加するだけで、新しいプロバイダを追加できます。

  • 📡 型付きイベントバス: OpenTelemetry および Prometheus での可観測性のためのライフサイクルイベント (request:start, request:success, request:fallback, provider:rate_limited)。

  • 🤖 Model Context Protocol (MCP) 対応: Claude Desktop、Cursor、またはエージェントワークフローで直接使用可能。


🧩 サポート対象プロバイダマトリックス (19アダプター)

プロバイダ

モダリティ / 機能

認証

制限範囲

Google AI Studio

text, tool_calling, vision, structured_output, embedding, tts

GOOGLE_API_KEY

モデル別

Groq

text, tool_calling, structured_output, reasoning, speech_to_text

GROQ_API_KEY

アカウント

SambaNova Cloud

text, tool_calling, reasoning, vision

SAMBANOVA_API_KEY

アカウント

NVIDIA NIM

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

NVIDIA_API_KEY

アカウント

Cohere

text, tool_calling, structured_output, reasoning, embedding, rerank

COHERE_API_KEY

アカウント

OpenRouter

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

OPENROUTER_API_KEY

アカウント

OpenCode Zen

code, tool_calling, reasoning, text

OPENCODE_API_KEY

アカウント

Bazaarlink.ai

text, code

BAZAARLINK_API_KEY

アカウント

aimlapi.com

text

AIMLAPI_API_KEY

アカウント

OVHcloud AI

text

OVHCLOUD_API_KEY

モデル別

Voyage AI

embedding

VOYAGE_API_KEY

アカウント

Jina AI

embedding, rerank

JINA_API_KEY

アカウント

Hugging Face

text, tool_calling, image_gen

HUGGINGFACE_API_KEY

共有プール

Cloudflare Workers AI

image_gen, embedding

CLOUDFLARE_API_TOKEN

共有プール

Google Cloud Platform

translation, speech_to_text, text_to_speech, vision

GCP_API_KEY

アカウント

MyMemory

translation

MYMEMORY_API_KEY

アカウント

Unstructured.io

document_processing

UNSTRUCTURED_API_KEY

アカウント

Exa AI

web_search

EXA_API_KEY

アカウント

Tavily

web_search

TAVILY_API_KEY

アカウント


🚀 クイックスタート

1. インストール

# 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. 環境設定

.env.example を .env にコピーし、有効にしたいプロバイダのキーを設定します。

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

3. ビルドと実行

# 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

💻 使用方法

オプションA: HTTPゲートウェイ (OpenAI互換)

任意のOpenAI SDKまたは 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);

オプションB: @free-ai-gateway/core をTypeScriptライブラリとして埋め込む

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);

オプションC: Model Context Protocol (MCP) サーバー

Free-AI Gateway を Claude Desktop または 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..."
      }
    }
  }
}

公開されるMCPツール:

  • freeai_generate: 自動フェイルオーバーによるテキスト、推論、コードの生成。

  • freeai_search: Exa / Tavily を使用したウェブ検索クエリ。

  • freeai_embed: Voyage、Jina、Gemini を使用したベクトル埋め込みの生成。

  • freeai_rerank: 検索拡張生成 (RAG) のための文書の再ランク付け。

  • freeai_analyze_image: マルチモーダルビジョン分析。


オプションD: エージェンシックIDEスキル (@free-ai-gateway/skills)

Free-AI Gateway のエージェントスキルをIDEまたは自律コーディングアシスタントに直接インストールします。

# 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

オプションE: ターミナルCLIツール (@free-ai-gateway/cli)

ターミナルまたはコマンドラインスクリプトから直接 Free-AI を使用します。

# 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

🏛️ モノレポ構造

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


🤝 コミュニティとガバナンス


👤 作者

開発・保守: ❤️を込めて Md. Mahedi Zaman Zaber。


📄 ライセンス

このプロジェクトはオープンソースであり、MITライセンスの下で利用可能です。

Related MCP Connectors

Related MCP Servers

  • A
    license
    Not graded
    quality
    D
    maintenance
    Multi-tool MCP server for AI agents with 29 tools across web scraping, SEO analysis, screenshot and PDF generation, domain intelligence, content extraction, multi-chain EVM blockchain queries, and security toolkit. Free tier available with no auth required.
    39 npm
    1
    MIT
  • F
    license
    A
    quality
    F
    maintenance
    MCP server that exposes 300+ AI agents as tools via a single API key. Supports listing agents, invoking any agent with chat-completion style messages, checking agent health, and retrieving platform statistics.
    5
    4
    -
  • A
    license
    Not graded
    quality
    C
    maintenance
    A unified MCP server providing AI agents with 40+ developer APIs including geolocation, crypto prices, DNS lookup, and web scraping. Enables natural language access to various tools through a single gateway.
    1
    MIT
  • A
    license
    Not graded
    quality
    D
    maintenance
    Enables AI agents to access a unified catalog of tools from various APIs (OpenAPI, GraphQL, MCP, Google Discovery) through the MCP protocol.
    173 npm
    MIT