Skip to content

Commit 852ba0f

Browse files
Use an explicit reflection-based converter for enums.
1 parent 15c50aa commit 852ba0f

File tree

1 file changed

+16
-2
lines changed

1 file changed

+16
-2
lines changed

src/ModelContextProtocol.Core/McpJsonUtilities.cs

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
using Microsoft.Extensions.AI;
22
using ModelContextProtocol.Protocol;
33
using System.Diagnostics.CodeAnalysis;
4+
using System.Reflection;
45
using System.Text.Json;
56
using System.Text.Json.Serialization;
67
using System.Text.Json.Serialization.Metadata;
@@ -33,16 +34,17 @@ public static partial class McpJsonUtilities
3334
/// Creates default options to use for MCP-related serialization.
3435
/// </summary>
3536
/// <returns>The configured options.</returns>
37+
[UnconditionalSuppressMessage("ReflectionAnalysis", "IL3050:RequiresDynamicCode", Justification = "Converter is guarded by IsReflectionEnabledByDefault check.")]
3638
private static JsonSerializerOptions CreateDefaultOptions()
3739
{
3840
// Copy the configuration from the source generated context.
3941
JsonSerializerOptions options = new(JsonContext.Default.Options);
4042

4143
// Chain with all supported types and converters from MEAI
4244
options.TypeInfoResolverChain.Add(AIJsonUtilities.DefaultOptions.TypeInfoResolver!);
43-
foreach (JsonConverter converter in AIJsonUtilities.DefaultOptions.Converters)
45+
if (JsonSerializer.IsReflectionEnabledByDefault)
4446
{
45-
options.Converters.Add(converter);
47+
options.Converters.Add(new UserDefinedJsonStringEnumConverter());
4648
}
4749

4850
options.MakeReadOnly();
@@ -79,6 +81,18 @@ internal static bool IsValidMcpToolSchema(JsonElement element)
7981
return false; // No type keyword found.
8082
}
8183

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+
8296
// Keep in sync with CreateDefaultOptions above.
8397
[JsonSourceGenerationOptions(JsonSerializerDefaults.Web,
8498
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,

0 commit comments

Comments
 (0)