Repository navigation
fix(agent-core-v2): reconnect MCP servers automatically after transient failures - #4283
Conversation
🦋 Changeset detectedLatest commit: 5493e2d The changes in this PR will be included in the next version bump. This PR includes changesets to release 1 package
Not sure what this means? Click here to learn what changesets are. Click here if you're a maintainer who wants to add another changeset to this PR |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
commit: |
652e28e to
d0d17c2
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 652e28e39c
ℹ️ About Codex in GitHub
Codex has been enabled to automatically 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 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| } | ||
| if (error instanceof Error2 && error.code === ErrorCodes.CONFIG_INVALID) return true; | ||
| if (error instanceof Error && error.message === MCP_STDIO_RUNTIME_REQUIRED_MESSAGE) return true; |
There was a problem hiding this comment.
Stop retrying rejected static credentials
When a workspace HTTP/SSE server uses pinned headers or bearerTokenEnvVar and the remote returns 401, shouldMarkNeedsAuth deliberately leaves it in failed, but this permanent-failure classifier does not recognize the authorization failure, so production's retry-enabled manager reconnects forever. Wrong static credentials cannot heal without a config change—which already initiates a connection—and repeated authentication attempts can cause rate limiting or account lockout; classify these failures as permanent or provide a real retry-off setting, since the new positive delay tunables cannot restore the previous zero-retry behavior.
AGENTS.md reference: AGENTS.md:L114-L116
Useful? React with 👍 / 👎.
| "@moonshot-ai/kimi-code": patch | ||
| --- | ||
|
|
||
| Reconnect MCP servers automatically with backoff when the initial connection fails or the connection drops, so their tools come back on their own; tune the interval with `[mcp] reconnect_initial_delay_ms` and `reconnect_max_delay_ms`. |
There was a problem hiding this comment.
Scope the changelog claim to workspace MCP servers
This user-facing sentence says MCP servers reconnect generally, but retries are opt-in and only the workspace baseline manager enables them; the sessionOverlay manager still leaves session-scoped ephemeral servers terminally failed. Qualify the release note as workspace-level/baseline MCP behavior so ephemeral-MCP users are not promised recovery that the implementation intentionally excludes.
AGENTS.md reference: AGENTS.md:L90-L90
Useful? React with 👍 / 👎.
| # reconnect_initial_delay_ms <- KIMI_MCP_RECONNECT_INITIAL_DELAY_MS (custom parse) | ||
| # reconnect_max_delay_ms <- KIMI_MCP_RECONNECT_MAX_DELAY_MS (custom parse) |
There was a problem hiding this comment.
Document the reconnect settings in the public config references
The new config keys and environment variables appear only in the generated manifest and changeset, while both English and Chinese configuration/config-files.md, configuration/env-vars.md, and the MCP customization page still enumerate only the startup/tool timeout controls. Users therefore cannot discover the reconnect defaults, valid range, precedence, or workspace-only scope from the configuration documentation; add both language variants alongside the existing MCP settings.
Useful? React with 👍 / 👎.
| // interruptionReminder.recorded interruptionReminder src/agent/interruptionReminder/interruptionReminderOps.ts | ||
| // llm.request llm.requestTrace src/agent/llmRequester/llmRequestOps.ts | ||
| // llm.tools_snapshot llm.requestTrace src/agent/llmRequester/llmRequestOps.ts | ||
| // mcp.server_failed (none) src/agent/mcp/mcpFailureOps.ts |
There was a problem hiding this comment.
Register the failure record in every wire inventory
Adding this durable type makes at least two existing tests fail: packages/agent-core-v2/test/index.test.ts rejects every EVENT2_REGISTRY type absent from its v1/v2 vocabulary sets, and apps/vis/web/test/renderers.test.ts requires every manifest type to have a WIRE_RENDERERS entry. Neither inventory contains mcp.server_failed, and McpServerFailed is also missing from the agent-core root exports used by the visualizer; export the payload and update the vocabulary, AgentRecord union, projector handling, and renderer together.
AGENTS.md reference: AGENTS.md:L122-L124
Useful? React with 👍 / 👎.
d0d17c2 to
f52924f
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: f52924f927
ℹ️ About Codex in GitHub
Codex has been enabled to automatically 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 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| } | ||
| if (error instanceof Error2 && error.code === ErrorCodes.CONFIG_INVALID) return true; | ||
| if (error instanceof Error && error.message === MCP_STDIO_RUNTIME_REQUIRED_MESSAGE) return true; | ||
| if (!isUnauthorizedLikeError(error)) return false; |
There was a problem hiding this comment.
Stop retrying static-credential 403 responses
Fresh evidence beyond the earlier 401 case: isUnauthorizedLikeError recognizes only 401/UnauthorizedError, so an HTTP or SSE server that rejects pinned headers or bearerTokenEnvVar credentials with the equally common 403 Forbidden response is classified as transient here and retried forever. This also contradicts the new MCP documentation's promise that rejected static credentials remain failed without retries; recognize 403 for static-credential configurations or provide a retry-disable escape hatch.
AGENTS.md reference: AGENTS.md:L114-L116
Useful? React with 👍 / 👎.
| reconnectInitialDelayMs: McpTimeoutMsSchema.optional(), | ||
| reconnectMaxDelayMs: McpTimeoutMsSchema.optional(), |
There was a problem hiding this comment.
Expose reconnect tunables through the SDK config schema
When SDK users try to inspect or set these new controls, packages/node-sdk/src/config/schema.ts still defines McpConfigSchema with only startupTimeoutMs and toolTimeoutMs; both the public KimiConfig return type and KimiConfigPatch derive from that schema. Consequently the v2 config mapper can return these runtime fields only through an unsound cast, while typed harness.setConfig({ mcp: ... }) callers cannot express either documented reconnect setting. Add both fields to the public SDK schema and its config round-trip tests.
AGENTS.md reference: AGENTS.md:L122-L124
Useful? React with 👍 / 👎.
| async markRemoved(name: string): Promise<boolean> { | ||
| const entry = this.entries.get(name); | ||
| if (entry === undefined) return false; | ||
| this.clearReconnectRetry(entry); |
There was a problem hiding this comment.
Invalidate in-flight retries before tombstoning a server
When a config or plugin removes a server after its retry timer has already fired, clearing retryTimer cannot cancel the reconnect now running, and markRemoved leaves both the map entry and attemptId unchanged while awaiting the close. That reconnect therefore still passes isCurrent after the tombstone and can overwrite removed with failed or connected, schedule another retry, and re-register tools for a server the user removed. Increment/invalidate the attempt before closing, or join and cancel the in-flight reconnect before publishing removed.
AGENTS.md reference: AGENTS.md:L130-L132
Useful? React with 👍 / 👎.
f52924f to
3b69a99
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 3b69a990f5
ℹ️ About Codex in GitHub
Codex has been enabled to automatically 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 👍.
When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".
| entry.error = undefined; | ||
| this.emit(entry); | ||
| await this.connectOne(entry, attemptId); | ||
| this.transition(entry, { type: 'kick' }); |
There was a problem hiding this comment.
Join automatic retries instead of restarting them
When an already-connected server drops, its stale registered tools remain callable while the backoff scheduler starts a new handshake directly via retryDue; that attempt is never entered in inFlightReconnects. A tool-call heal or manual reconnect during a slow handshake therefore reaches this unconditional kick, invalidates and closes the automatic attempt, and starts over. Repeated stale tool calls can continually restart startup and prevent recovery, so scheduled attempts need to participate in the same join chain or reconnect must join entry.attemptPromise while the entry is already connecting.
Useful? React with 👍 / 👎.
| if (error instanceof HostProcessError && error.code === HostProcessErrorCode.SpawnFailed) { | ||
| return new McpClassifiedStartupError('config', error.message, { cause: error }); | ||
| } |
There was a problem hiding this comment.
Keep transient spawn failures retryable
When stdio startup fails because the host temporarily cannot spawn another process, this classifies every HostProcessErrorCode.SpawnFailed as permanent configuration failure. HostProcessService.spawn uses that same code for all child-process spawn rejections and preserves the underlying errno, including recoverable resource-pressure cases such as EAGAIN, EMFILE/ENFILE, or ENOMEM; those servers now remain terminally failed even after the condition clears. Inspect the stored errno and reserve config classification for genuinely permanent executable/configuration errors.
Useful? React with 👍 / 👎.
| readonly status: McpServerStatus; | ||
| readonly toolCount: number; | ||
| readonly error?: string; | ||
| readonly nextRetryAt?: number; |
There was a problem hiding this comment.
Propagate retry deadlines through client contracts
When a server is waiting to retry, the manager now returns nextRetryAt, but the Klient mcpServerEntrySchema omits it and Zod output validation strips unknown properties; the node SDK's McpServerInfo and observable McpServerStatusPayload omit it as well. Consequently Klient, SDK, and event consumers cannot observe the retry deadline represented by this new exported field. Mirror it through those public contract surfaces and their parity tests.
AGENTS.md reference: AGENTS.md:L122-L124
Useful? React with 👍 / 👎.
| if (fromFamily && !toFamily) { | ||
| const client = entry.client; | ||
| entry.client = undefined; | ||
| if (client !== undefined) void this.closeRuntimeClient(client); |
There was a problem hiding this comment.
Await old clients before starting replacement connections
When a manual reconnect or config upsert replaces a connected/probing server, this launches client shutdown without awaiting it and the same transition immediately starts the replacement attempt; previously reconnect awaited closeClient first. A stdio server that releases a singleton lock or listening port only on exit, or an HTTP server that completes session cleanup during close, can therefore reject the replacement while the old client is still alive—leaving retry-disabled session overlays failed and making :restart or a config edit unreliable. Sequence the close into the asynchronous reconnect before creating the new client.
AGENTS.md reference: AGENTS.md:L110-L112
Useful? React with 👍 / 👎.
| function classifyStartupFailure(error: unknown): McpFailureKind { | ||
| if (error instanceof McpClassifiedStartupError) return error.failureKind; | ||
| if (error instanceof Error2 && error.code === ErrorCodes.CONFIG_INVALID) return 'config'; | ||
| return 'transport'; |
There was a problem hiding this comment.
Stop retrying deterministic discovery failures
When the transport connects but tool discovery deterministically fails—for example, listTools returns an MCP MethodNotFound error or assertMcpInputSchema rejects a malformed tool schema—the error reaches this fallback and is classified as a transport failure. Workspace managers then retry forever even though the same server response cannot heal without a server or configuration change, whereas these inputs previously settled in failed; classify protocol/application discovery errors as permanent while keeping connection and timeout failures transient.
AGENTS.md reference: AGENTS.md:L110-L112
Useful? React with 👍 / 👎.
| declare readonly _serviceBrand: undefined; | ||
| private readonly mcpTools = new Map<string, McpToolRegistration>(); | ||
| private readonly pendingDiscoveries: Array<() => void> = []; | ||
| private readonly failedServerEpisodes = new Set<string>(); |
There was a problem hiding this comment.
Persist failure-episode deduplication across agent reconstruction
When an agent scope is reconstructed while its workspace server remains in the same failed retry episode—for example after subagent-scope cache eviction and resume—this in-memory set starts empty, and attachMcpTools immediately records another durable mcp.server_failed for the unchanged failed entry. The wire therefore accumulates duplicate records for one episode despite the advertised once-per-episode contract; restore the deduplication state from durable agent state or the journal rather than tying it to one service instance.
AGENTS.md reference: AGENTS.md:L122-L124
Useful? React with 👍 / 👎.
| case 'retryWaiting': { | ||
| entry.error = plan.error; | ||
| const delayMs = this.nextRetryDelayMs(entry.failureStreak); | ||
| entry.failureStreak = Math.min(entry.failureStreak + 1, MAX_FAILURE_STREAK); | ||
| entry.nextRetryAt = Date.now() + delayMs; |
There was a problem hiding this comment.
Reschedule pending retries when tunables reload
When config.toml is hot-reloaded while a server is already in retryWaiting, the new reconnect delay or cap is visible through resolveDefaults only on a later failure; the existing nextRetryAt is fixed here and no MCP listener recomputes it. Lowering an accidentally large reconnect_initial_delay_ms or reconnect_max_delay_ms can therefore leave the server waiting on the old deadline—potentially for days—despite configuration reload being enabled, so reschedule waiting entries when the [mcp] section changes.
AGENTS.md reference: AGENTS.md:L110-L112
Useful? React with 👍 / 👎.
3b69a99 to
176879a
Compare
…nt failures - serialize per-server connection, probe, close, and OAuth transitions - retry transient startup and session failures with live backoff settings - persist failure episodes and expose retry timing across client contracts
176879a to
5493e2d
Compare
|
Codex Review: Didn't find any major issues. Keep it up! Reviewed commit: ℹ️ About Codex in GitHubCodex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback". |
Kimi Code 2.4.0 (MoonshotAI/kimi-code#4283) reconnects workspace-level MCP servers automatically after transient failures, with an exponential backoff tuned by `[mcp] reconnect_initial_delay_ms` (default 5000) and `reconnect_max_delay_ms` (default 300000) in config.toml. Add `reconnectInitialDelayMs` / `reconnectMaxDelayMs` to the `kimi-code` MCP block, write them to the shared global config.toml with the same per-key merge as the other `[mcp]` defaults, and lift them back on import. Refs dyoshikawa#2502 Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_0179ZomNiDQHCzgoxeRVmfth
Requirement or Bug
When a remote MCP server is unavailable at process start, its tools stay missing from the model's tool list for the entire process lifetime; the model still believes it has them (from earlier conversation history) and loops on fallback tools. Same after a mid-session drop: once the MCP SDK's built-in 2 reconnect attempts are exhausted, the server stays dead until a manual
:restartor config edit.Bug Reproduction Steps
fetch failed) → server entersfailedand nothing ever retries; its tools never register even after the server comes online minutes later.failedterminally; when the server recovers, tools do not come back without manual intervention.Root Cause
The initial connect is single-shot (
connectOnehas one try/catch that lands directly in terminalfailed), and the unexpected-close watcher marksfailedand stops — there is no application-layer retry anywhere, no permanent-vs-transient failure classification, and the only reconnect triggers are manual restart, OAuth token events, and tool-call healing (which can never fire for a server whose tools were never registered). This is a fundamental fix: classify failures, retry transient ones with backoff on both the first-connect and the unexpected-drop paths.Code Changes
mcpCore/connection-manager.ts): each server uses an explicit internal state machine (connecting / connected / probing / retryWaiting / failed / needsAuth / disabled / removed) mapped onto the unchanged public status vocabulary (probing → connected,retryWaiting → failed). State transitions, attempt guards, and public event emission share one funnel.mcpCore/client-stdio.ts,client-remote.ts,client-shared.ts): invalid executable paths, invalid config/bindings, deterministic discovery/protocol failures, and rejected static credentials are terminal; temporary process-resource errors, network failures, timeouts, and unknown failures remain retryable. Discovery 401/403 follows the same static-credential/OAuth rules as handshake failures.[mcp] reconnectInitialDelayMs/reconnectMaxDelayMsand their env bindings configure the policy; changing either delay reschedules existing retry waits without increasing the failure streak or opening another durable failure episode.mcpCore/client-*.ts): stdio process exit is hard evidence → backoff retry. For HTTP/SSE servers, exhaustion of the SDK's SSE-stream reconnection is weak evidence (plain POSTs may still work) → the session is probed once (ping, 5s timeout); a healthy probe keeps the connection silently connected, a failed one starts the backoff retry.reconnectRetryEnabled; only the workspace-level baseline manager enables it. Session-scoped ephemeral MCP servers behave exactly as before.agent/mcp/mcpFailureOps.ts,mcpService.ts):mcp.server_failedopens one episode per agent/server, andmcp.server_failure_resolvedcloses it withrecovered / needs-auth / disabled / removed. Replayablemcp.failuresstate prevents duplicate opens after Agent reconstruction; serialized, awaited writes preserve failed→recovered→failed ordering, repeated restores, and recovery even when the tool list is unchanged. Wire/state manifests and the vis pipeline cover the new records.nextRetryAtis propagated through core events, Klient, Node SDK, and kap-server WS; REST exposesnext_retry_at. Existing public status values are unchanged and older consumers can ignore the optional field.Behavior Changes and Affected Users
failedfor the process lifetime; tools never register without manual:restartor config edit[mcp] reconnect_initial_delay_ms/reconnect_max_delay_ms; manual:restartunchangedfailed; tools kept registered but calls fail until tool-call heal or manual restartfailedimmediately, zero retryfailedimmediately, zero retry[mcp]reconnect delays while a server is waitingfailedstatusfailed → pending → failedtransitions while retrying (≤ 1 cycle per 5 min at cap); a waiting entry additionally carries optional retry timing (nextRetryAt, or RESTnext_retry_at)mcp.server_failedandmcp.server_failure_resolvedrecords plus replayable open-failure stateAffected modules:
packages/agent-core-v2(mcpCore,agent/mcp,workspace/workspaceMcp*,app/mcpConfig),packages/kap-server,packages/klient,packages/node-sdk, andapps/vis— covered by their existing suites plus the extended cases intest/mcpCore/connection-manager.test.tsandtest/agent/mcp/mcp.test.ts.Checklist
/approve).gen-changesetsskill, or this PR needs no changeset.gen-docsskill, or this PR needs no doc update.