Skip to content

Commit 053501c

Browse files
bkudiessCopilotCopilot
authored
Add connection diagnostics MCP commands (#961)
Expose read-only local MCP diagnostics for connection state and saved gateways. Add snapshot-derived projection, command docs, and regression coverage for credential-safe URL display and degenerate gateway records. Co-authored-by: Copilot <[email protected]> Co-authored-by: Copilot App <[email protected]>
1 parent 8a9e351 commit 053501c

14 files changed

Lines changed: 876 additions & 6 deletions

File tree

‎docs/CONNECTION_ARCHITECTURE.md‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,29 @@ Idle → Connecting → Connected
123123

124124
`GatewayConnectionSnapshot.NodeConnectionIntended` records the Node mode intent used by the manager's state machine. If Node mode is enabled but node startup is skipped, blocked, or missing a node credential, the manager publishes a blocked node snapshot (`NodeState=Error`, `NodeError=...`) instead of leaving the node idle and letting tray surfaces report a healthy connection.
125125

126+
### Status projection and legacy ledger
127+
128+
`GatewayConnectionManager.CurrentSnapshot` is the lifecycle truth. Tray/UI state
129+
must treat `AppState.Status` / `ConnectionStatus` as a derived compatibility
130+
projection only, produced from the manager snapshot by
131+
`ConnectionStatusPresenter`. New connection diagnostics should read
132+
`GatewayConnectionSnapshot`, `GatewayRegistry`, and `ConnectionDiagnostics`
133+
directly instead of writing a second runtime model.
134+
135+
Current derived compatibility debt:
136+
137+
| Surface | Status | Notes |
138+
|---|---|---|
139+
| `AppState.Status` | Derived read-side adapter | The only writer is the manager `StateChanged` handler, which maps the snapshot through `ConnectionStatusPresenter` for older UI consumers. |
140+
| `ConnectionStatus` enum | Retained | Still used by shared gateway/client and tray read-side surfaces. Do not remove it until protocol/client and UI consumers are separated in a smaller migration. |
141+
| Command Center / tray projections | Mixed | New diagnostics use snapshot-derived DTOs. Some older warnings still read `AppStateSnapshot.Status`; those reads are compatibility gates, not lifecycle ownership. |
142+
143+
The local MCP `app.connection.status` command is the agent-facing projection of
144+
this model. It reports effective mode/state, active gateway metadata,
145+
operator/node credential resolution, MCP runtime state, browser-proxy caveats,
146+
pending approval actions, retry hints from diagnostics, and recent diagnostic
147+
events without exposing token values.
148+
126149
## Gateway registry and persistence
127150

128151
`GatewayRegistry` is the source of truth for configured gateways:

‎docs/MCP_MODE.md‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,7 @@ The capability list lives on `NodeService`, *not* on `WindowsNodeClient`. That s
6363
`OpenClaw.Shared/Mcp/McpToolBridge.cs` is transport-agnostic JSON-RPC 2.0. It implements:
6464

6565
- `initialize` — protocol version `2024-11-05`, server info.
66-
- `tools/list` — flattens `_capabilities` into MCP tools. Tool name = command name (`"screen.snapshot"`); description = `"{category} capability: {command}"`; `inputSchema` is permissive.
66+
- `tools/list` — flattens `_capabilities` into MCP tools. Tool name = command name (`"screen.snapshot"`); known commands get curated descriptions from `McpToolBridge.CommandDescriptions`; unknown commands fall back to `"{category} capability: {command}"`. `inputSchema` is permissive.
6767
- `tools/call` — finds the capability via `INodeCapability.CanHandle(name)`, builds a `NodeInvokeRequest` (the same struct the gateway path uses), calls `ExecuteAsync`, wraps the result as MCP `content[].text`. Tool failures come back as `result.isError = true`, not JSON-RPC errors (per MCP spec — JSON-RPC errors are reserved for protocol issues).
6868
- `ping`, `notifications/initialized` — protocol housekeeping.
6969

@@ -173,7 +173,15 @@ Local MCP-only app control commands currently include:
173173

174174
- `app.navigate`, `app.status`, `app.sessions`, `app.agents`, `app.nodes`, `app.config.get`, `app.settings.get`, `app.settings.set`, `app.menu`, `app.search`, `app.dashboard.url`
175175
- Chat automation: `app.chat.snapshot`, `app.chat.send`, `app.chat.reset`
176-
- Connection automation: `app.connection.applySetupCode`, `app.connection.connectSharedToken`, `app.connection.pendingApprovals`, `app.connection.approveDevicePairing`, `app.connection.rejectDevicePairing`, `app.connection.approveNodePairing`, `app.connection.rejectNodePairing`, `app.connection.reconnect`, `app.connection.reconnectNode`
176+
- Connection diagnostics/automation: `app.connection.status`, `app.connection.gateways`, `app.connection.applySetupCode`, `app.connection.connectSharedToken`, `app.connection.pendingApprovals`, `app.connection.approveDevicePairing`, `app.connection.rejectDevicePairing`, `app.connection.approveNodePairing`, `app.connection.rejectNodePairing`, `app.connection.reconnect`, `app.connection.reconnectNode`
177+
178+
For connection troubleshooting, prefer `app.connection.status` over the older
179+
`app.status` summary. It is read-only and returns the manager-owned
180+
operator/node snapshot, active gateway metadata, credential source/status,
181+
MCP listener state, browser-proxy shared-token caveat, pending approval commands,
182+
retry hints inferred from recent diagnostics, and recent diagnostic events.
183+
`app.connection.gateways` lists saved gateway records with credential presence
184+
booleans only; it never returns token values.
177185

178186
Example chat automation smoke:
179187

‎docs/WINDOWS_NODE_TESTING.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,7 @@ When the node connects, it advertises these capabilities:
104104
- `tts` - Windows speech synthesis or ElevenLabs playback, when enabled in Settings
105105
- `stt` - Local speech-to-text via Whisper.net, when enabled in Settings
106106

107-
Local MCP clients also see MCP-only `app.*` commands such as `app.navigate`, `app.status`, `app.chat.snapshot`/`app.chat.send`/`app.chat.reset`, and `app.chat.queue.list`/`app.chat.queue.cancel`. These are local testing and automation hooks registered with the tray's MCP server and are not advertised to the gateway WebSocket.
107+
Local MCP clients also see MCP-only `app.*` commands such as `app.navigate`, `app.status`, `app.chat.snapshot`/`app.chat.send`/`app.chat.reset`, and `app.chat.queue.list`/`app.chat.queue.cancel`. Connection diagnostics and setup tools live under `app.connection.*`; use `app.connection.status` to inspect active gateway, operator/node credential state, MCP runtime status, browser proxy caveat, pending approval commands, and recent diagnostics, and `app.connection.gateways` to list saved gateway records without token values. These are local testing and automation hooks registered with the tray's MCP server and are not advertised to the gateway WebSocket.
108108

109109
## Security Features
110110

‎src/OpenClaw.Shared/Capabilities/AppConnectionCapability.cs‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@ public sealed class AppConnectionCapability : NodeCapabilityBase
1414

1515
private static readonly string[] s_commands =
1616
[
17+
"app.connection.status",
18+
"app.connection.gateways",
1719
"app.connection.applySetupCode",
1820
"app.connection.connectSharedToken",
1921
"app.connection.pendingApprovals",
@@ -29,6 +31,8 @@ public sealed class AppConnectionCapability : NodeCapabilityBase
2931

3032
public Func<string, Task<object?>>? ApplySetupCodeHandler;
3133
public Func<string, string, Task<object?>>? ConnectSharedTokenHandler;
34+
public Func<Task<object?>>? StatusHandler;
35+
public Func<Task<object?>>? GatewaysHandler;
3236
public Func<Task<object?>>? PendingApprovalsHandler;
3337
public Func<string, Task<object?>>? ApproveDevicePairingHandler;
3438
public Func<string, Task<object?>>? RejectDevicePairingHandler;
@@ -43,6 +47,8 @@ public override async Task<NodeInvokeResponse> ExecuteAsync(NodeInvokeRequest re
4347
{
4448
return request.Command switch
4549
{
50+
"app.connection.status" => await HandleStatus(),
51+
"app.connection.gateways" => await HandleGateways(),
4652
"app.connection.applySetupCode" => await HandleApplySetupCode(request),
4753
"app.connection.connectSharedToken" => await HandleConnectSharedToken(request),
4854
"app.connection.pendingApprovals" => await HandlePendingApprovals(),
@@ -56,6 +62,22 @@ public override async Task<NodeInvokeResponse> ExecuteAsync(NodeInvokeRequest re
5662
};
5763
}
5864

65+
private async Task<NodeInvokeResponse> HandleStatus()
66+
{
67+
if (StatusHandler == null)
68+
return Error("Connection status handler not registered");
69+
var result = await StatusHandler();
70+
return Success(result);
71+
}
72+
73+
private async Task<NodeInvokeResponse> HandleGateways()
74+
{
75+
if (GatewaysHandler == null)
76+
return Error("Connection gateways handler not registered");
77+
var result = await GatewaysHandler();
78+
return Success(result);
79+
}
80+
5981
private async Task<NodeInvokeResponse> HandleApplySetupCode(NodeInvokeRequest request)
6082
{
6183
var setupCode = GetStringArg(request.Args, "setupCode");

‎src/OpenClaw.Shared/GatewayUrlHelper.cs‎

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,9 @@ public static string DecodeCredentials(string credentials)
7777
}
7878

7979
/// <summary>
80-
/// Remove user-info credentials from a URL for safe logging and display.
80+
/// Remove user-info credentials plus query/fragment data from a URL for safe
81+
/// logging and display. Gateway URLs can carry token-like query parameters
82+
/// even when the connection stack does not normally use them.
8183
/// </summary>
8284
public static string SanitizeForDisplay(string? gatewayUrl)
8385
{
@@ -86,7 +88,7 @@ public static string SanitizeForDisplay(string? gatewayUrl)
8688
return gatewayUrl?.Trim() ?? string.Empty;
8789
}
8890

89-
return RemoveUserInfo(gatewayUrl.Trim());
91+
return RemoveQueryAndFragment(RemoveUserInfo(gatewayUrl.Trim()));
9092
}
9193

9294
public static bool TryNormalizeWebSocketUrl(string? gatewayUrl, out string normalizedUrl)
@@ -156,5 +158,18 @@ private static string RemoveUserInfo(string url)
156158

157159
return string.Concat(url.AsSpan(0, authorityStart), url.AsSpan(atIndex + 1));
158160
}
159-
}
160161

162+
private static string RemoveQueryAndFragment(string url)
163+
{
164+
var queryIndex = url.IndexOf('?');
165+
var fragmentIndex = url.IndexOf('#');
166+
var cutIndex = queryIndex switch
167+
{
168+
>= 0 when fragmentIndex >= 0 => Math.Min(queryIndex, fragmentIndex),
169+
>= 0 => queryIndex,
170+
_ => fragmentIndex
171+
};
172+
173+
return cutIndex >= 0 ? url[..cutIndex] : url;
174+
}
175+
}

‎src/OpenClaw.Shared/Mcp/McpToolBridge.cs‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -284,6 +284,28 @@ private object HandleToolsList()
284284
"READ-ALL: List native chat outgoing queue entries. Args: threadId/sessionKey (string, optional; omit to return all queued threads). Returns { defaultThreadId, requestedThreadId, totalCount, selectedThread, threads: [{ threadId, count, messages: [{ id, text, createdAt, sendState, errorText, canCancel }] }] }.",
285285
["app.chat.queue.cancel"] =
286286
"Cancel/remove one native chat outgoing queue entry before it is sent. Args: queuedMessageId (string, required), threadId/sessionKey (string, required; use the threadId returned by app.chat.queue.list or app.chat.snapshot). Only Queued/Failed entries can be removed; Sending entries may already have reached the gateway. Returns { canceled, threadId, queuedMessageId, remainingCount, error? }.",
287+
["app.connection.status"] =
288+
"READ-ONLY local MCP connection diagnostics. No args. Returns effective mode/state, active gateway metadata, operator/node credential resolution, MCP runtime state, browser proxy caveat, pending approval actions, retry hints, and recent diagnostic events.",
289+
["app.connection.gateways"] =
290+
"READ-ONLY saved gateway diagnostics. No args. Returns { activeGatewayId, count, gateways[] } with per-gateway id/name/url, active flag, lastConnected, credential presence booleans, SSH/browser-proxy configuration, and no token values.",
291+
["app.connection.applySetupCode"] =
292+
"Apply a setup/QR code to create or update the active gateway record and connect. Args: setupCode (string, required). Local MCP-only; not advertised to the gateway node transport. Returns { outcome, error, gatewayUrl, connected }.",
293+
["app.connection.connectSharedToken"] =
294+
"Connect the tray to a gateway using a shared token. Args: gatewayUrl (string, required), token (string, required). Persists the gateway record and active gateway. Local MCP-only. Returns { outcome, error, gatewayUrl, connected }.",
295+
["app.connection.pendingApprovals"] =
296+
"READ-ONLY pending pairing approval snapshot from the connected gateway. No args. Returns { connected, error, totalPending, devicePending[], nodePending[] }.",
297+
["app.connection.approveDevicePairing"] =
298+
"Approve a pending device pairing request through the connected operator client. Args: requestId or id (string, required). Local MCP-only. Returns the refreshed pending approvals payload plus decision metadata.",
299+
["app.connection.rejectDevicePairing"] =
300+
"Reject a pending device pairing request through the connected operator client. Args: requestId or id (string, required). Local MCP-only. Returns the refreshed pending approvals payload plus decision metadata.",
301+
["app.connection.approveNodePairing"] =
302+
"Approve a pending Windows node pairing or command-trust request through the connected operator client. Args: requestId or id (string, required). Local MCP-only. Returns the refreshed pending approvals payload plus decision metadata.",
303+
["app.connection.rejectNodePairing"] =
304+
"Reject a pending Windows node pairing or command-trust request through the connected operator client. Args: requestId or id (string, required). Local MCP-only. Returns the refreshed pending approvals payload plus decision metadata.",
305+
["app.connection.reconnect"] =
306+
"Reconnect the active gateway through GatewayConnectionManager. No args. Local MCP-only. Returns { reconnected, error? }.",
307+
["app.connection.reconnectNode"] =
308+
"Reconnect only the Windows node role for the active gateway through GatewayConnectionManager. No args. Local MCP-only. Returns { reconnected, error? }.",
287309

288310
// location.*
289311
["location.get"] =

‎src/OpenClaw.Tray.WinUI/App.CapabilityHandlers.cs‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -233,6 +233,34 @@ private void WireAppCapabilityHandlers()
233233
app.ChatQueueListHandler = ListQueuedChatMessagesForMcpAsync;
234234
app.ChatQueueCancelHandler = CancelQueuedChatMessageForMcpAsync;
235235

236+
connection.StatusHandler = () =>
237+
{
238+
var enableMcpServer = _settings?.EnableMcpServer == true;
239+
var isMcpRunning = _nodeService?.IsMcpRunning == true;
240+
var mcpPlan = McpRuntimeStatePolicy.PlanStartupNotification(
241+
enableMcpServer,
242+
isMcpRunning,
243+
_nodeService?.McpStartupError);
244+
var diagnostics = _connectionManager?.Diagnostics;
245+
var recentDiagnostics = diagnostics?.GetRecent(50) ?? [];
246+
return Task.FromResult<object?>(ConnectionDiagnosticsProjection.BuildStatus(
247+
_connectionManager?.CurrentSnapshot,
248+
_gatewayRegistry?.GetActive(),
249+
enableNodeMode: _settings?.EnableNodeMode == true,
250+
enableMcpServer: enableMcpServer,
251+
isMcpRunning: isMcpRunning,
252+
mcpError: mcpPlan.ShouldShow ? mcpPlan.Message : null,
253+
nodeBrowserProxyEnabled: _settings?.NodeBrowserProxyEnabled != false,
254+
recentDiagnostics: recentDiagnostics,
255+
diagnosticEventCount: diagnostics?.Count ?? recentDiagnostics.Count));
256+
};
257+
258+
connection.GatewaysHandler = () =>
259+
Task.FromResult<object?>(ConnectionDiagnosticsProjection.BuildGateways(
260+
_gatewayRegistry?.GetAll() ?? [],
261+
_gatewayRegistry?.ActiveGatewayId,
262+
nodeBrowserProxyEnabled: _settings?.NodeBrowserProxyEnabled != false));
263+
236264
connection.ApplySetupCodeHandler = async setupCode =>
237265
{
238266
if (_connectionManager == null)

0 commit comments

Comments
 (0)