-
Notifications
You must be signed in to change notification settings - Fork 720
Expand file tree
/
Copy pathTaskCancellationIntegrationTests.cs
More file actions
372 lines (317 loc) · 12.9 KB
/
Copy pathTaskCancellationIntegrationTests.cs
File metadata and controls
372 lines (317 loc) · 12.9 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
using Microsoft.Extensions.DependencyInjection;
using ModelContextProtocol.Client;
using ModelContextProtocol.Protocol;
using ModelContextProtocol.Server;
using ModelContextProtocol.Tests.Utils;
using System.Runtime.InteropServices;
using System.Text.Json;
#pragma warning disable MCPEXP001
namespace ModelContextProtocol.Tests.Server;
/// <summary>
/// Integration tests for task cancellation behavior, including explicit cancellation
/// via tasks/cancel and TTL-based automatic cancellation.
/// </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)
{
#if !NET
Assert.SkipWhen(RuntimeInformation.IsOSPlatform(OSPlatform.Windows), "https://github.com/modelcontextprotocol/csharp-sdk/issues/587");
#endif
}
protected override void ConfigureServices(ServiceCollection services, IMcpServerBuilder mcpServerBuilder)
{
mcpServerBuilder.Services.Configure<McpServerOptions>(options =>
{
options.TaskStore = new InMemoryMcpTaskStore
{
DefaultPollIntervalMs = 50,
DefaultTimeToLive = TimeSpan.FromSeconds(5),
};
});
mcpServerBuilder.WithTools([McpServerTool.Create(
async (CancellationToken ct) =>
{
_toolStarted.TrySetResult(true);
try
{
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"
})]);
}
[Fact]
public async Task TaskTool_CancellationToken_FiresWhenExplicitlyCancelled()
{
await using var client = await CreateMcpClientForServer();
var ct = TestContext.Current.CancellationToken;
var augmented = await client.CallToolRawAsync(
new CallToolRequestParams { Name = "long-running-tool" }, ct);
Assert.True(augmented.IsTask);
var taskId = augmented.TaskCreated!.TaskId;
// Wait for the tool to start executing
await _toolStarted.Task.WaitAsync(TestConstants.DefaultTimeout, ct);
// Explicitly cancel the task
await client.CancelTaskAsync(taskId, ct);
// Wait for the cancellation to propagate to the tool
var cancelled = await _toolCancellationFired.Task.WaitAsync(TestConstants.DefaultTimeout, ct);
Assert.True(cancelled);
// Verify task status shows cancelled
var taskResult = await client.GetTaskAsync(taskId, ct);
Assert.IsType<CancelledTaskResult>(taskResult);
}
[Fact]
public async Task TaskTool_CancellationToken_GetTaskShowsWorkingBeforeCancel()
{
await using var client = await CreateMcpClientForServer();
var ct = TestContext.Current.CancellationToken;
var augmented = await client.CallToolRawAsync(
new CallToolRequestParams { Name = "long-running-tool" }, ct);
Assert.True(augmented.IsTask);
var taskId = augmented.TaskCreated!.TaskId;
// Wait for the tool to start
await _toolStarted.Task.WaitAsync(TestConstants.DefaultTimeout, ct);
// Check status while still running
var taskResult = await client.GetTaskAsync(taskId, ct);
Assert.IsType<WorkingTaskResult>(taskResult);
// Cleanup
await client.CancelTaskAsync(taskId, ct);
}
}
/// <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)
{
#if !NET
Assert.SkipWhen(RuntimeInformation.IsOSPlatform(OSPlatform.Windows), "https://github.com/modelcontextprotocol/csharp-sdk/issues/587");
#endif
}
protected override void ConfigureServices(ServiceCollection services, IMcpServerBuilder mcpServerBuilder)
{
mcpServerBuilder.Services.Configure<McpServerOptions>(options =>
{
options.TaskStore = new InMemoryMcpTaskStore
{
DefaultPollIntervalMs = 50,
};
});
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()
{
await using var client = await CreateMcpClientForServer();
var ct = TestContext.Current.CancellationToken;
RegisterMarker("task1");
RegisterMarker("task2");
// Start two tasks
var result1 = await client.CallToolRawAsync(
new CallToolRequestParams
{
Name = "trackable-tool",
Arguments = CreateMarkerArgs("task1"),
}, ct);
var result2 = await client.CallToolRawAsync(
new CallToolRequestParams
{
Name = "trackable-tool",
Arguments = CreateMarkerArgs("task2"),
}, ct);
Assert.True(result1.IsTask);
Assert.True(result2.IsTask);
// Wait for both tools to start
await WaitForStart("task1", ct);
await WaitForStart("task2", ct);
// Cancel only task1
await client.CancelTaskAsync(result1.TaskCreated!.TaskId, ct);
// task1 should be cancelled
var task1Cancelled = await WaitForCancellation("task1", ct);
Assert.True(task1Cancelled);
// task2 should still be working
var task2Status = await client.GetTaskAsync(result2.TaskCreated!.TaskId, ct);
Assert.IsType<WorkingTaskResult>(task2Status);
// Cleanup
await client.CancelTaskAsync(result2.TaskCreated!.TaskId, ct);
}
}
/// <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)
{
#if !NET
Assert.SkipWhen(RuntimeInformation.IsOSPlatform(OSPlatform.Windows), "https://github.com/modelcontextprotocol/csharp-sdk/issues/587");
#endif
}
protected override void ConfigureServices(ServiceCollection services, IMcpServerBuilder mcpServerBuilder)
{
mcpServerBuilder.Services.Configure<McpServerOptions>(options =>
{
options.TaskStore = new InMemoryMcpTaskStore
{
DefaultPollIntervalMs = 50,
};
});
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"
})
]);
}
[Fact]
public async Task CompletedTask_CancelIsAcknowledgedIdempotentlyAndStateUnchanged()
{
await using var client = await CreateMcpClientForServer();
var ct = TestContext.Current.CancellationToken;
var augmented = await client.CallToolRawAsync(
new CallToolRequestParams { Name = "quick-tool" }, ct);
Assert.True(augmented.IsTask);
var taskId = augmented.TaskCreated!.TaskId;
// Wait for completion
GetTaskResult? taskResult;
do
{
await Task.Delay(50, ct);
taskResult = await client.GetTaskAsync(taskId, ct);
}
while (taskResult is not CompletedTaskResult);
// SEP-2663: cancel on a terminal task must be acknowledged idempotently.
var cancelResult = await client.CancelTaskAsync(taskId, ct);
Assert.NotNull(cancelResult);
// Verify status is still completed (not flipped to cancelled).
var verifyResult = await client.GetTaskAsync(taskId, ct);
Assert.IsType<CompletedTaskResult>(verifyResult);
}
[Fact]
public async Task CompletedWithErrorTask_CancelIsAcknowledgedIdempotently()
{
await using var client = await CreateMcpClientForServer();
var ct = TestContext.Current.CancellationToken;
var augmented = await client.CallToolRawAsync(
new CallToolRequestParams { Name = "failing-tool" }, ct);
Assert.True(augmented.IsTask);
var taskId = augmented.TaskCreated!.TaskId;
// Wait for completion (tool errors are wrapped as completed with isError=true)
GetTaskResult? taskResult;
do
{
await Task.Delay(50, ct);
taskResult = await client.GetTaskAsync(taskId, ct);
}
while (taskResult is not CompletedTaskResult);
// SEP-2663: cancel on a terminal task must be acknowledged idempotently.
var cancelResult = await client.CancelTaskAsync(taskId, ct);
Assert.NotNull(cancelResult);
// Verify status is still completed (not flipped to cancelled).
var verifyResult = await client.GetTaskAsync(taskId, ct);
Assert.IsType<CompletedTaskResult>(verifyResult);
}
}