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
43 changed files with 5169 additions and 3786 deletions

View file

@ -106,7 +106,7 @@ public class AuthEventTests : KestrelInMemoryTest, IAsyncDisposable
await app.StartAsync(TestContext.Current.CancellationToken);
await using var transport = new SseClientTransport(
await using var transport = new HttpClientTransport(
new()
{
Endpoint = new(McpServerUrl),
@ -122,7 +122,7 @@ public class AuthEventTests : KestrelInMemoryTest, IAsyncDisposable
LoggerFactory
);
await using var client = await McpClientFactory.CreateAsync(
await using var client = await McpClient.CreateAsync(
transport,
loggerFactory: LoggerFactory,
cancellationToken: TestContext.Current.CancellationToken
@ -142,7 +142,7 @@ public class AuthEventTests : KestrelInMemoryTest, IAsyncDisposable
DynamicClientRegistrationResponse? dcrResponse = null;
await using var transport = new SseClientTransport(
await using var transport = new HttpClientTransport(
new()
{
Endpoint = new(McpServerUrl),
@ -167,7 +167,7 @@ public class AuthEventTests : KestrelInMemoryTest, IAsyncDisposable
LoggerFactory
);
await using var client = await McpClientFactory.CreateAsync(
await using var client = await McpClient.CreateAsync(
transport,
loggerFactory: LoggerFactory,
cancellationToken: TestContext.Current.CancellationToken

View file

@ -97,7 +97,7 @@ public class AuthTests : KestrelInMemoryTest, IAsyncDisposable
await app.StartAsync(TestContext.Current.CancellationToken);
await using var transport = new SseClientTransport(new()
await using var transport = new HttpClientTransport(new()
{
Endpoint = new(McpServerUrl),
OAuth = new()
@ -109,7 +109,7 @@ public class AuthTests : KestrelInMemoryTest, IAsyncDisposable
},
}, HttpClient, LoggerFactory);
await using var client = await McpClientFactory.CreateAsync(
await using var client = await McpClient.CreateAsync(
transport, loggerFactory: LoggerFactory, cancellationToken: TestContext.Current.CancellationToken);
}
@ -124,12 +124,12 @@ public class AuthTests : KestrelInMemoryTest, IAsyncDisposable
await app.StartAsync(TestContext.Current.CancellationToken);
await using var transport = new SseClientTransport(new()
await using var transport = new HttpClientTransport(new()
{
Endpoint = new(McpServerUrl),
}, HttpClient, LoggerFactory);
var httpEx = await Assert.ThrowsAsync<HttpRequestException>(async () => await McpClientFactory.CreateAsync(
var httpEx = await Assert.ThrowsAsync<HttpRequestException>(async () => await McpClient.CreateAsync(
transport, loggerFactory: LoggerFactory, cancellationToken: TestContext.Current.CancellationToken));
Assert.Equal(HttpStatusCode.Unauthorized, httpEx.StatusCode);
@ -146,7 +146,7 @@ public class AuthTests : KestrelInMemoryTest, IAsyncDisposable
await app.StartAsync(TestContext.Current.CancellationToken);
await using var transport = new SseClientTransport(new()
await using var transport = new HttpClientTransport(new()
{
Endpoint = new(McpServerUrl),
OAuth = new()
@ -159,7 +159,7 @@ public class AuthTests : KestrelInMemoryTest, IAsyncDisposable
}, HttpClient, LoggerFactory);
// The EqualException is thrown by HandleAuthorizationUrlAsync when the /authorize request gets a 400
var equalEx = await Assert.ThrowsAsync<EqualException>(async () => await McpClientFactory.CreateAsync(
var equalEx = await Assert.ThrowsAsync<EqualException>(async () => await McpClient.CreateAsync(
transport, loggerFactory: LoggerFactory, cancellationToken: TestContext.Current.CancellationToken));
}
@ -174,7 +174,7 @@ public class AuthTests : KestrelInMemoryTest, IAsyncDisposable
await app.StartAsync(TestContext.Current.CancellationToken);
await using var transport = new SseClientTransport(new()
await using var transport = new HttpClientTransport(new()
{
Endpoint = new(McpServerUrl),
OAuth = new ClientOAuthOptions()
@ -190,7 +190,7 @@ public class AuthTests : KestrelInMemoryTest, IAsyncDisposable
},
}, HttpClient, LoggerFactory);
await using var client = await McpClientFactory.CreateAsync(
await using var client = await McpClient.CreateAsync(
transport, loggerFactory: LoggerFactory, cancellationToken: TestContext.Current.CancellationToken);
}
@ -205,7 +205,7 @@ public class AuthTests : KestrelInMemoryTest, IAsyncDisposable
await app.StartAsync(TestContext.Current.CancellationToken);
await using var transport = new SseClientTransport(new()
await using var transport = new HttpClientTransport(new()
{
Endpoint = new(McpServerUrl),
OAuth = new()
@ -219,7 +219,7 @@ public class AuthTests : KestrelInMemoryTest, IAsyncDisposable
// The test-refresh-client should get an expired token first,
// then automatically refresh it to get a working token
await using var client = await McpClientFactory.CreateAsync(
await using var client = await McpClient.CreateAsync(
transport, loggerFactory: LoggerFactory, cancellationToken: TestContext.Current.CancellationToken);
Assert.True(_testOAuthServer.HasIssuedRefreshToken);
@ -236,7 +236,7 @@ public class AuthTests : KestrelInMemoryTest, IAsyncDisposable
await app.StartAsync(TestContext.Current.CancellationToken);
await using var transport = new SseClientTransport(new()
await using var transport = new HttpClientTransport(new()
{
Endpoint = new(McpServerUrl),
OAuth = new()
@ -252,7 +252,7 @@ public class AuthTests : KestrelInMemoryTest, IAsyncDisposable
},
}, HttpClient, LoggerFactory);
await using var client = await McpClientFactory.CreateAsync(
await using var client = await McpClient.CreateAsync(
transport, loggerFactory: LoggerFactory, cancellationToken: TestContext.Current.CancellationToken);
Assert.NotNull(_lastAuthorizationUri?.Query);
@ -270,7 +270,7 @@ public class AuthTests : KestrelInMemoryTest, IAsyncDisposable
await app.StartAsync(TestContext.Current.CancellationToken);
await using var transport = new SseClientTransport(new()
await using var transport = new HttpClientTransport(new()
{
Endpoint = new(McpServerUrl),
OAuth = new()
@ -286,7 +286,7 @@ public class AuthTests : KestrelInMemoryTest, IAsyncDisposable
},
}, HttpClient, LoggerFactory);
await Assert.ThrowsAsync<ArgumentException>(() => McpClientFactory.CreateAsync(
await Assert.ThrowsAsync<ArgumentException>(() => McpClient.CreateAsync(
transport, loggerFactory: LoggerFactory, cancellationToken: TestContext.Current.CancellationToken));
}

View file

@ -19,14 +19,14 @@ public class AuthorizeAttributeTests(ITestOutputHelper testOutputHelper) : Kestr
{
private readonly MockLoggerProvider _mockLoggerProvider = new();
private async Task<IMcpClient> ConnectAsync()
private async Task<McpClient> ConnectAsync()
{
await using var transport = new SseClientTransport(new SseClientTransportOptions
await using var transport = new HttpClientTransport(new HttpClientTransportOptions
{
Endpoint = new("http://localhost:5000"),
}, HttpClient, LoggerFactory);
return await McpClientFactory.CreateAsync(transport, cancellationToken: TestContext.Current.CancellationToken, loggerFactory: LoggerFactory);
return await McpClient.CreateAsync(transport, cancellationToken: TestContext.Current.CancellationToken, loggerFactory: LoggerFactory);
}
[Fact]
@ -447,7 +447,7 @@ public class AuthorizeAttributeTests(ITestOutputHelper testOutputHelper) : Kestr
private ClaimsPrincipal CreateUser(string name, params string[] roles)
=> new ClaimsPrincipal(new ClaimsIdentity(
[new Claim("name", name), new Claim(ClaimTypes.NameIdentifier, name), ..roles.Select(role => new Claim("role", role))],
[new Claim("name", name), new Claim(ClaimTypes.NameIdentifier, name), .. roles.Select(role => new Claim("role", role))],
"TestAuthType", "name", "role"));
[McpServerToolType]

View file

@ -21,9 +21,9 @@ public abstract class HttpServerIntegrationTests : LoggedTest, IClassFixture<Sse
base.Dispose();
}
protected abstract SseClientTransportOptions ClientTransportOptions { get; }
protected abstract HttpClientTransportOptions ClientTransportOptions { get; }
private Task<IMcpClient> GetClientAsync(McpClientOptions? options = null)
private Task<McpClient> GetClientAsync(McpClientOptions? options = null)
{
return _fixture.ConnectMcpClientAsync(options, LoggerFactory);
}

View file

@ -23,21 +23,21 @@ public abstract class MapMcpTests(ITestOutputHelper testOutputHelper) : KestrelI
options.Stateless = Stateless;
}
protected async Task<IMcpClient> ConnectAsync(
protected async Task<McpClient> ConnectAsync(
string? path = null,
SseClientTransportOptions? transportOptions = null,
HttpClientTransportOptions? transportOptions = null,
McpClientOptions? clientOptions = null)
{
// Default behavior when no options are provided
path ??= UseStreamableHttp ? "/" : "/sse";
await using var transport = new SseClientTransport(transportOptions ?? new SseClientTransportOptions
await using var transport = new HttpClientTransport(transportOptions ?? new HttpClientTransportOptions
{
Endpoint = new Uri($"http://localhost:5000{path}"),
TransportMode = UseStreamableHttp ? HttpTransportMode.StreamableHttp : HttpTransportMode.Sse,
}, HttpClient, LoggerFactory);
return await McpClientFactory.CreateAsync(transport, clientOptions, LoggerFactory, TestContext.Current.CancellationToken);
return await McpClient.CreateAsync(transport, clientOptions, LoggerFactory, TestContext.Current.CancellationToken);
}
[Fact]
@ -244,7 +244,7 @@ public abstract class MapMcpTests(ITestOutputHelper testOutputHelper) : KestrelI
private class SamplingRegressionTools
{
[McpServerTool(Name = "sampling-tool")]
public static async Task<string> SamplingToolAsync(IMcpServer server, string prompt, CancellationToken cancellationToken)
public static async Task<string> SamplingToolAsync(McpServer server, string prompt, CancellationToken cancellationToken)
{
// This tool reproduces the scenario described in https://github.com/modelcontextprotocol/csharp-sdk/issues/464
// 1. The client calls tool with request ID 2, because it's the first request after the initialize request.

View file

@ -15,15 +15,15 @@ namespace ModelContextProtocol.AspNetCore.Tests;
public partial class SseIntegrationTests(ITestOutputHelper outputHelper) : KestrelInMemoryTest(outputHelper)
{
private readonly SseClientTransportOptions DefaultTransportOptions = new()
private readonly HttpClientTransportOptions DefaultTransportOptions = new()
{
Endpoint = new("http://localhost:5000/sse"),
Name = "In-memory SSE Client",
};
private Task<IMcpClient> ConnectMcpClientAsync(HttpClient? httpClient = null, SseClientTransportOptions? transportOptions = null)
=> McpClientFactory.CreateAsync(
new SseClientTransport(transportOptions ?? DefaultTransportOptions, httpClient ?? HttpClient, LoggerFactory),
private Task<McpClient> ConnectMcpClientAsync(HttpClient? httpClient = null, HttpClientTransportOptions? transportOptions = null)
=> McpClient.CreateAsync(
new HttpClientTransport(transportOptions ?? DefaultTransportOptions, httpClient ?? HttpClient, LoggerFactory),
loggerFactory: LoggerFactory,
cancellationToken: TestContext.Current.CancellationToken);
@ -195,7 +195,7 @@ public partial class SseIntegrationTests(ITestOutputHelper outputHelper) : Kestr
app.MapMcp();
await app.StartAsync(TestContext.Current.CancellationToken);
var sseOptions = new SseClientTransportOptions
var sseOptions = new HttpClientTransportOptions
{
Endpoint = new("http://localhost:5000/sse"),
Name = "In-memory SSE Client",
@ -222,7 +222,7 @@ public partial class SseIntegrationTests(ITestOutputHelper outputHelper) : Kestr
app.MapMcp();
await app.StartAsync(TestContext.Current.CancellationToken);
var sseOptions = new SseClientTransportOptions
var sseOptions = new HttpClientTransportOptions
{
Endpoint = new("http://localhost:5000/sse"),
Name = "In-memory SSE Client",
@ -257,7 +257,7 @@ public partial class SseIntegrationTests(ITestOutputHelper outputHelper) : Kestr
try
{
var transportTask = transport.RunAsync(cancellationToken: requestAborted);
await using var server = McpServerFactory.Create(transport, optionsSnapshot.Value, loggerFactory, endpoints.ServiceProvider);
await using var server = McpServer.Create(transport, optionsSnapshot.Value, loggerFactory, endpoints.ServiceProvider);
try
{

View file

@ -18,7 +18,7 @@ public class SseServerIntegrationTestFixture : IAsyncDisposable
// multiple tests, so this dispatches the output to the current test.
private readonly DelegatingTestOutputHelper _delegatingTestOutputHelper = new();
private SseClientTransportOptions DefaultTransportOptions { get; set; } = new()
private HttpClientTransportOptions DefaultTransportOptions { get; set; } = new()
{
Endpoint = new("http://localhost:5000/"),
};
@ -44,16 +44,16 @@ public class SseServerIntegrationTestFixture : IAsyncDisposable
public HttpClient HttpClient { get; }
public Task<IMcpClient> ConnectMcpClientAsync(McpClientOptions? options, ILoggerFactory loggerFactory)
public Task<McpClient> ConnectMcpClientAsync(McpClientOptions? options, ILoggerFactory loggerFactory)
{
return McpClientFactory.CreateAsync(
new SseClientTransport(DefaultTransportOptions, HttpClient, loggerFactory),
return McpClient.CreateAsync(
new HttpClientTransport(DefaultTransportOptions, HttpClient, loggerFactory),
options,
loggerFactory,
TestContext.Current.CancellationToken);
}
public void Initialize(ITestOutputHelper output, SseClientTransportOptions clientTransportOptions)
public void Initialize(ITestOutputHelper output, HttpClientTransportOptions clientTransportOptions)
{
_delegatingTestOutputHelper.CurrentTestOutputHelper = output;
DefaultTransportOptions = clientTransportOptions;

View file

@ -8,7 +8,7 @@ public class SseServerIntegrationTests(SseServerIntegrationTestFixture fixture,
: HttpServerIntegrationTests(fixture, testOutputHelper)
{
protected override SseClientTransportOptions ClientTransportOptions => new()
protected override HttpClientTransportOptions ClientTransportOptions => new()
{
Endpoint = new("http://localhost:5000/sse"),
Name = "In-memory SSE Client",

View file

@ -5,7 +5,7 @@ namespace ModelContextProtocol.AspNetCore.Tests;
public class StatelessServerIntegrationTests(SseServerIntegrationTestFixture fixture, ITestOutputHelper testOutputHelper)
: StreamableHttpServerIntegrationTests(fixture, testOutputHelper)
{
protected override SseClientTransportOptions ClientTransportOptions => new()
protected override HttpClientTransportOptions ClientTransportOptions => new()
{
Endpoint = new("http://localhost:5000/stateless"),
Name = "In-memory Streamable HTTP Client",

View file

@ -14,7 +14,7 @@ public class StatelessServerTests(ITestOutputHelper outputHelper) : KestrelInMem
{
private WebApplication? _app;
private readonly SseClientTransportOptions DefaultTransportOptions = new()
private readonly HttpClientTransportOptions DefaultTransportOptions = new()
{
Endpoint = new("http://localhost:5000/"),
Name = "In-memory Streamable HTTP Client",
@ -58,9 +58,9 @@ public class StatelessServerTests(ITestOutputHelper outputHelper) : KestrelInMem
HttpClient.DefaultRequestHeaders.Accept.Add(new("text/event-stream"));
}
private Task<IMcpClient> ConnectMcpClientAsync(McpClientOptions? clientOptions = null)
=> McpClientFactory.CreateAsync(
new SseClientTransport(DefaultTransportOptions, HttpClient, LoggerFactory),
private Task<McpClient> ConnectMcpClientAsync(McpClientOptions? clientOptions = null)
=> McpClient.CreateAsync(
new HttpClientTransport(DefaultTransportOptions, HttpClient, LoggerFactory),
clientOptions, LoggerFactory, TestContext.Current.CancellationToken);
public async ValueTask DisposeAsync()
@ -194,7 +194,7 @@ public class StatelessServerTests(ITestOutputHelper outputHelper) : KestrelInMem
}
[McpServerTool(Name = "testSamplingErrors")]
public static async Task<string> TestSamplingErrors(IMcpServer server)
public static async Task<string> TestSamplingErrors(McpServer server)
{
const string expectedSamplingErrorMessage = "Sampling is not supported in stateless mode.";
@ -212,7 +212,7 @@ public class StatelessServerTests(ITestOutputHelper outputHelper) : KestrelInMem
}
[McpServerTool(Name = "testRootsErrors")]
public static async Task<string> TestRootsErrors(IMcpServer server)
public static async Task<string> TestRootsErrors(McpServer server)
{
const string expectedRootsErrorMessage = "Roots are not supported in stateless mode.";
@ -227,7 +227,7 @@ public class StatelessServerTests(ITestOutputHelper outputHelper) : KestrelInMem
}
[McpServerTool(Name = "testElicitationErrors")]
public static async Task<string> TestElicitationErrors(IMcpServer server)
public static async Task<string> TestElicitationErrors(McpServer server)
{
const string expectedElicitationErrorMessage = "Elicitation is not supported in stateless mode.";

View file

@ -112,13 +112,13 @@ public class StreamableHttpClientConformanceTests(ITestOutputHelper outputHelper
{
await StartAsync();
await using var transport = new SseClientTransport(new()
await using var transport = new HttpClientTransport(new()
{
Endpoint = new("http://localhost:5000/mcp"),
TransportMode = HttpTransportMode.StreamableHttp,
}, HttpClient, LoggerFactory);
await using var client = await McpClientFactory.CreateAsync(transport, loggerFactory: LoggerFactory, cancellationToken: TestContext.Current.CancellationToken);
await using var client = await McpClient.CreateAsync(transport, loggerFactory: LoggerFactory, cancellationToken: TestContext.Current.CancellationToken);
var tools = await client.ListToolsAsync(cancellationToken: TestContext.Current.CancellationToken);
var echoTool = Assert.Single(tools);
@ -132,13 +132,13 @@ public class StreamableHttpClientConformanceTests(ITestOutputHelper outputHelper
{
await StartAsync();
await using var transport = new SseClientTransport(new()
await using var transport = new HttpClientTransport(new()
{
Endpoint = new("http://localhost:5000/mcp"),
TransportMode = HttpTransportMode.StreamableHttp,
}, HttpClient, LoggerFactory);
await using var client = await McpClientFactory.CreateAsync(transport, loggerFactory: LoggerFactory, cancellationToken: TestContext.Current.CancellationToken);
await using var client = await McpClient.CreateAsync(transport, loggerFactory: LoggerFactory, cancellationToken: TestContext.Current.CancellationToken);
var tools = await client.ListToolsAsync(cancellationToken: TestContext.Current.CancellationToken);
var echoTool = Assert.Single(tools);
@ -158,13 +158,13 @@ public class StreamableHttpClientConformanceTests(ITestOutputHelper outputHelper
{
await StartAsync(enableDelete: true);
await using var transport = new SseClientTransport(new()
await using var transport = new HttpClientTransport(new()
{
Endpoint = new("http://localhost:5000/mcp"),
TransportMode = HttpTransportMode.StreamableHttp,
}, HttpClient, LoggerFactory);
await using var client = await McpClientFactory.CreateAsync(transport, loggerFactory: LoggerFactory, cancellationToken: TestContext.Current.CancellationToken);
await using var client = await McpClient.CreateAsync(transport, loggerFactory: LoggerFactory, cancellationToken: TestContext.Current.CancellationToken);
// Dispose should trigger DELETE request
await client.DisposeAsync();

View file

@ -252,7 +252,7 @@ public class StreamableHttpServerConformanceTests(ITestOutputHelper outputHelper
[Fact]
public async Task GetRequest_Receives_UnsolicitedNotifications()
{
IMcpServer? server = null;
McpServer? server = null;
Builder.Services.AddMcpServer()
.WithHttpTransport(options =>

View file

@ -11,7 +11,7 @@ public class StreamableHttpServerIntegrationTests(SseServerIntegrationTestFixtur
{"jsonrpc":"2.0","id":"1","method":"initialize","params":{"protocolVersion":"2025-03-26","capabilities":{},"clientInfo":{"name":"IntegrationTestClient","version":"1.0.0"}}}
""";
protected override SseClientTransportOptions ClientTransportOptions => new()
protected override HttpClientTransportOptions ClientTransportOptions => new()
{
Endpoint = new("http://localhost:5000/"),
Name = "In-memory Streamable HTTP Client",

View file

@ -51,7 +51,7 @@ internal static class Program
using var loggerFactory = CreateLoggerFactory();
await using var stdioTransport = new StdioServerTransport("TestServer", loggerFactory);
await using IMcpServer server = McpServerFactory.Create(stdioTransport, options, loggerFactory);
await using McpServer server = McpServer.Create(stdioTransport, options, loggerFactory);
Log.Logger.Information("Server running...");
@ -61,7 +61,7 @@ internal static class Program
await server.RunAsync();
}
private static async Task RunBackgroundLoop(IMcpServer server, CancellationToken cancellationToken = default)
private static async Task RunBackgroundLoop(McpServer server, CancellationToken cancellationToken = default)
{
var loggingLevels = (LoggingLevel[])Enum.GetValues(typeof(LoggingLevel));
var random = new Random();

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

View file

@ -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,

View file

@ -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()
{

Some files were not shown because too many files have changed in this diff Show more