Repository navigation
feat: local MCP HTTP server mode for the Windows tray - #234
Merged
Merged
Conversation
Co-authored-by: Copilot <[email protected]>
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]>
10 of 17 tasks
6 of 16 tasks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
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 to127.0.0.1, defensiveIsLoopbackcheck, and a CSRF/DNS-rebinding gate (reject any request with anOriginheader, non-127.0.0.1/localhostHost, or non-application/jsonPOST).McpToolBridge(src/OpenClaw.Shared/Mcp/McpToolBridge.cs): transport-agnostic JSON-RPC core that auto-discovers tools from the liveINodeCapabilityregistry, with curated per-command descriptions fortools/listand graceful handling ofresources/list/prompts/listprobes.NodeServiceMCP-only mode:StartLocalOnlyAsync()brings up capabilities without a gateway WebSocket; tray Settings gets an MCP toggle + status surface.system.runtimeoutMsclamped (<=0→ default, capped at 10 minutes).StopAsyncdrains in-flight handlers with a 5s budget before tearing the semaphore down. Removes theTask.Run(..., ct)cancellation-before-delegate-start race that could leak slots.camera.clipfloor-clamps duration so 0/negative no longer slips through.HttpListenerExceptionstartup errors categorized —URL ACL access deniedincludes the exactnetsh http add urlaclremediation; 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
Originheader, mismatchedHost, or non-application/jsonPOST is rejected before reaching capability code.Test plan
OpenClaw.Shared.Testssuite. New coverage adds:tools/callwith a wedged tool returns "request timed out".ObjectDisposedException/SemaphoreFullException.Debug|x64.curl http://127.0.0.1:8765/returns the friendly probe;tools/listand asystem.notifytools/callwork from Claude Desktop / curl with MCP toggle on.🤖 Generated with Claude Code