Recursive AI

Limit HTTP client response size in C#

OneModelContext is a free, open-source .NET SDK for the Model Context Protocol® from Recursive AI. MIT or Apache-2.0, no native dependencies.

Set separate byte caps for JSON replies and streamed events in your protocol client.

Terminal
dotnet add package RecursiveAI.OneModelContext

Requires .NET 10 (net10.0); .NET 9 and earlier aren’t supported.

C#
using RecursiveAI.OneModelContext;
 
var limits = new HttpTransportOptions
{
    MaxResponseBodyBytes = 1024,
    MaxEventBytes = 4096
};
// Pass the protocol URL as args[0].
var endpoint = new Uri(args[0]);
var transport = ContextTransport.Http(
    endpoint, options: limits);
await using var client = await
    ModelContext.ConnectAsync(transport);
try
{
    await client.ListToolsAsync();
}
catch (TransportException error)
{
    Console.WriteLine(error.Message);
}

With an oversized JSON reply to ListToolsAsync, this prints The server's response is larger than 1024 bytes. To get a URL for args[0], unzip the example and run dotnet run -- serve. Pass the printed URL to the snippet while the example’s built-in test server is still running.

Unzip the example, then dotnet run.

The full program

The example’s built-in test server answers initialization normally. For the first tool list it includes a description of 2,048 ASCII a characters, so the serialized JSON exceeds 1,024 bytes. The second tool list is empty. The test server uses the Microsoft.AspNetCore.App framework reference in the project file; the client itself does not need it. EraPreference.Legacy uses the legacy handshake the test server implements, and OpenListeningStream = false skips the separate legacy GET stream so the example only needs POST replies.

C#
using System.Text.Json;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Hosting;
using RecursiveAI.OneModelContext;
 
var builder = WebApplication.CreateBuilder();
builder.Logging.ClearProviders();
await using var fixture = builder.Build();
fixture.Urls.Add("http://" + System.Net.IPAddress.Loopback + ":0");
int listCalls = 0;
fixture.MapPost("/protocol", async (HttpContext http) =>
{
    using var request = await JsonDocument.ParseAsync(http.Request.Body);
    var body = request.RootElement;
    var method = body.GetProperty("method").GetString();
    if (!body.TryGetProperty("id", out var id))
        return Results.Accepted();
 
    object result = method == "initialize"
        ? new { protocolVersion = "2025-11-25", capabilities = new { tools = new { } }, serverInfo = new { name = "Local", version = "1.0" } }
        : new { tools = method == "tools/list" && Interlocked.Increment(ref listCalls) == 1
            ? new[] { new { name = "sample", description = new string('a', 2048), inputSchema = new { type = "object" } } }
            : [] };
    return Results.Json(new { jsonrpc = "2.0", id = id.Clone(), result });
});
await fixture.StartAsync();
var endpoint = new Uri(new Uri(fixture.Urls.Single()), "/protocol");
if (args is ["serve"])
{
    Console.WriteLine(endpoint);
    await fixture.WaitForShutdownAsync();
    return;
}
 
var options = new HttpTransportOptions
{
    MaxResponseBodyBytes = 1024,
    MaxEventBytes = 4096,
    OpenListeningStream = false
};
var transport = ContextTransport.Http(endpoint, options: options);
await using var client = await ModelContext.ConnectAsync(transport, era: EraPreference.Legacy);
try
{
    await client.ListToolsAsync();
    throw new InvalidOperationException("Expected the large response to be rejected.");
}
catch (TransportException error)
{
    Console.WriteLine(error.Message);
}
await client.ListToolsAsync();
Console.WriteLine("Next response accepted.");
Text
The server's response is larger than 1024 bytes.
Next response accepted.

After the connection is established, the large JSON reply fails that call with a TransportException; you don’t have to reconnect before making a new call.

Variations

To let a streamed event carry up to 8 KiB while still rejecting the sample’s oversized JSON response, change the options to:

C#
MaxResponseBodyBytes = 1024,
MaxEventBytes = 8192,

The short answer

Set HttpTransportOptions.MaxResponseBodyBytes for JSON responses and MaxEventBytes for streamed events, then pass the options to ContextTransport.Http. These are client-side checks on what the client reads. They don’t change how much data the server is allowed to send or how much data it accepts from your requests.

Is there a limit to the size of an HTTP response body?

The .NET HttpClient buffering option limits the bytes HttpClient buffers for the response content. OneModelContext reads the response stream itself, so set its transport limits rather than relying on the buffering option. The client transport docs list defaults of 16 MiB for a JSON body and 8 MiB per event. The client checks a known JSON content length before reading and also enforces the cap as it reads, so the check doesn’t depend on a length header.

Choose a JSON cap large enough for the encoded reply you expect. It includes JSON syntax, field names and protocol metadata, not just the characters in a tool description. The 1,024-byte cap in the example is small enough to show a refusal; a production cap must also allow the server’s initialization or discovery reply. If the limit is exceeded during negotiation, the connection itself can fail rather than just one request.

Is the response limit the same as the HTTP request limit?

No. A request limit applies to bytes sent to a server, such as tool arguments. A response limit applies to bytes read from it, such as the returned tool list. The example doesn’t produce an HTTP 413: the server sends a successful HTTP response, then the client refuses to read the oversized JSON reply as a valid result.

A stream is different from a JSON body. MaxEventBytes limits each event, not the total bytes received over the stream’s lifetime. An oversized event ends that stream. MaxQueuedMessages separately limits how many messages can wait for the client to read them, and StreamIdleTimeout detects a stream that stops sending events or keep-alive comments. Raising one allowance doesn’t raise the others.

All onemodelcontext recipes