-
Notifications
You must be signed in to change notification settings - Fork 720
Expand file tree
/
Copy pathInMemoryMcpTaskStoreTests.cs
More file actions
495 lines (397 loc) · 17.4 KB
/
Copy pathInMemoryMcpTaskStoreTests.cs
File metadata and controls
495 lines (397 loc) · 17.4 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
using ModelContextProtocol.Protocol;
using ModelContextProtocol.Server;
using System.Text.Json;
#pragma warning disable MCPEXP001
namespace ModelContextProtocol.Tests.Server;
/// <summary>
/// Unit tests for <see cref="InMemoryMcpTaskStore"/>.
/// </summary>
public class InMemoryMcpTaskStoreTests
{
private CancellationToken CT => TestContext.Current.CancellationToken;
private static InputRequest MakeRequest(string payload) =>
new() { Method = "test/method", Params = JsonSerializer.SerializeToElement(payload, McpJsonUtilities.DefaultOptions) };
private static InputResponse MakeResponse(string payload) =>
new() { RawValue = JsonSerializer.SerializeToElement(payload, McpJsonUtilities.DefaultOptions) };
[Fact]
public async Task CreateTaskAsync_ReturnsWorkingTaskWithUniqueId()
{
var store = new InMemoryMcpTaskStore();
var result = await store.CreateTaskAsync(CT);
Assert.NotNull(result);
Assert.NotEmpty(result.TaskId);
Assert.Equal(McpTaskStatus.Working, result.Status);
Assert.NotEqual(default, result.CreatedAt);
Assert.NotEqual(default, result.LastUpdatedAt);
}
[Fact]
public async Task CreateTaskAsync_GeneratesUniqueIds()
{
var store = new InMemoryMcpTaskStore();
var task1 = await store.CreateTaskAsync(CT);
var task2 = await store.CreateTaskAsync(CT);
Assert.NotEqual(task1.TaskId, task2.TaskId);
}
[Fact]
public async Task CreateTaskAsync_UsesDefaultPollInterval()
{
var store = new InMemoryMcpTaskStore { DefaultPollIntervalMs = 500 };
var result = await store.CreateTaskAsync(CT);
Assert.Equal(500, result.PollIntervalMs);
}
[Fact]
public async Task CreateTaskAsync_UsesDefaultTimeToLive()
{
var store = new InMemoryMcpTaskStore { DefaultTimeToLive = TimeSpan.FromSeconds(30) };
var result = await store.CreateTaskAsync(CT);
Assert.Equal(TimeSpan.FromSeconds(30), result.TimeToLive);
}
[Fact]
public async Task GetTaskAsync_ReturnsWorkingTask()
{
var store = new InMemoryMcpTaskStore();
var created = await store.CreateTaskAsync(CT);
var result = await store.GetTaskAsync(created.TaskId, CT);
Assert.NotNull(result);
Assert.Equal(McpTaskStatus.Working, result.Status);
Assert.Equal(created.TaskId, result.TaskId);
}
[Fact]
public async Task GetTaskAsync_ReturnsNullForUnknownId()
{
var store = new InMemoryMcpTaskStore();
var result = await store.GetTaskAsync("nonexistent", CT);
Assert.Null(result);
}
[Fact]
public async Task SetCompletedAsync_TransitionsToCompleted()
{
var store = new InMemoryMcpTaskStore();
var created = await store.CreateTaskAsync(CT);
var resultPayload = JsonDocument.Parse("""{"answer":42}""").RootElement.Clone();
await store.SetCompletedAsync(created.TaskId, resultPayload, CT);
var task = await store.GetTaskAsync(created.TaskId, CT);
Assert.NotNull(task);
Assert.Equal(McpTaskStatus.Completed, task.Status);
Assert.Equal(42, task.Result!.Value.GetProperty("answer").GetInt32());
}
[Fact]
public async Task SetFailedAsync_TransitionsToFailed()
{
var store = new InMemoryMcpTaskStore();
var created = await store.CreateTaskAsync(CT);
var errorPayload = JsonDocument.Parse("""{"message":"boom"}""").RootElement.Clone();
await store.SetFailedAsync(created.TaskId, errorPayload, CT);
var task = await store.GetTaskAsync(created.TaskId, CT);
Assert.NotNull(task);
Assert.Equal(McpTaskStatus.Failed, task.Status);
Assert.Equal("boom", task.Error!.Value.GetProperty("message").GetString());
}
[Fact]
public async Task SetCancelledAsync_TransitionsToCancelled()
{
var store = new InMemoryMcpTaskStore();
var created = await store.CreateTaskAsync(CT);
var cancelled = await store.SetCancelledAsync(created.TaskId, CT);
Assert.True(cancelled);
var task = await store.GetTaskAsync(created.TaskId, CT);
Assert.NotNull(task);
Assert.Equal(McpTaskStatus.Cancelled, task.Status);
}
[Fact]
public async Task SetCancelledAsync_ReturnsFalseForTerminalTask()
{
var store = new InMemoryMcpTaskStore();
var created = await store.CreateTaskAsync(CT);
await store.SetCompletedAsync(created.TaskId, JsonSerializer.SerializeToElement("done", McpJsonUtilities.DefaultOptions), CT);
var cancelled = await store.SetCancelledAsync(created.TaskId, CT);
Assert.False(cancelled);
var task = await store.GetTaskAsync(created.TaskId, CT);
Assert.NotNull(task);
Assert.Equal(McpTaskStatus.Completed, task.Status);
}
[Fact]
public async Task SetCancelledAsync_ReturnsFalseForUnknownId()
{
var store = new InMemoryMcpTaskStore();
var cancelled = await store.SetCancelledAsync("nonexistent", CT);
Assert.False(cancelled);
}
[Fact]
public async Task SetInputRequestsAsync_TransitionsToInputRequired()
{
var store = new InMemoryMcpTaskStore();
var created = await store.CreateTaskAsync(CT);
var requests = new Dictionary<string, InputRequest>
{
["req1"] = new InputRequest
{
Method = "elicitation/create",
Params = JsonElement.Parse("""{"message":"hello"}"""),
},
};
await store.SetInputRequestsAsync(created.TaskId, requests, CT);
var task = await store.GetTaskAsync(created.TaskId, CT);
Assert.NotNull(task);
Assert.Equal(McpTaskStatus.InputRequired, task.Status);
Assert.NotNull(task.InputRequests);
Assert.Single(task.InputRequests);
Assert.True(task.InputRequests.ContainsKey("req1"));
}
[Fact]
public async Task SetInputRequestsAsync_MergesMultipleRequests()
{
var store = new InMemoryMcpTaskStore();
var created = await store.CreateTaskAsync(CT);
await store.SetInputRequestsAsync(created.TaskId, new Dictionary<string, InputRequest>
{
["req1"] = MakeRequest("first")
}, CT);
await store.SetInputRequestsAsync(created.TaskId, new Dictionary<string, InputRequest>
{
["req2"] = MakeRequest("second")
}, CT);
var task = await store.GetTaskAsync(created.TaskId, CT);
Assert.NotNull(task);
Assert.Equal(McpTaskStatus.InputRequired, task.Status);
Assert.NotNull(task.InputRequests);
Assert.Equal(2, task.InputRequests.Count);
Assert.True(task.InputRequests.ContainsKey("req1"));
Assert.True(task.InputRequests.ContainsKey("req2"));
}
[Fact]
public async Task ResolveInputRequestsAsync_RemovesMatchedRequests()
{
var store = new InMemoryMcpTaskStore();
var created = await store.CreateTaskAsync(CT);
await store.SetInputRequestsAsync(created.TaskId, new Dictionary<string, InputRequest>
{
["req1"] = MakeRequest("request1"),
["req2"] = MakeRequest("request2"),
}, CT);
await store.ResolveInputRequestsAsync(created.TaskId, new Dictionary<string, InputResponse>
{
["req1"] = MakeResponse("response1"),
}, CT);
var task = await store.GetTaskAsync(created.TaskId, CT);
Assert.NotNull(task);
Assert.Equal(McpTaskStatus.InputRequired, task.Status);
Assert.NotNull(task.InputRequests);
Assert.Single(task.InputRequests);
Assert.True(task.InputRequests.ContainsKey("req2"));
}
[Fact]
public async Task ResolveInputRequestsAsync_TransitionsToWorkingWhenAllSatisfied()
{
var store = new InMemoryMcpTaskStore();
var created = await store.CreateTaskAsync(CT);
await store.SetInputRequestsAsync(created.TaskId, new Dictionary<string, InputRequest>
{
["req1"] = MakeRequest("request1"),
}, CT);
await store.ResolveInputRequestsAsync(created.TaskId, new Dictionary<string, InputResponse>
{
["req1"] = MakeResponse("response1"),
}, CT);
var task = await store.GetTaskAsync(created.TaskId, CT);
Assert.NotNull(task);
Assert.Equal(McpTaskStatus.Working, task.Status);
}
[Fact]
public async Task SetCompletedAsync_ThrowsForUnknownTask()
{
var store = new InMemoryMcpTaskStore();
await Assert.ThrowsAsync<InvalidOperationException>(
() => store.SetCompletedAsync("nonexistent", JsonSerializer.SerializeToElement("x", McpJsonUtilities.DefaultOptions), CT));
}
[Fact]
public async Task ConcurrentUpdates_DoNotLoseData()
{
var store = new InMemoryMcpTaskStore();
var created = await store.CreateTaskAsync(CT);
var tasks = Enumerable.Range(0, 50).Select(i =>
store.SetInputRequestsAsync(created.TaskId, new Dictionary<string, InputRequest>
{
[$"req{i}"] = MakeRequest($"value{i}")
}, CT));
await Task.WhenAll(tasks);
var task = await store.GetTaskAsync(created.TaskId, CT);
Assert.NotNull(task);
Assert.Equal(McpTaskStatus.InputRequired, task.Status);
Assert.NotNull(task.InputRequests);
Assert.Equal(50, task.InputRequests.Count);
}
[Fact]
public async Task ResolveInputRequestsAsync_ForExtraKeys_DoesNotThrow()
{
var store = new InMemoryMcpTaskStore();
var created = await store.CreateTaskAsync(CT);
await store.ResolveInputRequestsAsync(created.TaskId, new Dictionary<string, InputResponse>
{
["unknown-key"] = MakeResponse("response"),
}, CT);
var task = await store.GetTaskAsync(created.TaskId, CT);
Assert.NotNull(task);
Assert.Equal(McpTaskStatus.Working, task.Status);
}
[Fact]
public async Task ResolveInputRequestsAsync_AlreadyResolvedKey_IsNoOp()
{
// SEP-2663: "Each entry key SHOULD be unique across the lifetime of a given task" and
// servers should tolerate clients re-sending an inputResponse for an already-resolved key.
var store = new InMemoryMcpTaskStore();
var created = await store.CreateTaskAsync(CT);
await store.SetInputRequestsAsync(created.TaskId, new Dictionary<string, InputRequest>
{
["a"] = MakeRequest("ask-a"),
["b"] = MakeRequest("ask-b"),
}, CT);
// First resolve "a" — task should still be InputRequired because "b" remains.
await store.ResolveInputRequestsAsync(created.TaskId, new Dictionary<string, InputResponse>
{
["a"] = MakeResponse("answer-a"),
}, CT);
var afterFirst = await store.GetTaskAsync(created.TaskId, CT);
Assert.NotNull(afterFirst);
Assert.Equal(McpTaskStatus.InputRequired, afterFirst.Status);
Assert.NotNull(afterFirst.InputRequests);
Assert.Single(afterFirst.InputRequests);
Assert.Contains("b", afterFirst.InputRequests.Keys);
// Re-send "a" — should be a no-op (no exception, no state change).
await store.ResolveInputRequestsAsync(created.TaskId, new Dictionary<string, InputResponse>
{
["a"] = MakeResponse("answer-a-again"),
}, CT);
var afterDup = await store.GetTaskAsync(created.TaskId, CT);
Assert.NotNull(afterDup);
Assert.Equal(McpTaskStatus.InputRequired, afterDup.Status);
Assert.NotNull(afterDup.InputRequests);
Assert.Single(afterDup.InputRequests);
Assert.Contains("b", afterDup.InputRequests.Keys);
// Resolve the remaining "b" — task should transition back to Working with an empty inputRequests.
await store.ResolveInputRequestsAsync(created.TaskId, new Dictionary<string, InputResponse>
{
["b"] = MakeResponse("answer-b"),
}, CT);
var final = await store.GetTaskAsync(created.TaskId, CT);
Assert.NotNull(final);
Assert.Equal(McpTaskStatus.Working, final.Status);
Assert.True(final.InputRequests is null || final.InputRequests.Count == 0);
}
[Fact]
public async Task ConcurrentResolveInputRequests_OnDisjointKeys_AllResolveCorrectly()
{
// Verifies the optimistic-concurrency loop in InMemoryMcpTaskStore handles parallel
// tasks/update calls that each resolve a distinct subset of pending input requests.
var store = new InMemoryMcpTaskStore();
var created = await store.CreateTaskAsync(CT);
var seed = Enumerable.Range(0, 20).ToDictionary(
i => $"req{i}",
i => MakeRequest($"ask{i}"));
await store.SetInputRequestsAsync(created.TaskId, seed, CT);
var resolveTasks = Enumerable.Range(0, 20).Select(i =>
store.ResolveInputRequestsAsync(created.TaskId, new Dictionary<string, InputResponse>
{
[$"req{i}"] = MakeResponse($"answer{i}"),
}, CT));
await Task.WhenAll(resolveTasks);
var task = await store.GetTaskAsync(created.TaskId, CT);
Assert.NotNull(task);
Assert.Equal(McpTaskStatus.Working, task.Status);
Assert.True(task.InputRequests is null || task.InputRequests.Count == 0);
}
[Fact]
public async Task SetCompletedAsync_DoesNotOverwriteCancelledTask()
{
var store = new InMemoryMcpTaskStore();
var created = await store.CreateTaskAsync(CT);
var cancelled = await store.SetCancelledAsync(created.TaskId, CT);
Assert.True(cancelled);
// Background worker finishing after cancellation must not flip the task back to Completed.
await store.SetCompletedAsync(
created.TaskId,
JsonSerializer.SerializeToElement("late-result", McpJsonUtilities.DefaultOptions),
CT);
var task = await store.GetTaskAsync(created.TaskId, CT);
Assert.NotNull(task);
Assert.Equal(McpTaskStatus.Cancelled, task.Status);
Assert.Null(task.Result);
}
[Fact]
public async Task SetFailedAsync_DoesNotOverwriteCancelledTask()
{
var store = new InMemoryMcpTaskStore();
var created = await store.CreateTaskAsync(CT);
await store.SetCancelledAsync(created.TaskId, CT);
await store.SetFailedAsync(
created.TaskId,
JsonElement.Parse("""{"message":"boom"}"""),
CT);
var task = await store.GetTaskAsync(created.TaskId, CT);
Assert.NotNull(task);
Assert.Equal(McpTaskStatus.Cancelled, task.Status);
Assert.Null(task.Error);
}
[Fact]
public async Task SetCompletedAsync_DoesNotOverwriteCompletedTask()
{
var store = new InMemoryMcpTaskStore();
var created = await store.CreateTaskAsync(CT);
var first = JsonSerializer.SerializeToElement("first", McpJsonUtilities.DefaultOptions);
await store.SetCompletedAsync(created.TaskId, first, CT);
// A second completion attempt must not replace the original result.
var second = JsonSerializer.SerializeToElement("second", McpJsonUtilities.DefaultOptions);
await store.SetCompletedAsync(created.TaskId, second, CT);
var task = await store.GetTaskAsync(created.TaskId, CT);
Assert.NotNull(task);
Assert.Equal(McpTaskStatus.Completed, task.Status);
Assert.Equal("first", task.Result!.Value.GetString());
}
[Fact]
public async Task ResolveInputRequestsAsync_OnTerminalTask_DoesNotResurrect()
{
var store = new InMemoryMcpTaskStore();
var created = await store.CreateTaskAsync(CT);
await store.SetCompletedAsync(
created.TaskId,
JsonSerializer.SerializeToElement("done", McpJsonUtilities.DefaultOptions),
CT);
// A client tasks/update against a Completed task must not flip it back to Working.
await store.ResolveInputRequestsAsync(created.TaskId, new Dictionary<string, InputResponse>
{
["req1"] = MakeResponse("response"),
}, CT);
var task = await store.GetTaskAsync(created.TaskId, CT);
Assert.NotNull(task);
Assert.Equal(McpTaskStatus.Completed, task.Status);
}
[Fact]
public async Task ResolveInputRequestsAsync_OnTerminalTask_DoesNotFireEvent()
{
var store = new InMemoryMcpTaskStore();
var created = await store.CreateTaskAsync(CT);
await store.SetCancelledAsync(created.TaskId, CT);
int eventCount = 0;
store.InputResponseReceived += _ => Interlocked.Increment(ref eventCount);
await store.ResolveInputRequestsAsync(created.TaskId, new Dictionary<string, InputResponse>
{
["req1"] = MakeResponse("response"),
}, CT);
Assert.Equal(0, eventCount);
}
[Fact]
public async Task SetInputRequestsAsync_OnTerminalTask_NoOps()
{
var store = new InMemoryMcpTaskStore();
var created = await store.CreateTaskAsync(CT);
await store.SetCancelledAsync(created.TaskId, CT);
await store.SetInputRequestsAsync(created.TaskId, new Dictionary<string, InputRequest>
{
["req1"] = MakeRequest("payload"),
}, CT);
var task = await store.GetTaskAsync(created.TaskId, CT);
Assert.NotNull(task);
Assert.Equal(McpTaskStatus.Cancelled, task.Status);
Assert.True(task.InputRequests is null || task.InputRequests.Count == 0);
}
}