forked from modelcontextprotocol/csharp-sdk
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathMcpClientExtensionsTests.cs
More file actions
202 lines (170 loc) · 8.91 KB
/
McpClientExtensionsTests.cs
File metadata and controls
202 lines (170 loc) · 8.91 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
using Microsoft.Extensions.DependencyInjection;
using ModelContextProtocol.Client;
using ModelContextProtocol.Protocol.Transport;
using ModelContextProtocol.Protocol.Types;
using ModelContextProtocol.Server;
using ModelContextProtocol.Tests.Utils;
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().WithStdioServerTransport();
// Call WithStdioServerTransport to get the IMcpServer registration, then overwrite default transport with a pipe transport.
sc.AddSingleton<ITransport>(new StreamServerTransport(_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);
}
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()
{
return await McpClientFactory.CreateAsync(
new McpServerConfig()
{
Id = "TestServer",
Name = "TestServer",
TransportType = "ignored",
},
createTransportFunc: (_, _) => new StreamClientTransport(
serverInput: _clientToServerPipe.Writer.AsStream(),
serverOutput: _serverToClientPipe.Reader.AsStream(),
LoggerFactory),
loggerFactory: LoggerFactory,
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)).FirstOrDefault();
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);
}
}