diff --git a/src/ModelContextProtocol.Core/Server/AIFunctionMcpServerTool.cs b/src/ModelContextProtocol.Core/Server/AIFunctionMcpServerTool.cs index 6d4579f66..f240080a0 100644 --- a/src/ModelContextProtocol.Core/Server/AIFunctionMcpServerTool.cs +++ b/src/ModelContextProtocol.Core/Server/AIFunctionMcpServerTool.cs @@ -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; @@ -15,6 +16,13 @@ internal sealed partial class AIFunctionMcpServerTool : McpServerTool { private readonly IReadOnlyList _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 _runtimeSerializers = []; + private readonly Queue _runtimeSerializerOrder = []; /// /// Creates an instance for a method, specified via a instance. @@ -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)); } /// @@ -68,7 +77,25 @@ internal sealed partial class AIFunctionMcpServerTool : McpServerTool return createTargetFunc(((RequestServiceProvider)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) @@ -127,9 +154,10 @@ private static AIFunctionFactoryOptions CreateAIFunctionFactoryOptions( /// Creates an that wraps the specified . 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); @@ -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) @@ -237,7 +265,8 @@ private static McpServerToolCreateOptions DeriveOptions(MethodInfo method, McpSe /// Initializes a new instance of the class. private AIFunctionMcpServerTool( - AIFunction function, Tool tool, IServiceProvider? serviceProvider, IReadOnlyList metadata, bool? returnsCallToolResult) + AIFunction function, Tool tool, IServiceProvider? serviceProvider, IReadOnlyList metadata, bool? returnsCallToolResult, + Type? generatedReturnType) { ValidateToolName(tool.Name); @@ -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; + } } /// @@ -319,7 +393,9 @@ public override async ValueTask 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() @@ -363,6 +439,41 @@ public override async ValueTask InvokeAsync( }; } + private bool ShouldRestoreRequiredNulls(RequestContext 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); + /// Creates a name to use based on the supplied method and naming policy. internal static string DeriveName(MethodInfo method, JsonNamingPolicy? policy = null) { @@ -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) { @@ -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": } envelope for non-object @@ -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 contentItems, JsonElement? structuredContent) { List contentList = []; @@ -903,4 +1024,4 @@ private static bool IsPrimitiveHeaderType(Type type) type == typeof(uint) || type == typeof(long); } -} \ No newline at end of file +} diff --git a/src/ModelContextProtocol.Core/Server/McpServerToolCreateOptions.cs b/src/ModelContextProtocol.Core/Server/McpServerToolCreateOptions.cs index b0b6b3de7..349b0100e 100644 --- a/src/ModelContextProtocol.Core/Server/McpServerToolCreateOptions.cs +++ b/src/ModelContextProtocol.Core/Server/McpServerToolCreateOptions.cs @@ -124,8 +124,20 @@ public sealed class McpServerToolCreateOptions /// The default is . /// /// + /// /// When enabled, the tool will attempt to populate the /// and provide structured content in the property. + /// + /// + /// For supported schemas inferred from a method's return type, required nullable members + /// omitted by the default + /// policy are included as null in structured content. Explicit schemas and separately supplied + /// 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. + /// /// public bool UseStructuredContent { get; set; } diff --git a/src/ModelContextProtocol.Core/Server/RequiredNullOutputSerializer.cs b/src/ModelContextProtocol.Core/Server/RequiredNullOutputSerializer.cs new file mode 100644 index 000000000..9a51cf280 --- /dev/null +++ b/src/ModelContextProtocol.Core/Server/RequiredNullOutputSerializer.cs @@ -0,0 +1,653 @@ +using System.Reflection; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Text.Json.Serialization.Metadata; + +namespace ModelContextProtocol.Server; + +internal sealed class RequiredNullOutputSerializer +{ + private const int DefaultMaxDepth = 64; + private readonly PlanNode _root; + private readonly int _maxDepth; + private readonly int _maxRecoveryDepth; + + private RequiredNullOutputSerializer(PlanNode root, int maxDepth, int maxRecoveryDepth) + { + _root = root; + _maxDepth = maxDepth; + _maxRecoveryDepth = maxRecoveryDepth; + } + + internal static RequiredNullOutputSerializer? Create(Type returnType, JsonElement schema, JsonSerializerOptions options) + { + if (options.DefaultIgnoreCondition != JsonIgnoreCondition.WhenWritingNull || + options.TypeInfoResolver is null) + { + return null; + } + + try + { + int maxDepth = options.MaxDepth == 0 ? DefaultMaxDepth : options.MaxDepth; + int maxRecoveryDepth = maxDepth; + PlanNode root = CreatePlan(returnType, schema, options, maxRecoveryDepth); + return HasRequiredNulls(root) ? new(root, maxDepth, maxRecoveryDepth) : null; + } + catch (NotSupportedException) + { + return null; + } + catch (InvalidOperationException) + { + return null; + } + } + + internal JsonElement Apply(JsonElement serialized) + { + if (!ContainsMissing(_root, serialized, 0)) + { + return serialized; + } + + using MemoryStream stream = new(); + using (Utf8JsonWriter writer = new(stream, new JsonWriterOptions { MaxDepth = _maxDepth })) + { + WritePatched(_root, serialized, writer, 0); + } + + using JsonDocument document = JsonDocument.Parse( + stream.ToArray(), new JsonDocumentOptions { MaxDepth = _maxDepth }); + return document.RootElement.Clone(); + } + + private static PlanNode CreatePlan(Type type, JsonElement schema, JsonSerializerOptions options, int maxDepth) + { + Dictionary<(Type, JsonElement, JsonElement), PlanNode> nodes = new(); + Queue<(PlanNode Plan, JsonTypeInfo TypeInfo, JsonElement Schema, JsonElement Root, int Depth)> pending = new(); + PlanNode rootPlan = GetOrCreatePlan(type, schema, schema, 0); + while (pending.Count > 0) + { + var (plan, typeInfo, currentSchema, root, depth) = pending.Dequeue(); + if (typeInfo.Kind == JsonTypeInfoKind.Enumerable) + { + if (typeInfo.ElementType is { } elementType && currentSchema.TryGetProperty("items", out JsonElement items)) + { + plan.Kind = PlanKind.Array; + plan.Element = GetOrCreatePlan(elementType, items, root, depth + 1); + } + + continue; + } + + if (typeInfo.Kind == JsonTypeInfoKind.Dictionary) + { + if (typeInfo.ElementType is { } valueType && currentSchema.TryGetProperty("additionalProperties", out JsonElement values)) + { + plan.Kind = PlanKind.Dictionary; + plan.Element = GetOrCreatePlan(valueType, values, root, depth + 1); + } + + continue; + } + + if (typeInfo.Kind != JsonTypeInfoKind.Object || + typeInfo.PolymorphismOptions is not null || + !currentSchema.TryGetProperty("properties", out JsonElement properties) || + properties.ValueKind != JsonValueKind.Object) + { + continue; + } + + HashSet required = new(StringComparer.Ordinal); + if (currentSchema.TryGetProperty("required", out JsonElement requiredNames) && requiredNames.ValueKind == JsonValueKind.Array) + { + foreach (JsonElement name in requiredNames.EnumerateArray()) + { + if (name.ValueKind == JsonValueKind.String && name.GetString() is { } value) + { + required.Add(value); + } + } + } + + Dictionary propertySchemas = new(StringComparer.Ordinal); + foreach (JsonProperty property in properties.EnumerateObject()) + { + propertySchemas[property.Name] = property.Value; + } + + plan.Kind = PlanKind.Object; + foreach (JsonPropertyInfo property in typeInfo.Properties) + { + if (property.IsExtensionData || !propertySchemas.TryGetValue(property.Name, out JsonElement propertySchema)) + { + continue; + } + + bool customConverter = property.CustomConverter is not null || + (property.AttributeProvider is ICustomAttributeProvider attributes && + attributes.IsDefined(typeof(JsonConverterAttribute), true)); + bool addNullWhenMissing = !customConverter && + required.Contains(property.Name) && + AllowsNull(propertySchema, root) && + CanOverrideNullOmission(property, options); + + PlanNode? child = null; + if (!customConverter && property.PropertyType != typeof(object) && property.Get is not null) + { + child = GetOrCreatePlan(property.PropertyType, propertySchema, root, depth + 1); + } + + PropertyPlan propertyPlan = new(property.Name, addNullWhenMissing, child); + plan.Properties.Add(propertyPlan); + plan.PropertiesByName[property.Name] = propertyPlan; + } + } + + return rootPlan; + + PlanNode GetOrCreatePlan(Type currentType, JsonElement currentSchema, JsonElement root, int depth) + { + PlanNode plan = new(); + if (depth >= maxDepth || currentSchema.ValueKind != JsonValueKind.Object) + { + return plan; + } + + if (!TryResolveSchema(ref currentSchema, ref root) || + currentSchema.ValueKind != JsonValueKind.Object || HasComposition(currentSchema)) + { + return plan; + } + + JsonTypeInfo declaredTypeInfo = options.GetTypeInfo(currentType); + if (declaredTypeInfo.Converter.GetType().Assembly != typeof(JsonSerializer).Assembly) + { + return plan; + } + + currentType = Nullable.GetUnderlyingType(currentType) ?? currentType; + if (nodes.TryGetValue((currentType, currentSchema, root), out PlanNode? existing)) + { + return existing; + } + + nodes.Add((currentType, currentSchema, root), plan); + JsonTypeInfo typeInfo = currentType == declaredTypeInfo.Type ? declaredTypeInfo : options.GetTypeInfo(currentType); + if (typeInfo.Converter.GetType().Assembly == typeof(JsonSerializer).Assembly) + { + pending.Enqueue((plan, typeInfo, currentSchema, root, depth)); + } + + return plan; + } + } + + private static bool HasRequiredNulls(PlanNode root) + { + List plans = []; + CollectPlans(root, new(), plans); + Dictionary> parents = new(); + Queue pending = new(); + + foreach (PlanNode plan in plans) + { + plan.HasRequiredNulls = plan.Properties.Any(static property => property.AddNullWhenMissing); + if (plan.HasRequiredNulls) + { + pending.Enqueue(plan); + } + + if (plan.Element is { } element) + { + AddParent(parents, element, plan); + } + + foreach (PropertyPlan property in plan.Properties) + { + if (property.Child is { } child) + { + AddParent(parents, child, plan); + } + } + } + + while (pending.Count > 0) + { + PlanNode child = pending.Dequeue(); + if (parents.TryGetValue(child, out List? dependents)) + { + foreach (PlanNode parent in dependents) + { + if (!parent.HasRequiredNulls) + { + parent.HasRequiredNulls = true; + pending.Enqueue(parent); + } + } + } + } + + return root.HasRequiredNulls; + } + + private static void AddParent(Dictionary> parents, PlanNode child, PlanNode parent) + { + if (!parents.TryGetValue(child, out List? dependents)) + { + parents.Add(child, dependents = []); + } + + dependents.Add(parent); + } + + private static void CollectPlans(PlanNode plan, HashSet visited, List plans) + { + Stack pending = new(); + pending.Push(plan); + while (pending.Count > 0) + { + PlanNode current = pending.Pop(); + if (!visited.Add(current)) + { + continue; + } + + plans.Add(current); + if (current.Element is { } element) + { + pending.Push(element); + } + + foreach (PropertyPlan property in current.Properties) + { + if (property.Child is { } child) + { + pending.Push(child); + } + } + } + } + + private bool ContainsMissing(PlanNode plan, JsonElement value, int depth) + { + Stack pending = new(); + pending.Push(new(plan, value, depth)); + while (pending.Count > 0) + { + TraversalFrame current = pending.Pop(); + if (current.Depth >= _maxRecoveryDepth || !current.Plan.HasRequiredNulls) + { + continue; + } + + if (current.Plan.Kind == PlanKind.Object && current.Value.ValueKind == JsonValueKind.Object) + { + Dictionary values = GetProperties(current.Value); + foreach (PropertyPlan property in current.Plan.Properties) + { + if (!values.TryGetValue(property.Name, out SerializedProperty childValue)) + { + if (property.AddNullWhenMissing) + { + return true; + } + } + else if (!childValue.IsDuplicate && + property.Child is { } child && + childValue.Value.ValueKind is not (JsonValueKind.Null or JsonValueKind.Undefined)) + { + pending.Push(new(child, childValue.Value, current.Depth + 1)); + } + } + } + else if (current.Plan.Kind == PlanKind.Array && current.Plan.Element is { } element && + current.Value.ValueKind == JsonValueKind.Array) + { + foreach (JsonElement item in current.Value.EnumerateArray()) + { + if (item.ValueKind is not (JsonValueKind.Null or JsonValueKind.Undefined)) + { + pending.Push(new(element, item, current.Depth + 1)); + } + } + } + else if (current.Plan.Kind == PlanKind.Dictionary && current.Plan.Element is { } dictionaryElement && + current.Value.ValueKind == JsonValueKind.Object) + { + foreach (JsonProperty item in current.Value.EnumerateObject()) + { + if (item.Value.ValueKind is not (JsonValueKind.Null or JsonValueKind.Undefined)) + { + pending.Push(new(dictionaryElement, item.Value, current.Depth + 1)); + } + } + } + } + + return false; + } + + private void WritePatched(PlanNode plan, JsonElement value, Utf8JsonWriter writer, int depth) + { + Stack pending = new(); + pending.Push(new(WriteActionKind.Value, plan, value, depth, null, default)); + while (pending.Count > 0) + { + WriteAction action = pending.Pop(); + switch (action.Kind) + { + case WriteActionKind.EndObject: + writer.WriteEndObject(); + continue; + case WriteActionKind.EndArray: + writer.WriteEndArray(); + continue; + case WriteActionKind.NullProperty: + writer.WriteNull(action.PropertyName!); + continue; + case WriteActionKind.Property: + writer.WritePropertyName(action.Property.Name); + action.Property.Value.WriteTo(writer); + continue; + } + + if (action.PropertyName is not null) + { + writer.WritePropertyName(action.PropertyName); + } + + PlanNode currentPlan = action.Plan!; + if (action.Depth >= _maxRecoveryDepth || !currentPlan.HasRequiredNulls) + { + action.Value.WriteTo(writer); + } + else if (currentPlan.Kind == PlanKind.Object && action.Value.ValueKind == JsonValueKind.Object) + { + Dictionary values = GetProperties(action.Value); + writer.WriteStartObject(); + pending.Push(new(WriteActionKind.EndObject, null, default, 0, null, default)); + + for (int i = currentPlan.Properties.Count - 1; i >= 0; i--) + { + PropertyPlan property = currentPlan.Properties[i]; + if (property.AddNullWhenMissing && !values.ContainsKey(property.Name)) + { + pending.Push(new(WriteActionKind.NullProperty, null, default, 0, property.Name, default)); + } + } + + JsonProperty[] properties = action.Value.EnumerateObject().ToArray(); + for (int i = properties.Length - 1; i >= 0; i--) + { + JsonProperty property = properties[i]; + if (currentPlan.PropertiesByName.TryGetValue(property.Name, out PropertyPlan? propertyPlan) && + values.TryGetValue(property.Name, out SerializedProperty childValue) && + !childValue.IsDuplicate && + propertyPlan.Child is { } child && + property.Value.ValueKind is not (JsonValueKind.Null or JsonValueKind.Undefined)) + { + pending.Push(new(WriteActionKind.Value, child, property.Value, action.Depth + 1, property.Name, default)); + } + else + { + pending.Push(new(WriteActionKind.Property, null, default, 0, null, property)); + } + } + } + else if (currentPlan.Kind == PlanKind.Array && currentPlan.Element is { } element && + action.Value.ValueKind == JsonValueKind.Array) + { + JsonElement[] items = action.Value.EnumerateArray().ToArray(); + writer.WriteStartArray(); + pending.Push(new(WriteActionKind.EndArray, null, default, 0, null, default)); + for (int i = items.Length - 1; i >= 0; i--) + { + pending.Push(new(WriteActionKind.Value, element, items[i], action.Depth + 1, null, default)); + } + } + else if (currentPlan.Kind == PlanKind.Dictionary && currentPlan.Element is { } dictionaryElement && + action.Value.ValueKind == JsonValueKind.Object) + { + JsonProperty[] properties = action.Value.EnumerateObject().ToArray(); + writer.WriteStartObject(); + pending.Push(new(WriteActionKind.EndObject, null, default, 0, null, default)); + for (int i = properties.Length - 1; i >= 0; i--) + { + JsonProperty property = properties[i]; + pending.Push(new(WriteActionKind.Value, dictionaryElement, property.Value, action.Depth + 1, property.Name, default)); + } + } + else + { + action.Value.WriteTo(writer); + } + } + } + + private static Dictionary GetProperties(JsonElement value) + { + Dictionary properties = new(StringComparer.Ordinal); + foreach (JsonProperty property in value.EnumerateObject()) + { + if (properties.TryGetValue(property.Name, out SerializedProperty existing)) + { + properties[property.Name] = existing with { IsDuplicate = true }; + } + else + { + properties.Add(property.Name, new(property.Value, IsDuplicate: false)); + } + } + + return properties; + } + + private static bool CanOverrideNullOmission(JsonPropertyInfo property, JsonSerializerOptions options) + { + return HasDefaultSerializationBehavior(property, options) && + options.GetTypeInfo(property.PropertyType).Converter.GetType().Assembly == typeof(JsonSerializer).Assembly; + } + + private static bool HasDefaultSerializationBehavior(JsonPropertyInfo property, JsonSerializerOptions options) + { + bool ignoreReadOnly = false; + if (property.Set is null) + { + bool ignoreReadOnlyMember = property.AttributeProvider switch + { + FieldInfo => options.IgnoreReadOnlyFields, + PropertyInfo => options.IgnoreReadOnlyProperties, + // Custom or source-generated metadata may not identify the member. + _ => options.IgnoreReadOnlyFields || options.IgnoreReadOnlyProperties, + }; + if (ignoreReadOnlyMember) + { + JsonTypeInfoKind propertyKind = options.GetTypeInfo(property.PropertyType).Kind; + ignoreReadOnly = propertyKind is not (JsonTypeInfoKind.Enumerable or JsonTypeInfoKind.Dictionary); + } + } + + return !(property.Get is null || property.ShouldSerialize is not null || property.CustomConverter is not null || + property.IsExtensionData || + ignoreReadOnly || + (options.RespectNullableAnnotations && !property.IsGetNullable) || + (property.AttributeProvider is ICustomAttributeProvider attributes && + (attributes.IsDefined(typeof(JsonIgnoreAttribute), true) || + attributes.IsDefined(typeof(JsonConverterAttribute), true)))); + } + + private static bool AllowsNull(JsonElement schema, JsonElement root) + { + if (!TryResolveSchema(ref schema, ref root)) + { + return false; + } + + if (schema.ValueKind is JsonValueKind.True or JsonValueKind.False) + { + return schema.ValueKind == JsonValueKind.True; + } + + if (HasComposition(schema) || schema.TryGetProperty("const", out JsonElement constant) && + constant.ValueKind != JsonValueKind.Null) + { + return false; + } + + bool typeAllowsNull = !schema.TryGetProperty("type", out JsonElement type) || + type.ValueKind == JsonValueKind.Array && type.EnumerateArray().Any(static value => value.ValueKind == JsonValueKind.String && value.ValueEquals("null")) || + type.ValueKind == JsonValueKind.String && type.ValueEquals("null"); + if (!typeAllowsNull) + { + return false; + } + + if (constant.ValueKind == JsonValueKind.Null) + { + return true; + } + + if (!schema.TryGetProperty("enum", out JsonElement enumValues)) + { + return true; + } + + return enumValues.ValueKind == JsonValueKind.Array && + enumValues.EnumerateArray().Any(static value => value.ValueKind == JsonValueKind.Null); + } + + private static bool TryResolveSchema(ref JsonElement schema, ref JsonElement root) + { + HashSet<(JsonElement Schema, JsonElement Root)>? visited = null; + while (true) + { + if (schema.ValueKind is JsonValueKind.True or JsonValueKind.False) + { + return true; + } + + if (schema.ValueKind != JsonValueKind.Object) + { + return false; + } + + if (schema.TryGetProperty("$id", out _)) + { + root = schema; + } + + if (!schema.TryGetProperty("$ref", out JsonElement reference)) + { + return true; + } + + foreach (JsonProperty property in schema.EnumerateObject()) + { + if (property.Name is not ("$ref" or "$id" or "description" or "title" or "default")) + { + return false; + } + } + + visited ??= []; + if (!visited.Add((schema, root)) || + reference.ValueKind != JsonValueKind.String || + !TryResolveReference(root, reference.GetString(), out schema)) + { + return false; + } + } + } + + private static bool HasComposition(JsonElement schema) => + schema.TryGetProperty("not", out _) || schema.TryGetProperty("allOf", out _) || + schema.TryGetProperty("anyOf", out _) || schema.TryGetProperty("oneOf", out _) || + schema.TryGetProperty("if", out _) || schema.TryGetProperty("dependentSchemas", out _) || + schema.TryGetProperty("patternProperties", out _) || schema.TryGetProperty("$dynamicRef", out _) || + schema.TryGetProperty("$recursiveRef", out _); + + private static bool TryResolveReference(JsonElement root, string? reference, out JsonElement resolved) + { + resolved = root; + if (reference is null) + { + return false; + } + + if (reference is "" or "#") + { + return true; + } + + if (!reference.StartsWith("#", StringComparison.Ordinal)) + { + return false; + } + + string pointer; + try + { + pointer = Uri.UnescapeDataString(reference.Substring(1)); + } + catch (UriFormatException) + { + return false; + } + + if (pointer.Length == 0) + { + return true; + } + + if (!pointer.StartsWith("/", StringComparison.Ordinal)) + { + return false; + } + + foreach (string part in pointer.Substring(1).Split('/')) + { + string name = part.Replace("~1", "/").Replace("~0", "~"); + if (resolved.ValueKind != JsonValueKind.Object || !resolved.TryGetProperty(name, out resolved)) + { + return false; + } + } + + return true; + } + + private enum PlanKind + { + None, + Object, + Array, + Dictionary, + } + + private enum WriteActionKind + { + Value, + Property, + EndObject, + EndArray, + NullProperty, + } + + private sealed class PlanNode + { + internal PlanKind Kind { get; set; } + internal bool HasRequiredNulls { get; set; } + internal List Properties { get; } = []; + internal Dictionary PropertiesByName { get; } = new(StringComparer.Ordinal); + internal PlanNode? Element { get; set; } + } + + private sealed record PropertyPlan(string Name, bool AddNullWhenMissing, PlanNode? Child); + private readonly record struct TraversalFrame(PlanNode Plan, JsonElement Value, int Depth); + private readonly record struct WriteAction( + WriteActionKind Kind, PlanNode? Plan, JsonElement Value, int Depth, string? PropertyName, JsonProperty Property); + private readonly record struct SerializedProperty(JsonElement Value, bool IsDuplicate); +} diff --git a/tests/ModelContextProtocol.AotCompatibility.TestApp/Program.cs b/tests/ModelContextProtocol.AotCompatibility.TestApp/Program.cs index 260bd3204..833cc0adf 100644 --- a/tests/ModelContextProtocol.AotCompatibility.TestApp/Program.cs +++ b/tests/ModelContextProtocol.AotCompatibility.TestApp/Program.cs @@ -1,4 +1,5 @@ using Microsoft.Extensions.DependencyInjection; +using ModelContextProtocol; using ModelContextProtocol.Client; using ModelContextProtocol.Extensions.Apps; using ModelContextProtocol.Extensions.Skills; @@ -6,7 +7,9 @@ using ModelContextProtocol.Server; using ModelContextProtocol.Tests.Utils; using System.IO.Pipelines; +using System.Text.Json; using System.Text.Json.Nodes; +using System.Text.Json.Serialization; Pipe clientToServerPipe = new(), serverToClientPipe = new(); const string FallbackUri = "skill://aot-fallback/SKILL.md"; @@ -24,6 +27,8 @@ var primitive = package.Skill; var services = new ServiceCollection(); var catalogTracker = new AotCatalogTracker(); +JsonSerializerOptions outputSerializerOptions = new(McpJsonUtilities.DefaultOptions); +outputSerializerOptions.TypeInfoResolverChain.Insert(0, AotJsonContext.Default); services.AddSingleton(catalogTracker); services.AddScoped(); services.AddMcpServer() @@ -33,6 +38,7 @@ [ new ForwardingAotTool(McpServerTool.Create(AotTools.Echo, new() { Name = "ForwardingEcho", UseStructuredContent = true })), new OverridingAotTool(McpServerTool.Create(AotTools.Echo, new() { Name = "OverridingEcho", UseStructuredContent = true })), + McpServerTool.Create(AotTools.CreateOrder, new() { Name = "RequiredNull", UseStructuredContent = true, SerializerOptions = outputSerializerOptions }), ]) .WithMcpApps() .WithSkillPackages([package]).WithSkills(options => @@ -105,6 +111,14 @@ } } +var requiredNullResult = await client.CallToolAsync("RequiredNull", new Dictionary()); +if (requiredNullResult.StructuredContent is not { } structured || + structured.GetProperty("note").ValueKind != JsonValueKind.Null || + structured.TryGetProperty("optional", out _)) +{ + throw new Exception("Required nullable output was not serialized as expected."); +} + // List, get, and verify a skill. var skills = await client.ListSkillsAsync(); if (skills.Count != 1 || skills[0].Name != "aot") @@ -167,8 +181,16 @@ internal sealed class AotTools [McpServerTool(Name = "Echo", UseStructuredContent = true)] [McpAppUi(ResourceUri = "ui://aot/echo")] public static string Echo(string arg) => $"Echo: {arg}"; + + public static AotOrder CreateOrder() => new("42", null); } +internal sealed record AotOrder(string Id, string? Note, string? Optional = null); + +[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase)] +[JsonSerializable(typeof(AotOrder))] +internal partial class AotJsonContext : JsonSerializerContext; + internal sealed class AotCatalogTracker { public int Created; diff --git a/tests/ModelContextProtocol.Tests/Server/DelegatingToolOutputSchemaTests.cs b/tests/ModelContextProtocol.Tests/Server/DelegatingToolOutputSchemaTests.cs index edd2d75df..fe15f4494 100644 --- a/tests/ModelContextProtocol.Tests/Server/DelegatingToolOutputSchemaTests.cs +++ b/tests/ModelContextProtocol.Tests/Server/DelegatingToolOutputSchemaTests.cs @@ -14,6 +14,61 @@ namespace ModelContextProtocol.Tests.Server; public partial class DelegatingToolOutputSchemaTests { + [Fact] + public async Task ListTools_DelegatingSchemaOverride_DoesNotRecoverAgainstInnerSchema() + { + JsonSerializerOptions serializerOptions = new(McpJsonUtilities.DefaultOptions) + { + TypeInfoResolver = new DefaultJsonTypeInfoResolver(), + }; + McpServerTool inner = McpServerTool.Create( + () => new DelegatingNullableOutput("42", null), + new() { Name = "optional_note", UseStructuredContent = true, SerializerOptions = serializerOptions }); + JsonElement outerSchema = ParseJson( + """{"type":"object","properties":{"id":{"type":"string"},"note":{"type":"string"}},"required":["id"]}"""); + JsonSchema validator = JsonSchema.FromText(outerSchema.GetRawText()); + McpServerTool tool = new SchemaOverrideTool(inner, outerSchema); + + await WithClientAsync(tool, "2026-07-28", async client => + { + var result = await client.CallToolAsync("optional_note", cancellationToken: TestContext.Current.CancellationToken); + + Assert.NotNull(result.StructuredContent); + Assert.False(result.StructuredContent.Value.TryGetProperty("note", out _)); + Assert.True(validator.Evaluate(result.StructuredContent.Value).IsValid); + }); + } + + [Theory] + [InlineData(1)] + [InlineData(2)] + public async Task ListTools_TransparentDelegatingTool_RecoversRequiredNullableMembers(int depth) + { + JsonSerializerOptions serializerOptions = new(McpJsonUtilities.DefaultOptions) + { + TypeInfoResolver = new DefaultJsonTypeInfoResolver(), + }; + McpServerTool inner = McpServerTool.Create( + () => new DelegatingNullableOutput("42", null), + new() { Name = "transparent_optional_note", UseStructuredContent = true, SerializerOptions = serializerOptions }); + McpServerTool tool = inner; + for (int i = 0; i < depth; i++) + { + tool = new DelegatingTool(tool); + } + + await WithClientAsync(tool, "2026-07-28", async client => + { + var result = await client.CallToolAsync("transparent_optional_note", cancellationToken: TestContext.Current.CancellationToken); + + Assert.NotNull(result.StructuredContent); + Assert.Equal(JsonValueKind.Null, result.StructuredContent.Value.GetProperty("note").ValueKind); + Assert.Equal("42", result.StructuredContent.Value.GetProperty("id").GetString()); + }); + } + + private sealed record DelegatingNullableOutput(string Id, string? Note); + [Theory] [InlineData("2025-06-18", 1, false)] [InlineData("2025-06-18", 2, false)] diff --git a/tests/ModelContextProtocol.Tests/Server/McpServerToolTests.cs b/tests/ModelContextProtocol.Tests/Server/McpServerToolTests.cs index c77151884..cec6245ae 100644 --- a/tests/ModelContextProtocol.Tests/Server/McpServerToolTests.cs +++ b/tests/ModelContextProtocol.Tests/Server/McpServerToolTests.cs @@ -3,6 +3,7 @@ using Microsoft.Extensions.DependencyInjection; using ModelContextProtocol.Protocol; using ModelContextProtocol.Server; +using ModelContextProtocol.Tests.Utils; using Moq; using System.ComponentModel; using System.Reflection; @@ -492,6 +493,1457 @@ public async Task SupportsSchemaCreateOptions() ); } + [Theory] + [InlineData("2025-11-25")] + [InlineData("2026-07-28")] + public async Task StructuredOutput_GeneratedSchema_PreservesRequiredNulls(string protocolVersion) + { + McpServerTool tool = McpServerTool.Create( + () => new ScopedOrder("42", null), + new() { UseStructuredContent = true, SerializerOptions = ScopedOutputSerializerOptions() }); + + CallToolResult result = await tool.InvokeAsync( + CreateRequestContextWithProtocolVersion(protocolVersion), TestContext.Current.CancellationToken); + + Assert.NotNull(result.StructuredContent); + Assert.Equal(JsonValueKind.Null, result.StructuredContent.Value.GetProperty("note").ValueKind); + Assert.False(result.StructuredContent.Value.TryGetProperty("optional", out _)); + Assert.DoesNotContain("\"note\"", Assert.IsType(result.Content[0]).Text); + AssertMatchesJsonSchema(tool.ProtocolTool.OutputSchema!.Value, result.StructuredContent); + } + + [Fact] + public async Task StructuredOutput_DefaultOptions_PreservesRequiredNulls() + { + JsonSerializerOptions options = new(McpJsonUtilities.DefaultOptions); + if (!JsonSerializer.IsReflectionEnabledByDefault) + { + options.TypeInfoResolverChain.Insert(0, JsonContext2.Default); + } + + McpServerTool tool = McpServerTool.Create( + () => new ScopedOrder("42", null), + new() { UseStructuredContent = true, SerializerOptions = options }); + + CallToolResult result = await tool.InvokeAsync( + CreateRequestContextWithProtocolVersion(Sep2106ProtocolVersion), TestContext.Current.CancellationToken); + + Assert.NotNull(result.StructuredContent); + Assert.Equal(JsonValueKind.Null, result.StructuredContent.Value.GetProperty("note").ValueKind); + AssertMatchesJsonSchema(tool.ProtocolTool.OutputSchema!.Value, result.StructuredContent); + } + + [Fact] + public async Task StructuredOutput_GeneratedSchema_PreservesNullsAlongsideEmptyObject() + { + McpServerTool tool = McpServerTool.Create( + () => new ScopedWithEmpty("42", null, new()), + new() { UseStructuredContent = true, SerializerOptions = ScopedOutputSerializerOptions() }); + + CallToolResult result = await tool.InvokeAsync( + CreateRequestContextWithProtocolVersion(Sep2106ProtocolVersion), TestContext.Current.CancellationToken); + + Assert.NotNull(result.StructuredContent); + Assert.Equal(JsonValueKind.Null, result.StructuredContent.Value.GetProperty("note").ValueKind); + Assert.Equal(JsonValueKind.Object, result.StructuredContent.Value.GetProperty("extra").ValueKind); + AssertMatchesJsonSchema(tool.ProtocolTool.OutputSchema!.Value, result.StructuredContent); + } + + [Fact] + public async Task StructuredOutput_GeneratedSchema_PreservesRecursiveRequiredNulls() + { + McpServerTool tool = McpServerTool.Create( + () => new ScopedRecursive("42", null, null), + new() { UseStructuredContent = true, SerializerOptions = ScopedOutputSerializerOptions() }); + + CallToolResult result = await tool.InvokeAsync( + CreateRequestContextWithProtocolVersion(Sep2106ProtocolVersion), TestContext.Current.CancellationToken); + + Assert.NotNull(result.StructuredContent); + Assert.Equal(JsonValueKind.Null, result.StructuredContent.Value.GetProperty("note").ValueKind); + Assert.Equal(JsonValueKind.Null, result.StructuredContent.Value.GetProperty("next").ValueKind); + AssertMatchesJsonSchema(tool.ProtocolTool.OutputSchema!.Value, result.StructuredContent); + } + + [Theory] + [InlineData("#")] + [InlineData("")] + public async Task StructuredOutput_GeneratedSchema_PreservesRequiredNullsForRootReference(string reference) + { + AIJsonSchemaCreateOptions schemaOptions = new() + { + TransformSchemaNode = (_, node) => + { + if (node is JsonObject obj && + obj["properties"] is JsonObject properties && + properties.ContainsKey("next")) + { + properties["next"] = new JsonObject { ["$ref"] = reference }; + } + + return node; + }, + }; + McpServerTool tool = McpServerTool.Create( + () => new ScopedRecursive("root", null, new ScopedRecursive("child", null, null)), + new() + { + UseStructuredContent = true, + SerializerOptions = ScopedOutputSerializerOptions(), + SchemaCreateOptions = schemaOptions, + }); + + CallToolResult result = await tool.InvokeAsync( + CreateRequestContextWithProtocolVersion(Sep2106ProtocolVersion), TestContext.Current.CancellationToken); + + Assert.NotNull(result.StructuredContent); + Assert.Equal(JsonValueKind.Null, result.StructuredContent.Value.GetProperty("note").ValueKind); + Assert.Equal(JsonValueKind.Null, result.StructuredContent.Value.GetProperty("next").GetProperty("note").ValueKind); + } + + [Fact] + public async Task StructuredOutput_GeneratedSchema_WithNoOpSchemaOptions_PreservesRequiredNulls() + { + McpServerTool tool = McpServerTool.Create( + () => new ScopedOrder("42", null), + new() + { + UseStructuredContent = true, + SerializerOptions = ScopedOutputSerializerOptions(), + SchemaCreateOptions = new AIJsonSchemaCreateOptions(), + }); + + CallToolResult result = await tool.InvokeAsync( + CreateRequestContextWithProtocolVersion(Sep2106ProtocolVersion), TestContext.Current.CancellationToken); + + Assert.NotNull(result.StructuredContent); + Assert.Equal(JsonValueKind.Null, result.StructuredContent.Value.GetProperty("note").ValueKind); + AssertMatchesJsonSchema(tool.ProtocolTool.OutputSchema!.Value, result.StructuredContent); + } + + [Fact] + public async Task StructuredOutput_GeneratedSchema_PreservesRequiredNullsForAsyncReturnTypes() + { + Func> task = static () => Task.FromResult(new ScopedOrder("42", null)); + McpServerTool taskTool = McpServerTool.Create( + task, + new() { UseStructuredContent = true, SerializerOptions = ScopedOutputSerializerOptions() }); + CallToolResult taskResult = await taskTool.InvokeAsync( + CreateRequestContextWithProtocolVersion(Sep2106ProtocolVersion), TestContext.Current.CancellationToken); + + Func> valueTask = static () => new(new ScopedOrder("43", null)); + McpServerTool valueTaskTool = McpServerTool.Create( + valueTask, + new() { UseStructuredContent = true, SerializerOptions = ScopedOutputSerializerOptions() }); + CallToolResult valueTaskResult = await valueTaskTool.InvokeAsync( + CreateRequestContextWithProtocolVersion(Sep2106ProtocolVersion), TestContext.Current.CancellationToken); + + Assert.NotNull(taskResult.StructuredContent); + Assert.Equal(JsonValueKind.Null, taskResult.StructuredContent.Value.GetProperty("note").ValueKind); + Assert.NotNull(valueTaskResult.StructuredContent); + Assert.Equal(JsonValueKind.Null, valueTaskResult.StructuredContent.Value.GetProperty("note").ValueKind); + AssertMatchesJsonSchema(taskTool.ProtocolTool.OutputSchema!.Value, taskResult.StructuredContent); + AssertMatchesJsonSchema(valueTaskTool.ProtocolTool.OutputSchema!.Value, valueTaskResult.StructuredContent); + } + + [Fact] + public async Task StructuredOutput_GeneratedSchema_PreservesNonNullValues() + { + McpServerTool tool = McpServerTool.Create( + () => new ScopedOrder("42", "hello"), + new() { UseStructuredContent = true, SerializerOptions = ScopedOutputSerializerOptions() }); + + CallToolResult result = await tool.InvokeAsync( + CreateRequestContextWithProtocolVersion(Sep2106ProtocolVersion), TestContext.Current.CancellationToken); + + Assert.NotNull(result.StructuredContent); + Assert.Equal("hello", result.StructuredContent.Value.GetProperty("note").GetString()); + Assert.False(result.StructuredContent.Value.TryGetProperty("optional", out _)); + AssertMatchesJsonSchema(tool.ProtocolTool.OutputSchema!.Value, result.StructuredContent); + } + + [Fact] + public async Task StructuredOutput_GeneratedSchema_PreservesNestedRequiredNulls() + { + McpServerTool tool = McpServerTool.Create( + () => new ScopedEnvelope(new ScopedParcel { Id = "42", Label = null }), + new() { UseStructuredContent = true, SerializerOptions = ScopedOutputSerializerOptions() }); + + CallToolResult result = await tool.InvokeAsync( + CreateRequestContextWithProtocolVersion(Sep2106ProtocolVersion), TestContext.Current.CancellationToken); + + Assert.NotNull(result.StructuredContent); + Assert.Equal(JsonValueKind.Null, result.StructuredContent.Value.GetProperty("parcel").GetProperty("label").ValueKind); + AssertMatchesJsonSchema(tool.ProtocolTool.OutputSchema!.Value, result.StructuredContent); + } + + [Fact] + public async Task StructuredOutput_GeneratedSchema_PreservesNestedAndSiblingRequiredNulls() + { + McpServerTool tool = McpServerTool.Create( + () => new ScopedMultipleNested( + null, + new ScopedParcel { Id = "first", Label = null }, + new ScopedParcel { Id = "second", Label = null }), + new() { UseStructuredContent = true, SerializerOptions = ScopedOutputSerializerOptions() }); + + CallToolResult result = await tool.InvokeAsync( + CreateRequestContextWithProtocolVersion(Sep2106ProtocolVersion), TestContext.Current.CancellationToken); + + Assert.NotNull(result.StructuredContent); + Assert.Equal(JsonValueKind.Null, result.StructuredContent.Value.GetProperty("note").ValueKind); + Assert.Equal(JsonValueKind.Null, result.StructuredContent.Value.GetProperty("first").GetProperty("label").ValueKind); + Assert.Equal(JsonValueKind.Null, result.StructuredContent.Value.GetProperty("second").GetProperty("label").ValueKind); + AssertMatchesJsonSchema(tool.ProtocolTool.OutputSchema!.Value, result.StructuredContent); + } + + [Fact] + public async Task StructuredOutput_GeneratedSchema_PreservesRequiredNullsInArrays() + { + McpServerTool tool = McpServerTool.Create( + () => new ScopedOrder[] { new("42", null) }, + new() { UseStructuredContent = true, SerializerOptions = ScopedOutputSerializerOptions() }); + + CallToolResult result = await tool.InvokeAsync( + CreateRequestContextWithProtocolVersion(Sep2106ProtocolVersion), TestContext.Current.CancellationToken); + + Assert.NotNull(result.StructuredContent); + Assert.Equal(JsonValueKind.Null, result.StructuredContent.Value[0].GetProperty("note").ValueKind); + AssertMatchesJsonSchema(tool.ProtocolTool.OutputSchema!.Value, result.StructuredContent); + } + + [Fact] + public async Task StructuredOutput_GeneratedSchema_PreservesRequiredNullsInDictionaries() + { + McpServerTool tool = McpServerTool.Create( + () => new Dictionary { ["first"] = new("42", null) }, + new() { UseStructuredContent = true, SerializerOptions = ScopedOutputSerializerOptions() }); + + CallToolResult result = await tool.InvokeAsync( + CreateRequestContextWithProtocolVersion(Sep2106ProtocolVersion), TestContext.Current.CancellationToken); + + Assert.NotNull(result.StructuredContent); + Assert.Equal(JsonValueKind.Null, result.StructuredContent.Value.GetProperty("first").GetProperty("note").ValueKind); + AssertMatchesJsonSchema(tool.ProtocolTool.OutputSchema!.Value, result.StructuredContent); + } + + [Fact] + public async Task StructuredOutput_ExplicitSchema_DoesNotChangeOmittedNulls() + { + using JsonDocument schema = JsonDocument.Parse("""{"type":"object","properties":{"note":{"type":"string"}}}"""); + McpServerTool tool = McpServerTool.Create( + () => new ScopedOrder("42", null), + new() { UseStructuredContent = true, OutputSchema = schema.RootElement.Clone(), SerializerOptions = ScopedOutputSerializerOptions() }); + + CallToolResult result = await tool.InvokeAsync( + CreateRequestContextWithProtocolVersion(Sep2106ProtocolVersion), TestContext.Current.CancellationToken); + + Assert.NotNull(result.StructuredContent); + Assert.False(result.StructuredContent.Value.TryGetProperty("note", out _)); + AssertMatchesJsonSchema(tool.ProtocolTool.OutputSchema!.Value, result.StructuredContent); + } + + [Fact] + public async Task StructuredOutput_SourceGeneratedMetadata_PreservesRequiredNulls() + { + JsonSerializerOptions options = new(McpJsonUtilities.DefaultOptions) { TypeInfoResolver = JsonContext2.Default }; + McpServerTool tool = McpServerTool.Create( + () => new ScopedOrder("42", null), + new() { UseStructuredContent = true, SerializerOptions = options }); + + CallToolResult result = await tool.InvokeAsync( + CreateRequestContextWithProtocolVersion(Sep2106ProtocolVersion), TestContext.Current.CancellationToken); + + Assert.NotNull(result.StructuredContent); + Assert.Equal(JsonValueKind.Null, result.StructuredContent.Value.GetProperty("note").ValueKind); + Assert.False(result.StructuredContent.Value.TryGetProperty("optional", out _)); + AssertMatchesJsonSchema(tool.ProtocolTool.OutputSchema!.Value, result.StructuredContent); + } + + [Fact] + public async Task StructuredOutput_ExplicitAIFunction_DoesNotChangeOmittedNulls() + { + AIFunction function = AIFunctionFactory.Create( + (Func)(() => new ScopedOrder("42", null)), + new AIFunctionFactoryOptions { SerializerOptions = ScopedOutputSerializerOptions() }); + McpServerTool tool = McpServerTool.Create(function, new() { UseStructuredContent = true }); + + CallToolResult result = await tool.InvokeAsync( + CreateRequestContextWithProtocolVersion(Sep2106ProtocolVersion), TestContext.Current.CancellationToken); + + Assert.NotNull(result.StructuredContent); + Assert.False(result.StructuredContent.Value.TryGetProperty("note", out _)); + } + + [Fact] + public async Task StructuredOutput_CustomTypeInfoResolver_DoesNotBreakSerialization() + { + JsonSerializerOptions options = new(McpJsonUtilities.DefaultOptions) { TypeInfoResolver = new ScopedStrictResolver() }; + McpServerTool tool = McpServerTool.Create( + () => new ScopedOrder("42", "not-null"), + new() { UseStructuredContent = true, SerializerOptions = options }); + + CallToolResult result = await tool.InvokeAsync( + CreateRequestContextWithProtocolVersion(Sep2106ProtocolVersion), TestContext.Current.CancellationToken); + + Assert.NotNull(result.StructuredContent); + Assert.Equal("not-null", result.StructuredContent.Value.GetProperty("note").GetString()); + } + + [Fact] + public async Task StructuredOutput_DefaultResolverModifier_IsNotWrapped() + { + DefaultJsonTypeInfoResolver resolver = new(); + resolver.Modifiers.Add(typeInfo => + { + if (typeInfo.Type == typeof(ScopedOrder) && !ReferenceEquals(typeInfo.Options.TypeInfoResolver, resolver)) + { + throw new InvalidOperationException("The configured resolver was replaced."); + } + }); + JsonSerializerOptions options = new(McpJsonUtilities.DefaultOptions) { TypeInfoResolver = resolver }; + McpServerTool tool = McpServerTool.Create( + () => new ScopedOrder("42", null), + new() { UseStructuredContent = true, SerializerOptions = options }); + + CallToolResult result = await tool.InvokeAsync( + CreateRequestContextWithProtocolVersion(Sep2106ProtocolVersion), TestContext.Current.CancellationToken); + + Assert.Null(result.IsError); + Assert.NotNull(result.StructuredContent); + Assert.Equal(JsonValueKind.Null, result.StructuredContent.Value.GetProperty("note").ValueKind); + } + + [Fact] + public async Task StructuredOutput_DefaultResolverSubclass_IsNotWrapped() + { + JsonSerializerOptions options = new(McpJsonUtilities.DefaultOptions) + { + TypeInfoResolver = new ScopedStrictDefaultResolver(), + }; + McpServerTool tool = McpServerTool.Create( + () => new ScopedOrder("42", null), + new() { UseStructuredContent = true, SerializerOptions = options }); + + CallToolResult result = await tool.InvokeAsync( + CreateRequestContextWithProtocolVersion(Sep2106ProtocolVersion), TestContext.Current.CancellationToken); + + Assert.Null(result.IsError); + Assert.NotNull(result.StructuredContent); + Assert.Equal(JsonValueKind.Null, result.StructuredContent.Value.GetProperty("note").ValueKind); + } + + [Fact] + public async Task StructuredOutput_RuntimeDerivedType_PreservesRequiredNulls() + { + McpServerTool tool = McpServerTool.Create( + (Func)(static () => new ScopedDerivedOrder { Id = "42", Note = null }), + new() { UseStructuredContent = true, SerializerOptions = ScopedOutputSerializerOptions() }); + + CallToolResult result = await tool.InvokeAsync( + CreateRequestContextWithProtocolVersion(Sep2106ProtocolVersion), TestContext.Current.CancellationToken); + + Assert.NotNull(result.StructuredContent); + Assert.Equal(JsonValueKind.Null, result.StructuredContent.Value.GetProperty("note").ValueKind); + AssertMatchesJsonSchema(tool.ProtocolTool.OutputSchema!.Value, result.StructuredContent); + } + + [Fact] + public async Task StructuredOutput_RuntimeDerivedType_UsesDerivedPlanWhenBasePlanIsUnavailable() + { + DefaultJsonTypeInfoResolver resolver = new(); + resolver.Modifiers.Add(typeInfo => + { + if (typeInfo.Type == typeof(ScopedBaseOrder)) + { + typeInfo.Properties.Single(property => property.Name == "note").ShouldSerialize = static (_, _) => false; + } + }); + JsonSerializerOptions options = new(McpJsonUtilities.DefaultOptions) { TypeInfoResolver = resolver }; + ScopedDerivedOrder value = new() { Id = "42", Note = "present" }; + JsonElement ordinary = JsonSerializer.SerializeToElement(value, options.GetTypeInfo(typeof(object))); + Assert.Equal("present", ordinary.GetProperty("note").GetString()); + value = new ScopedDerivedOrder { Id = "42", Note = null }; + + McpServerTool tool = McpServerTool.Create( + (Func)(() => value), + new() { UseStructuredContent = true, SerializerOptions = options }); + + CallToolResult result = await tool.InvokeAsync( + CreateRequestContextWithProtocolVersion(Sep2106ProtocolVersion), TestContext.Current.CancellationToken); + + Assert.NotNull(result.StructuredContent); + Assert.Equal(JsonValueKind.Null, result.StructuredContent.Value.GetProperty("note").ValueKind); + AssertMatchesJsonSchema(tool.ProtocolTool.OutputSchema!.Value, result.StructuredContent); + } + + [Fact] + public async Task StructuredOutput_RuntimeDerivedCustomBehavior_IsNotOverridden() + { + McpServerTool tool = McpServerTool.Create( + (Func)(static () => new ScopedDerivedEnvelope + { + Normal = new() { Id = "normal", Label = null }, + Arbitrary = new ScopedParcel { Id = "opaque", Label = null }, + Custom = new ScopedParcel { Id = "converter", Label = null }, + }), + new() { UseStructuredContent = true, SerializerOptions = ScopedOutputSerializerOptions() }); + + CallToolResult result = await tool.InvokeAsync( + CreateRequestContextWithProtocolVersion(Sep2106ProtocolVersion), TestContext.Current.CancellationToken); + + Assert.NotNull(result.StructuredContent); + Assert.Equal(JsonValueKind.Null, result.StructuredContent.Value.GetProperty("normal").GetProperty("label").ValueKind); + Assert.False(result.StructuredContent.Value.GetProperty("arbitrary").TryGetProperty("label", out _)); + Assert.Equal("omitted", result.StructuredContent.Value.GetProperty("custom").GetString()); + } + + [Fact] + public async Task StructuredOutput_RuntimeDerivedScalarConverter_DoesNotObservePatches() + { + McpServerTool tool = McpServerTool.Create( + (Func)(static () => new ScopedDerivedScalarConverter + { + Normal = new() { Id = "normal", Label = null }, + }), + new() { UseStructuredContent = true, SerializerOptions = ScopedOutputSerializerOptions() }); + + CallToolResult result = await tool.InvokeAsync( + CreateRequestContextWithProtocolVersion(Sep2106ProtocolVersion), TestContext.Current.CancellationToken); + + Assert.NotNull(result.StructuredContent); + Assert.Equal(JsonValueKind.Null, result.StructuredContent.Value.GetProperty("normal").GetProperty("label").ValueKind); + Assert.Equal("omitted", result.StructuredContent.Value.GetProperty("extra").GetString()); + } + + [Fact] + public async Task StructuredOutput_AlternatingRuntimeDerivedTypes_PreservesRequiredNulls() + { + int next = 0; + Func method = () => next++ % 2 == 0 + ? new ScopedDerivedOrder { Id = "42", Note = null } + : new ScopedOtherDerivedOrder { Id = "43", Note = null }; + McpServerTool tool = McpServerTool.Create( + method, + new() { UseStructuredContent = true, SerializerOptions = ScopedOutputSerializerOptions() }); + + for (int i = 0; i < 8; i++) + { + CallToolResult result = await tool.InvokeAsync( + CreateRequestContextWithProtocolVersion(Sep2106ProtocolVersion), TestContext.Current.CancellationToken); + + Assert.NotNull(result.StructuredContent); + Assert.Equal(JsonValueKind.Null, result.StructuredContent.Value.GetProperty("note").ValueKind); + } + } + + [Fact] + public async Task StructuredOutput_IgnoredOpaqueProperty_DoesNotDisableRecovery() + { + McpServerTool tool = McpServerTool.Create( + () => new ScopedIgnoredOpaque("42", null), + new() { UseStructuredContent = true, SerializerOptions = ScopedOutputSerializerOptions() }); + + CallToolResult result = await tool.InvokeAsync( + CreateRequestContextWithProtocolVersion(Sep2106ProtocolVersion), TestContext.Current.CancellationToken); + + Assert.NotNull(result.StructuredContent); + Assert.Equal(JsonValueKind.Null, result.StructuredContent.Value.GetProperty("note").ValueKind); + Assert.False(result.StructuredContent.Value.TryGetProperty("arbitrary", out _)); + } + + [Fact] + public async Task StructuredOutput_ExtensionData_RepairsSchemaMembersWithoutChangingExtensionValues() + { + McpServerTool tool = McpServerTool.Create( + () => new ScopedExtensionEnvelope + { + Normal = new() { Id = "normal", Label = null }, + Additional = new Dictionary + { + ["arbitrary"] = new ScopedParcel { Id = "opaque", Label = null }, + }, + }, + new() { UseStructuredContent = true, SerializerOptions = ScopedOutputSerializerOptions() }); + + CallToolResult result = await tool.InvokeAsync( + CreateRequestContextWithProtocolVersion(Sep2106ProtocolVersion), TestContext.Current.CancellationToken); + + Assert.NotNull(result.StructuredContent); + Assert.Equal(JsonValueKind.Null, result.StructuredContent.Value.GetProperty("normal").GetProperty("label").ValueKind); + Assert.False(result.StructuredContent.Value.GetProperty("arbitrary").TryGetProperty("label", out _)); + } + + [Fact] + public async Task StructuredOutput_NullableEnum_PreservesRequiredNull() + { + McpServerTool tool = McpServerTool.Create( + () => new ScopedEnumOrder(null), + new() { UseStructuredContent = true, SerializerOptions = ScopedOutputSerializerOptions() }); + + CallToolResult result = await tool.InvokeAsync( + CreateRequestContextWithProtocolVersion(Sep2106ProtocolVersion), TestContext.Current.CancellationToken); + + Assert.NotNull(result.StructuredContent); + Assert.Equal(JsonValueKind.Null, result.StructuredContent.Value.GetProperty("status").ValueKind); + AssertMatchesJsonSchema(tool.ProtocolTool.OutputSchema!.Value, result.StructuredContent); + } + + [Fact] + public async Task StructuredOutput_IgnoreReadOnlyFields_DoesNotIgnoreReadOnlyProperties() + { + JsonSerializerOptions options = ScopedOutputSerializerOptions(); + options.IgnoreReadOnlyFields = true; + McpServerTool tool = McpServerTool.Create( + () => new ScopedReadOnlyOrder(null), + new() { UseStructuredContent = true, SerializerOptions = options }); + + CallToolResult result = await tool.InvokeAsync( + CreateRequestContextWithProtocolVersion(Sep2106ProtocolVersion), TestContext.Current.CancellationToken); + + Assert.NotNull(result.StructuredContent); + Assert.Equal(JsonValueKind.Null, result.StructuredContent.Value.GetProperty("note").ValueKind); + } + + [Theory] + [InlineData("present", true, false, false)] + [InlineData(null, true, false, false)] + [InlineData(null, false, false, true)] + [InlineData("present", false, true, true)] + [InlineData(null, false, true, false)] + public async Task StructuredOutput_SourceGeneratedReadOnlyFieldWithoutMemberInfo_IsConservative( + string? note, bool ignoreFields, bool ignoreProperties, bool expectedProperty) + { + JsonSerializerOptions options = new(McpJsonUtilities.DefaultOptions) + { + TypeInfoResolver = ScopedReadOnlyFieldsContext.Default.WithAddedModifier(static typeInfo => + { + if (typeInfo.Type == typeof(ScopedReadOnlyScalarField)) + { + typeInfo.Properties.Single(p => p.Name == "note").AttributeProvider = null; + } + }), + IncludeFields = true, + IgnoreReadOnlyFields = ignoreFields, + IgnoreReadOnlyProperties = ignoreProperties, + }; + ScopedReadOnlyScalarField value = new(note); + McpServerTool tool = McpServerTool.Create( + () => value, + new() { UseStructuredContent = true, SerializerOptions = options }); + + JsonElement ordinary = JsonSerializer.SerializeToElement(value, options.GetTypeInfo(typeof(ScopedReadOnlyScalarField))); + Assert.Equal(!ignoreFields && note is not null, ordinary.TryGetProperty("note", out _)); + Assert.Null(options.GetTypeInfo(typeof(ScopedReadOnlyScalarField)).Properties.Single(p => p.Name == "note").AttributeProvider); + Assert.Contains(tool.ProtocolTool.OutputSchema!.Value.GetProperty("required").EnumerateArray(), + static item => item.ValueEquals("note")); + + CallToolResult result = await tool.InvokeAsync( + CreateRequestContextWithProtocolVersion(Sep2106ProtocolVersion), TestContext.Current.CancellationToken); + + Assert.NotNull(result.StructuredContent); + Assert.Equal(expectedProperty, result.StructuredContent.Value.TryGetProperty("note", out JsonElement actual)); + if (expectedProperty) + { + Assert.Equal(note is null ? JsonValueKind.Null : JsonValueKind.String, actual.ValueKind); + } + } + + [Fact] + public async Task StructuredOutput_SourceGeneratedReadOnlyCollectionWithoutMemberInfo_PreservesRequiredNull() + { + JsonSerializerOptions options = new(McpJsonUtilities.DefaultOptions) + { + TypeInfoResolver = ScopedReadOnlyFieldsContext.Default.WithAddedModifier(static typeInfo => + { + if (typeInfo.Type == typeof(ScopedReadOnlyCollectionField)) + { + typeInfo.Properties.Single(p => p.Name == "items").AttributeProvider = null; + } + }), + IncludeFields = true, + IgnoreReadOnlyFields = true, + IgnoreReadOnlyProperties = true, + }; + McpServerTool tool = McpServerTool.Create( + () => new ScopedReadOnlyCollectionField(null), + new() { UseStructuredContent = true, SerializerOptions = options }); + + CallToolResult result = await tool.InvokeAsync( + CreateRequestContextWithProtocolVersion(Sep2106ProtocolVersion), TestContext.Current.CancellationToken); + + Assert.NotNull(result.StructuredContent); + Assert.Equal(JsonValueKind.Null, result.StructuredContent.Value.GetProperty("items").ValueKind); + } + + [Fact] + public async Task StructuredOutput_IgnoreReadOnlyFields_PreservesRequiredNullCollection() + { + JsonSerializerOptions options = ScopedOutputSerializerOptions(); + options.IncludeFields = true; + options.IgnoreReadOnlyFields = true; + McpServerTool tool = McpServerTool.Create( + () => new ScopedReadOnlyCollectionField(null), + new() { UseStructuredContent = true, SerializerOptions = options }); + + CallToolResult result = await tool.InvokeAsync( + CreateRequestContextWithProtocolVersion(Sep2106ProtocolVersion), TestContext.Current.CancellationToken); + + Assert.NotNull(result.StructuredContent); + Assert.Equal(JsonValueKind.Null, result.StructuredContent.Value.GetProperty("items").ValueKind); + AssertMatchesJsonSchema(tool.ProtocolTool.OutputSchema!.Value, result.StructuredContent); + } + + [Fact] + public async Task StructuredOutput_IgnoreReadOnlyProperties_PreservesRequiredNullCollection() + { + JsonSerializerOptions options = ScopedOutputSerializerOptions(); + options.IgnoreReadOnlyProperties = true; + McpServerTool tool = McpServerTool.Create( + () => new ScopedReadOnlyCollection(null), + new() { UseStructuredContent = true, SerializerOptions = options }); + + CallToolResult result = await tool.InvokeAsync( + CreateRequestContextWithProtocolVersion(Sep2106ProtocolVersion), TestContext.Current.CancellationToken); + + Assert.NotNull(result.StructuredContent); + Assert.Equal(JsonValueKind.Null, result.StructuredContent.Value.GetProperty("items").ValueKind); + AssertMatchesJsonSchema(tool.ProtocolTool.OutputSchema!.Value, result.StructuredContent); + } + + [Fact] + public async Task StructuredOutput_RequiredNull_DoesNotReadGetterAgain() + { + ScopedCounting value = new() { Note = null }; + McpServerTool tool = McpServerTool.Create( + () => value, + new() { UseStructuredContent = true, SerializerOptions = ScopedOutputSerializerOptions() }); + + CallToolResult result = await tool.InvokeAsync( + CreateRequestContextWithProtocolVersion(Sep2106ProtocolVersion), TestContext.Current.CancellationToken); + + Assert.NotNull(result.StructuredContent); + Assert.Equal(JsonValueKind.Null, result.StructuredContent.Value.GetProperty("note").ValueKind); + Assert.Equal(2, value.Reads); + } + + [Fact] + public async Task StructuredOutput_KeepNulls_RespectsSerializerOptions() + { + JsonSerializerOptions options = ScopedOutputSerializerOptions(); + options.DefaultIgnoreCondition = JsonIgnoreCondition.Never; + McpServerTool tool = McpServerTool.Create( + () => new ScopedOrder("42", null), + new() { UseStructuredContent = true, SerializerOptions = options }); + + CallToolResult result = await tool.InvokeAsync( + CreateRequestContextWithProtocolVersion(Sep2106ProtocolVersion), TestContext.Current.CancellationToken); + + Assert.NotNull(result.StructuredContent); + Assert.Equal(JsonValueKind.Null, result.StructuredContent.Value.GetProperty("note").ValueKind); + Assert.Equal(JsonValueKind.Null, result.StructuredContent.Value.GetProperty("optional").ValueKind); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task StructuredOutput_ExplicitIgnoreAndConverter_AreNotOverridden(bool sourceGenerated) + { + JsonSerializerOptions options = sourceGenerated + ? new(McpJsonUtilities.DefaultOptions) { TypeInfoResolver = JsonContext2.Default } + : ScopedOutputSerializerOptions(); + McpServerTool tool = McpServerTool.Create( + () => new ScopedOverrides { Ignore = null, Converted = null, Change = null }, + new() { UseStructuredContent = true, SerializerOptions = options }); + + CallToolResult result = await tool.InvokeAsync( + CreateRequestContextWithProtocolVersion(Sep2106ProtocolVersion), TestContext.Current.CancellationToken); + + Assert.NotNull(result.StructuredContent); + Assert.Equal(JsonValueKind.Null, result.StructuredContent.Value.GetProperty("change").ValueKind); + Assert.False(result.StructuredContent.Value.TryGetProperty("ignore", out _)); + Assert.False(result.StructuredContent.Value.TryGetProperty("converted", out _)); + } + + [Fact] + public async Task StructuredOutput_RootObjectConverter_IsNotOverridden() + { + JsonSerializerOptions options = ScopedOutputSerializerOptions(); + options.Converters.Add(new ScopedObjectConverter()); + McpServerTool tool = McpServerTool.Create( + (Func)(static () => new ScopedDerivedOrder { Id = "42", Note = null }), + new() { UseStructuredContent = true, SerializerOptions = options }); + + CallToolResult result = await tool.InvokeAsync( + CreateRequestContextWithProtocolVersion(Sep2106ProtocolVersion), TestContext.Current.CancellationToken); + + Assert.NotNull(result.StructuredContent); + Assert.Equal("custom", result.StructuredContent.Value.GetProperty("id").GetString()); + Assert.False(result.StructuredContent.Value.TryGetProperty("note", out _)); + } + + [Fact] + public async Task StructuredOutput_RequiredNullsWithBooleanTrueSchemas_AreRestored() + { + McpServerTool tool = McpServerTool.Create( + () => new ScopedBooleanSchemaOutput(null, null, null), + new() { UseStructuredContent = true, SerializerOptions = ScopedOutputSerializerOptions() }); + + JsonElement schema = tool.ProtocolTool.OutputSchema!.Value; + JsonElement properties = schema.GetProperty("properties"); + Assert.Equal(JsonValueKind.True, properties.GetProperty("arbitrary").ValueKind); + Assert.Equal(JsonValueKind.True, properties.GetProperty("element").ValueKind); + Assert.Equal(JsonValueKind.True, properties.GetProperty("node").ValueKind); + + CallToolResult result = await tool.InvokeAsync( + CreateRequestContextWithProtocolVersion(Sep2106ProtocolVersion), TestContext.Current.CancellationToken); + + Assert.NotNull(result.StructuredContent); + Assert.Equal(JsonValueKind.Null, result.StructuredContent.Value.GetProperty("arbitrary").ValueKind); + Assert.Equal(JsonValueKind.Null, result.StructuredContent.Value.GetProperty("element").ValueKind); + Assert.Equal(JsonValueKind.Null, result.StructuredContent.Value.GetProperty("node").ValueKind); + } + + [Fact] + public async Task StructuredOutput_ExtensionDataDuplicateProperties_ArePreservedWhileRepairing() + { + using JsonDocument extensionValue = JsonDocument.Parse("\"extension\""); + McpServerTool tool = McpServerTool.Create( + () => new ScopedDuplicateExtension + { + Id = "model", + Note = null, + Additional = new Dictionary { ["id"] = extensionValue.RootElement.Clone() }, + }, + new() { UseStructuredContent = true, SerializerOptions = ScopedOutputSerializerOptions() }); + + CallToolResult result = await tool.InvokeAsync( + CreateRequestContextWithProtocolVersion(Sep2106ProtocolVersion), TestContext.Current.CancellationToken); + + Assert.NotNull(result.StructuredContent); + Assert.Equal(2, result.StructuredContent.Value.EnumerateObject().Count(static property => property.Name == "id")); + Assert.Equal(JsonValueKind.Null, result.StructuredContent.Value.GetProperty("note").ValueKind); + } + + [Fact] + public async Task StructuredOutput_UsesConfiguredMaxDepthWhenRepairing() + { + JsonSerializerOptions options = ScopedOutputSerializerOptions(); + options.MaxDepth = 128; + object deepValue = "leaf"; + for (int i = 0; i < 70; i++) + { + deepValue = new object?[] { deepValue }; + } + + McpServerTool tool = McpServerTool.Create( + () => new ScopedDeepOutput(null, deepValue), + new() { UseStructuredContent = true, SerializerOptions = options }); + + CallToolResult result = await tool.InvokeAsync( + CreateRequestContextWithProtocolVersion(Sep2106ProtocolVersion), TestContext.Current.CancellationToken); + + Assert.NotNull(result.StructuredContent); + Assert.Equal(JsonValueKind.Null, result.StructuredContent.Value.GetProperty("note").ValueKind); + JsonElement nested = result.StructuredContent.Value.GetProperty("deep"); + for (int i = 0; i < 70; i++) + { + nested = nested[0]; + } + + Assert.Equal("leaf", nested.GetString()); + } + + [Fact] + public async Task StructuredOutput_RepairsRequiredNullsWithinSerializerDepth() + { + ScopedDeepRecursive value = new() { Note = null, Next = null }; + for (int i = 0; i < 40; i++) + { + value = new ScopedDeepRecursive { Note = "present", Next = value }; + } + + McpServerTool tool = McpServerTool.Create( + () => value, + new() { UseStructuredContent = true, SerializerOptions = ScopedOutputSerializerOptions() }); + + CallToolResult result = await tool.InvokeAsync( + CreateRequestContextWithProtocolVersion(Sep2106ProtocolVersion), TestContext.Current.CancellationToken); + + Assert.NotNull(result.StructuredContent); + JsonElement nested = result.StructuredContent.Value; + while (nested.TryGetProperty("next", out JsonElement next) && next.ValueKind == JsonValueKind.Object) + { + nested = next; + } + + Assert.Equal(JsonValueKind.Null, nested.GetProperty("note").ValueKind); + AssertMatchesJsonSchema(tool.ProtocolTool.OutputSchema!.Value, result.StructuredContent); + } + + [Fact] + public async Task StructuredOutput_DeepRecoveryDoesNotOverflowTheCallStack() + { + JsonSerializerOptions options = ScopedOutputSerializerOptions(); + options.MaxDepth = 4096; + + ScopedDeepRecursive nested = new() { Note = null, Next = null }; + for (int i = 0; i < 1100; i++) + { + nested = new ScopedDeepRecursive { Note = "present", Next = nested }; + } + + McpServerTool tool = McpServerTool.Create( + () => nested, + new() { UseStructuredContent = true, SerializerOptions = options }); + + CallToolResult result = await tool.InvokeAsync( + CreateRequestContextWithProtocolVersion(Sep2106ProtocolVersion), TestContext.Current.CancellationToken); + + Assert.NotNull(result.StructuredContent); + JsonElement current = result.StructuredContent.Value; + int depth = 0; + while (current.TryGetProperty("next", out JsonElement next) && next.ValueKind == JsonValueKind.Object) + { + current = next; + depth++; + } + + Assert.Equal(1100, depth); + Assert.Equal(JsonValueKind.Null, current.GetProperty("note").ValueKind); + Assert.Equal(JsonValueKind.Null, current.GetProperty("next").ValueKind); + } + + [Fact] + public async Task StructuredOutput_WideTypesDoNotExhaustRecoveryPlan() + { + const int precedingProperties = 1030; + DefaultJsonTypeInfoResolver resolver = new(); + resolver.Modifiers.Add(typeInfo => + { + if (typeInfo.Type != typeof(ScopedWideOutput)) + { + return; + } + + JsonPropertyInfo child = typeInfo.Properties.Single(property => property.Name == "child"); + typeInfo.Properties.Remove(child); + for (int i = 0; i < precedingProperties; i++) + { + JsonPropertyInfo property = typeInfo.CreateJsonPropertyInfo(typeof(string), $"p{i}"); + property.Get = static _ => "value"; + typeInfo.Properties.Add(property); + } + + typeInfo.Properties.Add(child); + }); + + JsonSerializerOptions options = ScopedOutputSerializerOptions(); + options.TypeInfoResolver = resolver; + McpServerTool tool = McpServerTool.Create( + () => new ScopedWideOutput { Child = new() { Note = null } }, + new() { UseStructuredContent = true, SerializerOptions = options }); + + CallToolResult result = await tool.InvokeAsync( + CreateRequestContextWithProtocolVersion(Sep2106ProtocolVersion), TestContext.Current.CancellationToken); + + Assert.NotNull(result.StructuredContent); + Assert.Equal(JsonValueKind.Null, result.StructuredContent.Value.GetProperty("child").GetProperty("note").ValueKind); + } + + [Fact] + public async Task StructuredOutput_EncodedLocalReferenceSeparatorPreservesRequiredNull() + { + AIJsonSchemaCreateOptions schemaOptions = new() + { + TransformSchemaNode = (_, node) => + { + if (node is JsonObject obj && + obj["properties"] is JsonObject properties && + properties.ContainsKey("note")) + { + properties["note"] = JsonNode.Parse("""{"$ref":"#%2F$defs%2Fvalue"}"""); + obj["$defs"] = JsonNode.Parse("""{"value":{"type":["string","null"]}}"""); + } + + return node; + }, + }; + McpServerTool tool = McpServerTool.Create( + () => new ScopedReferenceOutput(null), + new() { UseStructuredContent = true, SerializerOptions = ScopedOutputSerializerOptions(), SchemaCreateOptions = schemaOptions }); + + CallToolResult result = await tool.InvokeAsync( + CreateRequestContextWithProtocolVersion(Sep2106ProtocolVersion), TestContext.Current.CancellationToken); + + Assert.NotNull(result.StructuredContent); + Assert.Equal(JsonValueKind.Null, result.StructuredContent.Value.GetProperty("note").ValueKind); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task StructuredOutput_EncodedLocalReferenceUsesUriDecodedPointer(bool allowsNull) + { + AIJsonSchemaCreateOptions schemaOptions = new() + { + TransformSchemaNode = (_, node) => + { + if (node is JsonObject obj && + obj["properties"] is JsonObject properties && + properties.ContainsKey("note")) + { + properties["note"] = JsonNode.Parse("""{"$ref":"#/$defs/a%2F$defs%2Fb"}"""); + obj["$defs"] = JsonNode.Parse(allowsNull + ? """{"a":{"$defs":{"b":{"type":["string","null"]}}},"a/$defs/b":{"type":"string"}}""" + : """{"a":{"$defs":{"b":{"type":"string"}}},"a/$defs/b":{"type":["string","null"]}}"""); + } + + return node; + }, + }; + McpServerTool tool = McpServerTool.Create( + () => new ScopedReferenceOutput(null), + new() + { + UseStructuredContent = true, + SerializerOptions = ScopedOutputSerializerOptions(), + SchemaCreateOptions = schemaOptions, + }); + + CallToolResult result = await tool.InvokeAsync( + CreateRequestContextWithProtocolVersion(Sep2106ProtocolVersion), TestContext.Current.CancellationToken); + + Assert.NotNull(result.StructuredContent); + Assert.Equal(allowsNull, result.StructuredContent.Value.TryGetProperty("note", out _)); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task StructuredOutput_ReferencesToBooleanSchemasDoNotDisableSiblingRecovery(bool allowsNull) + { + AIJsonSchemaCreateOptions schemaOptions = new() + { + TransformSchemaNode = (_, node) => + { + if (node is JsonObject obj && obj["properties"] is JsonObject properties && properties.ContainsKey("change")) + { + obj["$defs"] = new JsonObject { ["value"] = JsonValue.Create(allowsNull) }; + properties["note"] = new JsonObject { ["$ref"] = "#/$defs/value" }; + } + + return node; + }, + }; + McpServerTool tool = McpServerTool.Create( + () => new ScopedPredicate(null, null), + new() { UseStructuredContent = true, SerializerOptions = ScopedOutputSerializerOptions(), SchemaCreateOptions = schemaOptions }); + + CallToolResult result = await tool.InvokeAsync( + CreateRequestContextWithProtocolVersion(Sep2106ProtocolVersion), TestContext.Current.CancellationToken); + + Assert.NotNull(result.StructuredContent); + Assert.Equal(allowsNull, result.StructuredContent.Value.TryGetProperty("note", out _)); + Assert.Equal(JsonValueKind.Null, result.StructuredContent.Value.GetProperty("change").ValueKind); + } + + [Fact] + public async Task StructuredOutput_FollowsReferenceChainsForNestedRecovery() + { + AIJsonSchemaCreateOptions schemaOptions = new() + { + TransformSchemaNode = (_, node) => + { + if (node is JsonObject obj && obj["properties"] is JsonObject properties && properties["nested"] is { } nested) + { + JsonObject definitions = obj["$defs"] as JsonObject ?? new(); + definitions["alias"] = new JsonObject { ["$ref"] = "#/$defs/nestedSchema" }; + definitions["nestedSchema"] = nested.DeepClone(); + obj["$defs"] = definitions; + properties["nested"] = new JsonObject { ["$ref"] = "#/$defs/alias" }; + } + + return node; + }, + }; + McpServerTool tool = McpServerTool.Create( + () => new ScopedReferenceEnvelope(new ScopedReferenceOutput(null)), + new() { UseStructuredContent = true, SerializerOptions = ScopedOutputSerializerOptions(), SchemaCreateOptions = schemaOptions }); + + CallToolResult result = await tool.InvokeAsync( + CreateRequestContextWithProtocolVersion(Sep2106ProtocolVersion), TestContext.Current.CancellationToken); + + Assert.NotNull(result.StructuredContent); + Assert.Equal(JsonValueKind.Null, result.StructuredContent.Value.GetProperty("nested").GetProperty("note").ValueKind); + } + + [Theory] + [InlineData(false, 0)] + [InlineData(true, 0)] + [InlineData(false, 4096)] + [InlineData(true, 4096)] + public async Task StructuredOutput_LongReferenceChainDoesNotOverflowTheCallStack(bool cyclic, int maxDepth) + { + AIJsonSchemaCreateOptions schemaOptions = new() + { + TransformSchemaNode = (_, node) => + { + if (node is JsonObject obj && obj["properties"] is JsonObject properties && properties.ContainsKey("note")) + { + JsonObject definitions = []; + for (int i = 0; i < 600; i++) + { + definitions[$"r{i}"] = new JsonObject { ["$ref"] = $"#/$defs/r{i + 1}" }; + } + + definitions["r600"] = cyclic + ? new JsonObject { ["$ref"] = "#/$defs/r0" } + : JsonNode.Parse("""{"type":["string","null"]}"""); + obj["$defs"] = definitions; + properties["note"] = new JsonObject { ["$ref"] = "#/$defs/r0" }; + } + + return node; + }, + }; + JsonSerializerOptions options = ScopedOutputSerializerOptions(); + options.MaxDepth = maxDepth; + TaskCompletionSource created = new(TaskCreationOptions.RunContinuationsAsynchronously); + Thread thread = new(() => + { + try + { + created.SetResult(McpServerTool.Create( + () => new ScopedReferenceOutput(null), + new() { UseStructuredContent = true, SerializerOptions = options, SchemaCreateOptions = schemaOptions })); + } + catch (Exception exception) + { + created.SetException(exception); + } + }, 256 * 1024) + { IsBackground = true }; + thread.Start(); + + McpServerTool tool = await created.Task.WaitAsync(TestConstants.DefaultTimeout, TestContext.Current.CancellationToken); + CallToolResult result = await tool.InvokeAsync( + CreateRequestContextWithProtocolVersion(Sep2106ProtocolVersion), TestContext.Current.CancellationToken); + + Assert.NotNull(result.StructuredContent); + Assert.Equal(!cyclic, result.StructuredContent.Value.TryGetProperty("note", out JsonElement note)); + if (!cyclic) + { + Assert.Equal(JsonValueKind.Null, note.ValueKind); + } + } + + [Fact] + public async Task StructuredOutput_DeepReferencePlanDoesNotOverflowTheCallStack() + { + AIJsonSchemaCreateOptions schemaOptions = new() + { + TransformSchemaNode = (_, node) => + { + if (node is JsonObject obj && obj["properties"] is JsonObject properties && properties.ContainsKey("next")) + { + JsonObject definitions = []; + for (int i = 0; i < 600; i++) + { + definitions[$"r{i}"] = new JsonObject + { + ["type"] = new JsonArray("object", "null"), + ["properties"] = new JsonObject + { + ["note"] = new JsonObject { ["type"] = new JsonArray("string", "null") }, + ["next"] = new JsonObject { ["$ref"] = $"#/$defs/r{i + 1}" }, + }, + ["required"] = new JsonArray("note", "next"), + }; + } + + definitions["r600"] = new JsonObject + { + ["type"] = new JsonArray("object", "null"), + ["properties"] = new JsonObject + { + ["note"] = new JsonObject { ["type"] = new JsonArray("string", "null") }, + }, + ["required"] = new JsonArray("note"), + }; + obj["$defs"] = definitions; + properties["next"] = new JsonObject { ["$ref"] = "#/$defs/r0" }; + } + + return node; + }, + }; + JsonSerializerOptions options = ScopedOutputSerializerOptions(); + options.MaxDepth = 4096; + TaskCompletionSource created = new(TaskCreationOptions.RunContinuationsAsynchronously); + Thread thread = new(() => + { + try + { + created.SetResult(McpServerTool.Create( + () => new ScopedDeepRecursive { Note = null, Next = null }, + new() { UseStructuredContent = true, SerializerOptions = options, SchemaCreateOptions = schemaOptions })); + } + catch (Exception exception) + { + created.SetException(exception); + } + }, 256 * 1024) + { IsBackground = true }; + thread.Start(); + + McpServerTool tool = await created.Task.WaitAsync(TestConstants.DefaultTimeout, TestContext.Current.CancellationToken); + CallToolResult result = await tool.InvokeAsync( + CreateRequestContextWithProtocolVersion(Sep2106ProtocolVersion), TestContext.Current.CancellationToken); + + Assert.NotNull(result.StructuredContent); + Assert.Equal(JsonValueKind.Null, result.StructuredContent.Value.GetProperty("note").ValueKind); + Assert.Equal(JsonValueKind.Null, result.StructuredContent.Value.GetProperty("next").ValueKind); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task StructuredOutput_EmbeddedLocalReferenceUsesItsResourceScope(bool allowsNull) + { + AIJsonSchemaCreateOptions schemaOptions = new() + { + TransformSchemaNode = (_, node) => + { + if (node is JsonObject obj && obj["properties"] is JsonObject properties) + { + if (properties.ContainsKey("note")) + { + obj["$id"] = allowsNull ? "https://example.test/inner-nullable" : "https://example.test/inner-nonnullable"; + obj["$defs"] = JsonNode.Parse(allowsNull + ? """{"x":{"type":["string","null"]}}""" + : """{"x":{"type":"string"}}"""); + properties["note"] = JsonNode.Parse("""{"$ref":"#/$defs/x"}"""); + } + else if (properties.ContainsKey("nested")) + { + obj["$defs"] = JsonNode.Parse(allowsNull + ? """{"x":{"type":"string"}}""" + : """{"x":{"type":["string","null"]}}"""); + } + } + + return node; + }, + }; + McpServerTool tool = McpServerTool.Create( + () => new ScopedReferenceEnvelope(new ScopedReferenceOutput(null)), + new() + { + UseStructuredContent = true, + SerializerOptions = ScopedOutputSerializerOptions(), + SchemaCreateOptions = schemaOptions, + }); + + CallToolResult result = await tool.InvokeAsync( + CreateRequestContextWithProtocolVersion(Sep2106ProtocolVersion), TestContext.Current.CancellationToken); + + Assert.NotNull(result.StructuredContent); + Assert.Equal(allowsNull, result.StructuredContent.Value.GetProperty("nested").TryGetProperty("note", out _)); + } + + [Fact] + public async Task StructuredOutput_NullableTypeConverterIsNotTraversed() + { + JsonSerializerOptions options = ScopedOutputSerializerOptions(); + options.Converters.Add(new ScopedNullableStructConverter()); + AIJsonSchemaCreateOptions schemaOptions = new() + { + TransformSchemaNode = (_, node) => + { + if (node is JsonObject obj && obj["properties"] is JsonObject properties && properties.ContainsKey("item")) + { + properties["item"] = JsonNode.Parse( + """{"type":["object","null"],"properties":{"note":{"type":["string","null"]}},"required":["note"]}"""); + } + + return node; + }, + }; + McpServerTool tool = McpServerTool.Create( + () => new ScopedNullableStructEnvelope(new ScopedNullableStruct { Note = "actual" }, null), + new() + { + UseStructuredContent = true, + SerializerOptions = options, + SchemaCreateOptions = schemaOptions, + }); + + CallToolResult result = await tool.InvokeAsync( + CreateRequestContextWithProtocolVersion(Sep2106ProtocolVersion), TestContext.Current.CancellationToken); + + Assert.NotNull(result.StructuredContent); + Assert.Equal("custom", result.StructuredContent.Value.GetProperty("item").GetProperty("id").GetString()); + Assert.False(result.StructuredContent.Value.GetProperty("item").TryGetProperty("note", out _)); + Assert.Equal(JsonValueKind.Null, result.StructuredContent.Value.GetProperty("marker").ValueKind); + } + + [Fact] + public async Task StructuredOutput_CustomConverterDoesNotObserveNullOverrides() + { + McpServerTool tool = McpServerTool.Create( + () => new ScopedConverterEnvelope(new ScopedParcel { Id = "normal", Label = null }, new ScopedParcel { Id = "custom", Label = null }), + new() { UseStructuredContent = true, SerializerOptions = ScopedOutputSerializerOptions() }); + + CallToolResult result = await tool.InvokeAsync( + CreateRequestContextWithProtocolVersion(Sep2106ProtocolVersion), TestContext.Current.CancellationToken); + + Assert.NotNull(result.StructuredContent); + Assert.Equal(JsonValueKind.Null, result.StructuredContent.Value.GetProperty("normal").GetProperty("label").ValueKind); + Assert.Equal("omitted", result.StructuredContent.Value.GetProperty("custom").GetString()); + } + + [Fact] + public async Task StructuredOutput_OpaqueObjectDoesNotObserveNullOverrides() + { + McpServerTool tool = McpServerTool.Create( + () => new ScopedOpaqueEnvelope(null, new ScopedOrder("42", null)), + new() { UseStructuredContent = true, SerializerOptions = ScopedOutputSerializerOptions() }); + + CallToolResult result = await tool.InvokeAsync( + CreateRequestContextWithProtocolVersion(Sep2106ProtocolVersion), TestContext.Current.CancellationToken); + + Assert.NotNull(result.StructuredContent); + Assert.Equal(JsonValueKind.Null, result.StructuredContent.Value.GetProperty("note").ValueKind); + Assert.False(result.StructuredContent.Value.GetProperty("arbitrary").TryGetProperty("note", out _)); + } + + [Fact] + public async Task StructuredOutput_CustomShouldSerialize_IsNotOverridden() + { + DefaultJsonTypeInfoResolver resolver = new(); + resolver.Modifiers.Add(typeInfo => + { + if (typeInfo.Type == typeof(ScopedPredicate)) + { + typeInfo.Properties.Single(p => p.Name == "note").ShouldSerialize = static (_, _) => false; + } + }); + JsonSerializerOptions options = new(McpJsonUtilities.DefaultOptions) { TypeInfoResolver = resolver }; + McpServerTool tool = McpServerTool.Create( + () => new ScopedPredicate(null, null), + new() { UseStructuredContent = true, SerializerOptions = options }); + + CallToolResult result = await tool.InvokeAsync( + CreateRequestContextWithProtocolVersion(Sep2106ProtocolVersion), TestContext.Current.CancellationToken); + + Assert.NotNull(result.StructuredContent); + Assert.Equal(JsonValueKind.Null, result.StructuredContent.Value.GetProperty("change").ValueKind); + Assert.False(result.StructuredContent.Value.TryGetProperty("note", out _)); + } + + private static JsonSerializerOptions ScopedOutputSerializerOptions() => + new(McpJsonUtilities.DefaultOptions) { TypeInfoResolver = new DefaultJsonTypeInfoResolver() }; + + private sealed record ScopedOrder(string Id, string? Note, string? Optional = null); + private class ScopedBaseOrder + { + public required string Id { get; init; } + public required string? Note { get; init; } + } + private sealed class ScopedDerivedOrder : ScopedBaseOrder; + private sealed class ScopedOtherDerivedOrder : ScopedBaseOrder; + private class ScopedBaseEnvelope + { + public required ScopedParcel Normal { get; init; } + } + private sealed class ScopedDerivedEnvelope : ScopedBaseEnvelope + { + public required object Arbitrary { get; init; } + + [JsonConverter(typeof(ScopedNestedConverter))] + public required ScopedParcel Custom { get; init; } + } + private sealed class ScopedDerivedScalarConverter : ScopedBaseEnvelope + { + [JsonConverter(typeof(ScopedReentrantStringConverter))] + public string Extra { get; init; } = "value"; + } + private sealed class ScopedIgnoredOpaque(string id, string? note) + { + public string Id { get; } = id; + public string? Note { get; } = note; + + [JsonIgnore] + public object? Arbitrary => null; + } + private sealed class ScopedExtensionEnvelope + { + public required ScopedParcel Normal { get; init; } + + [JsonExtensionData] + public Dictionary? Additional { get; init; } + } + private sealed record ScopedEnumOrder(ScopedStatus? Status); + private enum ScopedStatus { Pending, Completed } + private sealed class ScopedReadOnlyOrder(string? note) + { + public string? Note { get; } = note; + } + private sealed class ScopedReadOnlyCollection(List? items) + { + public List? Items { get; } = items; + } + private sealed record ScopedConverterEnvelope(ScopedParcel Normal, [property: JsonConverter(typeof(ScopedNestedConverter))] ScopedParcel Custom); + private sealed record ScopedOpaqueEnvelope(string? Note, object Arbitrary); + private sealed record ScopedWithEmpty(string Id, string? Note, ScopedEmpty Extra); + private sealed class ScopedEmpty; + private sealed record ScopedRecursive(string Id, string? Note, ScopedRecursive? Next); + private sealed record ScopedPredicate(string? Note, string? Change); + private sealed record ScopedEnvelope(ScopedParcel Parcel); + private sealed record ScopedMultipleNested(string? Note, ScopedParcel First, ScopedParcel Second); + private sealed class ScopedDuplicateExtension + { + public required string Id { get; init; } + public required string? Note { get; init; } + [JsonExtensionData] + public Dictionary Additional { get; init; } = []; + } + private sealed record ScopedDeepOutput(string? Note, object Deep); + private sealed record ScopedBooleanSchemaOutput(object? Arbitrary, JsonElement? Element, JsonNode? Node); + private sealed class ScopedWideOutput + { + public ScopedWideChild? Child { get; set; } + } + private sealed class ScopedWideChild + { + public required string? Note { get; set; } + } + private sealed record ScopedReferenceOutput(string? Note); + private sealed record ScopedReferenceEnvelope(ScopedReferenceOutput Nested); + private sealed record ScopedNullableStructEnvelope(ScopedNullableStruct? Item, string? Marker); + private struct ScopedNullableStruct + { + public string? Note { get; init; } + } + private sealed class ScopedDeepRecursive + { + public required string? Note { get; init; } + public required ScopedDeepRecursive? Next { get; init; } + } + private sealed class ScopedReadOnlyCollectionField(List? items) + { + public readonly List? Items = items; + } + private sealed class ScopedReadOnlyScalarField(string? note) + { + public readonly string? Note = note; + } + private sealed class ScopedCounting + { + [JsonIgnore] + public int Reads { get; private set; } + + public required string? Note + { + get { Reads++; return null; } + init { } + } + } + private sealed class ScopedParcel + { + public required string Id { get; init; } + public required string? Label { get; init; } + } + private sealed class ScopedOverrides + { + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public required string? Ignore { get; init; } + + [JsonConverter(typeof(ScopedNullConverter))] + public required string? Converted { get; init; } + + public required string? Change { get; init; } + } + private sealed class ScopedNullConverter : JsonConverter + { + public override bool HandleNull => true; + public override string? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) => throw new NotSupportedException(); + public override void Write(Utf8JsonWriter writer, string? value, JsonSerializerOptions options) => writer.WriteStringValue(value ?? "converted"); + } + private sealed class ScopedObjectConverter : JsonConverter + { + public override object? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) => + throw new NotSupportedException(); + + public override void Write(Utf8JsonWriter writer, object value, JsonSerializerOptions options) + { + writer.WriteStartObject(); + writer.WriteString("id", "custom"); + writer.WriteEndObject(); + } + } + private sealed class ScopedNullableStructConverter : JsonConverter + { + public override ScopedNullableStruct? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) => + throw new NotSupportedException(); + + public override void Write(Utf8JsonWriter writer, ScopedNullableStruct? value, JsonSerializerOptions options) + { + writer.WriteStartObject(); + writer.WriteString("id", "custom"); + writer.WriteEndObject(); + } + } + private sealed class ScopedNestedConverter : JsonConverter + { + public override ScopedParcel? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) => throw new NotSupportedException(); + + public override void Write(Utf8JsonWriter writer, ScopedParcel value, JsonSerializerOptions options) + { + JsonElement nested = JsonSerializer.SerializeToElement(value, options); + writer.WriteStringValue(nested.TryGetProperty("label", out _) ? "present" : "omitted"); + } + } + private sealed class ScopedReentrantStringConverter : JsonConverter + { + public override string? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) => + throw new NotSupportedException(); + + public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options) + { + JsonElement nested = JsonSerializer.SerializeToElement( + new ScopedParcel { Id = "converter", Label = null }, options); + writer.WriteStringValue(nested.TryGetProperty("label", out _) ? "present" : "omitted"); + } + } + private sealed class ScopedStrictResolver : IJsonTypeInfoResolver + { + private readonly DefaultJsonTypeInfoResolver _inner = new(); + + public JsonTypeInfo? GetTypeInfo(Type type, JsonSerializerOptions options) + { + if (!ReferenceEquals(options.TypeInfoResolver, this)) + { + throw new InvalidOperationException("The configured resolver was replaced."); + } + + return _inner.GetTypeInfo(type, options); + } + } + private sealed class ScopedStrictDefaultResolver : DefaultJsonTypeInfoResolver + { + public override JsonTypeInfo GetTypeInfo(Type type, JsonSerializerOptions options) + { + if (type == typeof(ScopedOrder) && !ReferenceEquals(options.TypeInfoResolver, this)) + { + throw new InvalidOperationException("The configured resolver was replaced."); + } + + return base.GetTypeInfo(type, options); + } + } + [Theory] [MemberData(nameof(StructuredOutput_ReturnsExpectedSchema_Inputs))] public async Task StructuredOutput_Enabled_ReturnsExpectedSchema(T value) @@ -1308,8 +2760,16 @@ public async Task EnablePollingAsync_ThrowsInvalidOperationException_WhenTranspo [JsonSerializable(typeof(DateTimeOffset?))] [JsonSerializable(typeof(Person))] [JsonSerializable(typeof(WeatherRequest))] + [JsonSerializable(typeof(ScopedOrder))] + [JsonSerializable(typeof(ScopedRecursive))] + [JsonSerializable(typeof(ScopedOverrides))] partial class JsonContext2 : JsonSerializerContext; + [JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase, IncludeFields = true)] + [JsonSerializable(typeof(ScopedReadOnlyScalarField))] + [JsonSerializable(typeof(ScopedReadOnlyCollectionField))] + partial class ScopedReadOnlyFieldsContext : JsonSerializerContext; + // ===== x-mcp-header tests ===== [Fact]