Add middleware and authz support for server-side handlers (#733)

This commit is contained in:
Stephen Halter 2025-09-10 10:07:45 -07:00 • committed by GitHub
commit d344c65120
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -111,6 +111,35 @@ public abstract class MapMcpTests(ITestOutputHelper testOutputHelper) : KestrelI
Assert.Equal(HttpStatusCode.Forbidden, httpRequestException.StatusCode);
}
[Fact]
public async Task ClaimsPrincipal_CanBeInjectedIntoToolMethod()
{
Builder.Services.AddMcpServer().WithHttpTransport(ConfigureStateless).WithTools<ClaimsPrincipalTools>();
Builder.Services.AddHttpContextAccessor();
await using var app = Builder.Build();
app.Use(next => async context =>
{
context.User = CreateUser("TestUser");
await next(context);
});
app.MapMcp();
await app.StartAsync(TestContext.Current.CancellationToken);
await using var client = await ConnectAsync();
var response = await client.CallToolAsync(
"echo_claims_principal",
new Dictionary<string, object?>() { ["message"] = "Hello world!" },
cancellationToken: TestContext.Current.CancellationToken);
var content = Assert.Single(response.Content.OfType<TextContentBlock>());
Assert.Equal("TestUser: Hello world!", content.Text);
}
[Fact]
public async Task Sampling_DoesNotCloseStream_Prematurely()
{
@ -200,6 +229,17 @@ public abstract class MapMcpTests(ITestOutputHelper testOutputHelper) : KestrelI
}
}
[McpServerToolType]
protected class ClaimsPrincipalTools
{
[McpServerTool, Description("Echoes the input back to the client with the user name from ClaimsPrincipal.")]
public string EchoClaimsPrincipal(ClaimsPrincipal? user, string message)
{
var userName = user?.Identity?.Name ?? "anonymous";
return $"{userName}: {message}";
}
}
[McpServerToolType]
private class SamplingRegressionTools
{