From e1a2564a4ea7cff538a2bec410879e709cb34958 Mon Sep 17 00:00:00 2001 From: Copilot <198982749+Copilot@users.noreply.github.com> Date: Tue, 5 Aug 2025 14:36:11 -0700 Subject: [PATCH] Fix NotSupportedException when returning IEnumerable (#675) --- .../McpJsonUtilities.cs | 1 + .../McpJsonUtilitiesTests.cs | 33 +++++++++++++++++++ 2 files changed, 34 insertions(+) diff --git a/src/ModelContextProtocol.Core/McpJsonUtilities.cs b/src/ModelContextProtocol.Core/McpJsonUtilities.cs index 21e2468..8bc9e21 100644 --- a/src/ModelContextProtocol.Core/McpJsonUtilities.cs +++ b/src/ModelContextProtocol.Core/McpJsonUtilities.cs @@ -146,6 +146,7 @@ public static partial class McpJsonUtilities [JsonSerializable(typeof(AudioContentBlock))] [JsonSerializable(typeof(EmbeddedResourceBlock))] [JsonSerializable(typeof(ResourceLinkBlock))] + [JsonSerializable(typeof(IEnumerable))] [JsonSerializable(typeof(PromptReference))] [JsonSerializable(typeof(ResourceTemplateReference))] [JsonSerializable(typeof(BlobResourceContents))] diff --git a/tests/ModelContextProtocol.Tests/McpJsonUtilitiesTests.cs b/tests/ModelContextProtocol.Tests/McpJsonUtilitiesTests.cs index e0af61e..cc55746 100644 --- a/tests/ModelContextProtocol.Tests/McpJsonUtilitiesTests.cs +++ b/tests/ModelContextProtocol.Tests/McpJsonUtilitiesTests.cs @@ -1,6 +1,7 @@ using System.Text.Json; using System.Text.Json.Serialization; using System.Text.Json.Serialization.Metadata; +using ModelContextProtocol.Protocol; namespace ModelContextProtocol.Tests; @@ -43,6 +44,38 @@ public static class McpJsonUtilitiesTests } } + [Fact] + public static void DefaultOptions_CanSerializeIEnumerableOfContentBlock() + { + var options = McpJsonUtilities.DefaultOptions; + + // Create an IEnumerable with different content types + IEnumerable contentBlocks = new List + { + new TextContentBlock { Text = "Hello World" }, + new TextContentBlock { Text = "Test message" } + }; + + // Should not throw NotSupportedException + string json = JsonSerializer.Serialize(contentBlocks, options); + + Assert.NotNull(json); + Assert.Contains("Hello World", json); + Assert.Contains("Test message", json); + Assert.Contains("\"type\":\"text\"", json); + + // Should also be able to deserialize back + var deserialized = JsonSerializer.Deserialize>(json, options); + Assert.NotNull(deserialized); + var deserializedList = deserialized.ToList(); + Assert.Equal(2, deserializedList.Count); + Assert.All(deserializedList, cb => Assert.Equal("text", cb.Type)); + + var textBlocks = deserializedList.Cast().ToArray(); + Assert.Equal("Hello World", textBlocks[0].Text); + Assert.Equal("Test message", textBlocks[1].Text); + } + public enum EnumWithoutAnnotation { A = 1, B = 2, C = 3 } [JsonConverter(typeof(JsonStringEnumConverter))]