Skip to content

Commit f7017ba

Browse files
committed
fix: preserve standalone content serialization contexts
Resolve nested content metadata through caller-first resolvers with an SDK-generated fallback, preserving caller settings and mutable direct-converter reads. Add standalone-context, nested collection, caller-contract precedence, and mutable-options regression coverage. AI assistance was used to prepare this change and its tests. Signed-off-by: FenjuFu <[email protected]>
1 parent 0d92883 commit f7017ba

2 files changed

Lines changed: 157 additions & 2 deletions

File tree

‎src/ModelContextProtocol.Core/Protocol/ContentBlock.cs‎

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,12 @@
33
using System.ComponentModel;
44
using System.Diagnostics;
55
using System.Diagnostics.CodeAnalysis;
6+
using System.Runtime.CompilerServices;
67
using System.Runtime.InteropServices;
78
using System.Text.Json;
89
using System.Text.Json.Nodes;
910
using System.Text.Json.Serialization;
11+
using System.Text.Json.Serialization.Metadata;
1012

1113
namespace ModelContextProtocol.Protocol;
1214

@@ -76,6 +78,28 @@ private protected ContentBlock()
7678
[EditorBrowsable(EditorBrowsableState.Never)]
7779
public sealed class Converter : JsonConverter<ContentBlock>
7880
{
81+
private static readonly ConditionalWeakTable<JsonSerializerOptions, JsonSerializerOptions> s_nestedReadOptions = new();
82+
83+
private static JsonTypeInfo<T> GetNestedTypeInfo<T>(JsonSerializerOptions options)
84+
{
85+
// JsonSerializer freezes options, but direct converter callers may still change them.
86+
JsonSerializerOptions nestedOptions = options.IsReadOnly
87+
? s_nestedReadOptions.GetValue(options, CreateNestedReadOptions)
88+
: CreateNestedReadOptions(options);
89+
return nestedOptions.GetTypeInfo<T>();
90+
}
91+
92+
private static JsonSerializerOptions CreateNestedReadOptions(JsonSerializerOptions callerOptions)
93+
{
94+
// A caller context may register ContentBlock without discovering the types read by
95+
// this custom converter. Keep caller contracts first, then supply the SDK metadata
96+
// (including nested collection types) using the same settings and converters.
97+
JsonSerializerOptions nestedOptions = new(callerOptions);
98+
nestedOptions.TypeInfoResolverChain.Add(McpJsonUtilities.JsonContext.Default);
99+
nestedOptions.MakeReadOnly();
100+
return nestedOptions;
101+
}
102+
79103
/// <inheritdoc/>
80104
public override ContentBlock? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
81105
{
@@ -172,7 +196,7 @@ public sealed class Converter : JsonConverter<ContentBlock>
172196
icons = [];
173197
while (reader.Read() && reader.TokenType != JsonTokenType.EndArray)
174198
{
175-
icons.Add(JsonSerializer.Deserialize(ref reader, options.GetTypeInfo<Icon>()) ??
199+
icons.Add(JsonSerializer.Deserialize(ref reader, GetNestedTypeInfo<Icon>(options)) ??
176200
throw new JsonException("Unexpected null item in icons array."));
177201
}
178202
}
@@ -183,7 +207,7 @@ public sealed class Converter : JsonConverter<ContentBlock>
183207
break;
184208

185209
case "annotations":
186-
annotations = JsonSerializer.Deserialize(ref reader, options.GetTypeInfo<Annotations>());
210+
annotations = JsonSerializer.Deserialize(ref reader, GetNestedTypeInfo<Annotations>(options));
187211
break;
188212

189213
case "_meta":

‎tests/ModelContextProtocol.Tests/Protocol/ContentBlockTests.cs‎

Lines changed: 131 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,132 @@
11
using ModelContextProtocol.Protocol;
22
using System.Text;
33
using System.Text.Json;
4+
using System.Text.Json.Serialization;
5+
using System.Text.Json.Serialization.Metadata;
46

57
namespace ModelContextProtocol.Tests.Protocol;
68

79
public class ContentBlockTests
810
{
11+
[Fact]
12+
public void NestedContracts_DirectConverterReadsRespectMutableOptionsChanges()
13+
{
14+
var options = new JsonSerializerOptions(McpJsonUtilities.ProtocolOptions);
15+
16+
Assert.Null(Read().Annotations!.Priority);
17+
options.PropertyNameCaseInsensitive = true;
18+
Assert.Equal((float?)0.5, Read().Annotations!.Priority);
19+
Assert.False(options.IsReadOnly);
20+
21+
ContentBlock Read()
22+
{
23+
Utf8JsonReader reader = new("""{"type":"text","text":"ok","annotations":{"Priority":0.5}}"""u8);
24+
Assert.True(reader.Read());
25+
return Assert.IsType<TextContentBlock>(new ContentBlock.Converter().Read(ref reader, typeof(ContentBlock), options));
26+
}
27+
}
28+
29+
[Theory]
30+
[InlineData(false, false, false)]
31+
[InlineData(false, false, true)]
32+
[InlineData(false, true, false)]
33+
[InlineData(false, true, true)]
34+
[InlineData(true, false, false)]
35+
[InlineData(true, false, true)]
36+
[InlineData(true, true, false)]
37+
[InlineData(true, true, true)]
38+
public void StandaloneContext_NestedAnnotations_UsesCallerSettings(bool wrapped, bool caseInsensitive, bool alternateCasing)
39+
{
40+
var options = GetStandaloneOptions(wrapped, caseInsensitive);
41+
string priority = alternateCasing ? "Priority" : "priority";
42+
string audience = alternateCasing ? "Audience" : "audience";
43+
string json = """{"type":"text","text":"ok","annotations":{"PRIORITY":0.5,"AUDIENCE":["user","assistant"]}}"""
44+
.Replace("PRIORITY", priority).Replace("AUDIENCE", audience);
45+
46+
var block = ReadStandaloneBlock(json, wrapped, options);
47+
48+
Assert.NotNull(block.Annotations);
49+
if (alternateCasing && !caseInsensitive)
50+
{
51+
Assert.Null(block.Annotations.Priority);
52+
Assert.Null(block.Annotations.Audience);
53+
}
54+
else
55+
{
56+
Assert.Equal((float?)0.5, block.Annotations.Priority);
57+
Assert.Equal([Role.User, Role.Assistant], block.Annotations.Audience);
58+
}
59+
}
60+
61+
[Theory]
62+
[InlineData(false, false, false)]
63+
[InlineData(false, false, true)]
64+
[InlineData(false, true, false)]
65+
[InlineData(false, true, true)]
66+
[InlineData(true, false, false)]
67+
[InlineData(true, false, true)]
68+
[InlineData(true, true, false)]
69+
[InlineData(true, true, true)]
70+
public void StandaloneContext_NestedIcons_UsesCallerSettings(bool wrapped, bool caseInsensitive, bool alternateCasing)
71+
{
72+
var options = GetStandaloneOptions(wrapped, caseInsensitive);
73+
string source = alternateCasing ? "Src" : "src";
74+
string sizes = alternateCasing ? "Sizes" : "sizes";
75+
string json = """{"type":"resource_link","uri":"file:///test","name":"test","icons":[{"SOURCE":"https://example.com/icon.png","SIZES":["48x48"]}]}"""
76+
.Replace("SOURCE", source).Replace("SIZES", sizes);
77+
78+
if (alternateCasing && !caseInsensitive)
79+
{
80+
Assert.Throws<JsonException>(() => ReadStandaloneBlock(json, wrapped, options));
81+
return;
82+
}
83+
84+
var block = Assert.IsType<ResourceLinkBlock>(ReadStandaloneBlock(json, wrapped, options));
85+
var icon = Assert.Single(Assert.IsAssignableFrom<IList<Icon>>(block.Icons));
86+
Assert.Equal("https://example.com/icon.png", icon.Source);
87+
Assert.Equal(["48x48"], icon.Sizes);
88+
}
89+
90+
[Fact]
91+
public void StandaloneContext_PrefersCallerNestedContracts()
92+
{
93+
var options = GetStandaloneOptions(wrapped: false, caseInsensitive: false);
94+
options.TypeInfoResolver = JsonTypeInfoResolver.Combine(
95+
options.TypeInfoResolver!,
96+
CallerNestedContentJsonContext.Default.WithAddedModifier(typeInfo =>
97+
{
98+
foreach (var property in typeInfo.Properties)
99+
{
100+
if (typeInfo.Type == typeof(Icon) && property.Name == "src")
101+
{
102+
property.Name = "callerSource";
103+
}
104+
else if (typeInfo.Type == typeof(Annotations) && property.Name == "priority")
105+
{
106+
property.Name = "callerPriority";
107+
}
108+
}
109+
}));
110+
const string Json = """{"type":"resource_link","uri":"file:///test","name":"test","icons":[{"callerSource":"https://example.com/icon.png","sizes":["48x48"]}],"annotations":{"callerPriority":0.5,"audience":["user"]}}""";
111+
112+
var block = Assert.IsType<ResourceLinkBlock>(ReadStandaloneBlock(Json, wrapped: false, options));
113+
114+
Assert.Equal("https://example.com/icon.png", Assert.Single(block.Icons!).Source);
115+
Assert.Equal((float?)0.5, block.Annotations!.Priority);
116+
Assert.Equal([Role.User], block.Annotations.Audience);
117+
}
118+
119+
private static JsonSerializerOptions GetStandaloneOptions(bool wrapped, bool caseInsensitive) =>
120+
new(wrapped ? StandaloneCallToolContentJsonContext.Default.Options : StandaloneContentJsonContext.Default.Options)
121+
{
122+
PropertyNameCaseInsensitive = caseInsensitive,
123+
};
124+
125+
private static ContentBlock ReadStandaloneBlock(string json, bool wrapped, JsonSerializerOptions options) =>
126+
wrapped
127+
? Assert.Single(JsonSerializer.Deserialize<CallToolResult>("{\"content\":[" + json + "]}", options)!.Content)
128+
: Assert.IsAssignableFrom<ContentBlock>(JsonSerializer.Deserialize<ContentBlock>(json, options));
129+
9130
[Theory]
10131
[InlineData(0, false)]
11132
[InlineData(0, true)]
@@ -614,3 +735,13 @@ public void AudioContentBlock_FromBytes_LazilyEncodesData(byte[] originalBytes)
614735
Assert.Equal(expectedBase64, Encoding.UTF8.GetString(audio.Data.ToArray()));
615736
}
616737
}
738+
739+
[JsonSerializable(typeof(ContentBlock))]
740+
internal partial class StandaloneContentJsonContext : JsonSerializerContext;
741+
742+
[JsonSerializable(typeof(CallToolResult))]
743+
internal partial class StandaloneCallToolContentJsonContext : JsonSerializerContext;
744+
745+
[JsonSerializable(typeof(Icon))]
746+
[JsonSerializable(typeof(Annotations))]
747+
internal partial class CallerNestedContentJsonContext : JsonSerializerContext;

0 commit comments

Comments
 (0)