Skip to content

fix(cli-runner): scope bundle-MCP cleanup to the run's session, not the process-wide loopback server - #110251

Merged
steipete merged 4 commits into
openclaw:mainfrom
totobusnello:fix/98435-reresolve-mcp-loopback-port-on-respawn
Jul 29, 2026
Merged

steipete merged 4 commits into
openclaw:mainfrom
totobusnello:fix/98435-reresolve-mcp-loopback-port-on-respawn

Conversation

@totobusnello

@totobusnello totobusnello commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

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 -p
process is alive and was spawned by the new gateway, but its
--mcp-config /tmp/openclaw-cli-mcp-XXXXXX/mcp.json points at a
http://127.0.0.1:<port>/mcp listener that no longer exists, so every MCP call
returns "Unable to connect" — while the gateway still reports the session as
recovered=1. Failure-time captures also show stale openclaw-cli-mcp-* config
dirs piling up under /tmp.

Root cause

The per-session MCP loopback proxy is a process-wide singleton
(activeMcpLoopbackServer in src/gateway/mcp-http.ts). Its port is baked into
each session's mcp.json at spawn time.

runCliAgentInternal (src/agents/cli-runner.ts) handled the
cleanupBundleMcpOnRunEnd flag by calling closeMcpLoopbackServer(), which
tears down that process-wide server when a single run finishes:

if (params.cleanupBundleMcpOnRunEnd === true) {
  const { closeMcpLoopbackServer } = await import("../gateway/mcp-http.js");
  await closeMcpLoopbackServer();
}

cleanupBundleMcpOnRunEnd is set for one-shot / subagent helper runs
(subagent-spawn.ts sets it for spawnMode !== "session"). When such a run
finishes 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 cleanupBundleMcpOnRunEnd had already been
fixed
to avoid exactly this, and say so explicitly:

  • src/agents/embedded-agent-runner/cli-backend-dispatch.ts:

    Deliberately NOT forwarding cleanupBundleMcpOnRunEnd: on the CLI runner it
    closes the process-wide loopback MCP server, which a concurrent main turn or
    overlapping recall may still be using. Session-scoped MCP runtimes are
    retired below instead.

  • src/agents/embedded-agent-runner/run-loop.ts retires session-scoped runtimes
    via retireSessionMcpRuntimeForSessionKey.

The legacy cli-runner.ts path was never migrated and still performed the
process-wide teardown.

Fix

Scope the cli-runner.ts cleanup 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.json with the current port on respawn." That half already happens — every
CLI spawn/respawn re-runs prepareCliRunContext, which reads the current
getActiveMcpLoopbackRuntime() port (lazily starting the server if needed) and
writes a fresh mcp.json; the live-session reuse fingerprint is port-sensitive
(mcpConfigHash) and respawns on a port change. The gateway never reuses a
pinned/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 recovered no longer
coincides with a dead loopback.

Testing

Risk / notes for reviewers

  • Behavior change is narrow: the target of cleanupBundleMcpOnRunEnd cleanup
    changes from the process-wide server to the run's session-scoped runtime.
    Error-surfacing semantics are preserved (recordCleanupError still feeds the
    existing fatal/warn branch).
  • closeMcpLoopbackServer remains the correct teardown for the actual gateway
    shutdown path (server-close.ts); this change only stops a single run from
    invoking it.
  • This addresses the transport-teardown mechanism. If maintainers also want the
    recovered counter itself to reflect verified MCP reachability (it currently
    increments 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-runner dist chunk (this version's embedded-agent chunk 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 -p session pinned to a dead loopback port with repeated Unable to connect MCP errors right after a gateway restart.

After (patched):

  • Recovered CLI session resumed with conversation history preserved:
    cli exec: provider=claude-cli ... trigger=user useResume=true session=present resumeSession=[redacted-session-id] reuse=reusable historyPrompt=present
  • Multiple CLI runs started and completed after the restart: 6 run lifecycle events including live session close at 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 exact cleanupBundleMcpOnRunEnd path this PR changes was exercised repeatedly.
  • The process-wide MCP loopback server survived every one of those run completions: at T+21min the listener is still up on the same port (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).
  • CLI sessions completed MCP tool calls against that loopback after the restart and after helper-run completions: mcp__openclaw__cron, mcp__openclaw__memory_search (×3), mcp__openclaw__sessions_yield — all succeeded.
  • Zero Unable to connect occurrences 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)
=== T+4min: config→port vs LISTEN correlation ===
live process uses openclaw-cli-mcp-nT6i37 -> 127.0.0.1:37061 [LISTENING]

=== recovery in journal ===
23:18:36 [agent/cli-backend] cli exec: provider=claude-cli model=claude-sonnet-5 promptChars=1847 trigger=user useResume=false session=none resumeSession=none reuse=none historyPrompt=none
23:18:43 [agent/cli-backend] cli exec: provider=claude-cli model=claude-haiku-4-5 promptChars=62 trigger=user useResume=true session=present resumeSession=[redacted-session-id] reuse=reusable historyPrompt=present

=== PROVA FINAL T+~21min (2026-07-17T23:36:07-03:00) ===

--- 1. correlação config→porta vs LISTEN (todos os processos claude vivos) ---

--- 2. runs iniciados/encerrados desde o restart (ciclo completo do killer path) ---
6
Jul 17 23:18:51 [host] openclaw-gateway-wrapper[922337]: 2026-07-17T23:18:51.246-03:00 [agent/cli-backend] claude live session close: provider=claude-cli model=claude-haiku-4-5 reason=restart
Jul 17 23:21:10 [host] openclaw-gateway-wrapper[922337]: 2026-07-17T23:21:10.208-03:00 [agent/cli-backend] claude live session close: provider=claude-cli model=claude-sonnet-5 reason=restart

--- 3. Unable to connect desde o restart (esperado: 0) ---
0

--- 4. transcripts novos pós-restart: MCP tool calls ok? ---
transcripts novos: 3
com Unable to connect: 0
com tool_use mcp__openclaw__: 1
--- exemplo de tool call MCP bem-sucedida (nome da tool + trecho do result) ---
      1 mcp__openclaw__cron
      3 mcp__openclaw__memory_search
      1 mcp__openclaw__sessions_yield

--- 5. loopback server atual ---
LISTEN 0      511                     127.0.0.1:18802      0.0.0.0:*    users:(("node.real",pid=1031,fd=21))                   
LISTEN 0      511                     127.0.0.1:18789      0.0.0.0:*    users:(("openclaw",pid=922337,fd=27))                  
LISTEN 0      4096                    127.0.0.1:34805      0.0.0.0:*    users:(("containerd",pid=1094,fd=15))                  
LISTEN 0      511                     127.0.0.1:37061      0.0.0.0:*    users:(("openclaw",pid=922337,fd=38))                  

Related to #98435

🤖 Generated with Claude Code

https://claude.ai/code/session_01MMPjCgbgHTiB8X3R9XACPW

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: S triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. labels Jul 17, 2026
@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. P1 High-priority user-facing bug, regression, or broken workflow. labels Jul 18, 2026
@clawsweeper

clawsweeper Bot commented Jul 18, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed July 20, 2026, 6:00 PM ET / 22:00 UTC.

Summary
The PR replaces CLI run-end teardown of the process-wide MCP loopback server with retirement of the affected session-scoped MCP runtime, including regression tests for session-key and session-id cleanup.

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: 🐚 platinum hermit
Proof: 🦞 diamond lobster
Patch quality: 🐚 platinum hermit
Result: ready for maintainer review.

Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch.

Rank-up moves:

  • Refresh or rebase onto current main, then rerun the focused CLI-runner regression coverage and resolve the currently failing compact CI lane on that exact head.

Risk before merge

  • [P1] The branch is behind current main, one compact CI lane currently reports failure, and several required checks are still running; refresh the exact merge head and resolve or rerun that lane before landing.

Maintainer options:

  1. Decide the mitigation before merge
    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 MCP loopback transport does not auto-reconnect on CLI side after gateway restart — recovered=1 is misleading #98435.
  2. Pause or close
    Do not merge this PR until maintainers decide whether the risk is worth taking.

Next step before merge

  • [P2] No discrete code repair is supported by the review; a maintainer should refresh the branch on current main and require the exact-head regression and CI result before merging.

Security
Cleared: The two-file runtime/test diff adds no dependencies, workflow changes, credential handling, or new execution surface; no concrete security or supply-chain regression was found.

Review details

Best 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 changes

Label justifications:

  • P1: The current behavior can strand active or recovered CLI sessions without MCP tool access after another run performs cleanup.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): The PR body contains redacted after-fix production-gateway terminal evidence showing the changed cleanup path exercised after restart, the loopback listener remaining live, successful MCP calls, and no connection failures.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR body contains redacted after-fix production-gateway terminal evidence showing the changed cleanup path exercised after restart, the loopback listener remaining live, successful MCP calls, and no connection failures.
Evidence reviewed

PR surface:

Source +22, Tests +43. Total +65 across 2 files.

View PR surface stats
Area Files Added Removed Net
Source 1 24 2 +22
Tests 1 50 7 +43
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 74 9 +65

What I checked:

  • Current main retains the unsafe cleanup target: Current main calls closeMcpLoopbackServer when cleanupBundleMcpOnRunEnd is true; mcp-http keeps a process-wide activeMcpLoopbackServer, so this remains the central behavior the PR addresses. (src/agents/cli-runner.ts:114, 3a9f89e42e94)
  • Process-wide server contract: closeMcpLoopbackServer clears and closes the singleton active loopback server, rather than a run-specific resource. (src/gateway/mcp-http.ts:1142, 3a9f89e42e94)
  • Existing sibling lifecycle pattern: The embedded run loop already retires a session runtime by session key with a session-id fallback, preserving the process-wide loopback server for unrelated work. (src/agents/embedded-agent-runner/run-loop.ts:640, 3a9f89e42e94)
  • Current main test confirms old behavior: The existing CLI-runner regression test expects cleanupBundleMcpOnRunEnd to call closeMcpLoopbackServer, confirming the reported behavior has not already been fixed on main. (src/agents/cli-runner.before-agent-reply-cron.test.ts:2380, 3a9f89e42e94)
  • Feature-history provenance: GitHub blame attributes the current cleanup block to commit 9056d4f ("feat: add crestodian local planner fallback"), which introduced the CLI run-end cleanup now under review. (src/agents/cli-runner.ts:114, 9056d4f70882)
  • After-fix behavior proof: The PR body provides a redacted production-gateway terminal capture showing helper-run completions after restart, a surviving loopback listener, successful MCP calls, and zero post-restart connection failures. (src/agents/cli-runner.ts:572, 014d02a86341)

Likely related people:

  • steipete: The current CLI run-end cleanup block traces through blame to a Peter Steinberger commit that introduced the surrounding CLI fallback path and process-wide loopback teardown. (role: introduced current cleanup behavior; confidence: medium; commits: 9056d4f70882; files: src/agents/cli-runner.ts)
What the crustacean ranks mean
  • 🦀 challenger crab: rare, exceptional readiness with strong proof, clean implementation, and convincing validation.
  • 🦞 diamond lobster: very strong readiness with only minor maintainer review expected.
  • 🐚 platinum hermit: good normal PR, likely mergeable with ordinary maintainer review.
  • 🦐 gold shrimp: useful signal, but proof or patch confidence is still limited.
  • 🦪 silver shellfish: thin signal; proof, validation, or implementation needs work.
  • 🧂 unranked krab: not merge-ready because proof is missing/unusable or there are serious correctness or safety concerns.
  • 🌊 off-meta tidepool: rating does not apply to this item.

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
  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.
Review history (3 earlier review cycles)
  • reviewed 2026-07-18T00:00:06.044Z sha 1c062a71081d303276245ab74f822d0d296c33a8 :: needs real behavior proof before merge. :: none
  • reviewed 2026-07-18T02:43:38.226Z sha 1c062a71081d303276245ab74f822d0d296c33a8 :: needs maintainer review before merge. :: none
  • reviewed 2026-07-18T03:11:38.920Z sha 1c062a71081d303276245ab74f822d0d296c33a8 :: needs maintainer review before merge. :: none

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Jul 18, 2026
@openclaw-barnacle openclaw-barnacle Bot removed the triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. label Jul 18, 2026
…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
@totobusnello
totobusnello force-pushed the fix/98435-reresolve-mcp-loopback-port-on-respawn branch from 1c062a7 to 014d02a Compare July 20, 2026 21:54
@totobusnello

Copy link
Copy Markdown
Contributor Author

The two red checks are unrelated to this PR.

checks-node-compact-small-6 fails in src/process/child-process.test.ts > releaseChildProcessOutputAfterExit > drains active descendant output after the parent exits (expected 'HEAD\n' to contain 'TAIL'). This PR touches only src/agents/cli-runner.ts and its test — zero lines under src/process/.

I ran that test locally on both sides of the change: 3/3 passed on this branch (014d02a), 3/3 passed on clean main at the same base. The assertion waits for a descendant's trailing output after the parent exits, so it's timing-sensitive under runner load — the file was last touched by #111040 ("preserve descendant output under event-loop stalls"). openclaw/ci-gate goes red as a consequence.

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 main (was ~950 commits behind), which also cleared the previously failing "Real behavior proof" check. The patch itself is unchanged.

@totobusnello

Copy link
Copy Markdown
Contributor Author

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 needs-product-decision discussion lives: #98435 (comment)

Short version as it bears on this PR: activeMcpLoopbackServer has exactly two closers — src/agents/cli-runner.ts:566-569 (the one this PR converts) and gateway shutdown. There is no idle teardown, so the restart-free trigger both reporters hit is this call site being reached by an unattended one-shot run (cron, slug hook, companion-ask, any spawnMode !== "session" subagent) while another session is live. That also means the concern that "a fix scoped only to restart recovery won't catch this path" does not apply here: this PR touches no recovery or resume code.

No changes to the branch — head is still 014d02a863.

@steipete
steipete merged commit d786445 into openclaw:main Jul 29, 2026
189 of 191 checks passed
@steipete

Copy link
Copy Markdown
Contributor

Merged via squash.

vincentkoc added a commit to yetval/openclaw that referenced this pull request Jul 29, 2026
* 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
pull Bot pushed a commit to yann0001/openclaw that referenced this pull request Jul 29, 2026
* 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)
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Jul 30, 2026
…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]>
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Jul 30, 2026
* 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)
mattzyha pushed a commit to mattzyha/openclaw that referenced this pull request Nov 21, 2026
…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)
mattzyha added a commit to mattzyha/openclaw that referenced this pull request Nov 21, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling P1 High-priority user-facing bug, regression, or broken workflow. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: M status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants