Skip to content

Commit 32f2549

Browse files
Add test for named user-defined types with source generation
- Added ToContentBlock_WithNamedUserDefinedTypeInAdditionalProperties_Works test - Test demonstrates that named types work with source generation regardless of reflection being enabled - Created TestCoordinates record and NamedTypeTestJsonContext for source generation support - Test passes on all frameworks including .NET 9 where reflection is disabled by default Co-authored-by: eiriktsarpalis <2813363+eiriktsarpalis@users.noreply.github.com>
1 parent bd598ea commit 32f2549

1 file changed

Lines changed: 51 additions & 1 deletion

File tree

tests/ModelContextProtocol.Tests/AIContentExtensionsTests.cs

Lines changed: 51 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
using Microsoft.Extensions.AI;
22
using ModelContextProtocol.Protocol;
33
using System.Text.Json;
4+
using System.Text.Json.Serialization;
45

56
namespace ModelContextProtocol.Tests;
67

@@ -337,4 +338,53 @@ public void ToContentBlock_WithCustomSerializerOptions_UsesProvidedOptions()
337338
var json = contentBlock.Meta.ToString();
338339
Assert.Contains("my_property", json.ToLowerInvariant());
339340
}
340-
}
341+
342+
[Fact]
343+
public void ToContentBlock_WithNamedUserDefinedTypeInAdditionalProperties_Works()
344+
{
345+
// This test should work regardless of reflection being enabled/disabled
346+
// because named types can be handled by source generators
347+
348+
// Create options with source generation support for the test type
349+
var options = new JsonSerializerOptions(McpJsonUtilities.DefaultOptions);
350+
options.TypeInfoResolverChain.Add(NamedTypeTestJsonContext.Default);
351+
352+
// Define a simple named type
353+
var testData = new TestCoordinates { X = 1.0, Y = 2.0 };
354+
355+
AIContent c = new()
356+
{
357+
AdditionalProperties = new()
358+
{
359+
["coordinates"] = testData
360+
}
361+
};
362+
363+
// Should not throw NotSupportedException
364+
var contentBlock = c.ToContentBlock(options);
365+
366+
Assert.NotNull(contentBlock);
367+
Assert.NotNull(contentBlock.Meta);
368+
Assert.True(contentBlock.Meta.ContainsKey("coordinates"));
369+
370+
// Verify the data was serialized correctly
371+
var coordinatesNode = contentBlock.Meta["coordinates"];
372+
Assert.NotNull(coordinatesNode);
373+
374+
var json = coordinatesNode.ToString();
375+
Assert.Contains("1", json);
376+
Assert.Contains("2", json);
377+
}
378+
}
379+
380+
// Test type for named user-defined type test
381+
internal record TestCoordinates
382+
{
383+
public double X { get; init; }
384+
public double Y { get; init; }
385+
}
386+
387+
// Source generation context for the test type
388+
[JsonSerializable(typeof(TestCoordinates))]
389+
[JsonSerializable(typeof(IReadOnlyDictionary<string, object>))]
390+
internal partial class NamedTypeTestJsonContext : JsonSerializerContext;

0 commit comments

Comments
 (0)