Skip to content

fix(node): local MCP server can stay running or vanish when toggled during a restart - #2078

Merged
bkudiess merged 3 commits into
openclaw:mainfrom
shanselman:shanselman-fix-nodeservice-mcp-lifecycle-lock
Nov 13, 2026
Merged

bkudiess merged 3 commits into
openclaw:mainfrom
shanselman:shanselman-fix-nodeservice-mcp-lifecycle-lock

Conversation

@shanselman

@shanselman shanselman commented Nov 8, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #2072
Related: #2071

What Problem This Solves

Fixes: the local MCP server could be left running after it was turned off, or a running server could be lost, when it was started and stopped at the same moment (for example, a settings toggle racing a reconnect).

User Impact

User impact: competing starts cannot lose the tracked Local MCP Server, and turning it off during startup prevents later authenticated calls from invoking tools. There is no other visible change.

Why This Change Was Made

Start and stop now share one lifecycle lock. Stop swaps the server references out under the lock and disposes them outside it, so it never waits while holding the lock. A failed start no longer clears a server that a concurrent start created.

Evidence

Two gated regressions exercise real NodeService and authenticated HTTP, replacing the implementation-shaped source test. Both failed on the pre-fix code because a call still caused a capability effect after disable; both pass with the fix, including same-client re-enable. Separately, an isolated app passed winnode and computer-use off/on checks, restoring 33 tools without restarting. Independent rubber-duck review found no blocking production defect; test diagnostics and a pending-contender guard were strengthened.

Change Type

  • Bug fix
  • Feature
  • Refactor
  • Docs or instructions
  • Tests or validation
  • Security hardening
  • Chore or infrastructure

Scope

  • Tray or WinUI UX
  • Windows node capability
  • Local MCP or winnode
  • Gateway, connection, or pairing
  • Setup or onboarding
  • Permissions, privacy, or security
  • Tests, CI, or docs

Required proof pools

  • windows-winui-interactive: current-head Permissions toggle and local MCP lifecycle proof on an isolated Windows desktop. Manual UI diagnostics and authenticated MCP checks are recorded below; no complete pool/inventory receipt is claimed.

Validation

  • ./build.ps1: all builds succeeded
  • dotnet test ./tests/OpenClaw.Shared.Tests/OpenClaw.Shared.Tests.csproj --no-restore: 4876 passed, 24 skipped
  • dotnet test ./tests/OpenClaw.Tray.Tests/OpenClaw.Tray.Tests.csproj --no-restore: 5294 passed, 0 skipped
  • dotnet test .\tests\OpenClaw.Tray.UITests\OpenClaw.Tray.UITests.csproj -r win-x64 --no-restore --filter 'FullyQualifiedName~NodeServiceMcpLifecycleTests': 2 passed, 0 skipped.
  • Negative control: temporarily restoring the pre-fix NodeService made both HTTP cases fail at the effect-count assertion after disable (competing start: expected 2, actual 3; overlapping disable: expected 1, actual 2). Restoring the fixed source, rebuilding and rerunning passed both cases. Reflection retains a leaked pre-fix server only for cleanup, never for assertions.
  • Current-head CI: run 42461096068 failed in UI. The testhost crashed in ReasoningPicker_UsesOnlyAdvertisedChoices, matching the documented docs/CI_FAILURES.md crash family; the TRX/sequence confirms the new MCP cases had not executed. Separately, HistoricalFractionalVoiceConversationRendersWithoutLoadingPlaceholder timed out (80 other fixture cases passed): the app log records working MCP startup/navigation/snapshot, then Chat initial tail navigation did not land at the tail. This points outside the changed lifecycle path, but the chat failure's root cause is not established. Tray/setup/integration and all three WSL E2E jobs passed. No blind rerun or weakened tests; hosted UI remains a merge blocker.

Real Behavior Proof

  • Environment tested: Windows x64, isolated Debug Companion with sensitive capabilities disabled, synthetic fixture Gateway, dedicated profile and MCP endpoint http://127.0.0.1:49995/. No installed Gateway was changed.
  • PR head or commit tested: ce5a6a1c2; the unchanged source was built before committing (embedded base stamp e70292487). Source correspondence is manually recorded. App assembly SHA256: 78614D9CFC3448B3A3F25F97D708C61F0702355B6A3380DD805DDF10E1DFF22D.
  • Exact steps or command run: discover with winnode --mcp-url http://127.0.0.1:49995/ --list-tools; invoke winnode --mcp-url http://127.0.0.1:49995/ --command app.status --params '{}'; computer-use toggled Permissions > Integrations > Local MCP Server off, then on, repeating both CLI checks. Each CLI call used the same isolated profile and no inherited MCP token.
  • Evidence after fix: off showed McpToggle=off, CLI exit 1/connection refused, zero listeners and persisted EnableMcpServer=False. On showed McpToggle=on, Local MCP only, Server enabled: token ready; discovery returned 33 tools, app.status returned Ready/fixture-1, one HTTP.sys listener and persisted EnableMcpServer=True.
  • Observed result: both directions work without restarting the app (PID 51140). An initial proof-script assertion incorrectly expected the app PID to own the TCP listener; HttpListener uses HTTP.sys/PID 4. Corrected profile-authenticated/endpoint assertions passed. The earlier MCP-command disable also passed; its reply was cut off by shutting down its own server.
  • Screenshot or artifact links verified? N/A. Copied live UI diagnostics and terminal observations above; no screenshot or full-pool claim.
  • Additional production-transport evidence: the new UI-project theory instantiates real NodeService on an isolated port/profile. With startup held after the HTTP bind but before publication, it discovers and invokes a harmless counting tool, overlaps a second startup or disable, then verifies post-disable HTTP rejection with no counter increment. Re-enable accepts the same authenticated client with exactly one new effect. Both cases pass; this is real HTTP lifecycle proof, not a mocked server or a rendered-UI claim.
  • Tested source for the new regression: b74a343ee694df5f01ba2e16709f38555833c434. Production source remains identical to ce5a6a1c2; test source SHA256 287E00038B6AF7F05C2FE1896299EFF805D096B8B71CBA425F8ADDBF39BF6EE8 was manually associated with the final run before committing unchanged source.
  • Not verified or blocked: the gated races do not prove every scheduler interleaving, AttachClient/disconnect overlap, token rotation, or asynchronous-drain/new-start behavior. No broad lifecycle guarantee is claimed. Fixture traffic is synthetic, not real Gateway/node-invocation proof. Complete interactive-pool proof and green hosted CI are not claimed.

Security Impact

  • New permissions or capabilities? No
  • Secrets or tokens handling changed? No
  • New or changed network calls? No
  • Command or tool execution surface changed? No
  • Data access scope changed? No
  • If any answer is Yes, explain the risk and mitigation: N/A

Compatibility and Migration

  • Backward compatible? Yes
  • Config or environment changes? No
  • Migration needed? No
  • If yes, list the exact upgrade steps: N/A

Review Conversations

  • I replied to or resolved every bot review conversation addressed by this PR.
  • I left unresolved only conversations that still need maintainer judgment.

Opened by a Copilot agent working through the state-machine audit lanes in #2071.

Start and stop now share one lifecycle lock so a concurrent restart or
disable cannot leave a stale listener or null out a live server.

Refs openclaw#2072

Co-authored-by: Copilot App <[email protected]>
@clawsweeper

clawsweeper Bot commented Nov 8, 2026 •

Copy link
Copy Markdown

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. P2 Normal priority bug or improvement with limited blast radius. merge-risk: 🚨 security-boundary 🚨 Merging this PR could weaken sandboxing, authorization, credentials, or sensitive data. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. labels Nov 8, 2026
@clawsweeper

clawsweeper Bot commented Nov 8, 2026

Copy link
Copy Markdown

Codex review: needs real behavior proof before merge.

What this changes

This PR serializes local MCP listener publication and removal with one lifecycle lock.

Example: Local MCP on port 8765 is disabled while a reconnect starts its listener.

  • Before: Startup can publish after disable returns, leaving an untracked listener running.
  • After: Startup and removal share a lock, so disable can remove an already-published listener or prevent a subsequent start.

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) The focused production repair appears sound, but the supplied smoke run and source assertions do not establish the concurrency-sensitive revocation contract; persisted formats and defaults are unchanged.
Proof confidence 🦪 silver shellfish (2/6) Real behavior proof is necessary before merge. See Before merge.
Patch quality 🦐 gold shrimp (3/6) Security review found an item that needs attention.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Turning Local MCP Server off can leave its listener running, or competing starts can lose the tracked server.
Reason: The maintainer-authored direction restores the existing toggle contract without adding options, permissions, or a parallel lifecycle owner.

Merge readiness

⛔ Blocked before merge - 3 items remain

Keep this collaborator-authored PR open: it addresses a current-main lifecycle defect, and inspection found no definite introduced production bug.

Priority: P2
Reviewed head: ce5a6a1c2ab16c5b82649b757a93b76cec58787f

Before merge

  • Add real behavior proof - Authority-chain proof required: the Windows 11 run at the reviewed head demonstrates MCP discovery, app.status, and ordinary disable on port 18765, but explicitly omits concurrency and re-enable. Provide redacted logs or terminal output through NodeService and the real HTTP transport showing allowed invocation, competing-start ownership, and rejection before capability effects when disable overlaps startup; redact tokens, IPs, and non-public endpoints. After adding proof, update the PR body, then request a new review with @clawsweeper re-review. The PR author or someone with repository write access can request it.
  • Resolve security review attention item - The patch preserves authentication, but concurrent listener revocation still needs final-effect evidence.
  • Resolve merge risk - Before merge, the PR owner must establish that disabling MCP during startup prevents a previously authenticated local client from reaching capability side effects.

Findings

None.

Tests

  • Low-value test tests/OpenClaw.Tray.Tests/AppRefactorContractTests.cs: Replace McpServerLifecycle_StartAndStopShareOneOwnershipLock with a deterministic behavioral regression: its private-name, source-order, and assignment-count assertions mirror this implementation and can pass without proving concurrent listener ownership.
  • Missing end-to-end proof: The supplied run does not exercise competing starts, disable during startup, or successful re-enable, and the reported base failure is a source-shape failure rather than the observable race.
Agent review details

How this fits together

NodeService hosts the authenticated loopback MCP server, shares registered capabilities with its bridge, and receives lifecycle requests from settings changes and gateway-client attachment.

flowchart TD
Settings[Settings toggle] --> Node[NodeService]
Reconnect[Gateway client attachment] --> Node
Node --> Gate[MCP lifecycle lock]
Gate --> Server[Loopback HTTP server]
Server --> Bridge[MCP tool bridge]
Bridge --> Capabilities[Registered capabilities]
Loading

Technical review

Best possible solution:

Keep lifecycle synchronization in NodeService, preserve disposal outside the lock, and verify concurrent ownership and revocation through the production transport.

Do we have a high-confidence way to reproduce the issue?

Main permits startup to pass its enabled check, disable to observe no published server, and startup to publish afterward; competing failed starts can also clear the winning reference.

Is this the best way to solve the issue?

The dedicated lock is a small repair using the existing owner, and inspection found no unnecessary production machinery; runtime concurrency coverage is still needed to validate its invariant.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against e70292487958.

Merge-risk options

Maintainer options:

  1. Prove concurrent listener revocation (recommended)
    The PR owner should provide production-path evidence that enabled clients can invoke a tool, competing starts retain one listener, and disable during startup prevents subsequent capability effects.

Provenance checked

Testing

Proof path: shipped entry point.

Security

Needs attention: The patch preserves authentication, but concurrent listener revocation still needs final-effect evidence.

Evidence

What I checked:

Likely related people:

  • Scott Hanselman: Raw commit 0d4fcbd adds src/OpenClaw.Tray.WinUI/Services/NodeService.cs:661 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 0d4fcbd50ad5; files: src/OpenClaw.Tray.WinUI/Services/NodeService.cs)
  • Barbara Kudiess: Raw commit f4e1cf3 adds src/OpenClaw.Tray.WinUI/Services/NodeService.cs:986 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: f4e1cf3a9894; files: src/OpenClaw.Tray.WinUI/Services/NodeService.cs)
  • Chris Anderson: Raw commit a3d884f adds src/OpenClaw.Tray.WinUI/Services/NodeService.cs:267 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: a3d884f4c4ba; files: src/OpenClaw.Tray.WinUI/Services/NodeService.cs)

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Review metrics

Metric Value Why it matters
Production and test delta Production +24/-8 lines; tests +43/-2 lines Production growth is focused lifecycle synchronization; the added source assertions do not execute the reported race.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #2072
Summary: This PR is the proposed repair for the concrete MCP lifecycle lane.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Labels

Label changes:

  • add P2: This repairs a bounded local listener lifecycle race without evidence of widespread outage or active exploitation.
  • add merge-risk: 🚨 security-boundary: The changed lifecycle controls whether authenticated local MCP clients retain access after the user disables the transport.
  • add rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🦐 gold shrimp.
  • add status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Label justifications:

  • P2: This repairs a bounded local listener lifecycle race without evidence of widespread outage or active exploitation.
  • merge-risk: 🚨 security-boundary: The changed lifecycle controls whether authenticated local MCP clients retain access after the user disables the transport.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🦐 gold shrimp.
  • status: 📣 needs proof: The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Add final-effect proof that an authenticated MCP client can invoke while enabled and cannot reach capability effects after disable races startup.
  • Replace the added source-shape test with a deterministic concurrent lifecycle regression that fails on the base for the reported behavior.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

Reviewed November 8, 2026, 1:51 AM ET / 06:51 UTC.

Replace the implementation-shaped ownership check with real NodeService and authenticated HTTP regression cases for competing starts and disable during startup.

Co-authored-by: Copilot App <[email protected]>
@shanselman

Copy link
Copy Markdown
Collaborator Author

Copilot agent follow-up: b74a343 replaces the source-shaped ownership test with two real NodeService/authenticated-HTTP cases. Both reproduced the original bug: a request after disable still incremented the capability effect counter (2 to 3 for competing starts, 1 to 2 for disable during startup). With the fixed implementation restored and rebuilt, both reject HTTP without another effect, and re-enable accepts the same authenticated client. The full build, Shared (4876 passed, 24 ordinary skips), Tray (5294 passed), and both focused HTTP cases passed. The PR body now includes the before/after evidence and the separate computer-use off/on check. This does not claim every lifecycle interleaving or green hosted CI.

@shanselman

Copy link
Copy Markdown
Collaborator Author

Hi @karkarl! I'm a Copilot triage bot posting for Scott (I'm not Scott). He asked me to assign this PR to you and see if you'd be up for reviewing it and merging it when you're happy with it.

This is one of five small fixes from the state machine audit in #2071 (Fix dangerous implicit state machines (audit lanes)). This one makes sure turning the local MCP server on or off during a restart can't leave it running when it should be off, or lose it when it should be on. Start and stop now share one lock.

CI note: the UI test job is red. The test host crashed in the known reasoning picker test family before the new MCP tests ran, and there is also a chat fixture timeout whose cause we haven't confirmed. Locally, the build, Shared tests, Tray tests and the two new real HTTP race tests all passed.

No rush at all, and please feel free to ask for changes or push back. Thank you so much!

@roboclaw-bot

Copy link
Copy Markdown
Contributor

PR cleanup review

Reviewed head: b74a343ee694df5f01ba2e16709f38555833c434. Main comparison: e59374c064f43d68f5c72d070d4c89ef2d20ec3b.

Source cleanup review at b74a343 against main e59374c: the lifecycle lock and ownership swap are not in main. The latest tests now exercise real NodeService publication and authenticated HTTP calls, so the older review that lacked that coverage is stale. Keep this candidate, but do not land from source review alone: current UI/CI Gate remains failed, and the remaining Gateway/token-rotation/drain overlap proof should be reconciled with the selected proof pools.

Action in this cleanup pass: leaving this PR open. No branch changes or runtime-proof waiver. The findings above come from source, discussion and recorded-CI review; Windows validation was not rerun in this pass.

@bkudiess
bkudiess merged commit c3bef89 into openclaw:main Nov 13, 2026
29 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

merge-risk: 🚨 security-boundary 🚨 Merging this PR could weaken sandboxing, authorization, credentials, or sensitive data. P2 Normal priority bug or improvement with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Make NodeService MCP server start and stop atomic

4 participants