-
Notifications
You must be signed in to change notification settings - Fork 687
Expand file tree
/
Copy pathMcpServerBuilderExtensionsToolsTests.cs
More file actions
1029 lines (853 loc) · 40 KB
/
McpServerBuilderExtensionsToolsTests.cs
File metadata and controls
1029 lines (853 loc) · 40 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.AI;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using ModelContextProtocol.Client;
using ModelContextProtocol.Protocol;
using ModelContextProtocol.Server;
using Moq;
using System.Collections;
using System.Collections.Concurrent;
using System.ComponentModel;
using System.IO.Pipelines;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
using System.Threading.Channels;
namespace ModelContextProtocol.Tests.Configuration;
public partial class McpServerBuilderExtensionsToolsTests : ClientServerTestBase
{
public McpServerBuilderExtensionsToolsTests(ITestOutputHelper testOutputHelper)
: base(testOutputHelper)
{
}
protected override void ConfigureServices(ServiceCollection services, IMcpServerBuilder mcpServerBuilder)
{
mcpServerBuilder
.WithListToolsHandler(async (request, cancellationToken) =>
{
var cursor = request.Params?.Cursor;
switch (cursor)
{
case null:
return new()
{
NextCursor = "abc",
Tools = [new()
{
Name = "FirstCustomTool",
Description = "First tool returned by custom handler",
InputSchema = JsonElement.Parse("""
{
"type": "object",
"properties": {},
"required": []
}
"""),
}],
};
case "abc":
return new()
{
NextCursor = "def",
Tools = [new()
{
Name = "SecondCustomTool",
Description = "Second tool returned by custom handler",
InputSchema = JsonElement.Parse("""
{
"type": "object",
"properties": {},
"required": []
}
"""),
}],
};
case "def":
return new()
{
NextCursor = null,
Tools = [new()
{
Name = "FinalCustomTool",
Description = "Third tool returned by custom handler",
InputSchema = JsonElement.Parse("""
{
"type": "object",
"properties": {},
"required": []
}
"""),
}],
};
default:
throw new McpProtocolException($"Unexpected cursor: '{cursor}'", McpErrorCode.InvalidParams);
}
})
.WithCallToolHandler(async (request, cancellationToken) =>
{
switch (request.Params?.Name)
{
case "FirstCustomTool":
case "SecondCustomTool":
case "FinalCustomTool":
return new CallToolResult
{
Content = [new TextContentBlock { Text = $"{request.Params.Name}Result" }],
};
default:
throw new McpProtocolException($"Unknown tool: '{request.Params?.Name}'", McpErrorCode.InvalidParams);
}
})
.WithTools<EchoTool>(serializerOptions: BuilderToolsJsonContext.Default.Options);
services.AddSingleton(new ObjectWithId());
}
[Fact]
public void Adds_Tools_To_Server()
{
var serverOptions = ServiceProvider.GetRequiredService<IOptions<McpServerOptions>>().Value;
var tools = serverOptions.ToolCollection;
Assert.NotNull(tools);
Assert.NotEmpty(tools);
}
[Fact]
public async Task Can_List_Registered_Tools()
{
await using McpClient client = await CreateMcpClientForServer();
var tools = await client.ListToolsAsync(cancellationToken: TestContext.Current.CancellationToken);
Assert.Equal(19, tools.Count);
McpClientTool echoTool = tools.First(t => t.Name == "echo");
Assert.Equal("Echoes the input back to the client.", echoTool.Description);
Assert.Equal("object", echoTool.JsonSchema.GetProperty("type").GetString());
Assert.Equal(JsonValueKind.Object, echoTool.JsonSchema.GetProperty("properties").GetProperty("message").ValueKind);
Assert.Equal("the echoes message", echoTool.JsonSchema.GetProperty("properties").GetProperty("message").GetProperty("description").GetString());
Assert.Equal(1, echoTool.JsonSchema.GetProperty("required").GetArrayLength());
McpClientTool doubleEchoTool = tools.First(t => t.Name == "double_echo");
Assert.Equal("double_echo", doubleEchoTool.Name);
Assert.Equal("Echoes the input back to the client.", doubleEchoTool.Description);
}
[Fact]
public async Task Can_Create_Multiple_Servers_From_Options_And_List_Registered_Tools()
{
var options = ServiceProvider.GetRequiredService<IOptions<McpServerOptions>>().Value;
var loggerFactory = ServiceProvider.GetRequiredService<ILoggerFactory>();
for (int i = 0; i < 2; i++)
{
var stdinPipe = new Pipe();
var stdoutPipe = new Pipe();
await using var transport = new StreamServerTransport(stdinPipe.Reader.AsStream(), stdoutPipe.Writer.AsStream());
await using var server = McpServer.Create(transport, options, loggerFactory, ServiceProvider);
var serverRunTask = server.RunAsync(TestContext.Current.CancellationToken);
await using (var client = await McpClient.CreateAsync(
new StreamClientTransport(
serverInput: stdinPipe.Writer.AsStream(),
serverOutput: stdoutPipe.Reader.AsStream(),
LoggerFactory),
loggerFactory: LoggerFactory,
cancellationToken: TestContext.Current.CancellationToken))
{
var tools = await client.ListToolsAsync(cancellationToken: TestContext.Current.CancellationToken);
Assert.Equal(19, tools.Count);
McpClientTool echoTool = tools.First(t => t.Name == "echo");
Assert.Equal("Echoes the input back to the client.", echoTool.Description);
Assert.Equal("object", echoTool.JsonSchema.GetProperty("type").GetString());
Assert.Equal(JsonValueKind.Object, echoTool.JsonSchema.GetProperty("properties").GetProperty("message").ValueKind);
Assert.Equal("the echoes message", echoTool.JsonSchema.GetProperty("properties").GetProperty("message").GetProperty("description").GetString());
Assert.Equal(1, echoTool.JsonSchema.GetProperty("required").GetArrayLength());
McpClientTool doubleEchoTool = tools.First(t => t.Name == "double_echo");
Assert.Equal("double_echo", doubleEchoTool.Name);
Assert.Equal("Echoes the input back to the client.", doubleEchoTool.Description);
}
stdinPipe.Writer.Complete();
await serverRunTask;
stdoutPipe.Writer.Complete();
}
}
[Fact]
public async Task Can_Be_Notified_Of_Tool_Changes()
{
await using McpClient client = await CreateMcpClientForServer();
var tools = await client.ListToolsAsync(cancellationToken: TestContext.Current.CancellationToken);
Assert.Equal(19, tools.Count);
Channel<JsonRpcNotification> listChanged = Channel.CreateUnbounded<JsonRpcNotification>();
var notificationRead = listChanged.Reader.ReadAsync(TestContext.Current.CancellationToken);
Assert.False(notificationRead.IsCompleted);
var serverOptions = ServiceProvider.GetRequiredService<IOptions<McpServerOptions>>().Value;
var serverTools = serverOptions.ToolCollection;
Assert.NotNull(serverTools);
var newTool = McpServerTool.Create([McpServerTool(Name = "NewTool")] () => "42");
await using (client.RegisterNotificationHandler(NotificationMethods.ToolListChangedNotification, (notification, cancellationToken) =>
{
listChanged.Writer.TryWrite(notification);
return default;
}))
{
serverTools.Add(newTool);
await notificationRead;
tools = await client.ListToolsAsync(cancellationToken: TestContext.Current.CancellationToken);
Assert.Equal(20, tools.Count);
Assert.Contains(tools, t => t.Name == "NewTool");
notificationRead = listChanged.Reader.ReadAsync(TestContext.Current.CancellationToken);
Assert.False(notificationRead.IsCompleted);
serverTools.Remove(newTool);
await notificationRead;
}
tools = await client.ListToolsAsync(cancellationToken: TestContext.Current.CancellationToken);
Assert.Equal(19, tools.Count);
Assert.DoesNotContain(tools, t => t.Name == "NewTool");
}
[Fact]
public async Task Can_Call_Registered_Tool()
{
await using McpClient client = await CreateMcpClientForServer();
var result = await client.CallToolAsync(
"echo",
new Dictionary<string, object?>() { ["message"] = "Peter" },
cancellationToken: TestContext.Current.CancellationToken);
Assert.NotNull(result);
Assert.NotNull(result.Content);
Assert.NotEmpty(result.Content);
var tc = Assert.IsType<TextContentBlock>(result.Content[0]);
Assert.Equal("hello Peter", tc.Text);
Assert.Equal("text", tc.Type);
}
[Fact]
public async Task Can_Call_Registered_Tool_With_Array_Result()
{
await using McpClient client = await CreateMcpClientForServer();
var result = await client.CallToolAsync(
"echo_array",
new Dictionary<string, object?>() { ["message"] = "Peter" },
cancellationToken: TestContext.Current.CancellationToken);
Assert.NotNull(result.Content);
Assert.NotEmpty(result.Content);
Assert.Equal("""["hello Peter","hello2 Peter"]""", (result.Content[0] as TextContentBlock)?.Text);
result = await client.CallToolAsync(
"SecondCustomTool",
cancellationToken: TestContext.Current.CancellationToken);
Assert.NotNull(result);
Assert.NotNull(result.Content);
Assert.NotEmpty(result.Content);
Assert.Equal("SecondCustomToolResult", (result.Content[0] as TextContentBlock)?.Text);
}
[Fact]
public async Task Can_Call_Registered_Tool_With_Null_Result()
{
await using McpClient client = await CreateMcpClientForServer();
var result = await client.CallToolAsync(
"return_null",
cancellationToken: TestContext.Current.CancellationToken);
Assert.NotNull(result);
Assert.NotNull(result.Content);
Assert.Empty(result.Content);
}
[Fact]
public async Task Can_Call_Registered_Tool_With_Json_Result()
{
await using McpClient client = await CreateMcpClientForServer();
var result = await client.CallToolAsync(
"return_json",
cancellationToken: TestContext.Current.CancellationToken);
Assert.NotNull(result);
Assert.NotNull(result.Content);
Assert.NotEmpty(result.Content);
Assert.Equal("""{"SomeProp":false}""", Regex.Replace((result.Content[0] as TextContentBlock)?.Text ?? string.Empty, "\\s+", ""));
Assert.Equal("text", (result.Content[0] as TextContentBlock)?.Type);
}
[Fact]
public async Task Can_Call_Registered_Tool_With_Int_Result()
{
await using McpClient client = await CreateMcpClientForServer();
var result = await client.CallToolAsync(
"return_integer",
cancellationToken: TestContext.Current.CancellationToken);
Assert.NotNull(result.Content);
Assert.NotEmpty(result.Content);
Assert.Equal("5", (result.Content[0] as TextContentBlock)?.Text);
}
[Fact]
public async Task Can_Call_Registered_Tool_And_Pass_ComplexType()
{
await using McpClient client = await CreateMcpClientForServer();
var result = await client.CallToolAsync(
"echo_complex",
new Dictionary<string, object?>() { ["complex"] = JsonDocument.Parse("""{"Name": "Peter", "Age": 25}""").RootElement },
cancellationToken: TestContext.Current.CancellationToken);
Assert.NotNull(result);
Assert.NotNull(result.Content);
Assert.NotEmpty(result.Content);
Assert.Equal("Peter", (result.Content[0] as TextContentBlock)?.Text);
}
[Fact]
public async Task Can_Call_Registered_Tool_With_Instance_Method()
{
await using McpClient client = await CreateMcpClientForServer();
string[][] parts = new string[2][];
for (int i = 0; i < 2; i++)
{
var result = await client.CallToolAsync(
"get_ctor_parameter",
cancellationToken: TestContext.Current.CancellationToken);
Assert.NotNull(result);
Assert.NotNull(result.Content);
Assert.NotEmpty(result.Content);
parts[i] = (result.Content[0] as TextContentBlock)?.Text?.Split(':') ?? [];
Assert.Equal(2, parts[i].Length);
}
string random1 = parts[0][0];
string random2 = parts[1][0];
Assert.NotEqual(random1, random2);
string id1 = parts[0][1];
string id2 = parts[1][1];
Assert.Equal(id1, id2);
}
[Fact]
public async Task Returns_IsError_Content_And_Logs_Error_When_Tool_Fails()
{
await using McpClient client = await CreateMcpClientForServer();
var result = await client.CallToolAsync(
"throw_exception",
cancellationToken: TestContext.Current.CancellationToken);
Assert.True(result.IsError);
Assert.NotNull(result.Content);
Assert.NotEmpty(result.Content);
Assert.Contains("An error occurred", (result.Content[0] as TextContentBlock)?.Text);
var errorLog = Assert.Single(MockLoggerProvider.LogMessages, m => m.LogLevel == LogLevel.Error);
Assert.Equal($"\"throw_exception\" threw an unhandled exception.", errorLog.Message);
Assert.IsType<InvalidOperationException>(errorLog.Exception);
Assert.Equal("Test error", errorLog.Exception.Message);
}
[Fact]
public async Task Logs_Tool_Name_On_Successful_Call()
{
await using McpClient client = await CreateMcpClientForServer();
var result = await client.CallToolAsync(
"echo",
new Dictionary<string, object?> { ["message"] = "test" },
cancellationToken: TestContext.Current.CancellationToken);
Assert.True(result.IsError is not true);
Assert.Equal("hello test", (result.Content[0] as TextContentBlock)?.Text);
var infoLog = Assert.Single(MockLoggerProvider.LogMessages, m => m.Message == "\"echo\" completed. IsError = False.");
Assert.Equal(LogLevel.Information, infoLog.LogLevel);
}
[Fact]
public async Task Logs_Tool_Name_With_IsError_When_Tool_Returns_Error()
{
await using McpClient client = await CreateMcpClientForServer();
var result = await client.CallToolAsync(
"return_is_error",
cancellationToken: TestContext.Current.CancellationToken);
Assert.True(result.IsError);
Assert.Contains("Tool returned an error", (result.Content[0] as TextContentBlock)?.Text);
var infoLog = Assert.Single(MockLoggerProvider.LogMessages, m => m.Message == "\"return_is_error\" completed. IsError = True.");
Assert.Equal(LogLevel.Information, infoLog.LogLevel);
}
[Fact]
public async Task Logs_Tool_Error_When_Tool_Throws_OperationCanceledException()
{
await using McpClient client = await CreateMcpClientForServer();
var result = await client.CallToolAsync(
"throw_operation_canceled_exception",
cancellationToken: TestContext.Current.CancellationToken);
Assert.True(result.IsError);
Assert.NotNull(result.Content);
Assert.NotEmpty(result.Content);
Assert.Contains("An error occurred", (result.Content[0] as TextContentBlock)?.Text);
Assert.Contains(MockLoggerProvider.LogMessages, m =>
m.LogLevel == LogLevel.Error &&
m.Message == "\"throw_operation_canceled_exception\" threw an unhandled exception." &&
m.Exception is OperationCanceledException);
}
[Fact]
public async Task Logs_Tool_Error_When_Tool_Throws_McpProtocolException()
{
await using McpClient client = await CreateMcpClientForServer();
await Assert.ThrowsAsync<McpProtocolException>(async () => await client.CallToolAsync(
"throw_mcp_protocol_exception",
cancellationToken: TestContext.Current.CancellationToken));
Assert.Contains(MockLoggerProvider.LogMessages, m =>
m.LogLevel == LogLevel.Error &&
m.Message == "\"throw_mcp_protocol_exception\" threw an unhandled exception." &&
m.Exception is McpProtocolException);
Assert.Contains(MockLoggerProvider.LogMessages, m =>
m.LogLevel == LogLevel.Warning &&
m.Message.Contains("request handler failed"));
}
[Fact]
public async Task Throws_Exception_On_Unknown_Tool()
{
await using McpClient client = await CreateMcpClientForServer();
var e = await Assert.ThrowsAsync<McpProtocolException>(async () => await client.CallToolAsync(
"NotRegisteredTool",
cancellationToken: TestContext.Current.CancellationToken));
Assert.Contains("'NotRegisteredTool'", e.Message);
}
[Fact]
public async Task Returns_IsError_Missing_Parameter()
{
await using McpClient client = await CreateMcpClientForServer();
var result = await client.CallToolAsync(
"echo",
cancellationToken: TestContext.Current.CancellationToken);
Assert.True(result.IsError);
}
[Fact]
public void WithTools_InvalidArgs_Throws()
{
IMcpServerBuilder builder = new ServiceCollection().AddMcpServer();
Assert.Throws<ArgumentNullException>("tools", () => builder.WithTools((IEnumerable<McpServerTool>)null!));
Assert.Throws<ArgumentNullException>("toolTypes", () => builder.WithTools(toolTypes: (IEnumerable<Type>)null!));
Assert.Throws<ArgumentNullException>("target", () => builder.WithTools<object>(target: null!));
IMcpServerBuilder nullBuilder = null!;
Assert.Throws<ArgumentNullException>("builder", () => nullBuilder.WithTools<object>());
Assert.Throws<ArgumentNullException>("builder", () => nullBuilder.WithTools(new object()));
Assert.Throws<ArgumentNullException>("builder", () => nullBuilder.WithTools(Array.Empty<Type>()));
Assert.Throws<ArgumentNullException>("builder", () => nullBuilder.WithToolsFromAssembly());
}
[Fact]
public void Empty_Enumerables_Is_Allowed()
{
IMcpServerBuilder builder = new ServiceCollection().AddMcpServer();
builder.WithTools(tools: []); // no exception
builder.WithTools(toolTypes: []); // no exception
builder.WithTools<object>(); // no exception even though no tools exposed
builder.WithToolsFromAssembly(typeof(AIFunction).Assembly); // no exception even though no tools exposed
}
[Fact]
public void Register_Tools_From_Current_Assembly()
{
if (!JsonSerializer.IsReflectionEnabledByDefault)
{
return;
}
ServiceCollection sc = new();
sc.AddMcpServer().WithToolsFromAssembly();
IServiceProvider services = sc.BuildServiceProvider();
Assert.Contains(services.GetServices<McpServerTool>(), t => t.ProtocolTool.Name == "echo");
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void WithTools_Parameters_Satisfiable_From_DI(bool parameterInServices)
{
ServiceCollection sc = new();
if (parameterInServices)
{
sc.AddSingleton(new ComplexObject());
}
sc.AddMcpServer().WithTools([typeof(EchoTool)], BuilderToolsJsonContext.Default.Options);
IServiceProvider services = sc.BuildServiceProvider();
McpServerTool tool = services.GetServices<McpServerTool>().First(t => t.ProtocolTool.Name == "echo_complex");
if (parameterInServices)
{
Assert.DoesNotContain("\"complex\"", JsonSerializer.Serialize(tool.ProtocolTool.InputSchema, AIJsonUtilities.DefaultOptions));
}
else
{
Assert.Contains("\"complex\"", JsonSerializer.Serialize(tool.ProtocolTool.InputSchema, AIJsonUtilities.DefaultOptions));
}
}
[Theory]
[InlineData(ServiceLifetime.Singleton)]
[InlineData(ServiceLifetime.Scoped)]
[InlineData(ServiceLifetime.Transient)]
[InlineData(null)]
public void WithToolsFromAssembly_Parameters_Satisfiable_From_DI(ServiceLifetime? lifetime)
{
if (!JsonSerializer.IsReflectionEnabledByDefault)
{
return;
}
ServiceCollection sc = new();
switch (lifetime)
{
case ServiceLifetime.Singleton:
sc.AddSingleton(new ComplexObject());
break;
case ServiceLifetime.Scoped:
sc.AddScoped(_ => new ComplexObject());
break;
case ServiceLifetime.Transient:
sc.AddTransient(_ => new ComplexObject());
break;
}
sc.AddMcpServer().WithToolsFromAssembly();
IServiceProvider services = sc.BuildServiceProvider();
McpServerTool tool = services.GetServices<McpServerTool>().First(t => t.ProtocolTool.Name == "echo_complex");
if (lifetime is not null)
{
Assert.DoesNotContain("\"complex\"", JsonSerializer.Serialize(tool.ProtocolTool.InputSchema, AIJsonUtilities.DefaultOptions));
}
else
{
Assert.Contains("\"complex\"", JsonSerializer.Serialize(tool.ProtocolTool.InputSchema, AIJsonUtilities.DefaultOptions));
}
}
[Fact]
public async Task WithTools_TargetInstance_UsesTarget()
{
ServiceCollection sc = new();
var target = new EchoTool(new ObjectWithId());
sc.AddMcpServer().WithTools(target, BuilderToolsJsonContext.Default.Options);
McpServerTool tool = sc.BuildServiceProvider().GetServices<McpServerTool>().First(t => t.ProtocolTool.Name == "get_ctor_parameter");
var result = await tool.InvokeAsync(new RequestContext<CallToolRequestParams>(new Mock<McpServer>().Object, new JsonRpcRequest { Method = "test", Id = new RequestId("1") }), TestContext.Current.CancellationToken);
Assert.Equal(target.GetCtorParameter(), (result.Content[0] as TextContentBlock)?.Text);
}
[Fact]
public async Task WithTools_TargetInstance_UsesEnumerableImplementation()
{
ServiceCollection sc = new();
sc.AddMcpServer().WithTools(new MyToolProvider());
var tools = sc.BuildServiceProvider().GetServices<McpServerTool>().ToArray();
Assert.Equal(2, tools.Length);
Assert.Contains(tools, t => t.ProtocolTool.Name == "Returns42");
Assert.Contains(tools, t => t.ProtocolTool.Name == "Returns43");
}
private sealed class MyToolProvider : IEnumerable<McpServerTool>
{
public IEnumerator<McpServerTool> GetEnumerator()
{
yield return McpServerTool.Create(() => "42", new() { Name = "Returns42" });
yield return McpServerTool.Create(() => "43", new() { Name = "Returns43" });
}
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
[Fact]
public async Task Recognizes_Parameter_Types()
{
await using McpClient client = await CreateMcpClientForServer();
var tools = await client.ListToolsAsync(cancellationToken: TestContext.Current.CancellationToken);
Assert.NotNull(tools);
Assert.NotEmpty(tools);
var tool = tools.First(t => t.Name == "test_tool");
Assert.Empty(tool.Description!);
Assert.Equal("object", tool.JsonSchema.GetProperty("type").GetString());
Assert.Contains("integer", tool.JsonSchema.GetProperty("properties").GetProperty("number").GetProperty("type").GetString());
Assert.Contains("number", tool.JsonSchema.GetProperty("properties").GetProperty("otherNumber").GetProperty("type").GetString());
Assert.Contains("boolean", tool.JsonSchema.GetProperty("properties").GetProperty("someCheck").GetProperty("type").GetString());
Assert.Contains("string", tool.JsonSchema.GetProperty("properties").GetProperty("someDate").GetProperty("type").GetString());
Assert.Contains("string", tool.JsonSchema.GetProperty("properties").GetProperty("someOtherDate").GetProperty("type").GetString());
Assert.Contains("array", tool.JsonSchema.GetProperty("properties").GetProperty("data").GetProperty("type").GetString());
Assert.Contains("object", tool.JsonSchema.GetProperty("properties").GetProperty("complexObject").GetProperty("type").GetString());
}
[Fact]
public void Register_Tools_From_Multiple_Sources()
{
ServiceCollection sc = new();
sc.AddMcpServer()
.WithTools<EchoTool>(serializerOptions: BuilderToolsJsonContext.Default.Options)
.WithTools<AnotherToolType>(serializerOptions: BuilderToolsJsonContext.Default.Options)
.WithTools([typeof(ToolTypeWithNoAttribute)], BuilderToolsJsonContext.Default.Options)
.WithTools([McpServerTool.Create(() => "42", new() { Name = "Returns42" })]);
IServiceProvider services = sc.BuildServiceProvider();
Assert.Contains(services.GetServices<McpServerTool>(), t => t.ProtocolTool.Name == "double_echo");
Assert.Contains(services.GetServices<McpServerTool>(), t => t.ProtocolTool.Name == "DifferentName");
Assert.Contains(services.GetServices<McpServerTool>(), t => t.ProtocolTool.Name == "method_b");
Assert.Contains(services.GetServices<McpServerTool>(), t => t.ProtocolTool.Name == "method_c");
Assert.Contains(services.GetServices<McpServerTool>(), t => t.ProtocolTool.Name == "method_d");
Assert.Contains(services.GetServices<McpServerTool>(), t => t.ProtocolTool.Name == "Returns42");
}
[Fact]
public void Register_Static_Tools_With_Custom_Schema_Create_Options()
{
var jsonString = "{\"value\":42}";
var schemaCreateOptions = new AIJsonSchemaCreateOptions
{
TransformSchemaNode = (context, node) => JsonNode.Parse(jsonString)!
};
ServiceCollection sc = new();
sc.AddMcpServer().WithTools([typeof(ToolTypeWithSchemaCreateOptions)], schemaCreateOptions);
IServiceProvider services = sc.BuildServiceProvider();
McpServerTool tool = services.GetServices<McpServerTool>().First(t => t.ProtocolTool.Name == "static_tool");
Assert.Contains("42", tool.ProtocolTool.InputSchema.GetProperty("properties").GetProperty("input").GetProperty("value").ToString());
}
[Fact]
public void Register_Instance_Tools_With_Custom_Schema_Create_Options()
{
var jsonString = "{\"value\":42}";
var schemaCreateOptions = new AIJsonSchemaCreateOptions
{
TransformSchemaNode = (context, node) => JsonNode.Parse(jsonString)!
};
ServiceCollection sc = new();
sc.AddMcpServer().WithTools([typeof(ToolTypeWithSchemaCreateOptions)], schemaCreateOptions);
IServiceProvider services = sc.BuildServiceProvider();
McpServerTool tool = services.GetServices<McpServerTool>().First(t => t.ProtocolTool.Name == "instance_tool");
Assert.Contains("42", tool.ProtocolTool.InputSchema.GetProperty("properties").GetProperty("input").GetProperty("value").ToString());
}
[Fact]
public void WithToolsFromAssembly_With_Custom_Schema_Create_Options()
{
var jsonString = "{\"value\":42}";
var schemaCreateOptions = new AIJsonSchemaCreateOptions
{
TransformSchemaNode = (context, node) => JsonNode.Parse(jsonString)!
};
ServiceCollection sc = new();
sc.AddMcpServer().WithToolsFromAssembly(schemaCreateOptions);
IServiceProvider services = sc.BuildServiceProvider();
McpServerTool tool = services.GetServices<McpServerTool>().First(t => t.ProtocolTool.Name == "instance_tool");
Assert.Contains("42", tool.ProtocolTool.InputSchema.GetProperty("properties").GetProperty("input").GetProperty("value").ToString());
}
[Fact]
public void Create_ExtractsToolAnnotations_AllSet()
{
var tool = McpServerTool.Create(EchoTool.ReturnInteger);
Assert.NotNull(tool);
Assert.NotNull(tool.ProtocolTool);
var annotations = tool.ProtocolTool.Annotations;
Assert.NotNull(annotations);
Assert.Equal("Return An Integer", annotations.Title);
Assert.Equal("Return An Integer", tool.ProtocolTool.Title);
Assert.False(annotations.DestructiveHint);
Assert.True(annotations.IdempotentHint);
Assert.False(annotations.OpenWorldHint);
Assert.True(annotations.ReadOnlyHint);
}
[Fact]
public void Create_ExtractsToolAnnotations_SomeSet()
{
var tool = McpServerTool.Create(EchoTool.ReturnJson);
Assert.NotNull(tool);
Assert.NotNull(tool.ProtocolTool);
var annotations = tool.ProtocolTool.Annotations;
Assert.NotNull(annotations);
Assert.Null(annotations.Title);
Assert.Null(annotations.DestructiveHint);
Assert.False(annotations.IdempotentHint);
Assert.Null(annotations.OpenWorldHint);
Assert.Null(annotations.ReadOnlyHint);
}
[Fact]
public async Task AttributeProperties_Propagated()
{
await using McpClient client = await CreateMcpClientForServer();
var tools = await client.ListToolsAsync(cancellationToken: TestContext.Current.CancellationToken);
Assert.NotNull(tools);
Assert.NotEmpty(tools);
McpClientTool tool = tools.First(t => t.Name == "echo_complex");
Assert.Equal("This is a title", tool.Title);
Assert.Equal("This is a title", tool.ProtocolTool.Title);
Assert.Equal("This is a title", tool.ProtocolTool.Annotations?.Title);
Assert.NotNull(tool.ProtocolTool.Icons);
Assert.NotEmpty(tool.ProtocolTool.Icons);
var icon = Assert.Single(tool.ProtocolTool.Icons);
Assert.Equal("https://example.com/tool-icon.svg", icon.Source);
Assert.Null(icon.Theme);
}
[Fact]
public async Task HandlesIProgressParameter()
{
await using McpClient client = await CreateMcpClientForServer();
var tools = await client.ListToolsAsync(cancellationToken: TestContext.Current.CancellationToken);
Assert.NotNull(tools);
Assert.NotEmpty(tools);
McpClientTool progressTool = tools.First(t => t.Name == "sends_progress_notifications");
TaskCompletionSource<bool> tcs = new(TaskCreationOptions.RunContinuationsAsynchronously);
int remainingNotifications = 10;
ConcurrentQueue<ProgressNotificationParams> notifications = new();
await using (client.RegisterNotificationHandler(NotificationMethods.ProgressNotification, (notification, cancellationToken) =>
{
if (JsonSerializer.Deserialize<ProgressNotificationParams>(notification.Params, McpJsonUtilities.DefaultOptions) is { } pn &&
pn.ProgressToken == new ProgressToken("abc123"))
{
notifications.Enqueue(pn);
if (Interlocked.Decrement(ref remainingNotifications) == 0)
{
tcs.SetResult(true);
}
}
return default;
}))
{
var result = await client.CallToolAsync(
new CallToolRequestParams
{
Name = progressTool.ProtocolTool.Name,
// Set the progress token in Meta
Meta = new JsonObject
{
["progressToken"] = "abc123",
}
},
cancellationToken: TestContext.Current.CancellationToken);
await tcs.Task;
Assert.Contains("done", JsonSerializer.Serialize(result, McpJsonUtilities.DefaultOptions));
}
ProgressNotificationParams[] array = notifications.OrderBy(n => n.Progress.Progress).ToArray();
Assert.Equal(10, array.Length);
for (int i = 0; i < array.Length; i++)
{
Assert.Equal("abc123", array[i].ProgressToken.ToString());
Assert.Equal(i, array[i].Progress.Progress);
Assert.Equal(10, array[i].Progress.Total);
Assert.Equal($"Progress {i}", array[i].Progress.Message);
}
}
[Fact]
public async Task CancellationNotificationsPropagateToToolTokens()
{
await using McpClient client = await CreateMcpClientForServer();
var tools = await client.ListToolsAsync(cancellationToken: TestContext.Current.CancellationToken);
Assert.NotNull(tools);
Assert.NotEmpty(tools);
McpClientTool cancelableTool = tools.First(t => t.Name == "infinite_cancelable_operation");
var requestId = new RequestId(Guid.NewGuid().ToString());
var invokeTask = client.SendRequestAsync<CallToolRequestParams, CallToolResult>(
RequestMethods.ToolsCall,
new CallToolRequestParams { Name = cancelableTool.ProtocolTool.Name },
requestId: requestId,
cancellationToken: TestContext.Current.CancellationToken);
await client.SendNotificationAsync(
NotificationMethods.CancelledNotification,
parameters: new CancelledNotificationParams
{
RequestId = requestId,
},
cancellationToken: TestContext.Current.CancellationToken);
await Assert.ThrowsAnyAsync<OperationCanceledException>(async () => await invokeTask);
}
[McpServerToolType]
public sealed class EchoTool(ObjectWithId objectFromDI)
{
private readonly string _randomValue = Guid.NewGuid().ToString("N");
[McpServerTool, Description("Echoes the input back to the client.")]
public static string Echo([Description("the echoes message")] string message)
{
return "hello " + message;
}
[McpServerTool(Name = "double_echo"), Description("Echoes the input back to the client.")]
public static string Echo2(string message)
{
return "hello hello" + message;
}
[McpServerTool]
public static string TestTool(int number, double otherNumber, bool someCheck, DateTime someDate, DateTimeOffset someOtherDate, string[] data, ComplexObject complexObject)
{
return "hello hello";
}
[McpServerTool]
public static string[] EchoArray(string message)
{
return ["hello " + message, "hello2 " + message];
}
[McpServerTool]
public static string? ReturnNull()
{
return null;
}
[McpServerTool(Idempotent = false)]
public static JsonElement ReturnJson()
{
return JsonDocument.Parse("{\"SomeProp\": false}").RootElement;
}
[McpServerTool(Title = "Return An Integer", Destructive = false, Idempotent = true, OpenWorld = false, ReadOnly = true)]
public static int ReturnInteger()
{
return 5;
}
[McpServerTool]
public static string ThrowException()
{
throw new InvalidOperationException("Test error");
}
[McpServerTool]
public static string ThrowOperationCanceledException()
{
throw new OperationCanceledException("Tool was canceled");
}
[McpServerTool]
public static string ThrowMcpProtocolException()
{
throw new McpProtocolException("Tool protocol error", McpErrorCode.InvalidParams);
}
[McpServerTool]
public static CallToolResult ReturnIsError()
{
return new CallToolResult
{
IsError = true,
Content = [new TextContentBlock { Text = "Tool returned an error" }],
};
}
[McpServerTool]
public static int ReturnCancellationToken(CancellationToken cancellationToken)
{
return cancellationToken.GetHashCode();
}
[McpServerTool(Title = "This is a title", IconSource = "https://example.com/tool-icon.svg")]
public static string EchoComplex(ComplexObject complex)
{
return complex.Name!;
}
[McpServerTool]
public static async Task<string> InfiniteCancelableOperation(CancellationToken cancellationToken)
{
try
{
await Task.Delay(Timeout.Infinite, cancellationToken);
}
catch (Exception)
{
return "canceled";
}
return "unreachable";
}
[McpServerTool]
public string GetCtorParameter() => $"{_randomValue}:{objectFromDI.Id}";
[McpServerTool]
public string SendsProgressNotifications(IProgress<ProgressNotificationValue> progress)
{
for (int i = 0; i < 10; i++)
{
progress.Report(new() { Progress = i, Total = 10, Message = $"Progress {i}" });
}
return "done";
}
}
[McpServerToolType]
internal class AnotherToolType
{
[McpServerTool(Name = "DifferentName")]
private static string MethodA(int a) => a.ToString();
[McpServerTool]
internal static string MethodB(string b) => b.ToString();
[McpServerTool]
protected static string MethodC(long c) => c.ToString();
}
internal class ToolTypeWithNoAttribute
{
[McpServerTool]
public static string MethodD(string d) => d.ToString();
}
public class ObjectWithId
{
public string Id { get; set; } = Guid.NewGuid().ToString("N");
}
public class ComplexObject