Repository navigation
fix(mcp): keep session servers alive between turns - #141125
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
@clawsweeper review Please review the current head, |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
Codex review: blocked before merge. Reviewed September 7, 2026, 10:59 AM ET / 14:59 UTC. ClawSweeper reviewWhat this changesKeeps session-owned MCP servers alive between turns, restores optional idle eviction, and updates admission limits and cleanup at session boundaries. Merge readiness⛔ Blocked before merge - 2 items remain The PR remains useful: current main and v2026.9.2 retain the fixed idle timeout. Both earlier findings are resolved, and no new blocking defect was found. The recorded approvals settle the configuration and capacity choices. Priority: P2 Review scores
Verification
How this fits togetherOpenClaw’s MCP runtime manager connects agent sessions to external tool servers. It owns connection reuse and cleanup across turns, session changes, and Gateway shutdown. flowchart TD
A[Agent session and MCP configuration] --> B[Runtime admission]
B --> C[Reuse existing connections]
B --> D[Reserve available capacity]
D --> C
C --> E[Tool calls and background server work]
E --> F[Keep alive between turns]
F --> C
F --> G[Session end, Stop, or optional idle timeout]
G --> H[Close connections and release capacity]
Before merge
Agent review detailsSecurityNone. PR surfaceSource +25, Tests +407, Docs +22, Generated 0. Total +454 across 42 files. View PR surface stats
Review metrics
Stored data modelPersistent data-model change detected: Root-cause clusterRelationship: Members:
Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything. Merge-risk optionsMaintainer options:
Technical reviewBest possible solution: Adopt the approved session-owned lifetime with explicit cleanup boundaries, optional idle eviction, and documented capacity recovery. Do we have a high-confidence way to reproduce the issue? Yes, from source: current main evicts unleased MCP runtimes after ten idle minutes, and the linked report records interrupted background indexing. This review did not execute a reproduction. Is this the best way to solve the issue? Yes. The patch repairs lifetime ownership across continuing sessions and detached runs, while preserving explicit cleanup and historical TTL values; the broader default and admission choices already have recorded approval. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against dd53f7fec223. LabelsLabel justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (3 earlier review cycles)
|
|
@clawsweeper review Both actionable findings from the prior review are fixed in 5e79337. Empty sessions and sign-in-only catalogs no longer consume runtime capacity; capacity is held through cleanup and cannot be released by a predecessor after replacement. Regressions cover 300 empty sessions, full-capacity admission, config cleanup, and concurrent replacement. The real stdio test now advances the manager clock; both cases fail against the original idle policy and pass with this repair. The serialized-data warning on sessions-abort.ts is not applicable: retirement uses the existing canonical session ID and changes no schema or persisted format. The schema guard remains green. Configuration restoration and the admission-cap tradeoff are expressly approved for this work order. Focused tests, pnpm check:changed, docs MDX, git diff --check, and complete-diff independent review through P2 are green. The two MCP fixture failures in the first hosted run were also reproduced and corrected without timeout or assertion weakening. Fresh exact-head CI is pending. |
|
🦞🧹 I asked ClawSweeper to review this item again. Re-review progress:
|
|
Maintainer disposition for the three checklist items at 5e79337:
The refreshed review identifies no actionable code or security finding and confirms both earlier findings resolved. Required exact-head CI remains pending before native preparation and merge. |
Keep OpenClaw-managed MCP runtimes for their owning session by default and restore mcp.sessionIdleTtlMs as an opt-in override. Preserve the key in Doctor. Replace requester LRU eviction with a Gateway-wide admission bound that holds capacity through creation and confirmed cleanup. Preserve continuing Gateway and nested sessions at run settlement. Retire ended compaction predecessors and explicit stops at their lifetime owners, with required retirement surviving pending acquisition and weaker run cleanup. Reported by @BottaniCals in #140447.
Reserve capacity only for runtimes that can own server connections, and retain the reservation until cleanup is confirmed. Reclaim emptied slots without allowing late reload cleanup to release a successor's reservation. Correct the real-child idle clock proof and sibling cleanup fixtures. Add regressions for serverless admission and concurrent config retirement.
5e79337 to
9a64a80
Compare
|
Merged via squash.
|
* fix(mcp): keep session servers alive between turns Keep OpenClaw-managed MCP runtimes for their owning session by default and restore mcp.sessionIdleTtlMs as an opt-in override. Preserve the key in Doctor. Replace requester LRU eviction with a Gateway-wide admission bound that holds capacity through creation and confirmed cleanup. Preserve continuing Gateway and nested sessions at run settlement. Retire ended compaction predecessors and explicit stops at their lifetime owners, with required retirement surviving pending acquisition and weaker run cleanup. Reported by @BottaniCals in openclaw#140447. * fix(mcp): exclude empty sessions from runtime capacity Reserve capacity only for runtimes that can own server connections, and retain the reservation until cleanup is confirmed. Reclaim emptied slots without allowing late reload cleanup to release a successor's reservation. Correct the real-child idle clock proof and sibling cleanup fixtures. Add regressions for serverless admission and concurrent config retirement.

Related: #140447 (reported by @BottaniCals).
What Problem This Solves
Fixes an issue where background MCP server work would be interrupted between turns. OpenClaw imposed a ten-minute idle eviction policy, rejected the former
mcp.sessionIdleTtlMsoverride, and some callers requested run-end cleanup even though the receiving session continued to exist.Why This Change Was Made
The lifetime owners are
src/agents/agent-bundle-mcp-manager-lifecycle.ts,src/agents/embedded-agent-runner/run/run-settlement.ts, and the compaction acceptance/adoption paths incompaction-successor.tsandrun/compaction-runtime.ts. MCP lifetime now belongs to the session by default. Unset or zeromcp.sessionIdleTtlMskeeps OpenClaw-managed runtimes alive; positive values opt into idle eviction. Doctor preserves the restored key. The approved configuration addition changes the core baseline from 2417 to 2418, with channel and plugin counts unchanged.The manager replaces requester LRU eviction with a 256-runtime admission bound across the Gateway, including creation and cleanup in progress. Existing runtimes survive capacity pressure, and new admissions receive an actionable error. Serverless sessions and sign-in-only catalogs do not consume the limit; removing all servers frees capacity only after cleanup is confirmed, while replacements retain their transferred slot. The idle sweep is absent from acquisition and its timer exists only for an enabled override. Reset/delete, explicit Stop, relevant server configuration changes, and shutdown retain cleanup ownership and terminate owned stdio children.
Gateway agent turns and nested session messages preserve the receiving session's runtime. Truly run-owned local CLI, detached cron, and run-mode subagent runtimes still retire at completion. Embedded settlement uses exact run-owned IDs, including an accepted transient compaction successor, instead of following a session key that may already point at another run. CLI dispatch delegates cleanup to the existing CLI settlement owner. Compaction retires each ended predecessor at the acceptance owner, covering repeated ID rotations, manual/CLI compaction, and cancellation after a committed rotation; transient in-memory adoption has the same cleanup boundary. The successor remains alive for its own session lifetime.
Restoring only the knob or increasing the hardcoded TTL would leave run-end retirement unresolved. MCP task-protocol tracking is unnecessary for the approved session-lifetime contract. Retained transcripts alone do not extend a detached run's process lifetime.
Comparison: sibling Codex was personally inspected at
64b482500d00b331189beefd173a5e08b4060ff2.codex-rs/codex-mcp/src/runtime.rs:92–103,692–694owns MCP connections per thread;codex-rs/codex-mcp/src/connection_manager.rs:846–860shuts down clients;codex-rs/rmcp-client/src/rmcp_client.rs:1010–1025terminates owned stdio processes, andcodex-rs/rmcp-client/src/local_child.rs:20–26enables kill-on-drop. The inspected runtime/config has operation deadlines and no server-inactivity eviction policy. Claude Code's MCP reference and environment-variable reference expose call-level startup, execution, and unanswered-call timeouts, rather than a configurable post-response server-idle eviction policy; pending background calls remain session-bound. This change aligns OpenClaw's managed runtime lifetime with that session ownership model.User Impact
Session MCP servers can finish background work through quiet periods and between turns. Operators can explicitly opt into idle cleanup with the restored setting, and can stop or reset unused sessions when the Gateway reaches its runtime bound. If an earlier Doctor run deleted the setting, its former value must be restored from an operator backup.
Evidence
The isolated default-lifetime regression failed before the repair because the manager discarded the session runtime during a quiet period. Additional before/after regressions cover uncertain replacement cleanup, stale TTL snapshots, compaction predecessor cleanup (including cancellation and transient adoption), and retirement surviving an in-flight acquisition.
Focused validation passed 940 distinct tests across 21 files (including reruns of the changed MCP suites); one Linux-only procfs case was skipped on macOS. Real stdio fixtures verify survival after a day of synthetic idle time and child termination on reset/shutdown; existing active lease/database-lock lifecycle tests also pass. Config validation and Doctor migration preserve zero, fractional, and positive overrides. Admission tests exercise all 256 slots, 300 serverless sessions, in-flight creation, pending cleanup, configuration removal racing replacement, and both static and requester runtimes. The real-child clock proof was corrected to advance the manager clock; both reset/shutdown cases were rerun against the original implementation and failed from idle eviction, then passed with this repair. Two sibling CI fixtures were corrected to honor cleanup ownership and release held disposal before awaiting publication, without weakening assertions or timeouts.
pnpm build: passed on the initial feature payload, including declaration/export checks and built plugin control-plane/Doctor loads.node scripts/check-docs-mdx.mjs docs/cli/mcp.md docs/gateway/config-extensions.md: passed.git diff --check: passed.Exact head:
9a64a801ec7cbfd6b92919716f7960b74c3f7c94.pnpm check:changed -- <all 42 changed files>completed with exit code 0, covering formatting, typechecks, lint, dead exports, runtime import cycles, storage/schema guards, and other selected checks. Local proof validates the candidate payload committed at this head. The first hosted run found the two now-corrected MCP fixture failures, plus unrelated Telegram max-lines, UI service-worker cache-installation, and Windows transform-timeout failures. Telegram cleanup is tracked in #141136; the UI and Windows files are unchanged by this PR. The normal PR run 34115848929 then failed only the unchanged CI planner inventory-growth stress test at its 120-second timeout. The exact fix landed on main as ed86b49 (#141137), preserving the timeout and assertions. This branch was rebased onto the containing main for that failing gate; git range-diff confirms both MCP commits are patch-identical. Post-rebase proof: 213 focused tests, all 42-file changed checks, and fresh independent review through P2 passed. Final exact-head CI run 34126017734 completed successfully with 108 passing jobs and no failures. Refreshed ClawSweeper review reports no actionable findings. Native preparation and merge completed successfully on the unchanged reviewed head. Squash commit fe8f7a3 is verified as an ancestor of main; all 42 changed paths retain the landed content. The earlier GitHub API TLS/EOF failures required no retries in the successful landing attempt.ClawSweeper's two actionable findings (empty runtime capacity and the real-child test clock) are addressed with before/after regressions. Its serialized-data-model warning on
sessions-abort.tsis not applicable: the change retires an in-process runtime by its existing canonical session ID and changes no serialized format, schema, or persistent-store semantics. The existing schema guard passes. The hard cap intentionally rejects new resource-owning admissions instead of evicting another session's runtime.Focused commands (task-local cache/log routing omitted):