openhuman icon indicating copy to clipboard operation
openhuman copied to clipboard

feat(mcp): auto-reconnect installed servers via a background supervisor (#3312)

Open YellowSnnowmann opened this issue 5 months ago • 2 comments

Summary

  • MCP transports drop silently over a long-running deployment (stdio subprocess exits, HTTP-remote session expires) and nothing re-establishes them — connections are brought up only once, at boot. After a few hours a headless deployment has 0 MCP tools with no recovery short of a restart.
  • Adds a background reconnect supervisor that periodically probes each connection and reconnects dropped/never-connected enabled servers with per-server exponential backoff.
  • Adds connections::is_connected + connections::probe_alive (a tools/list round-trip under timeout) so a silently-dropped transport — which stays in the registry map until something calls it — becomes observable.
  • Addresses 1 of the 4 robustness gaps in #3312 (MCP auto-reconnect). Does not close the issue.

Problem

  • A dropped MCP transport stays in the in-process registry map (CONNECTIONS) as a dead Arc<Connection> — the failure only surfaces on the next actual call_tool. So "is it in the map" is not a liveness signal.
  • The boot pass (boot::spawn_installed_servers) runs once; there is no later reconnect, so the orchestrator's tool catalog silently collapses over hours of uptime.

Solution

  • Detect drops with connections::probe_alive(server_id, timeout): issues a tools/list round-trip under an 8s timeout; returns false on transport error/timeout/missing — i.e. "reconnect".
  • Supervise in supervisor::run, mirroring the cron scheduler's tick loop: every 60s it walks each enabled installed server and probes live ones (keep), disconnects + reconnects dropped ones, and reconnects never-connected ones — each gated by per-server exponential backoff (5s base, doubling, 300s cap) so a genuinely-down/misconfigured server isn't hammered. Spawned once at startup after the boot pass; first tick delayed by the interval so it doesn't race boot.
  • Scope decision: connectivity only. The supervisor deliberately does not publish health events to the global health bus — doing so would flip the whole container to unhealthy/503 whenever a single MCP server is down, which is the all-or-nothing coupling the granular-health item of #3312 addresses separately. Keeping these decoupled avoids a regression before that lands.

Submission Checklist

If a section does not apply to this change, mark the item as N/A with a one-line reason. Do not delete items.

  • [x] Tests added or updated (happy path + at least one failure / edge case) per Testing Strategy — unit: backoff truth table (exponential growth, cap, overflow-safety, ready/defer transitions). e2e (hermetic test-mcp-stub): reconnect-a-dropped-server, leave-healthy-intact, skip-disabled, probe-alive liveness lifecycle.
  • [x] Diff coverage ≥ 80% — changed lines (Vitest + cargo-llvm-cov merged via diff-cover) meet the gate enforced by .github/workflows/pr-ci.yml. Run pnpm test:coverage and pnpm test:rust locally; PRs below 80% on changed lines will not merge. — Backoff core (unit) + tick_once/probe_alive/reconnect paths (e2e via run_single_tick_for_test) are covered; the startup spawn block and the probe-fails-while-mapped sub-branch (needs killing a live subprocess) are not. Will confirm diff-cover in CI.
  • [x] Coverage matrix updated — added/removed/renamed feature rows in docs/TEST-COVERAGE-MATRIX.md reflect this change (or N/A: behaviour-only change) — N/A: behaviour-only robustness change.
  • [x] All affected feature IDs from the matrix are listed in the PR description under ## Related — N/A (no matrix rows touched).
  • [x] No new external network dependencies introduced (mock backend used per Testing Strategy) — e2e is hermetic (test-mcp-stub subprocess, no npx/network); no new deps.
  • [x] Manual smoke checklist updated if this touches release-cut surfaces (docs/RELEASE-MANUAL-SMOKE.md) — N/A: Rust core only, no release-cut UI surface.
  • [x] N/A — linked issue intentionally NOT auto-closed: this is a partial fix (1 of 4 items in #3312); maintainer closes #3312 once all land.

Impact

  • Runtime/platform impact (desktop/mobile/web/CLI), if any. — Rust core (CLI/desktop/docker); no frontend changes.
  • Performance, security, migration, or compatibility implications. — One background task; each 60s tick is a lightweight tools/list probe per connected server plus reconnect attempts gated by backoff. No new persistence/migration. Does not alter the /health contract (no health events emitted).

Related

  • Closes: — none (partial fix; #3312 stays open until embedding fallback and granular health also land). Refs #3312 (MCP auto-reconnect item), #3329 (scheduler auto-recovery, merged).
  • Follow-up PR(s)/TODOs: embedding cloud→local fallback (separate PR); granular per-component health (separate PR) — the latter is where MCP health should feed the /health response.

AI Authored PR Metadata (required for Codex/Linear PRs)

Keep this section for AI-authored PRs. For human-only PRs, mark each field N/A.

Linear Issue

  • Key: N/A
  • URL: N/A

Commit & Branch

  • Branch: fix/3312-mcp-auto-reconnect
  • Commit SHA: 88f0dfb94af4b7c533875ee1f43fa9afd4edbfbe

Validation Run

  • [x] pnpm --filter openhuman-app format:check — passed via pre-push hook.
  • [x] pnpm typecheck — passed via pre-push hook.
  • [x] Focused tests: GGML_NATIVE=OFF cargo test --lib mcp_registry::supervisor (4 passed); cargo test --test mcp_registry_e2e (15 passed, incl. 4 new).
  • [x] Rust fmt/check (if changed): cargo fmt --check clean; GGML_NATIVE=OFF cargo check --bin openhuman-core clean.
  • [x] Tauri fmt/check (if changed): N/A — no app/src-tauri changes.

Validation Blocked

  • command: N/A
  • error: N/A
  • impact: N/A

Behavior Changes

  • Intended behavior change: installed MCP servers that drop mid-session are automatically reconnected within ~60s (with backoff) instead of staying dead until a restart.
  • User-visible effect: MCP tools remain available across long uptimes; no manual reconnect/restart needed.

Parity Contract

  • Legacy behavior preserved: boot connect pass and the explicit mcp_clients_connect RPC are unchanged; disabled servers are never auto-connected; all_status semantics unchanged.
  • Guard/fallback/dispatch parity checks: reconnect is gated on server.enabled; backoff prevents retry storms; the supervisor emits no health events, so the /health contract is unchanged.

Duplicate / Superseded PR Handling

  • Duplicate PR(s): none
  • Canonical PR: this PR
  • Resolution (closed/superseded/updated): N/A

Summary by CodeRabbit

  • New Features

    • Added background connection supervision for MCP servers with periodic liveness verification and automatic reconnection logic.
    • Introduced new connection status and health-check APIs.
  • Tests

    • Added comprehensive end-to-end tests for connection supervision, reconnection handling, and server availability scenarios.

YellowSnnowmann avatar Jun 10 '26 08:06 YellowSnnowmann

Review Change Stack

📝 Walkthrough

Walkthrough

This PR adds a background supervisor that periodically probes and reconnects enabled MCP servers, keeping transports alive across long process uptimes with exponential backoff on reconnect failures.

Changes

MCP Server Reconnect Supervision

Layer / File(s) Summary
Connection liveness helpers
src/openhuman/mcp_registry/connections.rs
New public is_connected(server_id) and probe_alive(server_id, timeout) functions query registry state and verify transport liveness via list_tools() round-trip.
Supervisor core and module export
src/openhuman/mcp_registry/mod.rs, src/openhuman/mcp_registry/supervisor.rs
Supervisor module implements periodic tick loop that probes connected servers, disconnects dead transports, and reconnects enabled servers using per-server exponential backoff (base 5s, cap 300s). Exposes run() for background task spawn and run_single_tick_for_test() for deterministic testing.
Core startup wiring
src/core/jsonrpc.rs
Spawns supervisor background task after boot-time MCP server spawn to maintain connection health across process lifetime.
Module documentation
src/openhuman/mcp_registry/README.md
Documents supervisor module role as background reconnect loop and updates public surface to reflect supervisor spawning during core startup.
End-to-end test coverage
tests/mcp_registry_e2e.rs
Four new integration tests verify: probe_alive reflects transport state, supervisor reconnects dropped servers, supervisor leaves healthy connections untouched, and supervisor skips disabled servers.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • tinyhumansai/openhuman#3339: Establishes the MCP server lifecycle and enabled/disabled semantics that this PR's supervisor loop depends on to decide whether to probe and reconnect servers.

Suggested labels

feature, rust-core, working

Poem

🐰 A supervisor hops and checks
Every server, every spec,
Backoff springs when connections drop,
Probing liveness, never stop.
Long live MCP, connected bright!

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title 'feat(mcp): auto-reconnect installed servers via a background supervisor' clearly and concisely describes the main change: adding automatic reconnection for MCP servers through a background supervisor task. It aligns with the PR objectives and the core modifications across multiple files.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.


Comment @coderabbitai help to get the list of available commands and usage tips.

coderabbitai[bot] avatar Jun 10 '26 08:06 coderabbitai[bot]

Pushed 262ef336: guarded the supervisor spawn with Once (the Critical), and applied the probe_alive trace-logging nitpick (trace entry + alive-success; error/timeout debug logs unchanged). The other nitpicks were reviewed; these two were the actionable ones. All 15 mcp_registry_e2e tests + supervisor unit tests still green.

YellowSnnowmann avatar Jun 10 '26 09:06 YellowSnnowmann