mcp-model-router
This server does not currently have a deployable release on Glama. Follow the repository's setup instructions to install and configure it for your MCP client, including any required credentials and local dependencies.
mcp-model-router
Summary: An MCP server that complements LiteLLM instead of replacing it. It (1) picks a model by task type from
config.yaml, (2) reads usage and budget from LiteLLM or OpenRouter, and (3) runs the same prompt set across several models and compares cost, latency and quality. Works over stdio or streamable HTTP; SQLite stores only call logs and eval results.
Technologies: TypeScript, Node.js 22/24, Model Context Protocol (stdio and streamable HTTP), SQLite, vitest. License: LICENSE.
Contents: Try it in a minute · Quick start from npm · Quick start from source · Try it without a key · Architecture · Installation · MCP tools · Measured comparison · Claude Desktop / Cursor · Proxmox LXC · Security · Known limitations
An MCP server that complements LiteLLM and does not replace it. LiteLLM and OpenRouter already handle per-agent keys and spending caps; this server does not rebuild them. It does three things:
Model selection by task type - reads the per-task-type models from
config.yaml(e.g.general,code,writing,orchestration) and calls them through an OpenAI-compatible/chat/completionsAPI. The base URL and key come from environment variables, and the API can be either a LiteLLM proxy or OpenRouter directly. There are no direct Anthropic calls. If the primary model fails, the configured fallback model is used.Usage and budget - reads them straight from the LiteLLM (
/user/info) or OpenRouter (/credits) API. There is no separate usage bookkeeping.Eval comparison - runs the same prompt set (a JSON file) across several models and reports cost, latency and response side by side, so that a cheaper model can be chosen based on measured quality. Quality is judged by a simple contains/matches check and an optional LLM judge.
SQLite is used only for call logs and eval results - not for usage or budget bookkeeping.
Try it in a minute
See the routing work end to end without an API key. The demo starts a local fake OpenAI-compatible provider on 127.0.0.1, launches the router as a real MCP server over stdio, connects to it with the MCP SDK client and sends one route_and_complete call per task type:
git clone https://github.com/tonyweckstrom1987/mcp-model-router.git
cd mcp-model-router
npm ci && npm run build
npm run exampleOutput:
Connected to mcp-model-router over stdio. Tools: route_and_complete, list_models, get_usage, run_eval
Routing (rules from examples/routing-demo/demo-config.yaml):
general demo/fast-cheap
[demo/fast-cheap] fake answer to: What is the capital of Finland?
code demo/coder
[demo/coder] fake answer to: Write a function that reverses a string.
writing demo/writer
[demo/writer] fake answer to: Summarise the README in one sentence.
orchestration demo/planner-unavailable -> demo/fast-cheap (primary failed, fallback used)
[demo/fast-cheap] fake answer to: Split 'ship v1.0' into three steps.
All answers came from a local fake provider: no API key, no cost.The routing rules are in examples/routing-demo/demo-config.yaml: each task type names a model and an optional fallback. The fake provider (fake-provider.mjs) answers HTTP 503 for the orchestration primary model, so the last line shows the fallback taking over. Edit the config and run npm run example again to see the routing change. npm test runs the same demo as an end-to-end test (test/example.e2e.test.ts), so CI catches it if the example breaks.
Related MCP server: ComputeGauge MCP
Quick start from npm
No clone needed. In an empty directory:
npm init -y
npm i mcp-model-router
cp node_modules/mcp-model-router/config.example.yaml config.yaml # edit as needed
CONFIG_PATH=./config.yaml npx mcp-model-routerThe server speaks MCP over stdio by default, so it waits for a client on stdin. Without a config file it exits with code 1 and a one-line message that names the path it looked for. Set MCP_TRANSPORT=http for streamable HTTP (see Quick start from source and Running). Calling a model needs LLM_API_KEY; list_models does not.
Check the server with mcp-doctor, no LLM key needed:
CONFIG_PATH=./config.yaml npx @tonyweckstrom/mcp-doctor --env CONFIG_PATH --strict -- node node_modules/mcp-model-router/dist/index.jsQuick start from source
A first route_and_complete call in HTTP mode (assuming LiteLLM is already
running at http://localhost:4000 and has at least a model configured for the
general task):
npm install && npm run build
cp config.example.yaml config.yaml # edit as needed
read -s -p "LLM_API_KEY: " LLM_API_KEY; echo
export LLM_API_KEY # or put it in an environment file; do not type the key on the command line
export MCP_AUTH_TOKEN="$(openssl rand -hex 32)" # required in HTTP mode, at least 32 characters
LLM_BASE_URL=http://localhost:4000 MCP_TRANSPORT=http MCP_HTTP_PORT=3100 npm start &
curl -s -X POST http://127.0.0.1:3100/mcp \
-H "Authorization: Bearer $MCP_AUTH_TOKEN" \
-H 'Content-Type: application/json' -H 'Accept: application/json, text/event-stream' \
-d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"route_and_complete","arguments":{"taskType":"general","prompt":"Sano hei suomeksi"}}}'The last command (curl) sends a tools/call request to the server's /mcp
endpoint and prints the response (as a streamable HTTP event stream). For more
on environment variables, the stdio transport and the GET /healthz health
check, see Installation and Running.
Try it without an LLM key
list_models works without LiteLLM or an API key: when the /models fetch fails, it shows the models from config.yaml together with a warning. In stdio mode the server reads JSON-RPC messages from stdin (sleep 2 keeps the pipe open until the response has arrived):
The command uses dist/index.js, so first run npm install && npm run build (see Installation).
cp config.example.yaml config.yaml
(printf '%s\n' \
'{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"kokeilu","version":"0"}}}' \
'{"jsonrpc":"2.0","method":"notifications/initialized"}' \
'{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"list_models","arguments":{}}}'; sleep 2) | node dist/index.jsThe text part of the last line's response with config.example.yaml, when nothing answers at LLM_BASE_URL:
Models per task type (config.yaml):
- general: openrouter/deepseek/deepseek-v4.1-flash (fallback: openrouter/qwen/qwen3-flash)
- code: openrouter/qwen/qwen3-coder (fallback: openrouter/deepseek/deepseek-v4.1-flash)
- writing: openrouter/anthropic/claude-3.5-sonnet (fallback: openrouter/openai/gpt-4o-mini)
- orchestration: openrouter/openai/gpt-4o (fallback: openrouter/anthropic/claude-3.5-sonnet)
WARNING: model list fetch failed (TypeError). Showing only the models from config.yaml; they may differ from what the server really offers.(TypeError is the error type of the failed connection; only the type or the HTTP status is shown, never the response body or the address.)
When the server's /models endpoint answers, the same call lists the models the server really offers after the task types, and marks task-type models that are missing from the server's list with [WARNING: ...]:
Available models (litellm /models, 3):
- extra-malli
- openrouter/deepseek/deepseek-v4.1-flash
- openrouter/qwen/qwen3-coder(Output from a local stub server that returns three model ids; the 3 listed models are the stub's.)
Architecture
┌─────────────────────────┐
AgentScope agent ────▶│ mcp-model-router (MCP) │
(or other MCP client) │ │
│ route_and_complete │
│ list_models │
│ get_usage │──▶ LiteLLM proxy / OpenRouter
│ run_eval │ (OpenAI-compatible API)
└───────────┬──────────────┘
│
▼
SQLite (call_log, eval_run, eval_result, token_budget)Transports: stdio (for local use, e.g. Claude Desktop/Cursor) and streamable HTTP (so that other containers can reach the server over the Tailscale network). HTTP mode is stateless (
sessionIdGenerator: undefined): every request gets its own transport instance, so several agents can call the server at the same time./mcprequires a Bearer token (MCP_AUTH_TOKEN), and network-level restriction (Tailscale ACLs) comes on top of that - see Security.Configuration:
config.yaml(with environment variable references, no secrets in the file) + the actual values from environment variables.Cost caps are hard-coded (
src/lib/limits.ts):maxTokensis an optional parameter, but its upper limit is 4096 and a daily token budget caps total consumption - see Security.
Installation
Requires Node.js 22.12 or newer (22 or 24).
npm install
cp config.example.yaml config.yaml # edit as needed
npm run buildTroubleshooting:
npm ci --ignore-scripts(orignore-scripts=truein.npmrc) skips building the nativebetter-sqlite3module, and the server and tests then fail withCould not locate the bindings file. Fix it withnpm rebuild better-sqlite3(needs a C/C++ toolchain if no prebuilt binary matches your Node version).
Environment variables (example values, no secrets in the repository):
Variable | Description | Default |
| Base URL of the OpenAI-compatible API |
|
| Key for the API above | (empty) |
|
|
|
| Base URL of the usage API (usually the same as |
|
| Key for the usage API | (empty) |
| Path to the |
|
| Path to the SQLite file |
|
|
|
|
| Bind address of the HTTP transport |
|
| Port of the HTTP transport (default changed to 3100 because 3000 is often taken, e.g. by Open WebUI) |
|
| Required in HTTP mode: Bearer token for the | (not set) |
| The only directory | (not set) |
| Comma-separated list of allowed Host headers (DNS rebinding protection) | (not set) |
Running
# stdio (e.g. Claude Desktop / Cursor)
npm start
# streamable HTTP (default: this machine only; for other Tailscale containers set MCP_HTTP_HOST to your own Tailscale address, not 0.0.0.0)
# MCP_AUTH_TOKEN is required (at least 32 characters), e.g. openssl rand -hex 32
MCP_TRANSPORT=http MCP_HTTP_HOST=127.0.0.1 MCP_HTTP_PORT=3100 MCP_AUTH_TOKEN=... npm startIn HTTP mode the server answers at http://<host>:<port>/mcp and also
provides a GET /healthz health check. In stdio mode the corresponding
tools/call request is fed to the server from stdin as a single JSON-RPC
message (see Quick start from source for the HTTP
version).
config.yaml example
See the full example in config.example.yaml.
In short:
provider:
baseUrl: ${LLM_BASE_URL:-http://localhost:4000}
apiKey: ${LLM_API_KEY:-}
kind: ${LLM_PROVIDER_KIND:-litellm} # litellm | openrouter
tasks:
general:
model: openrouter/deepseek/deepseek-v4.1-flash
fallbackModel: openrouter/qwen/qwen3-flash
code:
model: openrouter/qwen/qwen3-coder
fallbackModel: openrouter/deepseek/deepseek-v4.1-flash
orchestration:
model: openrouter/openai/gpt-4o
timeoutMs: 120000 # overrides provider.timeoutMs for this task type
usage:
provider: litellm # litellm | openrouter
baseUrl: ${USAGE_BASE_URL:-http://localhost:4000}
apiKey: ${USAGE_API_KEY:-}
# timeoutMs: 15000 # timeout of the usage API (default 15 s)
eval:
judge:
enabled: false
model: openrouter/openai/gpt-4o-mini # a different model than the models under evaluation, see below
concurrency: 4 # how many (model, prompt) calls run at the same time
# run_eval accepts only the models of the tasks section by default; add other models to compare here:
# allowedModels: [openrouter/anthropic/claude-haiku-5-5]
pricing:
openrouter/deepseek/deepseek-v4.1-flash:
inputPerMillionUsd: 0.2
outputPerMillionUsd: 0.8
database:
path: ${DB_PATH:-./data/mcp-model-router.sqlite}Model identifiers: LiteLLM vs. direct OpenRouter
Model identifiers in the tasks block are always written in the form LiteLLM
uses, e.g. openrouter/deepseek/deepseek-v4.1-flash. The openrouter/
prefix is LiteLLM's own way of saying that the request is routed through
OpenRouter - it is not part of OpenRouter's own model identifier.
provider.kind: litellm(default,LLM_BASE_URLpoints to a LiteLLM proxy): the identifier is sent as it is, prefix included.provider.kind: openrouter(LLM_BASE_URLpoints directly tohttps://openrouter.ai/api/v1): the router strips theopenrouter/prefix automatically before the API call (seesrc/lib/modelId.ts), so the sameconfig.yamlworks unchanged with both - onlyLLM_BASE_URL/LLM_PROVIDER_KINDchange.
Per-task-type timeout (timeoutMs)
tasks.<taskType>.timeoutMs is optional and overrides provider.timeoutMs
for that task type only (it affects route_and_complete calls, for both the
primary model and the fallback model). By default all task types use
provider.timeoutMs (default 60000 ms).
This is especially useful for reasoning models, which can take considerably longer on complex decomposition or orchestration tasks than on simple general-knowledge or short-code tasks - see Example: measured comparison, where the "pilkkominen" (decomposition) task type caused timeouts with the 60 s default timeout:
tasks:
orchestration:
model: openrouter/deepseek/deepseek-v4.1-flash
timeoutMs: 120000 # 2 min, instead of the default 60000 ms (1 min)MCP tools
Tool | Description |
| Picks a model by the |
| Lists the task types in |
| Returns the state of usage and budget from LiteLLM/OpenRouter. Optional |
| Runs a JSON prompt set across several models and reports cost/latency/quality. |
get_usage and includeRaw
get_usage returns source, spend, budget and remaining as text, and the same values as summary in structuredContent. With includeRaw: true it appends a second text block, raw response:, with JSON from the provider:
Provider ( |
|
|
|
| The unmodified |
Breaking change (unreleased): before, the LiteLLM raw was the unmodified /user/info response. Code that read raw.keys, raw.teams or raw.user_id now finds nothing; read summary instead. Older LiteLLM versions that return spend and max_budget at the top level are handled: those values are taken from the top level, and a field missing from user_info is filled in from there. See the CHANGELOG.
For the format of the eval prompt file, see the example
examples/eval-prompts.example.json:
[
{ "id": "p1", "prompt": "Mikä on Suomen pääkaupunki?", "expectedContains": "Helsinki" }
]A larger example set of 15-20 Finnish-language prompts for four task types
(general knowledge, coding, writing/summarising, task decomposition) is in
examples/eval-prompts.fi.json.
Checking prompt files (evalkit): npm run eval:validate checks the example files with the
evalkit tool without network calls or costs
(format, duplicate ids, invalid expressions). CI runs it on every push, so a broken
prompt file is caught before run_eval meets it. evalkit reads this array format
(expectedContains, category) as it is.
Recorded responses (llm-cassette): test/cassettes/fi.json contains the responses of a real model (deepseek-flash)
to 20 prompts, and test/cassettes/fi.baseline.json holds the results computed from them. npm run eval:replay
replays the responses without a network or a key and compares them to the baseline; CI runs it, so a
regression in the evaluation logic (e.g. a change in the checks) fails CI. For a new recording (needs your own LiteLLM key, costs a few cents):
set EVALKIT_BASE_URL, EVALKIT_MODELS and LLM_API_KEY, run npm run eval:record and then
npm run eval:anonymize, which replaces the real address with a placeholder and refuses if the cassette contains ts.net
or a string that looks like a key.
Running evals (run_eval)
run_eval is an MCP tool, not a separate CLI command - it is called the same
way as the other tools (tools/call, see Quick start from
source). An example in HTTP mode, with two models
and the eval-prompts.fi.json set:
Models are restricted: run_eval accepts only the models in the tasks section of config.yaml (model,
fallbackModel) and the list eval.allowedModels. Any other model is rejected before a single call is made, so that
the token holder cannot steer calls to the most expensive model of the proxy.
# server started with the environment variable EVAL_DIR=/path/mcp-model-router/examples
curl -s -X POST http://127.0.0.1:3100/mcp \
-H "Authorization: Bearer $MCP_AUTH_TOKEN" \
-H 'Content-Type: application/json' -H 'Accept: application/json, text/event-stream' \
-d '{
"jsonrpc":"2.0","id":1,"method":"tools/call",
"params":{
"name":"run_eval",
"arguments":{
"promptSetPath":"eval-prompts.fi.json",
"models":["openrouter/deepseek/deepseek-v4.1-flash","openrouter/qwen/qwen3-flash"],
"judge": false
}
}
}'promptSetPathis resolved relative to theEVAL_DIRdirectory (see Security); a path outside the directory is rejected.The
modelslist uses the same LiteLLMmodel_namealiases as thetasksblock ofconfig.yaml(see Known limitations). Each model must be allowed: either it appears in thetaskssection (modelorfallbackModel, of anytaskType) or it is listed ineval.allowedModels. A model outside both is rejected before any call is made. To compare a model that no task uses, add it toeval.allowedModels. The same model may not appear twice in the list.The
judgeparameter (optional) overrides theeval.judge.enabledsetting ofconfig.yamlfor a single run. When the judge is on, every response is additionally sent toeval.judge.modelto be rated on a scale of 1-5 (usingeval.judge.systemPromptfromconfig.yamlor the default) - this makes as many extra model calls as there are prompt cases, so it costs more and takes longer.If a
dbinstance is in use (which is always the case when the server is started withdist/index.js- seesrc/index.ts), every run and result row is stored in SQLite (theeval_run/eval_resulttables) in the file thatDB_PATHpoints to, so runs can also be compared afterwards directly from the database.An eval can make a lot of model calls: e.g. 2 models × 20 prompts = 40 (model, prompt) pairs, and each call can take several seconds (or as long as
provider.timeoutMs/the task type's owntimeoutMsif the model hangs) - see Example: measured comparison.judge: truenearly doubles the run time, because every response is also rated separately with an extra model call.
Parallel execution (eval.concurrency)
run_eval runs (model, prompt) pairs in parallel, at most as many at a time
as the eval.concurrency setting of config.yaml allows (default 4, minimum
1). The implementation is a simple bounded work queue
(mapWithConcurrency, see src/eval/runEval.ts) with no new dependencies:
a fixed number of "workers" take the next unprocessed task from the queue one
at a time until the queue is empty.
The calls are in practice all I/O wait (a network response from the model),
not CPU work, so parallel execution shortens the total run time directly in
proportion to the concurrency value - e.g. 2 models × 20 prompts × judge on
(40 response calls + 40 judge calls = 80 calls) used to take about 12 minutes
when run sequentially; with concurrency: 4 the same calls go four at a time,
which shortens the run time considerably with the same prompt set and model
selection.
Notes:
Result order is preserved regardless of the order in which individual calls finish: the
casesarray is always in the same order as in a sequential run (model as the outer loop, prompt as the inner loop, in the order ofinput.models/the prompt file).Error handling is still per call: a timeout or other error in one call (including a judge call error) does not interrupt the other parallel or queued calls - it shows only in the
errorfield of that case, just as in a sequential run.Why the default is 4, not more: too much parallelism can overload the rate limits of the LiteLLM proxy or OpenRouter, so that some calls start to fail with 429 errors instead of the eval actually getting faster. Raise the value carefully according to the limits of your own proxy/API key, or lower it to
1if you want a fully sequential run (the simplest in terms of deterministic timing), e.g. for troubleshooting.
Reading the results (EvalReport, see src/eval/runEval.ts):
cases: one row per (model, prompt) - containslatencyMs, theresponsetext,passed(true/false/nullif the prompt has noexpectedContainsfield),judgeScore(1-5 ornull),priceUsd(nullif the model has no price entry in theeval.pricingblock ofconfig.yaml) anderror(an error message ornull).perModel: a summary per model -avgLatencyMs,passRate(the share ofexpectedContainspasses, 0-1, with failed calls excluded,nullif none of the prompts had anexpectedContainsfield),avgJudgeScore,avgPriceUsdanderrorCount/caseCount. This is the fastest way to compare models: a loweravgPriceUsdandavgLatencyMswhilepassRate/avgJudgeScorestays high enough tells you which model to pick for thetasksblock ofconfig.yaml.perTaskType: the same summary grouped by (model, task type) pairs. The task type is derived from the prefix of the promptidby dropping the trailing-<number>, e.g."yleinen-01"→"yleinen","pilkkominen-05"→"pilkkominen"(seetaskTypeFromPromptIdinsrc/eval/runEval.ts) - this has nothing to do with thetaskskeys ofconfig.yaml, it is just a naming convention in the prompt file. Each row contains:caseCount,errorCount- how many cases and how many of them were errors.passedCount/expectedCount- how many passed the keyword check among the cases whereexpectedContainswas given (= "passed/n").passRateExcludingErrors- the pass rate computed only over successful calls (failed calls are left out of both the numerator and the denominator). It tells the quality of the response when the model did respond at all.passRateIncludingErrors- the pass rate computed so that errors (e.g. a timeout) count as not passed (included in the denominator). It tells the overall reliability of the model for the task type.avgLatencyMs,avgPriceUsd- as inperModel, but limited to this task type.
The text response of the MCP tool summarises both the
perModeland theperTaskTyperows in a human-readable form; the wholeEvalReport(includingcases) is available programmatically in thestructuredContentfield.
Judge mode (eval.judge) - a more reliable quality metric
The expectedContains keyword check is coarse: it rejects even a good
response if it does not contain exactly the expected word (see Example:
measured comparison - especially on
writing/summarising tasks it gives a misleadingly low pass rate). The LLM
judge rates the quality of the response on a scale of 1-5 regardless of
whether the response hits the expected wording exactly, and is therefore a
more reliable metric especially for open-ended (writing, summarising,
decomposition) tasks.
Enable the judge either permanently in config.yaml or for a single run:
eval:
judge:
enabled: true
model: openrouter/openai/gpt-4o-mini # the model acting as judge
systemPrompt: "You are a strict evaluator. Rate the quality of the answer on a scale of 1-5 and reply with the number only."or pass "judge": true in the arguments field of the run_eval call (see
the example above) - this overrides the config.yaml setting for that run
only. As a result EvalCaseResult.judgeScore/EvalModelSummary.avgJudgeScore
are filled in instead of null. Note the effect on cost: the judge makes one
extra model call per prompt case, so it both costs and takes roughly twice as
much as the keyword check.
The max_tokens of a judge call is 64 by default, because the response is a
single number. If the judge model uses reasoning tokens, raise the value with
the optional eval.judge.maxTokens setting (1-4096). If no judge score is
obtained (the call fails or the response has no unambiguous score from 1 to
5), the score is left as null, and the reason shows in the judgeError field
of the case and in the per-model judgeErrorCount figure.
Choose eval.judge.model to be a different model than the models under
evaluation. A model typically favours its own response style (e.g. its own
way of structuring a response or phrasing sentences), so the same model as a
judge would give higher scores to responses resembling its own style - this
skews the comparison in favour of that very model. So use as the judge a model
that is not on the models list of any run_eval call.
Example: measured comparison
Below are the results of one real run_eval run (examples/eval-prompts.fi.json,
20 prompts, judge off) that compared two models run through OpenRouter behind
a LiteLLM proxy: deepseek-v4.1-flash vs. qwen3-coder. Numbers use English
formatting (a comma as the thousands separator and a point as the decimal
separator).
Overall:
Model | Pass rate | Avg. latency | Avg. price/call |
deepseek-v4.1-flash | 83 % (15/18, 2 timeouts) | 14,802 ms | 0.000744 USD |
qwen3-coder | 85 % (17/20) | 9,887 ms | 0.000466 USD |
By task type (passed/n, avg. latency, avg. price in USD/call):
Task type | deepseek-v4.1-flash | qwen3-coder |
yleinen (general) | 5/5, 2,190 ms, 0.000119 | 5/5, 5,600 ms, 0.000159 |
koodaus (coding) | 5/5, 4,025 ms, 0.000278 | 5/5, 3,742 ms, 0.000188 |
kirjoitus (writing) | 3/5, 7,841 ms, 0.000416 | 3/5, 1,567 ms, 0.000121 |
pilkkominen (decomposition) | 2/5 (+2 timeouts), 45,151 ms, 0.001867 | 4/5, 28,640 ms, 0.001395 |
Interpretation: the overall pass rate is close for both models, but
qwen3-coder is both faster and cheaper in the coding, writing and
decomposition task types of this run. In the general task type it was both
slower (5,600 ms vs. 2,190 ms) and more expensive (0.000159 vs. 0.000119
USD). It also got through the decomposition tasks without timeouts. The two timeouts of
deepseek-v4.1-flash both hit decomposition tasks (with the 60 s default
timeout) - see
Per-task-type timeout, which exists for
exactly this.
Limitations - read these numbers with care:
Small sample: only 5 prompts per task type (20 in total). A single case changes the percentage by 20 percentage points; the results should not be generalised directly to other prompts or use cases.
The keyword check rates writing tasks poorly:
expectedContainsrejects an otherwise good response if it does not contain exactly the expected word - the 3/5 figures in the writing/summarising row for both models probably underestimate the real quality. See Judge mode for a more reliable alternative.Deepseek's timeouts raised its average latency and price in the decomposition column significantly (60 s per timeout is counted in the latency) - without them the average latency would have been lower.
The results are from a single run (run
be440639-9aa7-4330-8c66-8cb2ed27b9ef) at a particular time and depend on the model versions of that moment and on OpenRouter's load/availability - they are not a lasting benchmark result, but an example of how to read the result report ofrun_eval. Run your own eval with your own prompts before production decisions.
Claude Desktop / Cursor configuration
claude_desktop_config.json (or the corresponding Cursor MCP settings file),
with the stdio transport:
{
"mcpServers": {
"model-router": {
"command": "node",
"args": ["/polku/mcp-model-router/dist/index.js"],
"env": {
"CONFIG_PATH": "/polku/mcp-model-router/config.yaml",
"LLM_BASE_URL": "http://localhost:4000",
"LLM_API_KEY": "sk-...",
"DB_PATH": "/polku/mcp-model-router/data/mcp-model-router.sqlite"
}
}
}
}If the server is already running in HTTP mode (e.g. in its own LXC container),
many MCP clients also support a direct streamable HTTP connection to
http://<tailscale-host>:3100/mcp without a command launch - see the
documentation of your client.
Running in a Proxmox LXC
No Docker - the server runs directly as a Node process under a systemd unit.
Create (or use) a Debian/Ubuntu-based LXC container and install Node.js 22 or 24.
Clone the repository into
/opt/mcp-model-routerand run:cd /opt/mcp-model-router npm ci npm run build cp config.example.yaml config.yaml # editCreate a dedicated user and data directory for the service:
useradd --system --home /opt/mcp-model-router --shell /usr/sbin/nologin mcp-model-router mkdir -p /opt/mcp-model-router/data chown -R mcp-model-router:mcp-model-router /opt/mcp-model-routerCopy the environment file and fill in the values (not into version control):
cp systemd/mcp-model-router.env.example /opt/mcp-model-router/mcp-model-router.env chmod 600 /opt/mcp-model-router/mcp-model-router.envInstall the systemd unit; see the ready-made example
systemd/mcp-model-router.service:cp systemd/mcp-model-router.service /etc/systemd/system/ systemctl daemon-reload systemctl enable --now mcp-model-router systemctl status mcp-model-router
The unit listens on the MCP_HTTP_HOST address (set the container's
Tailscale address, tailscale ip -4, in the env file), so that other LXC
containers can reach the server over the Tailscale network. The env file must
contain MCP_AUTH_TOKEN (at least 32 characters), otherwise the server does
not start, and clients must send it in the Bearer header. Also set
EVAL_DIR if you use run_eval. Access is additionally restricted with
Tailscale ACLs.
Security
Principle: the limits are in the code and they fail closed (in an error
state, the action is denied). None of the limits below can be loosened with an
environment variable, with config.yaml or with a tool parameter.
Bearer authentication (MCP_AUTH_TOKEN). In HTTP mode /mcp (POST, GET,
DELETE) requires the header Authorization: Bearer <token>.
The server does not start in HTTP mode if
MCP_AUTH_TOKENis missing or shorter than 32 characters. Create a token with e.g.openssl rand -hex 32.A missing header, a wrong scheme and a wrong token all give exactly the same 401 response, which does not reveal the reason. The comparison is constant-time (
crypto.timingSafeEqualon SHA-256 digests, so inputs of different lengths do not leak information).The token is not written to logs or error messages. Keep it in an environment file (
chmod 600), not in version control.The default bind is
127.0.0.1./healthzis open and returns nothing but{"status":"ok"}.The stdio mode does not use a token (the process is local).
The token does not replace network-level restriction: keep using Tailscale ACLs and do not listen on
0.0.0.0.The Bearer token travels unencrypted over HTTP. Use HTTP mode only over Tailscale (WireGuard) or localhost, never over an open network.
Authentication runs before the JSON body is parsed, so the body of an unauthenticated request is not read. A parse error in an authenticated request returns the JSON-RPC error
-32700 Parse error. The DNS rebinding protection (Host header check) is applied before that.Startup warning: if
MCP_HTTP_HOSTis not a localhost address (127.0.0.1,localhost,::1) andMCP_ALLOWED_HOSTSis not set, the server printsWarning: listening on <host> without DNS rebinding protection; set allowedHosts (MCP_ALLOWED_HOSTS).to stderr. This covers any other address too, such as a Tailscale IP, not only0.0.0.0and::. The server still starts: setMCP_ALLOWED_HOSTSto the Host values clients use (for example100.x.y.z:3100) to enable the check.
run_eval file paths (EVAL_DIR). run_eval reads prompt files from a
single directory only.
If
EVAL_DIRis not set,run_evalrefuses all paths.The path is resolved with
realpathand compared to the directory:../paths, absolute paths outside the directory and symlinks that lead out are rejected. Relative paths are interpreted relative toEVAL_DIR.Only
.jsonextensions (case-insensitive), checked afterrealpath.The rejection message is always the same and does not contain the path.
Cost caps (constants in src/lib/limits.ts,
checked in callChatCompletion, so they cover route_and_complete,
run_eval and the judge):
Limit | Value | Behaviour |
| 4096 | A larger requested |
Model calls per | 200 | Counted as models × prompts (× 2 if the judge is on). Exceeding it is rejected before the first call. |
Daily budget | 1,000,000 tokens / day | A day is defined in |
The daily budget works on a reservation principle: before every call, the
input estimate + max_tokens is reserved from the SQLite token_budget table
in a BEGIN IMMEDIATE transaction (the check and the reservation are
indivisible, so parallel calls cannot bypass the limit). After the call the
reservation is corrected to the usage value of the response. If usage is
missing, the reservation stays in effect. A failed and an empty response
consume budget. Exceeding the budget does not trigger the fallback model.
Changing the limit requires a code change.
Empty responses. An empty, whitespace-only or missing response is the
error vastaus_tyhja, not a success. In run_eval it is a failed case
(passed: false, error starts with vastaus_tyhja) and is counted in the
denominator of the pass rate.
Development
npm run dev # tsx, stdio transport straight from the source
npm run typecheck # tsc --noEmit
npm test # vitest, HTTP calls mocked with undici
python -m unittest discover # tests for tools/automerge.py (stdlib only)The Python tools (tools/) support Python 3.10-3.13; CI runs the tests on all four.
CI also runs mcp-doctor v0.5.0, pinned by commit in .github/workflows/ci.yml (MCP handshake, tool schemas and an offline smoke run test/mcp-doctor/smoke.json). Locally:
npm run build
CONFIG_PATH=$PWD/config.example.yaml npx @tonyweckstrom/mcp-doctor --env CONFIG_PATH --strict --smoke test/mcp-doctor/smoke.json -- node dist/index.jsKnown limitations
HTTP mode authentication is a single shared Bearer token (no per-user or per-agent credentials, no token rotation at run time), and the server does not encrypt traffic itself (HTTP does not encrypt the token), so traffic may travel only through
127.0.0.1or Tailscale.The daily budget is token-based and covers only calls made through this server; it does not know about consumption by other LiteLLM/OpenRouter clients (
get_usageshows it).The input token count is an estimate (character count / 3); the reservation is corrected to the actual
usagevalue only after the call.A failed or empty model call is not refunded: the reservation made before the call (input estimate +
max_tokens) stays in the daily budget, and so does the reservation of a successful call whose response has nousagefield.The cost limits (1,000,000 tokens per day,
max_tokens4096, 200 calls perrun_eval, theEurope/Helsinkiday boundary) are constants insrc/lib/limits.ts. They cannot be changed with configuration or an environment variable, only by editing the code and rebuilding.list_modelsfetches the available models from the server's/modelsendpoint (unreleased, see the CHANGELOG). The result is cached (provider.modelsCacheTtlMs, default 60 s) and the request times out afterprovider.modelsTimeoutMs(default 10 s), so a call can wait up to that long. If the fetch fails, the tool shows only the models fromconfig.yamland reports the error (type and HTTP status only); the shown models may then differ from the server's real list.The eval price estimate is based on the
eval.pricingprice list inconfig.yaml, not on automatic price lookup from OpenRouter.get_usagerequires that LiteLLM has been started with a database (Postgres) and thatUSAGE_API_KEYis LiteLLM's master key (LITELLM_MASTER_KEY), because/user/infois an admin API. Without a database LiteLLM returns"Database not connected"(HTTP 500), andget_usagepasses this error on to the caller as it is. OpenRouter-only use (usage.provider: openrouter) does not require a database.The model identifiers of the
tasksblock and ofrun_evalare LiteLLMmodel_namealiases (names defined in the LiteLLM configuration/proxy model list), not directly the model identifiers of OpenRouter or another backend. See Model identifiers: LiteLLM vs. direct OpenRouter.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
Loading tool schema changelog…
This server cannot be deployed
Maintenance
Related MCP Connectors
AI model routing on your own vendor keys: pick the best model per prompt, or route and run it.
AI routing, memory, guardrails, and governance. Routes across Claude, GPT, Gemini.
Agent FinOps Spend Guard, Deterministic Budget Passport, LLM Token Cost Router & VIP Discounts.
Enterprise AI Control Plane: governance, guardrails, spend tracking, compliance & smart routing.
Related MCP Servers
- AlicenseAqualityDmaintenanceEnables AI agents to connect to and chat with multiple LLM models (OpenAI, OpenRouter, custom endpoints) with conversation history management and model switching capabilities.316 npm2MIT

ComputeGauge MCPofficial
AlicenseNot gradedqualityDmaintenanceProvides cost intelligence and a reputation scoring system to help AI agents optimize spending through smart model selection and local-to-cloud routing. It enables real-time cost tracking and rewards agents for making efficient, high-credibility decisions across various LLM providers.Apache 2.0- AlicenseNot gradedqualityDmaintenanceCompare AI inference pricing across 9 providers in real time. Routing recommendations, spend tracking, and budget alerts for AI agents.MIT
- AlicenseBqualityDmaintenanceRoute prompts intelligently across Claude, Gemini, and GPT-4o, automatically picking the best model for every task while minimizing token cost.557 npmMIT