Skip to content

Mark failing remote MCP servers unhealthy instead of starting - #4844

Merged
aponcedeleonch merged 11 commits into
stacklok:mainfrom
slyt3:fix/remote-server-unhealhty-on-errors
Nov 26, 2026
Merged

aponcedeleonch merged 11 commits into
stacklok:mainfrom
slyt3:fix/remote-server-unhealhty-on-errors

Conversation

@slyt3

@slyt3 slyt3 commented Apr 15, 2026 •

Copy link
Copy Markdown
Contributor

Summary

A remote MCP server that keeps returning errors (for example, HTTP 500) leaves its workload stuck in starting. thv list doesn'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:

  1. Remote health checks were off unless TOOLHIVE_REMOTE_HEALTHCHECKS=true was set.
  2. Even with checks on, monitorHealth counted 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.

  • Remote health checks are on by default; TOOLHIVE_REMOTE_HEALTHCHECKS=false turns 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.
  • After the failure threshold, a remote workload becomes unhealthy and its proxy keeps running. When a later check passes, the workload goes back to running without a restart. Local workloads keep the current behavior: the proxy stops.
  • The status is written only on transitions. While a server stays unhealthy, each failed check re-reads the status and rewrites unhealthy only if something else changed it, so a failed write, or the auth monitor writing running mid-outage, is put right within one interval. An unauthenticated status is never overwritten, and recovery moves a workload to running only from unhealthy.
  • The runner's status writes are serialized, so marking a workload running at startup can't overwrite an unhealthy status set at the same moment.
  • thv list shows unhealthy remote workloads without -a, with "Remote server failed health checks" in the status column. Stopping an unhealthy remote workload marks it stopped and removes its client configuration, as for a running one.

Fixes #4459

Type of change

  • Bug fix
  • New feature
  • Refactoring (no behavior change)
  • Dependency update
  • Documentation
  • Other (describe):

Test plan

  • Unit tests (task test)
  • E2E tests (task test-e2e)
  • Linting (task lint-fix)
  • Manual testing (describe below)

New and updated unit tests cover:

  • a remote server that returns 500 before initialization being marked unhealthy while the proxy stays up
  • the health check reaching the remote path and query: the backend fails only on the MCP path
  • failure, repeated notification while unhealthy, a single recovery, and a second outage
  • the runner's transitions: writes only on change, keeps unauthenticated, skips recovery when the status can't be read, keeps callback statuses at startup
  • stopping an unhealthy remote workload, the remote thv list filter, and the TOOLHIVE_REMOTE_HEALTHCHECKS opt-out
  • local proxies still not counting failures before initialization

The health_check_zombie e2e tests run in CI. One covers running → unhealthy → running. The other covers the issue's scenario: a server that fails from the start shows as unhealthy with its reason in plain thv list, then reaches running. Linting is left to CI because the local linter run crashes on the Go 1.27 toolchain.

Changes

File Change
pkg/transport/http.go Enable remote health checks by default; TOOLHIVE_REMOTE_HEALTHCHECKS=false opts out
pkg/transport/proxy/transparent/transparent_proxy.go Check the remote path and query; count remote failures before initialization; keep remote proxies running when unhealthy; re-notify while unhealthy and notify recovery once
pkg/transport/types/transport.go, stdio.go, types/mocks/ Add the SetOnHealthCheckRecovered callback
pkg/runner/runner.go markRemoteUnhealthy / markRemoteRecovered callbacks; route callback and startup status writes through one mutex-guarded transitionWorkloadStatus
pkg/workloads/manager.go Show Unhealthy remote workloads without -a; include the status context; stop unhealthy remote workloads like running ones
cmd/thv/app/list.go, docs/cli/thv_list.md Show the unhealthy reason for remote workloads; update the --all help
docs/arch/03-transport-architecture.md, 08-workloads-lifecycle.md Describe remote health checks and the unhealthy ⇄ running transitions
Tests Regression and recovery tests; constructor argument updates; the e2e test drops the env var and checks recovery

Does this introduce a user-facing change?

Yes.

  • Before: a remote MCP server that keeps failing stays in starting indefinitely, or is marked running after the 5-minute initialize wait even though it is broken. It doesn't appear in thv list without -a. Remote health checks run only with TOOLHIVE_REMOTE_HEALTHCHECKS=true.
  • After: after TOOLHIVE_HEALTH_CHECK_FAILURE_THRESHOLD consecutive failures (default 5), the workload shows as unhealthy (Remote server failed health checks) in plain thv list. It returns to running by 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=false turns them off, and =true is now redundant.

Special notes for reviewers

  • Extra traffic to remote servers: this deliberately reverses the earlier opt-in. Every remote server now gets an unauthenticated GET (a JSON-RPC ping POST for --stateless) on its MCP path every TOOLHIVE_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 the GET by opening a stream, which the check closes after the headers. TOOLHIVE_REMOTE_HEALTHCHECKS=false is 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.
  • Fixed reason string: the status context is a fixed "Remote server failed health checks", not the pinger's error. That error can include the remote URL with its query, which may carry credentials, and the context is persisted and printed by thv list.
  • AuthRetrying overlap: the failure callback overwrites auth_retrying with unhealthy. If the auth monitor later writes running while the server is still down, the next failed check puts unhealthy back.
  • Unhealthy stops the proxy only for local workloads: a local proxy still stops when its server is unhealthy, because ToolHive owns the container. A remote proxy doesn't. The same difference is why the remote thv list filter shows Unhealthy while the local filter in file_status.go doesn't: a local unhealthy workload is terminal, while a remote one recovers by itself, like AuthRetrying.
  • This was started by @slyt3. Maintainers took it over to merge main (which conflicted with Answer /health from the health monitor's last check #7001) and address review feedback, in 3ed579067 (merge), ef8136111 (review fixes) and 84351ec58 (endpoint check, stop path, status hardening, opt-out).

🤖 Generated with Claude Code

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Claude Code Review

This pull request is from a fork — automated review is disabled. A repository maintainer can comment @claude review to run a one-time review.

@github-actions github-actions Bot added the size/S Small PR: 100-299 lines changed label Apr 15, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

@slyt3
slyt3 force-pushed the fix/remote-server-unhealhty-on-errors branch from 6181e82 to dd528ec Compare April 15, 2026 11:34
@github-actions github-actions Bot added size/S Small PR: 100-299 lines changed and removed size/S Small PR: 100-299 lines changed labels Apr 15, 2026
@amirejaz

amirejaz commented Apr 15, 2026 •

Copy link
Copy Markdown
Contributor

Review: Regression risk + proposed approach

The 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 regression

When `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 workloads

The 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
if p.onHealthCheckFailed != nil {
p.onHealthCheckFailed()
}
if p.isRemote {
// Stay in degraded mode, keep monitoring for recovery
return consecutiveFailures, true // shouldContinue = true, no Stop()
}
// Local container: we own the lifecycle, stop it
if err := p.Stop(ctx); err != nil { ... }
return consecutiveFailures, false
```

`monitorHealth` — fire a recovery callback when health returns:

```go
if consecutiveFailures >= healthCheckRetryCount && p.onHealthCheckRecovered != nil {
p.onHealthCheckRecovered()
}
consecutiveFailures = 0
```

`runner.go` — wire both callbacks:

```go
transportHandler.SetOnHealthCheckFailed(func() {
r.statusManager.SetWorkloadStatus(ctx, r.Config.BaseName, rt.WorkloadStatusUnhealthy, "Server stopped responding")
})
transportHandler.SetOnHealthCheckRecovered(func() {
r.statusManager.SetWorkloadStatus(ctx, r.Config.BaseName, rt.WorkloadStatusRunning, "")
})
```

`runner.go` — extend the existing unauthenticated status guard to also preserve `unhealthy`, preventing `waitForInitializeSuccess` from racing with the health check loop:

```go
if currentWorkload.Status == rt.WorkloadStatusUnauthenticated ||
currentWorkload.Status == rt.WorkloadStatusUnhealthy {
// health checks drive this state, don't overwrite
} else {
SetWorkloadStatus(running)
}
```

Resulting state machine for remote workloads

Scenario Behaviour
Server returns 500 from start (original bug) Marked `unhealthy` in ~45s, stays there, visible in `thv list`
Server temporarily unavailable (e.g. scale-to-zero cold start) Marked `unhealthy` during downtime, auto-recovers when it comes back — no manual restart
Permanently broken server Stays `unhealthy` indefinitely; user sees it in `thv list` and runs `thv stop` manually
Local container workload Unchanged — proxy stops on failure (ToolHive controls the container lifecycle)

Why `TOOLHIVE_REMOTE_HEALTHCHECKS` stays removed

The 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.

@amirejaz amirejaz left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

added a comment

@slyt3
slyt3 force-pushed the fix/remote-server-unhealhty-on-errors branch from dd528ec to 49d6979 Compare April 16, 2026 10:30
@github-actions github-actions Bot added size/M Medium PR: 300-599 lines changed and removed size/S Small PR: 100-299 lines changed labels Apr 16, 2026
@slyt3

slyt3 commented Apr 16, 2026 •

Copy link
Copy Markdown
Contributor Author

@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 unhealhty checks and removed TOOLHIVE_REMOTE_HEALTHCEKS` the only reason it existed was to avoid the proxy ding on temporary outages, which now hanlded properly

@codecov

codecov Bot commented Apr 16, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 82.27848% with 14 lines in your changes missing coverage. Please review.
✅ Project coverage is 82.23%. Comparing base (ac27d5e) to head (d9fce35).
⚠️ Report is 2 commits behind head on main.

Files with missing lines Patch % Lines
pkg/runner/runner.go 71.42% 10 Missing ⚠️
...g/transport/proxy/transparent/transparent_proxy.go 93.75% 2 Missing ⚠️
pkg/transport/http.go 75.00% 1 Missing ⚠️
pkg/transport/stdio.go 0.00% 1 Missing ⚠️
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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@slyt3
slyt3 force-pushed the fix/remote-server-unhealhty-on-errors branch from 49d6979 to e4f6532 Compare April 16, 2026 10:36
@github-actions github-actions Bot added size/M Medium PR: 300-599 lines changed and removed size/M Medium PR: 300-599 lines changed labels Apr 16, 2026

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 transformation

Alternative:

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.

@github-actions github-actions Bot added size/XL Extra large PR: 1000+ lines changed and removed size/XL Extra large PR: 1000+ lines changed labels Apr 16, 2026
@slyt3
slyt3 requested a review from reyortiz3 as a code owner July 20, 2026 10:00
@slyt3

slyt3 commented Jul 20, 2026 •

Copy link
Copy Markdown
Contributor Author

@aponcedeleonch Hey, thanks for the review, fixed all three things:

Merged main in and resolved the conflict in manager.go
Fixed the mojibake em-dashes in backend_routing_test.go
Stripped the blank-line churn out of transparent_test.go so it only shows the real changes now
Diff's a lot smaller now, should be easy to review. Let me know if I missed anything.

@github-actions github-actions Bot added size/M Medium PR: 300-599 lines changed and removed size/XL Extra large PR: 1000+ lines changed labels Jul 20, 2026
@slyt3

slyt3 commented Jul 20, 2026

Copy link
Copy Markdown
Contributor Author

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.
Always-on remote health checks reversing the old opt-in, yeah, that's intentional, it's the whole point of the fix (silent starting forever otherwise). Flagging for whoever signs off on the tradeoff.

timeout_test.go and body_limit_test.go also call
NewTransparentProxyWithOptions directly and were missed when the
onHealthCheckRecovered parameter was added, breaking the build.
@github-actions github-actions Bot added size/M Medium PR: 300-599 lines changed and removed size/M Medium PR: 300-599 lines changed labels Jul 20, 2026

@aponcedeleonch aponcedeleonch left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread pkg/runner/runner.go Resolved
Comment thread pkg/workloads/manager.go Resolved
ChrisJBurns and others added 2 commits November 25, 2026 22:48
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]>
@ChrisJBurns ChrisJBurns changed the title fix remote MCP servers stuck in starting when upstream returns errors Mark failing remote MCP servers unhealthy instead of starting Nov 25, 2026
@ChrisJBurns

Copy link
Copy Markdown
Collaborator

@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):

  • 3ed579067: merges main and resolves the conflicts with Answer /health from the health monitor's last check #7001, which made the health monitor check before initialization so /health answers from the last check. Remote failures now count from the first check; local workloads still count only after initialization, and the test Answer /health from the health monitor's last check #7001 added for that now runs against a local proxy. With remote health checks on by default, TestFactoryStripConsentCookieChangesLiveProxyBehavior's backend also sees the health-check requests, so it now ignores those.
  • ef8136111: addresses the last review round:
    • Repeated logging and status writes: the failure callback now fires only when a remote server becomes unhealthy, and the recovery callback only when it comes back. During an outage, each failed check logs only at debug level.
    • Runner race: callback and startup status writes go through one mutex-guarded transitionWorkloadStatus. Startup no longer overwrites an unhealthy status set just before it, and recovery moves a workload to running only from unhealthy.
    • manager.go filter (the CI failure): I dropped Unauthenticated and kept Unhealthy. The comment now explains why the remote filter shows more than file_status.go: a remote unhealthy proxy recovers by itself, while a local one stops. The existing test now covers Unhealthy too.
    • Docs and e2e: docs/arch no longer says the proxy stops proxying. The health_check_zombie e2e test now expects unhealthy and then a return to running.

The PR description is updated to match the current behavior.

@aponcedeleonch could you take another look?

ChrisJBurns
ChrisJBurns previously approved these changes Nov 26, 2026
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]>
ChrisJBurns and others added 2 commits November 26, 2026 11:13
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]>
@aponcedeleonch
aponcedeleonch dismissed amirejaz’s stale review November 26, 2026 12:07

The request for changes was in an old commit. All comments have been addressed

@aponcedeleonch
aponcedeleonch merged commit 90c8676 into stacklok:main Nov 26, 2026
53 of 54 checks passed
rdimitrov pushed a commit that referenced this pull request Nov 26, 2026
* 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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

size/M Medium PR: 300-599 lines changed

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Remote MCP servers stuck in "starting" state when upstream returns errors

4 participants