Skip to main content
Glama
zaber-dev

Free-AI Gateway MCP Server

by zaber-dev

⚡ Free-AI Gateway

企业级能力路由 AI 网关单体仓库,将免费层 AI API 聚合为可复用库、模型上下文协议(MCP)服务器和兼容 OpenAI 的 HTTP 代理。

许可证: MIT TypeScript Node.js Fastify Docker 学习指南 欢迎 PR

📚 初次接触 Free-AI Gateway? 请查阅全面的 架构与开发者指南 (LEARN.md),获取详细的深入解析、教程和集成模式。


📖 架构与单体仓库概览

free-ai-gateway 以企业级单体仓库形式组织,将纯 AI 编排基础设施与协议特定的交付机制(HTTP Fastify 代理和 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

单体仓库工作区矩阵

包 / 应用

位置

用途

依赖项

@free-ai-gateway/core

packages/core

协议无关的能力路由器、弹性引擎和 19 个提供商适配器。

ajv, dotenv(零 HTTP 服务器)

@free-ai-gateway/mcp

packages/mcp

模型上下文协议服务器,向 AI 代理(Claude Desktop、Cursor)暴露能力工具。

@free-ai-gateway/core

@free-ai-gateway/skills

packages/skills

代理 IDE 技能(SKILL.md)和安装 CLI,适用于 Antigravity、Claude、Cursor 和 Copilot。

独立 CLI 和 API

@free-ai-gateway/cli

packages/cli

终端 AI 助手、交互式聊天 REPL、模型目录和诊断工具。

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

@free-ai-gateway/gateway

apps/gateway

高吞吐量 Fastify HTTP 代理,提供兼容 OpenAI 的端点并支持自动发现。

@free-ai-gateway/core, fastify


Related MCP server: agentforge

✨ 关键能力

  • 🎯 基于能力的路由:请求所需内容(model: "auto:tool_calling+structured_output"),让路由器选择最快的健康免费提供商。

  • 📐 策略模式引擎:可插拔的负载均衡策略(AdaptiveHealthStrategy、LowestLatencyStrategy 或自定义 IRoutingStrategy)。

  • 🔄 自动故障转移:遇到上游 429(速率限制)或 5xx 错误时,透明地循环遍历排名候选提供商直至成功。

  • 🛡️ 断路器:检测故障提供商并进入指数冷却退避,防止级联故障。

  • ⏱️ 滑动窗口配额跟踪:内存中的 RPM、TPM 和 RPD 核算,并主动限制保护。

  • 🔌 动态提供商自动加载器:通过将扩展 BaseProvider 的类放入 packages/core/src/providers/ 来添加新提供商。

  • 📡 类型化事件总线:生命周期事件(request:start、request:success、request:fallback、provider:rate_limited),用于 OpenTelemetry 和 Prometheus 可观测性。

  • 🤖 模型上下文协议(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:模型上下文协议(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