Skip to content

Add Support for DataAnnotations in JSON Schema Generation #6536

@rwoodley

Description

@rwoodley

Summary:

Add support for System.ComponentModel.DataAnnotations attributes in JSON schema generation to enable proper validation constraints in tool schemas. (Originally opened in the https://github.com/modelcontextprotocol
csharp-sdk repo as this issue: modelcontextprotocol/csharp-sdk#535 ).

Problem Statement:

Currently, the Microsoft.Extensions.AI's AIFunction infrastructure for JSON schema generation doesn't honor standard .NET validation attributes like [Range], [Required], [StringLength], etc. This means that tool parameters cannot have proper validation constraints expressed in their JSON schemas, forcing developers to implement runtime validation manually.

Motivation: LLMs respect JSON schema validation attributes and if available will generate correctly formed JSON in one shot. This is preferable to having the MCP server throw validation exceptions which force the LLM to iterate to generate valid inputs.

Current Behavior:

When a record parameter has the following attributes:

public record SimulationSettings(
    [Range(-1, 10, ErrorMessage = "Must be between -1 and 10")]
    decimal MarketROR
);

The generated JSON schema only includes:

{
  "marketROR": {
    "type": "number"
  }
}

Expected Behavior:

The generated JSON schema should include validation constraints:

{
  "marketROR": {
    "type": "number",
    "minimum": -1,
    "maximum": 10
  }
}

Attributes to be supported:

[Range(min, max)] → "minimum" and "maximum" properties
[Required] → "required" array inclusion
[StringLength(max)] → "maxLength" property
[RegularExpression(pattern)] → "pattern" property
[EmailAddress] → "format": "email"

Benefits:

Standards Compliance: Leverages existing .NET validation patterns
Better DX: Developers can use familiar validation attributes
Client Validation: MCP clients can validate inputs before making tool calls
Documentation: Schema serves as self-documenting API contracts
Consistency: Aligns with ASP.NET Core, Minimal APIs, and other .NET frameworks

Thank you.

Metadata

Metadata

Assignees

Labels

area-aiMicrosoft.Extensions.AI libraries

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions