Snippet

Reject tool calls the host never offered

A complete DelegatingHandler that checks model tool calls and argument shapes before the agent framework or its telemetry sees them.

csharpNov 6, 2026MIT

AI-generated, human-reviewed: the first draft was generated by an AI agent; I fact-checked, tested, and edited it. AI use policy

What it does#

Inspects every model response on the HTTP pipeline before the agent framework reads it. A function_call for a tool name you did not offer, or with arguments that are not exactly the expected string properties, turns the response into a 502 with a fixed error body. So does a response that calls prepare_transfer more than once, because one turn may prepare only one proposal. Upstream error bodies are replaced the same way, so provider text never lands on spans or logs.

It does not pick tools or classify intent. The model still decides what to call; this only refuses calls that should not exist. It sees one model response at a time, so the prepare tool must still refuse a second proposal in the same turn when the model calls it again in a later response.

You need#

  • .NET 10
  • An agent whose HttpClient calls a model through the Responses API (non-streaming), for example the Microsoft Agent Framework with the OpenAI client
  • Your own tool names and their argument names in AllowedTools

Where it goes#

Register it on the named HttpClient that talks to the model, before any handler that logs or inspects responses:

csharp
builder.Services.AddTransient<ToolCallAllowlistHandler>();
builder.Services.AddHttpClient("model").AddHttpMessageHandler<ToolCallAllowlistHandler>();
ToolCallAllowlistHandler.cs
// SPDX-License-Identifier: MIT
// Copyright (c) 2026 Sarang Datye
using System.Net;
using System.Text;
using System.Text.Json;

/// <summary>
/// Sits on the HttpClient that calls the model through the Responses API. It rejects tool calls
/// the host never offered, and argument shapes it does not expect, before the agent framework
/// or its instrumentation sees them. It does not choose tools; the model still does.
/// Upstream error bodies are replaced with a fixed message so they never reach spans or logs.
/// </summary>
public sealed class ToolCallAllowlistHandler : DelegatingHandler
{
    // Tool name to the exact string arguments it may carry. Replace with your own tools.
    private static readonly Dictionary<string, string[]> AllowedTools = new(StringComparer.Ordinal)
    {
        ["get_current_utc_time"] = [],
        ["get_transfer_requirements"] = [],
        ["search_recipients"] = ["query"],
        ["prepare_transfer"] = ["recipientId", "amount", "currency"],
        ["get_transfer_status"] = [],
    };

    // Tools that may appear at most once in one model response.
    private static readonly HashSet<string> OncePerResponse = new(StringComparer.Ordinal) { "prepare_transfer" };

    private const int MaximumArgumentLength = 100;

    protected override async Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request, CancellationToken cancellationToken)
    {
        var response = await base.SendAsync(request, cancellationToken);
        await ValidateAsync(response, cancellationToken);
        return response;
    }

    public static async Task ValidateAsync(HttpResponseMessage response, CancellationToken cancellationToken)
    {
        try
        {
            if (!response.IsSuccessStatusCode)
            {
                ReplaceError(response);
                return;
            }

            var bytes = await response.Content.ReadAsByteArrayAsync(cancellationToken);
            using var document = JsonDocument.Parse(bytes);
            if (document.RootElement.TryGetProperty("error", out var error) && error.ValueKind != JsonValueKind.Null)
                throw new JsonException();
            if (!document.RootElement.TryGetProperty("output", out var output) || output.ValueKind != JsonValueKind.Array)
                throw new JsonException();

            var calledOnce = new HashSet<string>(StringComparer.Ordinal);
            foreach (var item in output.EnumerateArray())
            {
                if (item.GetProperty("type").GetString() != "function_call") continue;
                var name = item.GetProperty("name").GetString() ?? "";
                if (!AllowedTools.TryGetValue(name, out var expected)) throw new JsonException();
                if (OncePerResponse.Contains(name) && !calledOnce.Add(name)) throw new JsonException();

                using var args = JsonDocument.Parse(item.GetProperty("arguments").GetString() ?? "");
                var properties = args.RootElement.EnumerateObject().ToArray();
                // Exactly the expected names, each once: a duplicate could hide a missing argument.
                if (properties.Length != expected.Length ||
                    properties.Select(p => p.Name).Distinct(StringComparer.Ordinal).Count() != expected.Length ||
                    properties.Any(p => !expected.Contains(p.Name)))
                    throw new JsonException();
                foreach (var property in properties)
                {
                    if (property.Value.ValueKind != JsonValueKind.String ||
                        property.Value.GetString()!.Length > MaximumArgumentLength)
                        throw new JsonException();
                }
            }
        }
        catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
        {
            throw;
        }
        catch (Exception)
        {
            response.StatusCode = HttpStatusCode.BadGateway;
            ReplaceError(response);
        }
    }

    private static void ReplaceError(HttpResponseMessage response)
    {
        response.Content.Dispose();
        response.Content = new StringContent(
            """{"error":{"message":"Model response unavailable.","type":"model_error","code":"model_error"}}""",
            Encoding.UTF8, "application/json");
    }
}

Check that it works#

Put a stub HttpMessageHandler under it that returns a Responses API body with "type": "function_call", "name": "execute_transfer". The response you get back is a 502 with Model response unavailable.; the same body with search_recipients and {"query":"John"} passes through unchanged.