-
Notifications
You must be signed in to change notification settings - Fork 182
/
Copy pathMcpServerTests.cs
768 lines (674 loc) · 28.7 KB
/
McpServerTests.cs
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
using Microsoft.Extensions.AI;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using ModelContextProtocol.Protocol.Messages;
using ModelContextProtocol.Protocol.Types;
using ModelContextProtocol.Server;
using ModelContextProtocol.Tests.Utils;
using System.Reflection;
using System.Text.Json;
using System.Text.Json.Nodes;
namespace ModelContextProtocol.Tests.Server;
public class McpServerTests : LoggedTest
{
private readonly McpServerOptions _options;
public McpServerTests(ITestOutputHelper testOutputHelper)
: base(testOutputHelper)
{
_options = CreateOptions();
}
private static McpServerOptions CreateOptions(ServerCapabilities? capabilities = null)
{
return new McpServerOptions
{
ProtocolVersion = "2024",
InitializationTimeout = TimeSpan.FromSeconds(30),
Capabilities = capabilities,
};
}
[Fact]
public async Task Constructor_Should_Initialize_With_Valid_Parameters()
{
// Arrange & Act
await using var transport = new TestServerTransport();
await using var server = McpServerFactory.Create(transport, _options, LoggerFactory);
// Assert
Assert.NotNull(server);
}
[Fact]
public void Constructor_Throws_For_Null_Transport()
{
// Arrange, Act & Assert
Assert.Throws<ArgumentNullException>(() => McpServerFactory.Create(null!, _options, LoggerFactory));
}
[Fact]
public async Task Constructor_Throws_For_Null_Options()
{
// Arrange, Act & Assert
await using var transport = new TestServerTransport();
Assert.Throws<ArgumentNullException>(() => McpServerFactory.Create(transport, null!, LoggerFactory));
}
[Fact]
public async Task Constructor_Does_Not_Throw_For_Null_Logger()
{
// Arrange & Act
await using var transport = new TestServerTransport();
await using var server = McpServerFactory.Create(transport, _options, null);
// Assert
Assert.NotNull(server);
}
[Fact]
public async Task Constructor_Does_Not_Throw_For_Null_ServiceProvider()
{
// Arrange & Act
await using var transport = new TestServerTransport();
await using var server = McpServerFactory.Create(transport, _options, LoggerFactory, null);
// Assert
Assert.NotNull(server);
}
[Fact]
public async Task RunAsync_Should_Throw_InvalidOperationException_If_Already_Running()
{
// Arrange
await using var transport = new TestServerTransport();
await using var server = McpServerFactory.Create(transport, _options, LoggerFactory);
var runTask = server.RunAsync(TestContext.Current.CancellationToken);
// Act & Assert
await Assert.ThrowsAsync<InvalidOperationException>(() => server.RunAsync(TestContext.Current.CancellationToken));
await transport.DisposeAsync();
await runTask;
}
[Fact]
public async Task RequestSamplingAsync_Should_Throw_McpException_If_Client_Does_Not_Support_Sampling()
{
// Arrange
await using var transport = new TestServerTransport();
await using var server = McpServerFactory.Create(transport, _options, LoggerFactory);
SetClientCapabilities(server, new ClientCapabilities());
var action = () => server.RequestSamplingAsync(new CreateMessageRequestParams { Messages = [] }, CancellationToken.None);
// Act & Assert
await Assert.ThrowsAsync<ArgumentException>("server", action);
}
[Fact]
public async Task RequestSamplingAsync_Should_SendRequest()
{
// Arrange
await using var transport = new TestServerTransport();
await using var server = McpServerFactory.Create(transport, _options, LoggerFactory);
SetClientCapabilities(server, new ClientCapabilities { Sampling = new SamplingCapability() });
var runTask = server.RunAsync(TestContext.Current.CancellationToken);
// Act
var result = await server.RequestSamplingAsync(new CreateMessageRequestParams { Messages = [] }, CancellationToken.None);
Assert.NotNull(result);
Assert.NotEmpty(transport.SentMessages);
Assert.IsType<JsonRpcRequest>(transport.SentMessages[0]);
Assert.Equal(RequestMethods.SamplingCreateMessage, ((JsonRpcRequest)transport.SentMessages[0]).Method);
await transport.DisposeAsync();
await runTask;
}
[Fact]
public async Task RequestRootsAsync_Should_Throw_McpException_If_Client_Does_Not_Support_Roots()
{
// Arrange
await using var transport = new TestServerTransport();
await using var server = McpServerFactory.Create(transport, _options, LoggerFactory);
SetClientCapabilities(server, new ClientCapabilities());
// Act & Assert
await Assert.ThrowsAsync<ArgumentException>("server", () => server.RequestRootsAsync(new ListRootsRequestParams(), CancellationToken.None));
}
[Fact]
public async Task RequestRootsAsync_Should_SendRequest()
{
// Arrange
await using var transport = new TestServerTransport();
await using var server = McpServerFactory.Create(transport, _options, LoggerFactory);
SetClientCapabilities(server, new ClientCapabilities { Roots = new RootsCapability() });
var runTask = server.RunAsync(TestContext.Current.CancellationToken);
// Act
var result = await server.RequestRootsAsync(new ListRootsRequestParams(), CancellationToken.None);
// Assert
Assert.NotNull(result);
Assert.NotEmpty(transport.SentMessages);
Assert.IsType<JsonRpcRequest>(transport.SentMessages[0]);
Assert.Equal(RequestMethods.RootsList, ((JsonRpcRequest)transport.SentMessages[0]).Method);
await transport.DisposeAsync();
await runTask;
}
[Fact]
public async Task Can_Handle_Ping_Requests()
{
await Can_Handle_Requests(
serverCapabilities: null,
method: RequestMethods.Ping,
configureOptions: null,
assertResult: response =>
{
JsonObject jObj = Assert.IsType<JsonObject>(response);
Assert.Empty(jObj);
});
}
[Fact]
public async Task Can_Handle_Initialize_Requests()
{
await Can_Handle_Requests(
serverCapabilities: null,
method: RequestMethods.Initialize,
configureOptions: null,
assertResult: response =>
{
var result = JsonSerializer.Deserialize<InitializeResult>(response);
Assert.NotNull(result);
Assert.Equal("ModelContextProtocol.Tests", result.ServerInfo.Name);
Assert.Equal("1.0.0.0", result.ServerInfo.Version);
Assert.Equal("2024", result.ProtocolVersion);
});
}
[Fact]
public async Task Can_Handle_Completion_Requests()
{
await Can_Handle_Requests(
serverCapabilities: null,
method: RequestMethods.CompletionComplete,
configureOptions: null,
assertResult: response =>
{
var result = JsonSerializer.Deserialize<CompleteResult>(response);
Assert.NotNull(result?.Completion);
Assert.Empty(result.Completion.Values);
Assert.Equal(0, result.Completion.Total);
Assert.False(result.Completion.HasMore);
});
}
[Fact]
public async Task Can_Handle_Completion_Requests_With_Handler()
{
await Can_Handle_Requests(
serverCapabilities: null,
method: RequestMethods.CompletionComplete,
configureOptions: options =>
{
options.GetCompletionHandler = (request, ct) =>
Task.FromResult(new CompleteResult
{
Completion = new()
{
Values = ["test"],
Total = 2,
HasMore = true
}
});
},
assertResult: response =>
{
CompleteResult? result = JsonSerializer.Deserialize<CompleteResult>(response);
Assert.NotNull(result?.Completion);
Assert.NotEmpty(result.Completion.Values);
Assert.Equal("test", result.Completion.Values[0]);
Assert.Equal(2, result.Completion.Total);
Assert.True(result.Completion.HasMore);
});
}
[Fact]
public async Task Can_Handle_ResourceTemplates_List_Requests()
{
await Can_Handle_Requests(
new ServerCapabilities
{
Resources = new()
{
ListResourceTemplatesHandler = (request, ct) =>
{
return Task.FromResult(new ListResourceTemplatesResult
{
ResourceTemplates = [new() { UriTemplate = "test", Name = "Test Resource" }]
});
},
ListResourcesHandler = (request, ct) =>
{
return Task.FromResult(new ListResourcesResult
{
Resources = [new() { Uri = "test", Name = "Test Resource" }]
});
},
ReadResourceHandler = (request, ct) => throw new NotImplementedException(),
}
},
RequestMethods.ResourcesTemplatesList,
configureOptions: null,
assertResult: response =>
{
var result = JsonSerializer.Deserialize<ListResourceTemplatesResult>(response);
Assert.NotNull(result?.ResourceTemplates);
Assert.NotEmpty(result.ResourceTemplates);
Assert.Equal("test", result.ResourceTemplates[0].UriTemplate);
});
}
[Fact]
public async Task Can_Handle_Resources_List_Requests()
{
await Can_Handle_Requests(
new ServerCapabilities
{
Resources = new()
{
ListResourcesHandler = (request, ct) =>
{
return Task.FromResult(new ListResourcesResult
{
Resources = [new() { Uri = "test", Name = "Test Resource" }]
});
},
ReadResourceHandler = (request, ct) => throw new NotImplementedException(),
}
},
RequestMethods.ResourcesList,
configureOptions: null,
assertResult: response =>
{
var result = JsonSerializer.Deserialize<ListResourcesResult>(response);
Assert.NotNull(result?.Resources);
Assert.NotEmpty(result.Resources);
Assert.Equal("test", result.Resources[0].Uri);
});
}
[Fact]
public async Task Can_Handle_Resources_List_Requests_Throws_Exception_If_No_Handler_Assigned()
{
await Throws_Exception_If_No_Handler_Assigned(new ServerCapabilities { Resources = new() }, RequestMethods.ResourcesList, "ListResources handler not configured");
}
[Fact]
public async Task Can_Handle_ResourcesRead_Requests()
{
await Can_Handle_Requests(
new ServerCapabilities
{
Resources = new()
{
ReadResourceHandler = (request, ct) =>
{
return Task.FromResult(new ReadResourceResult
{
Contents = [new TextResourceContents { Text = "test" }]
});
},
ListResourcesHandler = (request, ct) => throw new NotImplementedException(),
}
},
method: RequestMethods.ResourcesRead,
configureOptions: null,
assertResult: response =>
{
var result = JsonSerializer.Deserialize<ReadResourceResult>(response);
Assert.NotNull(result?.Contents);
Assert.NotEmpty(result.Contents);
TextResourceContents textResource = Assert.IsType<TextResourceContents>(result.Contents[0]);
Assert.Equal("test", textResource.Text);
});
}
[Fact]
public async Task Can_Handle_Resources_Read_Requests_Throws_Exception_If_No_Handler_Assigned()
{
await Throws_Exception_If_No_Handler_Assigned(new ServerCapabilities { Resources = new() }, RequestMethods.ResourcesRead, "ReadResource handler not configured");
}
[Fact]
public async Task Can_Handle_List_Prompts_Requests()
{
await Can_Handle_Requests(
new ServerCapabilities
{
Prompts = new()
{
ListPromptsHandler = (request, ct) =>
{
return Task.FromResult(new ListPromptsResult
{
Prompts = [new() { Name = "test" }]
});
},
GetPromptHandler = (request, ct) => throw new NotImplementedException(),
},
},
method: RequestMethods.PromptsList,
configureOptions: null,
assertResult: response =>
{
var result = JsonSerializer.Deserialize<ListPromptsResult>(response);
Assert.NotNull(result?.Prompts);
Assert.NotEmpty(result.Prompts);
Assert.Equal("test", result.Prompts[0].Name);
});
}
[Fact]
public async Task Can_Handle_List_Prompts_Requests_Throws_Exception_If_No_Handler_Assigned()
{
await Throws_Exception_If_No_Handler_Assigned(new ServerCapabilities { Prompts = new() }, RequestMethods.PromptsList, "ListPrompts handler not configured");
}
[Fact]
public async Task Can_Handle_Get_Prompts_Requests()
{
await Can_Handle_Requests(
new ServerCapabilities
{
Prompts = new()
{
GetPromptHandler = (request, ct) => Task.FromResult(new GetPromptResult { Description = "test" }),
ListPromptsHandler = (request, ct) => throw new NotImplementedException(),
}
},
method: RequestMethods.PromptsGet,
configureOptions: null,
assertResult: response =>
{
var result = JsonSerializer.Deserialize<GetPromptResult>(response);
Assert.NotNull(result);
Assert.Equal("test", result.Description);
});
}
[Fact]
public async Task Can_Handle_Get_Prompts_Requests_Throws_Exception_If_No_Handler_Assigned()
{
await Throws_Exception_If_No_Handler_Assigned(new ServerCapabilities { Prompts = new() }, RequestMethods.PromptsGet, "GetPrompt handler not configured");
}
[Fact]
public async Task Can_Handle_List_Tools_Requests()
{
await Can_Handle_Requests(
new ServerCapabilities
{
Tools = new()
{
ListToolsHandler = (request, ct) =>
{
return Task.FromResult(new ListToolsResult
{
Tools = [new() { Name = "test" }]
});
},
CallToolHandler = (request, ct) => throw new NotImplementedException(),
}
},
method: RequestMethods.ToolsList,
configureOptions: null,
assertResult: response =>
{
var result = JsonSerializer.Deserialize<ListToolsResult>(response);
Assert.NotNull(result);
Assert.NotEmpty(result.Tools);
Assert.Equal("test", result.Tools[0].Name);
});
}
[Fact]
public async Task Can_Handle_List_Tools_Requests_Throws_Exception_If_No_Handler_Assigned()
{
await Throws_Exception_If_No_Handler_Assigned(new ServerCapabilities { Tools = new() }, RequestMethods.ToolsList, "ListTools handler not configured");
}
[Fact]
public async Task Can_Handle_Call_Tool_Requests()
{
await Can_Handle_Requests(
new ServerCapabilities
{
Tools = new()
{
CallToolHandler = (request, ct) =>
{
return Task.FromResult(new CallToolResponse
{
Content = [new Content { Text = "test" }]
});
},
ListToolsHandler = (request, ct) => throw new NotImplementedException(),
}
},
method: RequestMethods.ToolsCall,
configureOptions: null,
assertResult: response =>
{
var result = JsonSerializer.Deserialize<CallToolResponse>(response);
Assert.NotNull(result);
Assert.NotEmpty(result.Content);
Assert.Equal("test", result.Content[0].Text);
});
}
[Fact]
public async Task Can_Handle_Call_Tool_Requests_Throws_Exception_If_No_Handler_Assigned()
{
await Throws_Exception_If_No_Handler_Assigned(new ServerCapabilities { Tools = new() }, RequestMethods.ToolsCall, "CallTool handler not configured");
}
private async Task Can_Handle_Requests(ServerCapabilities? serverCapabilities, string method, Action<McpServerOptions>? configureOptions, Action<JsonNode?> assertResult)
{
await using var transport = new TestServerTransport();
var options = CreateOptions(serverCapabilities);
configureOptions?.Invoke(options);
await using var server = McpServerFactory.Create(transport, options, LoggerFactory);
var runTask = server.RunAsync(TestContext.Current.CancellationToken);
var receivedMessage = new TaskCompletionSource<JsonRpcResponse>();
transport.OnMessageSent = (message) =>
{
if (message is JsonRpcResponse response && response.Id.ToString() == "55")
receivedMessage.SetResult(response);
};
await transport.SendMessageAsync(
new JsonRpcRequest
{
Method = method,
Id = new RequestId(55)
}
);
var response = await receivedMessage.Task.WaitAsync(TimeSpan.FromSeconds(5));
Assert.NotNull(response);
assertResult(response.Result);
await transport.DisposeAsync();
await runTask;
}
private async Task Throws_Exception_If_No_Handler_Assigned(ServerCapabilities serverCapabilities, string method, string expectedError)
{
await using var transport = new TestServerTransport();
var options = CreateOptions(serverCapabilities);
Assert.Throws<McpException>(() => McpServerFactory.Create(transport, options, LoggerFactory));
}
[Fact]
public async Task AsSamplingChatClient_NoSamplingSupport_Throws()
{
await using var server = new TestServerForIChatClient(supportsSampling: false);
Assert.Throws<ArgumentException>("server", () => server.AsSamplingChatClient());
}
[Fact]
public async Task AsSamplingChatClient_HandlesRequestResponse()
{
await using var server = new TestServerForIChatClient(supportsSampling: true);
IChatClient client = server.AsSamplingChatClient();
ChatMessage[] messages =
[
new (ChatRole.System, "You are a helpful assistant."),
new (ChatRole.User, "I am going to France."),
new (ChatRole.User, "What is the most famous tower in Paris?"),
new (ChatRole.System, "More system stuff."),
];
ChatResponse response = await client.GetResponseAsync(messages, new ChatOptions
{
Temperature = 0.75f,
MaxOutputTokens = 42,
StopSequences = ["."],
}, TestContext.Current.CancellationToken);
Assert.Equal("amazingmodel", response.ModelId);
Assert.Equal(ChatFinishReason.Stop, response.FinishReason);
Assert.Single(response.Messages);
Assert.Equal("The Eiffel Tower.", response.Text);
Assert.Equal(ChatRole.Assistant, response.Messages[0].Role);
}
[Fact]
public async Task Can_SendMessage_Before_RunAsync()
{
await using var transport = new TestServerTransport();
await using var server = McpServerFactory.Create(transport, _options, LoggerFactory);
var logNotification = new JsonRpcNotification()
{
Method = NotificationMethods.LoggingMessageNotification
};
await server.SendMessageAsync(logNotification, TestContext.Current.CancellationToken);
var runTask = server.RunAsync(TestContext.Current.CancellationToken);
await transport.DisposeAsync();
await runTask;
Assert.NotEmpty(transport.SentMessages);
Assert.Same(logNotification, transport.SentMessages[0]);
}
private static void SetClientCapabilities(IMcpServer server, ClientCapabilities capabilities)
{
PropertyInfo? property = server.GetType().GetProperty("ClientCapabilities", BindingFlags.Public | BindingFlags.Instance);
Assert.NotNull(property);
property.SetValue(server, capabilities);
}
private sealed class TestServerForIChatClient(bool supportsSampling) : IMcpServer
{
public ClientCapabilities? ClientCapabilities =>
supportsSampling ? new ClientCapabilities { Sampling = new SamplingCapability() } :
null;
public Task<JsonRpcResponse> SendRequestAsync(JsonRpcRequest request, CancellationToken cancellationToken)
{
CreateMessageRequestParams? rp = JsonSerializer.Deserialize<CreateMessageRequestParams>(request.Params);
Assert.NotNull(rp);
Assert.Equal(0.75f, rp.Temperature);
Assert.Equal(42, rp.MaxTokens);
Assert.Equal(["."], rp.StopSequences);
Assert.Null(rp.IncludeContext);
Assert.Null(rp.Metadata);
Assert.Null(rp.ModelPreferences);
Assert.Equal($"You are a helpful assistant.{Environment.NewLine}More system stuff.", rp.SystemPrompt);
Assert.Equal(2, rp.Messages.Count);
Assert.Equal("I am going to France.", rp.Messages[0].Content.Text);
Assert.Equal("What is the most famous tower in Paris?", rp.Messages[1].Content.Text);
CreateMessageResult result = new()
{
Content = new() { Text = "The Eiffel Tower.", Type = "text" },
Model = "amazingmodel",
Role = "assistant",
StopReason = "endTurn",
};
return Task.FromResult(new JsonRpcResponse
{
Id = new RequestId("0"),
Result = JsonSerializer.SerializeToNode(result),
});
}
public ValueTask DisposeAsync() => default;
public Implementation? ClientInfo => throw new NotImplementedException();
public McpServerOptions ServerOptions => throw new NotImplementedException();
public IServiceProvider? Services => throw new NotImplementedException();
public Task SendMessageAsync(IJsonRpcMessage message, CancellationToken cancellationToken = default) =>
throw new NotImplementedException();
public Task RunAsync(CancellationToken cancellationToken = default) =>
throw new NotImplementedException();
public IAsyncDisposable RegisterNotificationHandler(string method, Func<JsonRpcNotification, CancellationToken, Task> handler) =>
throw new NotImplementedException();
}
[Fact]
public async Task NotifyProgress_Should_Be_Handled()
{
await using TestServerTransport transport = new();
var options = CreateOptions();
var notificationReceived = new TaskCompletionSource<JsonRpcNotification>();
options.Capabilities = new()
{
NotificationHandlers = [new(NotificationMethods.ProgressNotification, (notification, cancellationToken) =>
{
notificationReceived.TrySetResult(notification);
return Task.CompletedTask;
})],
};
var server = McpServerFactory.Create(transport, options, LoggerFactory);
Task serverTask = server.RunAsync(TestContext.Current.CancellationToken);
await transport.SendMessageAsync(new JsonRpcNotification
{
Method = NotificationMethods.ProgressNotification,
Params = JsonSerializer.SerializeToNode(new ProgressNotification
{
ProgressToken = new("abc"),
Progress = new()
{
Progress = 50,
Total = 100,
Message = "Progress message",
},
}),
}, TestContext.Current.CancellationToken);
var notification = await notificationReceived.Task;
var progress = JsonSerializer.Deserialize<ProgressNotification>(notification.Params);
Assert.NotNull(progress);
Assert.Equal("abc", progress.ProgressToken.ToString());
Assert.Equal(50, progress.Progress.Progress);
Assert.Equal(100, progress.Progress.Total);
Assert.Equal("Progress message", progress.Progress.Message);
await server.DisposeAsync();
await serverTask;
}
[Fact]
public async Task NotifyCancel_Should_Be_Handled()
{
// Arrange
TaskCompletionSource<JsonRpcNotification> notificationReceived = new();
await using TestServerTransport transport = new(LoggerFactory);
transport.OnMessageSent = (message) =>
{
if (message is JsonRpcNotification notification
&& notification.Method == NotificationMethods.CancelledNotification)
notificationReceived.TrySetResult(notification);
};
var options = CreateOptions();
await using var server = McpServerFactory.Create(transport, options, LoggerFactory);
// Act
var token = TestContext.Current.CancellationToken;
Task serverTask = server.RunAsync(token);
await server.SendNotificationAsync(
NotificationMethods.CancelledNotification,
new CancelledNotification
{
RequestId = new("abc"),
Reason = "Cancelled",
}, cancellationToken: token);
await server.DisposeAsync();
await serverTask.WaitAsync(TimeSpan.FromSeconds(1), token);
var notification = await notificationReceived.Task.WaitAsync(TimeSpan.FromSeconds(1), token);
// Assert
var cancelled = JsonSerializer.Deserialize<CancelledNotification>(notification.Params);
Assert.NotNull(cancelled);
Assert.Equal("abc", cancelled.RequestId.ToString());
Assert.Equal("Cancelled", cancelled.Reason);
}
[Fact]
public async Task SendRequest_Should_Notify_When_Cancelled()
{
// Arrange
TaskCompletionSource<JsonRpcNotification> notificationReceived = new();
await using TestServerTransport transport = new(LoggerFactory);
transport.OnMessageSent = (message) =>
{
if (message is JsonRpcNotification notification
&& notification.Method == NotificationMethods.CancelledNotification)
notificationReceived.TrySetResult(notification);
};
var options = CreateOptions();
await using var server = McpServerFactory.Create(transport, options, LoggerFactory);
// Act
var token = TestContext.Current.CancellationToken;
Task serverTask = server.RunAsync(token);
using CancellationTokenSource cts = new();
await cts.CancelAsync();
await Assert.ThrowsAsync<TaskCanceledException>(async () =>
{
await server.SendRequestAsync(new JsonRpcRequest
{
Method = RequestMethods.Ping,
Id = new("abc"),
}, cts.Token);
});
await server.DisposeAsync();
await serverTask.WaitAsync(TimeSpan.FromSeconds(1), token);
var notification = await notificationReceived.Task.WaitAsync(TimeSpan.FromSeconds(1), token);
// Assert
var cancelled = JsonSerializer.Deserialize<CancelledNotification>(notification.Params);
Assert.NotNull(cancelled);
Assert.Equal("abc", cancelled.RequestId.ToString());
Assert.Null(cancelled.Reason);
}
}