Skip to content

Commit e1a2564

Browse files
authored
Fix NotSupportedException when returning IEnumerable<ContentBlock> (modelcontextprotocol#675)
1 parent 5e5b1af commit e1a2564

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

src/ModelContextProtocol.Core/McpJsonUtilities.cs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -146,6 +146,7 @@ internal static bool IsValidMcpToolSchema(JsonElement element)
146146
[JsonSerializable(typeof(AudioContentBlock))]
147147
[JsonSerializable(typeof(EmbeddedResourceBlock))]
148148
[JsonSerializable(typeof(ResourceLinkBlock))]
149+
[JsonSerializable(typeof(IEnumerable<ContentBlock>))]
149150
[JsonSerializable(typeof(PromptReference))]
150151
[JsonSerializable(typeof(ResourceTemplateReference))]
151152
[JsonSerializable(typeof(BlobResourceContents))]

tests/ModelContextProtocol.Tests/McpJsonUtilitiesTests.cs

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

56
namespace ModelContextProtocol.Tests;
67

@@ -43,6 +44,38 @@ public static void DefaultOptions_UnknownEnumHandling()
4344
}
4445
}
4546

47+
[Fact]
48+
public static void DefaultOptions_CanSerializeIEnumerableOfContentBlock()
49+
{
50+
var options = McpJsonUtilities.DefaultOptions;
51+
52+
// Create an IEnumerable<ContentBlock> with different content types
53+
IEnumerable<ContentBlock> contentBlocks = new List<ContentBlock>
54+
{
55+
new TextContentBlock { Text = "Hello World" },
56+
new TextContentBlock { Text = "Test message" }
57+
};
58+
59+
// Should not throw NotSupportedException
60+
string json = JsonSerializer.Serialize(contentBlocks, options);
61+
62+
Assert.NotNull(json);
63+
Assert.Contains("Hello World", json);
64+
Assert.Contains("Test message", json);
65+
Assert.Contains("\"type\":\"text\"", json);
66+
67+
// Should also be able to deserialize back
68+
var deserialized = JsonSerializer.Deserialize<IEnumerable<ContentBlock>>(json, options);
69+
Assert.NotNull(deserialized);
70+
var deserializedList = deserialized.ToList();
71+
Assert.Equal(2, deserializedList.Count);
72+
Assert.All(deserializedList, cb => Assert.Equal("text", cb.Type));
73+
74+
var textBlocks = deserializedList.Cast<TextContentBlock>().ToArray();
75+
Assert.Equal("Hello World", textBlocks[0].Text);
76+
Assert.Equal("Test message", textBlocks[1].Text);
77+
}
78+
4679
public enum EnumWithoutAnnotation { A = 1, B = 2, C = 3 }
4780

4881
[JsonConverter(typeof(JsonStringEnumConverter<EnumWithAnnotation>))]

0 commit comments

Comments
 (0)