-
Notifications
You must be signed in to change notification settings - Fork 192
/
Copy pathMcpClientExtensionsTests.cs
506 lines (445 loc) · 19.8 KB
/
McpClientExtensionsTests.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
using Microsoft.Extensions.AI;
using Microsoft.Extensions.DependencyInjection;
using ModelContextProtocol.Client;
using ModelContextProtocol.Protocol.Messages;
using ModelContextProtocol.Protocol.Transport;
using ModelContextProtocol.Protocol.Types;
using ModelContextProtocol.Server;
using ModelContextProtocol.Tests.Utils;
using Moq;
using System.Buffers;
using System.IO.Pipelines;
using System.Text.Json;
using System.Text.Json.Serialization.Metadata;
namespace ModelContextProtocol.Tests.Client;
public class McpClientExtensionsTests : LoggedTest
{
private readonly Pipe _clientToServerPipe = new();
private readonly Pipe _serverToClientPipe = new();
private readonly ServiceProvider _serviceProvider;
private readonly CancellationTokenSource _cts;
private readonly Task _serverTask;
public McpClientExtensionsTests(ITestOutputHelper outputHelper)
: base(outputHelper)
{
ServiceCollection sc = new();
sc.AddSingleton(LoggerFactory);
sc.AddMcpServer().WithStreamServerTransport(_clientToServerPipe.Reader.AsStream(), _serverToClientPipe.Writer.AsStream());
for (int f = 0; f < 10; f++)
{
string name = $"Method{f}";
sc.AddSingleton(McpServerTool.Create((int i) => $"{name} Result {i}", new() { Name = name }));
}
sc.AddSingleton(McpServerTool.Create([McpServerTool(Destructive = false, OpenWorld = true)](string i) => $"{i} Result", new() { Name = "ValuesSetViaAttr" }));
sc.AddSingleton(McpServerTool.Create([McpServerTool(Destructive = false, OpenWorld = true)](string i) => $"{i} Result", new() { Name = "ValuesSetViaOptions", Destructive = true, OpenWorld = false, ReadOnly = true }));
_serviceProvider = sc.BuildServiceProvider();
var server = _serviceProvider.GetRequiredService<IMcpServer>();
_cts = CancellationTokenSource.CreateLinkedTokenSource(TestContext.Current.CancellationToken);
_serverTask = server.RunAsync(cancellationToken: _cts.Token);
}
[Theory]
[InlineData(null, null)]
[InlineData(0.7f, 50)]
[InlineData(1.0f, 100)]
public async Task CreateSamplingHandler_ShouldHandleTextMessages(float? temperature, int? maxTokens)
{
// Arrange
var mockChatClient = new Mock<IChatClient>();
var requestParams = new CreateMessageRequestParams
{
Messages =
[
new SamplingMessage
{
Role = Role.User,
Content = new Content { Type = "text", Text = "Hello" }
}
],
Temperature = temperature,
MaxTokens = maxTokens,
Meta = new RequestParamsMetadata
{
ProgressToken = new ProgressToken(),
}
};
var cancellationToken = CancellationToken.None;
var expectedResponse = new[] {
new ChatResponseUpdate
{
ModelId = "test-model",
FinishReason = ChatFinishReason.Stop,
Role = ChatRole.Assistant,
Contents =
[
new TextContent("Hello, World!") { RawRepresentation = "Hello, World!" }
]
}
}.ToAsyncEnumerable();
mockChatClient
.Setup(client => client.GetStreamingResponseAsync(It.IsAny<IEnumerable<ChatMessage>>(), It.IsAny<ChatOptions>(), cancellationToken))
.Returns(expectedResponse);
var handler = McpClientExtensions.CreateSamplingHandler(mockChatClient.Object);
// Act
var result = await handler(requestParams, Mock.Of<IProgress<ProgressNotificationValue>>(), cancellationToken);
// Assert
Assert.NotNull(result);
Assert.Equal("Hello, World!", result.Content.Text);
Assert.Equal("test-model", result.Model);
Assert.Equal("assistant", result.Role);
Assert.Equal("endTurn", result.StopReason);
}
[Fact]
public async Task CreateSamplingHandler_ShouldHandleImageMessages()
{
// Arrange
var mockChatClient = new Mock<IChatClient>();
var requestParams = new CreateMessageRequestParams
{
Messages =
[
new SamplingMessage
{
Role = Role.User,
Content = new Content
{
Type = "image",
MimeType = "image/png",
Data = Convert.ToBase64String(new byte[] { 1, 2, 3 })
}
}
],
MaxTokens = 100
};
const string expectedData = "SGVsbG8sIFdvcmxkIQ==";
var cancellationToken = CancellationToken.None;
var expectedResponse = new[] {
new ChatResponseUpdate
{
ModelId = "test-model",
FinishReason = ChatFinishReason.Stop,
Role = ChatRole.Assistant,
Contents =
[
new DataContent($"data:image/png;base64,{expectedData}") { RawRepresentation = "Hello, World!" }
]
}
}.ToAsyncEnumerable();
mockChatClient
.Setup(client => client.GetStreamingResponseAsync(It.IsAny<IEnumerable<ChatMessage>>(), It.IsAny<ChatOptions>(), cancellationToken))
.Returns(expectedResponse);
var handler = McpClientExtensions.CreateSamplingHandler(mockChatClient.Object);
// Act
var result = await handler(requestParams, Mock.Of<IProgress<ProgressNotificationValue>>(), cancellationToken);
// Assert
Assert.NotNull(result);
Assert.Equal(expectedData, result.Content.Data);
Assert.Equal("test-model", result.Model);
Assert.Equal("assistant", result.Role);
Assert.Equal("endTurn", result.StopReason);
}
[Fact]
public async Task CreateSamplingHandler_ShouldHandleResourceMessages()
{
// Arrange
const string data = "SGVsbG8sIFdvcmxkIQ==";
string content = $"data:application/octet-stream;base64,{data}";
var mockChatClient = new Mock<IChatClient>();
var resource = new BlobResourceContents
{
Blob = data,
MimeType = "application/octet-stream",
Uri = "data:application/octet-stream"
};
var requestParams = new CreateMessageRequestParams
{
Messages =
[
new SamplingMessage
{
Role = Role.User,
Content = new Content
{
Type = "resource",
Resource = resource
},
}
],
MaxTokens = 100
};
var cancellationToken = CancellationToken.None;
var expectedResponse = new[] {
new ChatResponseUpdate
{
ModelId = "test-model",
FinishReason = ChatFinishReason.Stop,
AuthorName = "bot",
Role = ChatRole.Assistant,
Contents =
[
resource.ToAIContent()
]
}
}.ToAsyncEnumerable();
mockChatClient
.Setup(client => client.GetStreamingResponseAsync(It.IsAny<IEnumerable<ChatMessage>>(), It.IsAny<ChatOptions>(), cancellationToken))
.Returns(expectedResponse);
var handler = McpClientExtensions.CreateSamplingHandler(mockChatClient.Object);
// Act
var result = await handler(requestParams, Mock.Of<IProgress<ProgressNotificationValue>>(), cancellationToken);
// Assert
Assert.NotNull(result);
Assert.Equal("test-model", result.Model);
Assert.Equal(ChatRole.Assistant.ToString(), result.Role);
Assert.Equal("endTurn", result.StopReason);
}
public async ValueTask DisposeAsync()
{
await _cts.CancelAsync();
_clientToServerPipe.Writer.Complete();
_serverToClientPipe.Writer.Complete();
await _serverTask;
await _serviceProvider.DisposeAsync();
_cts.Dispose();
}
private async Task<IMcpClient> CreateMcpClientForServer(
McpClientOptions? options = null,
CancellationToken? cancellationToken = default)
{
return await McpClientFactory.CreateAsync(
new()
{
Id = "TestServer",
Name = "TestServer",
TransportType = "ignored",
},
clientOptions: options,
createTransportFunc: (_, _) => new StreamClientTransport(
serverInput: _clientToServerPipe.Writer.AsStream(),
serverOutput: _serverToClientPipe.Reader.AsStream(),
LoggerFactory),
loggerFactory: LoggerFactory,
cancellationToken: cancellationToken ?? TestContext.Current.CancellationToken);
}
[Fact]
public async Task ListToolsAsync_AllToolsReturned()
{
IMcpClient client = await CreateMcpClientForServer();
var tools = await client.ListToolsAsync(cancellationToken: TestContext.Current.CancellationToken);
Assert.Equal(12, tools.Count);
var echo = tools.Single(t => t.Name == "Method4");
var result = await echo.InvokeAsync(new Dictionary<string, object?>() { ["i"] = 42 }, TestContext.Current.CancellationToken);
Assert.Contains("Method4 Result 42", result?.ToString());
var valuesSetViaAttr = tools.Single(t => t.Name == "ValuesSetViaAttr");
Assert.Null(valuesSetViaAttr.ProtocolTool.Annotations?.Title);
Assert.Null(valuesSetViaAttr.ProtocolTool.Annotations?.ReadOnlyHint);
Assert.Null(valuesSetViaAttr.ProtocolTool.Annotations?.IdempotentHint);
Assert.False(valuesSetViaAttr.ProtocolTool.Annotations?.DestructiveHint);
Assert.True(valuesSetViaAttr.ProtocolTool.Annotations?.OpenWorldHint);
var valuesSetViaOptions = tools.Single(t => t.Name == "ValuesSetViaOptions");
Assert.Null(valuesSetViaOptions.ProtocolTool.Annotations?.Title);
Assert.True(valuesSetViaOptions.ProtocolTool.Annotations?.ReadOnlyHint);
Assert.Null(valuesSetViaOptions.ProtocolTool.Annotations?.IdempotentHint);
Assert.True(valuesSetViaOptions.ProtocolTool.Annotations?.DestructiveHint);
Assert.False(valuesSetViaOptions.ProtocolTool.Annotations?.OpenWorldHint);
}
[Fact]
public async Task EnumerateToolsAsync_AllToolsReturned()
{
IMcpClient client = await CreateMcpClientForServer();
await foreach (var tool in client.EnumerateToolsAsync(cancellationToken: TestContext.Current.CancellationToken))
{
if (tool.Name == "Method4")
{
var result = await tool.InvokeAsync(new Dictionary<string, object?>() { ["i"] = 42 }, TestContext.Current.CancellationToken);
Assert.Contains("Method4 Result 42", result?.ToString());
return;
}
}
Assert.Fail("Couldn't find target method");
}
[Fact]
public async Task EnumerateToolsAsync_FlowsJsonSerializerOptions()
{
JsonSerializerOptions options = new(JsonSerializerOptions.Default);
IMcpClient client = await CreateMcpClientForServer();
bool hasTools = false;
await foreach (var tool in client.EnumerateToolsAsync(options, TestContext.Current.CancellationToken))
{
Assert.Same(options, tool.JsonSerializerOptions);
hasTools = true;
}
foreach (var tool in await client.ListToolsAsync(options, TestContext.Current.CancellationToken))
{
Assert.Same(options, tool.JsonSerializerOptions);
}
Assert.True(hasTools);
}
[Fact]
public async Task EnumerateToolsAsync_HonorsJsonSerializerOptions()
{
JsonSerializerOptions emptyOptions = new() { TypeInfoResolver = JsonTypeInfoResolver.Combine() };
IMcpClient client = await CreateMcpClientForServer();
var tool = (await client.ListToolsAsync(emptyOptions, TestContext.Current.CancellationToken)).First();
await Assert.ThrowsAsync<NotSupportedException>(() => tool.InvokeAsync(new Dictionary<string, object?> { ["i"] = 42 }, TestContext.Current.CancellationToken));
}
[Fact]
public async Task SendRequestAsync_HonorsJsonSerializerOptions()
{
JsonSerializerOptions emptyOptions = new() { TypeInfoResolver = JsonTypeInfoResolver.Combine() };
IMcpClient client = await CreateMcpClientForServer();
await Assert.ThrowsAsync<NotSupportedException>(() => client.SendRequestAsync<CallToolRequestParams, CallToolResponse>("Method4", new() { Name = "tool" }, emptyOptions, cancellationToken: TestContext.Current.CancellationToken));
}
[Fact]
public async Task SendNotificationAsync_HonorsJsonSerializerOptions()
{
JsonSerializerOptions emptyOptions = new() { TypeInfoResolver = JsonTypeInfoResolver.Combine() };
IMcpClient client = await CreateMcpClientForServer();
await Assert.ThrowsAsync<NotSupportedException>(() => client.SendNotificationAsync("Method4", new { Value = 42 }, emptyOptions, cancellationToken: TestContext.Current.CancellationToken));
}
[Fact]
public async Task GetPromptsAsync_HonorsJsonSerializerOptions()
{
JsonSerializerOptions emptyOptions = new() { TypeInfoResolver = JsonTypeInfoResolver.Combine() };
IMcpClient client = await CreateMcpClientForServer();
await Assert.ThrowsAsync<NotSupportedException>(() => client.GetPromptAsync("Prompt", new Dictionary<string, object?> { ["i"] = 42 }, emptyOptions, cancellationToken: TestContext.Current.CancellationToken));
}
[Fact]
public async Task WithName_ChangesToolName()
{
JsonSerializerOptions options = new(JsonSerializerOptions.Default);
IMcpClient client = await CreateMcpClientForServer();
var tool = (await client.ListToolsAsync(options, TestContext.Current.CancellationToken)).First();
var originalName = tool.Name;
var renamedTool = tool.WithName("RenamedTool");
Assert.NotNull(renamedTool);
Assert.Equal("RenamedTool", renamedTool.Name);
Assert.Equal(originalName, tool?.Name);
}
[Fact]
public async Task WithDescription_ChangesToolDescription()
{
JsonSerializerOptions options = new(JsonSerializerOptions.Default);
IMcpClient client = await CreateMcpClientForServer();
var tool = (await client.ListToolsAsync(options, TestContext.Current.CancellationToken)).FirstOrDefault();
var originalDescription = tool?.Description;
var redescribedTool = tool?.WithDescription("ToolWithNewDescription");
Assert.NotNull(redescribedTool);
Assert.Equal("ToolWithNewDescription", redescribedTool.Description);
Assert.Equal(originalDescription, tool?.Description);
}
[Fact]
public async Task Can_Handle_Notify_Cancel()
{
// Arrange
var token = TestContext.Current.CancellationToken;
TaskCompletionSource<JsonRpcNotification> clientReceived = new();
await using var client = await CreateMcpClientForServer(
options: CreateClientOptions([new(NotificationMethods.CancelledNotification, (notification, cancellationToken) =>
{
clientReceived.TrySetResult(notification);
return clientReceived.Task;
})]),
cancellationToken: token);
CancelledNotification rpcNotification = new()
{
RequestId = new("abc"),
Reason = "Cancelled",
};
// Act
await NotifyClientAsync(
message: NotificationMethods.CancelledNotification,
parameters: rpcNotification,
token: token);
var notification = await clientReceived.Task
.WaitAsync(TimeSpan.FromSeconds(5), token);
// Assert
Assert.NotNull(notification.Params);
// Parse the Params string back to a CancelledNotification
var cancelled = JsonSerializer.Deserialize<CancelledNotification>(notification.Params.ToString());
Assert.NotNull(cancelled);
Assert.Equal(rpcNotification.RequestId.ToString(), cancelled.RequestId.ToString());
Assert.Equal(rpcNotification.Reason, cancelled.Reason);
}
[Fact]
public async Task Should_Not_Intercept_Sent_Notifications()
{
// Arrange
var token = TestContext.Current.CancellationToken;
TaskCompletionSource<JsonRpcNotification> clientReceived = new();
await using var client = await CreateMcpClientForServer(
options: CreateClientOptions([new(NotificationMethods.CancelledNotification, (notification, cancellationToken) =>
{
var exception = new InvalidOperationException("Should not intercept sent notifications");
clientReceived.TrySetException(exception);
return clientReceived.Task;
})]),
cancellationToken: token);
// Act
await client.SendNotificationAsync(
method: NotificationMethods.CancelledNotification,
parameters: new CancelledNotification
{
RequestId = new("abc"),
Reason = "Cancelled",
}, cancellationToken: token);
await Assert.ThrowsAsync<TimeoutException>(
async () => await clientReceived.Task
.WaitAsync(TimeSpan.FromSeconds(5), token));
// Assert
Assert.False(clientReceived.Task.IsCompleted);
}
[Fact]
public async Task Can_Notify_Cancel()
{
// Arrange
var token = TestContext.Current.CancellationToken;
TaskCompletionSource clientReceived = new();
await using var client = await CreateMcpClientForServer(
options: CreateClientOptions(new Dictionary<string, Func<JsonRpcNotification, CancellationToken, Task>>()
{
[NotificationMethods.CancelledNotification] = (notification, cancellationToken) =>
{
InvalidOperationException exception = new("Should not intercept sent notifications");
clientReceived.TrySetException(exception);
return clientReceived.Task;
}
}), cancellationToken: token);
RequestId expectedRequestId = new("abc");
var expectedReason = "Cancelled";
// Act
await client.SendNotificationAsync(
method: NotificationMethods.CancelledNotification,
parameters: new CancelledNotification
{
RequestId = expectedRequestId,
Reason = expectedReason,
}, cancellationToken: token);
// Assert
await Assert.ThrowsAsync<TimeoutException>(
async () => await clientReceived.Task
.WaitAsync(TimeSpan.FromSeconds(3), token));
}
private static McpClientOptions CreateClientOptions(
IEnumerable<KeyValuePair<string, Func<JsonRpcNotification, CancellationToken, Task>>>? notificationHandlers = null)
=> new()
{
Capabilities = new()
{
NotificationHandlers = notificationHandlers ?? [],
},
};
private async Task NotifyClientAsync(
string message, object? parameters = null, CancellationToken token = default)
=> await NotifyPipeAsync(_serverToClientPipe, message, parameters, token);
private async static Task NotifyPipeAsync(
Pipe pipe, string message, object? parameters = null, CancellationToken token = default)
{
var bytes = JsonSerializer.SerializeToUtf8Bytes(new JsonRpcNotification
{
Method = message,
Params = parameters is not null ? JsonSerializer.Serialize(parameters) : null,
});
await pipe.Writer.WriteAsync(bytes, token);
await pipe.Writer.CompleteAsync(); // Signal the end of the message
}
}