Separate ASP.NET Core tests into a distinct project and make the main test project netfx compatible. (#254)

* Separate ASP.NET Core tests into a distinct project and make the main test project netfx compatible.

* Fix merge conflicts.

* Update tests/ModelContextProtocol.Tests/ModelContextProtocol.Tests.csproj

Co-authored-by: Stephen Halter <halter73@gmail.com>

* Revert "Fix merge conflicts."

This reverts commit 852169b96786bad2144795540fa164e20b4b197e.

* Fix merge conflicts

---------

Co-authored-by: Stephen Halter <halter73@gmail.com>
This commit is contained in:
Eirik Tsarpalis 2025-04-09 19:16:53 +01:00 • committed by GitHub
commit 39ab6cde0d
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
32 changed files with 324 additions and 63 deletions

View file

@ -66,5 +66,6 @@
<PackageVersion Include="System.Linq.AsyncEnumerable" Version="$(System10Version)" />
<PackageVersion Include="xunit.v3" Version="2.0.1" />
<PackageVersion Include="xunit.runner.visualstudio" Version="3.0.2" />
<PackageVersion Include="System.Net.Http" Version="4.3.4" />
</ItemGroup>
</Project>

View file

@ -54,6 +54,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "EverythingServer", "samples
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ModelContextProtocol.AspNetCore", "src\ModelContextProtocol.AspNetCore\ModelContextProtocol.AspNetCore.csproj", "{37B6A5E0-9995-497D-8B43-3BC6870CC716}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ModelContextProtocol.AspNetCore.Tests", "tests\ModelContextProtocol.AspNetCore.Tests\ModelContextProtocol.AspNetCore.Tests.csproj", "{85557BA6-3D29-4C95-A646-2A972B1C2F25}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@ -104,6 +106,10 @@ Global
{37B6A5E0-9995-497D-8B43-3BC6870CC716}.Debug|Any CPU.Build.0 = Debug|Any CPU
{37B6A5E0-9995-497D-8B43-3BC6870CC716}.Release|Any CPU.ActiveCfg = Release|Any CPU
{37B6A5E0-9995-497D-8B43-3BC6870CC716}.Release|Any CPU.Build.0 = Release|Any CPU
{85557BA6-3D29-4C95-A646-2A972B1C2F25}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{85557BA6-3D29-4C95-A646-2A972B1C2F25}.Debug|Any CPU.Build.0 = Debug|Any CPU
{85557BA6-3D29-4C95-A646-2A972B1C2F25}.Release|Any CPU.ActiveCfg = Release|Any CPU
{85557BA6-3D29-4C95-A646-2A972B1C2F25}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
@ -121,6 +127,7 @@ Global
{0D1552DC-E6ED-4AAC-5562-12F8352F46AA} = {02EA681E-C7D8-13C7-8484-4AC65E1B71E8}
{17B8453F-AB72-99C5-E5EA-D0B065A6AE65} = {02EA681E-C7D8-13C7-8484-4AC65E1B71E8}
{37B6A5E0-9995-497D-8B43-3BC6870CC716} = {A2F1F52A-9107-4BF8-8C3F-2F6670E7D0AD}
{85557BA6-3D29-4C95-A646-2A972B1C2F25} = {2A77AF5C-138A-4EBB-9A13-9205DCD67928}
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {384A3888-751F-4D75-9AE5-587330582D89}

View file

@ -35,5 +35,5 @@ catch (Exception ex)
}
finally
{
await Log.CloseAndFlushAsync();
Log.CloseAndFlush();
}

View file

@ -2,7 +2,7 @@
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFrameworks>net9.0;net8.0</TargetFrameworks>
<TargetFrameworks>net9.0;net8.0;net472</TargetFrameworks>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<!--

View file

@ -10,4 +10,28 @@ internal static class ProcessExtensions
_ = entireProcessTree;
process.Kill();
}
public static async Task WaitForExitAsync(this Process process, CancellationToken cancellationToken = default)
{
if (process.HasExited)
{
return;
}
var tcs = new TaskCompletionSource<bool>();
void ProcessExitedHandler(object? sender, EventArgs e) => tcs.TrySetResult(true);
try
{
process.EnableRaisingEvents = true;
process.Exited += ProcessExitedHandler;
using var _ = cancellationToken.Register(() => tcs.TrySetCanceled(cancellationToken));
await tcs.Task.ConfigureAwait(false);
}
finally
{
process.Exited -= ProcessExitedHandler;
}
}
}

View file

@ -4,21 +4,7 @@ internal static class TextReaderExtensions
{
public static Task<string> ReadLineAsync(this TextReader reader, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled<string>(cancellationToken);
}
cancellationToken.ThrowIfCancellationRequested();
return reader.ReadLineAsync();
}
public static Task<string> ReadToEndAsync(this TextReader reader, CancellationToken cancellationToken)
{
if (cancellationToken.IsCancellationRequested)
{
return Task.FromCanceled<string>(cancellationToken);
}
return reader.ReadToEndAsync();
}
}

View file

@ -5,33 +5,6 @@ namespace System.IO;
internal static class TextWriterExtensions
{
public static async Task WriteLineAsync(this TextWriter writer, ReadOnlyMemory<char> value, CancellationToken cancellationToken)
{
Throw.IfNull(writer);
if (value.IsEmpty)
{
return;
}
cancellationToken.ThrowIfCancellationRequested();
if (MemoryMarshal.TryGetString(value, out string str, out int start, out int length) &&
start == 0 && length == str.Length)
{
await writer.WriteLineAsync(str).ConfigureAwait(false);
}
else if (MemoryMarshal.TryGetArray(value, out ArraySegment<char> array) &&
array.Array is not null && array.Offset == 0 && array.Count == array.Array.Length)
{
await writer.WriteLineAsync(array.Array).ConfigureAwait(false);
}
else
{
await writer.WriteLineAsync(value.ToArray()).ConfigureAwait(false);
}
}
public static async Task FlushAsync(this TextWriter writer, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();

View file

@ -9,13 +9,18 @@ internal static class TaskExtensions
return WaitAsync(task, Timeout.InfiniteTimeSpan, cancellationToken);
}
public static async Task<T> WaitAsync<T>(this Task<T> task, CancellationToken cancellationToken)
public static Task<T> WaitAsync<T>(this Task<T> task, CancellationToken cancellationToken)
{
await WaitAsync(task, Timeout.InfiniteTimeSpan, cancellationToken);
return WaitAsync(task, Timeout.InfiniteTimeSpan, cancellationToken);
}
public static async Task<T> WaitAsync<T>(this Task<T> task, TimeSpan timeout, CancellationToken cancellationToken = default)
{
await WaitAsync((Task)task, timeout, cancellationToken).ConfigureAwait(false);
return task.Result;
}
public static async Task WaitAsync(this Task task, TimeSpan timeout, CancellationToken cancellationToken)
public static async Task WaitAsync(this Task task, TimeSpan timeout, CancellationToken cancellationToken = default)
{
Throw.IfNull(task);

41
src/Common/Throw.cs Normal file
View file

@ -0,0 +1,41 @@
using System.Diagnostics.CodeAnalysis;
using System.Runtime.CompilerServices;
namespace ModelContextProtocol.Utils;
/// <summary>Provides helper methods for throwing exceptions.</summary>
internal static class Throw
{
// NOTE: Most of these should be replaced with extension statics for the relevant extension
// type as downlevel polyfills once the C# 14 extension everything feature is available.
public static void IfNull([NotNull] object? arg, [CallerArgumentExpression(nameof(arg))] string? parameterName = null)
{
if (arg is null)
{
ThrowArgumentNullException(parameterName);
}
}
public static void IfNullOrWhiteSpace([NotNull] string? arg, [CallerArgumentExpression(nameof(arg))] string? parameterName = null)
{
if (arg is null || arg.AsSpan().IsWhiteSpace())
{
ThrowArgumentNullOrWhiteSpaceException(parameterName);
}
}
[DoesNotReturn]
private static void ThrowArgumentNullOrWhiteSpaceException(string? parameterName)
{
if (parameterName is null)
{
ThrowArgumentNullException(parameterName);
}
throw new ArgumentException("Value cannot be empty or composed entirely of whitespace.", parameterName);
}
[DoesNotReturn]
private static void ThrowArgumentNullException(string? parameterName) => throw new ArgumentNullException(parameterName);
}

View file

@ -14,6 +14,10 @@
<IsAotCompatible>true</IsAotCompatible>
</PropertyGroup>
<ItemGroup>
<Compile Include="..\Common\Throw.cs" Link="Utils\Throw.cs" />
</ItemGroup>
<!-- Dependencies only needed by netstandard2.0 -->
<ItemGroup Condition="'$(TargetFramework)' == 'netstandard2.0'">
<Compile Include="..\Common\Polyfills\**\*.cs" />

View file

@ -0,0 +1 @@
global using Xunit;

View file

@ -0,0 +1,52 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>net9.0;net8.0</TargetFrameworks>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<LangVersion>Latest</LangVersion>
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
<RootNamespace>ModelContextProtocol.AspNetCore.Tests</RootNamespace>
</PropertyGroup>
<PropertyGroup>
<!-- Without this, tests are currently not showing results until all tests complete
https://xunit.net/docs/getting-started/v3/microsoft-testing-platform
-->
<DisableTestingPlatformServerCapability>true</DisableTestingPlatformServerCapability>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="coverlet.collector">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="GitHubActionsTestLogger">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.AI" />
<PackageReference Include="Microsoft.Extensions.AI.OpenAI" />
<PackageReference Include="Microsoft.Extensions.Logging" />
<PackageReference Include="Microsoft.Extensions.Logging.Console" />
<PackageReference Include="Microsoft.NET.Test.Sdk" />
<PackageReference Include="Moq" />
<PackageReference Include="OpenTelemetry" />
<PackageReference Include="OpenTelemetry.Exporter.InMemory" />
<PackageReference Include="System.Linq.AsyncEnumerable" />
<PackageReference Include="xunit.v3" />
<PackageReference Include="xunit.runner.visualstudio">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\samples\TestServerWithHosting\TestServerWithHosting.csproj" />
<ProjectReference Include="..\..\src\ModelContextProtocol\ModelContextProtocol.csproj" />
<ProjectReference Include="..\..\src\ModelContextProtocol.AspNetCore\ModelContextProtocol.AspNetCore.csproj" />
<ProjectReference Include="..\ModelContextProtocol.TestSseServer\ModelContextProtocol.TestSseServer.csproj" />
</ItemGroup>
</Project>

View file

@ -0,0 +1,19 @@
using Microsoft.AspNetCore.Builder;
using ModelContextProtocol.Tests.Utils;
namespace ModelContextProtocol.AspNetCore.Tests.Server;
public class MapMcpTests(ITestOutputHelper testOutputHelper) : KestrelInMemoryTest(testOutputHelper)
{
[Fact]
public async Task Allows_Customizing_Route()
{
await using var app = Builder.Build();
app.MapMcp("/mcp");
await app.StartAsync(TestContext.Current.CancellationToken);
using var httpClient = CreateHttpClient();
using var response = await httpClient.GetAsync("http://localhost/mcp/sse", HttpCompletionOption.ResponseHeadersRead, TestContext.Current.CancellationToken);
response.EnsureSuccessStatusCode();
}
}

View file

@ -0,0 +1,208 @@
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Routing;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using ModelContextProtocol.Client;
using ModelContextProtocol.Protocol.Messages;
using ModelContextProtocol.Protocol.Transport;
using ModelContextProtocol.Server;
using ModelContextProtocol.Tests.Utils;
using ModelContextProtocol.Utils.Json;
using TestServerWithHosting.Tools;
namespace ModelContextProtocol.Tests;
public class SseIntegrationTests(ITestOutputHelper outputHelper) : KestrelInMemoryTest(outputHelper)
{
private SseClientTransportOptions DefaultTransportOptions = new()
{
Endpoint = new Uri("http://localhost/sse"),
Name = "In-memory Test Server",
};
private Task<IMcpClient> ConnectMcpClient(HttpClient httpClient, McpClientOptions? clientOptions = null)
=> McpClientFactory.CreateAsync(
new SseClientTransport(DefaultTransportOptions, httpClient, LoggerFactory),
clientOptions,
LoggerFactory,
TestContext.Current.CancellationToken);
[Fact]
public async Task ConnectAndReceiveMessage_InMemoryServer()
{
await using var app = Builder.Build();
app.MapMcp();
await app.StartAsync(TestContext.Current.CancellationToken);
using var httpClient = CreateHttpClient();
await using var mcpClient = await ConnectMcpClient(httpClient);
// Send a test message through POST endpoint
await mcpClient.SendNotificationAsync("test/message", new { message = "Hello, SSE!" }, cancellationToken: TestContext.Current.CancellationToken);
Assert.True(true);
}
[Fact]
public async Task ConnectAndReceiveMessage_InMemoryServer_WithFullEndpointEventUri()
{
await using var app = Builder.Build();
MapAbsoluteEndpointUriMcp(app);
await app.StartAsync(TestContext.Current.CancellationToken);
using var httpClient = CreateHttpClient();
await using var mcpClient = await ConnectMcpClient(httpClient);
// Send a test message through POST endpoint
await mcpClient.SendNotificationAsync("test/message", new { message = "Hello, SSE!" }, cancellationToken: TestContext.Current.CancellationToken);
Assert.True(true);
}
[Fact]
public async Task ConnectAndReceiveNotification_InMemoryServer()
{
var receivedNotification = new TaskCompletionSource<string?>();
await using var app = Builder.Build();
app.MapMcp(runSessionAsync: (httpContext, mcpServer, cancellationToken) =>
{
mcpServer.RegisterNotificationHandler("test/notification", async (notification, cancellationToken) =>
{
Assert.Equal("Hello from client!", notification.Params?["message"]?.GetValue<string>());
await mcpServer.SendNotificationAsync("test/notification", new { message = "Hello from server!" }, cancellationToken: cancellationToken);
});
return mcpServer.RunAsync(cancellationToken);
});
await app.StartAsync(TestContext.Current.CancellationToken);
using var httpClient = CreateHttpClient();
await using var mcpClient = await ConnectMcpClient(httpClient);
mcpClient.RegisterNotificationHandler("test/notification", (args, ca) =>
{
var msg = args.Params?["message"]?.GetValue<string>();
receivedNotification.SetResult(msg);
return Task.CompletedTask;
});
// Send a test message through POST endpoint
await mcpClient.SendNotificationAsync("test/notification", new { message = "Hello from client!" }, cancellationToken: TestContext.Current.CancellationToken);
var message = await receivedNotification.Task.WaitAsync(TimeSpan.FromSeconds(10), TestContext.Current.CancellationToken);
Assert.Equal("Hello from server!", message);
}
[Fact]
public async Task AddMcpServer_CanBeCalled_MultipleTimes()
{
var firstOptionsCallbackCallCount = 0;
var secondOptionsCallbackCallCount = 0;
Builder.Services.AddMcpServer(options =>
{
Interlocked.Increment(ref firstOptionsCallbackCallCount);
})
.WithTools<EchoTool>();
Builder.Services.AddMcpServer(options =>
{
Interlocked.Increment(ref secondOptionsCallbackCallCount);
})
.WithTools<SampleLlmTool>();
await using var app = Builder.Build();
app.MapMcp();
await app.StartAsync(TestContext.Current.CancellationToken);
using var httpClient = CreateHttpClient();
await using var mcpClient = await ConnectMcpClient(httpClient);
// Options can be lazily initialized, but they must be instantiated by the time an MCP client can finish connecting.
// Callbacks can be called multiple times if configureOptionsAsync is configured, because that uses the IOptionsFactory,
// but that's not the case in this test.
Assert.Equal(1, firstOptionsCallbackCallCount);
Assert.Equal(1, secondOptionsCallbackCallCount);
var tools = await mcpClient.ListToolsAsync(cancellationToken: TestContext.Current.CancellationToken);
Assert.Equal(2, tools.Count);
Assert.Contains(tools, tools => tools.Name == "Echo");
Assert.Contains(tools, tools => tools.Name == "sampleLLM");
var echoResponse = await mcpClient.CallToolAsync(
"Echo",
new Dictionary<string, object?>
{
["message"] = "from client!"
},
cancellationToken: TestContext.Current.CancellationToken);
var textContent = Assert.Single(echoResponse.Content, c => c.Type == "text");
Assert.Equal("hello from client!", textContent.Text);
}
private static void MapAbsoluteEndpointUriMcp(IEndpointRouteBuilder endpoints)
{
var loggerFactory = endpoints.ServiceProvider.GetRequiredService<ILoggerFactory>();
var optionsSnapshot = endpoints.ServiceProvider.GetRequiredService<IOptions<McpServerOptions>>();
var routeGroup = endpoints.MapGroup("");
SseResponseStreamTransport? session = null;
routeGroup.MapGet("/sse", async context =>
{
var response = context.Response;
var requestAborted = context.RequestAborted;
response.Headers.ContentType = "text/event-stream";
await using var transport = new SseResponseStreamTransport(response.Body, "http://localhost/message");
session = transport;
try
{
var transportTask = transport.RunAsync(cancellationToken: requestAborted);
await using var server = McpServerFactory.Create(transport, optionsSnapshot.Value, loggerFactory, endpoints.ServiceProvider);
try
{
await server.RunAsync(requestAborted);
}
finally
{
await transport.DisposeAsync();
await transportTask;
}
}
catch (OperationCanceledException) when (requestAborted.IsCancellationRequested)
{
// RequestAborted always triggers when the client disconnects before a complete response body is written,
// but this is how SSE connections are typically closed.
}
});
routeGroup.MapPost("/message", async context =>
{
if (session is null)
{
await Results.BadRequest("Session not started.").ExecuteAsync(context);
return;
}
var message = (IJsonRpcMessage?)await context.Request.ReadFromJsonAsync(McpJsonUtilities.DefaultOptions.GetTypeInfo(typeof(IJsonRpcMessage)), context.RequestAborted);
if (message is null)
{
await Results.BadRequest("No message in request body.").ExecuteAsync(context);
return;
}
await session.OnMessageReceivedAsync(message, context.RequestAborted);
context.Response.StatusCode = StatusCodes.Status202Accepted;
await context.Response.WriteAsync("Accepted");
});
}
}

View file

@ -0,0 +1,83 @@
using Microsoft.Extensions.Logging;
using ModelContextProtocol.Client;
using ModelContextProtocol.Protocol.Transport;
using ModelContextProtocol.Test.Utils;
using ModelContextProtocol.Tests.Utils;
using ModelContextProtocol.TestSseServer;
namespace ModelContextProtocol.Tests;
public class SseServerIntegrationTestFixture : IAsyncDisposable
{
private readonly KestrelInMemoryTransport _inMemoryTransport = new();
private readonly Task _serverTask;
private readonly CancellationTokenSource _stopCts = new();
// XUnit's ITestOutputHelper is created per test, while this fixture is used for
// multiple tests, so this dispatches the output to the current test.
private readonly DelegatingTestOutputHelper _delegatingTestOutputHelper = new();
private SseClientTransportOptions DefaultTransportOptions { get; } = new()
{
Endpoint = new Uri("http://localhost/sse"),
Name = "TestServer",
};
public SseServerIntegrationTestFixture()
{
var socketsHttpHandler = new SocketsHttpHandler()
{
ConnectCallback = (context, token) =>
{
var connection = _inMemoryTransport.CreateConnection();
return new(connection.ClientStream);
},
};
HttpClient = new HttpClient(socketsHttpHandler)
{
BaseAddress = DefaultTransportOptions.Endpoint,
};
_serverTask = Program.MainAsync([], new XunitLoggerProvider(_delegatingTestOutputHelper), _inMemoryTransport, _stopCts.Token);
}
public HttpClient HttpClient { get; }
public Task<IMcpClient> ConnectMcpClientAsync(McpClientOptions? options, ILoggerFactory loggerFactory)
{
return McpClientFactory.CreateAsync(
new SseClientTransport(DefaultTransportOptions, HttpClient, loggerFactory),
options,
loggerFactory,
TestContext.Current.CancellationToken);
}
public void Initialize(ITestOutputHelper output)
{
_delegatingTestOutputHelper.CurrentTestOutputHelper = output;
}
public void TestCompleted()
{
_delegatingTestOutputHelper.CurrentTestOutputHelper = null;
}
public async ValueTask DisposeAsync()
{
_delegatingTestOutputHelper.CurrentTestOutputHelper = null;
HttpClient.Dispose();
_stopCts.Cancel();
try
{
await _serverTask.ConfigureAwait(false);
}
catch (OperationCanceledException)
{
}
_stopCts.Dispose();
}
}

View file

@ -0,0 +1,325 @@
using ModelContextProtocol.Client;
using ModelContextProtocol.Protocol.Types;
using ModelContextProtocol.Tests.Utils;
using System.Net;
using System.Text;
namespace ModelContextProtocol.Tests;
public class SseServerIntegrationTests : LoggedTest, IClassFixture<SseServerIntegrationTestFixture>
{
private readonly SseServerIntegrationTestFixture _fixture;
public SseServerIntegrationTests(SseServerIntegrationTestFixture fixture, ITestOutputHelper testOutputHelper)
: base(testOutputHelper)
{
_fixture = fixture;
_fixture.Initialize(testOutputHelper);
}
public override void Dispose()
{
_fixture.TestCompleted();
base.Dispose();
}
private Task<IMcpClient> GetClientAsync(McpClientOptions? options = null)
{
return _fixture.ConnectMcpClientAsync(options, LoggerFactory);
}
[Fact]
public async Task ConnectAndPing_Sse_TestServer()
{
// Arrange
// Act
await using var client = await GetClientAsync();
await client.PingAsync(TestContext.Current.CancellationToken);
// Assert
Assert.NotNull(client);
}
[Fact]
public async Task Connect_TestServer_ShouldProvideServerFields()
{
// Arrange
// Act
await using var client = await GetClientAsync();
// Assert
Assert.NotNull(client.ServerCapabilities);
Assert.NotNull(client.ServerInfo);
}
[Fact]
public async Task ListTools_Sse_TestServer()
{
// arrange
// act
await using var client = await GetClientAsync();
var tools = await client.ListToolsAsync(cancellationToken: TestContext.Current.CancellationToken);
// assert
Assert.NotNull(tools);
}
[Fact]
public async Task CallTool_Sse_EchoServer()
{
// arrange
// act
await using var client = await GetClientAsync();
var result = await client.CallToolAsync(
"echo",
new Dictionary<string, object?>
{
["message"] = "Hello MCP!"
},
cancellationToken: TestContext.Current.CancellationToken
);
// assert
Assert.NotNull(result);
Assert.False(result.IsError);
var textContent = Assert.Single(result.Content, c => c.Type == "text");
Assert.Equal("Echo: Hello MCP!", textContent.Text);
}
[Fact]
public async Task ListResources_Sse_TestServer()
{
// arrange
// act
await using var client = await GetClientAsync();
IList<Resource> allResources = await client.ListResourcesAsync(TestContext.Current.CancellationToken);
// The everything server provides 100 test resources
Assert.Equal(100, allResources.Count);
}
[Fact]
public async Task ReadResource_Sse_TextResource()
{
// arrange
// act
await using var client = await GetClientAsync();
// Odd numbered resources are text in the everything server (despite the docs saying otherwise)
// 1 is index 0, which is "even" in the 0-based index
// We copied this oddity to the test server
var result = await client.ReadResourceAsync("test://static/resource/1", TestContext.Current.CancellationToken);
Assert.NotNull(result);
Assert.Single(result.Contents);
TextResourceContents textContent = Assert.IsType<TextResourceContents>(result.Contents[0]);
Assert.NotNull(textContent.Text);
}
[Fact]
public async Task ReadResource_Sse_BinaryResource()
{
// arrange
// act
await using var client = await GetClientAsync();
// Even numbered resources are binary in the everything server (despite the docs saying otherwise)
// 2 is index 1, which is "odd" in the 0-based index
// We copied this oddity to the test server
var result = await client.ReadResourceAsync("test://static/resource/2", TestContext.Current.CancellationToken);
Assert.NotNull(result);
Assert.Single(result.Contents);
BlobResourceContents blobContent = Assert.IsType<BlobResourceContents>(result.Contents[0]);
Assert.NotNull(blobContent.Blob);
}
[Fact]
public async Task ListPrompts_Sse_TestServer()
{
// arrange
// act
await using var client = await GetClientAsync();
var prompts = await client.ListPromptsAsync(TestContext.Current.CancellationToken);
// assert
Assert.NotNull(prompts);
Assert.NotEmpty(prompts);
// We could add specific assertions for the known prompts
Assert.Contains(prompts, p => p.Name == "simple_prompt");
Assert.Contains(prompts, p => p.Name == "complex_prompt");
}
[Fact]
public async Task GetPrompt_Sse_SimplePrompt()
{
// arrange
// act
await using var client = await GetClientAsync();
var result = await client.GetPromptAsync("simple_prompt", null, cancellationToken: TestContext.Current.CancellationToken);
// assert
Assert.NotNull(result);
Assert.NotEmpty(result.Messages);
}
[Fact]
public async Task GetPrompt_Sse_ComplexPrompt()
{
// arrange
// act
await using var client = await GetClientAsync();
var arguments = new Dictionary<string, object?>
{
{ "temperature", "0.7" },
{ "style", "formal" }
};
var result = await client.GetPromptAsync("complex_prompt", arguments, cancellationToken: TestContext.Current.CancellationToken);
// assert
Assert.NotNull(result);
Assert.NotEmpty(result.Messages);
}
[Fact]
public async Task GetPrompt_Sse_NonExistent_ThrowsException()
{
// arrange
// act
await using var client = await GetClientAsync();
await Assert.ThrowsAsync<McpException>(() =>
client.GetPromptAsync("non_existent_prompt", null, cancellationToken: TestContext.Current.CancellationToken));
}
[Fact]
public async Task Sampling_Sse_TestServer()
{
// arrange
// Set up the sampling handler
int samplingHandlerCalls = 0;
#pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously
McpClientOptions options = new();
options.Capabilities = new();
options.Capabilities.Sampling ??= new();
options.Capabilities.Sampling.SamplingHandler = async (_, _, _) =>
{
samplingHandlerCalls++;
return new CreateMessageResult
{
Model = "test-model",
Role = "assistant",
Content = new Content
{
Type = "text",
Text = "Test response"
}
};
};
await using var client = await GetClientAsync(options);
#pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously
// Call the server's sampleLLM tool which should trigger our sampling handler
var result = await client.CallToolAsync("sampleLLM", new Dictionary<string, object?>
{
["prompt"] = "Test prompt",
["maxTokens"] = 100
},
cancellationToken: TestContext.Current.CancellationToken);
// assert
Assert.NotNull(result);
var textContent = Assert.Single(result.Content);
Assert.Equal("text", textContent.Type);
Assert.False(string.IsNullOrEmpty(textContent.Text));
}
[Fact]
public async Task CallTool_Sse_EchoServer_Concurrently()
{
await using var client1 = await GetClientAsync();
await using var client2 = await GetClientAsync();
for (int i = 0; i < 4; i++)
{
var client = (i % 2 == 0) ? client1 : client2;
var result = await client.CallToolAsync(
"echo",
new Dictionary<string, object?>
{
["message"] = $"Hello MCP! {i}"
},
cancellationToken: TestContext.Current.CancellationToken
);
Assert.NotNull(result);
Assert.False(result.IsError);
var textContent = Assert.Single(result.Content, c => c.Type == "text");
Assert.Equal($"Echo: Hello MCP! {i}", textContent.Text);
}
}
[Fact]
public async Task EventSourceResponse_Includes_ExpectedHeaders()
{
using var sseResponse = await _fixture.HttpClient.GetAsync("", HttpCompletionOption.ResponseHeadersRead, TestContext.Current.CancellationToken);
sseResponse.EnsureSuccessStatusCode();
Assert.Equal("text/event-stream", sseResponse.Content.Headers.ContentType?.MediaType);
Assert.Equal("identity", sseResponse.Content.Headers.ContentEncoding.ToString());
Assert.NotNull(sseResponse.Headers.CacheControl);
Assert.True(sseResponse.Headers.CacheControl.NoStore);
Assert.True(sseResponse.Headers.CacheControl.NoCache);
}
[Fact]
public async Task EventSourceStream_Includes_MessageEventType()
{
// Simulate our own MCP client handshake using a plain HttpClient so we can look for "event: message"
// in the raw SSE response stream which is not exposed by the real MCP client.
await using var sseResponse = await _fixture.HttpClient.GetStreamAsync("", TestContext.Current.CancellationToken);
using var streamReader = new StreamReader(sseResponse);
var endpointEvent = await streamReader.ReadLineAsync(TestContext.Current.CancellationToken);
Assert.Equal("event: endpoint", endpointEvent);
var endpointData = await streamReader.ReadLineAsync(TestContext.Current.CancellationToken);
Assert.NotNull(endpointData);
Assert.StartsWith("data: ", endpointData);
var messageEndpoint = endpointData["data: ".Length..];
const string initializeRequest = """
{"jsonrpc":"2.0","id":"1","method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"IntegrationTestClient","version":"1.0.0"}}}
""";
using (var initializeRequestBody = new StringContent(initializeRequest, Encoding.UTF8, "application/json"))
{
var response = await _fixture.HttpClient.PostAsync(messageEndpoint, initializeRequestBody, TestContext.Current.CancellationToken);
Assert.Equal(HttpStatusCode.Accepted, response.StatusCode);
}
const string initializedNotification = """
{"jsonrpc":"2.0","method":"notifications/initialized"}
""";
using (var initializedNotificationBody = new StringContent(initializedNotification, Encoding.UTF8, "application/json"))
{
var response = await _fixture.HttpClient.PostAsync(messageEndpoint, initializedNotificationBody, TestContext.Current.CancellationToken);
Assert.Equal(HttpStatusCode.Accepted, response.StatusCode);
}
Assert.Equal("", await streamReader.ReadLineAsync(TestContext.Current.CancellationToken));
var messageEvent = await streamReader.ReadLineAsync(TestContext.Current.CancellationToken);
Assert.Equal("event: message", messageEvent);
}
}

View file

@ -0,0 +1,13 @@
namespace ModelContextProtocol.Tests.Utils;
public class DelegatingTestOutputHelper : ITestOutputHelper
{
public ITestOutputHelper? CurrentTestOutputHelper { get; set; }
public string Output => CurrentTestOutputHelper?.Output ?? string.Empty;
public void Write(string message) => CurrentTestOutputHelper?.Write(message);
public void Write(string format, params object[] args) => CurrentTestOutputHelper?.Write(format, args);
public void WriteLine(string message) => CurrentTestOutputHelper?.WriteLine(message);
public void WriteLine(string format, params object[] args) => CurrentTestOutputHelper?.WriteLine(format, args);
}

View file

@ -0,0 +1,113 @@
using Microsoft.AspNetCore.Connections;
using Microsoft.AspNetCore.Http.Features;
using System.IO.Pipelines;
namespace ModelContextProtocol.Tests.Utils;
public sealed class KestrelInMemoryConnection : ConnectionContext
{
private readonly Pipe _clientToServerPipe = new();
private readonly Pipe _serverToClientPipe = new();
private readonly CancellationTokenSource _connectionClosedCts = new();
private readonly FeatureCollection _features = new();
public KestrelInMemoryConnection()
{
ConnectionClosed = _connectionClosedCts.Token;
Transport = new DuplexPipe
{
Input = _clientToServerPipe.Reader,
Output = _serverToClientPipe.Writer,
};
Application = new DuplexPipe
{
Input = _serverToClientPipe.Reader,
Output = _clientToServerPipe.Writer,
};
ClientStream = new DuplexStream(Application, _connectionClosedCts);
}
public IDuplexPipe Application { get; }
public Stream ClientStream { get; }
public override IDuplexPipe Transport { get; set; }
public override string ConnectionId { get; set; } = Guid.NewGuid().ToString("N");
public override IFeatureCollection Features => _features;
public override IDictionary<object, object?> Items { get; set; } = new Dictionary<object, object?>();
public override async ValueTask DisposeAsync()
{
// This is called by Kestrel. The client should dispose the DuplexStream which
// completes the other half of these pipes.
await _serverToClientPipe.Writer.CompleteAsync();
await _serverToClientPipe.Reader.CompleteAsync();
// Don't bother disposing the _connectionClosedCts, since this is just for testing,
// and it's annoying to synchronize with DuplexStream.
await base.DisposeAsync();
}
private class DuplexPipe : IDuplexPipe
{
public required PipeReader Input { get; init; }
public required PipeWriter Output { get; init; }
}
private class DuplexStream(IDuplexPipe duplexPipe, CancellationTokenSource connectionClosedCts) : Stream
{
private readonly Stream _readStream = duplexPipe.Input.AsStream();
private readonly Stream _writeStream = duplexPipe.Output.AsStream();
public override bool CanRead => true;
public override bool CanWrite => true;
public override bool CanSeek => false;
public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
=> _readStream.ReadAsync(buffer, offset, count, cancellationToken);
public override ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)
=> _readStream.ReadAsync(buffer, cancellationToken);
public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
=> _writeStream.WriteAsync(buffer, offset, count, cancellationToken);
public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default)
=> _writeStream.WriteAsync(buffer, cancellationToken);
public override Task FlushAsync(CancellationToken cancellationToken)
=> _writeStream.FlushAsync(cancellationToken);
protected override void Dispose(bool disposing)
{
// Signal to the server the the client has closed the connection, and dispose the client-half of the Pipes.
connectionClosedCts.Cancel();
duplexPipe.Input.Complete();
duplexPipe.Output.Complete();
}
// Unsupported stuff
public override long Length => throw new NotSupportedException();
public override long Position
{
get => throw new NotSupportedException();
set => throw new NotSupportedException();
}
public override long Seek(long offset, SeekOrigin origin)
{
throw new NotSupportedException();
}
public override void SetLength(long value)
{
throw new NotSupportedException();
}
// Don't bother supporting sync or APM methods. SocketsHttpHandler shouldn't use them.
public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException();
public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException();
public override void Flush() => throw new NotSupportedException();
}
}

View file

@ -0,0 +1,38 @@
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Connections;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
namespace ModelContextProtocol.Tests.Utils;
public class KestrelInMemoryTest : LoggedTest
{
private readonly KestrelInMemoryTransport _inMemoryTransport = new();
public KestrelInMemoryTest(ITestOutputHelper testOutputHelper)
: base(testOutputHelper)
{
// Use SlimBuilder instead of EmptyBuilder to avoid having to call UseRouting() and UseEndpoints(_ => { })
// or a helper that does the same every test. But clear out the existing socket transport to avoid potential port conflicts.
Builder = WebApplication.CreateSlimBuilder();
Builder.Services.RemoveAll<IConnectionListenerFactory>();
Builder.Services.AddSingleton<IConnectionListenerFactory>(_inMemoryTransport);
Builder.Services.AddSingleton(LoggerProvider);
}
public WebApplicationBuilder Builder { get; }
public HttpClient CreateHttpClient()
{
var socketsHttpHandler = new SocketsHttpHandler()
{
ConnectCallback = (context, token) =>
{
var connection = _inMemoryTransport.CreateConnection();
return new(connection.ClientStream);
},
};
return new HttpClient(socketsHttpHandler);
}
}

View file

@ -0,0 +1,50 @@
using Microsoft.AspNetCore.Connections;
using System.Net;
using System.Threading.Channels;
namespace ModelContextProtocol.Tests.Utils;
public sealed class KestrelInMemoryTransport : IConnectionListenerFactory, IConnectionListener
{
private readonly Channel<ConnectionContext> _acceptQueue = Channel.CreateUnbounded<ConnectionContext>();
private EndPoint? _endPoint;
public EndPoint EndPoint => _endPoint ?? throw new InvalidOperationException("EndPoint is not set. Call BindAsync first.");
public KestrelInMemoryConnection CreateConnection()
{
var connection = new KestrelInMemoryConnection();
_acceptQueue.Writer.TryWrite(connection);
return connection;
}
public async ValueTask<ConnectionContext?> AcceptAsync(CancellationToken cancellationToken = default)
{
if (await _acceptQueue.Reader.WaitToReadAsync(cancellationToken))
{
while (_acceptQueue.Reader.TryRead(out var item))
{
return item;
}
}
return null;
}
public ValueTask<IConnectionListener> BindAsync(EndPoint endpoint, CancellationToken cancellationToken = default)
{
_endPoint = endpoint;
return new ValueTask<IConnectionListener>(this);
}
public ValueTask DisposeAsync()
{
return UnbindAsync(default);
}
public ValueTask UnbindAsync(CancellationToken cancellationToken = default)
{
_acceptQueue.Writer.TryComplete();
return default;
}
}

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