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:
Mackinnon Buck 2025-09-16 13:22:10 -04:00 • committed by GitHub
commit 38b4a26998
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
4 changed files with 5169 additions and 3786 deletions

View file

@ -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);
}
}
}

View file

@ -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));
}
}
}

View file

@ -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);

View 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));
}
}