-
Notifications
You must be signed in to change notification settings - Fork 680
Expand file tree
/
Copy pathMcpServerTaskAugmentedValidationTests.cs
More file actions
936 lines (788 loc) · 37.1 KB
/
McpServerTaskAugmentedValidationTests.cs
File metadata and controls
936 lines (788 loc) · 37.1 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
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using ModelContextProtocol.Client;
using ModelContextProtocol.Protocol;
using ModelContextProtocol.Server;
using ModelContextProtocol.Tests.Utils;
using System.Text.Json;
namespace ModelContextProtocol.Tests.Server;
/// <summary>
/// Tests for validation of task-augmented tool call requests.
/// </summary>
public class McpServerTaskAugmentedValidationTests : LoggedTest
{
public McpServerTaskAugmentedValidationTests(ITestOutputHelper outputHelper)
: base(outputHelper)
{
}
private static IDictionary<string, JsonElement> CreateArguments(string key, object? value)
{
return new Dictionary<string, JsonElement>
{
[key] = JsonDocument.Parse($"\"{value}\"").RootElement.Clone()
};
}
[Fact]
public async Task CallToolAsTask_ThrowsError_WhenNoTaskStoreConfigured()
{
// Arrange - Server WITHOUT task store, but with an async tool (auto-marked as taskSupport: optional)
await using var fixture = new ServerClientFixture(LoggerFactory, configureServer: (services, builder) =>
{
// Note: NOT configuring a task store
builder.WithTools([McpServerTool.Create(
async (string input, CancellationToken ct) =>
{
await Task.Delay(10, ct);
return $"Result: {input}";
},
new McpServerToolCreateOptions
{
Name = "async-tool",
Description = "An async tool"
})]);
});
await using var client = await fixture.CreateClientAsync(TestContext.Current.CancellationToken);
// Act & Assert - Calling with task metadata should fail
var exception = await Assert.ThrowsAsync<McpProtocolException>(async () =>
await client.CallToolAsync(
new CallToolRequestParams
{
Name = "async-tool",
Arguments = CreateArguments("input", "test"),
Task = new McpTaskMetadata()
},
TestContext.Current.CancellationToken));
Assert.Contains("not supported", exception.Message, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public async Task CallToolAsTask_ThrowsError_WhenToolHasForbiddenTaskSupport()
{
// Arrange - Server with task store, but tool has taskSupport: forbidden (sync tool)
var taskStore = new InMemoryMcpTaskStore();
await using var fixture = new ServerClientFixture(LoggerFactory, configureServer: (services, builder) =>
{
services.AddSingleton<IMcpTaskStore>(taskStore);
services.Configure<McpServerOptions>(options =>
{
options.TaskStore = taskStore;
});
// Create a synchronous tool - which will have taskSupport: forbidden (default)
builder.WithTools([McpServerTool.Create(
(string input) => $"Result: {input}",
new McpServerToolCreateOptions
{
Name = "sync-tool",
Description = "A synchronous tool that does not support tasks"
})]);
});
await using var client = await fixture.CreateClientAsync(TestContext.Current.CancellationToken);
// Act & Assert - Calling with task metadata should fail because tool doesn't support it
var exception = await Assert.ThrowsAsync<McpProtocolException>(async () =>
await client.CallToolAsync(
new CallToolRequestParams
{
Name = "sync-tool",
Arguments = CreateArguments("input", "test"),
Task = new McpTaskMetadata()
},
TestContext.Current.CancellationToken));
Assert.Contains("does not support task-augmented execution", exception.Message, StringComparison.OrdinalIgnoreCase);
Assert.Equal(McpErrorCode.InvalidParams, exception.ErrorCode);
}
[Fact]
public async Task CallToolAsTask_Succeeds_WhenToolHasOptionalTaskSupport()
{
// Arrange - Server with task store and async tool (auto-marked as taskSupport: optional)
var taskStore = new InMemoryMcpTaskStore();
await using var fixture = new ServerClientFixture(LoggerFactory, configureServer: (services, builder) =>
{
services.AddSingleton<IMcpTaskStore>(taskStore);
services.Configure<McpServerOptions>(options =>
{
options.TaskStore = taskStore;
});
builder.WithTools([McpServerTool.Create(
async (string input, CancellationToken ct) =>
{
await Task.Delay(10, ct);
return $"Result: {input}";
},
new McpServerToolCreateOptions
{
Name = "async-tool",
Description = "An async tool with optional task support"
})]);
});
await using var client = await fixture.CreateClientAsync(TestContext.Current.CancellationToken);
// Act - Calling with task metadata should succeed
var result = await client.CallToolAsync(
new CallToolRequestParams
{
Name = "async-tool",
Arguments = CreateArguments("input", "test"),
Task = new McpTaskMetadata()
},
TestContext.Current.CancellationToken);
// Assert - Should return a task
Assert.NotNull(result.Task);
Assert.NotNull(result.Task.TaskId);
}
[Fact]
public async Task CallToolNormally_Succeeds_WhenToolHasForbiddenTaskSupport()
{
// Arrange - Server with task store, but calling without task metadata
var taskStore = new InMemoryMcpTaskStore();
await using var fixture = new ServerClientFixture(LoggerFactory, configureServer: (services, builder) =>
{
services.AddSingleton<IMcpTaskStore>(taskStore);
services.Configure<McpServerOptions>(options =>
{
options.TaskStore = taskStore;
});
builder.WithTools([McpServerTool.Create(
(string input) => $"Result: {input}",
new McpServerToolCreateOptions
{
Name = "sync-tool",
Description = "A synchronous tool"
})]);
});
await using var client = await fixture.CreateClientAsync(TestContext.Current.CancellationToken);
// Act - Calling WITHOUT task metadata should succeed
var result = await client.CallToolAsync(
new CallToolRequestParams
{
Name = "sync-tool",
Arguments = CreateArguments("input", "test"),
},
TestContext.Current.CancellationToken);
// Assert - Should return normal result
Assert.NotNull(result.Content);
Assert.Null(result.Task);
}
[Fact]
public async Task CallToolNormally_ThrowsError_WhenToolHasRequiredTaskSupport()
{
// Arrange - Server with task store and tool with taskSupport: required
var taskStore = new InMemoryMcpTaskStore();
await using var fixture = new ServerClientFixture(LoggerFactory, configureServer: (services, builder) =>
{
services.AddSingleton<IMcpTaskStore>(taskStore);
services.Configure<McpServerOptions>(options =>
{
options.TaskStore = taskStore;
});
builder.WithTools([McpServerTool.Create(
async (string input, CancellationToken ct) =>
{
await Task.Delay(100, ct);
return $"Result: {input}";
},
new McpServerToolCreateOptions
{
Name = "required-task-tool",
Description = "A tool that requires task-augmented execution",
Execution = new ToolExecution { TaskSupport = ToolTaskSupport.Required }
})]);
});
await using var client = await fixture.CreateClientAsync(TestContext.Current.CancellationToken);
// Act & Assert - Calling WITHOUT task metadata should fail
var exception = await Assert.ThrowsAsync<McpProtocolException>(async () =>
await client.CallToolAsync(
new CallToolRequestParams
{
Name = "required-task-tool",
Arguments = CreateArguments("input", "test"),
},
TestContext.Current.CancellationToken));
Assert.Contains("requires task-augmented execution", exception.Message, StringComparison.OrdinalIgnoreCase);
Assert.Equal(McpErrorCode.InvalidParams, exception.ErrorCode);
}
[Fact]
public async Task CallToolAsTask_Succeeds_WhenToolHasRequiredTaskSupport()
{
// Arrange - Server with task store and tool with taskSupport: required
var taskStore = new InMemoryMcpTaskStore();
await using var fixture = new ServerClientFixture(LoggerFactory, configureServer: (services, builder) =>
{
services.AddSingleton<IMcpTaskStore>(taskStore);
services.Configure<McpServerOptions>(options =>
{
options.TaskStore = taskStore;
});
builder.WithTools([McpServerTool.Create(
async (string input, CancellationToken ct) =>
{
await Task.Delay(10, ct);
return $"Result: {input}";
},
new McpServerToolCreateOptions
{
Name = "required-task-tool",
Description = "A tool that requires task-augmented execution",
Execution = new ToolExecution { TaskSupport = ToolTaskSupport.Required }
})]);
});
await using var client = await fixture.CreateClientAsync(TestContext.Current.CancellationToken);
// Act - Calling WITH task metadata should succeed
var result = await client.CallToolAsync(
new CallToolRequestParams
{
Name = "required-task-tool",
Arguments = CreateArguments("input", "test"),
Task = new McpTaskMetadata()
},
TestContext.Current.CancellationToken);
// Assert - Should return a task
Assert.NotNull(result.Task);
Assert.NotNull(result.Task.TaskId);
}
[Fact]
public async Task CallToolAsTaskAsync_WithProgress_CreatesTaskSuccessfully()
{
// Arrange - Server with task store and a tool that reports progress
var taskStore = new InMemoryMcpTaskStore();
await using var fixture = new ServerClientFixture(LoggerFactory, configureServer: (services, builder) =>
{
services.AddSingleton<IMcpTaskStore>(taskStore);
services.Configure<McpServerOptions>(options =>
{
options.TaskStore = taskStore;
});
builder.WithTools([McpServerTool.Create(
async (IProgress<ProgressNotificationValue> progress, CancellationToken ct) =>
{
// Report progress
progress.Report(new ProgressNotificationValue
{
Progress = 50,
Total = 100,
Message = "Halfway done"
});
await Task.Delay(10, ct);
return "Completed with progress";
},
new McpServerToolCreateOptions
{
Name = "progress-task-tool",
Description = "A tool that reports progress during task execution"
})]);
});
await using var client = await fixture.CreateClientAsync(TestContext.Current.CancellationToken);
// Track progress notifications received by client
var receivedProgressValues = new List<ProgressNotificationValue>();
IProgress<ProgressNotificationValue> progress = new SynchronousProgress(value =>
{
lock (receivedProgressValues)
{
receivedProgressValues.Add(value);
}
});
// Act - Call tool as task with progress tracking
var mcpTask = await client.CallToolAsTaskAsync(
"progress-task-tool",
arguments: null,
taskMetadata: new McpTaskMetadata(),
progress: progress,
cancellationToken: TestContext.Current.CancellationToken);
// Assert - Task was created successfully
Assert.NotNull(mcpTask);
Assert.NotEmpty(mcpTask.TaskId);
// Note: Progress notifications may not be received for task-augmented calls
// because the notification handler is disposed when the task creation response returns.
// This test verifies the code path executes without errors.
}
[Fact]
public async Task CallToolAsTaskAsync_WithoutProgress_DoesNotRequireProgressHandler()
{
// Arrange - Server with task store and a tool that reports progress
var taskStore = new InMemoryMcpTaskStore();
await using var fixture = new ServerClientFixture(LoggerFactory, configureServer: (services, builder) =>
{
services.AddSingleton<IMcpTaskStore>(taskStore);
services.Configure<McpServerOptions>(options =>
{
options.TaskStore = taskStore;
});
builder.WithTools([McpServerTool.Create(
async (IProgress<ProgressNotificationValue> progress, CancellationToken ct) =>
{
// Tool reports progress but client doesn't listen
progress.Report(new ProgressNotificationValue { Progress = 50, Message = "Halfway" });
await Task.Delay(10, ct);
return "Done";
},
new McpServerToolCreateOptions
{
Name = "progress-tool",
Description = "A tool that reports progress"
})]);
});
await using var client = await fixture.CreateClientAsync(TestContext.Current.CancellationToken);
// Act - Call tool as task WITHOUT progress tracking (progress: null)
var mcpTask = await client.CallToolAsTaskAsync(
"progress-tool",
arguments: null,
taskMetadata: new McpTaskMetadata(),
progress: null, // No progress handler
cancellationToken: TestContext.Current.CancellationToken);
// Assert - Task was still created successfully
Assert.NotNull(mcpTask);
Assert.NotEmpty(mcpTask.TaskId);
}
private sealed class SynchronousProgress(Action<ProgressNotificationValue> callback) : IProgress<ProgressNotificationValue>
{
public void Report(ProgressNotificationValue value) => callback(value);
}
#region Error Code Tests for Invalid/Nonexistent TaskId
[Fact]
public async Task GetTaskAsync_WithNonexistentTaskId_ReturnsInvalidParamsError()
{
// Arrange - Spec: "Invalid or nonexistent taskId in tasks/get: -32602 (Invalid params)"
var taskStore = new InMemoryMcpTaskStore();
await using var fixture = new ServerClientFixture(LoggerFactory, configureServer: (services, builder) =>
{
services.AddSingleton<IMcpTaskStore>(taskStore);
services.Configure<McpServerOptions>(options => options.TaskStore = taskStore);
builder.WithTools([McpServerTool.Create(
async (CancellationToken ct) => { await Task.Delay(10, ct); return "ok"; },
new McpServerToolCreateOptions { Name = "test-tool" })]);
});
await using var client = await fixture.CreateClientAsync(TestContext.Current.CancellationToken);
// Act & Assert
var exception = await Assert.ThrowsAsync<McpProtocolException>(async () =>
await client.GetTaskAsync("nonexistent-task-id-12345", cancellationToken: TestContext.Current.CancellationToken));
Assert.Equal(McpErrorCode.InvalidParams, exception.ErrorCode);
Assert.Contains("not found", exception.Message, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public async Task GetTaskResultAsync_WithNonexistentTaskId_ReturnsInvalidParamsError()
{
// Arrange - Spec: "Invalid or nonexistent taskId in tasks/result: -32602 (Invalid params)"
var taskStore = new InMemoryMcpTaskStore();
await using var fixture = new ServerClientFixture(LoggerFactory, configureServer: (services, builder) =>
{
services.AddSingleton<IMcpTaskStore>(taskStore);
services.Configure<McpServerOptions>(options => options.TaskStore = taskStore);
builder.WithTools([McpServerTool.Create(
async (CancellationToken ct) => { await Task.Delay(10, ct); return "ok"; },
new McpServerToolCreateOptions { Name = "test-tool" })]);
});
await using var client = await fixture.CreateClientAsync(TestContext.Current.CancellationToken);
// Act & Assert
var exception = await Assert.ThrowsAsync<McpProtocolException>(async () =>
await client.GetTaskResultAsync("nonexistent-task-id-12345", cancellationToken: TestContext.Current.CancellationToken));
Assert.Equal(McpErrorCode.InvalidParams, exception.ErrorCode);
Assert.Contains("not found", exception.Message, StringComparison.OrdinalIgnoreCase);
}
[Fact]
public async Task CancelTaskAsync_WithNonexistentTaskId_ReturnsError()
{
// Arrange - Spec: "Invalid or nonexistent taskId in tasks/cancel: -32602 (Invalid params)"
// NOTE: Current implementation throws InternalError; this documents actual behavior
var taskStore = new InMemoryMcpTaskStore();
await using var fixture = new ServerClientFixture(LoggerFactory, configureServer: (services, builder) =>
{
services.AddSingleton<IMcpTaskStore>(taskStore);
services.Configure<McpServerOptions>(options => options.TaskStore = taskStore);
builder.WithTools([McpServerTool.Create(
async (CancellationToken ct) => { await Task.Delay(10, ct); return "ok"; },
new McpServerToolCreateOptions { Name = "test-tool" })]);
});
await using var client = await fixture.CreateClientAsync(TestContext.Current.CancellationToken);
// Act & Assert
var exception = await Assert.ThrowsAsync<McpProtocolException>(async () =>
await client.CancelTaskAsync("nonexistent-task-id-12345", cancellationToken: TestContext.Current.CancellationToken));
Assert.NotNull(exception);
}
[Fact]
public async Task ListTasksAsync_WithInvalidCursor_HandlesGracefully()
{
// Arrange - Spec says: "Invalid or nonexistent cursor in tasks/list: -32602 (Invalid params)"
// Current implementation ignores invalid cursors gracefully
var taskStore = new InMemoryMcpTaskStore();
await using var fixture = new ServerClientFixture(LoggerFactory, configureServer: (services, builder) =>
{
services.AddSingleton<IMcpTaskStore>(taskStore);
services.Configure<McpServerOptions>(options => options.TaskStore = taskStore);
builder.WithTools([McpServerTool.Create(
async (CancellationToken ct) => { await Task.Delay(10, ct); return "ok"; },
new McpServerToolCreateOptions { Name = "test-tool" })]);
});
await using var client = await fixture.CreateClientAsync(TestContext.Current.CancellationToken);
// Act - Pass invalid cursor
var result = await client.ListTasksAsync(
new ListTasksRequestParams { Cursor = "invalid-cursor-that-does-not-exist" },
TestContext.Current.CancellationToken);
// Assert - Should return valid (possibly empty) result
Assert.NotNull(result.Tasks);
}
#endregion
#region Blocking Behavior Tests
[Fact]
public async Task GetTaskResultAsync_ReturnsImmediately_WhenTaskAlreadyComplete()
{
// Arrange
var taskStore = new InMemoryMcpTaskStore();
await using var fixture = new ServerClientFixture(LoggerFactory, configureServer: (services, builder) =>
{
services.AddSingleton<IMcpTaskStore>(taskStore);
services.Configure<McpServerOptions>(options => options.TaskStore = taskStore);
builder.WithTools([McpServerTool.Create(
async (CancellationToken ct) => { await Task.Delay(10, ct); return "quick result"; },
new McpServerToolCreateOptions { Name = "quick-tool" })]);
});
await using var client = await fixture.CreateClientAsync(TestContext.Current.CancellationToken);
// Create and wait for task to complete
var callResult = await client.CallToolAsync(
new CallToolRequestParams
{
Name = "quick-tool",
Arguments = new Dictionary<string, JsonElement>(),
Task = new McpTaskMetadata()
},
cancellationToken: TestContext.Current.CancellationToken);
Assert.NotNull(callResult.Task);
string taskId = callResult.Task.TaskId;
// Wait for task to complete
McpTask taskStatus;
do
{
await Task.Delay(50, TestContext.Current.CancellationToken);
taskStatus = await client.GetTaskAsync(taskId, cancellationToken: TestContext.Current.CancellationToken);
}
while (taskStatus.Status == McpTaskStatus.Working);
// Act - Get result (should return since task is complete)
var result = await client.GetTaskResultAsync(taskId, cancellationToken: TestContext.Current.CancellationToken);
// Assert - Should get valid result
Assert.NotEqual(default, result);
}
[Fact]
public async Task GetTaskResultAsync_ForFailedTask_ReturnsErrorResult()
{
// Arrange
var taskStore = new InMemoryMcpTaskStore();
await using var fixture = new ServerClientFixture(LoggerFactory, configureServer: (services, builder) =>
{
services.AddSingleton<IMcpTaskStore>(taskStore);
services.Configure<McpServerOptions>(options => options.TaskStore = taskStore);
builder.WithTools([McpServerTool.Create(
async (CancellationToken ct) =>
{
await Task.Delay(10, ct);
throw new InvalidOperationException("Tool execution failed intentionally");
#pragma warning disable CS0162 // Unreachable code detected
return "never";
#pragma warning restore CS0162
},
new McpServerToolCreateOptions { Name = "failable-tool" })]);
});
await using var client = await fixture.CreateClientAsync(TestContext.Current.CancellationToken);
// Create a failing task
var callResult = await client.CallToolAsync(
new CallToolRequestParams
{
Name = "failable-tool",
Arguments = new Dictionary<string, JsonElement>(),
Task = new McpTaskMetadata()
},
cancellationToken: TestContext.Current.CancellationToken);
Assert.NotNull(callResult.Task);
string taskId = callResult.Task.TaskId;
// Wait for task to fail
McpTask taskStatus;
int attempts = 0;
do
{
await Task.Delay(50, TestContext.Current.CancellationToken);
taskStatus = await client.GetTaskAsync(taskId, cancellationToken: TestContext.Current.CancellationToken);
attempts++;
}
while (taskStatus.Status == McpTaskStatus.Working && attempts < 50);
Assert.Equal(McpTaskStatus.Failed, taskStatus.Status);
// Act - Get result for failed task
var result = await client.GetTaskResultAsync(taskId, cancellationToken: TestContext.Current.CancellationToken);
var toolResult = result.Deserialize<CallToolResult>(McpJsonUtilities.DefaultOptions);
// Assert - Failed task should have isError=true
Assert.NotNull(toolResult);
Assert.True(toolResult.IsError, "Failed task should have isError=true in the result");
}
#endregion
#region Task Consistency and Lifecycle Tests
[Fact]
public async Task ListTasksAsync_ContainsAllTasksRetrievableByGet()
{
// Arrange - Spec: "If a task is retrievable via tasks/get, it MUST be retrievable via tasks/list"
var taskStore = new InMemoryMcpTaskStore();
await using var fixture = new ServerClientFixture(LoggerFactory, configureServer: (services, builder) =>
{
services.AddSingleton<IMcpTaskStore>(taskStore);
services.Configure<McpServerOptions>(options => options.TaskStore = taskStore);
builder.WithTools([McpServerTool.Create(
async (string input, CancellationToken ct) => { await Task.Delay(10, ct); return $"Result: {input}"; },
new McpServerToolCreateOptions { Name = "test-tool" })]);
});
await using var client = await fixture.CreateClientAsync(TestContext.Current.CancellationToken);
// Create multiple tasks
var createdTaskIds = new List<string>();
for (int i = 0; i < 3; i++)
{
var result = await client.CallToolAsync(
new CallToolRequestParams
{
Name = "test-tool",
Arguments = new Dictionary<string, JsonElement>
{
["input"] = JsonDocument.Parse($"\"task-{i}\"").RootElement.Clone()
},
Task = new McpTaskMetadata()
},
cancellationToken: TestContext.Current.CancellationToken);
Assert.NotNull(result.Task);
createdTaskIds.Add(result.Task.TaskId);
}
// Verify each task is retrievable via get
foreach (var taskId in createdTaskIds)
{
var task = await client.GetTaskAsync(taskId, cancellationToken: TestContext.Current.CancellationToken);
Assert.NotNull(task);
}
// Act - List all tasks
var allTasks = await client.ListTasksAsync(cancellationToken: TestContext.Current.CancellationToken);
// Assert - All tasks must be in the list
foreach (var taskId in createdTaskIds)
{
Assert.Contains(allTasks, t => t.TaskId == taskId);
}
}
[Fact]
public async Task NewTask_StartsInWorkingStatus()
{
// Arrange - Spec: "Tasks MUST begin in the working status when created."
var taskStarted = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
var taskCanComplete = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
var taskStore = new InMemoryMcpTaskStore();
await using var fixture = new ServerClientFixture(LoggerFactory, configureServer: (services, builder) =>
{
services.AddSingleton<IMcpTaskStore>(taskStore);
services.Configure<McpServerOptions>(options => options.TaskStore = taskStore);
builder.WithTools([McpServerTool.Create(
async (CancellationToken ct) =>
{
taskStarted.TrySetResult(true);
await taskCanComplete.Task.WaitAsync(ct);
return "done";
},
new McpServerToolCreateOptions { Name = "controllable-tool" })]);
});
await using var client = await fixture.CreateClientAsync(TestContext.Current.CancellationToken);
// Act - Create a task
var callResult = await client.CallToolAsync(
new CallToolRequestParams
{
Name = "controllable-tool",
Arguments = new Dictionary<string, JsonElement>(),
Task = new McpTaskMetadata()
},
cancellationToken: TestContext.Current.CancellationToken);
// Assert
Assert.NotNull(callResult.Task);
Assert.Equal(McpTaskStatus.Working, callResult.Task.Status);
// Cleanup
taskCanComplete.TrySetResult(true);
}
[Fact]
public async Task Task_ContainsRequiredTimestamps()
{
// Arrange - Spec: "Receivers MUST include createdAt and lastUpdatedAt timestamps"
var taskStore = new InMemoryMcpTaskStore();
await using var fixture = new ServerClientFixture(LoggerFactory, configureServer: (services, builder) =>
{
services.AddSingleton<IMcpTaskStore>(taskStore);
services.Configure<McpServerOptions>(options => options.TaskStore = taskStore);
builder.WithTools([McpServerTool.Create(
async (CancellationToken ct) => { await Task.Delay(10, ct); return "ok"; },
new McpServerToolCreateOptions { Name = "test-tool" })]);
});
await using var client = await fixture.CreateClientAsync(TestContext.Current.CancellationToken);
var beforeCreation = DateTimeOffset.UtcNow;
// Act
var callResult = await client.CallToolAsync(
new CallToolRequestParams
{
Name = "test-tool",
Arguments = new Dictionary<string, JsonElement>(),
Task = new McpTaskMetadata()
},
cancellationToken: TestContext.Current.CancellationToken);
var afterCreation = DateTimeOffset.UtcNow;
// Assert
Assert.NotNull(callResult.Task);
Assert.NotEqual(default, callResult.Task.CreatedAt);
Assert.NotEqual(default, callResult.Task.LastUpdatedAt);
Assert.True(callResult.Task.CreatedAt >= beforeCreation.AddSeconds(-1));
Assert.True(callResult.Task.CreatedAt <= afterCreation.AddSeconds(1));
}
[Fact]
public async Task Task_IncludesTtlInResponse()
{
// Arrange - Spec: "Receivers MUST include the actual ttl duration in tasks/get responses."
var taskStore = new InMemoryMcpTaskStore();
await using var fixture = new ServerClientFixture(LoggerFactory, configureServer: (services, builder) =>
{
services.AddSingleton<IMcpTaskStore>(taskStore);
services.Configure<McpServerOptions>(options => options.TaskStore = taskStore);
builder.WithTools([McpServerTool.Create(
async (CancellationToken ct) => { await Task.Delay(10, ct); return "ok"; },
new McpServerToolCreateOptions { Name = "test-tool" })]);
});
await using var client = await fixture.CreateClientAsync(TestContext.Current.CancellationToken);
// Act
var callResult = await client.CallToolAsync(
new CallToolRequestParams
{
Name = "test-tool",
Arguments = new Dictionary<string, JsonElement>(),
Task = new McpTaskMetadata { TimeToLive = TimeSpan.FromMinutes(30) }
},
cancellationToken: TestContext.Current.CancellationToken);
// Assert
Assert.NotNull(callResult.Task);
Assert.NotNull(callResult.Task.TimeToLive);
var taskStatus = await client.GetTaskAsync(callResult.Task.TaskId, cancellationToken: TestContext.Current.CancellationToken);
Assert.NotNull(taskStatus.TimeToLive);
}
[Fact]
public async Task Task_IncludesPollIntervalInResponse()
{
// Arrange - Spec: "Receivers MAY include a pollInterval value"
var taskStore = new InMemoryMcpTaskStore();
await using var fixture = new ServerClientFixture(LoggerFactory, configureServer: (services, builder) =>
{
services.AddSingleton<IMcpTaskStore>(taskStore);
services.Configure<McpServerOptions>(options => options.TaskStore = taskStore);
builder.WithTools([McpServerTool.Create(
async (CancellationToken ct) => { await Task.Delay(10, ct); return "ok"; },
new McpServerToolCreateOptions { Name = "test-tool" })]);
});
await using var client = await fixture.CreateClientAsync(TestContext.Current.CancellationToken);
// Act
var callResult = await client.CallToolAsync(
new CallToolRequestParams
{
Name = "test-tool",
Arguments = new Dictionary<string, JsonElement>(),
Task = new McpTaskMetadata()
},
cancellationToken: TestContext.Current.CancellationToken);
// Assert
Assert.NotNull(callResult.Task);
Assert.NotNull(callResult.Task.PollInterval);
}
#endregion
#region Server Without Tasks Capability Tests
[Fact]
public async Task ServerCapabilities_DoNotIncludeTasks_WhenNoTaskStore()
{
// Arrange - Spec: "If capabilities.tasks is not defined, the peer SHOULD NOT attempt to create tasks"
await using var fixture = new ServerClientFixture(LoggerFactory, configureServer: (services, builder) =>
{
// NOT configuring a task store
builder.WithTools([McpServerTool.Create(
async (CancellationToken ct) => { await Task.Delay(10, ct); return "ok"; },
new McpServerToolCreateOptions { Name = "async-tool" })]);
});
await using var client = await fixture.CreateClientAsync(TestContext.Current.CancellationToken);
// Assert
Assert.Null(client.ServerCapabilities?.Tasks);
}
[Fact]
public async Task NormalRequest_Succeeds_WhenTasksNotSupported()
{
// Arrange - Normal requests should work without task support
await using var fixture = new ServerClientFixture(LoggerFactory, configureServer: (services, builder) =>
{
builder.WithTools([McpServerTool.Create(
(string input) => $"Sync result: {input}",
new McpServerToolCreateOptions { Name = "sync-tool" })]);
});
await using var client = await fixture.CreateClientAsync(TestContext.Current.CancellationToken);
// Act
var result = await client.CallToolAsync(
new CallToolRequestParams
{
Name = "sync-tool",
Arguments = CreateArguments("input", "test")
},
cancellationToken: TestContext.Current.CancellationToken);
// Assert
Assert.NotNull(result.Content);
Assert.Null(result.Task);
}
#endregion
/// <summary>
/// Helper fixture for creating server-client pairs with custom configuration.
/// </summary>
private sealed class ServerClientFixture : IAsyncDisposable
{
private readonly System.IO.Pipelines.Pipe _clientToServerPipe = new();
private readonly System.IO.Pipelines.Pipe _serverToClientPipe = new();
private readonly IServiceProvider _serviceProvider;
private readonly McpServer _server;
private readonly Task _serverTask;
private readonly CancellationTokenSource _cts;
private readonly ILoggerFactory _loggerFactory;
public ServerClientFixture(
ILoggerFactory loggerFactory,
Action<ServiceCollection, IMcpServerBuilder>? configureServer = null)
{
_loggerFactory = loggerFactory;
_cts = new CancellationTokenSource();
var services = new ServiceCollection();
services.AddLogging();
services.AddSingleton(loggerFactory);
var builder = services
.AddMcpServer()
.WithStreamServerTransport(
_clientToServerPipe.Reader.AsStream(),
_serverToClientPipe.Writer.AsStream());
configureServer?.Invoke(services, builder);
_serviceProvider = services.BuildServiceProvider(validateScopes: true);
_server = _serviceProvider.GetRequiredService<McpServer>();
_serverTask = _server.RunAsync(_cts.Token);
}
public async Task<McpClient> CreateClientAsync(CancellationToken cancellationToken)
{
return await McpClient.CreateAsync(
new StreamClientTransport(
serverInput: _clientToServerPipe.Writer.AsStream(),
_serverToClientPipe.Reader.AsStream(),
_loggerFactory),
loggerFactory: _loggerFactory,
cancellationToken: cancellationToken);
}
public async ValueTask DisposeAsync()
{
await _cts.CancelAsync();
_clientToServerPipe.Writer.Complete();
_serverToClientPipe.Writer.Complete();
try
{
await _serverTask;
}
catch (OperationCanceledException)
{
// Expected
}
if (_serviceProvider is IAsyncDisposable asyncDisposable)
{
await asyncDisposable.DisposeAsync();
}
else if (_serviceProvider is IDisposable disposable)
{
disposable.Dispose();
}
_cts.Dispose();
}
}
}