Repository navigation
Mark failing remote MCP servers unhealthy instead of starting - #4844
Conversation
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 6181e8215d
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
6181e82 to
dd528ec
Compare
Review: Regression risk + proposed approachThe fix for the stuck-in-`starting` bug is correct and the removal of `TOOLHIVE_REMOTE_HEALTHCHECKS` is the right call. However, the current implementation introduces a regression for remote MCP servers with a sleep/awake lifecycle (e.g. scale-to-zero serverless backends): after ~45s of downtime (3 failures × 10s interval + 5s retry), the proxy self-terminates. Root cause of the regressionWhen `handleHealthCheckFailure` exhausts retries, it calls both `onHealthCheckFailed()` (sets status → `unhealthy`) and `p.Stop()` (kills the listener, exits `monitorHealth`). For a temporarily unavailable remote server there is nothing left to observe recovery — the proxy is dead. Proposed fix: soft-unhealthy with auto-recovery for remote workloadsThe key insight: ToolHive does not control the lifecycle of a remote server the way it controls a container. Stopping the proxy because a remote server is temporarily unavailable is too aggressive. `handleHealthCheckFailure` — branch on `isRemote`: ```go `monitorHealth` — fire a recovery callback when health returns: ```go `runner.go` — wire both callbacks: ```go `runner.go` — extend the existing unauthenticated status guard to also preserve `unhealthy`, preventing `waitForInitializeSuccess` from racing with the health check loop: ```go Resulting state machine for remote workloads
Why `TOOLHIVE_REMOTE_HEALTHCHECKS` stays removedThe env var existed solely to prevent health checks from killing the proxy for temporarily unavailable servers. With auto-recovery, that reason is gone. Health checks are now safe to enable unconditionally for remote workloads: they catch broken servers fast and survive temporary downtime transparently. |
dd528ec to
49d6979
Compare
|
@amirejaz Yeah you right, stopping the proy was too aggresive, fixed it so remote proxies stay alive after fail and auto-recover when he serer come back, instead of dying and requiring a manual restrt, also wired recovery callback in runner.go and extended the atus guard to cover |
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## main #4844 +/- ##
==========================================
+ Coverage 82.18% 82.23% +0.04%
==========================================
Files 932 932
Lines 94564 94615 +51
==========================================
+ Hits 77715 77803 +88
+ Misses 16844 16807 -37
Partials 5 5 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
49d6979 to
e4f6532
Compare
There was a problem hiding this comment.
Large PR Detected
This PR exceeds 1000 lines of changes and requires justification before it can be reviewed.
How to unblock this PR:
Add a section to your PR description with the following format:
## Large PR Justification
[Explain why this PR must be large, such as:]
- Generated code that cannot be split
- Large refactoring that must be atomic
- Multiple related changes that would break if separated
- Migration or data transformationAlternative:
Consider splitting this PR into smaller, focused changes (< 1000 lines each) for easier review and reduced risk.
See our Contributing Guidelines for more details.
This review will be automatically dismissed once you add the justification section.
|
@aponcedeleonch Hey, thanks for the review, fixed all three things: Merged main in and resolved the conflict in manager.go |
|
Also re: your two notes. The repeated logging/status-write on every failed tick during a sustained outage, didn't touch that yet, happy to fix it in a follow-up if you want it now instead. |
timeout_test.go and body_limit_test.go also call NewTransparentProxyWithOptions directly and were missed when the onHealthCheckRecovered parameter was added, breaking the build.
aponcedeleonch
left a comment
There was a problem hiding this comment.
Thanks for turning this around. The stay-alive + auto-recovery design reads well and the diff is a lot tighter now.
Requesting changes mainly for the red CI, plus the two items worth locking down here rather than deferring. Details inline.
CI: Tests / Test Go Code is failing on TestGetRemoteWorkloadsFromState_AuthRetryingVisibleWithoutAll. I checked the job log, it's this PR and not a flake. The manager.go filter change surfaces Unauthenticated without -a, which that existing test asserts should stay hidden. See the inline note on manager.go for the two ways to resolve it.
On your two notes from last round:
- Repeated logging/status-write per failed tick: I'd rather fix it here than in a follow-up. It's a small change and the current behavior emits an ERROR log line and a status-write every interval for as long as a remote server is down. Inline on
transparent_proxy.go. - Always-on remote health checks reversing the old opt-in: agreed, that's the point of the fix. No concern from me there.
One new thing that wasn't in the earlier round: there's a TOCTOU race in runner.go between the health-check callback and the final SetWorkloadStatus(Running). It's coupled to the logging fix, so worth reading the two inline notes together.
Resolves conflicts with stacklok#7001, which made the health monitor check before the MCP server is initialized so /health answers from the last check. Remote workloads now count those checks from the start; local workloads keep counting only after initialization, so the test stacklok#7001 added for that behavior now runs against a local proxy. Adds the onHealthCheckRecovered constructor argument to the proxy calls main added, and keeps waitForShutdown for local-proxy shutdown alongside the remote tests' waitForCallback. Remote health checks now run by default, so the consent-cookie test's backend ignores the cookie-less health check requests. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
During a sustained remote outage, the failure callback fired on every failed check, logging and rewriting the unhealthy status each interval. Notify only on the transitions into and out of unhealthy. Serialize the runner's status writes, so the read-then-write that marks a workload running cannot overwrite an unhealthy status set between the read and the write. With notifications edge-triggered, that overwrite would otherwise stick. Recovery moves a workload to running only from unhealthy. Surface only Unhealthy, not Unauthenticated, in default remote thv list output: an unhealthy remote proxy keeps running and recovers by itself, like AuthRetrying. Update the architecture docs and the e2e test to cover unhealthy and recovery. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
|
@slyt3 thanks for all the work on this. To get it over the line, we've taken it over and pushed two commits to your branch (no force-push, your history is intact):
The PR description is updated to match the current behavior. @aponcedeleonch could you take another look? |
The remote health check pinged the host root, because the proxy's target holds only scheme and host. On a shared host the root can answer while the MCP endpoint fails, so the workload was never marked unhealthy. Ping the remote URL's path and query instead. Stopping an unhealthy remote workload skipped client cleanup and the stopped status, although its proxy was still running. Treat unhealthy as active there. Call the failure callback on every failed check while unhealthy, and have the runner write only when the status is not already unhealthy, so a failed write or another writer's status is put right within one interval. Keep an unauthenticated status, which a later recovery would otherwise turn into running, and skip recovery when the status cannot be read. Restore TOOLHIVE_REMOTE_HEALTHCHECKS as an opt-out, for remote servers that answer the health check badly while serving MCP requests. Show the unhealthy reason in thv list only for remote workloads, update the --all help, and add runner, proxy, stop, and e2e coverage for the issue's start-unhealthy scenario. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Adds the onHealthCheckRecovered constructor argument to the proxy call in ownership_test.go, which main added since the last merge. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Every caller passed the same 50ms retry delay to withHealthCheckRetryDelay, which unparam rejects. Build the fast health check options in one helper that the remote proxy tests share. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
The request for changes was in an old commit. All comments have been addressed
* Harden remote health check status reporting Follow-up to #4844, which turned remote health checks on by default and keeps failing remotes running as unhealthy. - Redact ping errors and pinger logs to the remote URL's scheme and host. The unauthenticated /health response echoed the ping error, which quoted the full remote URL, so secrets in its path or query were readable by anyone who could reach the proxy. - Stop firing health callbacks once the proxy is shutting down, and have the runner keep stopping/stopped/removing and skip deleted workloads, so stopping or removing an unhealthy remote no longer leaves it unhealthy or recreates its status file. - Make HealthCheckRecoveredCallback return an error and retry it on later passing checks, so one failed status write no longer leaves a recovered remote stuck as unhealthy. - Fix the health check docs that contradicted the opt-out and the repeated-write behaviour. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> * Fix codespell failure in pinger redaction Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
Summary
A remote MCP server that keeps returning errors (for example, HTTP 500) leaves its workload stuck in
starting.thv listdoesn't show it without-a, and the user gets no sign that anything is wrong unless they read debug logs (#4459). There are two causes:TOOLHIVE_REMOTE_HEALTHCHECKS=truewas set.monitorHealthcounted failures only after the MCP server was initialized, and a server that keeps failing never initializes.Stopping the proxy on failure, as local workloads do, would be wrong for remote servers, because ToolHive doesn't own their lifecycle. A scale-to-zero backend, for example, is expected to come back. So a remote proxy now stays up, marks the workload
unhealthy, and keeps checking until the server recovers.TOOLHIVE_REMOTE_HEALTHCHECKS=falseturns them off. They now check the remote URL's path and query instead of the host root, so a failing MCP endpoint on a shared host is detected. Remote failures count from the first interval check; local workloads still count failures only after initialization.unhealthyand its proxy keeps running. When a later check passes, the workload goes back torunningwithout a restart. Local workloads keep the current behavior: the proxy stops.unhealthyonly if something else changed it, so a failed write, or the auth monitor writingrunningmid-outage, is put right within one interval. Anunauthenticatedstatus is never overwritten, and recovery moves a workload torunningonly fromunhealthy.runningat startup can't overwrite anunhealthystatus set at the same moment.thv listshows unhealthy remote workloads without-a, with "Remote server failed health checks" in the status column. Stopping an unhealthy remote workload marks itstoppedand removes its client configuration, as for a running one.Fixes #4459
Type of change
Test plan
task test)task test-e2e)task lint-fix)New and updated unit tests cover:
unauthenticated, skips recovery when the status can't be read, keeps callback statuses at startupthv listfilter, and theTOOLHIVE_REMOTE_HEALTHCHECKSopt-outThe
health_check_zombiee2e tests run in CI. One covers running →unhealthy→running. The other covers the issue's scenario: a server that fails from the start shows asunhealthywith its reason in plainthv list, then reachesrunning. Linting is left to CI because the local linter run crashes on the Go 1.27 toolchain.Changes
pkg/transport/http.goTOOLHIVE_REMOTE_HEALTHCHECKS=falseopts outpkg/transport/proxy/transparent/transparent_proxy.gopkg/transport/types/transport.go,stdio.go,types/mocks/SetOnHealthCheckRecoveredcallbackpkg/runner/runner.gomarkRemoteUnhealthy/markRemoteRecoveredcallbacks; route callback and startup status writes through one mutex-guardedtransitionWorkloadStatuspkg/workloads/manager.goUnhealthyremote workloads without-a; include the status context; stop unhealthy remote workloads like running onescmd/thv/app/list.go,docs/cli/thv_list.md--allhelpdocs/arch/03-transport-architecture.md,08-workloads-lifecycle.mdDoes this introduce a user-facing change?
Yes.
startingindefinitely, or is markedrunningafter the 5-minute initialize wait even though it is broken. It doesn't appear inthv listwithout-a. Remote health checks run only withTOOLHIVE_REMOTE_HEALTHCHECKS=true.TOOLHIVE_HEALTH_CHECK_FAILURE_THRESHOLDconsecutive failures (default 5), the workload shows asunhealthy (Remote server failed health checks)in plainthv list. It returns torunningby itself when the server answers again, with no restart needed. Remote health checks run by default against the remote URL's path;TOOLHIVE_REMOTE_HEALTHCHECKS=falseturns them off, and=trueis now redundant.Special notes for reviewers
GET(a JSON-RPCpingPOSTfor--stateless) on its MCP path everyTOOLHIVE_HEALTH_CHECK_INTERVAL(default 10s); without that, a broken remote server can't be detected. Any status below 500 counts as healthy, so 401, 405 and 406 answers are fine. A remote SSE endpoint answers theGETby opening a stream, which the check closes after the headers.TOOLHIVE_REMOTE_HEALTHCHECKS=falseis the escape hatch for servers that answer the check badly. One existing test broke because of the extra request:TestFactoryStripConsentCookieChangesLiveProxyBehavior, whose backend now also sees health checks.thv list.AuthRetryingoverlap: the failure callback overwritesauth_retryingwithunhealthy. If the auth monitor later writesrunningwhile the server is still down, the next failed check putsunhealthyback.thv listfilter showsUnhealthywhile the local filter infile_status.godoesn't: a local unhealthy workload is terminal, while a remote one recovers by itself, likeAuthRetrying.3ed579067(merge),ef8136111(review fixes) and84351ec58(endpoint check, stop path, status hardening, opt-out).🤖 Generated with Claude Code