Skip to content
Project-SandStarPublic

About

Reconnecting MCP proxy. Fronts multiple HTTP/stdio MCP servers behind one port so clients survive upstream restarts instead of losing their session.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

mcp-proxy

A reconnecting MCP proxy. Fronts multiple HTTP/stdio MCP servers behind one HTTP port so Claude Code clients survive upstream restarts.

What it does

                          ┌─► fantom-mcp (HTTP :3848)
Claude Code ──HTTP──► proxy ─┼─► axon-mcp   (HTTP :3847)
   (never drops)             └─► sedona-mcp (stdio child)

Each Claude Code instance opens a long-lived HTTP MCP session against the proxy. The proxy holds one upstream connection per configured server and transparently reconnects when an upstream restarts. Tool calls that arrive during the gap wait inside the proxy (default 15s) and succeed when the upstream returns. Claude Code never sees a disconnect.

Layout

server.mjs                  HTTP listener — mounts docs + per-upstream MCP routes
config.json                 your live list of upstreams (not in git; copy config.example.json)
config.example.json         template with example hosts and paths
upstreams/httpUpstream.mjs  HTTP client with reconnect + stale-session retry
upstreams/stdioUpstream.mjs stdio child process bridge + crash-loop guard
upstreams/tokenSources.mjs  pluggable bearer-token providers
upstreams/dnsFallback.mjs   retry via the domain's own nameservers on ENOTFOUND
upstreams/outageAlert.mjs   macOS notification when an upstream stays down
routes/mcpRoute.mjs         multi-session per-upstream HTTP MCP transport
routes/docs.mjs             dynamic markdown docs at GET / and /docs
docs/install.md.tmpl        template (interpolates live config)
scripts/start.sh stop.sh restart.sh   PID-file managed lifecycle
test/smoke.mjs              listTools probe against each endpoint
ecosystem.config.cjs        PM2 deployment

Running

npm install
./scripts/start.sh         # background, PID written to .mcp-proxy.pid
./scripts/restart.sh       # idempotent restart
./scripts/stop.sh          # SIGTERM then SIGKILL after 5s grace

Or under PM2:

pm2 start ecosystem.config.cjs
pm2 save
pm2 startup

Configuration

config.json (copy config.example.json and edit it; it is not in git):

{
  "port": 9191,
  "host": "127.0.0.1",
  "waitMs": 15000,
  "callTimeoutMs": 120000,
  "allowedOrigins": [],
  "upstreams": [
    {
      "name": "fantom",
      "path": "/fantom/mcp",
      "type": "http",
      "url": "http://localhost:3848/mcp",
      "tokenSource": {
        "type": "fantom-admin-grant",
        "username": "${FANTOM_ADMIN_USER}",
        "password": "${FANTOM_ADMIN_PASS}",
        "scope": "mcp:read mcp:write"
      }
    },
    { "name": "axon", "path": "/axon/mcp", "type": "http",
      "url": "http://localhost:3847/mcp" },
    { "name": "sedona", "path": "/sedona/mcp", "type": "stdio",
      "command": "node",
      "args": ["/path/to/mcpserversedona/dist/index.js"],
      "cwd": "/path/to/mcpserversedona" }
  ]
}

Top-level keys

  • port (default 9191) — TCP port to listen on.
  • host (default 127.0.0.1) — bind address. The proxy binds loopback only by default; set explicitly (e.g. a LAN IP) if you really want wider exposure.
  • waitMs (default 15000) — how long a request waits for an upstream to (re)connect before failing. Overridable per upstream.
  • callTimeoutMs (default 120000) — per-request timeout once connected. Overridable per upstream (set it higher for slow tools).
  • allowedOrigins (default []) — extra browser Origins allowed by CORS and the MCP endpoints' DNS-rebinding protection, in addition to the built-in http://127.0.0.1:<port> / http://localhost:<port>. Non-browser clients (no Origin header) are always allowed.

Invalid upstream entries (unknown type, missing keys, bad/duplicate path, or a stdio command/script that doesn't exist) are logged and skipped rather than crashing the proxy; startup only fails if no valid upstream remains.

headers (per upstream)

Static headers per HTTP upstream. Values support ${ENV_VAR} interpolation:

"headers": { "Authorization": "Bearer ${MY_TOKEN}" }

forwardSession (per upstream, default false)

All clients of one path share a single upstream session. With "forwardSession": true, each forwarded request carries the client's identity in params._meta, so the upstream can keep per-client state:

  • mcp-proxy/sessionId — the proxy's session id for that client.
  • mcp-proxy/project — ?project=instance/project on the client's URL (or its X-Axon-Project header) at initialize, if set.

axon-mcp uses these to keep each client's active SkySpark project, also across its own restarts. Example client URL: http://localhost:9191/axon/mcp?project=calinos/calinos.

tokenSource (per HTTP upstream)

A bearer-token provider. Each candidate URL gets its OWN token source (own grant URL, own cache): a token from one server is not valid on another. Built-in types:

  • static — { "type": "static", "token": "..." } (or ${ENV_VAR})
  • fantom-admin-grant — POSTs {clientId, scope} with Basic auth to <candidate origin>/admin/oauth/token-grant (mcpfantom user store). Set url on a candidate's own tokenSource to override the grant URL. An entry-level url is used only by candidates on the same origin. Optional safetySec (default 60): re-mint when the token is this close to expiry.

Renewal: the token is read on every request. The active candidate renews its token on a timer (at 80% of its lifetime), so a long session survives expiry without a reconnect. A 401 drops the cached token, mints once and retries. If a server rejects even a freshly minted token, the proxy stops re-minting for remintBackoffMs (default 5 min; top-level or per upstream).

When every candidate fails, the error names each one: all 3 fantom upstreams failed: https://… → HTTP 401 …; http://… → token mint failed at http://…/admin/oauth/token-grant: fetch failed (ECONNREFUSED). The admin GUI shows every candidate (grant URL, token state, renewals, last mint error) and the last 20 events per upstream.

dnsFallback (top level or per HTTP upstream)

Requests use the system resolver. If one fails with ENOTFOUND or EAI_AGAIN, the proxy asks the nameservers for that host's domain directly and sends the same request again to the IP it gets. The URL does not change, so TLS (SNI, certificate) and the Host header still use the host name.

Where the nameservers come from, in order:

  1. dnsFallback in config.json (per-upstream entries win over top-level ones):

    "dnsFallback": { "vpn.example.org": ["192.0.2.53"] }
  2. On macOS, the scoped resolvers in scutil --dns (domain : vpn.example.org, nameserver[0] : 192.0.2.53). The proxy reads them at most once per 60 s.

The answer is kept for 60 s. The proxy logs one line when it uses the fallback:

[fantom] system DNS failed for fantom.vpn.example.org (ENOTFOUND); using 192.0.2.10 from 192.0.2.53

This covers the case where a long-running proxy can no longer resolve *.vpn.example.org while a new process on the same Mac can.

Health check and candidate states

Before it asks a candidate for a token, the proxy sends GET <origin>/health (through the same DNS fallback). If that fails at the network level, the proxy does not try to log in; it tries again on the normal reconnect schedule. Any HTTP answer counts as "server up", so a server without /health can still log in.

Each candidate has one state:

State Meaning
dns-failed the host name did not resolve, also not through the fallback
server-down connect refused, unreachable or timed out
server-up the server answers, but the MCP session is not open
login-refused the token grant or the MCP endpoint answered 401/403
connected the MCP session is open

The admin GUI shows the state of each candidate. Reconnect error lines show it after the URL:

all 3 fantom upstreams failed: https://fantom.vpn.example.org/mcp [dns-failed] → token mint failed …; http://localhost:3848/mcp [server-down] → health check failed at http://localhost:3848/health: fetch failed (ECONNREFUSED)

Keys (top level or per upstream): healthCheck (default true), healthTimeoutMs (default 5000, never more than connectTimeoutMs).

alertAfterMs (top level or per upstream, default 5 min)

If every candidate of an upstream fails without a break for alertAfterMs, the proxy shows one macOS notification ("mcp-proxy: fantom is down") and the admin GUI marks the upstream red. When it connects again, the proxy shows a second notification ("mcp-proxy: fantom is back online"). One alert per outage. Notifications use osascript and run on macOS only. A pm2 daemon that runs outside your login (GUI) session may not be able to show them; the log line and the red GUI section still appear.

Claude Code config

{
  "mcpServers": {
    "fantom-mcp": { "type": "http", "url": "http://localhost:9191/fantom/mcp" },
    "axon-mcp":   { "type": "http", "url": "http://localhost:9191/axon/mcp" },
    "sedona-mcp": { "type": "http", "url": "http://localhost:9191/sedona/mcp" }
  }
}

Restart Claude Code once after editing. From then on, restarting any upstream is invisible to Claude Code.

Endpoints

  • GET / and /docs — dynamic install page rendered from docs/install.md.tmpl
  • GET /status — JSON: per-upstream type/path/session count
  • GET /config.json — live config (for debugging)
  • POST /<name>/mcp — per-upstream MCP HTTP endpoint (one per upstreams[])

Rotating credentials

The proxy ships with a small admin GUI for rotating upstream passwords without editing shell env vars or restarting the daemon.

  1. Set a strong secret in the environment (e.g. add to scripts/start.sh):

    export MCP_PROXY_ADMIN_SECRET="$(openssl rand -hex 32)"
  2. Restart the proxy, then visit:

    http://localhost:9191/admin?secret=<that-secret>
    

    You'll see one section per HTTP upstream that has a tokenSource. Each section shows connection state, last mint time, and TTL remaining, plus a form with username / password / optional URL override.

  3. Submit the form. Changes:

    • persist to ~/.mcp-proxy/credentials.json (mode 0600, dir 0700);
    • immediately call upstream.reload(...) — the adapter closes its current transport, invalidates the cached token, and reconnects with the new credentials. No proxy restart needed.

The on-disk credentials override the ${FANTOM_ADMIN_USER} / ${FANTOM_ADMIN_PASS} env defaults from config.json on subsequent startups. Delete the file (or the relevant key from it) to fall back to env.

Programmatic access:

curl -sS -X POST http://localhost:9191/admin/save \
  -H "Authorization: Bearer $MCP_PROXY_ADMIN_SECRET" \
  -H "Content-Type: application/json" \
  -d '{"name":"fantom","username":"admin","password":"new-strong-pass"}'

curl -sS "http://localhost:9191/admin/status?secret=$MCP_PROXY_ADMIN_SECRET"

If MCP_PROXY_ADMIN_SECRET is unset the admin routes return HTTP 503 with a setup hint — they're never exposed without auth.

Changing the admin password

Two ways to rotate MCP_PROXY_ADMIN_SECRET:

  • From the GUI (no restart): visit /admin?secret=<current>, fill in the "Admin password" card at the top with the new value twice, and submit. The proxy writes the new value to .admin-secret atomically (tmp file + rename, mode 0600), updates the in-process env var, and rewrites your browser URL to /admin?secret=<new> so the bookmark stays valid. No restart needed.

  • By editing the file (requires restart): edit .admin-secret at the repo root (single line, no trailing junk), then ./scripts/restart.sh. The start script reads the file back into MCP_PROXY_ADMIN_SECRET on launch.

Programmatic equivalent of the GUI rotate:

curl -sS -X POST http://localhost:9191/admin/change-password \
  -H "Authorization: Bearer $MCP_PROXY_ADMIN_SECRET" \
  -H "Content-Type: application/json" \
  -d '{"next":"new-strong-pass"}'

Smoke test

npm run smoke

Opens an MCP client against each endpoint in turn and lists tools.

Notes

  • The proxy's per-upstream reconnect is the whole point. If you bounce a fantom-mcp / axon-mcp listener with the wrong lsof pattern (lsof -ti without -sTCP:LISTEN), the script will also match the proxy's outbound TCP connection to that port and kill the proxy too. Either invoke upstream stop scripts that filter LISTEN, or kill the upstream PID directly.
  • Stdio upstreams share one child process across all downstream sessions. This avoids the per-Claude-Code stdio-spawn that would otherwise contend on per-project locks (e.g. mcpfantom's Kuzu .cache/graph/<id>.db).
  • The proxy ignores unhandledRejection by design — transient upstream fetch failures during reconnect must not crash the daemon.

About

Reconnecting MCP proxy. Fronts multiple HTTP/stdio MCP servers behind one port so clients survive upstream restarts instead of losing their session.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages