---
title: "Validate LLM tool arguments in C#"
url: https://recursiveai.org/onellm/cookbook/validate-llm-tool-arguments-offline/
description: "Validate model-generated tool arguments in C#. Use a generated OneLLM tool and a scripted provider to test missing keys, wrong types, and invalid JSON offline."
version: "1.0.1"
---

# Validate LLM tool arguments in C#

**OneLLM** is a free, open-source LLM and agent library for .NET from Recursive AI. MIT or Apache-2.0, no native dependencies.

[NuGet](https://www.nuget.org/packages/RecursiveAI.OneLlm) · [GitHub](https://github.com/recursive-ai-oss/onellm-csharp) · [Docs](https://recursiveai.org/onellm/docs/) · [Download example (.zip)](https://recursiveai.org/onellm/cookbook/validate-llm-tool-arguments-offline/validate-llm-tool-arguments-offline.zip)

Catch bad tool arguments before the C# method runs. No API key needed.

```shell
dotnet add package RecursiveAI.OneLlm
```

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

```csharp
using OneLlm.Messages;
using OneLlm.Tools;

// [Tool] generates GetTools().
var result = await ToolInvoker.InvokeAsync(
    LookupTools.GetTools().Single(),
    new() { ["orderId"] = "seven" },
    // Instance ID, tool call ID, and clock.
    new("demo", "1", TimeProvider.System),
    CancellationToken.None);
Console.WriteLine(result.IsError);
Console.WriteLine(
    ((TextPart)result.Parts.Single()).Text);

public sealed partial class LookupTools
{
    [Tool]
    public static string Lookup(int orderId)
        => $"Order {orderId}";
}
```

Unzip [the example](https://recursiveai.org/onellm/cookbook/validate-llm-tool-arguments-offline/validate-llm-tool-arguments-offline.zip), then `dotnet run`.

```text
True
Argument 'orderId' must be an integer from -2147483648 to 2147483647.
```

## The full program

The download exercises the same generated argument binding through the tool loop. The local `ScriptedProvider` supplies each raw argument string shown in `Check`, and the program reads the tool result from the next request to that provider. It also checks that the invalid calls never enter `Lookup`.

```csharp
using OneLlm;
using OneLlm.Definitions;
using OneLlm.Messages;
using OneLlm.Testing;
using OneLlm.Tools;

var runtime = new Runtime();
var provider = new ScriptedProvider("openai");
runtime.Providers.Set("openai", provider);
runtime.Tools.Add<LookupTools>();

await Check("broken JSON", "{", true, 0);
await Check("wrong type", """{"orderId":"seven"}""", true, 0);
await Check("missing", "{}", true, 0);
await Check("unknown", """{"orderId":7,"extra":true}""", true, 0);
await Check("valid", """{"orderId":7}""", false, 1);

async Task Check(string label, string json, bool isError, int calls)
{
    provider.Enqueue(new ScriptStep
    {
        ToolCalls = [new ScriptedToolCall("lookup-1", "lookup", json)]
    });
    provider.EnqueueText("Done.");
    await runtime.RunAgentAsync(new AgentDefinition
    {
        Name = "lookup-demo",
        // OneLLM resolves this to openai. The scripted
        // provider ignores the model name and plays the queue.
        Model = "gpt-6-luna",
        SystemPrompt = "Look up order 7.",
        InitialPrompts = [Message.FromUser("Find order 7.")],
        References = [new ToolReference { Tools = ["lookup"] }]
    });
    var call = provider.Requests[^1].Messages
        .SelectMany(message => message.ToolCalls).Single();
    if (call.IsError != isError || LookupTools.Calls != calls)
        throw new InvalidOperationException($"Unexpected result: {label}");
    var text = (TextPart)call.Result.Single();
    Console.WriteLine($"{label}: {text.Text}");
}

public sealed partial class LookupTools
{
    public static int Calls { get; private set; }

    [Tool]
    public static string Lookup(int orderId)
    {
        Calls++;
        return $"Order {orderId}";
    }
}
```

```text
broken JSON: Tool 'lookup' was called with arguments that are not a JSON object: {
wrong type: Argument 'orderId' must be an integer from -2147483648 to 2147483647.
missing: Argument 'orderId' is required but missing.
unknown: Argument 'extra' is not a parameter of this tool.
valid: Order 7
```

A rejected call has `IsError` set; its result contains the reason, and the loop can send that result back to the model instead of returning an unhandled argument exception.

## Variations

**Test JSON null.** Add this call before the valid case in the full program. `int` is non-nullable, so the method call count must stay at zero.

```csharp
await Check("null", """{"orderId":null}""", true, 0);
```

## Related recipes

- [Generate tool JSON Schema in C#](https://recursiveai.org/onellm/cookbook/generate-tool-json-schema-offline/)
- [Test LLM code without an API key](https://recursiveai.org/onellm/cookbook/test-llm-code-without-api-key/)

## The short answer

Mark a method `[Tool]` and invoke the generated tool via `ToolInvoker.InvokeAsync` to check a JSON object against the method’s arguments without a model call. For an end-to-end negative test, feed raw argument text through `ScriptedProvider` and inspect the resulting tool call’s `IsError` flag and error text. Also check that the method body was not called. The flag alone can’t distinguish an argument rejected before invocation from an exception thrown inside the method.

## What happens when an LLM sends invalid tool arguments?

There are two different failure points. A string like `{` can’t become a JSON object at all. The loop refuses it before invoking the tool. A string like `{"orderId":"seven"}` is valid JSON and does become an object, but the generated invocation code refuses the string where the C# signature requires an `int`. An empty object reaches the same binding stage and fails because the signature requires `orderId`. An extra property also fails, even if every required argument is present: the generated tool accepts only the declared names.

A binding error differs from cancellation. As the [tool reference](https://recursiveai.org/onellm/docs/tool-schemas/#errors-become-results) puts it, “Cancellation by the caller is not an error result.” An `OperationCanceledException` propagates in that case rather than being returned as an invalid call.

## How do you test tool calls without a live model?

Queue the exact raw argument string you want to test so you can reproduce a failure at will. Test one defect per call: if a fixture has both a missing key and a wrong type, it may only show which check runs first. Keep a valid control with the same tool name. It confirms the tool is registered and that your call counter can detect a real invocation. In the example, the second scripted response ends the run; it isn’t evidence that any model can interpret or repair the error.

A successfully bound argument isn’t necessarily a valid application request. The signature `Lookup(int orderId)` checks the shape and range of an integer, not whether that order exists. Keep that decision in the lookup itself, where the application has access to the catalog or database. Test those cases separately with valid JSON so the arguments reach the method.
