Repository navigation
feat(api): model catalog enrichment + MCP model-catalog tools #3306
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from 2 commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -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 ============ | ||
|
|
@@ -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) : {}; | ||
| } | ||
|
|
@@ -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
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. The 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
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. If any single provider connection fails to fetch (e.g., due to a temporary network issue or misconfiguration), the entire 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>, | ||
|
|
@@ -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", | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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.