How to Test MCP Servers in ASP.NET Core 10 Using C# – Unit Tests, Integration Tests and Security (2026)

A green unit test for a tool method says little about whether an MCP client can discover it, bind arguments, receive an error, or cancel the request. Those failures belong to different boundaries. A test suite becomes easier to debug when it tells you which boundary failed.

This tutorial builds a small ASP.NET Core 10 server and an xUnit suite with both pure C# tests and real Streamable HTTP integration tests. The example uses MCP C# SDK 2.3.1, the July 2026 protocol, and a read-only slug tool.

Which parts of an MCP server need tests?

The test suite separates the pure slug policy, the MCP tool contract, and the HTTP security boundary.
The test suite separates the pure slug policy, the MCP tool contract, and the HTTP security boundary.
Layer Use Example assertion
Unit Exercise deterministic application logic Repeated spaces normalize to one hyphen
Protocol integration Use the real SDK and transport A registered tool appears and returns the expected content
HTTP security Send a raw request to the host Missing credentials and untrusted Origin are rejected
Deployment smoke test Exercise actual ingress HTTPS, buffering and disconnect behavior match expectations

The suite uses no mock for the slug policy because it has no I/O. If the tool calls a database or a model, put the dependency behind an interface and use a small fake in unit tests. Test the real adapter separately against a disposable dependency. Mocking the MCP client in a protocol test would bypass precisely the serialization and transport behavior you want to cover.

Set up the projects

Install the .NET 10 SDK and create the layout below. The app project explicitly excludes the test source under tests. The test project references the server so it can exercise the public slug policy. Run the tests against a dedicated loopback instance, never a production endpoint.

Project layout
McpTestLab/
  Lab.csproj
  Program.cs
  tests/
    Lab.Tests.csproj
    ServerTests.cs
Lab.csproj
<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup><TargetFramework>net10.0</TargetFramework><ImplicitUsings>enable</ImplicitUsings><Nullable>enable</Nullable></PropertyGroup>
  <ItemGroup><PackageReference Include="ModelContextProtocol.AspNetCore" Version="2.3.1" /></ItemGroup>
  <ItemGroup><Compile Remove="tests/**/*.cs" /></ItemGroup>
</Project>
tests/Lab.Tests.csproj
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup><TargetFramework>net10.0</TargetFramework><ImplicitUsings>enable</ImplicitUsings><Nullable>enable</Nullable><IsTestProject>true</IsTestProject></PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
    <PackageReference Include="xunit" Version="2.9.3" />
    <PackageReference Include="xunit.runner.visualstudio" Version="3.1.1" />
    <ProjectReference Include="../Lab.csproj" />
  </ItemGroup>
</Project>

The server uses the official ASP.NET Core MCP package. The test project gets the MCP Core types transitively from the server reference. Pinning versions makes it easier to reproduce protocol behavior. When upgrading the SDK, rerun transport tests alongside your package upgrade. The ASP.NET Core integration-testing documentation describes in-process hosting as another option. This lab uses a real loopback listener because stream closure matters to the cancellation test.

Implement the MCP tool and test boundary

Create Program.cs. The demo uses one random lab key, rejects browser-origin requests and binds to loopback. These checks deliberately create repeatable denial cases. For a remote deployment, use real caller authentication, scoped authorization, HTTPS, and request limits. The small delay creates an interval during which the integration test can cancel the call.

Program.cs
using System.ComponentModel;
using System.Security.Cryptography;
using System.Text;
using ModelContextProtocol;
using ModelContextProtocol.Server;

var builder = WebApplication.CreateBuilder(args);
var key = builder.Configuration["LabKey"];
if (key is null || key.Length < 32) throw new InvalidOperationException("Set LabKey.");
var expected = SHA256.HashData(Encoding.UTF8.GetBytes("Bearer " + key));
builder.Services.AddMcpServer().WithHttpTransport().WithTools<SlugTools>();
var app = builder.Build();
app.Use(async (ctx, next) =>
{
    if (ctx.Request.Headers.ContainsKey("Origin") || ctx.Request.Host.Host != "127.0.0.1")
    {
        ctx.Response.StatusCode = 403;
        return;
    }
    var auth = ctx.Request.Headers.Authorization;
    if (auth.Count != 1 || auth.ToString().Length > 256 ||
        !CryptographicOperations.FixedTimeEquals(expected,
            SHA256.HashData(Encoding.UTF8.GetBytes(auth.ToString()))))
    {
        ctx.Response.StatusCode = 401;
        return;
    }
    await next(ctx);
});
app.MapMcp("/mcp");
await app.RunAsync();

public static class Slugs
{
    public static string Make(string title)
    {
        if (string.IsNullOrWhiteSpace(title) || title.Length > 80 ||
            title.Any(c => !char.IsAsciiLetterOrDigit(c) && c != ' '))
            throw new McpException("Use 1–80 ASCII letters, digits and spaces.");
        return string.Join("-", title.ToLowerInvariant().Split(' ',
            StringSplitOptions.RemoveEmptyEntries));
    }
}

[McpServerToolType]
public sealed class SlugTools
{
    [McpServerTool(Name = "make_slug", ReadOnly = true)]
    [Description("Create a simple URL slug from a title.")]
    public static async Task<string> Run(string title, CancellationToken cancellationToken)
    {
        await Task.Delay(TimeSpan.FromMilliseconds(300), cancellationToken);
        return Slugs.Make(title);
    }
}

A slug is application data. The implementation deliberately restricts input to ASCII letters, digits and spaces. If a product needs Unicode slugs, define normalization, collision, and transliteration rules before changing the tests. Treat the slug as a display identifier unless you separately validate how it will be used in a filesystem or route.

Add unit and integration tests

Create tests/ServerTests.cs. The protocol test asserts the tool name and content type, then verifies invalid input produces an MCP tool error. The raw HTTP tests send a request without credentials and a request with an untrusted Origin. A 401 or 403 is different from an MCP tool error.

tests/ServerTests.cs
using System.Net;
using ModelContextProtocol;
using ModelContextProtocol.Client;
using ModelContextProtocol.Protocol;
using Xunit;

public sealed class ServerTests
{
    private static readonly Uri Endpoint = new("http://127.0.0.1:5080/mcp");

    [Theory]
    [InlineData("Hello World", "hello-world")]
    [InlineData(" A  B ", "a-b")]
    public void SlugPolicyIsDeterministic(string input, string expected) =>
        Assert.Equal(expected, Slugs.Make(input));

    [Fact]
    public void RejectsPathInput() =>
        Assert.Throws<McpException>(() => Slugs.Make("../secret"));

    [Fact]
    public async Task MissingCredentialIsRejectedBeforeMcp()
    {
        using var http = new HttpClient();
        using var response = await http.GetAsync(Endpoint);
        Assert.Equal(HttpStatusCode.Unauthorized, response.StatusCode);
    }

    [Fact]
    public async Task OriginIsRejected()
    {
        using var http = new HttpClient();
        using var request = new HttpRequestMessage(HttpMethod.Get, Endpoint);
        request.Headers.TryAddWithoutValidation("Origin", "https://untrusted.example");
        using var response = await http.SendAsync(request);
        Assert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
    }

    [Fact]
    public async Task ToolContractAndFailureAreObservable()
    {
        using var http = new HttpClient();
        using var budget = new CancellationTokenSource(TimeSpan.FromSeconds(10));
        await using var client = await Connect(http, budget.Token);
        var tools = await client.ListToolsAsync(cancellationToken: budget.Token);
        Assert.Contains(tools, tool => tool.Name == "make_slug");
        var ok = await client.CallToolAsync("make_slug", Args("Hello World"),
            cancellationToken: budget.Token);
        Assert.NotEqual(true, ok.IsError);
        Assert.Equal("hello-world", Assert.Single(ok.Content.OfType<TextContentBlock>()).Text);
        var bad = await client.CallToolAsync("make_slug", Args("../secret"),
            cancellationToken: budget.Token);
        Assert.True(bad.IsError == true);
    }

    [Fact]
    public async Task CallerCanAbandonInFlightRequest()
    {
        using var http = new HttpClient();
        using var connectBudget = new CancellationTokenSource(TimeSpan.FromSeconds(10));
        await using var client = await Connect(http, connectBudget.Token);
        using var stop = new CancellationTokenSource(TimeSpan.FromMilliseconds(80));
        await Assert.ThrowsAnyAsync<OperationCanceledException>(async () =>
        {
            await client.CallToolAsync("make_slug", Args("Example"),
                cancellationToken: stop.Token);
        });
    }

    private static Dictionary<string, object?> Args(string title) => new() { ["title"] = title };

    private static Task<McpClient> Connect(HttpClient http, CancellationToken ct)
    {
        var key = Environment.GetEnvironmentVariable("LabKey")
            ?? throw new InvalidOperationException("Set LabKey for the test process.");
        return McpClient.CreateAsync(new HttpClientTransport(new HttpClientTransportOptions
        {
            Endpoint = Endpoint, TransportMode = HttpTransportMode.StreamableHttp,
            AdditionalHeaders = new Dictionary<string, string> { ["Authorization"] = "Bearer " + key }
        }, http), new McpClientOptions { ProtocolVersion = "2026-07-28" },
            cancellationToken: ct);
    }
}

The cancellation test asserts the caller observes cancellation. It does not assert the server completed cleanup. For that stronger claim, instrument a completion signal inside a fake dependency or check a structured server log and prove that concurrency slots or temporary files are released. The lab uses a timer to create an observable cancellation window. Avoid treating the exact elapsed time as part of the contract.

Run the suite

Open two shells. Set the same random lab key in both without committing it or printing it. Make sure no other process is listening on port 5080.

Start a dedicated loopback host
export LabKey="$(openssl rand -hex 32)"
dotnet run --project Lab.csproj --no-launch-profile -- --urls http://127.0.0.1:5080
Run unit and protocol checks
dotnet test tests/Lab.Tests.csproj

Expected results include the slug hello-world, a tool error for the traversal-like input, and the two expected HTTP denial statuses. The server does not interpret ../secret as a path. The test asserts it rejects those characters.

All seven xUnit cases passed against a local .NET 10 loopback instance. The suite did not exercise a reverse proxy, legacy transports, or server-side cancellation cleanup.

Expand coverage with meaningful failure cases

A tool’s contract includes required fields, accepted types, limits, and the shape of its output. Add representative tests for malformed arguments, schema changes, and forbidden operations. Pin the protocol revision and include a separate compatibility run for any older client version you actually support. Use a unique resource identifier for each test so parallel tests cannot observe each other’s changes.

For tests with real writes, create a disposable database and assert state after an exception, timeout, and retry. A response can disappear after a commit. Use an idempotency key and inspect the durable result to check whether duplicate effects were prevented. Add a cross-tenant denial test wherever a tool accesses user-owned data. Deny both direct identifier substitution and a mismatched token audience.

In a CI pipeline, allocate a unique local port or run one listener per isolated job. Wait for readiness with a bounded polling loop. Stop the host in cleanup even when a test fails. Treat logs as diagnostic artifacts and remove credentials, raw prompts, and private fixtures before publishing them.

Troubleshooting

Symptom First check
Connection refused Dedicated host and port
All protocol calls return unauthorized Same key in both process environments
Tool list is empty Tool attributes and registration
Test passes despite a tool error Assert IsError as well as content
Cancellation test flakes in CI Use a controlled signal to ensure work started before canceling

Frequently asked questions

Should I mock the MCP transport?

A mock can exercise an application component’s behavior, but keep at least one test that uses the real MCP protocol. Tool registration and argument binding can fail while direct method tests pass.

Does one test cover authorization?

One test covers one rule. Include missing, invalid, expired, and wrong-audience credentials for an authenticated deployment. Verify tenant authorization independently after authentication.

Can an HTTP 200 represent a failed tool call?

Yes. Check the MCP result for a tool error. Protocol success and business success describe different layers.

Conclusion and references

Start with deterministic policy tests, then exercise a real SDK call and the denial paths at the HTTP boundary. These checks complement the ASP.NET PB MCP server guide.

Comments