forked from modelcontextprotocol/csharp-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMcpClientExtensions.cs
1061 lines (971 loc) · 51 KB
/
McpClientExtensions.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
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.Logging;
using ModelContextProtocol.Protocol.Messages;
using ModelContextProtocol.Protocol.Types;
using ModelContextProtocol.Server;
using ModelContextProtocol.Utils;
using ModelContextProtocol.Utils.Json;
using System.Runtime.CompilerServices;
using System.Text.Json;
namespace ModelContextProtocol.Client;
/// <summary>
/// Provides extension methods for interacting with an <see cref="IMcpClient"/>.
/// </summary>
/// <remarks>
/// <para>
/// This class contains extension methods that simplify common operations with an MCP client,
/// such as pinging a server, listing and working with tools, prompts, and resources, and
/// managing subscriptions to resources.
/// </para>
/// </remarks>
public static class McpClientExtensions
{
/// <summary>
/// Sends a ping request to verify server connectivity.
/// </summary>
/// <param name="client">The client instance used to communicate with the MCP server.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param>
/// <returns>A task that completes when the ping is successful.</returns>
/// <remarks>
/// <para>
/// This method is used to check if the MCP server is online and responding to requests.
/// It can be useful for health checking, ensuring the connection is established, or verifying
/// that the client has proper authorization to communicate with the server.
/// </para>
/// <para>
/// The ping operation is lightweight and does not require any parameters. A successful completion
/// of the task indicates that the server is operational and accessible.
/// </para>
/// </remarks>
/// <exception cref="ArgumentNullException"><paramref name="client"/> is <see langword="null"/>.</exception>
/// <exception cref="McpException">Thrown when the server cannot be reached or returns an error response.</exception>
public static Task PingAsync(this IMcpClient client, CancellationToken cancellationToken = default)
{
Throw.IfNull(client);
return client.SendRequestAsync(
RequestMethods.Ping,
parameters: null,
McpJsonUtilities.JsonContext.Default.Object!,
McpJsonUtilities.JsonContext.Default.Object,
cancellationToken: cancellationToken);
}
/// <summary>
/// Retrieves a list of available tools from the server.
/// </summary>
/// <param name="client">The client instance used to communicate with the MCP server.</param>
/// <param name="serializerOptions">The serializer options governing tool parameter serialization. If null, the default options will be used.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param>
/// <returns>A list of all available tools as <see cref="McpClientTool"/> instances.</returns>
/// <remarks>
/// <para>
/// This method fetches all available tools from the MCP server and returns them as a complete list.
/// It automatically handles pagination with cursors if the server responds with only a portion per request.
/// </para>
/// <para>
/// For servers with a large number of tools and that responds with paginated responses, consider using
/// <see cref="EnumerateToolsAsync"/> instead, as it streams tools as they arrive rather than loading them all at once.
/// </para>
/// <para>
/// The serializer options provided are flowed to each <see cref="McpClientTool"/> and will be used
/// when invoking tools in order to serialize any parameters.
/// </para>
/// </remarks>
/// <example>
/// <code>
/// // Get all tools available on the server
/// var tools = await mcpClient.ListToolsAsync();
///
/// // Use tools with an AI client
/// ChatOptions chatOptions = new()
/// {
/// Tools = [.. tools]
/// };
///
/// await foreach (var update in chatClient.GetStreamingResponseAsync(userMessage, chatOptions))
/// {
/// Console.Write(update);
/// }
/// </code>
/// </example>
/// <exception cref="ArgumentNullException"><paramref name="client"/> is <see langword="null"/>.</exception>
public static async Task<IList<McpClientTool>> ListToolsAsync(
this IMcpClient client,
JsonSerializerOptions? serializerOptions = null,
CancellationToken cancellationToken = default)
{
Throw.IfNull(client);
serializerOptions ??= McpJsonUtilities.DefaultOptions;
serializerOptions.MakeReadOnly();
List<McpClientTool>? tools = null;
string? cursor = null;
do
{
var toolResults = await client.SendRequestAsync(
RequestMethods.ToolsList,
new() { Cursor = cursor },
McpJsonUtilities.JsonContext.Default.ListToolsRequestParams,
McpJsonUtilities.JsonContext.Default.ListToolsResult,
cancellationToken: cancellationToken).ConfigureAwait(false);
tools ??= new List<McpClientTool>(toolResults.Tools.Count);
foreach (var tool in toolResults.Tools)
{
tools.Add(new McpClientTool(client, tool, serializerOptions));
}
cursor = toolResults.NextCursor;
}
while (cursor is not null);
return tools;
}
/// <summary>
/// Creates an enumerable for asynchronously enumerating all available tools from the server.
/// </summary>
/// <param name="client">The client instance used to communicate with the MCP server.</param>
/// <param name="serializerOptions">The serializer options governing tool parameter serialization. If null, the default options will be used.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param>
/// <returns>An asynchronous sequence of all available tools as <see cref="McpClientTool"/> instances.</returns>
/// <remarks>
/// <para>
/// This method uses asynchronous enumeration to retrieve tools from the server, which allows processing tools
/// as they arrive rather than waiting for all tools to be retrieved. The method automatically handles pagination
/// with cursors if the server responds with tools split across multiple responses.
/// </para>
/// <para>
/// The serializer options provided are flowed to each <see cref="McpClientTool"/> and will be used
/// when invoking tools in order to serialize any parameters.
/// </para>
/// <para>
/// Every iteration through the returned <see cref="IAsyncEnumerable{McpClientTool}"/>
/// will result in requerying the server and yielding the sequence of available tools.
/// </para>
/// </remarks>
/// <example>
/// <code>
/// // Enumerate all tools available on the server
/// await foreach (var tool in client.EnumerateToolsAsync())
/// {
/// Console.WriteLine($"Tool: {tool.Name}");
/// }
/// </code>
/// </example>
/// <exception cref="ArgumentNullException"><paramref name="client"/> is <see langword="null"/>.</exception>
public static async IAsyncEnumerable<McpClientTool> EnumerateToolsAsync(
this IMcpClient client,
JsonSerializerOptions? serializerOptions = null,
[EnumeratorCancellation] CancellationToken cancellationToken = default)
{
Throw.IfNull(client);
serializerOptions ??= McpJsonUtilities.DefaultOptions;
serializerOptions.MakeReadOnly();
string? cursor = null;
do
{
var toolResults = await client.SendRequestAsync(
RequestMethods.ToolsList,
new() { Cursor = cursor },
McpJsonUtilities.JsonContext.Default.ListToolsRequestParams,
McpJsonUtilities.JsonContext.Default.ListToolsResult,
cancellationToken: cancellationToken).ConfigureAwait(false);
foreach (var tool in toolResults.Tools)
{
yield return new McpClientTool(client, tool, serializerOptions);
}
cursor = toolResults.NextCursor;
}
while (cursor is not null);
}
/// <summary>
/// Retrieves a list of available prompts from the server.
/// </summary>
/// <param name="client">The client instance used to communicate with the MCP server.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param>
/// <returns>A list of all available prompts as <see cref="McpClientPrompt"/> instances.</returns>
/// <remarks>
/// <para>
/// This method fetches all available prompts from the MCP server and returns them as a complete list.
/// It automatically handles pagination with cursors if the server responds with only a portion per request.
/// </para>
/// <para>
/// For servers with a large number of prompts and that responds with paginated responses, consider using
/// <see cref="EnumeratePromptsAsync"/> instead, as it streams prompts as they arrive rather than loading them all at once.
/// </para>
/// </remarks>
/// <exception cref="ArgumentNullException"><paramref name="client"/> is <see langword="null"/>.</exception>
public static async Task<IList<McpClientPrompt>> ListPromptsAsync(
this IMcpClient client, CancellationToken cancellationToken = default)
{
Throw.IfNull(client);
List<McpClientPrompt>? prompts = null;
string? cursor = null;
do
{
var promptResults = await client.SendRequestAsync(
RequestMethods.PromptsList,
new() { Cursor = cursor },
McpJsonUtilities.JsonContext.Default.ListPromptsRequestParams,
McpJsonUtilities.JsonContext.Default.ListPromptsResult,
cancellationToken: cancellationToken).ConfigureAwait(false);
prompts ??= new List<McpClientPrompt>(promptResults.Prompts.Count);
foreach (var prompt in promptResults.Prompts)
{
prompts.Add(new McpClientPrompt(client, prompt));
}
cursor = promptResults.NextCursor;
}
while (cursor is not null);
return prompts;
}
/// <summary>
/// Creates an enumerable for asynchronously enumerating all available prompts from the server.
/// </summary>
/// <param name="client">The client instance used to communicate with the MCP server.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param>
/// <returns>An asynchronous sequence of all available prompts as <see cref="McpClientPrompt"/> instances.</returns>
/// <remarks>
/// <para>
/// This method uses asynchronous enumeration to retrieve prompts from the server, which allows processing prompts
/// as they arrive rather than waiting for all prompts to be retrieved. The method automatically handles pagination
/// with cursors if the server responds with prompts split across multiple responses.
/// </para>
/// <para>
/// Every iteration through the returned <see cref="IAsyncEnumerable{McpClientPrompt}"/>
/// will result in requerying the server and yielding the sequence of available prompts.
/// </para>
/// </remarks>
/// <example>
/// <code>
/// // Enumerate all prompts available on the server
/// await foreach (var prompt in client.EnumeratePromptsAsync())
/// {
/// Console.WriteLine($"Prompt: {prompt.Name}");
/// }
/// </code>
/// </example>
/// <exception cref="ArgumentNullException"><paramref name="client"/> is <see langword="null"/>.</exception>
public static async IAsyncEnumerable<McpClientPrompt> EnumeratePromptsAsync(
this IMcpClient client, [EnumeratorCancellation] CancellationToken cancellationToken = default)
{
Throw.IfNull(client);
string? cursor = null;
do
{
var promptResults = await client.SendRequestAsync(
RequestMethods.PromptsList,
new() { Cursor = cursor },
McpJsonUtilities.JsonContext.Default.ListPromptsRequestParams,
McpJsonUtilities.JsonContext.Default.ListPromptsResult,
cancellationToken: cancellationToken).ConfigureAwait(false);
foreach (var prompt in promptResults.Prompts)
{
yield return new(client, prompt);
}
cursor = promptResults.NextCursor;
}
while (cursor is not null);
}
/// <summary>
/// Retrieves a specific prompt from the MCP server.
/// </summary>
/// <param name="client">The client instance used to communicate with the MCP server.</param>
/// <param name="name">The name of the prompt to retrieve.</param>
/// <param name="arguments">Optional arguments for the prompt. Keys are parameter names, and values are the argument values.</param>
/// <param name="serializerOptions">The serialization options governing argument serialization.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param>
/// <returns>A task containing the prompt's result with content and messages.</returns>
/// <remarks>
/// <para>
/// This method sends a request to the MCP server to create the specified prompt with the provided arguments.
/// The server will process the arguments and return a prompt containing messages or other content.
/// </para>
/// <para>
/// Arguments are serialized into JSON and passed to the server, where they may be used to customize the
/// prompt's behavior or content. Each prompt may have different argument requirements.
/// </para>
/// <para>
/// The returned <see cref="GetPromptResult"/> contains a collection of <see cref="PromptMessage"/> objects,
/// which can be converted to <see cref="ChatMessage"/> objects using the <see cref="AIContentExtensions.ToChatMessages"/> method.
/// </para>
/// </remarks>
/// <exception cref="McpException">Thrown when the prompt does not exist, when required arguments are missing, or when the server encounters an error processing the prompt.</exception>
/// <exception cref="ArgumentNullException"><paramref name="client"/> is <see langword="null"/>.</exception>
public static Task<GetPromptResult> GetPromptAsync(
this IMcpClient client,
string name,
IReadOnlyDictionary<string, object?>? arguments = null,
JsonSerializerOptions? serializerOptions = null,
CancellationToken cancellationToken = default)
{
Throw.IfNull(client);
Throw.IfNullOrWhiteSpace(name);
serializerOptions ??= McpJsonUtilities.DefaultOptions;
serializerOptions.MakeReadOnly();
return client.SendRequestAsync(
RequestMethods.PromptsGet,
new() { Name = name, Arguments = ToArgumentsDictionary(arguments, serializerOptions) },
McpJsonUtilities.JsonContext.Default.GetPromptRequestParams,
McpJsonUtilities.JsonContext.Default.GetPromptResult,
cancellationToken: cancellationToken);
}
/// <summary>
/// Retrieves a list of available resource templates from the server.
/// </summary>
/// <param name="client">The client instance used to communicate with the MCP server.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param>
/// <returns>A list of all available resource templates as <see cref="ResourceTemplate"/> instances.</returns>
/// <remarks>
/// <para>
/// This method fetches all available resource templates from the MCP server and returns them as a complete list.
/// It automatically handles pagination with cursors if the server responds with only a portion per request.
/// </para>
/// <para>
/// For servers with a large number of resource templates and that responds with paginated responses, consider using
/// <see cref="EnumerateResourceTemplatesAsync"/> instead, as it streams templates as they arrive rather than loading them all at once.
/// </para>
/// </remarks>
/// <exception cref="ArgumentNullException"><paramref name="client"/> is <see langword="null"/>.</exception>
public static async Task<IList<ResourceTemplate>> ListResourceTemplatesAsync(
this IMcpClient client, CancellationToken cancellationToken = default)
{
Throw.IfNull(client);
List<ResourceTemplate>? templates = null;
string? cursor = null;
do
{
var templateResults = await client.SendRequestAsync(
RequestMethods.ResourcesTemplatesList,
new() { Cursor = cursor },
McpJsonUtilities.JsonContext.Default.ListResourceTemplatesRequestParams,
McpJsonUtilities.JsonContext.Default.ListResourceTemplatesResult,
cancellationToken: cancellationToken).ConfigureAwait(false);
if (templates is null)
{
templates = templateResults.ResourceTemplates;
}
else
{
templates.AddRange(templateResults.ResourceTemplates);
}
cursor = templateResults.NextCursor;
}
while (cursor is not null);
return templates;
}
/// <summary>
/// Creates an enumerable for asynchronously enumerating all available resource templates from the server.
/// </summary>
/// <param name="client">The client instance used to communicate with the MCP server.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param>
/// <returns>An asynchronous sequence of all available resource templates as <see cref="ResourceTemplate"/> instances.</returns>
/// <remarks>
/// <para>
/// This method uses asynchronous enumeration to retrieve resource templates from the server, which allows processing templates
/// as they arrive rather than waiting for all templates to be retrieved. The method automatically handles pagination
/// with cursors if the server responds with templates split across multiple responses.
/// </para>
/// <para>
/// Every iteration through the returned <see cref="IAsyncEnumerable{ResourceTemplate}"/>
/// will result in requerying the server and yielding the sequence of available resource templates.
/// </para>
/// </remarks>
/// <example>
/// <code>
/// // Enumerate all resource templates available on the server
/// await foreach (var template in client.EnumerateResourceTemplatesAsync())
/// {
/// Console.WriteLine($"Template: {template.Name}");
/// }
/// </code>
/// </example>
/// <exception cref="ArgumentNullException"><paramref name="client"/> is <see langword="null"/>.</exception>
public static async IAsyncEnumerable<ResourceTemplate> EnumerateResourceTemplatesAsync(
this IMcpClient client, [EnumeratorCancellation] CancellationToken cancellationToken = default)
{
Throw.IfNull(client);
string? cursor = null;
do
{
var templateResults = await client.SendRequestAsync(
RequestMethods.ResourcesTemplatesList,
new() { Cursor = cursor },
McpJsonUtilities.JsonContext.Default.ListResourceTemplatesRequestParams,
McpJsonUtilities.JsonContext.Default.ListResourceTemplatesResult,
cancellationToken: cancellationToken).ConfigureAwait(false);
foreach (var template in templateResults.ResourceTemplates)
{
yield return template;
}
cursor = templateResults.NextCursor;
}
while (cursor is not null);
}
/// <summary>
/// Retrieves a list of available resources from the server.
/// </summary>
/// <param name="client">The client instance used to communicate with the MCP server.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param>
/// <returns>A list of all available resources as <see cref="Resource"/> instances.</returns>
/// <remarks>
/// <para>
/// This method fetches all available resources from the MCP server and returns them as a complete list.
/// It automatically handles pagination with cursors if the server responds with only a portion per request.
/// </para>
/// <para>
/// For servers with a large number of resources and that responds with paginated responses, consider using
/// <see cref="EnumerateResourcesAsync"/> instead, as it streams resources as they arrive rather than loading them all at once.
/// </para>
/// </remarks>
/// <example>
/// <code>
/// // Get all resources available on the server
/// var resources = await client.ListResourcesAsync();
///
/// // Display information about each resource
/// foreach (var resource in resources)
/// {
/// Console.WriteLine($"Resource URI: {resource.Uri}");
/// }
/// </code>
/// </example>
/// <exception cref="ArgumentNullException"><paramref name="client"/> is <see langword="null"/>.</exception>
public static async Task<IList<Resource>> ListResourcesAsync(
this IMcpClient client, CancellationToken cancellationToken = default)
{
Throw.IfNull(client);
List<Resource>? resources = null;
string? cursor = null;
do
{
var resourceResults = await client.SendRequestAsync(
RequestMethods.ResourcesList,
new() { Cursor = cursor },
McpJsonUtilities.JsonContext.Default.ListResourcesRequestParams,
McpJsonUtilities.JsonContext.Default.ListResourcesResult,
cancellationToken: cancellationToken).ConfigureAwait(false);
if (resources is null)
{
resources = resourceResults.Resources;
}
else
{
resources.AddRange(resourceResults.Resources);
}
cursor = resourceResults.NextCursor;
}
while (cursor is not null);
return resources;
}
/// <summary>
/// Creates an enumerable for asynchronously enumerating all available resources from the server.
/// </summary>
/// <param name="client">The client instance used to communicate with the MCP server.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param>
/// <returns>An asynchronous sequence of all available resources as <see cref="Resource"/> instances.</returns>
/// <remarks>
/// <para>
/// This method uses asynchronous enumeration to retrieve resources from the server, which allows processing resources
/// as they arrive rather than waiting for all resources to be retrieved. The method automatically handles pagination
/// with cursors if the server responds with resources split across multiple responses.
/// </para>
/// <para>
/// Every iteration through the returned <see cref="IAsyncEnumerable{Resource}"/>
/// will result in requerying the server and yielding the sequence of available resources.
/// </para>
/// </remarks>
/// <example>
/// <code>
/// // Enumerate all resources available on the server
/// await foreach (var resource in client.EnumerateResourcesAsync())
/// {
/// Console.WriteLine($"Resource URI: {resource.Uri}");
/// }
/// </code>
/// </example>
/// <exception cref="ArgumentNullException"><paramref name="client"/> is <see langword="null"/>.</exception>
public static async IAsyncEnumerable<Resource> EnumerateResourcesAsync(
this IMcpClient client, [EnumeratorCancellation] CancellationToken cancellationToken = default)
{
Throw.IfNull(client);
string? cursor = null;
do
{
var resourceResults = await client.SendRequestAsync(
RequestMethods.ResourcesList,
new() { Cursor = cursor },
McpJsonUtilities.JsonContext.Default.ListResourcesRequestParams,
McpJsonUtilities.JsonContext.Default.ListResourcesResult,
cancellationToken: cancellationToken).ConfigureAwait(false);
foreach (var resource in resourceResults.Resources)
{
yield return resource;
}
cursor = resourceResults.NextCursor;
}
while (cursor is not null);
}
/// <summary>
/// Reads a resource from the server.
/// </summary>
/// <param name="client">The client instance used to communicate with the MCP server.</param>
/// <param name="uri">The uri of the resource.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param>
/// <exception cref="ArgumentNullException"><paramref name="client"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentNullException"><paramref name="uri"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentException"><paramref name="uri"/> is empty or composed entirely of whitespace.</exception>
public static Task<ReadResourceResult> ReadResourceAsync(
this IMcpClient client, string uri, CancellationToken cancellationToken = default)
{
Throw.IfNull(client);
Throw.IfNullOrWhiteSpace(uri);
return client.SendRequestAsync(
RequestMethods.ResourcesRead,
new() { Uri = uri },
McpJsonUtilities.JsonContext.Default.ReadResourceRequestParams,
McpJsonUtilities.JsonContext.Default.ReadResourceResult,
cancellationToken: cancellationToken);
}
/// <summary>
/// Reads a resource from the server.
/// </summary>
/// <param name="client">The client instance used to communicate with the MCP server.</param>
/// <param name="uri">The uri of the resource.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param>
/// <exception cref="ArgumentNullException"><paramref name="client"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentNullException"><paramref name="uri"/> is <see langword="null"/>.</exception>
public static Task<ReadResourceResult> ReadResourceAsync(
this IMcpClient client, Uri uri, CancellationToken cancellationToken = default)
{
Throw.IfNull(client);
Throw.IfNull(uri);
return ReadResourceAsync(client, uri.ToString(), cancellationToken);
}
/// <summary>
/// Requests completion suggestions for a prompt argument or resource reference.
/// </summary>
/// <param name="client">The client instance used to communicate with the MCP server.</param>
/// <param name="reference">The reference object specifying the type and optional URI or name.</param>
/// <param name="argumentName">The name of the argument for which completions are requested.</param>
/// <param name="argumentValue">The current value of the argument, used to filter relevant completions.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param>
/// <returns>A <see cref="CompleteResult"/> containing completion suggestions.</returns>
/// <remarks>
/// <para>
/// This method allows clients to request auto-completion suggestions for arguments in a prompt template
/// or for resource references.
/// </para>
/// <para>
/// When working with prompt references, the server will return suggestions for the specified argument
/// that match or begin with the current argument value. This is useful for implementing intelligent
/// auto-completion in user interfaces.
/// </para>
/// <para>
/// When working with resource references, the server will return suggestions relevant to the specified
/// resource URI.
/// </para>
/// </remarks>
/// <exception cref="ArgumentNullException"><paramref name="client"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentNullException"><paramref name="reference"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentNullException"><paramref name="argumentName"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentException"><paramref name="argumentName"/> is empty or composed entirely of whitespace.</exception>
/// <exception cref="McpException">The server returned an error response.</exception>
public static Task<CompleteResult> CompleteAsync(this IMcpClient client, Reference reference, string argumentName, string argumentValue, CancellationToken cancellationToken = default)
{
Throw.IfNull(client);
Throw.IfNull(reference);
Throw.IfNullOrWhiteSpace(argumentName);
if (!reference.Validate(out string? validationMessage))
{
throw new ArgumentException($"Invalid reference: {validationMessage}", nameof(reference));
}
return client.SendRequestAsync(
RequestMethods.CompletionComplete,
new()
{
Ref = reference,
Argument = new Argument { Name = argumentName, Value = argumentValue }
},
McpJsonUtilities.JsonContext.Default.CompleteRequestParams,
McpJsonUtilities.JsonContext.Default.CompleteResult,
cancellationToken: cancellationToken);
}
/// <summary>
/// Subscribes to a resource on the server to receive notifications when it changes.
/// </summary>
/// <param name="client">The client instance used to communicate with the MCP server.</param>
/// <param name="uri">The URI of the resource to which to subscribe.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
/// <remarks>
/// <para>
/// This method allows the client to register interest in a specific resource identified by its URI.
/// When the resource changes, the server will send notifications to the client, enabling real-time
/// updates without polling.
/// </para>
/// <para>
/// The subscription remains active until explicitly unsubscribed using <see cref="M:UnsubscribeFromResourceAsync"/>
/// or until the client disconnects from the server.
/// </para>
/// <para>
/// To handle resource change notifications, register an event handler for the appropriate notification events,
/// such as with <see cref="IMcpEndpoint.RegisterNotificationHandler"/>.
/// </para>
/// </remarks>
/// <exception cref="ArgumentNullException"><paramref name="client"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentNullException"><paramref name="uri"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentException"><paramref name="uri"/> is empty or composed entirely of whitespace.</exception>
public static Task SubscribeToResourceAsync(this IMcpClient client, string uri, CancellationToken cancellationToken = default)
{
Throw.IfNull(client);
Throw.IfNullOrWhiteSpace(uri);
return client.SendRequestAsync(
RequestMethods.ResourcesSubscribe,
new() { Uri = uri },
McpJsonUtilities.JsonContext.Default.SubscribeRequestParams,
McpJsonUtilities.JsonContext.Default.EmptyResult,
cancellationToken: cancellationToken);
}
/// <summary>
/// Subscribes to a resource on the server to receive notifications when it changes.
/// </summary>
/// <param name="client">The client instance used to communicate with the MCP server.</param>
/// <param name="uri">The URI of the resource to which to subscribe.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
/// <remarks>
/// <para>
/// This method allows the client to register interest in a specific resource identified by its URI.
/// When the resource changes, the server will send notifications to the client, enabling real-time
/// updates without polling.
/// </para>
/// <para>
/// The subscription remains active until explicitly unsubscribed using <see cref="M:UnsubscribeFromResourceAsync"/>
/// or until the client disconnects from the server.
/// </para>
/// <para>
/// To handle resource change notifications, register an event handler for the appropriate notification events,
/// such as with <see cref="IMcpEndpoint.RegisterNotificationHandler"/>.
/// </para>
/// </remarks>
/// <exception cref="ArgumentNullException"><paramref name="client"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentNullException"><paramref name="uri"/> is <see langword="null"/>.</exception>
public static Task SubscribeToResourceAsync(this IMcpClient client, Uri uri, CancellationToken cancellationToken = default)
{
Throw.IfNull(client);
Throw.IfNull(uri);
return SubscribeToResourceAsync(client, uri.ToString(), cancellationToken);
}
/// <summary>
/// Unsubscribes from a resource on the server to stop receiving notifications about its changes.
/// </summary>
/// <param name="client">The client instance used to communicate with the MCP server.</param>
/// <param name="uri">The URI of the resource to unsubscribe from.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
/// <remarks>
/// <para>
/// This method cancels a previous subscription to a resource, stopping the client from receiving
/// notifications when that resource changes.
/// </para>
/// <para>
/// The unsubscribe operation is idempotent, meaning it can be called multiple times for the same
/// resource without causing errors, even if there is no active subscription.
/// </para>
/// <para>
/// Due to the nature of the MCP protocol, it is possible the client may receive notifications after
/// unsubscribing if those notifications were issued by the server prior to the unsubscribe request being received.
/// </para>
/// </remarks>
/// <exception cref="ArgumentNullException"><paramref name="client"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentNullException"><paramref name="uri"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentException"><paramref name="uri"/> is empty or composed entirely of whitespace.</exception>
public static Task UnsubscribeFromResourceAsync(this IMcpClient client, string uri, CancellationToken cancellationToken = default)
{
Throw.IfNull(client);
Throw.IfNullOrWhiteSpace(uri);
return client.SendRequestAsync(
RequestMethods.ResourcesUnsubscribe,
new() { Uri = uri },
McpJsonUtilities.JsonContext.Default.UnsubscribeRequestParams,
McpJsonUtilities.JsonContext.Default.EmptyResult,
cancellationToken: cancellationToken);
}
/// <summary>
/// Unsubscribes from a resource on the server to stop receiving notifications about its changes.
/// </summary>
/// <param name="client">The client instance used to communicate with the MCP server.</param>
/// <param name="uri">The URI of the resource to unsubscribe from.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
/// <remarks>
/// <para>
/// This method cancels a previous subscription to a resource, stopping the client from receiving
/// notifications when that resource changes.
/// </para>
/// <para>
/// The unsubscribe operation is idempotent, meaning it can be called multiple times for the same
/// resource without causing errors, even if there is no active subscription.
/// </para>
/// <para>
/// Due to the nature of the MCP protocol, it is possible the client may receive notifications after
/// unsubscribing if those notifications were issued by the server prior to the unsubscribe request being received.
/// </para>
/// </remarks>
/// <exception cref="ArgumentNullException"><paramref name="client"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentNullException"><paramref name="uri"/> is <see langword="null"/>.</exception>
public static Task UnsubscribeFromResourceAsync(this IMcpClient client, Uri uri, CancellationToken cancellationToken = default)
{
Throw.IfNull(client);
Throw.IfNull(uri);
return UnsubscribeFromResourceAsync(client, uri.ToString(), cancellationToken);
}
/// <summary>
/// Invokes a tool on the server
/// </summary>
/// <param name="client">The client instance used to communicate with the MCP server.</param>
/// <param name="toolName">The name of the tool to call on the server..</param>
/// <param name="arguments">Optional dictionary of arguments to pass to the tool. Each key represents a parameter name,
/// and its associated value represents the argument value.
/// </param>
/// <param name="serializerOptions">
/// The JSON serialization options governing argument serialization. If <see langword="null"/>, the default serialization options will be used.
/// </param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param>
/// <returns>
/// A task containing the <see cref="CallToolResponse"/> from the tool execution. The response includes
/// the tool's output content, which may be structured data, text, or an error message.
/// </returns>
/// <exception cref="ArgumentNullException"><paramref name="client"/> is <see langword="null"/>.</exception>
/// <exception cref="ArgumentNullException"><paramref name="toolName"/> is <see langword="null"/>.</exception>
/// <exception cref="McpException">The server could not find the requested tool, or the server encountered an error while processing the request.</exception>
/// <example>
/// <code>
/// // Call a simple echo tool with a string argument
/// var result = await client.CallToolAsync(
/// "echo",
/// new Dictionary<string, object?>
/// {
/// ["message"] = "Hello MCP!"
/// });
/// </code>
/// </example>
public static Task<CallToolResponse> CallToolAsync(
this IMcpClient client,
string toolName,
IReadOnlyDictionary<string, object?>? arguments = null,
JsonSerializerOptions? serializerOptions = null,
CancellationToken cancellationToken = default)
{
Throw.IfNull(client);
Throw.IfNull(toolName);
serializerOptions ??= McpJsonUtilities.DefaultOptions;
serializerOptions.MakeReadOnly();
return client.SendRequestAsync(
RequestMethods.ToolsCall,
new() { Name = toolName, Arguments = ToArgumentsDictionary(arguments, serializerOptions) },
McpJsonUtilities.JsonContext.Default.CallToolRequestParams,
McpJsonUtilities.JsonContext.Default.CallToolResponse,
cancellationToken: cancellationToken);
}
/// <summary>
/// Converts the contents of a <see cref="CreateMessageRequestParams"/> into a pair of
/// <see cref="IEnumerable{ChatMessage}"/> and <see cref="ChatOptions"/> instances to use
/// as inputs into a <see cref="IChatClient"/> operation.
/// </summary>
/// <param name="requestParams"></param>
/// <returns>The created pair of messages and options.</returns>
/// <exception cref="ArgumentNullException"><paramref name="requestParams"/> is <see langword="null"/>.</exception>
internal static (IList<ChatMessage> Messages, ChatOptions? Options) ToChatClientArguments(
this CreateMessageRequestParams requestParams)
{
Throw.IfNull(requestParams);
ChatOptions? options = null;
if (requestParams.MaxTokens is int maxTokens)
{
(options ??= new()).MaxOutputTokens = maxTokens;
}
if (requestParams.Temperature is float temperature)
{
(options ??= new()).Temperature = temperature;
}
if (requestParams.StopSequences is { } stopSequences)
{
(options ??= new()).StopSequences = stopSequences.ToArray();
}
List<ChatMessage> messages = [];
foreach (SamplingMessage sm in requestParams.Messages)
{
ChatMessage message = new()
{
Role = sm.Role == Role.User ? ChatRole.User : ChatRole.Assistant,
};
if (sm.Content is { Type: "text" })
{
message.Contents.Add(new TextContent(sm.Content.Text));
}
else if (sm.Content is { Type: "image" or "audio", MimeType: not null, Data: not null })
{
message.Contents.Add(new DataContent(Convert.FromBase64String(sm.Content.Data), sm.Content.MimeType));
}
else if (sm.Content is { Type: "resource", Resource: not null })
{
message.Contents.Add(sm.Content.Resource.ToAIContent());
}
messages.Add(message);
}
return (messages, options);
}
/// <summary>Converts the contents of a <see cref="ChatResponse"/> into a <see cref="CreateMessageResult"/>.</summary>
/// <param name="chatResponse">The <see cref="ChatResponse"/> whose contents should be extracted.</param>
/// <returns>The created <see cref="CreateMessageResult"/>.</returns>
/// <exception cref="ArgumentNullException"><paramref name="chatResponse"/> is <see langword="null"/>.</exception>
internal static CreateMessageResult ToCreateMessageResult(this ChatResponse chatResponse)
{
Throw.IfNull(chatResponse);
// The ChatResponse can include multiple messages, of varying modalities, but CreateMessageResult supports
// only either a single blob of text or a single image. Heuristically, we'll use an image if there is one
// in any of the response messages, or we'll use all the text from them concatenated, otherwise.
ChatMessage? lastMessage = chatResponse.Messages.LastOrDefault();
Content? content = null;
if (lastMessage is not null)
{
foreach (var lmc in lastMessage.Contents)
{
if (lmc is DataContent dc && (dc.HasTopLevelMediaType("image") || dc.HasTopLevelMediaType("audio")))
{
content = new()
{
Type = dc.HasTopLevelMediaType("image") ? "image" : "audio",
MimeType = dc.MediaType,
Data = dc.GetBase64Data(),
};
}
}
}
content ??= new()
{
Text = lastMessage?.Text ?? string.Empty,
Type = "text",
};
return new()
{
Content = content,
Model = chatResponse.ModelId ?? "unknown",
Role = lastMessage?.Role == ChatRole.User ? Role.User : Role.Assistant,
StopReason = chatResponse.FinishReason == ChatFinishReason.Length ? "maxTokens" : "endTurn",
};
}
/// <summary>
/// Creates a sampling handler for use with <see cref="SamplingCapability.SamplingHandler"/> that will
/// satisfy sampling requests using the specified <see cref="IChatClient"/>.
/// </summary>
/// <param name="chatClient">The <see cref="IChatClient"/> with which to satisfy sampling requests.</param>
/// <returns>The created handler delegate that can be assigned to <see cref="SamplingCapability.SamplingHandler"/>.</returns>
/// <remarks>
/// <para>
/// This method creates a function that converts MCP message requests into chat client calls, enabling
/// an MCP client to generate text or other content using an actual AI model via the provided chat client.
/// </para>
/// <para>
/// The handler can process text messages, image messages, and resource messages as defined in the
/// Model Context Protocol.
/// </para>
/// </remarks>
/// <exception cref="ArgumentNullException"><paramref name="chatClient"/> is <see langword="null"/>.</exception>
public static Func<CreateMessageRequestParams?, IProgress<ProgressNotificationValue>, CancellationToken, Task<CreateMessageResult>> CreateSamplingHandler(
this IChatClient chatClient)
{
Throw.IfNull(chatClient);
return async (requestParams, progress, cancellationToken) =>
{
Throw.IfNull(requestParams);
var (messages, options) = requestParams.ToChatClientArguments();
var progressToken = requestParams.Meta?.ProgressToken;
List<ChatResponseUpdate> updates = [];
await foreach (var update in chatClient.GetStreamingResponseAsync(messages, options, cancellationToken).ConfigureAwait(false))
{
updates.Add(update);
if (progressToken is not null)
{
progress.Report(new()
{
Progress = updates.Count,
});
}
}
return updates.ToChatResponse().ToCreateMessageResult();
};
}
/// <summary>
/// Sets the logging level for the server to control which log messages are sent to the client.
/// </summary>
/// <param name="client">The client instance used to communicate with the MCP server.</param>
/// <param name="level">The minimum severity level of log messages to receive from the server.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param>
/// <returns>A task representing the asynchronous operation.</returns>
/// <remarks>
/// <para>
/// After this request is processed, the server will send log messages at or above the specified
/// logging level as notifications to the client. For example, if <see cref="LoggingLevel.Warning"/> is set,
/// the client will receive <see cref="LoggingLevel.Warning"/>, <see cref="LoggingLevel.Error"/>,
/// <see cref="LoggingLevel.Critical"/>, <see cref="LoggingLevel.Alert"/>, and <see cref="LoggingLevel.Emergency"/>
/// level messages.
/// </para>
/// <para>
/// To receive all log messages, set the level to <see cref="LoggingLevel.Debug"/>.
/// </para>
/// <para>
/// Log messages are delivered as notifications to the client and can be captured by registering