|
2 | 2 | using ModelContextProtocol.Protocol;
|
3 | 3 | using ModelContextProtocol.Server;
|
4 | 4 | using System.Diagnostics.CodeAnalysis;
|
| 5 | +using System.Reflection; |
5 | 6 | using System.Text.Json;
|
6 | 7 | using System.Text.Json.Serialization;
|
7 | 8 | using System.Text.Json.Serialization.Metadata;
|
@@ -34,16 +35,17 @@ public static partial class McpJsonUtilities
|
34 | 35 | /// Creates default options to use for MCP-related serialization.
|
35 | 36 | /// </summary>
|
36 | 37 | /// <returns>The configured options.</returns>
|
| 38 | + [UnconditionalSuppressMessage("ReflectionAnalysis", "IL3050:RequiresDynamicCode", Justification = "Converter is guarded by IsReflectionEnabledByDefault check.")] |
37 | 39 | private static JsonSerializerOptions CreateDefaultOptions()
|
38 | 40 | {
|
39 | 41 | // Copy the configuration from the source generated context.
|
40 | 42 | JsonSerializerOptions options = new(JsonContext.Default.Options);
|
41 | 43 |
|
42 | 44 | // Chain with all supported types and converters from MEAI
|
43 | 45 | options.TypeInfoResolverChain.Add(AIJsonUtilities.DefaultOptions.TypeInfoResolver!);
|
44 |
| - foreach (JsonConverter converter in AIJsonUtilities.DefaultOptions.Converters) |
| 46 | + if (JsonSerializer.IsReflectionEnabledByDefault) |
45 | 47 | {
|
46 |
| - options.Converters.Add(converter); |
| 48 | + options.Converters.Add(new UserDefinedJsonStringEnumConverter()); |
47 | 49 | }
|
48 | 50 |
|
49 | 51 | options.MakeReadOnly();
|
@@ -104,6 +106,18 @@ internal static bool IsValidMcpToolSchema(JsonElement element)
|
104 | 106 | return AIJsonUtilities.CreateJsonSchema(returnType, serializerOptions: function.JsonSerializerOptions, inferenceOptions: schemaCreateOptions);
|
105 | 107 | }
|
106 | 108 |
|
| 109 | + |
| 110 | + // Defines a JsonStringEnumConverter that only applies to enums outside of the current assembly. |
| 111 | + // This is to ensure that we're not overriding the CustomizableJsonStringEnumConverter that our |
| 112 | + // built-in enums are relying on. |
| 113 | + [RequiresDynamicCode("Depends on JsonStringEnumConverter which requires dynamic code.")] |
| 114 | + private sealed class UserDefinedJsonStringEnumConverter : JsonConverterFactory |
| 115 | + { |
| 116 | + private readonly JsonStringEnumConverter _converter = new(); |
| 117 | + public override bool CanConvert(Type typeToConvert) => _converter.CanConvert(typeToConvert) && typeToConvert.Assembly != Assembly.GetExecutingAssembly(); |
| 118 | + public override JsonConverter? CreateConverter(Type typeToConvert, JsonSerializerOptions options) => _converter.CreateConverter(typeToConvert, options); |
| 119 | + } |
| 120 | + |
107 | 121 | // Keep in sync with CreateDefaultOptions above.
|
108 | 122 | [JsonSourceGenerationOptions(JsonSerializerDefaults.Web,
|
109 | 123 | DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
|
|
0 commit comments