---
title: "Generate tool input JSON Schema in C#"
url: https://recursiveai.org/onemodelcontext/cookbook/generate-tool-input-json-schema/
description: "Generate a tool input JSON Schema from C# parameters. Inspect required arguments, defaults, validation attributes and read-only annotations offline."
version: "1.0.1"
---

# Generate tool input JSON Schema 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/generate-tool-input-json-schema/generate-tool-input-json-schema.zip)

AI clients use the Model Context Protocol® to find and call tools, and read the input schema to learn the arguments.

```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.

```csharp
using System.Text.Json;
using RecursiveAI.OneModelContext;

var server = new ContextServer("demo", "1.0");
server.Tool("echo", (string text) => text);
if (server.Tools.TryGet("echo",
    out var tool, out _))
    Console.WriteLine(JsonSerializer.Serialize(
        tool.InputSchema,
        new JsonSerializerOptions { WriteIndented = true }));
```

```text
{
  "type": "object",
  "properties": {
    "text": {
      "type": "string"
    }
  },
  "required": [
    "text"
  ],
  "additionalProperties": false
}
```

Unzip [the example](https://recursiveai.org/onemodelcontext/cookbook/generate-tool-input-json-schema/generate-tool-input-json-schema.zip), then `dotnet run`.

## The full program

The full program uses `[Tool]` on a partial class. The package’s source generator writes `AddTo` and the schema during compilation; no extra generator package is needed.

```csharp
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Text.Json;
using RecursiveAI.OneModelContext;

var server = new ContextServer("schema-demo", "1.0");
new SearchTools().AddTo(server);
if (!server.Tools.TryGet("search", out var tool, out _))
    throw new InvalidOperationException("Missing search tool.");
Console.WriteLine(JsonSerializer.Serialize(tool.InputSchema,
    new JsonSerializerOptions { WriteIndented = true }));
Console.WriteLine("ReadOnly: " + tool.Annotations?.ReadOnlyHint);

public partial class SearchTools
{
    [Tool(ReadOnly = true)]
    public string Search(
        [Description("Words to find."), MinLength(1)] string query,
        [Range(1, 20)] int limit = 5) => query;
}
```

`dotnet run` prints:

```text
{
  "type": "object",
  "properties": {
    "query": {
      "type": "string",
      "description": "Words to find.",
      "minLength": 1
    },
    "limit": {
      "type": "integer",
      "minimum": 1,
      "maximum": 20,
      "default": 5
    }
  },
  "required": [
    "query"
  ],
  "additionalProperties": false
}
ReadOnly: True
```

Unsupported signatures are refused by the source generator; schema generation is not a general-purpose JSON Schema validation API.

## Variations

**Inspect required fields and defaults.** Insert this before the `SearchTools` class in the full program:

```csharp
Console.WriteLine(string.Join(", ", tool.InputSchema
    .GetProperty("required").EnumerateArray()
    .Select(field => field.GetString())));
Console.WriteLine(tool.InputSchema.GetProperty("properties")
    .GetProperty("limit").GetProperty("default").GetInt32());
```

```text
query
5
```

## Related recipes

- [Register tools](https://recursiveai.org/onemodelcontext/cookbook/add-tools-at-runtime/)
- [Tool schema mapping](https://recursiveai.org/onemodelcontext/docs/tool-schemas/)

## The short answer

OneModelContext generates a tool input JSON Schema from its C# parameter list. The snippet at the top uses the reflection quick path, `server.Tool`, and reads the definition from `server.Tools`. The full program uses the `[Tool]` source generator instead. Both paths use the documented signature-to-schema mapping. Nothing in this example connects to an external service or calls a model.

For tools exposed through the Model Context Protocol®, the generated schema is the argument description clients discover. Use the simple delegate path for an ordinary untrimmed application, or the generated path when you need compile-time signature checks and source-generated invocation. The [tool schema mapping](https://recursiveai.org/onemodelcontext/docs/tool-schemas/) is the reference for supported types and attributes.

## How do I generate a tool input JSON Schema from C#?

Declare a tool method in a partial class and mark it with `[Tool]`. After building, call the generated `AddTo(server)` method, retrieve the registered definition, and inspect `InputSchema`. The example’s `Search` method becomes the tool named `search`; the input property names remain `query` and `limit`, exactly as the parameters are written. The method is registered but never invoked in this program.

`Description` supplies readable parameter documentation. `MinLength(1)` becomes `minLength`, while `Range(1, 20)` sets the integer bounds. Those constraints are visible in the actual printed schema. The mapping also covers string length, maximum length, regular expressions, email addresses and URLs, but only the documented keyword set is emitted. This is a tool-signature exporter, not a way to load and rewrite an arbitrary schema document.

Scalar types work directly. More complex records and collections can require a `JsonSerializerContext` listing their types for the generated invoker. An unsupported type or a missing required context is a build-time diagnostic rather than a silent fallback to reflection.

### Which tool arguments are required in the generated schema?

A parameter is required unless it has a C# default value. In the example, `query` is required and `limit` is optional because its declaration supplies `5`. That default is also written into the schema. The variation reads the actual `required` array and `default` keyword, rather than inferring them from whether a property happened to appear.

Nullability is separate from optionality. A nullable parameter without a default is still required, but accepts `null`. A null default makes a parameter optional without emitting a `default` keyword. Parameters of type `RequestContext` and `CancellationToken` are supplied by the library and are not listed as input properties. The generated input object is closed with `additionalProperties: false`.

`[Tool(ReadOnly = true)]` is a tool annotation, not an input constraint. That is why the program prints it separately from `InputSchema`. It describes the tool’s intended behavior to clients; it does not change which arguments are required or enforce that the method has no side effects.

The docs identify the schema dialect as JSON Schema 2020-12, with a defined subset of emitted keywords. Inspecting that schema does not run argument validation, execute the tool or establish compatibility with every consumer of JSON Schema.
