-
Notifications
You must be signed in to change notification settings - Fork 680
Expand file tree
/
Copy pathTaskCancellationIntegrationTests.cs
More file actions
509 lines (429 loc) · 19.7 KB
/
TaskCancellationIntegrationTests.cs
File metadata and controls
509 lines (429 loc) · 19.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
using Microsoft.Extensions.DependencyInjection;
using ModelContextProtocol.Client;
using ModelContextProtocol.Protocol;
using ModelContextProtocol.Server;
using ModelContextProtocol.Tests.Utils;
using System.Text.Json;
namespace ModelContextProtocol.Tests.Server;
/// <summary>
/// Integration tests for task cancellation behavior, including TTL-based automatic
/// cancellation and explicit cancellation via tasks/cancel.
/// </summary>
public class TaskCancellationIntegrationTests : ClientServerTestBase
{
private readonly TaskCompletionSource<bool> _toolCancellationFired = new(TaskCreationOptions.RunContinuationsAsynchronously);
private readonly TaskCompletionSource<bool> _toolStarted = new(TaskCreationOptions.RunContinuationsAsynchronously);
public TaskCancellationIntegrationTests(ITestOutputHelper testOutputHelper)
: base(testOutputHelper)
{
}
protected override void ConfigureServices(ServiceCollection services, IMcpServerBuilder mcpServerBuilder)
{
// Add task store for server-side task support
var taskStore = new InMemoryMcpTaskStore();
services.AddSingleton<IMcpTaskStore>(taskStore);
services.Configure<McpServerOptions>(options =>
{
options.TaskStore = taskStore;
});
// Add a long-running tool that captures cancellation
mcpServerBuilder.WithTools([McpServerTool.Create(
async (CancellationToken ct) =>
{
_toolStarted.TrySetResult(true);
try
{
// Wait indefinitely until cancelled
await Task.Delay(Timeout.Infinite, ct);
return "completed";
}
catch (OperationCanceledException)
{
_toolCancellationFired.TrySetResult(true);
throw;
}
},
new McpServerToolCreateOptions
{
Name = "long-running-tool",
Description = "A tool that runs until cancelled"
})]);
}
private static IDictionary<string, JsonElement> EmptyArguments() => new Dictionary<string, JsonElement>();
[Fact]
public async Task TaskTool_CancellationToken_FiresWhenTtlExpires()
{
// Arrange
await using McpClient client = await CreateMcpClientForServer();
// Act - Call tool with short TTL (200ms)
var callResult = await client.CallToolAsync(
new CallToolRequestParams
{
Name = "long-running-tool",
Arguments = EmptyArguments(),
// Use a TTL long enough that thread pool scheduling delays on loaded CI machines
// don't cause the CTS to fire before the tool lambda begins executing.
Task = new McpTaskMetadata { TimeToLive = TimeSpan.FromSeconds(5) }
},
cancellationToken: TestContext.Current.CancellationToken);
// Verify task was created
Assert.NotNull(callResult.Task);
// Wait for the tool to start executing
await _toolStarted.Task.WaitAsync(TestConstants.DefaultTimeout, TestContext.Current.CancellationToken);
// Assert - Wait for the cancellation to fire (should happen when TTL expires)
var cancelled = await _toolCancellationFired.Task.WaitAsync(TestConstants.DefaultTimeout, TestContext.Current.CancellationToken);
Assert.True(cancelled, "Tool's CancellationToken should have been triggered when TTL expired");
// Note: TTL-based expiration does not explicitly set task status to Cancelled.
// Instead, expired tasks are considered "dead" and will be cleaned up by the task store.
// The task may still be in Working status or may throw "not found" if already cleaned up.
}
[Fact]
public async Task TaskTool_CancellationToken_FiresWhenExplicitlyCancelled()
{
// Arrange
await using McpClient client = await CreateMcpClientForServer();
// Start a long-running task with a long TTL
var callResult = await client.CallToolAsync(
new CallToolRequestParams
{
Name = "long-running-tool",
Arguments = EmptyArguments(),
Task = new McpTaskMetadata { TimeToLive = TimeSpan.FromMinutes(10) }
},
cancellationToken: TestContext.Current.CancellationToken);
Assert.NotNull(callResult.Task);
string taskId = callResult.Task.TaskId;
// Wait for the tool to start executing
await _toolStarted.Task.WaitAsync(TestConstants.DefaultTimeout, TestContext.Current.CancellationToken);
// Act - Explicitly cancel the task
var cancelledTask = await client.CancelTaskAsync(taskId, cancellationToken: TestContext.Current.CancellationToken);
// Assert - Wait for the cancellation to propagate to the tool
var cancelled = await _toolCancellationFired.Task.WaitAsync(TestConstants.DefaultTimeout, TestContext.Current.CancellationToken);
Assert.True(cancelled, "Tool's CancellationToken should have been triggered by explicit cancellation");
// Verify task status
Assert.Equal(McpTaskStatus.Cancelled, cancelledTask.Status);
}
[Fact]
public async Task TaskTool_CompletesSuccessfully_WhenNotCancelled()
{
// Arrange - Create a new test with a quick-completing tool
var quickToolCompleted = new TaskCompletionSource<string>(TaskCreationOptions.RunContinuationsAsynchronously);
var services = new ServiceCollection();
services.AddLogging();
var taskStore = new InMemoryMcpTaskStore();
services.AddSingleton<IMcpTaskStore>(taskStore);
var builder = services
.AddMcpServer()
.WithStreamServerTransport(
new System.IO.Pipelines.Pipe().Reader.AsStream(),
new System.IO.Pipelines.Pipe().Writer.AsStream());
builder.WithTools([McpServerTool.Create(
async (string input, CancellationToken ct) =>
{
await Task.Delay(50, ct); // Quick operation
var result = $"Result: {input}";
quickToolCompleted.TrySetResult(result);
return result;
},
new McpServerToolCreateOptions
{
Name = "quick-tool",
Description = "A tool that completes quickly"
})]);
services.Configure<McpServerOptions>(options =>
{
options.TaskStore = taskStore;
});
await using var client = await CreateMcpClientForServer();
// Act - Call tool with long TTL
var callResult = await client.CallToolAsync(
new CallToolRequestParams
{
Name = "long-running-tool", // Use the base class tool which will block
Arguments = EmptyArguments(),
Task = new McpTaskMetadata { TimeToLive = TimeSpan.FromMinutes(5) }
},
cancellationToken: TestContext.Current.CancellationToken);
Assert.NotNull(callResult.Task);
// Verify task is in working state initially
var task = await client.GetTaskAsync(callResult.Task.TaskId, cancellationToken: TestContext.Current.CancellationToken);
Assert.Equal(McpTaskStatus.Working, task.Status);
}
}
/// <summary>
/// Tests for task cancellation with multiple concurrent tasks.
/// </summary>
public class TaskCancellationConcurrencyTests : ClientServerTestBase
{
private readonly Dictionary<string, TaskCompletionSource<bool>> _toolCancellations = new();
private readonly Dictionary<string, TaskCompletionSource<bool>> _toolStarts = new();
private readonly object _lock = new();
public TaskCancellationConcurrencyTests(ITestOutputHelper testOutputHelper)
: base(testOutputHelper)
{
}
protected override void ConfigureServices(ServiceCollection services, IMcpServerBuilder mcpServerBuilder)
{
var taskStore = new InMemoryMcpTaskStore();
services.AddSingleton<IMcpTaskStore>(taskStore);
services.Configure<McpServerOptions>(options =>
{
options.TaskStore = taskStore;
});
// Tool that tracks cancellation per-invocation using a marker argument
mcpServerBuilder.WithTools([McpServerTool.Create(
async (string marker, CancellationToken ct) =>
{
TaskCompletionSource<bool> startTcs;
TaskCompletionSource<bool> cancelTcs;
lock (_lock)
{
if (!_toolStarts.TryGetValue(marker, out startTcs!))
{
startTcs = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
_toolStarts[marker] = startTcs;
}
if (!_toolCancellations.TryGetValue(marker, out cancelTcs!))
{
cancelTcs = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
_toolCancellations[marker] = cancelTcs;
}
}
startTcs.TrySetResult(true);
try
{
await Task.Delay(Timeout.Infinite, ct);
return $"completed-{marker}";
}
catch (OperationCanceledException)
{
cancelTcs.TrySetResult(true);
throw;
}
},
new McpServerToolCreateOptions
{
Name = "trackable-tool",
Description = "A tool that can be tracked by marker"
})]);
}
private void RegisterMarker(string marker)
{
lock (_lock)
{
_toolStarts[marker] = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
_toolCancellations[marker] = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
}
}
private Task WaitForStart(string marker, CancellationToken ct)
{
lock (_lock)
{
return _toolStarts[marker].Task.WaitAsync(TestConstants.DefaultTimeout, ct);
}
}
private Task<bool> WaitForCancellation(string marker, CancellationToken ct)
{
lock (_lock)
{
return _toolCancellations[marker].Task.WaitAsync(TestConstants.DefaultTimeout, ct);
}
}
private static IDictionary<string, JsonElement> CreateMarkerArgs(string marker) =>
new Dictionary<string, JsonElement>
{
["marker"] = JsonDocument.Parse($"\"{marker}\"").RootElement.Clone()
};
[Fact]
public async Task CancelTask_OnlyCancelsTargetTask_NotOtherTasks()
{
// Arrange
await using McpClient client = await CreateMcpClientForServer();
RegisterMarker("task1");
RegisterMarker("task2");
// Start two tasks
var result1 = await client.CallToolAsync(
new CallToolRequestParams
{
Name = "trackable-tool",
Arguments = CreateMarkerArgs("task1"),
Task = new McpTaskMetadata { TimeToLive = TimeSpan.FromMinutes(10) }
},
cancellationToken: TestContext.Current.CancellationToken);
var result2 = await client.CallToolAsync(
new CallToolRequestParams
{
Name = "trackable-tool",
Arguments = CreateMarkerArgs("task2"),
Task = new McpTaskMetadata { TimeToLive = TimeSpan.FromMinutes(10) }
},
cancellationToken: TestContext.Current.CancellationToken);
Assert.NotNull(result1.Task);
Assert.NotNull(result2.Task);
// Wait for both tools to start
await WaitForStart("task1", TestContext.Current.CancellationToken);
await WaitForStart("task2", TestContext.Current.CancellationToken);
// Act - Cancel only task1
await client.CancelTaskAsync(result1.Task.TaskId, cancellationToken: TestContext.Current.CancellationToken);
// Assert - task1 should be cancelled
var task1Cancelled = await WaitForCancellation("task1", TestContext.Current.CancellationToken);
Assert.True(task1Cancelled, "Task1 should have been cancelled");
// task2 should still be running (give it a moment to verify it wasn't cancelled)
var task2Status = await client.GetTaskAsync(result2.Task.TaskId, cancellationToken: TestContext.Current.CancellationToken);
Assert.Equal(McpTaskStatus.Working, task2Status.Status);
// Clean up - cancel task2
await client.CancelTaskAsync(result2.Task.TaskId, cancellationToken: TestContext.Current.CancellationToken);
}
[Fact]
public async Task MultipleTasks_WithDifferentTtls_CancelIndependently()
{
// Arrange
await using McpClient client = await CreateMcpClientForServer();
RegisterMarker("short-ttl");
RegisterMarker("long-ttl");
// Start task with short TTL. Use a TTL long enough that thread pool scheduling
// delays on loaded CI machines don't cause the CTS to fire before the tool
// lambda begins executing (CancelAfter starts counting at task creation, not
// when the tool's Task.Run is scheduled).
var shortTtlResult = await client.CallToolAsync(
new CallToolRequestParams
{
Name = "trackable-tool",
Arguments = CreateMarkerArgs("short-ttl"),
Task = new McpTaskMetadata { TimeToLive = TimeSpan.FromSeconds(5) }
},
cancellationToken: TestContext.Current.CancellationToken);
// Start task with long TTL
var longTtlResult = await client.CallToolAsync(
new CallToolRequestParams
{
Name = "trackable-tool",
Arguments = CreateMarkerArgs("long-ttl"),
Task = new McpTaskMetadata { TimeToLive = TimeSpan.FromMinutes(10) }
},
cancellationToken: TestContext.Current.CancellationToken);
Assert.NotNull(shortTtlResult.Task);
Assert.NotNull(longTtlResult.Task);
// Wait for both to start
await WaitForStart("short-ttl", TestContext.Current.CancellationToken);
await WaitForStart("long-ttl", TestContext.Current.CancellationToken);
// Assert - short TTL task should be cancelled automatically
var shortCancelled = await WaitForCancellation("short-ttl", TestContext.Current.CancellationToken);
Assert.True(shortCancelled, "Short TTL task should have been cancelled when TTL expired");
// Long TTL task should still be running
var longTtlStatus = await client.GetTaskAsync(longTtlResult.Task.TaskId, cancellationToken: TestContext.Current.CancellationToken);
Assert.Equal(McpTaskStatus.Working, longTtlStatus.Status);
// Clean up
await client.CancelTaskAsync(longTtlResult.Task.TaskId, cancellationToken: TestContext.Current.CancellationToken);
}
}
/// <summary>
/// Tests verifying that terminal task states (completed, failed, cancelled) cannot transition.
/// Per spec: "Tasks with a completed, failed, or cancelled status are in a terminal state
/// and MUST NOT transition to any other status"
/// </summary>
public class TerminalTaskStatusTransitionTests : ClientServerTestBase
{
public TerminalTaskStatusTransitionTests(ITestOutputHelper testOutputHelper)
: base(testOutputHelper)
{
}
protected override void ConfigureServices(ServiceCollection services, IMcpServerBuilder mcpServerBuilder)
{
var taskStore = new InMemoryMcpTaskStore();
services.AddSingleton<IMcpTaskStore>(taskStore);
services.Configure<McpServerOptions>(options =>
{
options.TaskStore = taskStore;
});
mcpServerBuilder.WithTools([
McpServerTool.Create(
async (CancellationToken ct) =>
{
await Task.Delay(10, ct);
return "quick result";
},
new McpServerToolCreateOptions
{
Name = "quick-tool",
Description = "A tool that completes quickly"
}),
McpServerTool.Create(
async (CancellationToken ct) =>
{
await Task.Delay(10, ct);
throw new InvalidOperationException("Intentional failure");
#pragma warning disable CS0162
return "never";
#pragma warning restore CS0162
},
new McpServerToolCreateOptions
{
Name = "failing-tool",
Description = "A tool that always fails"
})
]);
}
private static IDictionary<string, JsonElement> EmptyArguments() => new Dictionary<string, JsonElement>();
[Fact]
public async Task CompletedTask_CannotTransitionToOtherStatus()
{
// Arrange
await using McpClient client = await CreateMcpClientForServer();
var callResult = await client.CallToolAsync(
new CallToolRequestParams
{
Name = "quick-tool",
Arguments = EmptyArguments(),
Task = new McpTaskMetadata()
},
cancellationToken: TestContext.Current.CancellationToken);
Assert.NotNull(callResult.Task);
string taskId = callResult.Task.TaskId;
// Wait for completion
McpTask taskStatus;
do
{
await Task.Delay(50, TestContext.Current.CancellationToken);
taskStatus = await client.GetTaskAsync(taskId, cancellationToken: TestContext.Current.CancellationToken);
}
while (taskStatus.Status == McpTaskStatus.Working);
Assert.Equal(McpTaskStatus.Completed, taskStatus.Status);
// Act - Try to cancel a completed task (should be idempotent)
var cancelResult = await client.CancelTaskAsync(taskId, cancellationToken: TestContext.Current.CancellationToken);
// Assert - Status should still be completed (not cancelled)
Assert.Equal(McpTaskStatus.Completed, cancelResult.Status);
// Verify via get
var verifyStatus = await client.GetTaskAsync(taskId, cancellationToken: TestContext.Current.CancellationToken);
Assert.Equal(McpTaskStatus.Completed, verifyStatus.Status);
}
[Fact]
public async Task FailedTask_CannotTransitionToOtherStatus()
{
// Arrange
await using McpClient client = await CreateMcpClientForServer();
var callResult = await client.CallToolAsync(
new CallToolRequestParams
{
Name = "failing-tool",
Arguments = EmptyArguments(),
Task = new McpTaskMetadata()
},
cancellationToken: TestContext.Current.CancellationToken);
Assert.NotNull(callResult.Task);
string taskId = callResult.Task.TaskId;
// Wait for failure
McpTask taskStatus;
do
{
await Task.Delay(50, TestContext.Current.CancellationToken);
taskStatus = await client.GetTaskAsync(taskId, cancellationToken: TestContext.Current.CancellationToken);
}
while (taskStatus.Status == McpTaskStatus.Working);
Assert.Equal(McpTaskStatus.Failed, taskStatus.Status);
// Act - Try to cancel a failed task (should be idempotent)
var cancelResult = await client.CancelTaskAsync(taskId, cancellationToken: TestContext.Current.CancellationToken);
// Assert - Status should still be failed
Assert.Equal(McpTaskStatus.Failed, cancelResult.Status);
}
}