A Stateless MCP Server in C# on .NET 11: Two Pods, No Sticky Sessions

Companion to the video Build a Stateless MCP Server in C# (.NET 11) That Actually Scales. The video walks through the whole stack on camera. This article has the code, the output from a run I did on my machine, and the trade-offs I only had time to mention in passing.

Put a second MCP server pod behind a round-robin load balancer and, with the old HTTP transport, request two fails. Pod B has never seen the session that pod A created. Most of us fixed that with sticky sessions and moved on, until Kubernetes rescheduled a pod or a deploy rolled the instances.

The MCP spec revision of July 28, 2026 removed the reason for the pin. This article builds a server on that revision with .NET 11 and the MCP C# SDK 2.4, puts two copies behind YARP with no affinity, and kills one of them halfway through. The code is on GitHub: Romain-OD/dotnet11-mcp-stack.

Why the old transport needed sticky sessions

Until this summer, an MCP client over HTTP started with an initialize handshake. The server answered with a session id in the Mcp-Session-Id header, every later request carried that id, and the server kept the session in its own memory.

One instance, no problem. With two instances behind round robin, request one lands on pod A and creates the session, then request two lands on pod B and fails because B has no record of it. Sticky sessions pin each client to one pod, which works until the platform moves the pod: Kubernetes reschedules it, Container Apps scales to zero, or a rolling deploy replaces it. The session leaves with the pod either way.

What the 2026-07-28 spec removed

The 2026-07-28 revision drops the initialize handshake and the session id entirely. Each request carries its own protocol version and the client's capabilities in its metadata, so any instance can answer it. The client now probes the server with server/discover instead of opening a session.

The C# SDK shipped v2 the same day (release notes), and stateless HTTP is its default. I used 2.4.0 here.

The protocol is stateless now, but your application still has state. If the model fills a basket over ten tool calls, that basket needs a database or a cache, the same as it would behind any other stateless HTTP API.

The four layers

The demo is one layer of a four-layer stack, and the host uses the other three:

  1. AG-UI streams the agent's progress, tool calls and approval prompts to a front end.
  2. Microsoft Agent Framework runs the reasoning loop and picks the next tool.
  3. IChatClient from Microsoft.Extensions.AI hides the model. Azure OpenAI or a local Ollama model sits behind it.
  4. The MCP server is the tool boundary, reached over plain HTTP POST and scaled out behind a load balancer.

Nothing above layer three references an OpenAI, Azure or Ollama type. That rule is the whole reason the model swap at the end of this article touches one line.

Scaffold the server

The MCP server template ships in the .NET 11 SDK, and in current .NET 10 SDKs too, so there's nothing to install:

dotnet new mcpserver -n InventoryMcpServer -t remote

-t remote gives you the HTTP transport. The default, local, talks over standard input and output for a server that runs on the user's machine. Some Microsoft Learn pages still tell you to install Microsoft.McpServer.ProjectTemplates first; with a current SDK you can skip that.

Program.cs and SessionMode

using ModelContextProtocol.AspNetCore;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddMcpServer()
    .WithHttpTransport(o => o.SessionMode = HttpServerSessionMode.Stateless)
    .WithToolsFromAssembly();

var app = builder.Build();
app.MapMcp();
app.MapGet("/health", () => "ok");

app.Run();

Stateless is already the default in v2. I set it anyway, because the next person to open this file sees the decision without having to know the default. The /health endpoint is for the load balancer's health check.

HttpServerSessionMode has two other values. Stateful keeps the old behaviour and refuses 2026-07-28 requests: when I sent one to a stateful pod, it answered with error -32022 (UnsupportedProtocolVersion). The hybrid mode keeps sessions only for older clients that still send initialize, which is the one to use while you migrate. The older Stateless = true property still compiles.

The tools

[McpServerToolType]
public sealed class InventoryTools(IConfiguration config, ILogger<InventoryTools> log)
{
    [McpServerTool, Description("Returns the quantity on hand for a SKU. Call this before AdjustInventory.")]
    public int GetStockLevel([Description("The SKU, for example A-42.")] string sku)
    {
        log.LogInformation("[{Pod}] GetStockLevel {Sku}", Pod, sku);
        return Read(sku);
    }

    [McpServerTool, Description("Adds units to (positive delta) or removes units from (negative delta) a SKU's stock and returns the new quantity. Adjustments over 100 units either way ask the user to confirm. Call GetStockLevel first.")]
    public string AdjustInventory(
        RequestContext<CallToolRequestParams> context,
        [Description("The SKU, for example A-42.")] string sku,
        [Description("Number of units: positive when stock arrives, negative when it ships.")] int delta)
    {
        // approval branch below, then a single UPDATE ... RETURNING qty
    }
}

On the wire the tools are get_stock_level and adjust_inventory. The descriptions are the only documentation the model ever reads, so I write them for the model: what the tool does, what unit the delta uses, and which tool to call first.

Stock lives in SQLite, never in a static field. A static dictionary looks fine with one instance. Start a second one and you have two stock levels for the same SKU, and nothing in the logs tells you which pod is lying. (The demo shares one SQLite file between the pods because they run on the same machine. Real pods need a real database.)

Approvals without a session

Any adjustment over 100 units needs a human. Before 2026-07-28 that was elicitation: the server sent a question down the open session and held the call in memory until the answer came back. With no session, the server has nowhere to send the question.

The spec's answer is multi round-trip requests, MRTR for short. The tool throws, the server forgets the call, and the client retries with the answer and a request state attached:

if (Math.Abs(delta) > 100)
{
    if (context.Params?.InputResponses?.TryGetValue("confirm", out var response) != true)
    {
        throw new InputRequiredException(
            inputRequests: new Dictionary<string, InputRequest>
            {
                ["confirm"] = InputRequest.ForElicitation(new ElicitRequestParams
                {
                    Message = $"Adjust {sku} by {delta} units?",
                    RequestedSchema = new()
                    {
                        Properties = { ["approve"] = new ElicitRequestParams.BooleanSchema { Description = "Approve the adjustment" } },
                        Required = ["approve"],
                    },
                }),
            },
            requestState: JsonSerializer.Serialize(new { sku, delta }));
    }

    var answer = response!.Deserialize(InputResponse.ElicitResultJsonTypeInfo);
    var approved = answer is { Action: "accept" }
        && answer.Content?.TryGetValue("approve", out var v) == true
        && v.ValueKind == JsonValueKind.True;
    if (!approved)
        return $"The user declined the adjustment of {sku} by {delta}. Stock is unchanged at {Read(sku)}.";
}

On the client you don't write the retry. You give the C# client an ElicitationHandler, it shows the question, and it resends the call by itself:

static ValueTask<ElicitResult> AskUser(ElicitRequestParams? request, CancellationToken ct)
{
    Console.Write($"{request?.Message} [y/N] ");
    var yes = Console.ReadLine()?.Trim().ToLowerInvariant() is "y" or "yes";
    return ValueTask.FromResult(new ElicitResult
    {
        Action = "accept",
        Content = new Dictionary<string, JsonElement> { ["approve"] = JsonSerializer.SerializeToElement(yes) },
    });
}

The retry carries everything the server needs, so it can land on any pod.

Two pods behind YARP

The load balancer is a dozen lines of YARP: round robin, no session affinity, and an active health check on /health every two seconds.

builder.Services.AddReverseProxy().LoadFromMemory(
    [new RouteConfig { RouteId = "mcp", ClusterId = "pods", Match = new() { Path = "{**all}" } }],
    [new ClusterConfig
    {
        ClusterId = "pods",
        LoadBalancingPolicy = "RoundRobin",
        HealthCheck = new() { Active = new() { Enabled = true, Interval = TimeSpan.FromSeconds(2), Timeout = TimeSpan.FromSeconds(1), Path = "/health" } },
        Destinations = new Dictionary<string, DestinationConfig>
        {
            ["podA"] = new() { Address = "http://localhost:5001" },
            ["podB"] = new() { Address = "http://localhost:5002" },
        },
    }]);

var app = builder.Build();
app.MapReverseProxy();
app.Run("http://localhost:5000");

Keep the health check. Without it I watched YARP keep sending half the calls to a dead pod, and every one of those failed.

To run it, start two copies of the server, then the proxy, then the host in probe mode, which calls the tools directly without a model:

# demo/InventoryMcpServer, two terminals
dotnet run --no-launch-profile -- --urls http://localhost:5001
dotnet run --no-launch-profile -- --urls http://localhost:5002

# demo/LoadBalancer
dotnet run

# demo/AgentHost
dotnet run -- --ollama probe

What the run printed

I ran this on November 25, 2026 with the .NET 11.0.100 SDK on a fresh stock.db, where A-42 starts at 400. The probe reads the stock, then tries to ship 150 units.

First run, approved:

Tools: get_stock_level, adjust_inventory
400
Adjust A-42 by -150 units? [y/N] y
A-42 adjusted by -150. New quantity: 250.

Second run, declined:

250
Adjust A-42 by -150 units? [y/N] n
The user declined the adjustment of A-42 by -150. Stock is unchanged at 250.

The pod logs show where each call landed:

[http://localhost:5002] GetStockLevel A-42
[http://localhost:5001] AdjustInventory A-42 -150: asking for confirmation
[http://localhost:5002] AdjustInventory A-42 -150: applied
[http://localhost:5001] GetStockLevel A-42
[http://localhost:5002] AdjustInventory A-42 -150: asking for confirmation
[http://localhost:5001] AdjustInventory A-42 -150: declined

In the first run, pod A asked the question and pod B applied the answer. The second run went the other way round. Neither pod knew about the other's half of the conversation, and neither needed to.

Then I killed pod A. YARP logged Active health state of destination 'podA' on cluster 'pods' is set to 'Unhealthy', and the next approved run went entirely through pod B:

[http://localhost:5002] GetStockLevel A-42
[http://localhost:5002] AdjustInventory A-42 -150: asking for confirmation
[http://localhost:5002] AdjustInventory A-42 -150: applied

Stock went from 250 to 100. The demo has no session cache to replicate between pods, and the client never noticed the failure.

The host and the agent

The host connects to the load balancer, never to a pod:

await using var mcp = await McpClient.CreateAsync(
    new HttpClientTransport(new() { Endpoint = new Uri("http://localhost:5000") }),
    new McpClientOptions { Handlers = new() { ElicitationHandler = AskUser } });

var tools = (await mcp.ListToolsAsync())
    .Where(t => t.Name is "get_stock_level" or "adjust_inventory")
    .ToList();

Each tool that ListToolsAsync returns is already an AIFunction, the tool type Microsoft.Extensions.AI uses, so there's no adapter to write. I filter to two tools on purpose. Every tool schema costs tokens on every turn, and a four-billion-parameter model handed forty tools starts picking the wrong one or making up arguments.

The agent is one call on the IChatClient from dependency injection:

var agent = host.Services.GetRequiredService<IChatClient>().AsAIAgent(
    instructions: "You manage warehouse stock. Check the stock level before you adjust it.",
    tools: [.. tools]);

await foreach (var update in agent.RunStreamingAsync("Ship 150 units of SKU A-42."))
    Console.Write(update);

The method is AsAIAgent. Older samples use CreateAIAgent, which doesn't exist in Agent Framework 1.28. To stream to a browser, the AG-UI hosting package adds AddAGUIServer() and MapAGUIServer("/", agent). That package (Microsoft.Agents.AI.Hosting.AGUI.AspNetCore) is still in preview, so pin its version.

The one-line swap to Ollama

This is the line that picks the model:

builder.Services.AddChatClient(new AzureOpenAIClient(new Uri(endpoint), new DefaultAzureCredential())
    .GetChatClient(deployment).AsIChatClient());

And this one replaces it:

builder.Services.AddChatClient(new OllamaApiClient(new Uri("http://localhost:11434"), "qwen3:4b"));

OllamaApiClient comes from the OllamaSharp package. Install Ollama, run ollama pull qwen3:4b, and the same prompt goes through the same two tools and the same approval without leaving your machine. Expect a small model to be slower and less reliable at picking tools, which is one more reason the host gives it only two.

A few things I tripped on while checking this:

  • Microsoft.Extensions.AI.Ollama is deprecated. Microsoft points to OllamaSharp instead.
  • AddOllamaChatClient() doesn't exist. In Aspire it's AddOllamaApiClient("ollama").AddChatClient() from CommunityToolkit.Aspire.OllamaSharp.
  • Don't add .UseFunctionInvocation() yourself. The agent already wraps the client in a function-invoking one.

I compiled the agent path against both providers but couldn't run a model from my corporate network, so the run above uses probe mode. The MCP side, which is what this article is about, ran for real.

.NET 11 or .NET 10?

.NET 11 is a standard-term release and .NET 10 is long-term, but both reach end of support on November 14, 2028 (support policy). Choosing 11 costs you no support time.

If your company ships only LTS releases, all of this works on .NET 10 today. The MCP SDK packages target .NET 8, 9 and 10, Microsoft.Extensions.AI runs there as well, and the current .NET 10 SDK includes the same dotnet new mcpserver template. .NET 8 went out of support on November 10, 2026, so if you're still on it, that upgrade comes first.

What stateless costs you

The request state now travels through the client. Between the two calls the client holds { sku, delta } and sends it back, and the server trusts whatever comes back. A client that edits the delta after the user approved gets a number applied that nobody approved. Sign the request state, or put only an id in it and look the rest up on the server. The demo does neither, and says so in a comment.

SDK v2 also has breaking changes. The legacy SSE endpoints are off by default, and sampling and roots are marked obsolete. Older clients that rely on them need the hybrid session mode for a while, so look at what your clients actually send before you switch every server to stateless.

When to skip MCP

If one agent in one process uses a tool and nothing else will ever call it, you don't need a server. Wrap the method with AIFunctionFactory.Create and pass it to the agent, and you save a network hop and a deployment. MCP starts paying off when tools are shared between several agents, other teams, or clients you don't control, like VS Code or GitHub Copilot.

Key takeaways

  • The 2026-07-28 spec removed Mcp-Session-Id and initialize. Each request carries its protocol version and capabilities, so any instance can answer.
  • In MCP C# SDK v2, HttpServerSessionMode.Stateless is the default. Stateful refuses new-protocol requests; use the hybrid mode for old clients during a migration.
  • MRTR replaces server-held elicitation: throw InputRequiredException with a request state, and the client retries with the answer on any pod.
  • Treat the request state as untrusted input. Sign it or store it server side.
  • Keep application state out of the process, and keep an active health check on the load balancer.
  • Depend on IChatClient, and the cloud-to-local model swap is one line.

References