Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
65 commits
Select commit Hold shift + click to select a range
519e96c
Fix nullable structured tool results
mikemikimike Oct 13, 2026
de107a5
Fix structured output for required nullable properties
mikemikimike Oct 19, 2026
55b7972
Preserve schema-required nullable output members
mikemikimike Oct 21, 2026
f1a39f8
Fix structured output required member restoration
mikemikimike Oct 22, 2026
6c530f6
Merge branch 'main' into fix/structured-content-null-schema
tarekgh Oct 22, 2026
c4f9d71
Repair structured output against explicit schemas
mikemikimike Oct 23, 2026
0170ae6
Add regression for structured output source lookups
mikemikimike Oct 23, 2026
d633262
Merge branch 'main' into fix/structured-content-null-schema
tarekgh Oct 23, 2026
dfed8d3
Fix structured content schema recovery
mikemikimike Oct 26, 2026
f756988
Test structured output schema edge cases
mikemikimike Oct 26, 2026
e294aeb
Cover branch-isolated structured output recovery
mikemikimike Oct 26, 2026
a3384df
Merge branch 'main' into fix/structured-content-null-schema
tarekgh Oct 26, 2026
5dd99de
Fix structured output repair edge cases
mikemikimike Oct 27, 2026
4dfae0e
Fix structured output recovery edge cases
Oct 27, 2026
db3d9e7
Merge branch 'main' into fix/structured-content-null-schema
tarekgh Oct 27, 2026
4ca13cf
Fix composed structured output recovery and embedded references
Oct 27, 2026
351451e
Fix structured output recovery review issues
mikemikimike Oct 28, 2026
d3d0080
Merge upstream review fixes and preserve expanded regression coverage
Oct 28, 2026
66dfae7
Merge branch 'main' into fix/structured-content-null-schema
tarekgh Oct 28, 2026
9b2f5c8
Fix structured output recovery contracts and bound schema traversal
Oct 28, 2026
5b24706
Fix structured output recovery boundaries and branch selection
Oct 28, 2026
8731f21
Cache structured output recovery contracts without mutating metadata
Oct 28, 2026
a1fb212
Merge upstream main into structured output recovery fixes
Oct 28, 2026
d4c38b2
Preserve ancestor cycle scope during structured output recovery
Oct 28, 2026
d0fe5e4
Respect effective schemas and serialization boundaries during output …
Oct 28, 2026
f249b4a
Fix structured output recovery edge cases
mikemikimike Oct 29, 2026
875cc0f
Avoid recovery from reordered enumerables
mikemikimike Oct 29, 2026
4bac0eb
Align NativeAOT iterator assertions with conservative recovery
Oct 29, 2026
1bee8f7
Recover structured output from generic lists
mikemikimike Oct 29, 2026
49b1bf9
Bound structured output recovery allocation and schema work
Oct 29, 2026
c23927f
Fix structured output recovery safety and annotation boundaries
Oct 29, 2026
4225c52
Preserve serializer readonly-member recovery capabilities
Oct 29, 2026
bd84672
Merge branch 'main' into fix/structured-content-null-schema
tarekgh Oct 29, 2026
21d1b3e
Retain original structured output after recovery failures
Oct 29, 2026
67b6f7a
Preserve effective schemas through forwarding tool invocations
Oct 30, 2026
ee847e7
Merge branch 'main' into fix/structured-content-null-schema
tarekgh Oct 30, 2026
493eb4d
Skip structured output recovery for serialized JSON results
Oct 30, 2026
cad6719
Merge branch 'main' into fix/structured-content-null-schema
tarekgh Oct 30, 2026
64f57d1
Preserve structured output across mutable forwarding boundaries
Oct 31, 2026
13a1357
Merge branch 'main' into fix/structured-content-null-schema
tarekgh Oct 31, 2026
3f0015d
Address structured output recovery review feedback
mikemikimike Oct 31, 2026
d086ca5
Fix structured output recovery across stacked delegation
Nov 3, 2026
87279ec
Merge branch 'main' into fix/structured-content-null-schema
tarekgh Nov 3, 2026
90ab0e5
Isolate structured output recovery and stabilize transport startup
Nov 4, 2026
0f74bab
Merge upstream main and update AOT skills test compatibility
mikemikimike Nov 8, 2026
b53e6c6
Avoid stdio cleanup read-loop deadlock
mikemikimike Nov 11, 2026
e41c1c9
Merge latest main into structured output fix
mikemikimike Nov 13, 2026
b07e0c6
Bound recovery retention and drain stdio shutdown
mikemikimike Nov 24, 2026
d3119c9
Harden structured output recovery and stdio shutdown
Nov 24, 2026
01ee7d1
Merge branch 'main' into fix/structured-content-null-schema
tarekgh Nov 24, 2026
f6905cc
Fix stdio reads at internal buffer boundaries
Nov 24, 2026
bdd780b
Merge remote-tracking branch 'refs/remotes/upstream/pr-1929-head' int…
Nov 24, 2026
fdefe1b
Harden structured tool output validation
Nov 24, 2026
4f4d2f9
Preserve structured output validation through filters
Nov 25, 2026
96caa9a
Fix deferred structured output validation matching
mikemikimike Nov 25, 2026
95f1c29
Avoid fetching external output schemas
Nov 25, 2026
6d9f66d
Fix deferred schema validation edge cases
Nov 25, 2026
f4090c3
Fix required nullable structured output members
mikemikimike Nov 26, 2026
ed1d02b
Fix scoped required-null structured output recovery
Nov 30, 2026
2347054
Handle root refs in null recovery plans
Dec 1, 2026
41e2598
Respect readonly settings with ambiguous metadata
Dec 1, 2026
206871c
Merge branch 'main' into fix/structured-content-null-schema
tarekgh Dec 1, 2026
3354551
Resolve encoded local schema references
Dec 1, 2026
37807c6
Preserve delegated tool output behavior
Dec 1, 2026
53ffdae
Fix nullable output recovery through transparent delegating tools
mikemikimike Dec 2, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
141 changes: 131 additions & 10 deletions src/ModelContextProtocol.Core/Server/AIFunctionMcpServerTool.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
using System.Reflection;
using System.Text.Json;
using System.Text.Json.Nodes;
using System.Text.Json.Serialization.Metadata;
using System.Text.RegularExpressions;

namespace ModelContextProtocol.Server;
Expand All @@ -15,6 +16,13 @@ internal sealed partial class AIFunctionMcpServerTool : McpServerTool
{
private readonly IReadOnlyList<object> _metadata;
private readonly bool? _returnsCallToolResult;
private readonly Type? _generatedReturnType;
private readonly RequiredNullOutputSerializer? _structuredOutputSerializer;
private readonly JsonElement? _generatedOutputSchema;
private const int MaxCachedRuntimeOutputTypes = 16;
private readonly object _runtimeSerializerLock = new();
private readonly Dictionary<Type, RequiredNullOutputSerializer?> _runtimeSerializers = [];
private readonly Queue<Type> _runtimeSerializerOrder = [];

/// <summary>
/// Creates an <see cref="McpServerTool"/> instance for a method, specified via a <see cref="Delegate"/> instance.
Expand Down Expand Up @@ -45,7 +53,8 @@ internal sealed partial class AIFunctionMcpServerTool : McpServerTool
return CreateCore(
AIFunctionFactory.Create(method, target, CreateAIFunctionFactoryOptions(method, options)),
options,
returnsCallToolResult: ReturnsCallToolResult(method));
returnsCallToolResult: ReturnsCallToolResult(method),
generatedReturnType: GetGeneratedReturnType(method, options));
}

/// <summary>
Expand All @@ -68,7 +77,25 @@ internal sealed partial class AIFunctionMcpServerTool : McpServerTool
return createTargetFunc(((RequestServiceProvider<CallToolRequestParams>)args.Services!).Request);
}, CreateAIFunctionFactoryOptions(method, options)),
options,
returnsCallToolResult: ReturnsCallToolResult(method));
returnsCallToolResult: ReturnsCallToolResult(method),
generatedReturnType: GetGeneratedReturnType(method, options));
}

private static Type? GetGeneratedReturnType(MethodInfo method, McpServerToolCreateOptions? options)
{
if (options?.UseStructuredContent is not true || options.OutputSchema is not null)
{
return null;
}

Type type = method.ReturnType;
if (type.IsGenericType &&
(type.GetGenericTypeDefinition() == typeof(Task<>) || type.GetGenericTypeDefinition() == typeof(ValueTask<>)))
{
type = type.GetGenericArguments()[0];
}

return type;
}

private static bool? ReturnsCallToolResult(MethodInfo method)
Expand Down Expand Up @@ -127,9 +154,10 @@ private static AIFunctionFactoryOptions CreateAIFunctionFactoryOptions(

/// <summary>Creates an <see cref="McpServerTool"/> that wraps the specified <see cref="AIFunction"/>.</summary>
public static new AIFunctionMcpServerTool Create(AIFunction function, McpServerToolCreateOptions? options) =>
CreateCore(function, options, returnsCallToolResult: null);
CreateCore(function, options, returnsCallToolResult: null, generatedReturnType: null);

private static AIFunctionMcpServerTool CreateCore(AIFunction function, McpServerToolCreateOptions? options, bool? returnsCallToolResult)
private static AIFunctionMcpServerTool CreateCore(
AIFunction function, McpServerToolCreateOptions? options, bool? returnsCallToolResult, Type? generatedReturnType)
{
Throw.IfNull(function);

Expand Down Expand Up @@ -174,7 +202,7 @@ options.OpenWorld is not null ||
options.Meta;
}

return new AIFunctionMcpServerTool(function, tool, options?.Services, options?.Metadata ?? [], returnsCallToolResult);
return new AIFunctionMcpServerTool(function, tool, options?.Services, options?.Metadata ?? [], returnsCallToolResult, generatedReturnType);
}

private static McpServerToolCreateOptions DeriveOptions(MethodInfo method, McpServerToolCreateOptions? options)
Expand Down Expand Up @@ -237,7 +265,8 @@ private static McpServerToolCreateOptions DeriveOptions(MethodInfo method, McpSe

/// <summary>Initializes a new instance of the <see cref="McpServerTool"/> class.</summary>
private AIFunctionMcpServerTool(
AIFunction function, Tool tool, IServiceProvider? serviceProvider, IReadOnlyList<object> metadata, bool? returnsCallToolResult)
AIFunction function, Tool tool, IServiceProvider? serviceProvider, IReadOnlyList<object> metadata, bool? returnsCallToolResult,
Type? generatedReturnType)
{
ValidateToolName(tool.Name);

Expand All @@ -246,6 +275,51 @@ private AIFunctionMcpServerTool(

_metadata = metadata;
_returnsCallToolResult = returnsCallToolResult;
_generatedReturnType = generatedReturnType;
if (generatedReturnType is not null && tool.OutputSchema is { } schema)
{
_structuredOutputSerializer = RequiredNullOutputSerializer.Create(generatedReturnType, schema, function.JsonSerializerOptions);
_generatedOutputSchema = schema;
}
}

private RequiredNullOutputSerializer? GetStructuredOutputSerializer(object value)
{
if (_generatedReturnType is null ||
ProtocolTool.OutputSchema is not { } schema ||
!Nullable.Equals(schema, _generatedOutputSchema))
{
return null;
}

Type runtimeType = value.GetType();
if (runtimeType == _generatedReturnType)
{
return _structuredOutputSerializer;
}

if (!_generatedReturnType.IsAssignableFrom(runtimeType))
{
return null;
}

lock (_runtimeSerializerLock)
{
if (_runtimeSerializers.TryGetValue(runtimeType, out RequiredNullOutputSerializer? serializer))
{
return serializer;
}

if (_runtimeSerializers.Count >= MaxCachedRuntimeOutputTypes)
{
_runtimeSerializers.Remove(_runtimeSerializerOrder.Dequeue());
}

serializer = RequiredNullOutputSerializer.Create(runtimeType, schema, AIFunction.JsonSerializerOptions);
_runtimeSerializers.Add(runtimeType, serializer);
_runtimeSerializerOrder.Enqueue(runtimeType);
return serializer;
}
}

/// <inheritdoc />
Expand Down Expand Up @@ -319,7 +393,9 @@ public override async ValueTask<CallToolResult> InvokeAsync(
return callToolResult;
}

JsonElement? structuredContent = CreateStructuredResponse(result, request.Server.NegotiatedProtocolVersion);
bool restoreRequiredNulls = ShouldRestoreRequiredNulls(request);
JsonElement? structuredContent = CreateStructuredResponse(
result, request.Server.NegotiatedProtocolVersion, restoreRequiredNulls);
return result switch
{
AIContent aiContent => new()
Expand Down Expand Up @@ -363,6 +439,41 @@ public override async ValueTask<CallToolResult> InvokeAsync(
};
}

private bool ShouldRestoreRequiredNulls(RequestContext<CallToolRequestParams> request)
{
if (request.MatchedPrimitive is null || ReferenceEquals(request.MatchedPrimitive, this))
{
return true;
}

if (request.MatchedPrimitive is not McpServerTool matchedTool)
{
return false;
}

McpServerTool current = matchedTool;
while (current is DelegatingMcpServerTool delegatingTool)
{
if (!OutputSchemasEqual(current.ProtocolTool.OutputSchema, ProtocolTool.OutputSchema))
{
return false;
}

current = delegatingTool.InnerTool;
if (ReferenceEquals(current, this))
{
return true;
}
}

return false;
}

private static bool OutputSchemasEqual(JsonElement? left, JsonElement? right) =>
left is null
? right is null
: right is { } rightSchema && JsonElement.DeepEquals(left.Value, rightSchema);

/// <summary>Creates a name to use based on the supplied method and naming policy.</summary>
internal static string DeriveName(MethodInfo method, JsonNamingPolicy? policy = null)
{
Expand Down Expand Up @@ -762,7 +873,8 @@ private static void RewriteRefProperty(JsonObject schema, string keyword, string
}
}

private JsonElement? CreateStructuredResponse(object? aiFunctionResult, string? negotiatedProtocolVersion)
private JsonElement? CreateStructuredResponse(
object? aiFunctionResult, string? negotiatedProtocolVersion, bool restoreRequiredNulls)
{
if (ProtocolTool.OutputSchema is null)
{
Expand All @@ -775,7 +887,7 @@ private static void RewriteRefProperty(JsonObject schema, string keyword, string
JsonElement jsonElement => jsonElement,
JsonNode node => JsonSerializer.SerializeToElement(node, McpJsonUtilities.JsonContext.Default.JsonNode),
null => null,
_ => JsonSerializer.SerializeToElement(aiFunctionResult, AIFunction.JsonSerializerOptions.GetTypeInfo(typeof(object))),
_ => SerializeStructuredOutput(aiFunctionResult, restoreRequiredNulls),
};

// Pre-SEP-2106 clients expect the {"result": <value>} envelope for non-object
Expand All @@ -796,6 +908,15 @@ private static void RewriteRefProperty(JsonObject schema, string keyword, string
return elementResult;
}

private JsonElement SerializeStructuredOutput(object value, bool restoreRequiredNulls)
{
JsonTypeInfo objectTypeInfo = AIFunction.JsonSerializerOptions.GetTypeInfo(typeof(object));
JsonElement result = JsonSerializer.SerializeToElement(value, objectTypeInfo);
return restoreRequiredNulls && objectTypeInfo.Converter.GetType().Assembly == typeof(JsonSerializer).Assembly
? GetStructuredOutputSerializer(value)?.Apply(result) ?? result
: result;
}

private static CallToolResult ConvertAIContentEnumerableToCallToolResult(IEnumerable<AIContent> contentItems, JsonElement? structuredContent)
{
List<ContentBlock> contentList = [];
Expand Down Expand Up @@ -903,4 +1024,4 @@ private static bool IsPrimitiveHeaderType(Type type)
type == typeof(uint) ||
type == typeof(long);
}
}
}
12 changes: 12 additions & 0 deletions src/ModelContextProtocol.Core/Server/McpServerToolCreateOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -124,8 +124,20 @@ public sealed class McpServerToolCreateOptions
/// The default is <see langword="false"/>.
/// </value>
/// <remarks>
/// <para>
/// When enabled, the tool will attempt to populate the <see cref="Tool.OutputSchema"/>
/// and provide structured content in the <see cref="CallToolResult.StructuredContent"/> property.
/// </para>
/// <para>
/// For supported schemas inferred from a method's return type, required nullable members
/// omitted by the default <see cref="System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull"/>
/// policy are included as null in structured content. Explicit schemas and separately supplied
/// <see cref="AIFunction"/> instances are not changed. Custom serialization resolvers are left untouched.
/// Custom converters, polymorphic types, and extension data retain their configured behavior and are not
/// traversed for repair. Required nulls are restored on opaque object members when their schema permits null,
/// but non-null opaque values are not traversed. Other schema-described members may still be repaired. This
/// option does not validate or repair other output mismatches.
/// </para>
/// </remarks>
public bool UseStructuredContent { get; set; }

Expand Down
Loading