Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/frameworks/MCP-SERVER.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ lastUpdated: 2026-05-30
>
> Source of truth: `open-sse/mcp-server/schemas/tools.ts` (30 tools) + `open-sse/mcp-server/tools/memoryTools.ts` (3 tools) + `open-sse/mcp-server/tools/skillTools.ts` (4 tools) + `open-sse/mcp-server/tools/notionTools.ts` (6 tools). Tool registration and scope wiring lives in `open-sse/mcp-server/server.ts`.

![MCP tool inventory (43 tools by category)](../diagrams/exported/mcp-tools-43.svg)
![MCP tool inventory (43 tools by category)](../diagrams/exported/mcp-tools-37.svg)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The image reference was updated to mcp-tools-37.svg, but the alt text still says (43 tools by category). It should be updated to match the new count of 37 tools.

Suggested change
![MCP tool inventory (43 tools by category)](../diagrams/exported/mcp-tools-37.svg)
![MCP tool inventory (37 tools by category)](../diagrams/exported/mcp-tools-37.svg)


> Source: [diagrams/mcp-tools-43.mmd](../diagrams/mcp-tools-43.mmd) (regenerate via `npm run docs:render-diagrams`).
Comment on lines +13 to 15

Expand Down
36 changes: 32 additions & 4 deletions open-sse/config/providerRegistry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,16 @@ const GPT_5_5_CODEX_CAPABILITIES = {
contextLength: GPT_5_5_CONTEXT_LENGTH,
} as const;

const GPT_5_4_CODEX_CAPABILITIES = {
targetFormat: "openai-responses",
toolCalling: true,
supportsReasoning: true,
supportsVision: true,
supportsXHighEffort: true,
contextLength: 200000,
maxOutputTokens: 128000,
} as const;

const CHAT_OPENAI_COMPAT_MODELS: Record<string, RegistryModel[]> = {
deepinfra: buildModels([
"anthropic/claude-4-opus",
Expand Down Expand Up @@ -866,9 +876,27 @@ const _REGISTRY_EAGER: Record<string, RegistryEntry> = {
{
id: "gpt-5.4",
name: "GPT 5.4",
targetFormat: "openai-responses",
supportsReasoning: true,
supportsXHighEffort: true,
...GPT_5_4_CODEX_CAPABILITIES,
},
{
id: "gpt-5.4-xhigh",
name: "GPT 5.4 (xHigh)",
...GPT_5_4_CODEX_CAPABILITIES,
},
{
id: "gpt-5.4-high",
name: "GPT 5.4 (High)",
...GPT_5_4_CODEX_CAPABILITIES,
},
{
id: "gpt-5.4-medium",
name: "GPT 5.4 (Medium)",
...GPT_5_4_CODEX_CAPABILITIES,
},
{
id: "gpt-5.4-low",
name: "GPT 5.4 (Low)",
...GPT_5_4_CODEX_CAPABILITIES,
},
{ id: "gpt-5.4-mini", name: "GPT 5.4 Mini", targetFormat: "openai-responses" },
{ id: "gpt-5.3-codex-spark", name: "GPT 5.3 Codex Spark" },
Expand Down Expand Up @@ -1007,7 +1035,7 @@ const _REGISTRY_EAGER: Record<string, RegistryEntry> = {
{ id: "gpt-5-mini", name: "GPT-5 Mini", targetFormat: "openai-responses" },
{ id: "gpt-5.3-codex", name: "GPT-5.3 Codex", targetFormat: "openai-responses" },
{ id: "gpt-5.4-mini", name: "GPT-5.4 Mini", targetFormat: "openai-responses" },
{ id: "gpt-5.4", name: "GPT-5.4", targetFormat: "openai-responses" },
{ id: "gpt-5.4", name: "GPT-5.4", targetFormat: "openai-responses", supportsXHighEffort: true },
{ id: "gpt-5.5", name: "GPT-5.5", ...GPT_5_5_CODEX_CAPABILITIES },
{
id: "claude-haiku-4.5",
Expand Down
1 change: 1 addition & 0 deletions open-sse/mcp-server/schemas/tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -370,6 +370,7 @@ export const listModelsCatalogOutput = z.object({
provider: z.string(),
capabilities: z.array(z.string()),
status: z.enum(["available", "degraded", "unavailable"]),
thinkingEffort: z.string().optional(),
pricing: z
.object({
inputPerMillion: z.number().nullable(),
Expand Down
252 changes: 208 additions & 44 deletions open-sse/mcp-server/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,10 @@ import {
type McpAccessibilityConfig,
} from "../services/compression/engines/mcpAccessibility/constants.ts";
import { getDbInstance } from "../../src/lib/db/core.ts";
import { getProviderConnections } from "../../src/lib/db/providers.ts";
import { getCodexRequestDefaults } from "../../src/lib/providers/requestDefaults.ts";
import { normalizeQuotaResponse } from "../../src/shared/contracts/quota.ts";
import { AI_PROVIDERS, NOAUTH_PROVIDERS } from "../../src/shared/constants/providers.ts";
import { resolveOmniRouteBaseUrl } from "../../src/shared/utils/resolveOmniRouteBaseUrl.ts";

// ============ Configuration ============
Expand Down Expand Up @@ -147,6 +150,28 @@ type TextToolResult = {
isError?: boolean;
};

type McpCatalogStatus = "available" | "degraded" | "unavailable";

type McpCatalogResponse = {
models: Array<{
id: string;
provider: string;
capabilities: string[];
status: McpCatalogStatus;
thinkingEffort?: string;
pricing?: unknown;
}>;
source: string;
warning?: string;
};

type ProviderConnectionLike = {
id?: string;
provider?: string;
isActive?: boolean;
providerSpecificData?: unknown;
};

function toRecord(value: unknown): JsonRecord {
return value && typeof value === "object" && !Array.isArray(value) ? (value as JsonRecord) : {};
}
Expand Down Expand Up @@ -214,6 +239,188 @@ async function omniRouteFetch(path: string, options: RequestInit = {}): Promise<
return response.json();
}

function buildProviderAliasMap(): Record<string, string> {
const aliasMap: Record<string, string> = {};

for (const provider of Object.values(AI_PROVIDERS)) {
if (!provider?.id) continue;
aliasMap[provider.id] = provider.id;
if (typeof provider.alias === "string" && provider.alias.length > 0) {
aliasMap[provider.alias] = provider.id;
}
}

for (const provider of Object.values(NOAUTH_PROVIDERS)) {
if (!provider?.id) continue;
aliasMap[provider.id] = provider.id;
if ("alias" in provider && typeof provider.alias === "string" && provider.alias.length > 0) {
aliasMap[provider.alias] = provider.id;
}
}

return aliasMap;
}

function normalizeCapability(value: string): string {
switch (value) {
case "embeddings":
return "embedding";
case "images":
return "image";
case "videos":
return "video";
case "moderations":
return "moderation";
case "chat-completions":
return "chat";
default:
return value;
}
}

function getCatalogModelCapabilities(model: JsonRecord): string[] {
if (Array.isArray(model.capabilities) && model.capabilities.length > 0) {
return toStringArray(model.capabilities, ["chat"]).map(normalizeCapability);
}

if (Array.isArray(model.supportedEndpoints) && model.supportedEndpoints.length > 0) {
return toStringArray(model.supportedEndpoints, ["chat"]).map(normalizeCapability);
}

const type = toString(model.type);
if (type) return [normalizeCapability(type)];

return ["chat"];
}

function normalizeCatalogStatus(model: JsonRecord, source: string, warning?: string): McpCatalogStatus {
const explicitStatus = toString(model.status);
if (explicitStatus === "available" || explicitStatus === "degraded" || explicitStatus === "unavailable") {
return explicitStatus;
}

if (warning || source === "local_catalog") return "degraded";
return "available";
}

function getConnectionThinkingEffort(connection: ProviderConnectionLike): string | undefined {
const provider = typeof connection.provider === "string" ? connection.provider : null;
const providerSpecificData = toRecord(connection.providerSpecificData);

if (provider === "codex") {
return getCodexRequestDefaults(providerSpecificData).reasoningEffort || "medium";
}

const rawThinkingEffort = toString(providerSpecificData.thinkingEffort);
return rawThinkingEffort || undefined;
}

function normalizeProviderModelRecord(
rawModel: unknown,
fallbackProvider: string,
source: string,
warning?: string,
thinkingEffort?: string
) {
const model = toRecord(rawModel);
const id = toString(model.id, "");

return {
id,
provider: toString(model.owned_by, toString(model.provider, fallbackProvider)),
capabilities: getCatalogModelCapabilities(model),
status: normalizeCatalogStatus(model, source, warning),
...(thinkingEffort ? { thinkingEffort } : {}),
pricing: model.pricing,
};
}
Comment on lines +318 to +336

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The pricing object is returned as-is from model.pricing. If the upstream provider returns pricing with unexpected fields or an empty object, it will fail the strict Zod validation in listModelsCatalogOutput (which requires both inputPerMillion and outputPerMillion to be present, even if they are null). Safely normalizing the pricing object here ensures it always conforms to the expected schema.

function normalizeProviderModelRecord(
  rawModel: unknown,
  fallbackProvider: string,
  source: string,
  warning?: string,
  thinkingEffort?: string
) {
  const model = toRecord(rawModel);
  const id = toString(model.id, "");

  const rawPricing = toRecord(model.pricing);
  const pricing = typeof model.pricing === "object" && model.pricing !== null
    ? {
        inputPerMillion: typeof rawPricing.inputPerMillion === "number" ? rawPricing.inputPerMillion : null,
        outputPerMillion: typeof rawPricing.outputPerMillion === "number" ? rawPricing.outputPerMillion : null,
      }
    : undefined;

  return {
    id,
    provider: toString(model.owned_by, toString(model.provider, fallbackProvider)),
    capabilities: getCatalogModelCapabilities(model),
    status: normalizeCatalogStatus(model, source, warning),
    ...(thinkingEffort ? { thinkingEffort } : {}),
    pricing,
  };
}


export async function getMcpModelsCatalog(
args: { provider?: string; capability?: string },
deps: {
fetchJson?: (path: string) => Promise<unknown>;
listProviderConnections?: () => Promise<ProviderConnectionLike[]>;
} = {}
): Promise<McpCatalogResponse> {
const fetchJson = deps.fetchJson ?? ((path: string) => omniRouteFetch(path));
const listProviderConnections = deps.listProviderConnections ?? getProviderConnections;
const aliasMap = buildProviderAliasMap();
const normalizeProviderId = (value: string) => aliasMap[value] || value;
const requestedProvider = args.provider ? normalizeProviderId(args.provider) : null;
const requestedCapability = args.capability ? normalizeCapability(args.capability) : null;

let connections = await listProviderConnections();
connections = Array.isArray(connections) ? connections : [];

const activeConnections = connections.filter((connection) => {
const provider = typeof connection?.provider === "string" ? normalizeProviderId(connection.provider) : null;
if (!provider || !connection?.id || connection.isActive === false) return false;
if (requestedProvider && provider !== requestedProvider) return false;
return true;
});

const requestSpecs = activeConnections.map((connection) => ({
provider: normalizeProviderId(String(connection.provider)),
path: `/api/providers/${encodeURIComponent(String(connection.id))}/models?excludeHidden=true`,
thinkingEffort: getConnectionThinkingEffort(connection),
}));

if (requestedProvider && requestSpecs.length === 0) {
const isNoAuthProvider = Object.values(NOAUTH_PROVIDERS).some((provider) => provider.id === requestedProvider);
if (isNoAuthProvider) {
requestSpecs.push({
provider: requestedProvider,
path: `/api/v1/providers/${encodeURIComponent(requestedProvider)}/models`,
thinkingEffort: undefined,
});
} else {
return {
models: [],
source: "provider_connections",
warning: `No active connections found for provider '${requestedProvider}'.`,
};
}
}

const collectedModels = new Map<string, McpCatalogResponse["models"][number]>();
const warnings = new Set<string>();
const sources = new Set<string>();

for (const spec of requestSpecs) {
const raw = toRecord(await fetchJson(spec.path));
const source = toString(raw.source, spec.path.startsWith("/api/providers/") ? "api" : "v1_catalog");
const warning = raw.warning ? String(raw.warning) : undefined;
if (warning) warnings.add(warning);
sources.add(source);

const rawModels = Array.isArray(raw.models)
? raw.models
: Array.isArray(raw.data)
? raw.data
: [];

for (const rawModel of rawModels) {
const normalized = normalizeProviderModelRecord(rawModel, spec.provider, source, warning);
if (spec.thinkingEffort && !normalized.thinkingEffort) {
normalized.thinkingEffort = spec.thinkingEffort;
}
if (!normalized.id) continue;
if (requestedCapability && !normalized.capabilities.includes(requestedCapability)) continue;

const key = `${normalized.provider}:${normalized.id}`;
if (!collectedModels.has(key)) {
collectedModels.set(key, normalized);
}
}
}
Comment on lines +389 to +415
Comment on lines +389 to +415

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

If any single provider connection fails to fetch (e.g., due to a temporary network issue or misconfiguration), the entire getMcpModelsCatalog call will throw an error and fail. This prevents models from other active, healthy connections from being returned. Wrapping the fetchJson call in a try-catch block ensures that a single failing provider does not break the entire model catalog tool, improving overall resilience.

  for (const spec of requestSpecs) {
    try {
      const raw = toRecord(await fetchJson(spec.path));
      const source = toString(raw.source, spec.path.startsWith("/api/providers/") ? "api" : "v1_catalog");
      const warning = raw.warning ? String(raw.warning) : undefined;
      if (warning) warnings.add(warning);
      sources.add(source);

      const rawModels = Array.isArray(raw.models)
        ? raw.models
        : Array.isArray(raw.data)
          ? raw.data
          : [];

      for (const rawModel of rawModels) {
        const normalized = normalizeProviderModelRecord(rawModel, spec.provider, source, warning);
        if (spec.thinkingEffort && !normalized.thinkingEffort) {
          normalized.thinkingEffort = spec.thinkingEffort;
        }
        if (!normalized.id) continue;
        if (requestedCapability && !normalized.capabilities.includes(requestedCapability)) continue;

        const key = `${normalized.provider}:${normalized.id}`;
        if (!collectedModels.has(key)) {
          collectedModels.set(key, normalized);
        }
      }
    } catch (err) {
      warnings.add(`Failed to fetch models for provider ${spec.provider}: ${err instanceof Error ? err.message : String(err)}`);
    }
  }


return {
models: [...collectedModels.values()],
source: sources.size === 1 ? [...sources][0] : "aggregated_provider_models",
...(warnings.size > 0 ? { warning: [...warnings].join(" | ") } : {}),
};
}

function withScopeEnforcement(
toolName: string,
handler: (args: unknown, extra?: McpToolExtraLike) => Promise<TextToolResult>,
Expand Down Expand Up @@ -522,50 +729,7 @@ async function handleCostReport(args: { period?: string }) {
async function handleListModelsCatalog(args: { provider?: string; capability?: string }) {
const start = Date.now();
try {
let path = "/v1/models";
let isProviderSpecific = false;
let source = "local_catalog";
let warning: string | undefined;

if (args.provider && !args.capability) {
// Use direct provider fetch to get real-time API status
path = `/api/providers/${encodeURIComponent(args.provider)}/models?excludeHidden=true`;
isProviderSpecific = true;
} else {
const params = new URLSearchParams();
if (args.provider) params.set("provider", args.provider);
if (args.capability) params.set("capability", args.capability);
if (params.toString()) path += `?${params.toString()}`;
}

const raw = toRecord(await omniRouteFetch(path));

// If we used the direct provider endpoint
let rawModels: unknown[] = [];
if (isProviderSpecific) {
rawModels = Array.isArray(raw.models) ? raw.models : [];
source = typeof raw.source === "string" ? raw.source : "api";
if (raw.warning) warning = String(raw.warning);
} else {
rawModels = Array.isArray(raw.data) ? raw.data : [];
source = "local_catalog";
// OmniRoute's global /v1/models is always a cached/local catalog
}

const result = {
models: rawModels.map((rawModel) => {
const model = toRecord(rawModel);
return {
id: toString(model.id, ""),
provider: toString(model.owned_by, toString(model.provider, args.provider || "unknown")),
capabilities: toStringArray(model.capabilities, ["chat"]),
status: toString(model.status, "available"),
pricing: model.pricing,
};
}),
source,
...(warning ? { warning } : {}),
};
const result = await getMcpModelsCatalog(args);

await logToolCall(
"omniroute_list_models_catalog",
Expand Down
17 changes: 6 additions & 11 deletions src/app/api/v1/models/catalog.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ import { getModelSpec } from "@/shared/constants/modelSpecs";
import { isAuthRequired, isDashboardSessionAuthenticated } from "@/shared/utils/apiAuth";
import { parseModel } from "@omniroute/open-sse/services/model";
import { getTokenLimit } from "@omniroute/open-sse/services/contextManager";
import { extractApiKey } from "@/sse/services/auth";
import type { ComboModelStep } from "@/lib/combos/steps";

interface CustomModelEntry {
Expand Down Expand Up @@ -188,13 +189,7 @@ function getOpenRouterDisplayName(model: {
: name;
}

function extractBearer(headers: Headers): string | null {
const authHeader = headers.get("authorization") || headers.get("Authorization");
if (!authHeader?.trim().toLowerCase().startsWith("bearer ")) return null;
return authHeader.trim().slice(7).trim() || null;
}

async function validateCatalogBearer(apiKey: string): Promise<boolean> {
async function validateCatalogApiKey(apiKey: string): Promise<boolean> {
const { validateApiKey } = await import("@/lib/db/apiKeys");
return validateApiKey(apiKey);
}
Expand All @@ -206,9 +201,9 @@ async function getModelCatalogAuthRejection(
): Promise<Response | null> {
if (settings.requireAuthForModels !== true || !(await isAuthRequired(request))) return null;

const bearer = extractBearer(request.headers);
if (bearer) {
if (await validateCatalogBearer(bearer)) return null;
const apiKey = extractApiKey(request);
if (apiKey) {
if (await validateCatalogApiKey(apiKey)) return null;
return Response.json(
{
error: {
Expand Down Expand Up @@ -1247,7 +1242,7 @@ export async function getUnifiedModelsResponse(
}

// Filter by API key permissions if requested
const apiKey = extractBearer(request.headers);
const apiKey = extractApiKey(request);
let finalModels = models;
if (apiKey) {
const { isModelAllowedForKey, getApiKeyMetadata } = await import("@/lib/db/apiKeys");
Expand Down
Loading