Hermes 39f3daaf01 mcp: junction wird selbst ein MCP-Server für alle angebundenen Server
Ein Agent verbindet sich einmal mit /mcp und sieht die Werkzeuge aller
eingetragenen MCP-Server, statt jeden einzeln zu abonnieren — dieselbe Rolle
wie der MCP-Gateway von LiteLLM.

    mcp tasksd url http://127.0.0.1:8781/mcp
    mcp skilld url http://127.0.0.1:8790/mcp header "Authorization: Bearer ..."

tools/list bündelt und macht die Namen eindeutig (tasksd__task_create),
tools/call trennt das Präfix ab und reicht auf, Beschreibung und Schema
bleiben unveraendert. initialize, ping, Meldungen ohne id (202) und die
Fehlerfaelle -32600/-32601/-32602 sind abgedeckt, die Werkzeugliste wird
mcp_cache_ttl Sekunden gehalten.

Drei Fehler, die der Test aufgedeckt hat und die alle drei still gewesen waeren:
  * 8 MB Puffer auf dem Stack — junction startet Verbindungs-Threads mit
    kleinem Stack, der Prozess starb mit SIGSEGV vor der ersten Zeile.
  * Von Hand gezaehlte Laengen fuer j_buf_append ergaben {"tools"[]}, also eine
    Antwort, die kein Parser mehr liest. Jetzt strlen, ueberall.
  * write() und read() ohne Zeitlimit: ein Server, der die Verbindung annimmt
    und dann schweigt, hielt die Anfrage fest. Jetzt poll plus SO_SNDTIMEO.

tests/mcp.py faehrt zwei erfundene MCP-Server und prueft sechs Faelle; in
tests/run.sh eingehaengt, make test bleibt gruen. 8157 aus der Portliste
entfernt — der Port gehoert dem Hermes-Gateway und wird von keinem Test benutzt.
2026-11-06 18:40:47 +00:00

junction

A policy router for OpenAI-compatible model endpoints. C99 + POSIX, plus OpenSSL when built with TLS. No branding in the code: the only name in the sources is junction (even the log prefix is a config keyword), so a product name can be layered on later without touching logic.

junction sits in front of N model servers and decides per request which one serves it — and what to do when none of them wants to.

What it does

  • Ordered rules, like a firewall. req ... pass ... / block, first match wins. Match on model glob, path glob and required context.

  • Shell pre-hooks per endpoint. A hook that exits non-zero means "not available yet" — retried with backoff for a bounded time, optionally after a wake command.

  • Unreachable means offline, immediately. A connect failure is not a retry case.

  • Honest timeouts. Two per endpoint: idle ("nothing for N seconds", logged as still_working) and total. A thinking model never looks like a hang.

  • Context-aware, without guessing. need reads max_tokens / max_completion_tokens from the request and nothing else — no character counting, no assumed default. An endpoint whose context is smaller than a declared budget is skipped; a request that declares nothing is passed through unsized.

  • Failover with cooldown, and a 503 that names why each endpoint was skipped.

  • Concurrency with a queue. One thread per connection, max_inflight upstream requests at a time, the rest wait in line instead of being refused. A waiting streaming caller is told why it waits — as SSE comments (: junction: waiting for a free slot (2 ahead of you)), which every conformant parser ignores and a human watching curl sees. The same heartbeat keeps a thinking model's stream alive — every 10 s of upstream silence produces : junction: model is still working (12s), so a proxy with a 60 s read timeout does not kill a stream that is perfectly alive. As soon as real data arrives the comments stop; nothing is buffered, nothing is rewritten. A non-streaming caller gets nothing injected at all and keeps its real status code.

    This is bounded, not endless: queue_timeout caps the wait for a slot, timeout caps the upstream request, and when either expires a streamer receives an error event plus data: [DONE]. If the client vanishes, the next comment write fails and the router stops waiting for a model nobody is listening to.

  • TLS both ways. https:// upstreams (SNI, optional chain + hostname verification, custom CA) and an optional TLS listener — no stunnel needed.

  • Chunked transfer coding. Chunked request bodies are decoded; chunked responses are relayed byte for byte, so streaming (text/event-stream) survives untouched.

  • Response cache. Memory-only LRU keyed on method + path + model + body, honouring Cache-Control: no-store/private, bypassed by the client's no-cache, flushed with one call. Streams are never cached.

  • Header passthrough. Client headers are forwarded (hop-by-hop removed), static headers can be added per endpoint, and X-Forwarded-For/Proto are appended. Every response carries X-Junction-Endpoint, X-Junction-Ms, X-Junction-Cache.

A worked, annotated configuration for a mixed local/cloud setup is in examples/olivia.conf; config.example is the same grammar, reduced to the bones.

Build / run

make                      # -> ./junction (TLS auto-detected via openssl headers)
make J_WITH_TLS=0         # dependency-free build: http:// upstreams only
make test                 # stub endpoints, no network, no models (~40 s)

sudo make install         # /usr/local/bin + /usr/local/share/junction
./junction --config junction.conf [--port 8090]
curl -s localhost:8090/status

Configuration — pf.conf style

Keyword, arguments, braces. # comments, double quotes group words, unknown keywords are a hard error with a line number. Full example: config.example.

# listen 0.0.0.0:8443 tls /etc/junction/tls/cert.pem /etc/junction/tls/key.pem
listen 0.0.0.0:8090
chars_per_token 4
default_max_tokens 4096
connect_timeout_ms 1500
offline_hold_s 20
cache_ttl 300
cache_entries 128
cache_bytes 33554432

endpoint peer1 {
    base http://192.0.2.10:8081/v1
    kind remote
    context 64000
    priority 20
    timeout 600
    idle_timeout 60
    cooldown 120
    hook /usr/local/share/junction/hooks/check-http.sh
}

endpoint workstation {
    base http://192.0.2.20:8080/v1
    context 128000
    timeout 1800
    idle_timeout 30
    hook_retry 180
    hook_backoff 5
    wake /usr/local/share/junction/hooks/wake-wol.sh
    hook /usr/local/share/junction/hooks/check-http.sh
    header "X-Box: workstation"
}

endpoint cloud {
    base https://api.example.com/v1
    context 200000
    timeout 900
    idle_timeout 120
    cache off
    tls_verify on
    api_key_env EXAMPLE_API_KEY
}

# rules — first match wins
req need >64000 pass workstation, cloud
req for "*coder*" retry 300 pass workstation as "Qwen3.8-Flash-Next-GSQ-RCO-IQ1_M"
req path "/v1/models" check none pass peer1
req for "blocked-*" block
req for "*" pass peer1, cloud

Rule syntax

req [for <model-glob>] [path <glob>] [need >N | <N | N]
    [check hooks|none] [retry <seconds>]
    ( pass <endpoint>[,<endpoint>...] [as <model>] | block )
  • for — model glob (fnmatch) against the model in the request body.
  • need — the output budget the client declared (max_tokens/max_completion_tokens); >64000 matches a declared budget above 64k. A request without one never matches a need rule: junction is a pass-through and does not invent sizes.
  • check hooks|none — override the endpoint's hook list for this rule.
  • retry <s> — override hook_retry ("wait up to N s for the box").
  • pass a, b — try a, then b on failure.
  • as <model> — after a target, rewrite the model field for that target only: pass peer-a as "qwen3.8-flash-next-q1m", peer-b, cloud sends the local id to the peers and the requested id to the cloud.
  • block — refuse with 403.

No matching rule → 503 no_matching_rule: an unmatched request is a config gap, not something to quietly send to a cloud.

Keys

Global: listen, connect_timeout_ms, offline_hold_s, max_body_bytes, log_prefix, cache_ttl, cache_entries, cache_bytes, max_inflight, queue_timeout.

Endpoint:

key meaning
base OpenAI-compatible base URL including /v1 (http:// or https://)
context usable context window in tokens
kind free-form label (local, remote, cloud)
priority lower wins when a rule lists several
timeout total wall clock for one request (seconds)
connect_timeout_ms per-endpoint connect limit; 0 = the global value
weight 1..100, how often this endpoint is chosen (default 1)

A chain can be named once and reused, and a pool may name another pool:

  pool lokal   box3, box6
  pool alles   cloud, lokal
  req for "*"  pass alles

| idle_timeout | silence before still_working is logged (seconds) | | cooldown | rest after a failed request (seconds) | | hook | shell command; exit 0 = usable, non-zero = not yet (repeatable) | | hook_retry | how long to keep retrying hooks | | hook_backoff | sleep between hook attempts | | wake | command run once before the hook retries begin | | api_key_env | env var sent as Authorization: Bearer ... | | tls_verify | on (default) / off | | tls_ca | CA bundle for a private CA (default: system store) | | cache | on / off for this endpoint | | header | static request header, "Name: value" (repeatable) | | vision | on / off — can this endpoint read images? Omitted = not checked | | kind opencode | the endpoint is an opencode serve; requests are translated | | auth_basic <user> | HTTP Basic instead of a bearer token (opencode wants this) | | pass_cmd <cmd> | stdout is the password — opencode makes a new one on every start | | base_cmd <cmd> | stdout is the base URL — the background server binds a random port |

Hooks

Plain POSIX shell, with the request in the environment:

JUNCTION_BACKEND  JUNCTION_BASE  JUNCTION_PATH  JUNCTION_MODEL
JUNCTION_NEED_TOKENS  JUNCTION_ATTEMPT

Exit non-zero and print the reason on stdout — it lands in /status and in the 503 body. Examples in hooks/: check-http.sh, check-budget.sh, wake-wol.sh.

MCP gateway — junction as one MCP server for all tools

junction can also serve MCP. Every MCP server you list in the configuration is reached through junction, so an agent connects once and sees every tool, instead of subscribing to each server separately. Same role the MCP gateway of LiteLLM plays.

mcp tasksd url http://127.0.0.1:8781/mcp
mcp skilld url http://127.0.0.1:8790/mcp header "Authorization: Bearer …" timeout 20
mcp_cache_ttl 60
key meaning
mcp <name> url <url> an upstream MCP server (Streamable HTTP, JSON-RPC 2.0)
header "Name: value" repeated; for tokens and anything else the server wants
timeout <s> per call; default 10 — a server that does not answer delays the tool list, it does not block it
off keep the entry, do not use it
mcp_cache_ttl <s> how long the aggregated tool list is kept, default 60

The client talks to http://<junction>:8090/mcp and gets initialize, ping, tools/list and tools/call. Tool names are prefixed with the server name — tasksd__task_create — because two servers may well have a tool of the same name; tools/call splits the prefix off before forwarding. Descriptions and input schemas are passed through untouched.

What it deliberately does not do: no session cookie, no server-to-client push, no SSE answer to a request. A tool call is a question with one answer. Requests without an id are notifications and get 202 with no body.

A server that is down or silent is skipped with a log line; the tools of the others still arrive. Nothing is invented to fill the gap.

Control plane

Method Path Effect
GET /status endpoints, counters, cache stats, rules
POST /admin/pause/<name> stop routing there
POST /admin/resume/<name> clear pause + cooldown + offline
POST /admin/flush/cache drop every cached response

/status also reports the queue: inflight, waiting, max_inflight, timeout_s.

Everything else is proxied to the endpoint the rules choose.

make install also installs junction-wol (C, 100 lines) for the wake-wol.sh hook — building a magic packet should not need an interpreter either.

Known limits (v0.1, deliberately named)

  • The queue is FIFO-ish: max_inflight slots go to whoever asks next; there is no prioritisation and no fairness guarantee beyond that.
  • HTTP/1.1 only — no HTTP/2, no h2c.
  • The cache is memory-only and lost on restart; it is not shared between processes and does not survive SIGHUP.
  • TLS client is verified against the system store or tls_ca; there is no certificate pinning and no client-certificate auth.
  • junction does not tokenise. It sees only the numbers the client writes, so a request that declares no budget is routed by its model and path alone.

Tests

tests/run.sh

C stubs for a failing endpoint, a hook-gated one, a slow one (6 s silence), a dead port, and a TLS peer with a self-signed cert. Checks: offline detection, cooldown and failover, hook retry, still_working, block rules, catch-all, model rewrite, no_matching_rule, config errors, chunked request decoding (byte-exact body), cache miss/hit/flush/bypass, header passthrough and injection, TLS listener, https upstream, and that certificate verification actually refuses a self-signed peer. Pass = PASS (49 checks), including two that would have caught the two mistakes this design invites: a serial stub making a concurrent router look serialised, and a "waiting" comment leaking into a caller that never asked for a stream.

The suite refuses to run if a test port is already taken — a stale junction on :8105 once answered requests with someone else's config and made a good test look broken.

S
Description
junction (from n95, ~/src/junction)
Readme
1.4 MiB
0 Stars 3 Watchers 0 Forks
Languages
C 64.5%
Shell 21.2%
Python 7.2%
JavaScript 2.9%
HTML 2.6%
Other 1.6%