7.4 billion tokens per month. 34 free LLM providers. 635 free model endpoints. All behind one /v1 endpoint, plus any custom OpenAI-compatible endpoint. Smart routing, automatic failover, encrypted keys. Personal experimentation only.
TypeScript
feat(mcp): ask_freellmapi inference tool for ChatGPT/MCP clients (#1302)
tripstar600070855db543fc
diff --git a/.env.example b/.env.exampleindex c261de03..eae8e6f1 100644--- a/.env.example+++ b/.env.example@@ -46,6 +46,12 @@ PORT=3001# with 413 'request_too_large'.# REQUEST_BODY_LIMIT_MB=25+# ChatGPT / MCP inference. ask_freellmapi uses "auto" unless this is set to+# a model id or named chain (for example auto:coding). The timeout applies only+# to the MCP inference tool; normal /v1 client requests keep their own limits.+# MCP_INFERENCE_DEFAULT_MODEL=auto+# MCP_INFERENCE_TIMEOUT_MS=120000+# Inbound image normalization: data-URL images over the threshold are# downscaled to the long-edge cap and re-encoded (JPEG, or PNG only when the# alpha channel carries real transparency) before routing, shrinking replayeddiff --git a/.gitignore b/.gitignoreindex ec7c9bb9..e9cf8f13 100644--- a/.gitignore+++ b/.gitignore@@ -13,6 +13,7 @@ server/data/.encryption-key.env.env.local+/tunnel-client.yaml.DS_Store# TypeScript incremental build cachediff --git a/README.md b/README.mdindex 3cd94462..c914dc23 100644--- a/README.md+++ b/README.md@@ -168,7 +168,7 @@ Based on public documentation, July 2026 — corrections welcome.- **Prompt compression (opt-in)** — a shared, fail-open request pipeline can deduplicate prompts, filter tool output, compact repeated JSON, and trim stale context before cache lookup and routing. [Details →](docs/en/compression/01-compression-pipeline.md)- **Encrypted keys, one token out** — provider keys are AES-256-GCM encrypted in SQLite and decrypted in-memory per request; your apps only ever see a single unified `freellmapi-…` bearer token.- **Admin dashboard & analytics** — React UI to manage keys, reorder the chain, run a playground, and read p50/p95/TTFT analytics over 24h–90d windows; login-gated, dark/light themes, [60 languages](#languages).-- **MCP server & interactive docs** — agents can introspect usable models, provider health, and routing strategy over `/mcp`; a dependency-free OpenAPI viewer lives at `/v1/docs`. [Coding agents →](docs/en/clients/01-agent-clients.md)+- **ChatGPT-ready MCP server & interactive docs** — ChatGPT and other MCP clients can call FreeLLMAPI inference, list usable models, inspect provider health/usage/cache/routing metadata, and manage the routing strategy over `/mcp`; a dependency-free OpenAPI viewer lives at `/v1/docs`. [ChatGPT and coding agents →](docs/en/clients/01-agent-clients.md#mcp-server)- **Ops niceties** — opt-in response cache, encrypted DB backups, periodic key health checks, bulk key import/export, declarative startup config. [Install & deploy →](docs/en/install/01-install.md)- **Runs anywhere Node 20+ runs** — Windows, macOS, Linux servers, or a small ARM SBC (Raspberry Pi included). ~40 MB RSS at idle behind PM2 / systemd / whatever supervisor you prefer.@@ -204,6 +204,13 @@ For macOS 12 Monterey or later, choose **arm64 (Apple Silicon)** or **x64 (IntelAnything that can target an OpenAI-compatible base URL works: set it to `http://localhost:3001/v1` with the unified key from the dashboard. **Claude Code**, **Codex CLI**, **Cline / Roo Code**, **Continue** (including inline autocomplete), **Aider**, **opencode**, and **Cursor** each have a short recipe in **[docs/en/clients/01-agent-clients.md](docs/en/clients/01-agent-clients.md)** — and the router doubles as an MCP server your agents can introspect mid-session.+**ChatGPT** connects to the same local router through a private Secure MCP Tunnel. The+`ask_freellmapi` MCP tool routes a ChatGPT-requested task through `/v1/chat/completions` and+returns the answer with served-model, fallback, cache, execution, and token metadata. Base+URL and bearer authentication live in the tunnel-client configuration; the default model is+set with `MCP_INFERENCE_DEFAULT_MODEL` (`auto` when unset). No key belongs in Git or in the+MCP URL. **[ChatGPT setup →](docs/en/clients/01-agent-clients.md#chatgpt-private-secure-mcp-tunnel)**+The fastest setup is generated from the models available on your live server:```bashdiff --git a/docs/en/architecture/06-observability.md b/docs/en/architecture/06-observability.mdindex e67ccfb5..1c8c8680 100644--- a/docs/en/architecture/06-observability.md+++ b/docs/en/architecture/06-observability.md@@ -87,9 +87,13 @@ the cache. Streamed frames omit it (the header carries it there).`requests.caller` records the surface: today every inference path writes `http`(the OpenAI-compatible proxy, `/v1/responses`, `/v1/messages`, the Ollama and-Gemini wires, and fusion sub-calls). `/mcp` is introspection-only and runs no-inference, and the dashboard playground calls the same HTTP endpoints as any-other client. The column is free-form, so a new surface needs no migration.+Gemini wires, fusion sub-calls, and `ask_freellmapi`). The MCP inference tool+deliberately loops through the same local `/v1/chat/completions` route, so it+inherits identical routing, fallback, cache, token accounting, and error+handling instead of maintaining a second inference implementation. The other+`/mcp` tools are local introspection/control calls. The dashboard playground+also calls the same HTTP endpoints as any other client. The column is free-form,+so a new surface needs no migration.### Attempt Trail (`request_attempts` table)@@ -305,4 +309,4 @@ CREATE TABLE request_attempts (-- Materialized aggregates (refreshed periodically)CREATE VIEW request_aggregates AS ...;-```\ No newline at end of file+```diff --git a/docs/en/clients/01-agent-clients.md b/docs/en/clients/01-agent-clients.mdindex c0b0afe3..90c5881b 100644--- a/docs/en/clients/01-agent-clients.md+++ b/docs/en/clients/01-agent-clients.md@@ -287,9 +287,10 @@ telemetry.## MCP server-On top of inference, the router is an **MCP server**: agents can introspect it mid-session-(usable models and the params each one honors, provider health, usage and cache stats,-routing strategy).+On top of the OpenAI-compatible API, the router is an **MCP server**: agents can ask a+FreeLLMAPI model to perform a text task and introspect the gateway mid-session (usable+models and the params each one honors, provider health, usage and cache stats, routing+strategy).The MCP surface is a setting rather than an always-on endpoint (#925). **Fresh installsstart with it off**; installs that already had provider keys configured when they upgraded@@ -314,6 +315,59 @@ claude mcp add --transport http freellmapi http://localhost:3001/mcp \Any MCP client that speaks Streamable HTTP works the same way: point it at `/mcp` with theunified key as a Bearer token.+### ChatGPT (private Secure MCP Tunnel)++`ask_freellmapi` makes FreeLLMAPI directly callable from a ChatGPT conversation. It uses+the same `/v1/chat/completions` implementation as every OpenAI-compatible client, so model+routing, fallback, response caching, prompt compression, token accounting, execution ids,+and redacted provider errors stay consistent. The result includes the answer, requested and+served model, usage, route, fallback trail, cache/compression state, and execution id.++The three relevant settings are deliberately separate:++| Setting | Where it lives | Example |+| --- | --- | --- |+| Base URL | `mcp.server_urls[].url` in tunnel-client | `http://127.0.0.1:3001/mcp` |+| API key | `FREELLMAPI_MCP_AUTHORIZATION` environment variable | `Bearer freellmapi-...` |+| Default model | FreeLLMAPI `MCP_INFERENCE_DEFAULT_MODEL` | `auto`, a model id, or `auto:<profile>` |++1. Enable the MCP surface as shown above. Optionally set the default model before starting+ FreeLLMAPI:++ ```bash+ MCP_INFERENCE_DEFAULT_MODEL=auto+ MCP_INFERENCE_TIMEOUT_MS=120000+ ```++2. Copy [`examples/chatgpt/tunnel-client.yaml.example`](../../../examples/chatgpt/tunnel-client.yaml.example)+ outside the repository or into an ignored local file, replace its non-secret `tunnel_id`,+ and provide both secrets only through the process environment. The FreeLLMAPI variable+ contains the complete HTTP header value, including `Bearer `:++ ```powershell+ $env:CONTROL_PLANE_API_KEY = '<OpenAI tunnel runtime key>'+ $env:FREELLMAPI_MCP_AUTHORIZATION = 'Bearer <FreeLLMAPI unified key>'+ tunnel-client doctor --profile-file .\tunnel-client.yaml --explain+ tunnel-client run --profile-file .\tunnel-client.yaml+ ```++ ```bash+ export CONTROL_PLANE_API_KEY='<OpenAI tunnel runtime key>'+ export FREELLMAPI_MCP_AUTHORIZATION='Bearer <FreeLLMAPI unified key>'+ tunnel-client doctor --profile-file ./tunnel-client.yaml --explain+ tunnel-client run --profile-file ./tunnel-client.yaml+ ```++3. In ChatGPT, enable **Settings → Security and login → Developer mode**. Open the Plugins+ directory, create a developer-mode plugin, choose **Tunnel**, and select the tunnel id.+ Review the discovered tools before saving. Start with `healthcheck`; use+ `ask_freellmapi` for inference and `list_models` when selecting an explicit model.++The tunnel's static MCP headers are sent only to the configured FreeLLMAPI origin. Do not+put either API key in the YAML file, MCP URL, screenshots, logs, or commits. A public plugin+deployment is a different security model and needs a stable public HTTPS endpoint plus the+authentication required by ChatGPT; the private tunnel above is the local-first path.+FreeLLMAPI is local-first and single-user by design. Your provider keys stay inyour SQLite database, encrypted at rest, and requests go from your machine to theupstream providers you enabled.diff --git a/docs/en/env/01-variables.md b/docs/en/env/01-variables.mdindex d6dbf5e9..80abface 100644--- a/docs/en/env/01-variables.md+++ b/docs/en/env/01-variables.md@@ -93,6 +93,8 @@ In Docker, `127.0.0.1` is the container, not your machine — see [03-outbound-p| Variable | Default | Purpose || --- | --- | --- || `REQUEST_BODY_LIMIT_MB` | `25` | JSON body limit in MB for the inference surfaces (`/v1`, `/v1beta`, `/mcp`, Ollama `/api/*`). Vision requests embed base64 images in the body and replay them with every turn, so large sessions can clear 10MB; this ceiling only gates parsing — inbound image normalization shrinks the payload afterwards. Raise it if bigger payloads are rejected with 413 `request_too_large`. |+| `MCP_INFERENCE_DEFAULT_MODEL` | `auto` | Default model id or named chain used by the MCP `ask_freellmapi` tool when the caller omits `model`. This is the model setting for a ChatGPT connection; each tool call may still override it. |+| `MCP_INFERENCE_TIMEOUT_MS` | `120000` | Timeout for `ask_freellmapi`, from 1,000 to 300,000 ms. An invalid value falls back to 120 seconds. This does not change ordinary `/v1` request timeouts. || `IMAGE_NORMALIZE` | `on` | Inbound image normalization master switch (`off` disables entirely). Data-URL images over the threshold are downscaled to the long-edge cap and re-encoded (JPEG, or PNG only when the alpha channel carries real transparency) before routing, shrinking replayed screenshots ~6–10x. Also normalizes exotic formats upstreams reject (bmp/gif/tiff/avif/webp → jpeg/png); gif keeps its first frame only. Every upstream resizes internally anyway (OpenAI to 2048px, Anthropic to 1568px), so pixels beyond the cap are transport waste. || `IMAGE_NORMALIZE_MAX_DIMENSION` | `2048` | Long-edge cap in pixels for normalized images. || `IMAGE_NORMALIZE_THRESHOLD_KB` | `1024` | Images above this size (KB) are candidates for downscaling. |diff --git a/examples/chatgpt/tunnel-client.yaml.example b/examples/chatgpt/tunnel-client.yaml.examplenew file mode 100644index 00000000..9e1a8571--- /dev/null+++ b/examples/chatgpt/tunnel-client.yaml.example@@ -0,0 +1,26 @@+# FreeLLMAPI -> ChatGPT private MCP connection.+# Secrets are read from environment variables and are never stored here.+config_version: 1++control_plane:+ # Replace this non-secret placeholder with the tunnel id from OpenAI Platform.+ tunnel_id: tunnel_00000000000000000000000000000000+ api_key: env:CONTROL_PLANE_API_KEY++mcp:+ server_urls:+ - channel: main+ url: http://127.0.0.1:3001/mcp+ # Set FREELLMAPI_MCP_AUTHORIZATION to the complete value+ # "Bearer freellmapi-..." in the process environment.+ extra_headers:+ Authorization: env:FREELLMAPI_MCP_AUTHORIZATION+ discovery_extra_headers:+ Authorization: env:FREELLMAPI_MCP_AUTHORIZATION+ startup_wait_timeout: 60s++health:+ listen_addr: 127.0.0.1:0++admin_ui:+ open_browser: falsediff --git a/server/src/__tests__/routes/mcp.test.ts b/server/src/__tests__/routes/mcp.test.tsindex 54d6c7f9..c1fb17b8 100644--- a/server/src/__tests__/routes/mcp.test.ts+++ b/server/src/__tests__/routes/mcp.test.ts@@ -1,7 +1,8 @@-import { describe, it, expect, beforeAll } from 'vitest';+import { describe, it, expect, beforeAll, vi } from 'vitest';import type { Express } from 'express';import { createApp } from '../../app.js';import { initDb, getDb, getUnifiedApiKey, setSetting } from '../../db/index.js';+import { encrypt } from '../../lib/crypto.js';let app: Express;@@ -127,14 +128,32 @@ describe('MCP server (/mcp, stateless Streamable HTTP)', () => {expect(data.top_models.some((m: any) => m.model_id === 'test-model')).toBe(true);});- it('lists the seven gateway tools with schemas', async () => {+ it('lists the ChatGPT inference and gateway tools with complete metadata', async () => {const { body } = await rpc({ jsonrpc: '2.0', id: 2, method: 'tools/list' });const names = body.result.tools.map((t: any) => t.name).sort();- expect(names).toEqual(['cache_stats', 'compression_stats', 'list_models', 'provider_health', 'routing_info', 'set_routing_strategy', 'usage_summary']);+ expect(names).toEqual([+ 'ask_freellmapi',+ 'cache_stats',+ 'compression_stats',+ 'healthcheck',+ 'list_models',+ 'provider_health',+ 'routing_info',+ 'set_routing_strategy',+ 'usage_summary',+ ]);for (const tool of body.result.tools) {+ expect(tool.title.length).toBeGreaterThan(5);expect(tool.description.length).toBeGreaterThan(20);expect(tool.inputSchema.type).toBe('object');+ expect(tool.annotations.destructiveHint).toBe(false);+ expect(typeof tool.annotations.readOnlyHint).toBe('boolean');+ expect(typeof tool.annotations.openWorldHint).toBe('boolean');}+ const ask = body.result.tools.find((tool: any) => tool.name === 'ask_freellmapi');+ expect(ask.inputSchema.required).toEqual(['prompt']);+ expect(ask.outputSchema.required).toContain('usage');+ expect(ask.annotations).toEqual({ readOnlyHint: true, destructiveHint: false, openWorldHint: true });});it('list_models returns catalog entries with supported_parameters', async () => {@@ -172,13 +191,95 @@ describe('MCP server (/mcp, stateless Streamable HTTP)', () => {});it('usage, health, cache, and compression stats answer on an empty install', async () => {- for (const name of ['usage_summary', 'provider_health', 'cache_stats', 'compression_stats']) {+ for (const name of ['healthcheck', 'usage_summary', 'provider_health', 'cache_stats', 'compression_stats']) {const { body } = await rpc({ jsonrpc: '2.0', id: 7, method: 'tools/call', params: { name } });expect(body.result.content[0].type).toBe('text');+ expect(body.result.structuredContent).toEqual(toolResultJson(body));expect(body.result.isError).toBeUndefined();}});+ it('validates ask_freellmapi arguments as a tool-level error', async () => {+ const { body } = await rpc({+ jsonrpc: '2.0', id: 70, method: 'tools/call',+ params: { name: 'ask_freellmapi', arguments: { prompt: '', timeout_ms: 10 } },+ });+ expect(body.error).toBeUndefined();+ expect(body.result.isError).toBe(true);+ expect(body.result.content[0].text).toContain('Invalid ask_freellmapi arguments');+ });++ it('returns model errors as sanitized tool-level failures', async () => {+ const { body } = await rpc({+ jsonrpc: '2.0', id: 72, method: 'tools/call',+ params: {+ name: 'ask_freellmapi',+ arguments: { prompt: 'This request must not reach a provider.', model: 'definitely-not-a-real-model' },+ },+ });+ expect(body.error).toBeUndefined();+ expect(body.result.isError).toBe(true);+ expect(body.result.content[0].text).toContain('FreeLLMAPI inference failed (404)');+ expect(body.result.content[0].text).toContain('definitely-not-a-real-model');+ expect(body.result.content[0].text).toContain('is not in the catalog');+ });++ it('runs ask_freellmapi through the OpenAI-compatible route and returns routing/token metadata', async () => {+ const db = getDb();+ const encrypted = encrypt('test-provider-key');+ const inserted = db.prepare(`+ INSERT INTO api_keys (platform, label, encrypted_key, iv, auth_tag, status, enabled)+ VALUES ('groq', 'mcp-chatgpt-test', ?, ?, ?, 'healthy', 1)+ `).run(encrypted.encrypted, encrypted.iv, encrypted.authTag);++ const originalFetch = global.fetch;+ vi.spyOn(global, 'fetch').mockImplementation(async (input, init) => {+ const url = typeof input === 'string' ? input : input.toString();+ if (url.includes('api.groq.com/openai/v1/chat/completions')) {+ return new Response(JSON.stringify({+ id: 'chatcmpl-mcp-test',+ object: 'chat.completion',+ created: 123,+ model: 'openai/gpt-oss-120b',+ choices: [{+ index: 0,+ message: { role: 'assistant', content: 'FreeLLMAPI answered from ChatGPT.' },+ finish_reason: 'stop',+ }],+ usage: { prompt_tokens: 9, completion_tokens: 6, total_tokens: 15 },+ }), { status: 200, headers: { 'Content-Type': 'application/json' } });+ }+ return originalFetch(input, init);+ });++ try {+ const { body } = await rpc({+ jsonrpc: '2.0', id: 71, method: 'tools/call',+ params: {+ name: 'ask_freellmapi',+ arguments: { prompt: 'Answer this through FreeLLMAPI.', temperature: 0, max_tokens: 64 },+ },+ });++ expect(body.result.isError).toBeUndefined();+ const data = toolResultJson(body);+ expect(body.result.structuredContent).toEqual(data);+ expect(data).toMatchObject({+ answer: 'FreeLLMAPI answered from ChatGPT.',+ requested_model: 'auto',+ finish_reason: 'stop',+ usage: { prompt_tokens: 9, completion_tokens: 6, total_tokens: 15 },+ cache: 'OFF',+ });+ expect(data.model).toBeTruthy();+ expect(data.routed_via).toContain('groq');+ expect(data.execution_id).toBeTruthy();+ } finally {+ vi.restoreAllMocks();+ db.prepare('DELETE FROM api_keys WHERE id = ?').run(inserted.lastInsertRowid);+ }+ });+it('unknown tool and unknown method return JSON-RPC errors', async () => {const tool = await rpc({ jsonrpc: '2.0', id: 8, method: 'tools/call', params: { name: 'rm_rf' } });expect(tool.body.error.code).toBe(-32602);diff --git a/server/src/routes/mcp.ts b/server/src/routes/mcp.tsindex 67ff9e1d..70f6d5d8 100644--- a/server/src/routes/mcp.ts+++ b/server/src/routes/mcp.ts@@ -8,6 +8,8 @@ import { getRoutingScores, getRoutingStrategy, setRoutingStrategy } from '../serimport type { RoutingStrategy } from '../services/scoring.js';import { getCacheStats } from '../services/cache.js';import { getCompressionStats } from '../services/compression/stats.js';+import { sanitizeProviderErrorMessage } from '../lib/error-redaction.js';+import { z } from 'zod';// ─────────────────────────────────────────────────────────────────────────// MCP server for the gateway (POST /mcp) — Model Context Protocol over@@ -17,8 +19,9 @@ import { getCompressionStats } from '../services/compression/stats.js';// questions mid-session: which free models are usable right now and with// which parameters, how healthy the provider pool is, what the routing// strategy is, and how much quota the cache has saved — plus one control-// knob (switching the routing strategy). Inference itself stays on the-// OpenAI/Anthropic surfaces; these tools are the gateway's introspection.+// knob (switching the routing strategy). The ask_freellmapi tool also lets+// ChatGPT and other MCP clients run a non-streaming inference through the same+// /v1/chat/completions path as every OpenAI-compatible client.//// Hand-rolled JSON-RPC instead of the MCP SDK for the same reason the// OpenAPI viewer is dependency-free (#482): the desktop bundle and the@@ -56,7 +59,13 @@ function rpcError(id: number | string | null, code: number, message: string) {// One text block carrying pretty-printed JSON — the standard shape for// machine-readable MCP tool output.function toolJson(data: unknown) {- return { content: [{ type: 'text', text: JSON.stringify(data, null, 2) }] };+ const structuredContent = data && typeof data === 'object' && !Array.isArray(data)+ ? data as Record<string, unknown>+ : { result: data };+ return {+ content: [{ type: 'text', text: JSON.stringify(data, null, 2) }],+ structuredContent,+ };}function toolError(message: string) {@@ -184,16 +193,231 @@ function setStrategy(args: Record<string, unknown>): unknown {return { strategy: getRoutingStrategy() };}+const DEFAULT_MCP_INFERENCE_TIMEOUT_MS = 120_000;+const MAX_MCP_INFERENCE_TIMEOUT_MS = 300_000;++const askFreeLlmApiSchema = z.object({+ prompt: z.string().min(1).max(400_000),+ system: z.string().min(1).max(50_000).optional(),+ model: z.string().min(1).max(256).optional(),+ temperature: z.number().min(0).max(2).optional(),+ max_tokens: z.number().int().min(1).max(32_768).optional(),+ timeout_ms: z.number().int().min(1_000).max(MAX_MCP_INFERENCE_TIMEOUT_MS).optional(),+}).strict();++function mcpDefaultModel(): string {+ const configured = process.env.MCP_INFERENCE_DEFAULT_MODEL?.trim();+ if (!configured) return 'auto';+ if (configured.length > 256) {+ throw new Error('MCP_INFERENCE_DEFAULT_MODEL must be at most 256 characters');+ }+ return configured;+}++function mcpInferenceTimeoutMs(): number {+ const raw = process.env.MCP_INFERENCE_TIMEOUT_MS?.trim();+ if (!raw) return DEFAULT_MCP_INFERENCE_TIMEOUT_MS;+ const parsed = Number(raw);+ if (!Number.isInteger(parsed) || parsed < 1_000 || parsed > MAX_MCP_INFERENCE_TIMEOUT_MS) {+ return DEFAULT_MCP_INFERENCE_TIMEOUT_MS;+ }+ return parsed;+}++function loopbackChatCompletionsUrl(req: Request): string {+ const port = req.socket.localPort;+ if (!port) throw new Error('Cannot determine the local FreeLLMAPI port for inference');++ let address = (req.socket.localAddress || '127.0.0.1').split('%')[0];+ if (address === '0.0.0.0') address = '127.0.0.1';+ if (address === '::') address = '::1';+ if (address.startsWith('::ffff:')) address = address.slice('::ffff:'.length);+ const host = address.includes(':') ? `[${address}]` : address;+ return `http://${host}:${port}/v1/chat/completions`;+}++function assistantText(payload: any): string {+ const content = payload?.choices?.[0]?.message?.content;+ if (typeof content === 'string') return content;+ if (!Array.isArray(content)) return '';+ return content+ .map((part: any) => typeof part === 'string' ? part : (typeof part?.text === 'string' ? part.text : ''))+ .join('');+}++async function askFreeLlmApi(args: Record<string, unknown>, req: Request, res: Response): Promise<unknown> {+ const parsed = askFreeLlmApiSchema.safeParse(args);+ if (!parsed.success) {+ const detail = parsed.error.errors+ .map(error => `${error.path.join('.') || 'arguments'}: ${error.message}`)+ .slice(0, 5)+ .join(', ');+ throw new Error(`Invalid ask_freellmapi arguments: ${detail}`);+ }++ const input = parsed.data;+ const model = input.model?.trim() || mcpDefaultModel();+ const timeoutMs = input.timeout_ms ?? mcpInferenceTimeoutMs();+ const controller = new AbortController();+ const timeout = setTimeout(() => controller.abort(), timeoutMs);+ const abortOnDisconnect = () => controller.abort();+ req.once('aborted', abortOnDisconnect);+ res.once('close', abortOnDisconnect);++ try {+ const messages = [+ ...(input.system ? [{ role: 'system', content: input.system }] : []),+ { role: 'user', content: input.prompt },+ ];+ const response = await fetch(loopbackChatCompletionsUrl(req), {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ Accept: 'application/json',+ Authorization: `Bearer ${getUnifiedApiKey()}`,+ },+ body: JSON.stringify({+ model,+ messages,+ stream: false,+ ...(input.temperature === undefined ? {} : { temperature: input.temperature }),+ ...(input.max_tokens === undefined ? {} : { max_tokens: input.max_tokens }),+ }),+ signal: controller.signal,+ });++ const raw = await response.text();+ let payload: any;+ try {+ payload = raw ? JSON.parse(raw) : null;+ } catch {+ throw new Error(`FreeLLMAPI inference returned non-JSON data (HTTP ${response.status})`);+ }++ if (!response.ok) {+ const upstreamMessage = payload?.error?.message ?? payload?.message ?? `HTTP ${response.status}`;+ throw new Error(`FreeLLMAPI inference failed (${response.status}): ${sanitizeProviderErrorMessage(upstreamMessage)}`);+ }++ const answer = assistantText(payload);+ if (!answer) {+ throw new Error(`FreeLLMAPI inference returned no assistant text (finish_reason: ${payload?.choices?.[0]?.finish_reason ?? 'unknown'})`);+ }++ return {+ answer,+ requested_model: model,+ model: typeof payload?.model === 'string' ? payload.model : null,+ finish_reason: typeof payload?.choices?.[0]?.finish_reason === 'string'+ ? payload.choices[0].finish_reason+ : null,+ usage: payload?.usage && typeof payload.usage === 'object' ? payload.usage : null,+ routed_via: response.headers.get('x-routed-via'),+ fallback_trail: response.headers.get('x-fallback-trail'),+ cache: response.headers.get('x-freellm-cache'),+ compression: response.headers.get('x-freellm-compress'),+ execution_id: typeof payload?.execution_id === 'string'+ ? payload.execution_id+ : response.headers.get('x-request-id'),+ };+ } catch (error: any) {+ if (error?.name === 'AbortError') {+ throw new Error(`FreeLLMAPI inference timed out or was cancelled after ${timeoutMs}ms`);+ }+ throw error;+ } finally {+ clearTimeout(timeout);+ req.off('aborted', abortOnDisconnect);+ res.off('close', abortOnDisconnect);+ }+}++function healthcheck(): unknown {+ const { models } = buildModelListing();+ const availableModels = models.filter(model => model.available === 1).length;+ const providers = providerHealth() as Record<string, {+ keys: Record<string, number>;+ active_cooldowns: number;+ available_models: number;+ }>;+ const providerRows = Object.values(providers);+ const healthyProviders = providerRows.filter(provider =>+ (provider.keys.healthy ?? 0) > 0 && provider.available_models > 0,+ ).length;+ return {+ status: availableModels > 0 ? 'ready' : 'needs_configuration',+ mcp_enabled: isMcpServerEnabled(),+ default_model: mcpDefaultModel(),+ available_models: availableModels,+ configured_providers: providerRows.length,+ healthy_providers: healthyProviders,+ checked_at: new Date().toISOString(),+ };+}+// ── Tool registry ────────────────────────────────────────────────────────interface McpTool {+ title: string;description: string;inputSchema: Record<string, unknown>;- run: (args: Record<string, unknown>) => unknown;+ outputSchema?: Record<string, unknown>;+ annotations: {+ readOnlyHint: boolean;+ destructiveHint: boolean;+ openWorldHint: boolean;+ };+ run: (args: Record<string, unknown>, req: Request, res: Response) => unknown | Promise<unknown>;}+const READ_ONLY_LOCAL = { readOnlyHint: true, destructiveHint: false, openWorldHint: false };+const TOOLS: Record<string, McpTool> = {+ ask_freellmapi: {+ title: 'Ask FreeLLMAPI',+ description: 'Use this when the user explicitly wants a FreeLLMAPI model to answer, analyze, rewrite, summarize, or generate text. Routes through the configured free-provider pool. Defaults to the server\'s MCP_INFERENCE_DEFAULT_MODEL (auto when unset). Returns the answer plus model, routing, cache, execution, and token-usage metadata.',+ inputSchema: {+ type: 'object',+ additionalProperties: false,+ properties: {+ prompt: { type: 'string', minLength: 1, maxLength: 400_000, description: 'The complete task or question for the selected FreeLLMAPI model.' },+ system: { type: 'string', minLength: 1, maxLength: 50_000, description: 'Optional system instructions for the FreeLLMAPI model.' },+ model: { type: 'string', minLength: 1, maxLength: 256, description: 'Model id, named chain, or auto. Omit to use MCP_INFERENCE_DEFAULT_MODEL.' },+ temperature: { type: 'number', minimum: 0, maximum: 2 },+ max_tokens: { type: 'integer', minimum: 1, maximum: 32_768 },+ timeout_ms: { type: 'integer', minimum: 1_000, maximum: MAX_MCP_INFERENCE_TIMEOUT_MS, description: 'Optional request timeout. Defaults to MCP_INFERENCE_TIMEOUT_MS or 120000.' },+ },+ required: ['prompt'],+ },+ outputSchema: {+ type: 'object',+ additionalProperties: false,+ properties: {+ answer: { type: 'string' },+ requested_model: { type: 'string' },+ model: { type: ['string', 'null'] },+ finish_reason: { type: ['string', 'null'] },+ usage: { type: ['object', 'null'], additionalProperties: true },+ routed_via: { type: ['string', 'null'] },+ fallback_trail: { type: ['string', 'null'] },+ cache: { type: ['string', 'null'] },+ compression: { type: ['string', 'null'] },+ execution_id: { type: ['string', 'null'] },+ },+ required: ['answer', 'requested_model', 'model', 'finish_reason', 'usage', 'routed_via', 'fallback_trail', 'cache', 'compression', 'execution_id'],+ },+ annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: true },+ run: (args, req, res) => askFreeLlmApi(args, req, res),+ },+ healthcheck: {+ title: 'Check FreeLLMAPI readiness',+ description: 'Check whether FreeLLMAPI is ready for ChatGPT calls, including MCP state, configured/healthy providers, available models, and the default MCP inference model. This does not spend provider quota.',+ inputSchema: { type: 'object', properties: {}, additionalProperties: false },+ annotations: READ_ONLY_LOCAL,+ run: () => healthcheck(),+ },list_models: {+ title: 'List FreeLLMAPI models',description: 'List the models this FreeLLMAPI router can serve, with context windows, tool support, and the parameters each model honors (supported_parameters). Defaults to only models that are usable right now.',inputSchema: {type: 'object',@@ -201,14 +425,18 @@ const TOOLS: Record<string, McpTool> = {available_only: { type: 'boolean', description: 'false to include models that are configured but not currently usable (no key, disabled)', default: true },},},+ annotations: READ_ONLY_LOCAL,run: listModels,},provider_health: {+ title: 'Inspect provider health',description: 'Per-provider key statuses (healthy/rate_limited/invalid/error/unknown), active cooldowns, and how many models each provider can serve right now.',inputSchema: { type: 'object', properties: {} },+ annotations: READ_ONLY_LOCAL,run: () => providerHealth(),},usage_summary: {+ title: 'Summarize FreeLLMAPI usage',description: 'Request/token totals, success rate, and the top models by traffic for a recent window.',inputSchema: {type: 'object',@@ -216,14 +444,18 @@ const TOOLS: Record<string, McpTool> = {range: { type: 'string', enum: ['24h', '7d', '30d'], default: '24h' },},},+ annotations: READ_ONLY_LOCAL,run: usageSummary,},routing_info: {+ title: 'Inspect model routing',description: 'The active routing strategy and the current top-scored models in the fallback chain.',inputSchema: { type: 'object', properties: {} },+ annotations: READ_ONLY_LOCAL,run: () => routingInfo(),},set_routing_strategy: {+ title: 'Set model routing strategy',description: 'Switch the routing strategy (priority = manual chain order; balanced / smartest / fastest / reliable are scored presets; custom uses the saved weight vector).',inputSchema: {type: 'object',@@ -232,16 +464,21 @@ const TOOLS: Record<string, McpTool> = {},required: ['strategy'],},+ annotations: { readOnlyHint: false, destructiveHint: false, openWorldHint: false },run: setStrategy,},cache_stats: {+ title: 'Inspect response-cache savings',description: 'Response-cache statistics: entries, total hits, and the prompt/completion tokens the cache has saved.',inputSchema: { type: 'object', properties: {} },+ annotations: READ_ONLY_LOCAL,run: () => getCacheStats(),},compression_stats: {+ title: 'Inspect prompt-compression savings',description: 'Prompt-compression statistics: requests compressed, estimated tokens saved, fidelity-gate discards, and per-engine savings.',inputSchema: { type: 'object', properties: {} },+ annotations: READ_ONLY_LOCAL,run: () => getCompressionStats(),},};@@ -253,21 +490,21 @@ const TOOLS: Record<string, McpTool> = {// `id` member (id:null is a — discouraged — request and gets a response);// detecting notifications by the `notifications/` method prefix answered// no-id requests and 202'd id-carrying notifications.-function handleRpc(msg: JsonRpcRequest): unknown | undefined {+async function handleRpc(msg: JsonRpcRequest, req: Request, res: Response): Promise<unknown | undefined> {const isNotification = msg.id === undefined;const respond = (response: unknown) => (isNotification ? undefined : response);const id = msg.id ?? null;- return respond(dispatchRpc(msg, id));+ return respond(await dispatchRpc(msg, id, req, res));}-function dispatchRpc(msg: JsonRpcRequest, id: number | string | null): unknown {+async function dispatchRpc(msg: JsonRpcRequest, id: number | string | null, req: Request, res: Response): Promise<unknown> {switch (msg.method) {case 'initialize': {return rpcResult(id, {protocolVersion: PROTOCOL_VERSION,capabilities: { tools: {} },serverInfo: { name: 'freellmapi', version: '1.0.0' },- instructions: 'FreeLLMAPI gateway introspection: list usable free models (with per-model supported_parameters), check provider/key health, read usage/cache/compression stats, and switch the routing strategy. Inference goes through the OpenAI-compatible /v1 endpoints, not MCP.',+ instructions: 'Use ask_freellmapi when the user explicitly asks FreeLLMAPI or one of its models to perform a text task. Use healthcheck before troubleshooting availability; list_models for model choice; provider_health, usage_summary, cache_stats, compression_stats, and routing_info for diagnostics. set_routing_strategy changes server state.',});}case 'ping':@@ -276,8 +513,11 @@ function dispatchRpc(msg: JsonRpcRequest, id: number | string | null): unknown {return rpcResult(id, {tools: Object.entries(TOOLS).map(([name, t]) => ({name,+ title: t.title,description: t.description,inputSchema: t.inputSchema,+ ...(t.outputSchema ? { outputSchema: t.outputSchema } : {}),+ annotations: t.annotations,})),});case 'tools/call': {@@ -289,7 +529,7 @@ function dispatchRpc(msg: JsonRpcRequest, id: number | string | null): unknown {if (!tool) return rpcError(id, -32602, `Unknown tool: ${name}`);try {const args = (msg.params?.arguments as Record<string, unknown>) ?? {};- return rpcResult(id, toolJson(tool.run(args)));+ return rpcResult(id, toolJson(await tool.run(args, req, res)));} catch (err: any) {// Tool-level failures are results with isError, not protocol errors.return rpcResult(id, toolError(err?.message ?? 'tool failed'));@@ -344,7 +584,7 @@ mcpRouter.use((req: Request, res: Response, next: NextFunction) => {res.status(403).json(rpcError(id, -32000, 'MCP server is disabled. Turn it on from the dashboard (Keys -> Agent compatibility) or with PUT /api/settings/enable-mcp {"enabled":true}.'));});-mcpRouter.post('/', (req: Request, res: Response) => {+mcpRouter.post('/', async (req: Request, res: Response) => {if (!authenticate(req, res)) return;const body = req.body;@@ -359,7 +599,7 @@ mcpRouter.post('/', (req: Request, res: Response) => {return;}- const response = handleRpc(body as JsonRpcRequest);+ const response = await handleRpc(body as JsonRpcRequest, req, res);if (response === undefined) {res.status(202).end(); // notification — accepted, nothing to sayreturn;