---
title: "Configure a custom HTTP handler for a tool client in C#"
url: https://recursiveai.org/onemodelcontext/cookbook/connect-tool-client-with-custom-http-handler/
description: "Pass a custom HttpClientHandler to a OneModelContext tool client in C#. Set redirect and cookie behavior and try it against a local tool server."
version: "1.0.2"
---

# Configure a custom HTTP handler for a tool client 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.

[NuGet](https://www.nuget.org/packages/RecursiveAI.OneModelContext) · [GitHub](https://github.com/recursive-ai-oss/onemodelcontext-csharp) · [Docs](https://recursiveai.org/onemodelcontext/docs/) · [Download example (.zip)](https://recursiveai.org/onemodelcontext/cookbook/connect-tool-client-with-custom-http-handler/connect-tool-client-with-custom-http-handler.zip)

Supply your own `HttpClient` to control how a Model Context Protocol® client sends requests. The [Model Context Protocol®](https://modelcontextprotocol.io/docs/getting-started/intro) is an open protocol that AI apps use to call tools on a server.

```shell
dotnet add package RecursiveAI.OneModelContext
```

Requires [.NET 10](https://dotnet.microsoft.com/download/dotnet/10.0) (net10.0); .NET 9 and earlier aren’t supported.

Pass the tool server’s URL as the first argument.

```csharp
using RecursiveAI.OneModelContext;

var url = new Uri(args[0]);
using var http = new HttpClient(
    new HttpClientHandler
    {
        AllowAutoRedirect = false,
        UseCookies = false
    });
var transport = ContextTransport.Http(url, http);
await using var client =
    await ModelContext.ConnectAsync(transport);
Console.WriteLine(client.ServerInfo.Name);
```

[The example](https://recursiveai.org/onemodelcontext/cookbook/connect-tool-client-with-custom-http-handler/connect-tool-client-with-custom-http-handler.zip) is the full program below: unzip it and `dotnet run`. To run only the code above, paste it into Program.cs of a new `dotnet new console` project and `dotnet run`.

The snippet takes the tool server’s URL: run it with `dotnet run -- <url>`. For a local URL, run `dotnet run -- serve` in the unzipped project and copy the printed URL from that terminal. The snippet prints the server’s name:

```text
Local tools
```

## The full program

With no arguments, the example starts a local server, connects through the custom handler, and shuts down the server when it’s done. It needs no external service or input file.

```csharp
using RecursiveAI.OneModelContext;

using var stop = new CancellationTokenSource();
var ready = new TaskCompletionSource<Uri>(TaskCreationOptions.RunContinuationsAsynchronously);
var server = new ContextServer("Local tools", "1.0");
var serving = ModelContext.ServeHttpAsync(server, port: 0, path: "/tools",
    onListening: url => ready.SetResult(url), cancellationToken: stop.Token);
try
{
    var finished = await Task.WhenAny(ready.Task, serving);
    if (finished == serving)
    {
        await serving;
        throw new InvalidOperationException("The server did not start.");
    }
    var endpoint = await ready.Task;
    if (args is ["serve"])
    {
        Console.WriteLine(endpoint);
        await serving;
        return;
    }

    using var http = new HttpClient(new HttpClientHandler
    {
        AllowAutoRedirect = false,
        UseCookies = false
    });
    var transport = ContextTransport.Http(endpoint, http);
    await using var client = await ModelContext.ConnectAsync(transport);
    Console.WriteLine(client.ServerInfo.Name);
}
finally
{
    stop.Cancel();
    await serving;
}
```

```text
Local tools
```

If a server responds with a redirect, OneModelContext reports a `TransportException` with the status rather than connecting to the redirect destination.

## Variations

**Disable proxy use.** If your local server must be reached directly, add this to the handler initializer:

```csharp
UseProxy = false
```

## Related recipes

- [Connect to a tool server in C#](https://recursiveai.org/onemodelcontext/cookbook/connect-to-a-server/)
- [Set a tool client request timeout](https://recursiveai.org/onemodelcontext/cookbook/set-tool-client-request-timeout/)
- [Serve over HTTP without ASP.NET Core](https://recursiveai.org/onemodelcontext/cookbook/serve-over-http-without-aspnet/)

---

## The short answer

Create an `HttpClient` with the handler you want, pass it as the second argument to `ContextTransport.Http`, and connect using that transport. Keep the HTTP client alive until you dispose the tool client. The transport does not dispose an HTTP client supplied by the caller, so if your application already owns it, the application retains that responsibility.

## How do I disable automatic redirects in HttpClient?

Set [`AllowAutoRedirect`](https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpclienthandler.allowautoredirect?view=net-10.0) to `false` on the handler before its first request. OneModelContext disables automatic redirects when it creates the HTTP client itself; a caller-supplied client needs the same setting on its own handler. The [transport documentation](https://recursiveai.org/onemodelcontext/docs/http-client/#credentials-and-redirects) recommends this so “a credential cannot be forwarded to another place.” Use the server’s actual protocol endpoint rather than a URL that redirects to it. Handling a redirect is also different from handling a `401` or `403`: the transport surfaces those as authorization errors with the challenge for the caller or OAuth client to act on.

## Should I set this on the HTTP handler or the tool client?

Use the [.NET HTTP handler](https://learn.microsoft.com/en-us/dotnet/api/system.net.http.httpclienthandler?view=net-10.0) for how requests travel: proxies, redirects, and automatic cookie handling. `UseCookies = false` turns off the handler’s automatic cookie storage and sending; it doesn’t configure protocol authentication. In contrast, `HttpTransportOptions` is where OneModelContext takes protocol transport settings such as the maximum JSON response size and how long an event stream may be idle. You can supply both the custom `HttpClient` and the options to the same `ContextTransport.Http` call. If you only need a protocol response limit, you can leave out the custom HTTP client and keep the built-in handler.
