Skip to content

feat: local MCP HTTP server mode for the Windows tray - #234

Merged
shanselman merged 4 commits into
openclaw:masterfrom
codemonkeychris:feat/mcp-mode
Apr 27, 2026
Merged

shanselman merged 4 commits into
openclaw:masterfrom
codemonkeychris:feat/mcp-mode

Conversation

@codemonkeychris

Copy link
Copy Markdown
Contributor

Summary

  • Adds an optional local MCP (Model Context Protocol) HTTP server hosted by the Windows tray, exposing the existing node capabilities (system / canvas / screen / camera / location / device) to local MCP clients (Claude Desktop, Cursor, Claude Code, curl, etc.) without requiring a gateway connection.
  • Independent of node mode — can run alongside the gateway client or stand-alone in MCP-only mode.
  • Hardened against the common local-HTTP attack surface (DNS rebinding, browser CSRF, oversized bodies, concurrency exhaustion) and addresses code-review feedback for cancellation, drain-on-shutdown, argument clamping, and operability.

What ships

  • McpHttpServer (src/OpenClaw.Shared/Mcp/McpHttpServer.cs): loopback-only HTTP listener (http://127.0.0.1:8765/) with three layers of defense — bind to 127.0.0.1, defensive IsLoopback check, and a CSRF/DNS-rebinding gate (reject any request with an Origin header, non-127.0.0.1/localhost Host, or non-application/json POST).
  • McpToolBridge (src/OpenClaw.Shared/Mcp/McpToolBridge.cs): transport-agnostic JSON-RPC core that auto-discovers tools from the live INodeCapability registry, with curated per-command descriptions for tools/list and graceful handling of resources/list / prompts/list probes.
  • NodeService MCP-only mode: StartLocalOnlyAsync() brings up capabilities without a gateway WebSocket; tray Settings gets an MCP toggle + status surface.
  • Stability / hardening (later commits in this branch):
    • Per-request 90s deadline propagated through body-read and bridge dispatch; system.run timeoutMs clamped (<=0 → default, capped at 10 minutes).
    • Active handler tracking; StopAsync drains in-flight handlers with a 5s budget before tearing the semaphore down. Removes the Task.Run(..., ct) cancellation-before-delegate-start race that could leak slots.
    • Boundary clamps in screen / camera / canvas capabilities for dimensions, quality, monitor index, durations, fps, window position. camera.clip floor-clamps duration so 0/negative no longer slips through.
    • HttpListenerException startup errors categorized — URL ACL access denied includes the exact netsh http add urlacl remediation; port-in-use is called out by name. Settings status replaces stale "save and restart" wording with "Will start/stop on Save".

Threat model — explicit non-goals

  • Off-machine reachability: blocked. Loopback bind + Host allowlist mean other machines and DNS-rebinding pivots cannot reach the server, regardless of firewall config.
  • Browser CSRF: blocked. Any Origin header, mismatched Host, or non-application/json POST is rejected before reaching capability code.
  • Same-user local processes: intentionally trusted (parity with node-mode trust model). Per-tool authentication and exposure gating are tracked separately, not in scope of this PR.

Test plan

  • Unit tests pass: 933 passed / 20 skipped on the full OpenClaw.Shared.Tests suite. New coverage adds:
    • JSON-RPC envelope (parse error, method-not-found, tool error vs. JSON-RPC error, id round-tripping including non-integer / large numeric ids).
    • HTTP transport security (Origin reject, Host reject, content-type enforcement, oversized body, 204 for notifications, idempotent dispose).
    • Cancellation: tools/call with a wedged tool returns "request timed out".
    • Drain: dispose during in-flight handler does not surface ObjectDisposedException / SemaphoreFullException.
    • Slow body: stuck client doesn't pin a handler slot; subsequent requests succeed.
    • Boundary clamps: oversized screen-snapshot params and zero/negative camera-clip duration.
  • Tray builds clean for Debug|x64.
  • Manual smoke: curl http://127.0.0.1:8765/ returns the friendly probe; tools/list and a system.notify tools/call work from Claude Desktop / curl with MCP toggle on.
  • Manual smoke: enabling MCP with port already in use surfaces the "Port 8765 is already in use" message in Settings.

🤖 Generated with Claude Code

codemonkeychris and others added 4 commits April 27, 2026 09:33
Addresses review of the initial MCP HTTP server cut. Loopback bind alone
does not protect against browser-driven attacks — any page in the user's
browser is also on loopback. Adds a three-layer security gate, a body
size cap, a handler concurrency limit, and full HTTP-transport coverage.

Security
- McpHttpServer rejects requests with an Origin header (browsers always
  set it; real MCP clients never do). Validates Host against loopback
  names (DNS-rebinding pivot defense). Requires application/json on
  POST so a cross-origin browser fetch must trigger a CORS preflight,
  which we never satisfy.
- 4 MiB body cap with bounded streaming read (413 on overrun).
- 8-handler concurrency cap so a misbehaving local client cannot pin
  every threadpool thread on long-running screen/camera calls.
- Settings migration: legacy McpOnlyMode=false no longer silently
  inherits EnableNodeMode (would have flipped MCP on without consent).

Bridge
- _capabilities snapshotted to array per call (was racing concurrent
  enumeration vs UI-thread mutation).
- Non-integer / out-of-range / string ids round-trip via GetRawText
  instead of GetInt64 (used to strip the id from error responses on
  fractional or big-int ids, breaking client correlation).
- tools/call validates 'arguments' is an object if present and rejects
  empty 'name'.
- Generic 'internal error' on the wire for unhandled exceptions; full
  exception with stack goes to the log via Error(string, Exception).
- Empty resources/list and prompts/list for Cursor compat (was
  MethodNotFound).
- Non-object root → InvalidRequest.

Lifecycle
- Start() failure now disposes the half-constructed listener/CTS
  instead of leaking the port reservation.
- _disposed guarded with Interlocked.Exchange (idempotent across
  threads).
- App.xaml.cs warns when both modes are enabled but gateway
  prerequisites are missing — silent fall-back to MCP-only was
  confusing.
- NodeService.McpStartupError surfaces the actual failure to Settings
  UI; status text shows 'Failed to start: <reason>' instead of the
  misleading 'Stopped — save and restart to start'.

Refactor
- McpHttpServer moved from OpenClaw.Tray.WinUI/Services to
  OpenClaw.Shared/Mcp (no WinUI deps; lets it be unit-tested).

Tests
- 10 new McpToolBridgeTests: non-object root, missing/non-string
  params, non-object arguments, fractional/big-int/string ids,
  empty resources/prompts, generic-message guarantee on internal
  errors.
- New McpHttpServerTests (13): GET probe, valid POST, Origin reject,
  rebind-Host reject, localhost-Host accept, text/plain reject,
  json+charset accept, PUT reject, oversized body reject, notification
  204, idempotent dispose, ctor null guards.

Docs
- MCP_MODE.md: rewritten Security Model section with the three-layer
  model and curl-based 'verify the gate' examples; tool list updated
  to reflect master (screen.snapshot, camera.clip, location.get).

All 715 tests pass (32 MCP, 20 integration, 663 other).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Per code review (GPT 5.5), tightens stability and operability of the
local MCP transport without changing the loopback-only trust model.

CR-003 — bound request and tool execution
  * McpHttpServer: per-request linked CTS with 90s deadline; CT propagated
    through ReadBodyAsync (slow-body defense) and bridge dispatch.
  * McpToolBridge.HandleRequestAsync(body, ct) overload uses Task.WaitAsync
    so a wedged tool surfaces as a "request timed out" tool error instead
    of pinning a handler slot.
  * SystemCapability.HandleRunAsync clamps timeoutMs <= 0 to the default
    and caps at 10 minutes — closes the "wait forever" hole that
    LocalCommandRunner.TimeoutMs <= 0 previously enabled.

CR-005 — drain in-flight handlers before disposal
  * Track active handler tasks; StopAsync(drainTimeout) cancels CT, stops
    the listener, awaits in-flight handlers (5s) before Dispose tears the
    semaphore down. Removes the Task.Run(..., ct) cancellation race that
    could leak a slot, and defensively swallows ObjectDisposedException
    on semaphore release during shutdown.

CR-007 — clamp arguments at the capability boundary
  * Screen / camera / canvas capabilities now clamp dimensions, quality,
    monitor index, durations, fps, and window position to safe ranges
    before any allocation. camera.clip floor-clamps duration so 0/-N can
    no longer slip through the original Math.Min cap.

CR-008 — surface MCP startup status in Settings
  * Categorize HttpListenerException by NativeErrorCode (5 = URL ACL
    access denied with the exact netsh remediation; 32/183 = port in use).
  * Settings status replaces the misleading "save and restart" wording
    with "Will start/stop on Save", reflecting the OnSettingsSaved flow
    that reinitializes services immediately.

Tests: 22 new test cases (timeout tool error, dispose-during-handler
hygiene, slow-body recovery, clamp behavior). Full Shared.Tests suite
remains green at 933 passing.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Two follow-ups from code review:

1. Hardcoded i18n strings in SettingsWindow are now resource-driven.
   New x:Uid bindings cover the MCP toggle header, description,
   Endpoint/Status labels, plus a new "Developer Mode" section header
   above the toggle so the use case is visually scoped. Status text
   ("Disabled", "Listening", "Stopped", "Will start/stop on Save",
   "Failed to start: ") routed through LocalizationHelper. Translations
   added to en-us, fr-fr, nl-nl, zh-cn, and zh-tw. The diagnostic detail
   appended after "Failed to start:" intentionally stays in English —
   it embeds a literal `netsh http add urlacl` command that does not
   localize meaningfully.

2. NodeService._capabilities is now guarded by _capabilitiesLock on
   every read and write. The MCP bridge was previously snapshotting
   _capabilities.ToArray() on threadpool threads while the UI thread
   could be in the middle of RegisterCapabilities (Clear + adds). Low
   probability but real — a tools/list mid-rebuild could observe an
   empty or partial list. RegisterCapabilities now holds the lock for
   the full sync rebuild; DisconnectAsync's Clear and the bridge
   snapshot lambda also take it.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@shanselman
shanselman merged commit f7800d8 into openclaw:master Apr 27, 2026
@codemonkeychris
codemonkeychris deleted the feat/mcp-mode branch April 27, 2026 19:26
@clawsweeper clawsweeper Bot mentioned this pull request Jun 26, 2026
10 of 17 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants