forked from modelcontextprotocol/csharp-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNotificationHandlerTests.cs
244 lines (207 loc) · 8.41 KB
/
NotificationHandlerTests.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
using Microsoft.Extensions.AI;
using Microsoft.Extensions.DependencyInjection;
using ModelContextProtocol.Client;
using ModelContextProtocol.Protocol.Transport;
using ModelContextProtocol.Server;
using ModelContextProtocol.Tests.Utils;
using System.IO.Pipelines;
namespace ModelContextProtocol.Tests;
public class NotificationHandlerTests : LoggedTest, IAsyncDisposable
{
private readonly Pipe _clientToServerPipe = new();
private readonly Pipe _serverToClientPipe = new();
private readonly ServiceProvider _serviceProvider;
private readonly IMcpServerBuilder _builder;
private readonly CancellationTokenSource _cts;
private readonly Task _serverTask;
private readonly IMcpServer _server;
public NotificationHandlerTests(ITestOutputHelper testOutputHelper)
: base(testOutputHelper)
{
ServiceCollection sc = new();
sc.AddSingleton(LoggerFactory);
_builder = sc
.AddMcpServer()
.WithStreamServerTransport(_clientToServerPipe.Reader.AsStream(), _serverToClientPipe.Writer.AsStream());
_serviceProvider = sc.BuildServiceProvider();
_cts = CancellationTokenSource.CreateLinkedTokenSource(TestContext.Current.CancellationToken);
_server = _serviceProvider.GetRequiredService<IMcpServer>();
_serverTask = _server.RunAsync(_cts.Token);
}
public async ValueTask DisposeAsync()
{
await _cts.CancelAsync();
_clientToServerPipe.Writer.Complete();
_serverToClientPipe.Writer.Complete();
await _serverTask;
await _serviceProvider.DisposeAsync();
_cts.Dispose();
Dispose();
}
private async Task<IMcpClient> CreateMcpClientForServer(McpClientOptions? options = null)
{
return await McpClientFactory.CreateAsync(
new McpServerConfig()
{
Id = "TestServer",
Name = "TestServer",
TransportType = "ignored",
},
options,
createTransportFunc: (_, _) => new StreamClientTransport(
serverInput: _clientToServerPipe.Writer.AsStream(),
_serverToClientPipe.Reader.AsStream(),
LoggerFactory),
loggerFactory: LoggerFactory,
cancellationToken: TestContext.Current.CancellationToken);
}
[Fact]
public async Task RegistrationsAreRemovedWhenDisposed()
{
const string NotificationName = "somethingsomething";
IMcpClient client = await CreateMcpClientForServer();
const int Iterations = 10;
int counter = 0;
for (int i = 0; i < Iterations; i++)
{
var tcs = new TaskCompletionSource<bool>();
await using (client.RegisterNotificationHandler(NotificationName, (notification, cancellationToken) =>
{
Interlocked.Increment(ref counter);
tcs.SetResult(true);
return Task.CompletedTask;
}))
{
await _server.SendNotificationAsync(NotificationName, TestContext.Current.CancellationToken);
await tcs.Task;
}
}
Assert.Equal(Iterations, counter);
}
[Fact]
public async Task MultipleRegistrationsResultInMultipleCallbacks()
{
const string NotificationName = "somethingsomething";
IMcpClient client = await CreateMcpClientForServer();
const int RegistrationCount = 10;
int remaining = RegistrationCount;
var tcs = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
IAsyncDisposable[] registrations = new IAsyncDisposable[RegistrationCount];
for (int i = 0; i < registrations.Length; i++)
{
registrations[i] = client.RegisterNotificationHandler(NotificationName, (notification, cancellationToken) =>
{
int result = Interlocked.Decrement(ref remaining);
Assert.InRange(result, 0, RegistrationCount);
if (result == 0)
{
tcs.TrySetResult(true);
}
return Task.CompletedTask;
});
}
try
{
await _server.SendNotificationAsync(NotificationName, TestContext.Current.CancellationToken);
await tcs.Task;
}
finally
{
for (int i = registrations.Length - 1; i >= 0; i--)
{
await registrations[i].DisposeAsync();
}
}
}
[Fact]
public async Task MultipleHandlersRunEvenIfOneThrows()
{
const string NotificationName = "somethingsomething";
IMcpClient client = await CreateMcpClientForServer();
const int RegistrationCount = 10;
int remaining = RegistrationCount;
var tcs = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
IAsyncDisposable[] registrations = new IAsyncDisposable[RegistrationCount];
for (int i = 0; i < registrations.Length; i++)
{
registrations[i] = client.RegisterNotificationHandler(NotificationName, (notification, cancellationToken) =>
{
int result = Interlocked.Decrement(ref remaining);
Assert.InRange(result, 0, RegistrationCount);
if (result == 0)
{
tcs.TrySetResult(true);
}
throw new InvalidOperationException("Test exception");
});
}
try
{
await _server.SendNotificationAsync(NotificationName, TestContext.Current.CancellationToken);
await tcs.Task;
}
finally
{
for (int i = registrations.Length - 1; i >= 0; i--)
{
await registrations[i].DisposeAsync();
}
}
}
[Theory]
[InlineData(1)]
[InlineData(3)]
public async Task DisposeAsyncDoesNotCompleteWhileNotificationHandlerRuns(int numberOfDisposals)
{
const string NotificationName = "somethingsomething";
IMcpClient client = await CreateMcpClientForServer();
var handlerRunning = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
var releaseHandler = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
IAsyncDisposable registration = client.RegisterNotificationHandler(NotificationName, async (notification, cancellationToken) =>
{
handlerRunning.SetResult(true);
await releaseHandler.Task;
});
await _server.SendNotificationAsync(NotificationName, TestContext.Current.CancellationToken);
await handlerRunning.Task;
var disposals = new ValueTask[numberOfDisposals];
for (int i = 0; i < numberOfDisposals; i++)
{
disposals[i] = registration.DisposeAsync();
}
await Task.Delay(1, TestContext.Current.CancellationToken);
foreach (ValueTask disposal in disposals)
{
Assert.False(disposal.IsCompleted);
}
releaseHandler.SetResult(true);
foreach (ValueTask disposal in disposals)
{
await disposal;
}
}
[Theory]
[InlineData(1)]
[InlineData(3)]
public async Task DisposeAsyncCompletesImmediatelyWhenInvokedFromHandler(int numberOfDisposals)
{
const string NotificationName = "somethingsomething";
IMcpClient client = await CreateMcpClientForServer();
var handlerRunning = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
var releaseHandler = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
IAsyncDisposable? registration = null;
await using var _ = registration = client.RegisterNotificationHandler(NotificationName, async (notification, cancellationToken) =>
{
for (int i = 0; i < numberOfDisposals; i++)
{
Assert.NotNull(registration);
ValueTask disposal = registration!.DisposeAsync();
Assert.True(disposal.IsCompletedSuccessfully);
await disposal;
}
handlerRunning.SetResult(true);
});
await _server.SendNotificationAsync(NotificationName, TestContext.Current.CancellationToken);
await handlerRunning.Task;
}
}