|
1 | 1 | using Microsoft.Extensions.AI; |
2 | 2 | using ModelContextProtocol.Protocol; |
3 | 3 | using System.Diagnostics.CodeAnalysis; |
| 4 | +using System.Reflection; |
4 | 5 | using System.Text.Json; |
5 | 6 | using System.Text.Json.Serialization; |
6 | 7 | using System.Text.Json.Serialization.Metadata; |
@@ -33,16 +34,17 @@ public static partial class McpJsonUtilities |
33 | 34 | /// Creates default options to use for MCP-related serialization. |
34 | 35 | /// </summary> |
35 | 36 | /// <returns>The configured options.</returns> |
| 37 | + [UnconditionalSuppressMessage("ReflectionAnalysis", "IL3050:RequiresDynamicCode", Justification = "Converter is guarded by IsReflectionEnabledByDefault check.")] |
36 | 38 | private static JsonSerializerOptions CreateDefaultOptions() |
37 | 39 | { |
38 | 40 | // Copy the configuration from the source generated context. |
39 | 41 | JsonSerializerOptions options = new(JsonContext.Default.Options); |
40 | 42 |
|
41 | 43 | // Chain with all supported types and converters from MEAI |
42 | 44 | options.TypeInfoResolverChain.Add(AIJsonUtilities.DefaultOptions.TypeInfoResolver!); |
43 | | - foreach (JsonConverter converter in AIJsonUtilities.DefaultOptions.Converters) |
| 45 | + if (JsonSerializer.IsReflectionEnabledByDefault) |
44 | 46 | { |
45 | | - options.Converters.Add(converter); |
| 47 | + options.Converters.Add(new UserDefinedJsonStringEnumConverter()); |
46 | 48 | } |
47 | 49 |
|
48 | 50 | options.MakeReadOnly(); |
@@ -79,6 +81,18 @@ internal static bool IsValidMcpToolSchema(JsonElement element) |
79 | 81 | return false; // No type keyword found. |
80 | 82 | } |
81 | 83 |
|
| 84 | + |
| 85 | + // Defines a JsonStringEnumConverter that only applies to enums outside of the current assembly. |
| 86 | + // This is to ensure that we're not overriding the CustomizableJsonStringEnumConverter that our |
| 87 | + // built-in enums are relying on. |
| 88 | + [RequiresDynamicCode("Depends on JsonStringEnumConverter which requires dynamic code.")] |
| 89 | + private sealed class UserDefinedJsonStringEnumConverter : JsonConverterFactory |
| 90 | + { |
| 91 | + private readonly JsonStringEnumConverter _converter = new(); |
| 92 | + public override bool CanConvert(Type typeToConvert) => _converter.CanConvert(typeToConvert) && typeToConvert.Assembly != Assembly.GetExecutingAssembly(); |
| 93 | + public override JsonConverter? CreateConverter(Type typeToConvert, JsonSerializerOptions options) => _converter.CreateConverter(typeToConvert, options); |
| 94 | + } |
| 95 | + |
82 | 96 | // Keep in sync with CreateDefaultOptions above. |
83 | 97 | [JsonSourceGenerationOptions(JsonSerializerDefaults.Web, |
84 | 98 | DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, |
|
0 commit comments