Repository navigation
fix(upstream): reconnect remote servers as soon as the network returns - #1931
Merged
Merged
Conversation
A remote upstream that failed because the network was gone (a laptop asleep overnight) kept failing while it was gone. Every failure advanced its backoff until the client gave up after 20 attempts and retried only every 30 minutes. When the machine woke and the network was back, nothing shortened that wait: the server stayed in Error for up to 30 minutes although a manual Restart connected at once. - Connect failures that happen before any upstream answered (DNS, dial, refused, timeout) are recorded as network failures (StateManager.SetNetworkError, ConnectionInfo.NetworkFailure). They advance the backoff exactly as before. - A connectivity watcher in the upstream manager probes such servers with a bare TCP dial to their host, or to the HTTP proxy they use: every 10s, every 30s after 5 minutes of failures. Probes that failed and then succeed reset the backoff and reconnect the server, so it is back within one probe interval. A system wake (a tick far later than scheduled) or a change of the machine's network addresses gives a server one attempt on its current ladder once its host answers. - The watcher never touches a server awaiting sign-in, failed on credentials or OAuth, parked as permanently broken, inside a Retry-After window, or logged out, and it reconnects one server at most every 30s. A server whose host answers all along while it keeps failing is left to the normal backoff (#1013). MCPPROXY_NETWORK_RECOVERY=off disables it. - An HTTP/SSE initialize timeout no longer reports the stdio-only "produced no stderr output ... help banner" text, and it keeps the typed deadline, so it is classified as a network failure. Refs #1929
Deploying mcpproxy-docs with
|
| Latest commit: |
99d8643
|
| Status: | ✅ Deploy successful! |
| Preview URL: | https://03579dc1.mcpproxy-docs.pages.dev |
| Branch Preview URL: | https://fix-1929-network-recovery.mcpproxy-docs.pages.dev |
…kens at once Review round 1 (Opus) on the connectivity watcher: - An OAuth token that expired overnight could not be refreshed on recovery: refreshes that failed while the machine was offline leave the refresh coordinator's transient cooldown (up to 5 min) on the credential, and the reconnect's reactive refresh was answered from it without a request. BeginNetworkRecovery now lifts that cooldown (RefreshCoordinator.ClearTransientCooldown); a revoked grant stays latched. - Backoff resets were unbounded for a remote that is only intermittently reachable, and every network change granted an attempt. Reconnects are now budgeted per server: the first three after the server was last seen connected are immediate and may reset the backoff; past that no reset is granted and the spacing doubles up to the 30-minute give-up interval. A successful connection restores the budget. - A quarantined (or disabled) server could be reconnected after an inspection exemption expired. Both are now ineligible. - The backoff clear is atomic with the eligibility check (StateManager.ClearNetworkBackoff) instead of a full Reset, so a connect that started or failed differently meanwhile is never overwritten. - Reconnects the watcher starts are bounded by the manager's shutdown context, honour the health loop's stop channel, and are waited for before the watcher exits. - Through an HTTP proxy an https upstream is probed with CONNECT, so a proxy that stays up while the network behind it is down does not hide the outage. - The HTTP initialize-timeout text no longer matches the stdio handshake diagnostic; it classifies as MCPX_HTTP_TIMEOUT. Refs #1929
…n the wall clock Review round 2 (Opus), two MINOR points: - The reconnect budget was restored only when a 10s tick happened to see the server connected, and its spacing ran on the monotonic clock, which stops while a Mac sleeps. A night of dark wakes that connected briefly could spend the budget and defer the morning's recovery by up to 30 minutes of awake time. The managed client now counts connects that reached Ready (ConnectSuccessCount); any change since the last tick restores the budget, and trigger spacing is measured on the wall clock. - ReconnectAfterNetworkRecovery re-checks eligibility and reads the health loop's stop channel together under the client lock that Disconnect takes, so a Disconnect that lands first is not undone. Refs #1929
Review round 3 (Opus), MINOR: trigger spacing is measured on the wall clock, so a clock stepped backwards (NTP, a manual date change) read as a negative elapsed time and deferred a server's recovery by the size of the jump. A negative elapsed time now counts as elapsed, for the trigger spacing and the probe cadence. Refs #1929
…; show outages as temporary Release QA blocker (run2 cooldown-503): an OAuth server stays connected while its token has expired and the token endpoint answers 5xx, so every refresh fails transiently and the refresh cooldown grows to minutes; after a network drop the first successful tool call came 136-166 s after the network returned. The connectivity watcher only handled servers in Error. - Refresh mode: a connected server whose OAuth refresh failed transiently (RefreshCoordinator.TransientlyFailing: no success since, no terminal latch) is now watched too. When the network demonstrably comes back the refresh cooldown is lifted and one proactive refresh runs through the coordinator (single flight); the connection is left alone. Revoked grants (invalid_grant) stay latched, disabled/quarantined/logged-out servers are excluded, and the same per-server budget bounds it. The integration test reproducing the scenario recovers in ~0.25 s (it fails past 60 s without this mode). Operator diagnostics, so an outage no longer reads as a hard failure or a sign-in requirement: - Health: an Error caused by a network failure is amber "Reconnecting: <cause>", status "connecting" while retries continue (CLI STATUS "Connecting"), with when the next attempt is due; it becomes an attention item (status error) again after the client gives up. Restart and Edit URL stay offered. - Health: an expired OAuth token whose refresh is being retried after a temporary failure is "Token refresh pending" with the next refresh attempt, not "Token expired" + Sign in. HealthRefreshState also reports transient coordinator failures outside the proactive schedule. - doctor: a self-resolving outage is not listed as an upstream connection error. - Web UI: the server page shows an amber "Reconnecting automatically" panel with the retry detail instead of a red "Server Error". Refs #1929
Review round 4 (Opus): - MAJOR: a live connection that failed on the network (health ping, tool call, list) was recorded with SetError, without the network flag, so the connectivity watcher dropped the server and wiped the outage it had observed; the QA scenario could still take minutes. setErrorIfCurrentConnection now records such failures of remote servers (typed network errors, or a hard network fault flattened into an error string, e.g. inside an OAuth token error) with SetNetworkError. The watcher also keeps a server's probe history while it is briefly not actionable but unhealthy, and clears it only once the server is healthy, so an observed outage or restore is not lost. - MINOR: a wrong host (action Edit URL) keeps status needs_config instead of connecting. - MINOR: the Web UI shows "Reconnecting automatically" only for a degraded "connecting" health (a network failure), not for every connect attempt. A new integration test runs the blocker with an outage longer than the health interval and a network-flavoured refresh cooldown at its cap; the first tool call succeeds ~1 s after the network returns. Refs #1929
Review round 5 (Opus), MINOR: TestNetworkRecovery_StalledRefreshLongOutage injected its in-outage refresh failure without ObservedRefreshToken, so the coordinator skipped the flight as superseded, the cooldown kept its 503 text and the server stayed Ready: the test only re-ran the refresh-mode path. It now passes the stored refresh token (as the RefreshManager's retry does), waits for the health check to move the server to Error, asserts the network flag, and restores the network at that moment - the timing in which the server used to fall out of the watcher. First successful call ~0.25 s after the restore; with the round-4 fixes removed it misses the 60 s bound. Refs #1929
CI (windows-latest) showed the network-recovery integration tests time out waiting for the outage to be noticed: Windows words a refused dial "connectex: No connection could be made because the target machine actively refused it." and a dropped connection "wsarecv: An existing connection was forcibly closed by the remote host.", which none of the text classifiers knew. A connected server's health check therefore never noticed a network drop on Windows and the server stayed Ready. isConnectionError, isTransientHealthCheckError (hard failures), isRemoteNetworkFailure and the health calculator's connection patterns and summaries now include the Windows wordings, verbatim from the CI log. Refs #1929
Review round 6 (Opus), MINOR: Windows words other network failures
differently again ("A socket operation was attempted to an unreachable
network.", "…did not properly respond after a period of time"), so a
phrase list cannot keep up. isConnectionError now treats any *net.OpError
as a connection error, and isTransientHealthCheckError decides a typed
socket error by type: a timeout is a soft miss, anything else is hard.
The health calculator's connection patterns gain the last Windows wording.
Refs #1929
… failure Release QA (integration 2965f50b2): /mcp call_tool_read qa-oauth:echo worked while /mcp/s/qa-oauth listed only describe_tool and echo answered "tool not found". Reproduced independently on main 6370f1f with isolated fixtures: a direct-catalog rebuild (any servers.changed) that runs while a CONNECTED server's tools/list fails transiently - here its OAuth token refresh was failing - publishes the catalog without that server's tools. The server then recovers on the same connection, no servers.changed follows, and the direct and single-server surfaces stay stale (still stale 120 s after the token endpoint recovered on main). - upstream.Manager.DiscoverToolsWithFailures reports the connected, enabled, non-quarantined servers whose tools/list did not succeed. - The direct rebuild retries while any such server exists: 5 s, doubling, capped at 30 s; a rebuild where every connected server listed clears it; Close stops it. Nothing stale is served in between. - An oauth.token_refreshed event rebuilds at once when a retry is pending, so the surfaces come back the moment the token does. Isolated repro, token endpoint failing then healthy: first successful token refresh +34.1 s (the refresh manager's own backoff), /mcp/s/qa-oauth republished 1 ms after it. Regression tests drive the single-server surface through a transient listing failure and recovery, and the retry's backoff and Close. Refs #1929
…ken save Review r7 on GH #1929: - Each retry of the direct rebuild lists every connected server, so a server whose tools/list fails for good kept the whole fleet re-listed every 30 s. The retry now stops after 6 attempts (about two minutes); the failed state is kept, so the next OAuth token save or servers.changed still rebuilds. - A retry timer's callback no longer clears a newer timer's reference. - A TLS alert from the peer ("remote error: tls: certificate required") is a credential fault, not a socket failure: the typed *net.OpError rule skips Op "remote error" and falls back to the text rules. Release QA clocks showed the network watcher's direct token refresh emits no oauth.token_refreshed, so the scoped surface waited for the retry timer. A runtime token-saved observer (every refresh path, run off the save path) now triggers the pending rebuild; it also covers the case after the retries stop.
Dumbris
force-pushed
the
fix/1929-network-recovery
branch
from
November 18, 2026 16:42
3c9585c to
8c35f9c
Compare
Dumbris
enabled auto-merge (squash)
November 18, 2026 17:06
Dumbris
disabled auto-merge
November 18, 2026 18:37
CI on #1931 (Build Binaries linux/arm64): TestNetworkRecovery_StaticHeaderAnd OAuthRecoverWithin60s left oauth-upstream in Error with "endpoint deprecated (410 Gone)" after the network returned. Both isDeprecatedEndpointError copies (core and managed) matched "410", "gone", "removed" and similar anywhere in the error text, so a reconnect failure naming an address such as 127.0.0.1:41039 was turned into ErrEndpointDeprecated on the OAuth initialize path: not a network failure, so recovery stopped. With the test relay pinned to 127.0.0.1:41039 the old classifier fails with exactly that message and the new one recovers in about 8 s; the CI run's relay port was not logged. Both copies now call transport.LooksLikeDeprecatedEndpoint: - the typed ErrEndpointDeprecated anywhere in the chain, or an HTTPError, decide by status (410 only); - a socket, DNS, url.Error or context failure is never a deprecation, whatever address or URL its text names; - when the text carries a response status ("status 500: ...", "status code: 410"), that number alone decides, so a 5xx/4xx body saying "gone away", "removed" or "order 410" does not; - otherwise "410 gone" and the existing phrases. The status-keyed rule and its non-410 body tests are by Codex.
Dumbris
enabled auto-merge (squash)
November 18, 2026 18:52
Dumbris
disabled auto-merge
November 18, 2026 19:42
…g saved Windows CI on #1931 (Build Binaries windows/amd64): TestNetworkRecovery_ConnectedServerWithStalledRefreshRecovers recovered (first call 253 ms after the network returned, token refreshed) and then still read TransientlyFailing=true. A successful refresh commits the new token to bbolt and only then calls NoteTokenSavedFor, which clears the transient state. Readers see the committed meta page while the writer is still syncing, and the sync is slow on Windows, so a tool call could already succeed with the new token while the coordinator still said the refresh was failing. RefreshCoordinator.BeginTokenSaveFor marks a successful token response as being stored; while any save is in progress TransientlyFailing and TransientRefreshStatus report nothing. All three save paths (PersistentTokenStore, coordinatedMemoryTokenStore, the stored-DCR refresh in core) begin before the write and end, deferred, after NoteTokenSavedFor. A save that fails or is discarded leaves the earlier transient state as it was. The test assertions are unchanged. Tests: the persist hook observes no transient failure during a save (fails without the change); an ended save without success keeps the failure. The integration test passes -count=20 and GOMAXPROCS=1 -count=20 under -race.
Dumbris
enabled auto-merge (squash)
November 18, 2026 20:44
Contributor
📦 Build ArtifactsWorkflow Run: View Run Available Artifacts
How to DownloadOption 1: GitHub Web UI (easiest)
Option 2: GitHub CLI gh run download 44385534618 --repo smart-mcp-proxy/mcpproxy-go
|
|
Codecov Report❌ Patch coverage is 📢 Thoughts on this report? Let us know! |
Dumbris
added a commit
that referenced
this pull request
Nov 19, 2026
…1934) ## Summary `TestRetire_HTTPDialParked_OldEndpointReceivesNothing/http/remove` failed once in the shuffled unit-test job on #1931 (job 135134947938, seed `1795038088268204092`) with `expected: 0, actual: 3` requests and 0 Authorization headers. This PR makes the retire fixture count only its own endpoint's traffic. It is a test-only change; no production code is touched. ## Classification: fixture contamination, not a retirement defect - **The retired instance did not send it.** The instance under test only ever sends `Authorization: Bearer qa-secret…`, and the CI run counted 0 Authorization headers next to the 3 requests. - **The test is clean in isolation.** On main `898572804`: 300/300 runs under `-race` and 100/100 with `GOMAXPROCS=1` (6 subtests each). The full package with the CI seed passes 3/3 on macOS and 6/6 on Linux (Docker, ephemeral port range narrowed to 1,024 ports). - **Senders seen directly.** In a scratch copy, every upstream request was tagged with its server and creating test, and a trap bound the free ports during the retire subtests. With only `internal/upstream` running, the trap caught 0 requests. With `server`, `runtime`, `httpapi` and four more packages running in parallel, as `go test ./...` does on CI, it caught 535 requests in two iterations: - `POST /` `initialize` with no Authorization, tagged e.g. `github|TestCallTool_ProfileV3_RestDispatchPreservesTypedRefusal`. 29 of the 30 tagged tests are in `internal/server`; the 30th tag carried a server name but no test name. - `GET /` listen streams and `DELETE /` closes with stale session ids. - **Which these are.** Clients from `internal/server` tests keep reconnecting to the ports of their own closed counting upstreams. When the OS reuses one of those ports for this fixture, the traffic lands here. - **What is shown and what is inferred.** The multi-package run shows this traffic exists and has the CI failure's shape: requests without credentials, three per reconnect attempt. That this exact traffic caused the historical CI run is inferred, not traced; the CI job kept no per-request record. The same class as the stray-client isolation in #1918's `dc864055d`, here across processes. ## Fix - The fixture serves its endpoint under a unique path (`/fx-<random>/mcp`, or `/fx-<random>/sse` with `WithStaticBasePath`). - It counts a request when its path carries that token, with or without credentials, or when it carries the fixture's own credential on any path. `httpServerConfig` now gives each fixture a unique bearer. - Origin-level OAuth paths are counted whoever sends them, so the fixture fails closed. These are `/.well-known/*` and mcp-go's default `/authorize`, `/token` and `/register`, which an OAuth attempt may reach without the token or a credential. This was review round 1, from gpt-6.1-sol. - Everything else is answered 404 and kept in `strays()`. - The handler and every field are in place before `Start`. - The zero-request assertions are unchanged. New tests: - `TestRetire_HTTPDialParked_StrayTrafficOnThePortIsNotTheOldEndpoint` runs the parked-dial scenario while a stranger sends `POST /`, `GET /` and `DELETE /` to the port. With the old fixture it fails exactly like CI, for both http and sse: `expected: 0, actual: 3`. - `TestCountingUpstream_CountsItsEndpointAndItsCredentialAnywhere` holds the controls. A request to the endpoint without credentials is counted. The fixture's credential on another path is counted. Origin-level OAuth paths are counted. Strangers on other paths, with or without their own credential, are not counted. ## Verification (macOS, `-race` unless noted) | Run | Result | |---|---| | `-run 'Retire\|CountingUpstream' -count=20` | ok | | same, `GOMAXPROCS=1 -count=10` | ok | | full package, CI seed, CI skip list | exit 0 | | full package, CI seed, under CPU load, 3 runs | exit 0 ×3 | | full package, `-shuffle=on -count=2` | ok | | golangci-lint v2 (`.github/.golangci.yml`), bare and `--build-tags server`, new from `origin/main` | 0 issues each | One earlier full-package run with the CI seed reported `FAIL` while both lint runs loaded the machine. Its output was not captured: the command kept only the last line. The later runs listed above used the final handler ordering and all passed. That failure is reported here as uncaptured, not as explained. A note on the barrier itself: disabling the retired checks in `dialgate`, plus connect cancellation in the managed client, still produced no traffic in the parked scenario, because further guards stop the dial. That is unchanged by this PR. The fixture's detection is covered by the control test above. ## Review | Round | Reviewer | SHA | Result | |---|---|---|---| | 1 | opencode `gpt-6.1-sol`, fixture chunk | `8b0057b05` | 1 medium: origin-level OAuth paths uncounted. Fixed in `6e7f49ad8` | | 2 | `gpt-6.1-sol`, fixture / tests | `6e7f49ad8` | CLEAN / 2 P2: exact stray counts, missing controls | | 2 | Claude Opus 5.5 | `6e7f49ad8` | same medium, plus 2 low. Fixed in `467da1fd5` | | 3 | Claude Opus 5.5 | `467da1fd5` | CLEAN: 11 filter mutations killed; real connects and the full OAuth fallback counted, 0 strays | | 3 | `gpt-6.1-sol`, tests | `467da1fd5` | 1 P3: shared stray marker. Fixed in `c1690a366` | | 4 | `gpt-6.1-sol` | `c1690a366` | P3 fixed; 1 P2: unbounded hook waits. Fixed in `e62c7610c`. The first try returned no verdict and was not counted | | 5 | `gpt-6.1-sol` | `e62c7610c` | CLEAN | | 5 | Claude Opus 5.5 | `e62c7610c` | CLEAN: 13 filter and recording mutations killed | Follow-ups, not blocking: - Add a control row for a foreign credential on the endpoint path, so the `auth` counter's "any Authorization" rule is pinned. Opus low; the request counter already catches it. - Rewrap one 113-character comment line. ## Not in this PR The `internal/server` tests that leave reconnecting clients behind are the source of the stray traffic. They are a separate cleanup. ## Merge condition Both reviewers are clean on `e62c7610c`. Merge that exact SHA once CI is green; if the head moves, review it again. Auto-merge is not armed.
Dumbris
added a commit
that referenced
this pull request
Nov 19, 2026
…ient outlives its test (#1936) ## Summary Test-only. `internal/server` fixtures created `upstream.Manager`s and never shut them down. Each one kept its network-recovery watcher (#1931) running, and its clients kept reconnecting to their fixture's closed port, for the rest of the package run. Those reconnects are the stray traffic that #1918 (fresh-process allocation tests) and #1934 (retire-fixture isolation) worked around. This PR fixes the source. The numbers below come from the end of a full `go test -v -race -timeout 60m -coverprofile … -skip "E2E|Binary|MCPProtocol|TestInfoEndpoint|TestGracefulShutdownNoPanic|TestSocketInfoEndpoint" ./internal/server/` run: | | goroutines | `(*networkRecovery).run` | `startOAuthEventMonitor` | lumberjack `millRun` | |---|---|---|---|---| | main 58a824e | 3196 | **1273** | 44 | 276 | | this branch | 739 | **0** | 0 | 0 | To find the sources, I labelled each watcher goroutine with the test frame that created it (a temporary local patch, not committed). Every leaked watcher came from a direct `upstream.NewManager` in a test file. `createTestProxyWithRuntimeCfg` alone accounted for about 70% of them. None came from a runtime or server that wasn't closed. ## Changes - **`newTestUpstreamManager` / `shutdownUpstreamOnCleanup`** (`upstream_fixture_cleanup_test.go`): all 37 direct `upstream.NewManager` calls in the package now call `ShutdownAll` when the test ends. This includes the shared `createTestProxyWithRuntimeCfg`. - **`stopUpstreamBeforeFixtureClose`**: some fixtures start their upstream after the manager exists: `startCountingUpstream` and the prompt-upstream helpers in `mcp_prompt_scope_test.go` and `scope_retained_effects_test.go`. They now remove the client in a cleanup registered after the listener's close, so it runs first: the client disconnects while the stub still listens and never redials a closed port. The old `DisconnectAll` cleanups in the prompt loops ran after the fixture had already closed. - `mcp_code_execution_test.go` (package `server_test`) defers the shutdown so it runs before the storage close it depends on. - `scope_latency_test.go` inlines the shutdown, because `scope-latency.yml` copies that one file onto the merge-base checkout, where the helper doesn't exist. - **Guard**: a new `TestMain` (`leak_guard_main_test.go`) fails an otherwise passing run if any `(*networkRecovery).run` goroutine is still alive after the last test. It polls for up to 10s and prints the first 5 stacks. I checked that it catches a leak: with the helper's shutdown commented out, `-run TestAggregatedPrompt_ScopeUsesCanonicalOwner` fails with "2 upstream.Manager network-recovery watcher(s) still running". - `MCPPROXY_NETWORK_RECOVERY=off` is not set anywhere. No production code changed. The leaks were all in test fixtures. ## Found, not fixed (production shutdown gap) The 739 goroutines that remain are mostly 227 × `(*Server).forwardRuntimeStatus` and 227 × `(*Server).listenForRoutingModeRefresh`. `NewServer` starts both (`server.go:488`, `:504`), and `Server.Shutdown` stops neither: - `listenForRoutingModeRefresh` ranges over a `SubscribeEvents` channel that is never unsubscribed. - `forwardRuntimeStatus` ranges over `Runtime.statusCh`, which nothing closes. They sit idle on a channel receive and send no network traffic. They are harmless in a real process, which exits after `Shutdown`. In tests they are still 2 leaked goroutines per server. I left them for a separate production change. ## Verification - Full `internal/server` race run: `ok … 1457.449s coverage: 83.5%`, and the guard passes. - `golangci-lint run --config .github/.golangci.yml --new-from-rev=origin/main ./...`, bare and `--build-tags server`: 0 issues.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Description
Release 1 of the recovery work for #1929: remote HTTP/SSE upstreams come back on their own within seconds of the network returning, instead of sitting in Error for up to 30 minutes after a laptop wakes.
Cause. While the machine sleeps, every reconnect attempt fails on DNS lookups or timeouts and advances the backoff. After 20 failures the client gives up and only the supervisor's 30-minute probe retries it (
types.GaveUpProbeInterval). Nothing reset that when the network came back. On top of that, an HTTP initialize timeout was rewritten into the stdio-only text "produced no stderr output … help banner" without wrapping the deadline. So it was not even recognised as a network failure.Changes
core.IsNetworkError) is recorded withStateManager.SetNetworkErrorand reported asConnectionInfo.NetworkFailure. It advances the backoff exactly as before, and every other state write clears it.internal/upstream/network_recovery.go) handles servers whose current failure is a network failure:Retry-Afterwindow ([Bug]: connect retries ignore Retry-After on 429 (remaining ask from #1013) #1040), logged out, retired, removed or local (stdio). A server whose host answers all along while the server itself keeps failing is left to the normal backoff.RefreshCoordinator.ClearTransientCooldown). Refreshes that failed while offline therefore do not make the reconnect wait up to 5 minutes. A revoked grant stays latched.http://proxy, anhttpsupstream is probed withCONNECTand must get a 2xx back. A plain-httpupstream, or one behind anhttps://or SOCKS proxy, is probed at the proxy only.StateManager.ClearNetworkBackoff).MCPPROXY_NETWORK_RECOVERY=offturns the watcher off.MCPX_HTTP_TIMEOUT, not the stdio handshake timeout.docs/configuration/upstream-servers.md, and the new variable indocs/configuration/environment-variables.md.Not in this release (from the issue's proposal list):
reconnect_on_useon by default, pausing the retry loop while offline, a configurable maximum backoff, and native OS wake/network notifications. HenceRefs, notCloses.Testing
End to end (
internal/upstream/network_recovery_integration_test.go). Real managed clients reach the repo's OAuth/MCP test server through a TCP relay the test turns off and on.Unit tests run the watcher on a fake clock, covering:
CONNECTprobe through a fake proxy.Managed-client tests cover:
Retry-After, OAuth, terminal and retired servers;The refresh-coordinator tests show the cooldown clear keeps the terminal latch. The core test checks the HTTP timeout wording and its classified code.
Live, on the real
mcpproxy servebinary built atd4187a1c4. A static-header upstream sat behind a relay process that was killed and restarted; the core was frozen with SIGSTOP/SIGCONT as a stand-in for sleep.Not covered: a real macOS sleep/wake cycle. SIGSTOP stands in for it, and wake is detected from the clock, not from native OS notifications.
Race and lint:
go test -race ./internal/upstream/... ./internal/oauth/...passes at3d04f8ae2;./internal/upstream/...again atd4187a1c4, and./internal/upstreamat41b0117cb.golangci-lintwith.github/.golangci.yml, bare and with--build-tags server: 0 issues.Independent review by an Opus 5.5 agent with fresh context, three rounds:
Release QA follow-up (
881713a3d,db3083075,2468ca3a3).Connected OAuth server with a stalled token refresh (QA
cooldown-503):invalid_grantstays latched; quarantined, disabled and logged-out servers are excluded; the same budget applies.Operator wording (verified live on a
41b0117cbcore and a new core side by side):Reconnecting: <cause>, with CLI STATUSConnectingand the next attempt time inhealth.detail.doctorno longer lists it, and the Web UI shows an amber "Reconnecting automatically" panel.Results:
db3083075(same production code as head2468ca3a3):mainversus 2.2 s with this PR;Review: Opus 5.5 rounds 4 and 5. Round 4 found 1 MAJOR and 3 MINOR, all fixed except the refresh-cap note below; round 5 was CLEAN.
Windows (
da121e773,f65e58892): the integration tests timed out on the Windows runner. Windows words socket failures differently ("actively refused", "forcibly closed by the remote host"), so an outage was not recognised. The classifiers now decide a typed*net.OpErrorby type: a timeout is a soft miss, anything else is a hard failure. The Windows phrases were added too. A TLS alert from the peer (Op "remote error", e.g. a rejected client certificate) is excluded, because it is a credential fault. Opus round 6: CLEAN.Single-server surface
/mcp/s/<server>stale after a token stall (99bf90d3c,8c35f9c27; QA int8 observation, reproduced onmain6370f1f):servers.changed) that ran while a connected server'stools/listfailed, because its token refresh was failing, published the catalogue without that server's tools./mcp/s/<server>listed onlydescribe_tool, and its tools answered "tool not found", while/mcprouter calls worked.mainthe surface was still stale more than 120 s after the token endpoint recovered.upstream.Manager.DiscoverToolsWithFailuresnames the connected servers whose listing failed.Runtime.AddTokenSavedObserver, any refresh path) rebuilds at once while such a server is pending. This covers the network watcher's direct refresh, which emits nooauth.token_refreshed, and the time after the retries stop.TestSingleServerSurface_RecoversAfterATransientListingFailureTestDirectRebuildRetry_BacksOffAndStopsOnCloseTestDirectRebuildRetry_GivesUpThenRebuildsOnTokenRefreshTestTokenSavedObserversRunOffTheSavePathClocks on the
8c35f9c27tree (isolated live core plus fixtures, T0 = token endpoint healthy or network back, calls polled every ~0.5 s):The scoped surface now republishes within 1 ms of the refresh. The 33 s and 123 s rows measure the refresh manager's provider backoff after an outage of the token endpoint alone, with the network up, which this PR leaves as it was.
Review: Opus round 7 asked for the retry cap, the timer-reference fix and the TLS-alert exclusion, all done. Round 8: CLEAN. Race tests pass for
./internal/server(40 m timeout),./internal/runtimeand./internal/upstream/.... Lint reports 0 new issues in both editions.Known gaps, by the reviewer and me:
httpupstream, or one behind anhttps://or SOCKS proxy, is probed at the proxy only, so a local proxy that stays up still hides an outage there.needs_config, action Edit URL).servers.changed, so a server whoseprompts/listfailed during a token stall stays missing from them until the next server change (follow-up).servers.changed. Several token saves at once can also queue back-to-back rebuilds, whichdirectRefreshMuserialises.-o json).Refs #1929