-
Notifications
You must be signed in to change notification settings - Fork 728
Expand file tree
/
Copy pathInMemoryMcpTaskStoreTests.cs
More file actions
1231 lines (1026 loc) · 53.3 KB
/
Copy pathInMemoryMcpTaskStoreTests.cs
File metadata and controls
1231 lines (1026 loc) · 53.3 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
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using Microsoft.Extensions.Time.Testing;
using ModelContextProtocol.Protocol;
using ModelContextProtocol.Server;
using ModelContextProtocol.Tests.Utils;
using System.Text.Json;
using TestInMemoryMcpTaskStore = ModelContextProtocol.Tests.Internal.InMemoryMcpTaskStore;
namespace ModelContextProtocol.Tests.Server;
public class InMemoryMcpTaskStoreTests : LoggedTest
{
public InMemoryMcpTaskStoreTests(ITestOutputHelper testOutputHelper)
: base(testOutputHelper)
{
}
[Fact]
public async Task CreateTaskAsync_CreatesTaskWithUniqueId()
{
// Arrange
using var store = new InMemoryMcpTaskStore();
var metadata = new McpTaskMetadata();
var requestId = new RequestId("req-1");
var request = new JsonRpcRequest { Method = "tools/call" };
// Act
var task = await store.CreateTaskAsync(metadata, requestId, request, "session-1", TestContext.Current.CancellationToken);
// Assert
Assert.NotNull(task);
Assert.NotEmpty(task.TaskId);
Assert.Equal(McpTaskStatus.Working, task.Status);
Assert.NotEqual(default, task.CreatedAt);
Assert.NotEqual(default, task.LastUpdatedAt);
}
[Fact]
public async Task CreateTaskAsync_GeneratesUniqueTaskIds()
{
// Arrange
using var store = new InMemoryMcpTaskStore();
var metadata = new McpTaskMetadata();
// Act
var task1 = await store.CreateTaskAsync(metadata, new RequestId("req-1"), new JsonRpcRequest { Method = "test" }, null, TestContext.Current.CancellationToken);
var task2 = await store.CreateTaskAsync(metadata, new RequestId("req-2"), new JsonRpcRequest { Method = "test" }, null, TestContext.Current.CancellationToken);
// Assert
Assert.NotEqual(task1.TaskId, task2.TaskId);
}
[Fact]
public async Task CreateTaskAsync_AppliesTtlFromMetadata()
{
// Arrange
using var store = new InMemoryMcpTaskStore();
var metadata = new McpTaskMetadata
{
TimeToLive = TimeSpan.FromSeconds(5)
};
// Act
var task = await store.CreateTaskAsync(metadata, new RequestId("req-1"), new JsonRpcRequest { Method = "test" }, null, TestContext.Current.CancellationToken);
// Assert
Assert.Equal(TimeSpan.FromSeconds(5), task.TimeToLive);
}
[Fact]
public async Task CreateTaskAsync_CapsMaxTtl()
{
// Arrange
var maxTtl = TimeSpan.FromMinutes(5);
using var store = new InMemoryMcpTaskStore(maxTtl: maxTtl);
var metadata = new McpTaskMetadata
{
TimeToLive = TimeSpan.FromHours(1) // Request 1 hour
};
// Act
var task = await store.CreateTaskAsync(metadata, new RequestId("req-1"), new JsonRpcRequest { Method = "test" }, null, TestContext.Current.CancellationToken);
// Assert
Assert.Equal(maxTtl, task.TimeToLive);
}
[Fact]
public async Task GetTaskAsync_ReturnsTaskById()
{
// Arrange
using var store = new InMemoryMcpTaskStore();
var metadata = new McpTaskMetadata();
var created = await store.CreateTaskAsync(metadata, new RequestId("req-1"), new JsonRpcRequest { Method = "test" }, null, TestContext.Current.CancellationToken);
// Act
var retrieved = await store.GetTaskAsync(created.TaskId, null, TestContext.Current.CancellationToken);
// Assert
Assert.NotNull(retrieved);
Assert.Equal(created.TaskId, retrieved.TaskId);
Assert.Equal(created.Status, retrieved.Status);
}
[Fact]
public async Task GetTaskAsync_ReturnsNullForNonexistentTask()
{
// Arrange
using var store = new InMemoryMcpTaskStore();
// Act
var task = await store.GetTaskAsync("nonexistent-id", null, TestContext.Current.CancellationToken);
// Assert
Assert.Null(task);
}
[Fact]
public async Task GetTaskAsync_EnforcesSessionIsolation()
{
// Arrange
using var store = new InMemoryMcpTaskStore();
var metadata = new McpTaskMetadata();
var task = await store.CreateTaskAsync(metadata, new RequestId("req-1"), new JsonRpcRequest { Method = "test" }, "session-1", TestContext.Current.CancellationToken);
// Act
var sameSession = await store.GetTaskAsync(task.TaskId, "session-1", TestContext.Current.CancellationToken);
var differentSession = await store.GetTaskAsync(task.TaskId, "session-2", TestContext.Current.CancellationToken);
// Assert
Assert.NotNull(sameSession);
Assert.Null(differentSession);
}
[Fact]
public async Task StoreTaskResultAsync_StoresResultForCompletedTask()
{
// Arrange
using var store = new InMemoryMcpTaskStore();
var metadata = new McpTaskMetadata();
var task = await store.CreateTaskAsync(metadata, new RequestId("req-1"), new JsonRpcRequest { Method = "test" }, null, TestContext.Current.CancellationToken);
var result = new CallToolResult { Content = [new TextContentBlock { Text = "Success" }] };
var resultElement = JsonSerializer.SerializeToElement(result, McpJsonUtilities.DefaultOptions);
// Act
await store.StoreTaskResultAsync(task.TaskId, McpTaskStatus.Completed, resultElement, null, TestContext.Current.CancellationToken);
// Assert
var retrieved = await store.GetTaskAsync(task.TaskId, null, TestContext.Current.CancellationToken);
Assert.Equal(McpTaskStatus.Completed, retrieved!.Status);
}
[Fact]
public async Task StoreTaskResultAsync_EnforcesSessionIsolation()
{
// Arrange
using var store = new InMemoryMcpTaskStore();
var metadata = new McpTaskMetadata();
var task = await store.CreateTaskAsync(metadata, new RequestId("req-1"), new JsonRpcRequest { Method = "test" }, "session-1", TestContext.Current.CancellationToken);
var result = new CallToolResult { Content = [new TextContentBlock { Text = "Success" }] };
var resultElement = JsonSerializer.SerializeToElement(result, McpJsonUtilities.DefaultOptions);
// Act & Assert
await Assert.ThrowsAsync<InvalidOperationException>(
() => store.StoreTaskResultAsync(task.TaskId, McpTaskStatus.Completed, resultElement, "session-2", TestContext.Current.CancellationToken));
}
[Fact]
public async Task StoreTaskResultAsync_ThrowsForNonTerminalStatus()
{
// Arrange
using var store = new InMemoryMcpTaskStore();
var metadata = new McpTaskMetadata();
var task = await store.CreateTaskAsync(metadata, new RequestId("req-1"), new JsonRpcRequest { Method = "test" }, null, TestContext.Current.CancellationToken);
var result = new CallToolResult { Content = [new TextContentBlock { Text = "Success" }] };
var resultElement = JsonSerializer.SerializeToElement(result, McpJsonUtilities.DefaultOptions);
// Act & Assert
await Assert.ThrowsAsync<ArgumentException>(
() => store.StoreTaskResultAsync(task.TaskId, McpTaskStatus.Working, resultElement, null, TestContext.Current.CancellationToken));
}
[Fact]
public async Task GetTaskResultAsync_ReturnsStoredResult()
{
// Arrange
using var store = new InMemoryMcpTaskStore();
var metadata = new McpTaskMetadata();
var task = await store.CreateTaskAsync(metadata, new RequestId("req-1"), new JsonRpcRequest { Method = "test" }, null, TestContext.Current.CancellationToken);
var result = new CallToolResult { Content = [new TextContentBlock { Text = "Success" }] };
var resultElement = JsonSerializer.SerializeToElement(result, McpJsonUtilities.DefaultOptions);
await store.StoreTaskResultAsync(task.TaskId, McpTaskStatus.Completed, resultElement, null, TestContext.Current.CancellationToken);
// Act
var retrieved = await store.GetTaskResultAsync(task.TaskId, null, TestContext.Current.CancellationToken);
// Assert
var callToolResult = retrieved.Deserialize<CallToolResult>(McpJsonUtilities.DefaultOptions)!;
Assert.Single(callToolResult.Content);
Assert.Equal("Success", ((TextContentBlock)callToolResult.Content[0]).Text);
}
[Fact]
public async Task GetTaskResultAsync_EnforcesSessionIsolation()
{
// Arrange
using var store = new InMemoryMcpTaskStore();
var metadata = new McpTaskMetadata();
var task = await store.CreateTaskAsync(metadata, new RequestId("req-1"), new JsonRpcRequest { Method = "test" }, "session-1", TestContext.Current.CancellationToken);
var result = new CallToolResult { Content = [new TextContentBlock { Text = "Success" }] };
var resultElement = JsonSerializer.SerializeToElement(result, McpJsonUtilities.DefaultOptions);
await store.StoreTaskResultAsync(task.TaskId, McpTaskStatus.Completed, resultElement, "session-1", TestContext.Current.CancellationToken);
// Act & Assert
await Assert.ThrowsAsync<InvalidOperationException>(
() => store.GetTaskResultAsync(task.TaskId, "session-2", TestContext.Current.CancellationToken));
}
[Fact]
public async Task UpdateTaskStatusAsync_UpdatesStatus()
{
// Arrange
using var store = new InMemoryMcpTaskStore();
var metadata = new McpTaskMetadata();
var task = await store.CreateTaskAsync(metadata, new RequestId("req-1"), new JsonRpcRequest { Method = "test" }, null, TestContext.Current.CancellationToken);
// Act
await store.UpdateTaskStatusAsync(task.TaskId, McpTaskStatus.Working, "Processing...", null, TestContext.Current.CancellationToken);
// Assert
var updated = await store.GetTaskAsync(task.TaskId, null, TestContext.Current.CancellationToken);
Assert.Equal(McpTaskStatus.Working, updated!.Status);
Assert.Equal("Processing...", updated.StatusMessage);
}
[Fact]
public async Task UpdateTaskStatusAsync_UpdatesLastUpdatedAt()
{
// Arrange - Use FakeTimeProvider for deterministic testing
var fakeTime = new FakeTimeProvider(DateTimeOffset.UtcNow);
using var store = new TestInMemoryMcpTaskStore(
defaultTtl: null,
maxTtl: null,
pollInterval: null,
cleanupInterval: Timeout.InfiniteTimeSpan,
pageSize: 100,
maxTasks: null,
maxTasksPerSession: null,
timeProvider: fakeTime);
var metadata = new McpTaskMetadata();
var task = await store.CreateTaskAsync(metadata, new RequestId("req-1"), new JsonRpcRequest { Method = "test" }, null, TestContext.Current.CancellationToken);
var originalTimestamp = task.LastUpdatedAt;
// Advance time to ensure timestamp changes
fakeTime.Advance(TimeSpan.FromMilliseconds(10));
// Act
await store.UpdateTaskStatusAsync(task.TaskId, McpTaskStatus.Working, null, null, TestContext.Current.CancellationToken);
// Assert
var updated = await store.GetTaskAsync(task.TaskId, null, TestContext.Current.CancellationToken);
Assert.True(updated!.LastUpdatedAt > originalTimestamp);
}
#region Input Required Status Tests
// NOTE: The InputRequired status is automatically set by the server when a tool executing
// as a task calls SampleAsync() or ElicitAsync(). The status is set back to Working when
// the request completes. See TaskExecutionContext for implementation details.
// The tests below verify the store correctly handles status transitions.
[Fact]
public async Task InputRequiredStatus_SerializesCorrectly()
{
// Verify the input_required status serializes as expected
var task = new McpTask
{
TaskId = "test-task",
Status = McpTaskStatus.InputRequired,
StatusMessage = "Waiting for user input",
CreatedAt = DateTimeOffset.UtcNow,
LastUpdatedAt = DateTimeOffset.UtcNow
};
string json = JsonSerializer.Serialize(task, McpJsonUtilities.DefaultOptions);
Assert.Contains("\"status\":\"input_required\"", json);
}
[Fact]
public async Task InputRequiredStatus_CanTransitionToWorking()
{
// Arrange - Spec: "From input_required: may move to working, completed, failed, or cancelled"
using var store = new InMemoryMcpTaskStore();
var metadata = new McpTaskMetadata();
var task = await store.CreateTaskAsync(metadata, new RequestId("req-1"), new JsonRpcRequest { Method = "test" }, null, TestContext.Current.CancellationToken);
// Transition to input_required (testing store's status transition capability)
var inputRequiredTask = await store.UpdateTaskStatusAsync(
task.TaskId,
McpTaskStatus.InputRequired,
"Waiting for user confirmation",
cancellationToken: TestContext.Current.CancellationToken);
Assert.Equal(McpTaskStatus.InputRequired, inputRequiredTask.Status);
// Act - Transition back to working
var workingTask = await store.UpdateTaskStatusAsync(
task.TaskId,
McpTaskStatus.Working,
"Processing resumed",
cancellationToken: TestContext.Current.CancellationToken);
// Assert
Assert.Equal(McpTaskStatus.Working, workingTask.Status);
}
[Fact]
public async Task InputRequiredStatus_CanTransitionToCancelled()
{
// Arrange - Spec: Task transitions show input_required can go to terminal states
using var store = new InMemoryMcpTaskStore();
var metadata = new McpTaskMetadata();
var task = await store.CreateTaskAsync(metadata, new RequestId("req-1"), new JsonRpcRequest { Method = "test" }, null, TestContext.Current.CancellationToken);
// Transition to input_required
await store.UpdateTaskStatusAsync(
task.TaskId,
McpTaskStatus.InputRequired,
"Need input",
cancellationToken: TestContext.Current.CancellationToken);
// Act - Transition to cancelled
var cancelledTask = await store.CancelTaskAsync(
task.TaskId,
cancellationToken: TestContext.Current.CancellationToken);
// Assert
Assert.Equal(McpTaskStatus.Cancelled, cancelledTask.Status);
}
#endregion
[Fact]
public async Task ListTasksAsync_ReturnsAllTasks()
{
// Arrange
using var store = new InMemoryMcpTaskStore();
var task1 = await store.CreateTaskAsync(new McpTaskMetadata(), new RequestId("req-1"), new JsonRpcRequest { Method = "test" }, null, TestContext.Current.CancellationToken);
var task2 = await store.CreateTaskAsync(new McpTaskMetadata(), new RequestId("req-2"), new JsonRpcRequest { Method = "test" }, null, TestContext.Current.CancellationToken);
// Act
var result = await store.ListTasksAsync(cancellationToken: TestContext.Current.CancellationToken);
// Assert
Assert.Equal(2, result.Tasks.Count);
Assert.Contains(result.Tasks, t => t.TaskId == task1.TaskId);
Assert.Contains(result.Tasks, t => t.TaskId == task2.TaskId);
Assert.Null(result.NextCursor);
}
[Fact]
public async Task ListTasksAsync_FiltersBySession()
{
// Arrange
using var store = new InMemoryMcpTaskStore();
var task1 = await store.CreateTaskAsync(new McpTaskMetadata(), new RequestId("req-1"), new JsonRpcRequest { Method = "test" }, "session-1", TestContext.Current.CancellationToken);
var task2 = await store.CreateTaskAsync(new McpTaskMetadata(), new RequestId("req-2"), new JsonRpcRequest { Method = "test" }, "session-2", TestContext.Current.CancellationToken);
// Act
var session1Result = await store.ListTasksAsync(sessionId: "session-1", cancellationToken: TestContext.Current.CancellationToken);
var session2Result = await store.ListTasksAsync(sessionId: "session-2", cancellationToken: TestContext.Current.CancellationToken);
// Assert
Assert.Single(session1Result.Tasks);
Assert.Equal(task1.TaskId, session1Result.Tasks[0].TaskId);
Assert.Single(session2Result.Tasks);
Assert.Equal(task2.TaskId, session2Result.Tasks[0].TaskId);
}
[Fact]
public async Task ListTasksAsync_SupportsPagination()
{
// Arrange
using var store = new InMemoryMcpTaskStore();
// Create 150 tasks (more than page size of 100)
for (int i = 0; i < 150; i++)
{
await store.CreateTaskAsync(new McpTaskMetadata(), new RequestId($"req-{i}"), new JsonRpcRequest { Method = "test" }, null, TestContext.Current.CancellationToken);
}
// Act - First page
var firstPageResult = await store.ListTasksAsync(cancellationToken: TestContext.Current.CancellationToken);
// Act - Second page
var secondPageResult = await store.ListTasksAsync(cursor: firstPageResult.NextCursor, cancellationToken: TestContext.Current.CancellationToken);
// Assert
Assert.Equal(100, firstPageResult.Tasks.Count);
Assert.NotNull(firstPageResult.NextCursor);
Assert.Equal(50, secondPageResult.Tasks.Count);
Assert.Null(secondPageResult.NextCursor);
}
[Fact]
public async Task CancelTaskAsync_CancelsTask()
{
// Arrange
using var store = new InMemoryMcpTaskStore();
var metadata = new McpTaskMetadata();
var task = await store.CreateTaskAsync(metadata, new RequestId("req-1"), new JsonRpcRequest { Method = "test" }, null, TestContext.Current.CancellationToken);
// Act
var cancelled = await store.CancelTaskAsync(task.TaskId, null, TestContext.Current.CancellationToken);
// Assert
Assert.Equal(McpTaskStatus.Cancelled, cancelled.Status);
}
[Fact]
public async Task CancelTaskAsync_IsIdempotent()
{
// Arrange
using var store = new InMemoryMcpTaskStore();
var metadata = new McpTaskMetadata();
var task = await store.CreateTaskAsync(metadata, new RequestId("req-1"), new JsonRpcRequest { Method = "test" }, null, TestContext.Current.CancellationToken);
// First cancellation
await store.CancelTaskAsync(task.TaskId, null, TestContext.Current.CancellationToken);
// Act - Second cancellation
var result = await store.CancelTaskAsync(task.TaskId, null, TestContext.Current.CancellationToken);
// Assert - Should return unchanged task, not throw
Assert.Equal(McpTaskStatus.Cancelled, result.Status);
}
[Fact]
public async Task CancelTaskAsync_DoesNotCancelCompletedTask()
{
// Arrange
using var store = new InMemoryMcpTaskStore();
var metadata = new McpTaskMetadata();
var task = await store.CreateTaskAsync(metadata, new RequestId("req-1"), new JsonRpcRequest { Method = "test" }, null, TestContext.Current.CancellationToken);
var result = new CallToolResult { Content = [new TextContentBlock { Text = "Success" }] };
var resultElement = JsonSerializer.SerializeToElement(result, McpJsonUtilities.DefaultOptions);
await store.StoreTaskResultAsync(task.TaskId, McpTaskStatus.Completed, resultElement, null, TestContext.Current.CancellationToken);
// Act
var cancelResult = await store.CancelTaskAsync(task.TaskId, null, TestContext.Current.CancellationToken);
// Assert - Task remains completed
Assert.Equal(McpTaskStatus.Completed, cancelResult.Status);
}
[Fact]
public async Task CancelTaskAsync_EnforcesSessionIsolation()
{
// Arrange
using var store = new InMemoryMcpTaskStore();
var metadata = new McpTaskMetadata();
var task = await store.CreateTaskAsync(metadata, new RequestId("req-1"), new JsonRpcRequest { Method = "test" }, "session-1", TestContext.Current.CancellationToken);
// Act & Assert
await Assert.ThrowsAsync<InvalidOperationException>(
() => store.CancelTaskAsync(task.TaskId, "session-2", TestContext.Current.CancellationToken));
}
[Fact]
public async Task Dispose_StopsCleanupTimer()
{
// Arrange - Use FakeTimeProvider for deterministic testing
var fakeTime = new FakeTimeProvider(DateTimeOffset.UtcNow);
var cleanupInterval = TimeSpan.FromMilliseconds(100);
var store = new TestInMemoryMcpTaskStore(
defaultTtl: null,
maxTtl: null,
pollInterval: null,
cleanupInterval: cleanupInterval,
pageSize: 100,
maxTasks: null,
maxTasksPerSession: null,
timeProvider: fakeTime);
var metadata = new McpTaskMetadata { TimeToLive = TimeSpan.FromMilliseconds(100) };
await store.CreateTaskAsync(metadata, new RequestId("req-1"), new JsonRpcRequest { Method = "test" }, null, TestContext.Current.CancellationToken);
// Act
store.Dispose();
// Advance time - timer should not fire after dispose
fakeTime.Advance(TimeSpan.FromTicks(cleanupInterval.Ticks * 3));
// Assert - Store should still be accessible after dispose (no exceptions)
// The cleanup timer should have stopped
Assert.True(true); // If we get here without exceptions, dispose worked
}
[Fact]
public async Task CleanupExpiredTasks_RemovesExpiredTasks()
{
// Arrange - Use FakeTimeProvider for deterministic testing
var fakeTime = new FakeTimeProvider(DateTimeOffset.UtcNow);
var cleanupInterval = TimeSpan.FromMilliseconds(50);
var ttl = TimeSpan.FromMilliseconds(100);
using var store = new TestInMemoryMcpTaskStore(
defaultTtl: null,
maxTtl: null,
pollInterval: null,
cleanupInterval: cleanupInterval,
pageSize: 100,
maxTasks: null,
maxTasksPerSession: null,
timeProvider: fakeTime);
var metadata = new McpTaskMetadata { TimeToLive = ttl };
var task = await store.CreateTaskAsync(metadata, new RequestId("req-1"), new JsonRpcRequest { Method = "test" }, null, TestContext.Current.CancellationToken);
// Verify task exists initially
var resultBefore = await store.ListTasksAsync(cancellationToken: TestContext.Current.CancellationToken);
Assert.Single(resultBefore.Tasks);
// Advance time past the TTL to make task expired
fakeTime.Advance(ttl + TimeSpan.FromMilliseconds(1));
// Trigger cleanup by advancing time past cleanup interval
fakeTime.Advance(cleanupInterval);
// Act - List tasks to verify cleanup happened
var resultAfter = await store.ListTasksAsync(cancellationToken: TestContext.Current.CancellationToken);
// Assert
Assert.Empty(resultAfter.Tasks); // Task should be cleaned up by the timer
}
[Fact]
public async Task DefaultTtl_AppliedWhenNoTtlSpecified()
{
// Arrange
var defaultTtl = TimeSpan.FromMinutes(10);
using var store = new InMemoryMcpTaskStore(defaultTtl: defaultTtl);
var metadata = new McpTaskMetadata(); // No TTL specified
// Act
var task = await store.CreateTaskAsync(metadata, new RequestId("req-1"), new JsonRpcRequest { Method = "test" }, null, TestContext.Current.CancellationToken);
// Assert
Assert.Equal(defaultTtl, task.TimeToLive);
}
[Fact]
public async Task MultipleOperations_ConcurrentAccess()
{
// Arrange
using var store = new InMemoryMcpTaskStore();
var tasks = new List<Task<McpTask>>();
// Act - Create multiple tasks concurrently
for (int i = 0; i < 10; i++)
{
int taskNum = i;
tasks.Add(Task.Run(async () =>
{
var metadata = new McpTaskMetadata();
return await store.CreateTaskAsync(metadata, new RequestId($"req-{taskNum}"), new JsonRpcRequest { Method = "test" }, null, TestContext.Current.CancellationToken);
}));
}
var createdTasks = await Task.WhenAll(tasks);
// Assert - All tasks should be created with unique IDs
Assert.Equal(10, createdTasks.Length);
Assert.Equal(10, createdTasks.Select(t => t.TaskId).Distinct().Count());
}
[Fact]
public void Constructor_ThrowsWhenDefaultTtlExceedsMaxTtl()
{
// Arrange & Act & Assert
var exception = Assert.Throws<ArgumentException>(() =>
new InMemoryMcpTaskStore(
defaultTtl: TimeSpan.FromHours(2),
maxTtl: TimeSpan.FromHours(1)));
Assert.Equal("defaultTtl", exception.ParamName);
Assert.Contains("Default TTL", exception.Message);
Assert.Contains("cannot exceed maximum TTL", exception.Message);
}
[Fact]
public async Task CreateTaskAsync_UsesConfiguredPollInterval()
{
// Arrange
using var store = new InMemoryMcpTaskStore(pollInterval: TimeSpan.FromMilliseconds(2500));
var metadata = new McpTaskMetadata();
// Act
var task = await store.CreateTaskAsync(metadata, new RequestId("req-1"), new JsonRpcRequest { Method = "test" }, null, TestContext.Current.CancellationToken);
// Assert
Assert.Equal(TimeSpan.FromMilliseconds(2500), task.PollInterval);
}
[Fact]
public void Constructor_ThrowsWhenPollIntervalIsZero()
{
// Arrange & Act & Assert
var exception = Assert.Throws<ArgumentOutOfRangeException>(() =>
new InMemoryMcpTaskStore(pollInterval: TimeSpan.Zero));
Assert.Equal("pollInterval", exception.ParamName);
Assert.Contains("Poll interval must be positive", exception.Message);
}
[Fact]
public void Constructor_ThrowsWhenPollIntervalIsNegative()
{
// Arrange & Act & Assert
var exception = Assert.Throws<ArgumentOutOfRangeException>(() =>
new InMemoryMcpTaskStore(pollInterval: TimeSpan.FromMilliseconds(-100)));
Assert.Equal("pollInterval", exception.ParamName);
Assert.Contains("Poll interval must be positive", exception.Message);
}
[Fact]
public async Task GetTaskAsync_ReturnsDefensiveCopy()
{
// Arrange
using var store = new InMemoryMcpTaskStore();
var metadata = new McpTaskMetadata();
var createdTask = await store.CreateTaskAsync(metadata, new RequestId("req-1"), new JsonRpcRequest { Method = "test" }, null, TestContext.Current.CancellationToken);
// Act - Get the task and modify the returned copy
var retrievedTask = await store.GetTaskAsync(createdTask.TaskId, null, TestContext.Current.CancellationToken);
var originalStatus = retrievedTask!.Status;
retrievedTask.Status = McpTaskStatus.Completed;
retrievedTask.StatusMessage = "Modified externally";
// Assert - Get the task again and verify the stored state wasn't affected
var taskAgain = await store.GetTaskAsync(createdTask.TaskId, null, TestContext.Current.CancellationToken);
Assert.Equal(originalStatus, taskAgain!.Status);
Assert.Null(taskAgain.StatusMessage);
}
[Fact]
public async Task ListTasksAsync_ReturnsDefensiveCopies()
{
// Arrange
using var store = new InMemoryMcpTaskStore();
var metadata = new McpTaskMetadata();
await store.CreateTaskAsync(metadata, new RequestId("req-1"), new JsonRpcRequest { Method = "test" }, null, TestContext.Current.CancellationToken);
// Act - List tasks and modify the returned copies
var result = await store.ListTasksAsync(cancellationToken: TestContext.Current.CancellationToken);
var firstTask = result.Tasks[0];
var originalTaskId = firstTask.TaskId;
firstTask.Status = McpTaskStatus.Failed;
firstTask.StatusMessage = "Modified in list";
// Assert - Get the task directly and verify the stored state wasn't affected
var directTask = await store.GetTaskAsync(originalTaskId, null, TestContext.Current.CancellationToken);
Assert.Equal(McpTaskStatus.Working, directTask!.Status);
Assert.Null(directTask.StatusMessage);
}
[Fact]
public async Task CancelTaskAsync_ReturnsDefensiveCopy()
{
// Arrange
using var store = new InMemoryMcpTaskStore();
var metadata = new McpTaskMetadata();
var createdTask = await store.CreateTaskAsync(metadata, new RequestId("req-1"), new JsonRpcRequest { Method = "test" }, null, TestContext.Current.CancellationToken);
// Act - Cancel the task and modify the returned copy
var cancelledTask = await store.CancelTaskAsync(createdTask.TaskId, null, TestContext.Current.CancellationToken);
cancelledTask.StatusMessage = "Modified after cancel";
cancelledTask.Status = McpTaskStatus.Completed;
// Assert - Get the task again and verify it's still cancelled with no message
var taskAgain = await store.GetTaskAsync(createdTask.TaskId, null, TestContext.Current.CancellationToken);
Assert.Equal(McpTaskStatus.Cancelled, taskAgain!.Status);
Assert.Null(taskAgain.StatusMessage);
}
[Fact]
public async Task ConcurrentUpdates_HandlesContentionCorrectly()
{
// Arrange
using var store = new InMemoryMcpTaskStore();
var task = await store.CreateTaskAsync(new McpTaskMetadata(), new RequestId("req-1"), new JsonRpcRequest { Method = "test" }, null, TestContext.Current.CancellationToken);
// Act - Launch 100 concurrent updates to the same task
var updateTasks = Enumerable.Range(0, 100).Select(i =>
Task.Run(async () =>
{
try
{
await store.UpdateTaskStatusAsync(task.TaskId, McpTaskStatus.Working, $"Update {i}", null, TestContext.Current.CancellationToken);
return true;
}
catch
{
return false;
}
}));
var results = await Task.WhenAll(updateTasks);
// Assert - All updates should succeed (retry loop handles contention)
Assert.All(results, success => Assert.True(success));
// Verify task is still in valid state (one of the updates won)
var finalTask = await store.GetTaskAsync(task.TaskId, null, TestContext.Current.CancellationToken);
Assert.NotNull(finalTask);
Assert.Equal(McpTaskStatus.Working, finalTask.Status);
Assert.Matches(@"Update \d+", finalTask.StatusMessage!);
}
[Fact]
public async Task ConcurrentStoreResult_OnlyFirstWins()
{
// Arrange
using var store = new InMemoryMcpTaskStore();
var task = await store.CreateTaskAsync(new McpTaskMetadata(), new RequestId("req-1"), new JsonRpcRequest { Method = "test" }, null, TestContext.Current.CancellationToken);
// Act - Try to store results concurrently (only first should succeed)
var storeTasks = Enumerable.Range(0, 10).Select(i =>
Task.Run(async () =>
{
try
{
var result = new CallToolResult { Content = [new TextContentBlock { Text = $"Result {i}" }] };
var resultElement = JsonSerializer.SerializeToElement(result, McpJsonUtilities.DefaultOptions);
await store.StoreTaskResultAsync(
task.TaskId,
McpTaskStatus.Completed,
resultElement,
null,
TestContext.Current.CancellationToken);
return i;
}
catch (InvalidOperationException)
{
// Expected: task already in terminal state
return -1;
}
}));
var results = await Task.WhenAll(storeTasks);
var successfulUpdates = results.Where(r => r >= 0).ToList();
// Assert - Exactly one update should succeed, others should fail
Assert.Single(successfulUpdates);
// Verify the winning result is stored
var finalTask = await store.GetTaskAsync(task.TaskId, null, TestContext.Current.CancellationToken);
Assert.Equal(McpTaskStatus.Completed, finalTask!.Status);
}
[Fact]
public async Task ListTasksAsync_PaginationWithCustomPageSize()
{
// Arrange - Use small page size for testing
using var store = new InMemoryMcpTaskStore(pageSize: 10);
// Create 25 tasks
for (int i = 0; i < 25; i++)
{
await store.CreateTaskAsync(new McpTaskMetadata(), new RequestId($"req-{i}"), new JsonRpcRequest { Method = "test" }, null, TestContext.Current.CancellationToken);
}
// Act - Paginate through all tasks
var result1 = await store.ListTasksAsync(cancellationToken: TestContext.Current.CancellationToken);
var result2 = await store.ListTasksAsync(cursor: result1.NextCursor, cancellationToken: TestContext.Current.CancellationToken);
var result3 = await store.ListTasksAsync(cursor: result2.NextCursor, cancellationToken: TestContext.Current.CancellationToken);
// Assert
Assert.Equal(10, result1.Tasks.Count);
Assert.NotNull(result1.NextCursor);
Assert.Equal(10, result2.Tasks.Count);
Assert.NotNull(result2.NextCursor);
Assert.Equal(5, result3.Tasks.Count);
Assert.Null(result3.NextCursor);
// Verify no duplicates across pages
var allTaskIds = result1.Tasks.Concat(result2.Tasks).Concat(result3.Tasks).Select(t => t.TaskId).ToList();
Assert.Equal(25, allTaskIds.Distinct().Count());
}
[Fact]
public async Task ListTasksAsync_NoDuplicatesWithIdenticalTimestamps()
{
// Arrange
using var store = new InMemoryMcpTaskStore(pageSize: 5);
// Create tasks with identical metadata to increase chance of timestamp collision
var createTasks = Enumerable.Range(0, 20).Select(i =>
store.CreateTaskAsync(new McpTaskMetadata(), new RequestId($"req-{i}"), new JsonRpcRequest { Method = "test" }, null, TestContext.Current.CancellationToken));
await Task.WhenAll(createTasks);
// Act - Collect all tasks through pagination
var allTasks = new List<McpTask>();
string? cursor = null;
do
{
var result = await store.ListTasksAsync(cursor: cursor, cancellationToken: TestContext.Current.CancellationToken);
allTasks.AddRange(result.Tasks);
cursor = result.NextCursor;
} while (cursor != null);
// Assert - No duplicates
var taskIds = allTasks.Select(t => t.TaskId).ToList();
Assert.Equal(20, taskIds.Count);
Assert.Equal(20, taskIds.Distinct().Count());
// Verify tasks are properly ordered
Assert.Equal(allTasks.OrderBy(t => t.CreatedAt).ThenBy(t => t.TaskId).Select(t => t.TaskId), taskIds);
}
[Fact]
public async Task ListTasksAsync_ConsistentWithExpiredTasksRemovedBetweenPages()
{
// Arrange - Use FakeTimeProvider for deterministic testing
var fakeTime = new FakeTimeProvider(DateTimeOffset.UtcNow);
var ttl = TimeSpan.FromSeconds(1);
using var store = new TestInMemoryMcpTaskStore(
defaultTtl: ttl,
maxTtl: null,
pollInterval: null,
cleanupInterval: Timeout.InfiniteTimeSpan,
pageSize: 5,
maxTasks: null,
maxTasksPerSession: null,
timeProvider: fakeTime);
// Create 15 tasks
for (int i = 0; i < 15; i++)
{
await store.CreateTaskAsync(new McpTaskMetadata(), new RequestId($"req-{i}"), new JsonRpcRequest { Method = "test" }, null, TestContext.Current.CancellationToken);
}
// Act - Get first page immediately
var result1 = await store.ListTasksAsync(cancellationToken: TestContext.Current.CancellationToken);
// Advance time past TTL to make tasks expire
fakeTime.Advance(ttl + TimeSpan.FromMilliseconds(500));
// Get second page after expiration
var result2 = await store.ListTasksAsync(cursor: result1.NextCursor, cancellationToken: TestContext.Current.CancellationToken);
// Assert - First page should have 5 tasks, second page should have 0 (all expired)
Assert.Equal(5, result1.Tasks.Count);
Assert.NotNull(result1.NextCursor);
Assert.Empty(result2.Tasks);
Assert.Null(result2.NextCursor);
}
[Fact]
public async Task ListTasksAsync_KeysetPaginationMaintainsConsistencyWithNewTasks()
{
// Arrange
using var store = new InMemoryMcpTaskStore(pageSize: 5);
// Create 10 initial tasks
for (int i = 0; i < 10; i++)
{
await store.CreateTaskAsync(new McpTaskMetadata(), new RequestId($"req-{i}"), new JsonRpcRequest { Method = "test" }, null, TestContext.Current.CancellationToken);
}
// Get first page
var result1 = await store.ListTasksAsync(cancellationToken: TestContext.Current.CancellationToken);
Assert.Equal(5, result1.Tasks.Count);
// Add more tasks between pages (these should appear in later queries, not retroactively in page 2)
for (int i = 10; i < 15; i++)
{
await store.CreateTaskAsync(new McpTaskMetadata(), new RequestId($"req-{i}"), new JsonRpcRequest { Method = "test" }, null, TestContext.Current.CancellationToken);
}
// Get second page using cursor from before new tasks were added
var result2 = await store.ListTasksAsync(cursor: result1.NextCursor, cancellationToken: TestContext.Current.CancellationToken);
// Assert - Second page should have 5 tasks from original set
Assert.Equal(5, result2.Tasks.Count);
Assert.NotNull(result2.NextCursor);
// Verify no overlap between pages
var page1Ids = result1.Tasks.Select(t => t.TaskId).ToHashSet();
var page2Ids = result2.Tasks.Select(t => t.TaskId).ToHashSet();
Assert.Empty(page1Ids.Intersect(page2Ids));
}
[Fact]
public async Task UpdateTaskStatusAsync_ConcurrentWithList_NoCorruption()
{
// Arrange
using var store = new InMemoryMcpTaskStore(pageSize: 10);
// Create 20 tasks
var tasks = new List<McpTask>();
for (int i = 0; i < 20; i++)
{
var task = await store.CreateTaskAsync(new McpTaskMetadata(), new RequestId($"req-{i}"), new JsonRpcRequest { Method = "test" }, null, TestContext.Current.CancellationToken);
tasks.Add(task);
}
// Act - Concurrently list and update tasks
var ct = TestContext.Current.CancellationToken;
var listTask = Task.Run(async () =>
{
var allTasks = new List<McpTask>();
string? cursor = null;
do
{
var result = await store.ListTasksAsync(cursor: cursor, cancellationToken: TestContext.Current.CancellationToken);
allTasks.AddRange(result.Tasks);
cursor = result.NextCursor;
await Task.Delay(10, ct); // Small delay to increase chance of interleaving
} while (cursor != null);
return allTasks;
}, ct);
var updateTask = Task.Run(async () =>
{
foreach (var task in tasks)
{
await store.UpdateTaskStatusAsync(task.TaskId, McpTaskStatus.Working, "Updated", null, TestContext.Current.CancellationToken);
await Task.Delay(5, ct); // Small delay
}
}, ct);
await Task.WhenAll(listTask, updateTask);
var listedTasks = await listTask;
// Assert - Should have listed all tasks without duplicates or corruption
Assert.Equal(20, listedTasks.Count);
Assert.Equal(20, listedTasks.Select(t => t.TaskId).Distinct().Count());
}
[Fact]
public void Constructor_ThrowsForInvalidMaxTasks()
{
// Assert
Assert.Throws<ArgumentOutOfRangeException>(() => new InMemoryMcpTaskStore(maxTasks: 0));
Assert.Throws<ArgumentOutOfRangeException>(() => new InMemoryMcpTaskStore(maxTasks: -1));
}
[Fact]
public void Constructor_ThrowsForInvalidMaxTasksPerSession()
{
// Assert
Assert.Throws<ArgumentOutOfRangeException>(() => new InMemoryMcpTaskStore(maxTasksPerSession: 0));
Assert.Throws<ArgumentOutOfRangeException>(() => new InMemoryMcpTaskStore(maxTasksPerSession: -1));
}
[Fact]
public async Task CreateTaskAsync_EnforcesMaxTasksLimit()
{
// Arrange
using var store = new InMemoryMcpTaskStore(maxTasks: 3);
var metadata = new McpTaskMetadata();
// Act - Create up to the limit
await store.CreateTaskAsync(metadata, new RequestId("req-1"), new JsonRpcRequest { Method = "test" }, null, TestContext.Current.CancellationToken);
await store.CreateTaskAsync(metadata, new RequestId("req-2"), new JsonRpcRequest { Method = "test" }, null, TestContext.Current.CancellationToken);
await store.CreateTaskAsync(metadata, new RequestId("req-3"), new JsonRpcRequest { Method = "test" }, null, TestContext.Current.CancellationToken);
// Assert - Fourth task should throw
var ex = await Assert.ThrowsAsync<InvalidOperationException>(() =>
store.CreateTaskAsync(metadata, new RequestId("req-4"), new JsonRpcRequest { Method = "test" }, null, TestContext.Current.CancellationToken));
Assert.Contains("Maximum number of tasks (3) has been reached", ex.Message);
}
[Fact]
public async Task CreateTaskAsync_EnforcesMaxTasksPerSessionLimit()
{
// Arrange
using var store = new InMemoryMcpTaskStore(maxTasksPerSession: 2);
var metadata = new McpTaskMetadata();
// Act - Create up to the limit for session-1
await store.CreateTaskAsync(metadata, new RequestId("req-1"), new JsonRpcRequest { Method = "test" }, "session-1", TestContext.Current.CancellationToken);
await store.CreateTaskAsync(metadata, new RequestId("req-2"), new JsonRpcRequest { Method = "test" }, "session-1", TestContext.Current.CancellationToken);
// Assert - Third task for session-1 should throw
var ex = await Assert.ThrowsAsync<InvalidOperationException>(() =>
store.CreateTaskAsync(metadata, new RequestId("req-3"), new JsonRpcRequest { Method = "test" }, "session-1", TestContext.Current.CancellationToken));
Assert.Contains("Maximum number of tasks per session (2) has been reached", ex.Message);
Assert.Contains("session-1", ex.Message);
}
[Fact]
public async Task CreateTaskAsync_MaxTasksPerSession_AllowsDifferentSessions()
{
// Arrange