-
Notifications
You must be signed in to change notification settings - Fork 742
Expand file tree
/
Copy pathExperimentalJsonConverter.cs
More file actions
53 lines (46 loc) · 1.94 KB
/
Copy pathExperimentalJsonConverter.cs
File metadata and controls
53 lines (46 loc) · 1.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
using System.Diagnostics.CodeAnalysis;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.Json.Serialization.Metadata;
namespace ModelContextProtocol;
/// <summary>
/// A JSON converter that handles serialization of experimental MCP types through <c>object?</c> backing fields.
/// </summary>
/// <typeparam name="T">The experimental type to serialize/deserialize.</typeparam>
/// <remarks>
/// <para>
/// This converter is used on internal <c>object?</c> backing fields that shadow public experimental properties
/// marked with <see cref="ExperimentalAttribute"/>. By declaring the backing field
/// as <c>object?</c>, the System.Text.Json source generator does not walk the experimental type graph, preventing
/// MCPEXP diagnostics from being emitted in generated code in consuming projects.
/// </para>
/// <para>
/// Serialization delegates to <see cref="McpJsonUtilities.DefaultOptions"/>, which already contains source-generated
/// contracts for all experimental types.
/// </para>
/// </remarks>
internal sealed class ExperimentalJsonConverter<T> : JsonConverter<object?> where T : class
{
private static JsonTypeInfo<T> TypeInfo => (JsonTypeInfo<T>)McpJsonUtilities.DefaultOptions.GetTypeInfo(typeof(T));
public override object? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
if (reader.TokenType == JsonTokenType.Null)
{
return null;
}
return JsonSerializer.Deserialize(ref reader, TypeInfo);
}
public override void Write(Utf8JsonWriter writer, object? value, JsonSerializerOptions options)
{
if (value is null)
{
writer.WriteNullValue();
return;
}
if (value is not T typed)
{
throw new JsonException($"Expected value of type '{typeof(T).Name}' but got '{value.GetType().Name}'.");
}
JsonSerializer.Serialize(writer, typed, TypeInfo);
}
}