Restructure IMcpEndpoint, IMcpClient, and IMcpServer (#723)
* Remove `McpEndpoint` & `IMcpClient` * Revise naming, add abstract classes * Fix missing renames * Move extension methods to instance methods * Add back old API, but obsoleted * Add back obsoleted factory classes * Move deprecation attributes * `SseClientTransport` -> `HttpClientTransport` * Update src/ModelContextProtocol.Core/Server/AugmentedServiceProvider.cs Co-authored-by: Stephen Halter <halter73@gmail.com> * PR feedback * PR feedback * Add back dispose lock * Fix docs projects * PR feedback * Undo `docs/*.md` changes --------- Co-authored-by: Stephen Halter <halter73@gmail.com>
This commit is contained in:
parent
fe2ce2bc60
commit
38b4a26998
29 changed files with 5169 additions and 3786 deletions
|
|
@ -0,0 +1,155 @@
|
|||
using ModelContextProtocol.Client;
|
||||
using ModelContextProtocol.Protocol;
|
||||
using System.IO.Pipelines;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Channels;
|
||||
|
||||
namespace ModelContextProtocol.Tests.Client;
|
||||
|
||||
public class McpClientCreationTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task CreateAsync_WithInvalidArgs_Throws()
|
||||
{
|
||||
await Assert.ThrowsAsync<ArgumentNullException>("clientTransport", () => McpClient.CreateAsync(null!, cancellationToken: TestContext.Current.CancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateAsync_NopTransport_ReturnsClient()
|
||||
{
|
||||
// Act
|
||||
await using var client = await McpClient.CreateAsync(
|
||||
new NopTransport(),
|
||||
cancellationToken: TestContext.Current.CancellationToken);
|
||||
|
||||
Assert.NotNull(client);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(false)]
|
||||
[InlineData(true)]
|
||||
public async Task Cancellation_ThrowsCancellationException(bool preCanceled)
|
||||
{
|
||||
var cts = new CancellationTokenSource();
|
||||
|
||||
if (preCanceled)
|
||||
{
|
||||
cts.Cancel();
|
||||
}
|
||||
|
||||
Task t = McpClient.CreateAsync(
|
||||
new StreamClientTransport(new Pipe().Writer.AsStream(), new Pipe().Reader.AsStream()),
|
||||
cancellationToken: cts.Token);
|
||||
if (!preCanceled)
|
||||
{
|
||||
Assert.False(t.IsCompleted);
|
||||
}
|
||||
|
||||
if (!preCanceled)
|
||||
{
|
||||
cts.Cancel();
|
||||
}
|
||||
|
||||
await Assert.ThrowsAnyAsync<OperationCanceledException>(() => t);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(typeof(NopTransport))]
|
||||
[InlineData(typeof(FailureTransport))]
|
||||
public async Task CreateAsync_WithCapabilitiesOptions(Type transportType)
|
||||
{
|
||||
// Arrange
|
||||
var clientOptions = new McpClientOptions
|
||||
{
|
||||
Capabilities = new ClientCapabilities
|
||||
{
|
||||
Sampling = new SamplingCapability
|
||||
{
|
||||
SamplingHandler = async (c, p, t) =>
|
||||
new CreateMessageResult
|
||||
{
|
||||
Content = new TextContentBlock { Text = "result" },
|
||||
Model = "test-model",
|
||||
Role = Role.User,
|
||||
StopReason = "endTurn"
|
||||
},
|
||||
},
|
||||
Roots = new RootsCapability
|
||||
{
|
||||
ListChanged = true,
|
||||
RootsHandler = async (t, r) => new ListRootsResult { Roots = [] },
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
var clientTransport = (IClientTransport)Activator.CreateInstance(transportType)!;
|
||||
McpClient? client = null;
|
||||
|
||||
var actionTask = McpClient.CreateAsync(clientTransport, clientOptions, loggerFactory: null, CancellationToken.None);
|
||||
|
||||
// Act
|
||||
if (clientTransport is FailureTransport)
|
||||
{
|
||||
var exception = await Assert.ThrowsAsync<InvalidOperationException>(async() => await actionTask);
|
||||
Assert.Equal(FailureTransport.ExpectedMessage, exception.Message);
|
||||
}
|
||||
else
|
||||
{
|
||||
client = await actionTask;
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(client);
|
||||
}
|
||||
}
|
||||
|
||||
private class NopTransport : ITransport, IClientTransport
|
||||
{
|
||||
private readonly Channel<JsonRpcMessage> _channel = Channel.CreateUnbounded<JsonRpcMessage>();
|
||||
|
||||
public bool IsConnected => true;
|
||||
public string? SessionId => null;
|
||||
|
||||
public ChannelReader<JsonRpcMessage> MessageReader => _channel.Reader;
|
||||
|
||||
public Task<ITransport> ConnectAsync(CancellationToken cancellationToken = default) => Task.FromResult<ITransport>(this);
|
||||
|
||||
public ValueTask DisposeAsync() => default;
|
||||
|
||||
public string Name => "Test Nop Transport";
|
||||
|
||||
public virtual Task SendMessageAsync(JsonRpcMessage message, CancellationToken cancellationToken = default)
|
||||
{
|
||||
switch (message)
|
||||
{
|
||||
case JsonRpcRequest:
|
||||
_channel.Writer.TryWrite(new JsonRpcResponse
|
||||
{
|
||||
Id = ((JsonRpcRequest)message).Id,
|
||||
Result = JsonSerializer.SerializeToNode(new InitializeResult
|
||||
{
|
||||
Capabilities = new ServerCapabilities(),
|
||||
ProtocolVersion = "2024-11-05",
|
||||
ServerInfo = new Implementation
|
||||
{
|
||||
Name = "NopTransport",
|
||||
Version = "1.0.0"
|
||||
},
|
||||
}, McpJsonUtilities.DefaultOptions),
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class FailureTransport : NopTransport
|
||||
{
|
||||
public const string ExpectedMessage = "Something failed";
|
||||
|
||||
public override Task SendMessageAsync(JsonRpcMessage message, CancellationToken cancellationToken = default)
|
||||
{
|
||||
throw new InvalidOperationException(ExpectedMessage);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,471 +1,387 @@
|
|||
using Microsoft.Extensions.AI;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using ModelContextProtocol.Client;
|
||||
using ModelContextProtocol.Protocol;
|
||||
using ModelContextProtocol.Server;
|
||||
using Moq;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization.Metadata;
|
||||
using System.Threading.Channels;
|
||||
|
||||
namespace ModelContextProtocol.Tests.Client;
|
||||
namespace ModelContextProtocol.Tests;
|
||||
|
||||
public class McpClientExtensionsTests : ClientServerTestBase
|
||||
#pragma warning disable CS0618 // Type or member is obsolete
|
||||
|
||||
public class McpClientExtensionsTests
|
||||
{
|
||||
public McpClientExtensionsTests(ITestOutputHelper outputHelper)
|
||||
: base(outputHelper)
|
||||
[Fact]
|
||||
public async Task PingAsync_Throws_When_Not_McpClient()
|
||||
{
|
||||
var client = new Mock<IMcpClient>(MockBehavior.Strict).Object;
|
||||
|
||||
var ex = await Assert.ThrowsAsync<InvalidOperationException>(async () => await client.PingAsync(TestContext.Current.CancellationToken));
|
||||
Assert.Contains("Prefer using 'McpClient.PingAsync' instead", ex.Message);
|
||||
}
|
||||
|
||||
protected override void ConfigureServices(ServiceCollection services, IMcpServerBuilder mcpServerBuilder)
|
||||
[Fact]
|
||||
public async Task GetPromptAsync_Throws_When_Not_McpClient()
|
||||
{
|
||||
for (int f = 0; f < 10; f++)
|
||||
{
|
||||
string name = $"Method{f}";
|
||||
mcpServerBuilder.WithTools([McpServerTool.Create((int i) => $"{name} Result {i}", new() { Name = name })]);
|
||||
}
|
||||
mcpServerBuilder.WithTools([McpServerTool.Create([McpServerTool(Destructive = false, OpenWorld = true)] (string i) => $"{i} Result", new() { Name = "ValuesSetViaAttr" })]);
|
||||
mcpServerBuilder.WithTools([McpServerTool.Create([McpServerTool(Destructive = false, OpenWorld = true)] (string i) => $"{i} Result", new() { Name = "ValuesSetViaOptions", Destructive = true, OpenWorld = false, ReadOnly = true })]);
|
||||
var client = new Mock<IMcpClient>(MockBehavior.Strict).Object;
|
||||
|
||||
var ex = await Assert.ThrowsAsync<InvalidOperationException>(async () => await client.GetPromptAsync(
|
||||
"name", cancellationToken: TestContext.Current.CancellationToken));
|
||||
Assert.Contains("Prefer using 'McpClient.GetPromptAsync' instead", ex.Message);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null, null)]
|
||||
[InlineData(0.7f, 50)]
|
||||
[InlineData(1.0f, 100)]
|
||||
public async Task CreateSamplingHandler_ShouldHandleTextMessages(float? temperature, int? maxTokens)
|
||||
[Fact]
|
||||
public async Task CallToolAsync_Throws_When_Not_McpClient()
|
||||
{
|
||||
// Arrange
|
||||
var mockChatClient = new Mock<IChatClient>();
|
||||
var requestParams = new CreateMessageRequestParams
|
||||
{
|
||||
Messages =
|
||||
[
|
||||
new SamplingMessage
|
||||
{
|
||||
Role = Role.User,
|
||||
Content = new TextContentBlock { Text = "Hello" }
|
||||
}
|
||||
],
|
||||
Temperature = temperature,
|
||||
MaxTokens = maxTokens,
|
||||
};
|
||||
var client = new Mock<IMcpClient>(MockBehavior.Strict).Object;
|
||||
|
||||
var cancellationToken = CancellationToken.None;
|
||||
var expectedResponse = new[] {
|
||||
new ChatResponseUpdate
|
||||
var ex = await Assert.ThrowsAsync<InvalidOperationException>(async () => await client.CallToolAsync(
|
||||
"tool", cancellationToken: TestContext.Current.CancellationToken));
|
||||
Assert.Contains("Prefer using 'McpClient.CallToolAsync' instead", ex.Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ListResourcesAsync_Throws_When_Not_McpClient()
|
||||
{
|
||||
var client = new Mock<IMcpClient>(MockBehavior.Strict).Object;
|
||||
|
||||
var ex = await Assert.ThrowsAsync<InvalidOperationException>(async () => await client.ListResourcesAsync(
|
||||
cancellationToken: TestContext.Current.CancellationToken));
|
||||
Assert.Contains("Prefer using 'McpClient.ListResourcesAsync' instead", ex.Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EnumerateResourcesAsync_Throws_When_Not_McpClient()
|
||||
{
|
||||
var client = new Mock<IMcpClient>(MockBehavior.Strict).Object;
|
||||
|
||||
var ex = Assert.Throws<InvalidOperationException>(() => client.EnumerateResourcesAsync(cancellationToken: TestContext.Current.CancellationToken));
|
||||
Assert.Contains("Prefer using 'McpClient.EnumerateResourcesAsync' instead", ex.Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SubscribeToResourceAsync_String_Throws_When_Not_McpClient()
|
||||
{
|
||||
var client = new Mock<IMcpClient>(MockBehavior.Strict).Object;
|
||||
|
||||
var ex = await Assert.ThrowsAsync<InvalidOperationException>(async () => await client.SubscribeToResourceAsync(
|
||||
"mcp://resource/1", TestContext.Current.CancellationToken));
|
||||
Assert.Contains("Prefer using 'McpClient.SubscribeToResourceAsync' instead", ex.Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SubscribeToResourceAsync_Uri_Throws_When_Not_McpClient()
|
||||
{
|
||||
var client = new Mock<IMcpClient>(MockBehavior.Strict).Object;
|
||||
|
||||
var ex = await Assert.ThrowsAsync<InvalidOperationException>(async () => await client.SubscribeToResourceAsync(
|
||||
new Uri("mcp://resource/1"), TestContext.Current.CancellationToken));
|
||||
Assert.Contains("Prefer using 'McpClient.SubscribeToResourceAsync' instead", ex.Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UnsubscribeFromResourceAsync_String_Throws_When_Not_McpClient()
|
||||
{
|
||||
var client = new Mock<IMcpClient>(MockBehavior.Strict).Object;
|
||||
|
||||
var ex = await Assert.ThrowsAsync<InvalidOperationException>(async () => await client.UnsubscribeFromResourceAsync(
|
||||
"mcp://resource/1", TestContext.Current.CancellationToken));
|
||||
Assert.Contains("Prefer using 'McpClient.UnsubscribeFromResourceAsync' instead", ex.Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UnsubscribeFromResourceAsync_Uri_Throws_When_Not_McpClient()
|
||||
{
|
||||
var client = new Mock<IMcpClient>(MockBehavior.Strict).Object;
|
||||
|
||||
var ex = await Assert.ThrowsAsync<InvalidOperationException>(async () => await client.UnsubscribeFromResourceAsync(
|
||||
new Uri("mcp://resource/1"), TestContext.Current.CancellationToken));
|
||||
Assert.Contains("Prefer using 'McpClient.UnsubscribeFromResourceAsync' instead", ex.Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ReadResourceAsync_String_Throws_When_Not_McpClient()
|
||||
{
|
||||
var client = new Mock<IMcpClient>(MockBehavior.Strict).Object;
|
||||
|
||||
var ex = await Assert.ThrowsAsync<InvalidOperationException>(async () => await client.ReadResourceAsync(
|
||||
"mcp://resource/1", TestContext.Current.CancellationToken));
|
||||
Assert.Contains("Prefer using 'McpClient.ReadResourceAsync' instead", ex.Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ReadResourceAsync_Uri_Throws_When_Not_McpClient()
|
||||
{
|
||||
var client = new Mock<IMcpClient>(MockBehavior.Strict).Object;
|
||||
|
||||
var ex = await Assert.ThrowsAsync<InvalidOperationException>(async () => await client.ReadResourceAsync(
|
||||
new Uri("mcp://resource/1"), TestContext.Current.CancellationToken));
|
||||
Assert.Contains("Prefer using 'McpClient.ReadResourceAsync' instead", ex.Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ReadResourceAsync_Template_Throws_When_Not_McpClient()
|
||||
{
|
||||
var client = new Mock<IMcpClient>(MockBehavior.Strict).Object;
|
||||
|
||||
var ex = await Assert.ThrowsAsync<InvalidOperationException>(async () => await client.ReadResourceAsync(
|
||||
"mcp://resource/{id}", new Dictionary<string, object?> { ["id"] = 1 }, TestContext.Current.CancellationToken));
|
||||
Assert.Contains("Prefer using 'McpClient.ReadResourceAsync' instead", ex.Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CompleteAsync_Throws_When_Not_McpClient()
|
||||
{
|
||||
var client = new Mock<IMcpClient>(MockBehavior.Strict).Object;
|
||||
var reference = new PromptReference { Name = "prompt" };
|
||||
|
||||
var ex = await Assert.ThrowsAsync<InvalidOperationException>(async () => await client.CompleteAsync(
|
||||
reference, "arg", "val", TestContext.Current.CancellationToken));
|
||||
Assert.Contains("Prefer using 'McpClient.CompleteAsync' instead", ex.Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ListToolsAsync_Throws_When_Not_McpClient()
|
||||
{
|
||||
var client = new Mock<IMcpClient>(MockBehavior.Strict).Object;
|
||||
|
||||
var ex = await Assert.ThrowsAsync<InvalidOperationException>(async () => await client.ListToolsAsync(
|
||||
cancellationToken: TestContext.Current.CancellationToken));
|
||||
Assert.Contains("Prefer using 'McpClient.ListToolsAsync' instead", ex.Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EnumerateToolsAsync_Throws_When_Not_McpClient()
|
||||
{
|
||||
var client = new Mock<IMcpClient>(MockBehavior.Strict).Object;
|
||||
|
||||
var ex = Assert.Throws<InvalidOperationException>(() => client.EnumerateToolsAsync(cancellationToken: TestContext.Current.CancellationToken));
|
||||
Assert.Contains("Prefer using 'McpClient.EnumerateToolsAsync' instead", ex.Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ListPromptsAsync_Throws_When_Not_McpClient()
|
||||
{
|
||||
var client = new Mock<IMcpClient>(MockBehavior.Strict).Object;
|
||||
|
||||
var ex = await Assert.ThrowsAsync<InvalidOperationException>(async () => await client.ListPromptsAsync(
|
||||
cancellationToken: TestContext.Current.CancellationToken));
|
||||
Assert.Contains("Prefer using 'McpClient.ListPromptsAsync' instead", ex.Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EnumeratePromptsAsync_Throws_When_Not_McpClient()
|
||||
{
|
||||
var client = new Mock<IMcpClient>(MockBehavior.Strict).Object;
|
||||
|
||||
var ex = Assert.Throws<InvalidOperationException>(() => client.EnumeratePromptsAsync(cancellationToken: TestContext.Current.CancellationToken));
|
||||
Assert.Contains("Prefer using 'McpClient.EnumeratePromptsAsync' instead", ex.Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ListResourceTemplatesAsync_Throws_When_Not_McpClient()
|
||||
{
|
||||
var client = new Mock<IMcpClient>(MockBehavior.Strict).Object;
|
||||
|
||||
var ex = await Assert.ThrowsAsync<InvalidOperationException>(async () => await client.ListResourceTemplatesAsync(
|
||||
cancellationToken: TestContext.Current.CancellationToken));
|
||||
Assert.Contains("Prefer using 'McpClient.ListResourceTemplatesAsync' instead", ex.Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void EnumerateResourceTemplatesAsync_Throws_When_Not_McpClient()
|
||||
{
|
||||
var client = new Mock<IMcpClient>(MockBehavior.Strict).Object;
|
||||
|
||||
var ex = Assert.Throws<InvalidOperationException>(() => client.EnumerateResourceTemplatesAsync(cancellationToken: TestContext.Current.CancellationToken));
|
||||
Assert.Contains("Prefer using 'McpClient.EnumerateResourceTemplatesAsync' instead", ex.Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task PingAsync_Forwards_To_McpClient_SendRequestAsync()
|
||||
{
|
||||
var mockClient = new Mock<McpClient> { CallBase = true };
|
||||
|
||||
mockClient
|
||||
.Setup(c => c.SendRequestAsync(It.IsAny<JsonRpcRequest>(), It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(new JsonRpcResponse
|
||||
{
|
||||
ModelId = "test-model",
|
||||
FinishReason = ChatFinishReason.Stop,
|
||||
Role = ChatRole.Assistant,
|
||||
Contents =
|
||||
[
|
||||
new TextContent("Hello, World!") { RawRepresentation = "Hello, World!" }
|
||||
]
|
||||
}
|
||||
}.ToAsyncEnumerable();
|
||||
Result = JsonSerializer.SerializeToNode(new object(), McpJsonUtilities.DefaultOptions),
|
||||
});
|
||||
|
||||
mockChatClient
|
||||
.Setup(client => client.GetStreamingResponseAsync(It.IsAny<IEnumerable<ChatMessage>>(), It.IsAny<ChatOptions>(), cancellationToken))
|
||||
.Returns(expectedResponse);
|
||||
IMcpClient client = mockClient.Object;
|
||||
|
||||
var handler = McpClientExtensions.CreateSamplingHandler(mockChatClient.Object);
|
||||
await client.PingAsync(TestContext.Current.CancellationToken);
|
||||
|
||||
// Act
|
||||
var result = await handler(requestParams, Mock.Of<IProgress<ProgressNotificationValue>>(), cancellationToken);
|
||||
mockClient.Verify(c => c.SendRequestAsync(It.IsAny<JsonRpcRequest>(), It.IsAny<CancellationToken>()), Times.Once);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetPromptAsync_Forwards_To_McpClient_SendRequestAsync()
|
||||
{
|
||||
var mockClient = new Mock<McpClient> { CallBase = true };
|
||||
|
||||
var resultPayload = new GetPromptResult { Messages = [new PromptMessage { Role = Role.User, Content = new TextContentBlock { Text = "hi" } }] };
|
||||
|
||||
mockClient
|
||||
.Setup(c => c.SendRequestAsync(It.IsAny<JsonRpcRequest>(), It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(new JsonRpcResponse
|
||||
{
|
||||
Result = JsonSerializer.SerializeToNode(resultPayload, McpJsonUtilities.DefaultOptions),
|
||||
});
|
||||
|
||||
IMcpClient client = mockClient.Object;
|
||||
|
||||
var result = await client.GetPromptAsync("name", cancellationToken: TestContext.Current.CancellationToken);
|
||||
|
||||
Assert.Equal("hi", Assert.IsType<TextContentBlock>(result.Messages[0].Content).Text);
|
||||
mockClient.Verify(c => c.SendRequestAsync(It.IsAny<JsonRpcRequest>(), It.IsAny<CancellationToken>()), Times.Once);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CallToolAsync_Forwards_To_McpClient_SendRequestAsync()
|
||||
{
|
||||
var mockClient = new Mock<McpClient> { CallBase = true };
|
||||
|
||||
var callResult = new CallToolResult { Content = [new TextContentBlock { Text = "ok" }] };
|
||||
|
||||
mockClient
|
||||
.Setup(c => c.SendRequestAsync(It.IsAny<JsonRpcRequest>(), It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(new JsonRpcResponse
|
||||
{
|
||||
Result = JsonSerializer.SerializeToNode(callResult, McpJsonUtilities.DefaultOptions),
|
||||
});
|
||||
|
||||
IMcpClient client = mockClient.Object;
|
||||
|
||||
var result = await client.CallToolAsync("tool", cancellationToken: TestContext.Current.CancellationToken);
|
||||
|
||||
Assert.Equal("ok", Assert.IsType<TextContentBlock>(result.Content[0]).Text);
|
||||
mockClient.Verify(c => c.SendRequestAsync(It.IsAny<JsonRpcRequest>(), It.IsAny<CancellationToken>()), Times.Once);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SubscribeToResourceAsync_Forwards_To_McpClient_SendRequestAsync()
|
||||
{
|
||||
var mockClient = new Mock<McpClient> { CallBase = true };
|
||||
|
||||
mockClient
|
||||
.Setup(c => c.SendRequestAsync(It.IsAny<JsonRpcRequest>(), It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(new JsonRpcResponse
|
||||
{
|
||||
Result = JsonSerializer.SerializeToNode(new EmptyResult(), McpJsonUtilities.DefaultOptions),
|
||||
});
|
||||
|
||||
IMcpClient client = mockClient.Object;
|
||||
|
||||
await client.SubscribeToResourceAsync("mcp://resource/1", TestContext.Current.CancellationToken);
|
||||
|
||||
mockClient.Verify(c => c.SendRequestAsync(It.IsAny<JsonRpcRequest>(), It.IsAny<CancellationToken>()), Times.Once);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UnsubscribeFromResourceAsync_Forwards_To_McpClient_SendRequestAsync()
|
||||
{
|
||||
var mockClient = new Mock<McpClient> { CallBase = true };
|
||||
|
||||
mockClient
|
||||
.Setup(c => c.SendRequestAsync(It.IsAny<JsonRpcRequest>(), It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(new JsonRpcResponse
|
||||
{
|
||||
Result = JsonSerializer.SerializeToNode(new EmptyResult(), McpJsonUtilities.DefaultOptions),
|
||||
});
|
||||
|
||||
IMcpClient client = mockClient.Object;
|
||||
|
||||
await client.UnsubscribeFromResourceAsync("mcp://resource/1", TestContext.Current.CancellationToken);
|
||||
|
||||
mockClient.Verify(c => c.SendRequestAsync(It.IsAny<JsonRpcRequest>(), It.IsAny<CancellationToken>()), Times.Once);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CompleteAsync_Forwards_To_McpClient_SendRequestAsync()
|
||||
{
|
||||
var mockClient = new Mock<McpClient> { CallBase = true };
|
||||
|
||||
var completion = new Completion { Values = ["one", "two"] };
|
||||
var resultPayload = new CompleteResult { Completion = completion };
|
||||
|
||||
mockClient
|
||||
.Setup(c => c.SendRequestAsync(It.IsAny<JsonRpcRequest>(), It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(new JsonRpcResponse
|
||||
{
|
||||
Result = JsonSerializer.SerializeToNode(resultPayload, McpJsonUtilities.DefaultOptions),
|
||||
});
|
||||
|
||||
IMcpClient client = mockClient.Object;
|
||||
|
||||
var result = await client.CompleteAsync(new PromptReference { Name = "p" }, "arg", "val", TestContext.Current.CancellationToken);
|
||||
|
||||
Assert.Contains("one", result.Completion.Values);
|
||||
mockClient.Verify(c => c.SendRequestAsync(It.IsAny<JsonRpcRequest>(), It.IsAny<CancellationToken>()), Times.Once);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ReadResourceAsync_String_Forwards_To_McpClient_SendRequestAsync()
|
||||
{
|
||||
var mockClient = new Mock<McpClient> { CallBase = true };
|
||||
|
||||
var resultPayload = new ReadResourceResult { Contents = [] };
|
||||
|
||||
mockClient
|
||||
.Setup(c => c.SendRequestAsync(It.IsAny<JsonRpcRequest>(), It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(new JsonRpcResponse
|
||||
{
|
||||
Result = JsonSerializer.SerializeToNode(resultPayload, McpJsonUtilities.DefaultOptions),
|
||||
});
|
||||
|
||||
IMcpClient client = mockClient.Object;
|
||||
|
||||
var result = await client.ReadResourceAsync("mcp://resource/1", TestContext.Current.CancellationToken);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal("Hello, World!", (result.Content as TextContentBlock)?.Text);
|
||||
Assert.Equal("test-model", result.Model);
|
||||
Assert.Equal(Role.Assistant, result.Role);
|
||||
Assert.Equal("endTurn", result.StopReason);
|
||||
mockClient.Verify(c => c.SendRequestAsync(It.IsAny<JsonRpcRequest>(), It.IsAny<CancellationToken>()), Times.Once);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateSamplingHandler_ShouldHandleImageMessages()
|
||||
public async Task ReadResourceAsync_Uri_Forwards_To_McpClient_SendRequestAsync()
|
||||
{
|
||||
// Arrange
|
||||
var mockChatClient = new Mock<IChatClient>();
|
||||
var requestParams = new CreateMessageRequestParams
|
||||
{
|
||||
Messages =
|
||||
[
|
||||
new SamplingMessage
|
||||
{
|
||||
Role = Role.User,
|
||||
Content = new ImageContentBlock
|
||||
{
|
||||
MimeType = "image/png",
|
||||
Data = Convert.ToBase64String(new byte[] { 1, 2, 3 })
|
||||
}
|
||||
}
|
||||
],
|
||||
MaxTokens = 100
|
||||
};
|
||||
var mockClient = new Mock<McpClient> { CallBase = true };
|
||||
|
||||
const string expectedData = "SGVsbG8sIFdvcmxkIQ==";
|
||||
var cancellationToken = CancellationToken.None;
|
||||
var expectedResponse = new[] {
|
||||
new ChatResponseUpdate
|
||||
var resultPayload = new ReadResourceResult { Contents = [] };
|
||||
|
||||
mockClient
|
||||
.Setup(c => c.SendRequestAsync(It.IsAny<JsonRpcRequest>(), It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(new JsonRpcResponse
|
||||
{
|
||||
ModelId = "test-model",
|
||||
FinishReason = ChatFinishReason.Stop,
|
||||
Role = ChatRole.Assistant,
|
||||
Contents =
|
||||
[
|
||||
new DataContent($"data:image/png;base64,{expectedData}") { RawRepresentation = "Hello, World!" }
|
||||
]
|
||||
}
|
||||
}.ToAsyncEnumerable();
|
||||
Result = JsonSerializer.SerializeToNode(resultPayload, McpJsonUtilities.DefaultOptions),
|
||||
});
|
||||
|
||||
mockChatClient
|
||||
.Setup(client => client.GetStreamingResponseAsync(It.IsAny<IEnumerable<ChatMessage>>(), It.IsAny<ChatOptions>(), cancellationToken))
|
||||
.Returns(expectedResponse);
|
||||
IMcpClient client = mockClient.Object;
|
||||
|
||||
var handler = McpClientExtensions.CreateSamplingHandler(mockChatClient.Object);
|
||||
var result = await client.ReadResourceAsync(new Uri("mcp://resource/1"), TestContext.Current.CancellationToken);
|
||||
|
||||
// Act
|
||||
var result = await handler(requestParams, Mock.Of<IProgress<ProgressNotificationValue>>(), cancellationToken);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal(expectedData, (result.Content as ImageContentBlock)?.Data);
|
||||
Assert.Equal("test-model", result.Model);
|
||||
Assert.Equal(Role.Assistant, result.Role);
|
||||
Assert.Equal("endTurn", result.StopReason);
|
||||
mockClient.Verify(c => c.SendRequestAsync(It.IsAny<JsonRpcRequest>(), It.IsAny<CancellationToken>()), Times.Once);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task CreateSamplingHandler_ShouldHandleResourceMessages()
|
||||
public async Task ReadResourceAsync_Template_Forwards_To_McpClient_SendRequestAsync()
|
||||
{
|
||||
// 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 mockClient = new Mock<McpClient> { CallBase = true };
|
||||
|
||||
var requestParams = new CreateMessageRequestParams
|
||||
{
|
||||
Messages =
|
||||
[
|
||||
new SamplingMessage
|
||||
{
|
||||
Role = Role.User,
|
||||
Content = new EmbeddedResourceBlock { Resource = resource },
|
||||
}
|
||||
],
|
||||
MaxTokens = 100
|
||||
};
|
||||
var resultPayload = new ReadResourceResult { Contents = [] };
|
||||
|
||||
var cancellationToken = CancellationToken.None;
|
||||
var expectedResponse = new[] {
|
||||
new ChatResponseUpdate
|
||||
mockClient
|
||||
.Setup(c => c.SendRequestAsync(It.IsAny<JsonRpcRequest>(), It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(new JsonRpcResponse
|
||||
{
|
||||
ModelId = "test-model",
|
||||
FinishReason = ChatFinishReason.Stop,
|
||||
AuthorName = "bot",
|
||||
Role = ChatRole.Assistant,
|
||||
Contents =
|
||||
[
|
||||
resource.ToAIContent()
|
||||
]
|
||||
}
|
||||
}.ToAsyncEnumerable();
|
||||
Result = JsonSerializer.SerializeToNode(resultPayload, McpJsonUtilities.DefaultOptions),
|
||||
});
|
||||
|
||||
mockChatClient
|
||||
.Setup(client => client.GetStreamingResponseAsync(It.IsAny<IEnumerable<ChatMessage>>(), It.IsAny<ChatOptions>(), cancellationToken))
|
||||
.Returns(expectedResponse);
|
||||
IMcpClient client = mockClient.Object;
|
||||
|
||||
var handler = McpClientExtensions.CreateSamplingHandler(mockChatClient.Object);
|
||||
var result = await client.ReadResourceAsync("mcp://resource/{id}", new Dictionary<string, object?> { ["id"] = 1 }, TestContext.Current.CancellationToken);
|
||||
|
||||
// Act
|
||||
var result = await handler(requestParams, Mock.Of<IProgress<ProgressNotificationValue>>(), cancellationToken);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(result);
|
||||
Assert.Equal("test-model", result.Model);
|
||||
Assert.Equal(Role.Assistant, result.Role);
|
||||
Assert.Equal("endTurn", result.StopReason);
|
||||
mockClient.Verify(c => c.SendRequestAsync(It.IsAny<JsonRpcRequest>(), It.IsAny<CancellationToken>()), Times.Once);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ListToolsAsync_AllToolsReturned()
|
||||
{
|
||||
await using 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() { ["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()
|
||||
{
|
||||
await using 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() { ["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);
|
||||
await using 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() };
|
||||
await using IMcpClient client = await CreateMcpClientForServer();
|
||||
|
||||
var tool = (await client.ListToolsAsync(emptyOptions, TestContext.Current.CancellationToken)).First();
|
||||
await Assert.ThrowsAsync<NotSupportedException>(async () => await tool.InvokeAsync(new() { ["i"] = 42 }, TestContext.Current.CancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SendRequestAsync_HonorsJsonSerializerOptions()
|
||||
{
|
||||
JsonSerializerOptions emptyOptions = new() { TypeInfoResolver = JsonTypeInfoResolver.Combine() };
|
||||
await using IMcpClient client = await CreateMcpClientForServer();
|
||||
|
||||
await Assert.ThrowsAsync<NotSupportedException>(async () => await client.SendRequestAsync<CallToolRequestParams, CallToolResult>("Method4", new() { Name = "tool" }, emptyOptions, cancellationToken: TestContext.Current.CancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SendNotificationAsync_HonorsJsonSerializerOptions()
|
||||
{
|
||||
JsonSerializerOptions emptyOptions = new() { TypeInfoResolver = JsonTypeInfoResolver.Combine() };
|
||||
await using 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() };
|
||||
await using IMcpClient client = await CreateMcpClientForServer();
|
||||
|
||||
await Assert.ThrowsAsync<NotSupportedException>(async () => await 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);
|
||||
await using 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);
|
||||
await using 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 WithProgress_ProgressReported()
|
||||
{
|
||||
const int TotalNotifications = 3;
|
||||
int remainingProgress = TotalNotifications;
|
||||
TaskCompletionSource<bool> allProgressReceived = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
|
||||
Server.ServerOptions.Capabilities?.Tools?.ToolCollection?.Add(McpServerTool.Create(async (IProgress<ProgressNotificationValue> progress) =>
|
||||
{
|
||||
for (int i = 0; i < TotalNotifications; i++)
|
||||
{
|
||||
progress.Report(new ProgressNotificationValue { Progress = i * 10, Message = "making progress" });
|
||||
await Task.Delay(1);
|
||||
}
|
||||
|
||||
await allProgressReceived.Task;
|
||||
|
||||
return 42;
|
||||
}, new() { Name = "ProgressReporter" }));
|
||||
|
||||
await using IMcpClient client = await CreateMcpClientForServer();
|
||||
|
||||
var tool = (await client.ListToolsAsync(cancellationToken: TestContext.Current.CancellationToken)).First(t => t.Name == "ProgressReporter");
|
||||
|
||||
IProgress<ProgressNotificationValue> progress = new SynchronousProgress(value =>
|
||||
{
|
||||
Assert.True(value.Progress >= 0 && value.Progress <= 100);
|
||||
Assert.Equal("making progress", value.Message);
|
||||
if (Interlocked.Decrement(ref remainingProgress) == 0)
|
||||
{
|
||||
allProgressReceived.SetResult(true);
|
||||
}
|
||||
});
|
||||
|
||||
Assert.Throws<ArgumentNullException>("progress", () => tool.WithProgress(null!));
|
||||
|
||||
var result = await tool.WithProgress(progress).InvokeAsync(cancellationToken: TestContext.Current.CancellationToken);
|
||||
Assert.Contains("42", result?.ToString());
|
||||
}
|
||||
|
||||
private sealed class SynchronousProgress(Action<ProgressNotificationValue> callback) : IProgress<ProgressNotificationValue>
|
||||
{
|
||||
public void Report(ProgressNotificationValue value) => callback(value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AsClientLoggerProvider_MessagesSentToClient()
|
||||
{
|
||||
await using IMcpClient client = await CreateMcpClientForServer();
|
||||
|
||||
ILoggerProvider loggerProvider = Server.AsClientLoggerProvider();
|
||||
Assert.Throws<ArgumentNullException>("categoryName", () => loggerProvider.CreateLogger(null!));
|
||||
|
||||
ILogger logger = loggerProvider.CreateLogger("TestLogger");
|
||||
Assert.NotNull(logger);
|
||||
|
||||
Assert.Null(logger.BeginScope(""));
|
||||
|
||||
Assert.Null(Server.LoggingLevel);
|
||||
Assert.False(logger.IsEnabled(LogLevel.Trace));
|
||||
Assert.False(logger.IsEnabled(LogLevel.Debug));
|
||||
Assert.False(logger.IsEnabled(LogLevel.Information));
|
||||
Assert.False(logger.IsEnabled(LogLevel.Warning));
|
||||
Assert.False(logger.IsEnabled(LogLevel.Error));
|
||||
Assert.False(logger.IsEnabled(LogLevel.Critical));
|
||||
|
||||
await client.SetLoggingLevel(LoggingLevel.Info, TestContext.Current.CancellationToken);
|
||||
|
||||
DateTime start = DateTime.UtcNow;
|
||||
while (Server.LoggingLevel is null)
|
||||
{
|
||||
await Task.Delay(1, TestContext.Current.CancellationToken);
|
||||
Assert.True(DateTime.UtcNow - start < TimeSpan.FromSeconds(10), "Timed out waiting for logging level to be set");
|
||||
}
|
||||
|
||||
Assert.Equal(LoggingLevel.Info, Server.LoggingLevel);
|
||||
Assert.False(logger.IsEnabled(LogLevel.Trace));
|
||||
Assert.False(logger.IsEnabled(LogLevel.Debug));
|
||||
Assert.True(logger.IsEnabled(LogLevel.Information));
|
||||
Assert.True(logger.IsEnabled(LogLevel.Warning));
|
||||
Assert.True(logger.IsEnabled(LogLevel.Error));
|
||||
Assert.True(logger.IsEnabled(LogLevel.Critical));
|
||||
|
||||
List<string> data = [];
|
||||
var channel = Channel.CreateUnbounded<LoggingMessageNotificationParams?>();
|
||||
|
||||
await using (client.RegisterNotificationHandler(NotificationMethods.LoggingMessageNotification,
|
||||
(notification, cancellationToken) =>
|
||||
{
|
||||
Assert.True(channel.Writer.TryWrite(JsonSerializer.Deserialize<LoggingMessageNotificationParams>(notification.Params, McpJsonUtilities.DefaultOptions)));
|
||||
return default;
|
||||
}))
|
||||
{
|
||||
logger.LogTrace("Trace {Message}", "message");
|
||||
logger.LogDebug("Debug {Message}", "message");
|
||||
logger.LogInformation("Information {Message}", "message");
|
||||
logger.LogWarning("Warning {Message}", "message");
|
||||
logger.LogError("Error {Message}", "message");
|
||||
logger.LogCritical("Critical {Message}", "message");
|
||||
|
||||
for (int i = 0; i < 4; i++)
|
||||
{
|
||||
var m = await channel.Reader.ReadAsync(TestContext.Current.CancellationToken);
|
||||
Assert.NotNull(m);
|
||||
Assert.NotNull(m.Data);
|
||||
|
||||
Assert.Equal("TestLogger", m.Logger);
|
||||
|
||||
string ? s = JsonSerializer.Deserialize<string>(m.Data.Value, McpJsonUtilities.DefaultOptions);
|
||||
Assert.NotNull(s);
|
||||
|
||||
if (s.Contains("Information"))
|
||||
{
|
||||
Assert.Equal(LoggingLevel.Info, m.Level);
|
||||
}
|
||||
else if (s.Contains("Warning"))
|
||||
{
|
||||
Assert.Equal(LoggingLevel.Warning, m.Level);
|
||||
}
|
||||
else if (s.Contains("Error"))
|
||||
{
|
||||
Assert.Equal(LoggingLevel.Error, m.Level);
|
||||
}
|
||||
else if (s.Contains("Critical"))
|
||||
{
|
||||
Assert.Equal(LoggingLevel.Critical, m.Level);
|
||||
}
|
||||
|
||||
data.Add(s);
|
||||
}
|
||||
|
||||
channel.Writer.Complete();
|
||||
}
|
||||
|
||||
Assert.False(await channel.Reader.WaitToReadAsync(TestContext.Current.CancellationToken));
|
||||
Assert.Equal(
|
||||
[
|
||||
"Critical message",
|
||||
"Error message",
|
||||
"Information message",
|
||||
"Warning message",
|
||||
],
|
||||
data.OrderBy(s => s));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -73,7 +73,7 @@ public partial class McpClientResourceTemplateTests : ClientServerTestBase
|
|||
public async Task UriTemplate_InputsProduceExpectedOutputs(
|
||||
IReadOnlyDictionary<string, object?> variables, string uriTemplate, object expected)
|
||||
{
|
||||
await using IMcpClient client = await CreateMcpClientForServer();
|
||||
await using McpClient client = await CreateMcpClientForServer();
|
||||
|
||||
var result = await client.ReadResourceAsync(uriTemplate, variables, TestContext.Current.CancellationToken);
|
||||
Assert.NotNull(result);
|
||||
|
|
|
|||
471
tests/ModelContextProtocol.Tests/Client/McpClientTests.cs
Normal file
471
tests/ModelContextProtocol.Tests/Client/McpClientTests.cs
Normal file
|
|
@ -0,0 +1,471 @@
|
|||
using Microsoft.Extensions.AI;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using ModelContextProtocol.Client;
|
||||
using ModelContextProtocol.Protocol;
|
||||
using ModelContextProtocol.Server;
|
||||
using Moq;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization.Metadata;
|
||||
using System.Threading.Channels;
|
||||
|
||||
namespace ModelContextProtocol.Tests.Client;
|
||||
|
||||
public class McpClientTests : ClientServerTestBase
|
||||
{
|
||||
public McpClientTests(ITestOutputHelper outputHelper)
|
||||
: base(outputHelper)
|
||||
{
|
||||
}
|
||||
|
||||
protected override void ConfigureServices(ServiceCollection services, IMcpServerBuilder mcpServerBuilder)
|
||||
{
|
||||
for (int f = 0; f < 10; f++)
|
||||
{
|
||||
string name = $"Method{f}";
|
||||
mcpServerBuilder.WithTools([McpServerTool.Create((int i) => $"{name} Result {i}", new() { Name = name })]);
|
||||
}
|
||||
mcpServerBuilder.WithTools([McpServerTool.Create([McpServerTool(Destructive = false, OpenWorld = true)] (string i) => $"{i} Result", new() { Name = "ValuesSetViaAttr" })]);
|
||||
mcpServerBuilder.WithTools([McpServerTool.Create([McpServerTool(Destructive = false, OpenWorld = true)] (string i) => $"{i} Result", new() { Name = "ValuesSetViaOptions", Destructive = true, OpenWorld = false, ReadOnly = true })]);
|
||||
}
|
||||
|
||||
[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 TextContentBlock { Text = "Hello" }
|
||||
}
|
||||
],
|
||||
Temperature = temperature,
|
||||
MaxTokens = maxTokens,
|
||||
};
|
||||
|
||||
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 as TextContentBlock)?.Text);
|
||||
Assert.Equal("test-model", result.Model);
|
||||
Assert.Equal(Role.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 ImageContentBlock
|
||||
{
|
||||
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 as ImageContentBlock)?.Data);
|
||||
Assert.Equal("test-model", result.Model);
|
||||
Assert.Equal(Role.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 EmbeddedResourceBlock { 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(Role.Assistant, result.Role);
|
||||
Assert.Equal("endTurn", result.StopReason);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ListToolsAsync_AllToolsReturned()
|
||||
{
|
||||
await using McpClient 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() { ["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()
|
||||
{
|
||||
await using McpClient client = await CreateMcpClientForServer();
|
||||
|
||||
await foreach (var tool in client.EnumerateToolsAsync(cancellationToken: TestContext.Current.CancellationToken))
|
||||
{
|
||||
if (tool.Name == "Method4")
|
||||
{
|
||||
var result = await tool.InvokeAsync(new() { ["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);
|
||||
await using McpClient 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() };
|
||||
await using McpClient client = await CreateMcpClientForServer();
|
||||
|
||||
var tool = (await client.ListToolsAsync(emptyOptions, TestContext.Current.CancellationToken)).First();
|
||||
await Assert.ThrowsAsync<NotSupportedException>(async () => await tool.InvokeAsync(new() { ["i"] = 42 }, TestContext.Current.CancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SendRequestAsync_HonorsJsonSerializerOptions()
|
||||
{
|
||||
JsonSerializerOptions emptyOptions = new() { TypeInfoResolver = JsonTypeInfoResolver.Combine() };
|
||||
await using McpClient client = await CreateMcpClientForServer();
|
||||
|
||||
await Assert.ThrowsAsync<NotSupportedException>(async () => await client.SendRequestAsync<CallToolRequestParams, CallToolResult>("Method4", new() { Name = "tool" }, emptyOptions, cancellationToken: TestContext.Current.CancellationToken));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SendNotificationAsync_HonorsJsonSerializerOptions()
|
||||
{
|
||||
JsonSerializerOptions emptyOptions = new() { TypeInfoResolver = JsonTypeInfoResolver.Combine() };
|
||||
await using McpClient 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() };
|
||||
await using McpClient client = await CreateMcpClientForServer();
|
||||
|
||||
await Assert.ThrowsAsync<NotSupportedException>(async () => await 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);
|
||||
await using McpClient 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);
|
||||
await using McpClient 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 WithProgress_ProgressReported()
|
||||
{
|
||||
const int TotalNotifications = 3;
|
||||
int remainingProgress = TotalNotifications;
|
||||
TaskCompletionSource<bool> allProgressReceived = new(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
|
||||
Server.ServerOptions.Capabilities?.Tools?.ToolCollection?.Add(McpServerTool.Create(async (IProgress<ProgressNotificationValue> progress) =>
|
||||
{
|
||||
for (int i = 0; i < TotalNotifications; i++)
|
||||
{
|
||||
progress.Report(new ProgressNotificationValue { Progress = i * 10, Message = "making progress" });
|
||||
await Task.Delay(1);
|
||||
}
|
||||
|
||||
await allProgressReceived.Task;
|
||||
|
||||
return 42;
|
||||
}, new() { Name = "ProgressReporter" }));
|
||||
|
||||
await using McpClient client = await CreateMcpClientForServer();
|
||||
|
||||
var tool = (await client.ListToolsAsync(cancellationToken: TestContext.Current.CancellationToken)).First(t => t.Name == "ProgressReporter");
|
||||
|
||||
IProgress<ProgressNotificationValue> progress = new SynchronousProgress(value =>
|
||||
{
|
||||
Assert.True(value.Progress >= 0 && value.Progress <= 100);
|
||||
Assert.Equal("making progress", value.Message);
|
||||
if (Interlocked.Decrement(ref remainingProgress) == 0)
|
||||
{
|
||||
allProgressReceived.SetResult(true);
|
||||
}
|
||||
});
|
||||
|
||||
Assert.Throws<ArgumentNullException>("progress", () => tool.WithProgress(null!));
|
||||
|
||||
var result = await tool.WithProgress(progress).InvokeAsync(cancellationToken: TestContext.Current.CancellationToken);
|
||||
Assert.Contains("42", result?.ToString());
|
||||
}
|
||||
|
||||
private sealed class SynchronousProgress(Action<ProgressNotificationValue> callback) : IProgress<ProgressNotificationValue>
|
||||
{
|
||||
public void Report(ProgressNotificationValue value) => callback(value);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AsClientLoggerProvider_MessagesSentToClient()
|
||||
{
|
||||
await using McpClient client = await CreateMcpClientForServer();
|
||||
|
||||
ILoggerProvider loggerProvider = Server.AsClientLoggerProvider();
|
||||
Assert.Throws<ArgumentNullException>("categoryName", () => loggerProvider.CreateLogger(null!));
|
||||
|
||||
ILogger logger = loggerProvider.CreateLogger("TestLogger");
|
||||
Assert.NotNull(logger);
|
||||
|
||||
Assert.Null(logger.BeginScope(""));
|
||||
|
||||
Assert.Null(Server.LoggingLevel);
|
||||
Assert.False(logger.IsEnabled(LogLevel.Trace));
|
||||
Assert.False(logger.IsEnabled(LogLevel.Debug));
|
||||
Assert.False(logger.IsEnabled(LogLevel.Information));
|
||||
Assert.False(logger.IsEnabled(LogLevel.Warning));
|
||||
Assert.False(logger.IsEnabled(LogLevel.Error));
|
||||
Assert.False(logger.IsEnabled(LogLevel.Critical));
|
||||
|
||||
await client.SetLoggingLevel(LoggingLevel.Info, TestContext.Current.CancellationToken);
|
||||
|
||||
DateTime start = DateTime.UtcNow;
|
||||
while (Server.LoggingLevel is null)
|
||||
{
|
||||
await Task.Delay(1, TestContext.Current.CancellationToken);
|
||||
Assert.True(DateTime.UtcNow - start < TimeSpan.FromSeconds(10), "Timed out waiting for logging level to be set");
|
||||
}
|
||||
|
||||
Assert.Equal(LoggingLevel.Info, Server.LoggingLevel);
|
||||
Assert.False(logger.IsEnabled(LogLevel.Trace));
|
||||
Assert.False(logger.IsEnabled(LogLevel.Debug));
|
||||
Assert.True(logger.IsEnabled(LogLevel.Information));
|
||||
Assert.True(logger.IsEnabled(LogLevel.Warning));
|
||||
Assert.True(logger.IsEnabled(LogLevel.Error));
|
||||
Assert.True(logger.IsEnabled(LogLevel.Critical));
|
||||
|
||||
List<string> data = [];
|
||||
var channel = Channel.CreateUnbounded<LoggingMessageNotificationParams?>();
|
||||
|
||||
await using (client.RegisterNotificationHandler(NotificationMethods.LoggingMessageNotification,
|
||||
(notification, cancellationToken) =>
|
||||
{
|
||||
Assert.True(channel.Writer.TryWrite(JsonSerializer.Deserialize<LoggingMessageNotificationParams>(notification.Params, McpJsonUtilities.DefaultOptions)));
|
||||
return default;
|
||||
}))
|
||||
{
|
||||
logger.LogTrace("Trace {Message}", "message");
|
||||
logger.LogDebug("Debug {Message}", "message");
|
||||
logger.LogInformation("Information {Message}", "message");
|
||||
logger.LogWarning("Warning {Message}", "message");
|
||||
logger.LogError("Error {Message}", "message");
|
||||
logger.LogCritical("Critical {Message}", "message");
|
||||
|
||||
for (int i = 0; i < 4; i++)
|
||||
{
|
||||
var m = await channel.Reader.ReadAsync(TestContext.Current.CancellationToken);
|
||||
Assert.NotNull(m);
|
||||
Assert.NotNull(m.Data);
|
||||
|
||||
Assert.Equal("TestLogger", m.Logger);
|
||||
|
||||
string ? s = JsonSerializer.Deserialize<string>(m.Data.Value, McpJsonUtilities.DefaultOptions);
|
||||
Assert.NotNull(s);
|
||||
|
||||
if (s.Contains("Information"))
|
||||
{
|
||||
Assert.Equal(LoggingLevel.Info, m.Level);
|
||||
}
|
||||
else if (s.Contains("Warning"))
|
||||
{
|
||||
Assert.Equal(LoggingLevel.Warning, m.Level);
|
||||
}
|
||||
else if (s.Contains("Error"))
|
||||
{
|
||||
Assert.Equal(LoggingLevel.Error, m.Level);
|
||||
}
|
||||
else if (s.Contains("Critical"))
|
||||
{
|
||||
Assert.Equal(LoggingLevel.Critical, m.Level);
|
||||
}
|
||||
|
||||
data.Add(s);
|
||||
}
|
||||
|
||||
channel.Writer.Complete();
|
||||
}
|
||||
|
||||
Assert.False(await channel.Reader.WaitToReadAsync(TestContext.Current.CancellationToken));
|
||||
Assert.Equal(
|
||||
[
|
||||
"Critical message",
|
||||
"Error message",
|
||||
"Information message",
|
||||
"Warning message",
|
||||
],
|
||||
data.OrderBy(s => s));
|
||||
}
|
||||
}
|
||||
|
|
@ -41,8 +41,8 @@ public class ClientIntegrationTestFixture
|
|||
_loggerFactory = loggerFactory;
|
||||
}
|
||||
|
||||
public Task<IMcpClient> CreateClientAsync(string clientId, McpClientOptions? clientOptions = null) =>
|
||||
McpClientFactory.CreateAsync(new StdioClientTransport(clientId switch
|
||||
public Task<McpClient> CreateClientAsync(string clientId, McpClientOptions? clientOptions = null) =>
|
||||
McpClient.CreateAsync(new StdioClientTransport(clientId switch
|
||||
{
|
||||
"everything" => EverythingServerTransportOptions,
|
||||
"test_server" => TestServerTransportOptions,
|
||||
|
|
|
|||
|
|
@ -471,7 +471,7 @@ public partial class ClientIntegrationTests : LoggedTest, IClassFixture<ClientIn
|
|||
ClientInfo = new() { Name = "IntegrationTestClient", Version = "1.0.0" }
|
||||
};
|
||||
|
||||
await using var client = await McpClientFactory.CreateAsync(
|
||||
await using var client = await McpClient.CreateAsync(
|
||||
new StdioClientTransport(stdioOptions),
|
||||
clientOptions,
|
||||
loggerFactory: LoggerFactory,
|
||||
|
|
@ -495,7 +495,7 @@ public partial class ClientIntegrationTests : LoggedTest, IClassFixture<ClientIn
|
|||
public async Task ListToolsAsync_UsingEverythingServer_ToolsAreProperlyCalled()
|
||||
{
|
||||
// Get the MCP client and tools from it.
|
||||
await using var client = await McpClientFactory.CreateAsync(
|
||||
await using var client = await McpClient.CreateAsync(
|
||||
new StdioClientTransport(_fixture.EverythingServerTransportOptions),
|
||||
cancellationToken: TestContext.Current.CancellationToken);
|
||||
var mappedTools = await client.ListToolsAsync(cancellationToken: TestContext.Current.CancellationToken);
|
||||
|
|
@ -527,7 +527,7 @@ public partial class ClientIntegrationTests : LoggedTest, IClassFixture<ClientIn
|
|||
var samplingHandler = new OpenAIClient(s_openAIKey).GetChatClient("gpt-4o-mini")
|
||||
.AsIChatClient()
|
||||
.CreateSamplingHandler();
|
||||
await using var client = await McpClientFactory.CreateAsync(new StdioClientTransport(_fixture.EverythingServerTransportOptions), new()
|
||||
await using var client = await McpClient.CreateAsync(new StdioClientTransport(_fixture.EverythingServerTransportOptions), new()
|
||||
{
|
||||
Capabilities = new()
|
||||
{
|
||||
|
|
|
|||
|
|
@ -29,11 +29,11 @@ public abstract class ClientServerTestBase : LoggedTest, IAsyncDisposable
|
|||
ServiceProvider = sc.BuildServiceProvider(validateScopes: true);
|
||||
|
||||
_cts = CancellationTokenSource.CreateLinkedTokenSource(TestContext.Current.CancellationToken);
|
||||
Server = ServiceProvider.GetRequiredService<IMcpServer>();
|
||||
Server = ServiceProvider.GetRequiredService<McpServer>();
|
||||
_serverTask = Server.RunAsync(_cts.Token);
|
||||
}
|
||||
|
||||
protected IMcpServer Server { get; }
|
||||
protected McpServer Server { get; }
|
||||
|
||||
protected IServiceProvider ServiceProvider { get; }
|
||||
|
||||
|
|
@ -63,9 +63,9 @@ public abstract class ClientServerTestBase : LoggedTest, IAsyncDisposable
|
|||
Dispose();
|
||||
}
|
||||
|
||||
protected async Task<IMcpClient> CreateMcpClientForServer(McpClientOptions? clientOptions = null)
|
||||
protected async Task<McpClient> CreateMcpClientForServer(McpClientOptions? clientOptions = null)
|
||||
{
|
||||
return await McpClientFactory.CreateAsync(
|
||||
return await McpClient.CreateAsync(
|
||||
new StreamClientTransport(
|
||||
serverInput: _clientToServerPipe.Writer.AsStream(),
|
||||
_serverToClientPipe.Reader.AsStream(),
|
||||
|
|
|
|||
|
|
@ -129,7 +129,7 @@ public class McpServerBuilderExtensionsFilterTests : ClientServerTestBase
|
|||
[Fact]
|
||||
public async Task AddListResourceTemplatesFilter_Logs_When_ListResourceTemplates_Called()
|
||||
{
|
||||
await using IMcpClient client = await CreateMcpClientForServer();
|
||||
await using McpClient client = await CreateMcpClientForServer();
|
||||
|
||||
await client.ListResourceTemplatesAsync(cancellationToken: TestContext.Current.CancellationToken);
|
||||
|
||||
|
|
@ -141,7 +141,7 @@ public class McpServerBuilderExtensionsFilterTests : ClientServerTestBase
|
|||
[Fact]
|
||||
public async Task AddListToolsFilter_Logs_When_ListTools_Called()
|
||||
{
|
||||
await using IMcpClient client = await CreateMcpClientForServer();
|
||||
await using McpClient client = await CreateMcpClientForServer();
|
||||
|
||||
await client.ListToolsAsync(cancellationToken: TestContext.Current.CancellationToken);
|
||||
|
||||
|
|
@ -153,7 +153,7 @@ public class McpServerBuilderExtensionsFilterTests : ClientServerTestBase
|
|||
[Fact]
|
||||
public async Task AddCallToolFilter_Logs_When_CallTool_Called()
|
||||
{
|
||||
await using IMcpClient client = await CreateMcpClientForServer();
|
||||
await using McpClient client = await CreateMcpClientForServer();
|
||||
|
||||
await client.CallToolAsync("test_tool_method", cancellationToken: TestContext.Current.CancellationToken);
|
||||
|
||||
|
|
@ -165,7 +165,7 @@ public class McpServerBuilderExtensionsFilterTests : ClientServerTestBase
|
|||
[Fact]
|
||||
public async Task AddListPromptsFilter_Logs_When_ListPrompts_Called()
|
||||
{
|
||||
await using IMcpClient client = await CreateMcpClientForServer();
|
||||
await using McpClient client = await CreateMcpClientForServer();
|
||||
|
||||
await client.ListPromptsAsync(cancellationToken: TestContext.Current.CancellationToken);
|
||||
|
||||
|
|
@ -177,7 +177,7 @@ public class McpServerBuilderExtensionsFilterTests : ClientServerTestBase
|
|||
[Fact]
|
||||
public async Task AddGetPromptFilter_Logs_When_GetPrompt_Called()
|
||||
{
|
||||
await using IMcpClient client = await CreateMcpClientForServer();
|
||||
await using McpClient client = await CreateMcpClientForServer();
|
||||
|
||||
await client.GetPromptAsync("test_prompt_method", cancellationToken: TestContext.Current.CancellationToken);
|
||||
|
||||
|
|
@ -189,7 +189,7 @@ public class McpServerBuilderExtensionsFilterTests : ClientServerTestBase
|
|||
[Fact]
|
||||
public async Task AddListResourcesFilter_Logs_When_ListResources_Called()
|
||||
{
|
||||
await using IMcpClient client = await CreateMcpClientForServer();
|
||||
await using McpClient client = await CreateMcpClientForServer();
|
||||
|
||||
await client.ListResourcesAsync(cancellationToken: TestContext.Current.CancellationToken);
|
||||
|
||||
|
|
@ -201,7 +201,7 @@ public class McpServerBuilderExtensionsFilterTests : ClientServerTestBase
|
|||
[Fact]
|
||||
public async Task AddReadResourceFilter_Logs_When_ReadResource_Called()
|
||||
{
|
||||
await using IMcpClient client = await CreateMcpClientForServer();
|
||||
await using McpClient client = await CreateMcpClientForServer();
|
||||
|
||||
await client.ReadResourceAsync("test://resource/123", cancellationToken: TestContext.Current.CancellationToken);
|
||||
|
||||
|
|
@ -213,7 +213,7 @@ public class McpServerBuilderExtensionsFilterTests : ClientServerTestBase
|
|||
[Fact]
|
||||
public async Task AddCompleteFilter_Logs_When_Complete_Called()
|
||||
{
|
||||
await using IMcpClient client = await CreateMcpClientForServer();
|
||||
await using McpClient client = await CreateMcpClientForServer();
|
||||
|
||||
var reference = new PromptReference { Name = "test_prompt_method" };
|
||||
await client.CompleteAsync(reference, "argument", "value", cancellationToken: TestContext.Current.CancellationToken);
|
||||
|
|
@ -226,7 +226,7 @@ public class McpServerBuilderExtensionsFilterTests : ClientServerTestBase
|
|||
[Fact]
|
||||
public async Task AddSubscribeToResourcesFilter_Logs_When_SubscribeToResources_Called()
|
||||
{
|
||||
await using IMcpClient client = await CreateMcpClientForServer();
|
||||
await using McpClient client = await CreateMcpClientForServer();
|
||||
|
||||
await client.SubscribeToResourceAsync("test://resource/123", cancellationToken: TestContext.Current.CancellationToken);
|
||||
|
||||
|
|
@ -238,7 +238,7 @@ public class McpServerBuilderExtensionsFilterTests : ClientServerTestBase
|
|||
[Fact]
|
||||
public async Task AddUnsubscribeFromResourcesFilter_Logs_When_UnsubscribeFromResources_Called()
|
||||
{
|
||||
await using IMcpClient client = await CreateMcpClientForServer();
|
||||
await using McpClient client = await CreateMcpClientForServer();
|
||||
|
||||
await client.UnsubscribeFromResourceAsync("test://resource/123", cancellationToken: TestContext.Current.CancellationToken);
|
||||
|
||||
|
|
@ -250,7 +250,7 @@ public class McpServerBuilderExtensionsFilterTests : ClientServerTestBase
|
|||
[Fact]
|
||||
public async Task AddSetLoggingLevelFilter_Logs_When_SetLoggingLevel_Called()
|
||||
{
|
||||
await using IMcpClient client = await CreateMcpClientForServer();
|
||||
await using McpClient client = await CreateMcpClientForServer();
|
||||
|
||||
await client.SetLoggingLevel(LoggingLevel.Info, cancellationToken: TestContext.Current.CancellationToken);
|
||||
|
||||
|
|
@ -262,7 +262,7 @@ public class McpServerBuilderExtensionsFilterTests : ClientServerTestBase
|
|||
[Fact]
|
||||
public async Task AddListToolsFilter_Multiple_Filters_Log_In_Expected_Order()
|
||||
{
|
||||
await using IMcpClient client = await CreateMcpClientForServer();
|
||||
await using McpClient client = await CreateMcpClientForServer();
|
||||
|
||||
await client.ListToolsAsync(cancellationToken: TestContext.Current.CancellationToken);
|
||||
|
||||
|
|
|
|||
|
|
@ -98,7 +98,7 @@ public partial class McpServerBuilderExtensionsPromptsTests : ClientServerTestBa
|
|||
[Fact]
|
||||
public async Task Can_List_And_Call_Registered_Prompts()
|
||||
{
|
||||
await using IMcpClient client = await CreateMcpClientForServer();
|
||||
await using McpClient client = await CreateMcpClientForServer();
|
||||
|
||||
var prompts = await client.ListPromptsAsync(TestContext.Current.CancellationToken);
|
||||
Assert.Equal(6, prompts.Count);
|
||||
|
|
@ -127,7 +127,7 @@ public partial class McpServerBuilderExtensionsPromptsTests : ClientServerTestBa
|
|||
[Fact]
|
||||
public async Task Can_Be_Notified_Of_Prompt_Changes()
|
||||
{
|
||||
await using IMcpClient client = await CreateMcpClientForServer();
|
||||
await using McpClient client = await CreateMcpClientForServer();
|
||||
|
||||
var prompts = await client.ListPromptsAsync(TestContext.Current.CancellationToken);
|
||||
Assert.Equal(6, prompts.Count);
|
||||
|
|
@ -168,7 +168,7 @@ public partial class McpServerBuilderExtensionsPromptsTests : ClientServerTestBa
|
|||
[Fact]
|
||||
public async Task TitleAttributeProperty_PropagatedToTitle()
|
||||
{
|
||||
await using IMcpClient client = await CreateMcpClientForServer();
|
||||
await using McpClient client = await CreateMcpClientForServer();
|
||||
|
||||
var prompts = await client.ListPromptsAsync(cancellationToken: TestContext.Current.CancellationToken);
|
||||
Assert.NotNull(prompts);
|
||||
|
|
@ -182,7 +182,7 @@ public partial class McpServerBuilderExtensionsPromptsTests : ClientServerTestBa
|
|||
[Fact]
|
||||
public async Task Throws_When_Prompt_Fails()
|
||||
{
|
||||
await using IMcpClient client = await CreateMcpClientForServer();
|
||||
await using McpClient client = await CreateMcpClientForServer();
|
||||
|
||||
await Assert.ThrowsAsync<McpException>(async () => await client.GetPromptAsync(
|
||||
nameof(SimplePrompts.ThrowsException),
|
||||
|
|
@ -192,7 +192,7 @@ public partial class McpServerBuilderExtensionsPromptsTests : ClientServerTestBa
|
|||
[Fact]
|
||||
public async Task Throws_Exception_On_Unknown_Prompt()
|
||||
{
|
||||
await using IMcpClient client = await CreateMcpClientForServer();
|
||||
await using McpClient client = await CreateMcpClientForServer();
|
||||
|
||||
var e = await Assert.ThrowsAsync<McpException>(async () => await client.GetPromptAsync(
|
||||
"NotRegisteredPrompt",
|
||||
|
|
@ -204,7 +204,7 @@ public partial class McpServerBuilderExtensionsPromptsTests : ClientServerTestBa
|
|||
[Fact]
|
||||
public async Task Throws_Exception_Missing_Parameter()
|
||||
{
|
||||
await using IMcpClient client = await CreateMcpClientForServer();
|
||||
await using McpClient client = await CreateMcpClientForServer();
|
||||
|
||||
var e = await Assert.ThrowsAsync<McpException>(async () => await client.GetPromptAsync(
|
||||
"returns_chat_messages",
|
||||
|
|
@ -238,7 +238,7 @@ public partial class McpServerBuilderExtensionsPromptsTests : ClientServerTestBa
|
|||
sc.AddMcpServer().WithPrompts(target);
|
||||
|
||||
McpServerPrompt prompt = sc.BuildServiceProvider().GetServices<McpServerPrompt>().First(t => t.ProtocolPrompt.Name == "returns_string");
|
||||
var result = await prompt.GetAsync(new RequestContext<GetPromptRequestParams>(new Mock<IMcpServer>().Object, new JsonRpcRequest { Method = "test", Id = new RequestId("1") })
|
||||
var result = await prompt.GetAsync(new RequestContext<GetPromptRequestParams>(new Mock<McpServer>().Object, new JsonRpcRequest { Method = "test", Id = new RequestId("1") })
|
||||
{
|
||||
Params = new GetPromptRequestParams
|
||||
{
|
||||
|
|
|
|||
|
|
@ -126,7 +126,7 @@ public partial class McpServerBuilderExtensionsResourcesTests : ClientServerTest
|
|||
[Fact]
|
||||
public async Task Can_List_And_Call_Registered_Resources()
|
||||
{
|
||||
await using IMcpClient client = await CreateMcpClientForServer();
|
||||
await using McpClient client = await CreateMcpClientForServer();
|
||||
|
||||
Assert.NotNull(client.ServerCapabilities.Resources);
|
||||
|
||||
|
|
@ -145,7 +145,7 @@ public partial class McpServerBuilderExtensionsResourcesTests : ClientServerTest
|
|||
[Fact]
|
||||
public async Task Can_List_And_Call_Registered_ResourceTemplates()
|
||||
{
|
||||
await using IMcpClient client = await CreateMcpClientForServer();
|
||||
await using McpClient client = await CreateMcpClientForServer();
|
||||
|
||||
var resources = await client.ListResourceTemplatesAsync(TestContext.Current.CancellationToken);
|
||||
Assert.Equal(3, resources.Count);
|
||||
|
|
@ -162,7 +162,7 @@ public partial class McpServerBuilderExtensionsResourcesTests : ClientServerTest
|
|||
[Fact]
|
||||
public async Task Can_Be_Notified_Of_Resource_Changes()
|
||||
{
|
||||
await using IMcpClient client = await CreateMcpClientForServer();
|
||||
await using McpClient client = await CreateMcpClientForServer();
|
||||
|
||||
var resources = await client.ListResourcesAsync(TestContext.Current.CancellationToken);
|
||||
Assert.Equal(5, resources.Count);
|
||||
|
|
@ -203,7 +203,7 @@ public partial class McpServerBuilderExtensionsResourcesTests : ClientServerTest
|
|||
[Fact]
|
||||
public async Task TitleAttributeProperty_PropagatedToTitle()
|
||||
{
|
||||
await using IMcpClient client = await CreateMcpClientForServer();
|
||||
await using McpClient client = await CreateMcpClientForServer();
|
||||
|
||||
var resources = await client.ListResourcesAsync(cancellationToken: TestContext.Current.CancellationToken);
|
||||
Assert.NotNull(resources);
|
||||
|
|
@ -221,7 +221,7 @@ public partial class McpServerBuilderExtensionsResourcesTests : ClientServerTest
|
|||
[Fact]
|
||||
public async Task Throws_When_Resource_Fails()
|
||||
{
|
||||
await using IMcpClient client = await CreateMcpClientForServer();
|
||||
await using McpClient client = await CreateMcpClientForServer();
|
||||
|
||||
await Assert.ThrowsAsync<McpException>(async () => await client.ReadResourceAsync(
|
||||
$"resource://mcp/{nameof(SimpleResources.ThrowsException)}",
|
||||
|
|
@ -231,7 +231,7 @@ public partial class McpServerBuilderExtensionsResourcesTests : ClientServerTest
|
|||
[Fact]
|
||||
public async Task Throws_Exception_On_Unknown_Resource()
|
||||
{
|
||||
await using IMcpClient client = await CreateMcpClientForServer();
|
||||
await using McpClient client = await CreateMcpClientForServer();
|
||||
|
||||
var e = await Assert.ThrowsAsync<McpException>(async () => await client.ReadResourceAsync(
|
||||
"test:///NotRegisteredResource",
|
||||
|
|
@ -265,7 +265,7 @@ public partial class McpServerBuilderExtensionsResourcesTests : ClientServerTest
|
|||
sc.AddMcpServer().WithResources(target);
|
||||
|
||||
McpServerResource resource = sc.BuildServiceProvider().GetServices<McpServerResource>().First(t => t.ProtocolResource?.Name == "returns_string");
|
||||
var result = await resource.ReadAsync(new RequestContext<ReadResourceRequestParams>(new Mock<IMcpServer>().Object, new JsonRpcRequest { Method = "test", Id = new RequestId("1") })
|
||||
var result = await resource.ReadAsync(new RequestContext<ReadResourceRequestParams>(new Mock<McpServer>().Object, new JsonRpcRequest { Method = "test", Id = new RequestId("1") })
|
||||
{
|
||||
Params = new()
|
||||
{
|
||||
|
|
|
|||
|
|
@ -127,7 +127,7 @@ public partial class McpServerBuilderExtensionsToolsTests : ClientServerTestBase
|
|||
[Fact]
|
||||
public async Task Can_List_Registered_Tools()
|
||||
{
|
||||
await using IMcpClient client = await CreateMcpClientForServer();
|
||||
await using McpClient client = await CreateMcpClientForServer();
|
||||
|
||||
var tools = await client.ListToolsAsync(cancellationToken: TestContext.Current.CancellationToken);
|
||||
Assert.Equal(16, tools.Count);
|
||||
|
|
@ -156,10 +156,10 @@ public partial class McpServerBuilderExtensionsToolsTests : ClientServerTestBase
|
|||
var stdoutPipe = new Pipe();
|
||||
|
||||
await using var transport = new StreamServerTransport(stdinPipe.Reader.AsStream(), stdoutPipe.Writer.AsStream());
|
||||
await using var server = McpServerFactory.Create(transport, options, loggerFactory, ServiceProvider);
|
||||
await using var server = McpServer.Create(transport, options, loggerFactory, ServiceProvider);
|
||||
var serverRunTask = server.RunAsync(TestContext.Current.CancellationToken);
|
||||
|
||||
await using (var client = await McpClientFactory.CreateAsync(
|
||||
await using (var client = await McpClient.CreateAsync(
|
||||
new StreamClientTransport(
|
||||
serverInput: stdinPipe.Writer.AsStream(),
|
||||
serverOutput: stdoutPipe.Reader.AsStream(),
|
||||
|
|
@ -191,7 +191,7 @@ public partial class McpServerBuilderExtensionsToolsTests : ClientServerTestBase
|
|||
[Fact]
|
||||
public async Task Can_Be_Notified_Of_Tool_Changes()
|
||||
{
|
||||
await using IMcpClient client = await CreateMcpClientForServer();
|
||||
await using McpClient client = await CreateMcpClientForServer();
|
||||
|
||||
var tools = await client.ListToolsAsync(cancellationToken: TestContext.Current.CancellationToken);
|
||||
Assert.Equal(16, tools.Count);
|
||||
|
|
@ -232,7 +232,7 @@ public partial class McpServerBuilderExtensionsToolsTests : ClientServerTestBase
|
|||
[Fact]
|
||||
public async Task Can_Call_Registered_Tool()
|
||||
{
|
||||
await using IMcpClient client = await CreateMcpClientForServer();
|
||||
await using McpClient client = await CreateMcpClientForServer();
|
||||
|
||||
var result = await client.CallToolAsync(
|
||||
"echo",
|
||||
|
|
@ -251,7 +251,7 @@ public partial class McpServerBuilderExtensionsToolsTests : ClientServerTestBase
|
|||
[Fact]
|
||||
public async Task Can_Call_Registered_Tool_With_Array_Result()
|
||||
{
|
||||
await using IMcpClient client = await CreateMcpClientForServer();
|
||||
await using McpClient client = await CreateMcpClientForServer();
|
||||
|
||||
var result = await client.CallToolAsync(
|
||||
"echo_array",
|
||||
|
|
@ -274,7 +274,7 @@ public partial class McpServerBuilderExtensionsToolsTests : ClientServerTestBase
|
|||
[Fact]
|
||||
public async Task Can_Call_Registered_Tool_With_Null_Result()
|
||||
{
|
||||
await using IMcpClient client = await CreateMcpClientForServer();
|
||||
await using McpClient client = await CreateMcpClientForServer();
|
||||
|
||||
var result = await client.CallToolAsync(
|
||||
"return_null",
|
||||
|
|
@ -288,7 +288,7 @@ public partial class McpServerBuilderExtensionsToolsTests : ClientServerTestBase
|
|||
[Fact]
|
||||
public async Task Can_Call_Registered_Tool_With_Json_Result()
|
||||
{
|
||||
await using IMcpClient client = await CreateMcpClientForServer();
|
||||
await using McpClient client = await CreateMcpClientForServer();
|
||||
|
||||
var result = await client.CallToolAsync(
|
||||
"return_json",
|
||||
|
|
@ -305,7 +305,7 @@ public partial class McpServerBuilderExtensionsToolsTests : ClientServerTestBase
|
|||
[Fact]
|
||||
public async Task Can_Call_Registered_Tool_With_Int_Result()
|
||||
{
|
||||
await using IMcpClient client = await CreateMcpClientForServer();
|
||||
await using McpClient client = await CreateMcpClientForServer();
|
||||
|
||||
var result = await client.CallToolAsync(
|
||||
"return_integer",
|
||||
|
|
@ -320,7 +320,7 @@ public partial class McpServerBuilderExtensionsToolsTests : ClientServerTestBase
|
|||
[Fact]
|
||||
public async Task Can_Call_Registered_Tool_And_Pass_ComplexType()
|
||||
{
|
||||
await using IMcpClient client = await CreateMcpClientForServer();
|
||||
await using McpClient client = await CreateMcpClientForServer();
|
||||
|
||||
var result = await client.CallToolAsync(
|
||||
"echo_complex",
|
||||
|
|
@ -337,7 +337,7 @@ public partial class McpServerBuilderExtensionsToolsTests : ClientServerTestBase
|
|||
[Fact]
|
||||
public async Task Can_Call_Registered_Tool_With_Instance_Method()
|
||||
{
|
||||
await using IMcpClient client = await CreateMcpClientForServer();
|
||||
await using McpClient client = await CreateMcpClientForServer();
|
||||
|
||||
string[][] parts = new string[2][];
|
||||
for (int i = 0; i < 2; i++)
|
||||
|
|
@ -366,7 +366,7 @@ public partial class McpServerBuilderExtensionsToolsTests : ClientServerTestBase
|
|||
[Fact]
|
||||
public async Task Returns_IsError_Content_And_Logs_Error_When_Tool_Fails()
|
||||
{
|
||||
await using IMcpClient client = await CreateMcpClientForServer();
|
||||
await using McpClient client = await CreateMcpClientForServer();
|
||||
|
||||
var result = await client.CallToolAsync(
|
||||
"throw_exception",
|
||||
|
|
@ -386,7 +386,7 @@ public partial class McpServerBuilderExtensionsToolsTests : ClientServerTestBase
|
|||
[Fact]
|
||||
public async Task Throws_Exception_On_Unknown_Tool()
|
||||
{
|
||||
await using IMcpClient client = await CreateMcpClientForServer();
|
||||
await using McpClient client = await CreateMcpClientForServer();
|
||||
|
||||
var e = await Assert.ThrowsAsync<McpException>(async () => await client.CallToolAsync(
|
||||
"NotRegisteredTool",
|
||||
|
|
@ -398,7 +398,7 @@ public partial class McpServerBuilderExtensionsToolsTests : ClientServerTestBase
|
|||
[Fact]
|
||||
public async Task Returns_IsError_Missing_Parameter()
|
||||
{
|
||||
await using IMcpClient client = await CreateMcpClientForServer();
|
||||
await using McpClient client = await CreateMcpClientForServer();
|
||||
|
||||
var result = await client.CallToolAsync(
|
||||
"echo",
|
||||
|
|
@ -525,7 +525,7 @@ public partial class McpServerBuilderExtensionsToolsTests : ClientServerTestBase
|
|||
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<IMcpServer>().Object, new JsonRpcRequest { Method = "test", Id = new RequestId("1") }), TestContext.Current.CancellationToken);
|
||||
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);
|
||||
}
|
||||
|
|
@ -557,7 +557,7 @@ public partial class McpServerBuilderExtensionsToolsTests : ClientServerTestBase
|
|||
[Fact]
|
||||
public async Task Recognizes_Parameter_Types()
|
||||
{
|
||||
await using IMcpClient client = await CreateMcpClientForServer();
|
||||
await using McpClient client = await CreateMcpClientForServer();
|
||||
|
||||
var tools = await client.ListToolsAsync(cancellationToken: TestContext.Current.CancellationToken);
|
||||
|
||||
|
|
@ -632,7 +632,7 @@ public partial class McpServerBuilderExtensionsToolsTests : ClientServerTestBase
|
|||
[Fact]
|
||||
public async Task TitleAttributeProperty_PropagatedToTitle()
|
||||
{
|
||||
await using IMcpClient client = await CreateMcpClientForServer();
|
||||
await using McpClient client = await CreateMcpClientForServer();
|
||||
|
||||
var tools = await client.ListToolsAsync(cancellationToken: TestContext.Current.CancellationToken);
|
||||
Assert.NotNull(tools);
|
||||
|
|
@ -648,7 +648,7 @@ public partial class McpServerBuilderExtensionsToolsTests : ClientServerTestBase
|
|||
[Fact]
|
||||
public async Task HandlesIProgressParameter()
|
||||
{
|
||||
await using IMcpClient client = await CreateMcpClientForServer();
|
||||
await using McpClient client = await CreateMcpClientForServer();
|
||||
|
||||
var tools = await client.ListToolsAsync(cancellationToken: TestContext.Current.CancellationToken);
|
||||
Assert.NotNull(tools);
|
||||
|
|
@ -702,7 +702,7 @@ public partial class McpServerBuilderExtensionsToolsTests : ClientServerTestBase
|
|||
[Fact]
|
||||
public async Task CancellationNotificationsPropagateToToolTokens()
|
||||
{
|
||||
await using IMcpClient client = await CreateMcpClientForServer();
|
||||
await using McpClient client = await CreateMcpClientForServer();
|
||||
|
||||
var tools = await client.ListToolsAsync(cancellationToken: TestContext.Current.CancellationToken);
|
||||
Assert.NotNull(tools);
|
||||
|
|
|
|||
|
|
@ -22,7 +22,7 @@ public partial class McpServerScopedTests : ClientServerTestBase
|
|||
[Fact]
|
||||
public async Task InjectScopedServiceAsArgument()
|
||||
{
|
||||
await using IMcpClient client = await CreateMcpClientForServer();
|
||||
await using McpClient client = await CreateMcpClientForServer();
|
||||
|
||||
var tools = await client.ListToolsAsync(McpServerScopedTestsJsonContext.Default.Options, TestContext.Current.CancellationToken);
|
||||
var tool = tools.First(t => t.Name == "echo_complex");
|
||||
|
|
|
|||
|
|
@ -128,7 +128,7 @@ public class DiagnosticTests
|
|||
Assert.Equal("-32602", doesNotExistToolClient.Tags.Single(t => t.Key == "rpc.jsonrpc.error_code").Value);
|
||||
}
|
||||
|
||||
private static async Task RunConnected(Func<IMcpClient, IMcpServer, Task> action, List<string> clientToServerLog)
|
||||
private static async Task RunConnected(Func<McpClient, McpServer, Task> action, List<string> clientToServerLog)
|
||||
{
|
||||
Pipe clientToServerPipe = new(), serverToClientPipe = new();
|
||||
StreamServerTransport serverTransport = new(clientToServerPipe.Reader.AsStream(), serverToClientPipe.Writer.AsStream());
|
||||
|
|
@ -137,7 +137,7 @@ public class DiagnosticTests
|
|||
|
||||
Task serverTask;
|
||||
|
||||
await using (IMcpServer server = McpServerFactory.Create(serverTransport, new()
|
||||
await using (McpServer server = McpServer.Create(serverTransport, new()
|
||||
{
|
||||
Capabilities = new()
|
||||
{
|
||||
|
|
@ -153,7 +153,7 @@ public class DiagnosticTests
|
|||
{
|
||||
serverTask = server.RunAsync(TestContext.Current.CancellationToken);
|
||||
|
||||
await using (IMcpClient client = await McpClientFactory.CreateAsync(
|
||||
await using (McpClient client = await McpClient.CreateAsync(
|
||||
clientTransport,
|
||||
cancellationToken: TestContext.Current.CancellationToken))
|
||||
{
|
||||
|
|
|
|||
|
|
@ -36,15 +36,15 @@ public class DockerEverythingServerTests(ITestOutputHelper testOutputHelper) : L
|
|||
ClientInfo = new() { Name = "IntegrationTestClient", Version = "1.0.0" }
|
||||
};
|
||||
|
||||
var defaultConfig = new SseClientTransportOptions
|
||||
var defaultConfig = new HttpClientTransportOptions
|
||||
{
|
||||
Endpoint = new Uri($"http://localhost:{port}/sse"),
|
||||
Name = "Everything",
|
||||
};
|
||||
|
||||
// Create client and run tests
|
||||
await using var client = await McpClientFactory.CreateAsync(
|
||||
new SseClientTransport(defaultConfig),
|
||||
await using var client = await McpClient.CreateAsync(
|
||||
new HttpClientTransport(defaultConfig),
|
||||
defaultOptions,
|
||||
loggerFactory: LoggerFactory,
|
||||
cancellationToken: TestContext.Current.CancellationToken);
|
||||
|
|
@ -63,7 +63,7 @@ public class DockerEverythingServerTests(ITestOutputHelper testOutputHelper) : L
|
|||
await using var fixture = new EverythingSseServerFixture(port);
|
||||
await fixture.StartAsync();
|
||||
|
||||
var defaultConfig = new SseClientTransportOptions
|
||||
var defaultConfig = new HttpClientTransportOptions
|
||||
{
|
||||
Endpoint = new Uri($"http://localhost:{port}/sse"),
|
||||
Name = "Everything",
|
||||
|
|
@ -90,8 +90,8 @@ public class DockerEverythingServerTests(ITestOutputHelper testOutputHelper) : L
|
|||
},
|
||||
};
|
||||
|
||||
await using var client = await McpClientFactory.CreateAsync(
|
||||
new SseClientTransport(defaultConfig),
|
||||
await using var client = await McpClient.CreateAsync(
|
||||
new HttpClientTransport(defaultConfig),
|
||||
defaultOptions,
|
||||
loggerFactory: LoggerFactory,
|
||||
cancellationToken: TestContext.Current.CancellationToken);
|
||||
|
|
|
|||
118
tests/ModelContextProtocol.Tests/McpEndpointExtensionsTests.cs
Normal file
118
tests/ModelContextProtocol.Tests/McpEndpointExtensionsTests.cs
Normal file
|
|
@ -0,0 +1,118 @@
|
|||
using ModelContextProtocol.Protocol;
|
||||
using Moq;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace ModelContextProtocol.Tests;
|
||||
|
||||
#pragma warning disable CS0618 // Type or member is obsolete
|
||||
|
||||
public class McpEndpointExtensionsTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task SendRequestAsync_Generic_Throws_When_Not_McpSession()
|
||||
{
|
||||
var endpoint = new Mock<IMcpEndpoint>(MockBehavior.Strict).Object;
|
||||
|
||||
var ex = await Assert.ThrowsAsync<InvalidOperationException>(async () => await McpEndpointExtensions.SendRequestAsync<string, int>(
|
||||
endpoint, "method", "param", cancellationToken: TestContext.Current.CancellationToken));
|
||||
Assert.Contains("Prefer using 'McpServer.SendRequestAsync' instead", ex.Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SendNotificationAsync_Parameterless_Throws_When_Not_McpSession()
|
||||
{
|
||||
var endpoint = new Mock<IMcpEndpoint>(MockBehavior.Strict).Object;
|
||||
|
||||
var ex = await Assert.ThrowsAsync<InvalidOperationException>(async () => await McpEndpointExtensions.SendNotificationAsync(
|
||||
endpoint, "notify", cancellationToken: TestContext.Current.CancellationToken));
|
||||
Assert.Contains("Prefer using 'McpServer.SendNotificationAsync' instead", ex.Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SendNotificationAsync_Generic_Throws_When_Not_McpSession()
|
||||
{
|
||||
var endpoint = new Mock<IMcpEndpoint>(MockBehavior.Strict).Object;
|
||||
|
||||
var ex = await Assert.ThrowsAsync<InvalidOperationException>(async () => await McpEndpointExtensions.SendNotificationAsync(
|
||||
endpoint, "notify", "payload", cancellationToken: TestContext.Current.CancellationToken));
|
||||
Assert.Contains("Prefer using 'McpServer.SendNotificationAsync' instead", ex.Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task NotifyProgressAsync_Throws_When_Not_McpSession()
|
||||
{
|
||||
var endpoint = new Mock<IMcpEndpoint>(MockBehavior.Strict).Object;
|
||||
|
||||
var ex = await Assert.ThrowsAsync<InvalidOperationException>(async () => await McpEndpointExtensions.NotifyProgressAsync(
|
||||
endpoint, new ProgressToken("t1"), new ProgressNotificationValue { Progress = 0.5f }, cancellationToken: TestContext.Current.CancellationToken));
|
||||
Assert.Contains("Prefer using 'McpServer.NotifyProgressAsync' instead", ex.Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SendRequestAsync_Generic_Forwards_To_McpSession_SendRequestAsync()
|
||||
{
|
||||
var mockSession = new Mock<McpSession> { CallBase = true };
|
||||
|
||||
mockSession
|
||||
.Setup(s => s.SendRequestAsync(It.IsAny<JsonRpcRequest>(), It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(new JsonRpcResponse
|
||||
{
|
||||
Result = JsonSerializer.SerializeToNode(42, McpJsonUtilities.DefaultOptions),
|
||||
});
|
||||
|
||||
IMcpEndpoint endpoint = mockSession.Object;
|
||||
|
||||
var result = await endpoint.SendRequestAsync<string, int>("method", "param", cancellationToken: TestContext.Current.CancellationToken);
|
||||
|
||||
Assert.Equal(42, result);
|
||||
mockSession.Verify(s => s.SendRequestAsync(It.IsAny<JsonRpcRequest>(), It.IsAny<CancellationToken>()), Times.Once);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SendNotificationAsync_Parameterless_Forwards_To_McpSession_SendMessageAsync()
|
||||
{
|
||||
var mockSession = new Mock<McpSession> { CallBase = true };
|
||||
|
||||
mockSession
|
||||
.Setup(s => s.SendMessageAsync(It.IsAny<JsonRpcMessage>(), It.IsAny<CancellationToken>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
IMcpEndpoint endpoint = mockSession.Object;
|
||||
|
||||
await endpoint.SendNotificationAsync("notify", cancellationToken: TestContext.Current.CancellationToken);
|
||||
|
||||
mockSession.Verify(s => s.SendMessageAsync(It.IsAny<JsonRpcMessage>(), It.IsAny<CancellationToken>()), Times.Once);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SendNotificationAsync_Generic_Forwards_To_McpSession_SendMessageAsync()
|
||||
{
|
||||
var mockSession = new Mock<McpSession> { CallBase = true };
|
||||
|
||||
mockSession
|
||||
.Setup(s => s.SendMessageAsync(It.IsAny<JsonRpcMessage>(), It.IsAny<CancellationToken>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
IMcpEndpoint endpoint = mockSession.Object;
|
||||
|
||||
await endpoint.SendNotificationAsync("notify", "payload", cancellationToken: TestContext.Current.CancellationToken);
|
||||
|
||||
mockSession.Verify(s => s.SendMessageAsync(It.IsAny<JsonRpcMessage>(), It.IsAny<CancellationToken>()), Times.Once);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task NotifyProgressAsync_Forwards_To_McpSession_SendMessageAsync()
|
||||
{
|
||||
var mockSession = new Mock<McpSession> { CallBase = true };
|
||||
|
||||
mockSession
|
||||
.Setup(s => s.SendMessageAsync(It.IsAny<JsonRpcMessage>(), It.IsAny<CancellationToken>()))
|
||||
.Returns(Task.CompletedTask);
|
||||
|
||||
IMcpEndpoint endpoint = mockSession.Object;
|
||||
|
||||
await endpoint.NotifyProgressAsync(new ProgressToken("progress-token"), new ProgressNotificationValue { Progress = 1 }, cancellationToken: TestContext.Current.CancellationToken);
|
||||
|
||||
mockSession.Verify(s => s.SendMessageAsync(It.IsAny<JsonRpcMessage>(), It.IsAny<CancellationToken>()), Times.Once);
|
||||
}
|
||||
}
|
||||
|
|
@ -67,7 +67,7 @@ public partial class ElicitationTests : ClientServerTestBase
|
|||
[Fact]
|
||||
public async Task Can_Elicit_Information()
|
||||
{
|
||||
await using IMcpClient client = await CreateMcpClientForServer(new McpClientOptions
|
||||
await using McpClient client = await CreateMcpClientForServer(new McpClientOptions
|
||||
{
|
||||
Capabilities = new()
|
||||
{
|
||||
|
|
|
|||
|
|
@ -1,7 +1,6 @@
|
|||
using Microsoft.Extensions.DependencyInjection;
|
||||
using ModelContextProtocol.Client;
|
||||
using ModelContextProtocol.Protocol;
|
||||
using ModelContextProtocol.Server;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
|
|
@ -102,7 +101,7 @@ public partial class ElicitationTypedTests : ClientServerTestBase
|
|||
[Fact]
|
||||
public async Task Can_Elicit_Typed_Information()
|
||||
{
|
||||
await using IMcpClient client = await CreateMcpClientForServer(new McpClientOptions
|
||||
await using McpClient client = await CreateMcpClientForServer(new McpClientOptions
|
||||
{
|
||||
Capabilities = new()
|
||||
{
|
||||
|
|
@ -198,7 +197,7 @@ public partial class ElicitationTypedTests : ClientServerTestBase
|
|||
[Fact]
|
||||
public async Task Elicit_Typed_Respects_NamingPolicy()
|
||||
{
|
||||
await using IMcpClient client = await CreateMcpClientForServer(new McpClientOptions
|
||||
await using McpClient client = await CreateMcpClientForServer(new McpClientOptions
|
||||
{
|
||||
Capabilities = new()
|
||||
{
|
||||
|
|
@ -242,7 +241,7 @@ public partial class ElicitationTypedTests : ClientServerTestBase
|
|||
[Fact]
|
||||
public async Task Elicit_Typed_With_Unsupported_Property_Type_Throws()
|
||||
{
|
||||
await using IMcpClient client = await CreateMcpClientForServer(new McpClientOptions
|
||||
await using McpClient client = await CreateMcpClientForServer(new McpClientOptions
|
||||
{
|
||||
Capabilities = new()
|
||||
{
|
||||
|
|
@ -267,7 +266,7 @@ public partial class ElicitationTypedTests : ClientServerTestBase
|
|||
[Fact]
|
||||
public async Task Elicit_Typed_With_Nullable_Property_Type_Throws()
|
||||
{
|
||||
await using IMcpClient client = await CreateMcpClientForServer(new McpClientOptions
|
||||
await using McpClient client = await CreateMcpClientForServer(new McpClientOptions
|
||||
{
|
||||
Capabilities = new()
|
||||
{
|
||||
|
|
@ -290,7 +289,7 @@ public partial class ElicitationTypedTests : ClientServerTestBase
|
|||
[Fact]
|
||||
public async Task Elicit_Typed_With_NonObject_Generic_Type_Throws()
|
||||
{
|
||||
await using IMcpClient client = await CreateMcpClientForServer(new McpClientOptions
|
||||
await using McpClient client = await CreateMcpClientForServer(new McpClientOptions
|
||||
{
|
||||
Capabilities = new()
|
||||
{
|
||||
|
|
|
|||
|
|
@ -13,7 +13,7 @@ public class NotificationHandlerTests : ClientServerTestBase
|
|||
public async Task RegistrationsAreRemovedWhenDisposed()
|
||||
{
|
||||
const string NotificationName = "somethingsomething";
|
||||
await using IMcpClient client = await CreateMcpClientForServer();
|
||||
await using McpClient client = await CreateMcpClientForServer();
|
||||
|
||||
const int Iterations = 10;
|
||||
|
||||
|
|
@ -40,7 +40,7 @@ public class NotificationHandlerTests : ClientServerTestBase
|
|||
public async Task MultipleRegistrationsResultInMultipleCallbacks()
|
||||
{
|
||||
const string NotificationName = "somethingsomething";
|
||||
await using IMcpClient client = await CreateMcpClientForServer();
|
||||
await using McpClient client = await CreateMcpClientForServer();
|
||||
|
||||
const int RegistrationCount = 10;
|
||||
|
||||
|
|
@ -80,7 +80,7 @@ public class NotificationHandlerTests : ClientServerTestBase
|
|||
public async Task MultipleHandlersRunEvenIfOneThrows()
|
||||
{
|
||||
const string NotificationName = "somethingsomething";
|
||||
await using IMcpClient client = await CreateMcpClientForServer();
|
||||
await using McpClient client = await CreateMcpClientForServer();
|
||||
|
||||
const int RegistrationCount = 10;
|
||||
|
||||
|
|
@ -122,7 +122,7 @@ public class NotificationHandlerTests : ClientServerTestBase
|
|||
public async Task DisposeAsyncDoesNotCompleteWhileNotificationHandlerRuns(int numberOfDisposals)
|
||||
{
|
||||
const string NotificationName = "somethingsomething";
|
||||
await using IMcpClient client = await CreateMcpClientForServer();
|
||||
await using McpClient client = await CreateMcpClientForServer();
|
||||
|
||||
var handlerRunning = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var releaseHandler = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
|
|
@ -163,7 +163,7 @@ public class NotificationHandlerTests : ClientServerTestBase
|
|||
public async Task DisposeAsyncCompletesImmediatelyWhenInvokedFromHandler(int numberOfDisposals)
|
||||
{
|
||||
const string NotificationName = "somethingsomething";
|
||||
await using IMcpClient client = await CreateMcpClientForServer();
|
||||
await using McpClient client = await CreateMcpClientForServer();
|
||||
|
||||
var handlerRunning = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
var releaseHandler = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
|
|
|
|||
|
|
@ -0,0 +1,195 @@
|
|||
using Microsoft.Extensions.AI;
|
||||
using ModelContextProtocol.Protocol;
|
||||
using ModelContextProtocol.Server;
|
||||
using Moq;
|
||||
using System.Text.Json;
|
||||
|
||||
namespace ModelContextProtocol.Tests.Server;
|
||||
|
||||
#pragma warning disable CS0618 // Type or member is obsolete
|
||||
|
||||
public class McpServerExtensionsTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task SampleAsync_Request_Throws_When_Not_McpServer()
|
||||
{
|
||||
var server = new Mock<IMcpServer>(MockBehavior.Strict).Object;
|
||||
|
||||
var ex = await Assert.ThrowsAsync<InvalidOperationException>(async () => await server.SampleAsync(
|
||||
new CreateMessageRequestParams { Messages = [new SamplingMessage { Role = Role.User, Content = new TextContentBlock { Text = "hi" } }] },
|
||||
TestContext.Current.CancellationToken));
|
||||
Assert.Contains("Prefer using 'McpServer.SampleAsync' instead", ex.Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SampleAsync_Messages_Throws_When_Not_McpServer()
|
||||
{
|
||||
var server = new Mock<IMcpServer>(MockBehavior.Strict).Object;
|
||||
|
||||
var ex = await Assert.ThrowsAsync<InvalidOperationException>(async () => await server.SampleAsync(
|
||||
[new ChatMessage(ChatRole.User, "hi")], cancellationToken: TestContext.Current.CancellationToken));
|
||||
Assert.Contains("Prefer using 'McpServer.SampleAsync' instead", ex.Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AsSamplingChatClient_Throws_When_Not_McpServer()
|
||||
{
|
||||
var server = new Mock<IMcpServer>(MockBehavior.Strict).Object;
|
||||
|
||||
var ex = Assert.Throws<InvalidOperationException>(server.AsSamplingChatClient);
|
||||
Assert.Contains("Prefer using 'McpServer.AsSamplingChatClient' instead", ex.Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void AsClientLoggerProvider_Throws_When_Not_McpServer()
|
||||
{
|
||||
var server = new Mock<IMcpServer>(MockBehavior.Strict).Object;
|
||||
|
||||
var ex = Assert.Throws<InvalidOperationException>(server.AsClientLoggerProvider);
|
||||
Assert.Contains("Prefer using 'McpServer.AsClientLoggerProvider' instead", ex.Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RequestRootsAsync_Throws_When_Not_McpServer()
|
||||
{
|
||||
var server = new Mock<IMcpServer>(MockBehavior.Strict).Object;
|
||||
|
||||
var ex = await Assert.ThrowsAsync<InvalidOperationException>(async () => await server.RequestRootsAsync(
|
||||
new ListRootsRequestParams(), TestContext.Current.CancellationToken));
|
||||
Assert.Contains("Prefer using 'McpServer.RequestRootsAsync' instead", ex.Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ElicitAsync_Throws_When_Not_McpServer()
|
||||
{
|
||||
var server = new Mock<IMcpServer>(MockBehavior.Strict).Object;
|
||||
|
||||
var ex = await Assert.ThrowsAsync<InvalidOperationException>(async () => await server.ElicitAsync(
|
||||
new ElicitRequestParams { Message = "hello" }, TestContext.Current.CancellationToken));
|
||||
Assert.Contains("Prefer using 'McpServer.ElicitAsync' instead", ex.Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SampleAsync_Request_Forwards_To_McpServer_SendRequestAsync()
|
||||
{
|
||||
var mockServer = new Mock<McpServer> { CallBase = true };
|
||||
|
||||
var resultPayload = new CreateMessageResult
|
||||
{
|
||||
Content = new TextContentBlock { Text = "resp" },
|
||||
Model = "test-model",
|
||||
Role = Role.Assistant,
|
||||
StopReason = "endTurn",
|
||||
};
|
||||
|
||||
mockServer
|
||||
.Setup(s => s.ClientCapabilities)
|
||||
.Returns(new ClientCapabilities() { Sampling = new() });
|
||||
|
||||
mockServer
|
||||
.Setup(s => s.SendRequestAsync(It.IsAny<JsonRpcRequest>(), It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(new JsonRpcResponse
|
||||
{
|
||||
Result = JsonSerializer.SerializeToNode(resultPayload, McpJsonUtilities.DefaultOptions),
|
||||
});
|
||||
|
||||
IMcpServer server = mockServer.Object;
|
||||
|
||||
var result = await server.SampleAsync(new CreateMessageRequestParams
|
||||
{
|
||||
Messages = [new SamplingMessage { Role = Role.User, Content = new TextContentBlock { Text = "hi" } }]
|
||||
}, TestContext.Current.CancellationToken);
|
||||
|
||||
Assert.Equal("test-model", result.Model);
|
||||
Assert.Equal(Role.Assistant, result.Role);
|
||||
Assert.Equal("resp", Assert.IsType<TextContentBlock>(result.Content).Text);
|
||||
mockServer.Verify(s => s.SendRequestAsync(It.IsAny<JsonRpcRequest>(), It.IsAny<CancellationToken>()), Times.Once);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SampleAsync_Messages_Forwards_To_McpServer_SendRequestAsync()
|
||||
{
|
||||
var mockServer = new Mock<McpServer> { CallBase = true };
|
||||
|
||||
var resultPayload = new CreateMessageResult
|
||||
{
|
||||
Content = new TextContentBlock { Text = "resp" },
|
||||
Model = "test-model",
|
||||
Role = Role.Assistant,
|
||||
StopReason = "endTurn",
|
||||
};
|
||||
|
||||
mockServer
|
||||
.Setup(s => s.ClientCapabilities)
|
||||
.Returns(new ClientCapabilities() { Sampling = new() });
|
||||
|
||||
mockServer
|
||||
.Setup(s => s.SendRequestAsync(It.IsAny<JsonRpcRequest>(), It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(new JsonRpcResponse
|
||||
{
|
||||
Result = JsonSerializer.SerializeToNode(resultPayload, McpJsonUtilities.DefaultOptions),
|
||||
});
|
||||
|
||||
IMcpServer server = mockServer.Object;
|
||||
|
||||
var chatResponse = await server.SampleAsync([new ChatMessage(ChatRole.User, "hi")], cancellationToken: TestContext.Current.CancellationToken);
|
||||
|
||||
Assert.Equal("test-model", chatResponse.ModelId);
|
||||
var last = chatResponse.Messages.Last();
|
||||
Assert.Equal(ChatRole.Assistant, last.Role);
|
||||
Assert.Equal("resp", last.Text);
|
||||
mockServer.Verify(s => s.SendRequestAsync(It.IsAny<JsonRpcRequest>(), It.IsAny<CancellationToken>()), Times.Once);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task RequestRootsAsync_Forwards_To_McpServer_SendRequestAsync()
|
||||
{
|
||||
var mockServer = new Mock<McpServer> { CallBase = true };
|
||||
|
||||
var resultPayload = new ListRootsResult { Roots = [new Root { Uri = "root://a" }] };
|
||||
|
||||
mockServer
|
||||
.Setup(s => s.ClientCapabilities)
|
||||
.Returns(new ClientCapabilities() { Roots = new() });
|
||||
|
||||
mockServer
|
||||
.Setup(s => s.SendRequestAsync(It.IsAny<JsonRpcRequest>(), It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(new JsonRpcResponse
|
||||
{
|
||||
Result = JsonSerializer.SerializeToNode(resultPayload, McpJsonUtilities.DefaultOptions),
|
||||
});
|
||||
|
||||
IMcpServer server = mockServer.Object;
|
||||
|
||||
var result = await server.RequestRootsAsync(new ListRootsRequestParams(), TestContext.Current.CancellationToken);
|
||||
|
||||
Assert.Equal("root://a", result.Roots[0].Uri);
|
||||
mockServer.Verify(s => s.SendRequestAsync(It.IsAny<JsonRpcRequest>(), It.IsAny<CancellationToken>()), Times.Once);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ElicitAsync_Forwards_To_McpServer_SendRequestAsync()
|
||||
{
|
||||
var mockServer = new Mock<McpServer> { CallBase = true };
|
||||
|
||||
var resultPayload = new ElicitResult { Action = "accept" };
|
||||
|
||||
mockServer
|
||||
.Setup(s => s.ClientCapabilities)
|
||||
.Returns(new ClientCapabilities() { Elicitation = new() });
|
||||
|
||||
mockServer
|
||||
.Setup(s => s.SendRequestAsync(It.IsAny<JsonRpcRequest>(), It.IsAny<CancellationToken>()))
|
||||
.ReturnsAsync(new JsonRpcResponse
|
||||
{
|
||||
Result = JsonSerializer.SerializeToNode(resultPayload, McpJsonUtilities.DefaultOptions),
|
||||
});
|
||||
|
||||
IMcpServer server = mockServer.Object;
|
||||
|
||||
var result = await server.ElicitAsync(new ElicitRequestParams { Message = "hi" }, TestContext.Current.CancellationToken);
|
||||
|
||||
Assert.Equal("accept", result.Action);
|
||||
mockServer.Verify(s => s.SendRequestAsync(It.IsAny<JsonRpcRequest>(), It.IsAny<CancellationToken>()), Times.Once);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,45 +0,0 @@
|
|||
using ModelContextProtocol.Server;
|
||||
using ModelContextProtocol.Tests.Utils;
|
||||
|
||||
namespace ModelContextProtocol.Tests.Server;
|
||||
|
||||
public class McpServerFactoryTests : LoggedTest
|
||||
{
|
||||
private readonly McpServerOptions _options;
|
||||
|
||||
public McpServerFactoryTests(ITestOutputHelper testOutputHelper)
|
||||
: base(testOutputHelper)
|
||||
{
|
||||
_options = new McpServerOptions
|
||||
{
|
||||
ProtocolVersion = "1.0",
|
||||
InitializationTimeout = TimeSpan.FromSeconds(30)
|
||||
};
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Create_Should_Initialize_With_Valid_Parameters()
|
||||
{
|
||||
// Arrange & Act
|
||||
await using var transport = new TestServerTransport();
|
||||
await using IMcpServer server = McpServerFactory.Create(transport, _options, LoggerFactory);
|
||||
|
||||
// Assert
|
||||
Assert.NotNull(server);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Create_Throws_For_Null_ServerTransport()
|
||||
{
|
||||
// Arrange, Act & Assert
|
||||
Assert.Throws<ArgumentNullException>("transport", () => McpServerFactory.Create(null!, _options, LoggerFactory));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Create_Throws_For_Null_Options()
|
||||
{
|
||||
// Arrange, Act & Assert
|
||||
await using var transport = new TestServerTransport();
|
||||
Assert.Throws<ArgumentNullException>("serverOptions", () => McpServerFactory.Create(transport, null!, LoggerFactory));
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue