|
| 1 | +// Environment-driven model provider for RepoLens MCP. |
| 2 | +// Keeps the MCP local + BYO-key while supporting the providers people already |
| 3 | +// have in agent workflows. Auto-select order is explicit and deterministic. |
| 4 | + |
| 5 | +const DEFAULT_TIMEOUT_MS = 60_000; |
| 6 | + |
| 7 | +const PROVIDERS = { |
| 8 | + anthropic: { |
| 9 | + env: 'ANTHROPIC_API_KEY', |
| 10 | + modelEnv: 'ANTHROPIC_MODEL', |
| 11 | + defaultModel: 'claude-sonnet-4-6', |
| 12 | + }, |
| 13 | + openai: { |
| 14 | + env: 'OPENAI_API_KEY', |
| 15 | + modelEnv: 'OPENAI_MODEL', |
| 16 | + defaultModel: 'gpt-4.1-mini', |
| 17 | + }, |
| 18 | + openrouter: { |
| 19 | + env: 'OPENROUTER_API_KEY', |
| 20 | + modelEnv: 'OPENROUTER_MODEL', |
| 21 | + defaultModel: 'anthropic/claude-sonnet-4.5', |
| 22 | + }, |
| 23 | + google: { |
| 24 | + env: 'GOOGLE_API_KEY', |
| 25 | + modelEnv: 'GOOGLE_MODEL', |
| 26 | + defaultModel: 'gemini-2.5-flash', |
| 27 | + }, |
| 28 | +}; |
| 29 | + |
| 30 | +function timeoutMs() { |
| 31 | + return ( |
| 32 | + Number(process.env.REPOLENS_MCP_TIMEOUT_MS) || |
| 33 | + Number(process.env.ANTHROPIC_TIMEOUT_MS) || |
| 34 | + DEFAULT_TIMEOUT_MS |
| 35 | + ); |
| 36 | +} |
| 37 | + |
| 38 | +export function pickModelProvider(env = process.env) { |
| 39 | + const forced = String(env.REPOLENS_MCP_PROVIDER || '') |
| 40 | + .toLowerCase() |
| 41 | + .trim(); |
| 42 | + if (forced) { |
| 43 | + const cfg = PROVIDERS[forced]; |
| 44 | + if (!cfg) throw new Error(`Unknown REPOLENS_MCP_PROVIDER "${forced}"`); |
| 45 | + if (!env[cfg.env]) throw new Error(`${cfg.env} is not set for REPOLENS_MCP_PROVIDER=${forced}`); |
| 46 | + return { id: forced, key: env[cfg.env], model: env[cfg.modelEnv] || cfg.defaultModel }; |
| 47 | + } |
| 48 | + for (const id of ['anthropic', 'openai', 'openrouter', 'google']) { |
| 49 | + const cfg = PROVIDERS[id]; |
| 50 | + if (env[cfg.env]) return { id, key: env[cfg.env], model: env[cfg.modelEnv] || cfg.defaultModel }; |
| 51 | + } |
| 52 | + throw new Error( |
| 53 | + 'No MCP model provider configured — set ANTHROPIC_API_KEY, OPENAI_API_KEY, OPENROUTER_API_KEY, or GOOGLE_API_KEY' |
| 54 | + ); |
| 55 | +} |
| 56 | + |
| 57 | +async function fetchWithTimeout(url, opts, label) { |
| 58 | + const ms = timeoutMs(); |
| 59 | + const controller = new AbortController(); |
| 60 | + const timer = setTimeout(() => controller.abort(), ms); |
| 61 | + try { |
| 62 | + return await fetch(url, { ...opts, signal: controller.signal }); |
| 63 | + } catch (err) { |
| 64 | + if (err && err.name === 'AbortError') throw new Error(`${label} request timed out after ${ms}ms`); |
| 65 | + throw err; |
| 66 | + } finally { |
| 67 | + clearTimeout(timer); |
| 68 | + } |
| 69 | +} |
| 70 | + |
| 71 | +function openAiBody(model, prompt) { |
| 72 | + return { model, max_tokens: 4096, messages: [{ role: 'user', content: prompt }] }; |
| 73 | +} |
| 74 | + |
| 75 | +function parseOpenAiText(json, label) { |
| 76 | + const text = json?.choices?.[0]?.message?.content; |
| 77 | + if (!text) throw new Error(`${label} returned an empty response`); |
| 78 | + return text; |
| 79 | +} |
| 80 | + |
| 81 | +async function callAnthropic({ key, model }, prompt) { |
| 82 | + const res = await fetchWithTimeout( |
| 83 | + 'https://api.anthropic.com/v1/messages', |
| 84 | + { |
| 85 | + method: 'POST', |
| 86 | + headers: { |
| 87 | + 'content-type': 'application/json', |
| 88 | + 'anthropic-version': '2023-06-01', |
| 89 | + 'x-api-key': key, |
| 90 | + }, |
| 91 | + body: JSON.stringify({ model, max_tokens: 4096, messages: [{ role: 'user', content: prompt }] }), |
| 92 | + }, |
| 93 | + 'Anthropic' |
| 94 | + ); |
| 95 | + if (!res.ok) throw new Error(`Anthropic API ${res.status}: ${(await res.text()).slice(0, 300)}`); |
| 96 | + const data = await res.json(); |
| 97 | + const text = (data.content || []) |
| 98 | + .map((b) => b.text || '') |
| 99 | + .join('') |
| 100 | + .trim(); |
| 101 | + if (!text) throw new Error('Anthropic returned an empty response'); |
| 102 | + return text; |
| 103 | +} |
| 104 | + |
| 105 | +async function callOpenAI({ key, model }, prompt) { |
| 106 | + const res = await fetchWithTimeout( |
| 107 | + 'https://api.openai.com/v1/chat/completions', |
| 108 | + { |
| 109 | + method: 'POST', |
| 110 | + headers: { 'content-type': 'application/json', Authorization: `Bearer ${key}` }, |
| 111 | + body: JSON.stringify(openAiBody(model, prompt)), |
| 112 | + }, |
| 113 | + 'OpenAI' |
| 114 | + ); |
| 115 | + if (!res.ok) throw new Error(`OpenAI API ${res.status}: ${(await res.text()).slice(0, 300)}`); |
| 116 | + return parseOpenAiText(await res.json(), 'OpenAI'); |
| 117 | +} |
| 118 | + |
| 119 | +async function callOpenRouter({ key, model }, prompt) { |
| 120 | + const res = await fetchWithTimeout( |
| 121 | + 'https://openrouter.ai/api/v1/chat/completions', |
| 122 | + { |
| 123 | + method: 'POST', |
| 124 | + headers: { |
| 125 | + 'content-type': 'application/json', |
| 126 | + Authorization: `Bearer ${key}`, |
| 127 | + 'HTTP-Referer': 'https://github.com/New1Direction/RepoLens', |
| 128 | + 'X-Title': 'RepoLens MCP', |
| 129 | + }, |
| 130 | + body: JSON.stringify(openAiBody(model, prompt)), |
| 131 | + }, |
| 132 | + 'OpenRouter' |
| 133 | + ); |
| 134 | + if (!res.ok) throw new Error(`OpenRouter API ${res.status}: ${(await res.text()).slice(0, 300)}`); |
| 135 | + return parseOpenAiText(await res.json(), 'OpenRouter'); |
| 136 | +} |
| 137 | + |
| 138 | +async function callGoogle({ key, model }, prompt) { |
| 139 | + const endpoint = `https://generativelanguage.googleapis.com/v1beta/models/${encodeURIComponent(model)}:generateContent?key=${encodeURIComponent(key)}`; |
| 140 | + const res = await fetchWithTimeout( |
| 141 | + endpoint, |
| 142 | + { |
| 143 | + method: 'POST', |
| 144 | + headers: { 'content-type': 'application/json' }, |
| 145 | + body: JSON.stringify({ contents: [{ role: 'user', parts: [{ text: prompt }] }] }), |
| 146 | + }, |
| 147 | + 'Google' |
| 148 | + ); |
| 149 | + if (!res.ok) throw new Error(`Google API ${res.status}: ${(await res.text()).slice(0, 300)}`); |
| 150 | + const data = await res.json(); |
| 151 | + const text = (data.candidates?.[0]?.content?.parts || []) |
| 152 | + .map((p) => p.text || '') |
| 153 | + .join('') |
| 154 | + .trim(); |
| 155 | + if (!text) throw new Error('Google returned an empty response'); |
| 156 | + return text; |
| 157 | +} |
| 158 | + |
| 159 | +export async function callModel(prompt) { |
| 160 | + const provider = pickModelProvider(); |
| 161 | + if (provider.id === 'anthropic') return callAnthropic(provider, prompt); |
| 162 | + if (provider.id === 'openai') return callOpenAI(provider, prompt); |
| 163 | + if (provider.id === 'openrouter') return callOpenRouter(provider, prompt); |
| 164 | + if (provider.id === 'google') return callGoogle(provider, prompt); |
| 165 | + throw new Error(`Unsupported MCP provider: ${provider.id}`); |
| 166 | +} |
0 commit comments