Repository navigation
fix(cli-runner): scope bundle-MCP cleanup to the run's session, not the process-wide loopback server - #110251
Conversation
|
Codex review: needs maintainer review before merge. Reviewed July 20, 2026, 6:00 PM ET / 22:00 UTC. Summary PR surface: Source +22, Tests +43. Total +65 across 2 files. Reproducibility: yes. at source level: current main routes one run's cleanup flag to the process-wide loopback close function, and the PR body supplies a matching redacted production before/after gateway reproduction. I did not independently execute the gateway scenario in this read-only review. Review metrics: none identified. Merge readiness Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch. Rank-up moves:
Risk before merge
Maintainer options:
Next step before merge
Security Review detailsBest possible solution: Retain session-scoped cleanup, refresh the branch on current main, and land it after focused CLI-runner regression coverage and required CI validate the exact head; keep the broader end-to-end meaning of recovery status in #98435. Do we have a high-confidence way to reproduce the issue? Yes at source level: current main routes one run's cleanup flag to the process-wide loopback close function, and the PR body supplies a matching redacted production before/after gateway reproduction. I did not independently execute the gateway scenario in this read-only review. Is this the best way to solve the issue? Yes for the narrow teardown defect: session-scoped retirement matches the existing embedded-runner lifecycle rather than closing shared transport state. It intentionally does not settle the broader recovery-status semantics tracked in #98435. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning high; reviewed against 3a9f89e42e94. Label changesLabel justifications:
Evidence reviewedPR surface: Source +22, Tests +43. Total +65 across 2 files. View PR surface stats
What I checked:
Likely related people:
What the crustacean ranks mean
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics. How this review workflow works
Review history (3 earlier review cycles)
|
…he process-wide loopback server
On run end, runCliAgentInternal handled cleanupBundleMcpOnRunEnd by calling
closeMcpLoopbackServer(), which tears down the process-wide MCP loopback HTTP
server for the whole gateway. Any concurrent CLI turn or restart-recovered live
session that already baked that loopback port into its --mcp-config is left
pinned to a dead port ("Unable to connect"), while the gateway still reports the
session as recovered. This is the same hazard the embedded-runner (run-loop.ts)
and CLI dispatch (cli-backend-dispatch.ts) paths already avoid by retiring only
session-scoped MCP runtimes.
Retire only this run's session-scoped MCP runtime here too (by session key, with
a session-id fallback), leaving the shared loopback server up for other sessions.
Every CLI spawn/respawn already re-derives the current loopback port and rewrites
mcp.json via prepareCliRunContext, so removing this teardown keeps recovered
sessions on a live transport instead of stranding them.
Fixes openclaw#98435
Co-Authored-By: Claude Fable 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01MMPjCgbgHTiB8X3R9XACPW
1c062a7 to
014d02a
Compare
|
The two red checks are unrelated to this PR.
I ran that test locally on both sides of the change: 3/3 passed on this branch (014d02a), 3/3 passed on clean I can't re-run the job (external contributor), so flagging it here rather than force-pushing just to retrigger CI. Context: the branch is now rebased onto current |
|
Two restart-free field reports landed on #98435 after this PR was opened (@jwest75674 2026-07-23, @Atlas-crete 2026-07-25). I posted a call-graph analysis there rather than here, since that is where the Short version as it bears on this PR: No changes to the branch — head is still |
|
Merged via squash.
|
* origin/main: fix: CJK replies are silently dropped instead of recovered when the model skips message(action=send) (openclaw#115556) fix(gateway): stop managed crash loops for pending agent DB migrations (openclaw#115631) fix(plugins): validate constrained empty config schemas (openclaw#109569) fix(cli-runner): scope bundle-MCP cleanup to the run's session, not the process-wide loopback server (openclaw#110251) fix(feishu): log message content JSON parse failures instead of silently swallowing (openclaw#107947) docs(vision,agents): layer calibration, interface-on-demand, telemetry opt-in, whole-document guidance rules
* origin/main: fix: CJK replies are silently dropped instead of recovered when the model skips message(action=send) (openclaw#115556) fix(gateway): stop managed crash loops for pending agent DB migrations (openclaw#115631) fix(plugins): validate constrained empty config schemas (openclaw#109569) fix(cli-runner): scope bundle-MCP cleanup to the run's session, not the process-wide loopback server (openclaw#110251) fix(feishu): log message content JSON parse failures instead of silently swallowing (openclaw#107947) docs(vision,agents): layer calibration, interface-on-demand, telemetry opt-in, whole-document guidance rules fix(memory): preserve Windows session ownership (openclaw#115851) fix(compaction): drop context-engine fallback on codex ownership skip (openclaw#114155) (openclaw#115666) fix(msteams): ignore blank certificate settings (openclaw#109112)
…he process-wide loopback server (openclaw#110251) * fix(cli-runner): scope bundle-MCP cleanup to the run's session, not the process-wide loopback server On run end, runCliAgentInternal handled cleanupBundleMcpOnRunEnd by calling closeMcpLoopbackServer(), which tears down the process-wide MCP loopback HTTP server for the whole gateway. Any concurrent CLI turn or restart-recovered live session that already baked that loopback port into its --mcp-config is left pinned to a dead port ("Unable to connect"), while the gateway still reports the session as recovered. This is the same hazard the embedded-runner (run-loop.ts) and CLI dispatch (cli-backend-dispatch.ts) paths already avoid by retiring only session-scoped MCP runtimes. Retire only this run's session-scoped MCP runtime here too (by session key, with a session-id fallback), leaving the shared loopback server up for other sessions. Every CLI spawn/respawn already re-derives the current loopback port and rewrites mcp.json via prepareCliRunContext, so removing this teardown keeps recovered sessions on a live transport instead of stranding them. Fixes openclaw#98435 Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01MMPjCgbgHTiB8X3R9XACPW * fix(cli): preserve rebound MCP session owners --------- Co-authored-by: Claude Fable 5 <[email protected]> Co-authored-by: Peter Steinberger <[email protected]>
* origin/main: fix: CJK replies are silently dropped instead of recovered when the model skips message(action=send) (openclaw#115556) fix(gateway): stop managed crash loops for pending agent DB migrations (openclaw#115631) fix(plugins): validate constrained empty config schemas (openclaw#109569) fix(cli-runner): scope bundle-MCP cleanup to the run's session, not the process-wide loopback server (openclaw#110251) fix(feishu): log message content JSON parse failures instead of silently swallowing (openclaw#107947) docs(vision,agents): layer calibration, interface-on-demand, telemetry opt-in, whole-document guidance rules fix(memory): preserve Windows session ownership (openclaw#115851) fix(compaction): drop context-engine fallback on codex ownership skip (openclaw#114155) (openclaw#115666) fix(msteams): ignore blank certificate settings (openclaw#109112)
…he process-wide loopback server (openclaw#110251) * fix(cli-runner): scope bundle-MCP cleanup to the run's session, not the process-wide loopback server On run end, runCliAgentInternal handled cleanupBundleMcpOnRunEnd by calling closeMcpLoopbackServer(), which tears down the process-wide MCP loopback HTTP server for the whole gateway. Any concurrent CLI turn or restart-recovered live session that already baked that loopback port into its --mcp-config is left pinned to a dead port ("Unable to connect"), while the gateway still reports the session as recovered. This is the same hazard the embedded-runner (run-loop.ts) and CLI dispatch (cli-backend-dispatch.ts) paths already avoid by retiring only session-scoped MCP runtimes. Retire only this run's session-scoped MCP runtime here too (by session key, with a session-id fallback), leaving the shared loopback server up for other sessions. Every CLI spawn/respawn already re-derives the current loopback port and rewrites mcp.json via prepareCliRunContext, so removing this teardown keeps recovered sessions on a live transport instead of stranding them. Fixes openclaw#98435 Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01MMPjCgbgHTiB8X3R9XACPW * fix(cli): preserve rebound MCP session owners --------- Co-authored-by: Claude Fable 5 <[email protected]> Co-authored-by: Peter Steinberger <[email protected]> (cherry picked from commit d786445)
…rk spec Co-Authored-By: Claude Opus 5.5 <[email protected]>
What Problem This Solves
After a gateway restart (SIGUSR1 → full process restart via systemd), CLI-backed
sessions can end up running against a dead MCP loopback port: the
claude -pprocess is alive and was spawned by the new gateway, but its
--mcp-config /tmp/openclaw-cli-mcp-XXXXXX/mcp.jsonpoints at ahttp://127.0.0.1:<port>/mcplistener that no longer exists, so every MCP callreturns "Unable to connect" — while the gateway still reports the session as
recovered=1. Failure-time captures also show staleopenclaw-cli-mcp-*configdirs piling up under
/tmp.Root cause
The per-session MCP loopback proxy is a process-wide singleton
(
activeMcpLoopbackServerinsrc/gateway/mcp-http.ts). Its port is baked intoeach session's
mcp.jsonat spawn time.runCliAgentInternal(src/agents/cli-runner.ts) handled thecleanupBundleMcpOnRunEndflag by callingcloseMcpLoopbackServer(), whichtears down that process-wide server when a single run finishes:
cleanupBundleMcpOnRunEndis set for one-shot / subagent helper runs(
subagent-spawn.tssets it forspawnMode !== "session"). When such a runfinishes on this path, it closes the loopback server out from under any
concurrent CLI turn or restart-recovered live session that is still bound
to that port — leaving them pinned to a dead loopback while the recovery
bookkeeping already counted them as recovered.
The two other paths that honor
cleanupBundleMcpOnRunEndhad already beenfixed to avoid exactly this, and say so explicitly:
src/agents/embedded-agent-runner/cli-backend-dispatch.ts:src/agents/embedded-agent-runner/run-loop.tsretires session-scoped runtimesvia
retireSessionMcpRuntimeForSessionKey.The legacy
cli-runner.tspath was never migrated and still performed theprocess-wide teardown.
Fix
Scope the
cli-runner.tscleanup to this run's session-scoped MCP runtime,mirroring the dispatch/embedded-runner paths: retire by session key, with a
session-id fallback, and leave the shared loopback server running for other
sessions.
Note on the port itself: the suggested direction in the issue was "regenerate
mcp.jsonwith the current port on respawn." That half already happens — everyCLI spawn/respawn re-runs
prepareCliRunContext, which reads the currentgetActiveMcpLoopbackRuntime()port (lazily starting the server if needed) andwrites a fresh
mcp.json; the live-session reuse fingerprint is port-sensitive(
mcpConfigHash) and respawns on a port change. The gateway never reuses apinned/persisted argv. The remaining defect was the opposite motion: a per-run
cleanup killing the shared transport under still-live sessions. Removing that
teardown keeps recovered sessions on a live transport, so
recoveredno longercoincides with a dead loopback.
Testing
pnpm test -- src/agents/cli-runner.before-agent-reply-cron.test.ts— passes(both the
agents-coreandagents-supportvitest projects). Updated thecleanup tests to assert the run retires its session-scoped MCP runtime and
does not close the process-wide loopback server (regression guard for
MCP loopback transport does not auto-reconnect on CLI side after gateway restart — recovered=1 is misleading #98435), plus the session-id fallback and the existing cleanup-failure
surfacing/preservation behavior.
tsgo:core(source) andtsgo:core:test(test types) both pass.Risk / notes for reviewers
cleanupBundleMcpOnRunEndcleanupchanges from the process-wide server to the run's session-scoped runtime.
Error-surfacing semantics are preserved (
recordCleanupErrorstill feeds theexisting fatal/warn branch).
closeMcpLoopbackServerremains the correct teardown for the actual gatewayshutdown path (
server-close.ts); this change only stops a single run frominvoking it.
recoveredcounter itself to reflect verified MCP reachability (it currentlyincrements on recovery-turn admission in
main-session-restart-recovery.ts),that is a separable follow-up.
Evidence
Real behavior proof (after-fix, production gateway).
Deployed this change to a production OpenClaw 2026.6.11 gateway — the same deployment that produced the failure-time captures in #98435 — by applying the equivalent patch to the shipped
cli-runnerdist chunk (this version'sembedded-agentchunk already uses the session-scoped retirement pattern, so the import surface exists), then performed a full systemd gateway restart at 23:18:25 local time.Before (same host, same day, unpatched — 18:38 local): the failure-time capture posted in #98435 shows a live
claude -psession pinned to a dead loopback port with repeatedUnable to connectMCP errors right after a gateway restart.After (patched):
cli exec: provider=claude-cli ... trigger=user useResume=true session=present resumeSession=[redacted-session-id] reuse=reusable historyPrompt=presentlive session closeat 23:18:51 and 23:21:10, plus three new session transcripts including one-shot helper runs from scheduled jobs at 23:22 and 23:30 — i.e. the exactcleanupBundleMcpOnRunEndpath this PR changes was exercised repeatedly.127.0.0.1:37061, owned by the gateway PID). Under the unpatched code, the first helper-run completion tore this listener down (that is precisely the 18:38 failure capture).mcp__openclaw__cron,mcp__openclaw__memory_search(×3),mcp__openclaw__sessions_yield— all succeeded.Unable to connectoccurrences in the gateway journal and in all post-restart session transcripts (the unpatched failure window produced 2+ per session).Redacted terminal capture (T+4min and T+21min after restart)
Related to #98435
🤖 Generated with Claude Code
https://claude.ai/code/session_01MMPjCgbgHTiB8X3R9XACPW