GeezerVison is showing github.com — fix(mcp): reconnect dropped servers with backoff by afonsoft · Pull Request #54378 · anomalyco/opencode
Conversation
afonsoft
commented
Oct 10, 2026
•
edited by opencode-agent
Bot
Loading
Uh oh!
There was an error while loading. Please reload this page.
Issue for this PR
Relates to #52943 (the V1 version of this fix).
Type of change
What does this PR do?
A dropped MCP server stayed failed until the next config change or manual reconnect: connection.onClose marked it failed, cleaned up, and nothing ever retried. A flaky stdio process or transient network cut therefore disabled the server permanently for the lifetime of the app.
packages/core/src/mcp/index.ts now retries failed servers with backoff:
- A new
scheduleReconnect(name, entry) funnel is invoked from connection.onClose (dropped connection) and from startServer's failure tail (never-connected startup), so both paths get retries.
- It spawns a detached retry fiber (
reconnecting dedupes concurrent schedulings). Each attempt takes the per-server KeyedMutex lock only for the duration of startServer, so backoff sleeps never block user-driven connect/disconnect or reconcile-driven replace/remove on the same server.
- A 500ms grace period precedes the first attempt: a drop often coincides with an in-flight reconcile that is about to replace or remove the entry — respawning instantly would race it.
- Attempts bail when the entry was replaced in
entries, when the config is disabled, or when the status is no longer failed (e.g. a user-driven connect landed). Up to 10 attempts on an exponential 1s-jittered schedule.
New test reconnects a dropped local MCP server as a fresh process spawns a real stdio server (test/fixture/mcp-reconnect.cjs records each spawned pid), kills it, and asserts the service reconnects a fresh process — not just a status flip.
How did you verify your code works?
bun test test/mcp.test.ts in packages/core: 78/79 pass. The one failure — MCP connection over the modern protocol > exposes every connection operation — fails identically on clean dev (pre-existing 5s timeout).
bun typecheck in packages/core: clean.
- The new test fails before the change (no reconnect: single pid, 5s timeout) and passes after (~160–380ms to a fresh pid).
Screenshots / recordings
N/A — headless MCP lifecycle.
Checklist
- I have tested my changes locally
- I have added tests that prove my fix is effective or that my feature works
- I have added necessary documentation (where appropriate)
Added by the opencode bot (AI-generated).
Related: #52237, #52564, #48743
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
yuji-hatakeyama and loeakaodas reacted with thumbs up emoji
|
cc @thdxr — this is the V2 port of #52943 you asked for after the V1 closure. Rebased onto current dev; details in the description.
|
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
|
The following comment was made by an LLM, it may be inaccurate:
|
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The fix works for the tested case. The new test times out on the base (the killed stdio server is never respawned) and passes with this change. bun test test/mcp.test.ts gives the same results as the base apart from the new test (one timeout failure exists in both), and bun run typecheck in packages/core is clean.
Public API: unchanged. Retries do add extra McpEvent.StatusChanged events (pending → failed) while a server is retrying.
The retry loop has problems worth fixing before merge (details inline):
- It runs in a detached fiber, so it can outlive the service or location and spawn a process after teardown.
- Duplicate retries are blocked by server name, not by entry, so a replaced config that then fails to start is never retried.
- The 500ms grace period runs inside the per-server lock, so it doesn't prevent the race with reconcile it is meant to avoid, and it holds the lock on every attempt.
Minor: the test's const dir = await tmpdir() never removes the directory. await using dir = await tmpdir() (or tmpdirScoped) would clean it up.
Fixes #53226
Related: #52237, #52564, #48743
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
|
|
name: ServerName,
|
|
|
entry: ServerEntry,
|
|
|
): Effect.fn.Return<void, never, never> {
|
|
|
if (reconnecting.has(name)) return
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Duplicate retries are blocked by name, but each loop belongs to one entry. Suppose a loop for the old entry is running (sleeping in backoff, or queued for the lock) and reconcile replaces the server. If the new entry's first startServer fails, its scheduleReconnect(name, newEntry) returns here because the name is still in reconnecting. On its next attempt the old loop sees entries.get(name) !== entry, returns successfully and clears the name, so the new config is never retried. Tracking the entry (for example a Map<ServerName, ServerEntry>, or a flag on the entry itself) would avoid this.
Effect.forkDetach takes the retry loop out of the service's lifetime. When the location's layer shuts down (#51730 and #53366 are tightening this), a loop that is sleeping or waiting for the lock keeps going and can call startServer → Scope.fork(root) after root has closed, which can leave an orphaned stdio process (#50363). The rest of this file forks with the scoped fork FiberSet runtime, so that teardown interrupts the fibers. Using fork(...) here would give the same guarantee.
This sleep runs inside locks.withLock(name) (line 395 wraps the whole generator). So each attempt takes the lock, then waits 500ms. A reconcile replaceServer or removeServer that arrives during the drop waits behind it. When the sleep ends, entries.get(name) === entry still holds and the process is respawned anyway, just before reconcile replaces it, which is the race the comment says it avoids. The wait also repeats on every retry and holds up user connect and disconnect meanwhile. Sleeping before taking the lock, and only for the first attempt, would match the description.
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
|
@opencode-agent[bot] — all four points addressed in the follow-up commit:
- Layer lifetime:
Effect.forkDetach → scoped fork (the same FiberSet runtime the rest of this file uses), so teardown interrupts a sleeping/queued retry loop instead of letting it call Scope.fork on a closed root.
- Per-entry dedup:
reconnecting is now Map<ServerName, ServerEntry>; scheduling checks reconnecting.get(name) === entry so a replaced config's first failure gets its own loop, and ensuring only deletes when the map still points at that entry (a stale loop can't clear the new entry's mark).
- Grace period placement: the 500ms delay and the exponential backoff both run outside
locks.withLock — the delay once, before the first attempt; each attempt then takes the lock only for startServer.
- Test cleanup:
await using dir = await tmpdir().
Re-ran bun test test/mcp.test.ts: 78/79 (only the pre-existing exposes every connection operation timeout that also fails on dev).
|
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
All four earlier concerns are resolved in b0adb1a:
- The retry loop now runs on the service's own scoped
fork runtime, so shutting down the service stops it.
- Retries are tracked per entry, so a replaced config gets its own loop. A stale loop gives up without spawning anything and only clears its own mark.
- The grace period runs once, before the first attempt. Both it and the backoff happen outside the per-server lock, which is now held only around
startServer.
- The test cleans up its temp directory.
I reran bun test test/mcp.test.ts in packages/core: 78 pass, and the one failure (terminates MCP descendants after the wrapper exits successfully) fails on the base too. The new reconnect test passed 3/3 alone; it timed out on the base last round. bun run typecheck is clean.
Public API: unchanged.
No remaining concerns.
Related: #52237, #52564, #48743
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
This was referenced Oct 19, 2026
This was referenced Oct 28, 2026
This was referenced Nov 6, 2026
This was referenced Nov 14, 2026
This branch has not been deployed
No deployments
Uh oh!
There was an error while loading. Please reload this page.
Assignees
No one assigned
Milestone
No milestone
Development
Successfully merging this pull request may close these issues.
Uh oh!
There was an error while loading. Please reload this page.
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.
|