Skip to content

Commit 03ad2bc

Browse files
committed
fix: harden cancellation response handling
Co-authored-by: Copilot App <[email protected]> Copilot-Session: 4ba999dd-6583-43ea-ac04-fcbe3c881113
1 parent 14db2d0 commit 03ad2bc

5 files changed

Lines changed: 236 additions & 9 deletions

File tree

‎docs/MCP_MODE.md‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -81,10 +81,13 @@ The capability list lives on `NodeService`, *not* on `WindowsNodeClient`. That s
8181
transport has no client identity, duplicate active IDs are allowed and
8282
cancellation is ignored when more than one active call matches; this prevents
8383
one local client from cancelling another client when the collision is already
84-
observable. A tombstone cannot predict a later cross-client ID collision, so
85-
it cancels the first matching registration; complete isolation would require
86-
client identity in the transport. A recent completion guard also prevents a
87-
late notification from poisoning immediate ID reuse.
84+
observable. Request matching uses the decoded JSON string value or normalized
85+
arbitrary-precision JSON number value, while preserving the distinction
86+
between string and numeric IDs. A tombstone cannot predict a later
87+
cross-client ID collision, so it cancels the first matching registration;
88+
complete isolation would require client identity in the transport. A recent
89+
completion guard also prevents a late notification from poisoning immediate
90+
ID reuse.
8891

8992
The bridge takes a `Func<IReadOnlyList<INodeCapability>>` rather than a snapshot. Every `tools/list` re-reads the live list. This is what guarantees zero-cost capability addition — register a new capability after server start and it appears on the next `tools/list`.
9093

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

Lines changed: 55 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
using System;
22
using System.Collections.Generic;
3+
using System.Globalization;
34
using System.IO;
5+
using System.Numerics;
46
using System.Text.Json;
57
using System.Threading;
68
using System.Threading.Tasks;
@@ -429,6 +431,7 @@ private async Task<object> HandleToolsCallAsync(
429431
}
430432

431433
var executionToken = invocation?.Token ?? cancellationToken;
434+
var cancelledByCaller = false;
432435
NodeInvokeResponse response;
433436
try
434437
{
@@ -456,6 +459,7 @@ private async Task<object> HandleToolsCallAsync(
456459
}
457460
finally
458461
{
462+
cancelledByCaller = invocation?.CancelledByCaller == true;
459463
invocation?.Dispose();
460464
}
461465

@@ -464,7 +468,7 @@ private async Task<object> HandleToolsCallAsync(
464468
var error = response.Error ?? "tool execution failed";
465469
if (error == "cancelled" &&
466470
executionToken.IsCancellationRequested &&
467-
invocation?.CancelledByCaller != true)
471+
!cancelledByCaller)
468472
{
469473
error = "request timed out";
470474
}
@@ -486,8 +490,56 @@ private async Task<object> HandleToolsCallAsync(
486490
};
487491
}
488492

489-
private static string GetRequestKey(JsonElement requestId)
490-
=> requestId.GetRawText();
493+
private static string GetRequestKey(JsonElement requestId) =>
494+
requestId.ValueKind switch
495+
{
496+
JsonValueKind.String => $"string:{requestId.GetString()}",
497+
JsonValueKind.Number => $"number:{NormalizeJsonNumber(requestId.GetRawText())}",
498+
_ => $"{requestId.ValueKind}:{requestId.GetRawText()}",
499+
};
500+
501+
private static string NormalizeJsonNumber(string rawNumber)
502+
{
503+
var exponentIndex = rawNumber.IndexOfAny('e', 'E');
504+
var mantissa = exponentIndex >= 0 ? rawNumber[..exponentIndex] : rawNumber;
505+
var exponent = exponentIndex >= 0
506+
? BigInteger.Parse(
507+
rawNumber.AsSpan(exponentIndex + 1),
508+
NumberStyles.AllowLeadingSign,
509+
CultureInfo.InvariantCulture)
510+
: BigInteger.Zero;
511+
512+
var negative = mantissa[0] == '-';
513+
if (negative)
514+
{
515+
mantissa = mantissa[1..];
516+
}
517+
518+
var decimalIndex = mantissa.IndexOf('.');
519+
var fractionalDigits = decimalIndex >= 0 ? mantissa.Length - decimalIndex - 1 : 0;
520+
var digits = decimalIndex >= 0 ? mantissa.Remove(decimalIndex, 1) : mantissa;
521+
exponent -= fractionalDigits;
522+
523+
digits = digits.TrimStart('0');
524+
if (digits.Length == 0)
525+
{
526+
return "0";
527+
}
528+
529+
var trailingZeros = 0;
530+
while (digits.Length - trailingZeros > 1 && digits[^(trailingZeros + 1)] == '0')
531+
{
532+
trailingZeros++;
533+
}
534+
535+
if (trailingZeros > 0)
536+
{
537+
digits = digits[..^trailingZeros];
538+
exponent += trailingZeros;
539+
}
540+
541+
return $"{(negative ? "-" : string.Empty)}{digits}e{exponent}";
542+
}
491543

492544
private static string WriteResult(JsonElement? id, object result)
493545
{

‎src/OpenClaw.Shared/WindowsNodeClient.cs‎

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1316,15 +1316,33 @@ private static bool TryGetCancellationTargetId(JsonElement container, out string
13161316

13171317
private void RaiseInvokeCompleted(string requestId, string command, bool ok, string? error, TimeSpan duration)
13181318
{
1319-
InvokeCompleted?.Invoke(this, new NodeInvokeCompletedEventArgs
1319+
var handlers = InvokeCompleted;
1320+
if (handlers is null)
1321+
return;
1322+
1323+
var args = new NodeInvokeCompletedEventArgs
13201324
{
13211325
RequestId = requestId,
13221326
Command = command,
13231327
Ok = ok,
13241328
Error = error,
13251329
Duration = duration,
13261330
NodeId = _nodeId ?? _deviceIdentity.DeviceId
1327-
});
1331+
};
1332+
1333+
foreach (var handler in handlers.GetInvocationList())
1334+
{
1335+
try
1336+
{
1337+
((EventHandler<NodeInvokeCompletedEventArgs>)handler)(this, args);
1338+
}
1339+
catch (Exception ex)
1340+
{
1341+
_logger.Warn(
1342+
$"[NODE] InvokeCompleted subscriber " +
1343+
$"{handler.Method.DeclaringType?.Name}.{handler.Method.Name} threw: {ex.Message}");
1344+
}
1345+
}
13281346
}
13291347

13301348
private async Task SendInvokeResponseAsync(NodeInvokeResponse response)

‎tests/OpenClaw.Shared.Tests/McpToolBridgeTests.cs‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -386,6 +386,44 @@ await bridge.HandleRequestAsync(
386386
doc.RootElement.GetProperty("result").GetProperty("content")[0].GetProperty("text").GetString());
387387
}
388388

389+
[Fact]
390+
public async Task CancellationNotification_MatchesEquivalentEscapedStringRequestId()
391+
{
392+
var capability = new CancellableCapability();
393+
var bridge = CreateBridge([capability]);
394+
var callTask = bridge.HandleRequestAsync(
395+
"""{"jsonrpc":"2.0","id":"request","method":"tools/call","params":{"name":"slow.wait","arguments":{}}}""");
396+
await capability.Entered.WaitAsync(TimeSpan.FromSeconds(5));
397+
398+
await bridge.HandleRequestAsync(
399+
"""{"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":"\u0072equest"}}""");
400+
var response = await callTask.WaitAsync(TimeSpan.FromSeconds(5));
401+
402+
using var doc = JsonDocument.Parse(response!);
403+
Assert.Equal(
404+
"cancelled",
405+
doc.RootElement.GetProperty("result").GetProperty("content")[0].GetProperty("text").GetString());
406+
}
407+
408+
[Fact]
409+
public async Task CancellationNotification_MatchesEquivalentNumericRequestId()
410+
{
411+
var capability = new CancellableCapability();
412+
var bridge = CreateBridge([capability]);
413+
var callTask = bridge.HandleRequestAsync(
414+
"""{"jsonrpc":"2.0","id":1.0e2,"method":"tools/call","params":{"name":"slow.wait","arguments":{}}}""");
415+
await capability.Entered.WaitAsync(TimeSpan.FromSeconds(5));
416+
417+
await bridge.HandleRequestAsync(
418+
"""{"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":100}}""");
419+
var response = await callTask.WaitAsync(TimeSpan.FromSeconds(5));
420+
421+
using var doc = JsonDocument.Parse(response!);
422+
Assert.Equal(
423+
"cancelled",
424+
doc.RootElement.GetProperty("result").GetProperty("content")[0].GetProperty("text").GetString());
425+
}
426+
389427
[Fact]
390428
public async Task UnknownMethod_ReturnsJsonRpcMethodNotFound()
391429
{

‎tests/OpenClaw.Shared.Tests/WindowsNodeClientTests.cs‎

Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1886,6 +1886,103 @@ public async Task CommandDispatch_EventPath_RoutesToRegisteredCapability()
18861886
}
18871887
}
18881888

1889+
[Fact]
1890+
public async Task CommandDispatch_RequestPath_ThrowingCompletionSubscriber_DoesNotSuppressResponse()
1891+
{
1892+
var dataPath = Path.Combine(Path.GetTempPath(), $"openclaw-node-test-{Guid.NewGuid():N}");
1893+
Directory.CreateDirectory(dataPath);
1894+
1895+
try
1896+
{
1897+
using var client = new CapturingWindowsNodeClient(
1898+
"ws://localhost:18789",
1899+
"test-token",
1900+
dataPath);
1901+
var capability = new MockCapability("mock", "mock.ping");
1902+
client.RegisterCapability(capability);
1903+
var laterSubscriberCalled = new TaskCompletionSource(
1904+
TaskCreationOptions.RunContinuationsAsynchronously);
1905+
client.InvokeCompleted += (_, _) => throw new InvalidOperationException("subscriber failure");
1906+
client.InvokeCompleted += (_, args) =>
1907+
{
1908+
if (args.RequestId == "invoke-throw-request")
1909+
{
1910+
laterSubscriberCalled.TrySetResult();
1911+
}
1912+
};
1913+
1914+
await InvokeProcessMessageAsync(
1915+
client,
1916+
BuildNodeInvokeRequest("invoke-throw-request", "mock.ping"));
1917+
1918+
await laterSubscriberCalled.Task.WaitAsync(TimeSpan.FromSeconds(5));
1919+
var responseJson = await WaitForSentMessageAsync(
1920+
client,
1921+
message => message.Contains("\"id\":\"invoke-throw-request\"", StringComparison.Ordinal));
1922+
using var response = JsonDocument.Parse(responseJson);
1923+
Assert.Equal("res", response.RootElement.GetProperty("type").GetString());
1924+
Assert.True(response.RootElement.GetProperty("ok").GetBoolean());
1925+
}
1926+
finally
1927+
{
1928+
if (Directory.Exists(dataPath))
1929+
Directory.Delete(dataPath, true);
1930+
}
1931+
}
1932+
1933+
[Fact]
1934+
public async Task CommandDispatch_EventPath_ThrowingCompletionSubscriber_DoesNotSuppressResult()
1935+
{
1936+
var dataPath = Path.Combine(Path.GetTempPath(), $"openclaw-node-test-{Guid.NewGuid():N}");
1937+
Directory.CreateDirectory(dataPath);
1938+
1939+
try
1940+
{
1941+
using var client = new CapturingWindowsNodeClient(
1942+
"ws://localhost:18789",
1943+
"test-token",
1944+
dataPath);
1945+
var capability = new MockCapability("mock", "mock.ping");
1946+
client.RegisterCapability(capability);
1947+
var laterSubscriberCalled = new TaskCompletionSource(
1948+
TaskCreationOptions.RunContinuationsAsynchronously);
1949+
client.InvokeCompleted += (_, _) => throw new InvalidOperationException("subscriber failure");
1950+
client.InvokeCompleted += (_, args) =>
1951+
{
1952+
if (args.RequestId == "invoke-throw-event")
1953+
{
1954+
laterSubscriberCalled.TrySetResult();
1955+
}
1956+
};
1957+
1958+
await InvokeProcessMessageAsync(client, """
1959+
{
1960+
"type": "event",
1961+
"event": "node.invoke.request",
1962+
"payload": {
1963+
"requestId": "invoke-throw-event",
1964+
"command": "mock.ping",
1965+
"args": {}
1966+
}
1967+
}
1968+
""");
1969+
1970+
await laterSubscriberCalled.Task.WaitAsync(TimeSpan.FromSeconds(5));
1971+
var responseJson = await WaitForSentMessageAsync(
1972+
client,
1973+
message => message.Contains("\"method\":\"node.invoke.result\"", StringComparison.Ordinal) &&
1974+
message.Contains("\"id\":\"invoke-throw-event\"", StringComparison.Ordinal));
1975+
using var response = JsonDocument.Parse(responseJson);
1976+
Assert.Equal("req", response.RootElement.GetProperty("type").GetString());
1977+
Assert.True(response.RootElement.GetProperty("params").GetProperty("ok").GetBoolean());
1978+
}
1979+
finally
1980+
{
1981+
if (Directory.Exists(dataPath))
1982+
Directory.Delete(dataPath, true);
1983+
}
1984+
}
1985+
18891986
[Fact]
18901987
public async Task CommandDispatch_SlowCapability_DoesNotBlockNextInvoke()
18911988
{
@@ -2193,6 +2290,25 @@ private static async Task InvokeProcessMessageAsync(WindowsNodeClient client, st
21932290
await task;
21942291
}
21952292

2293+
private static async Task<string> WaitForSentMessageAsync(
2294+
CapturingWindowsNodeClient client,
2295+
Func<string, bool> predicate)
2296+
{
2297+
using var timeout = new CancellationTokenSource(TimeSpan.FromSeconds(5));
2298+
while (!timeout.IsCancellationRequested)
2299+
{
2300+
var message = client.SentMessages.FirstOrDefault(predicate);
2301+
if (message != null)
2302+
{
2303+
return message;
2304+
}
2305+
2306+
await Task.Delay(10, timeout.Token);
2307+
}
2308+
2309+
throw new TimeoutException("Expected gateway response was not sent.");
2310+
}
2311+
21962312
private static string BuildNodeInvokeRequest(string requestId, string command)
21972313
=> $$"""
21982314
{

0 commit comments

Comments
 (0)