Adding support for returning collections from tools (#116)

* Adding support for returning collections from tools

This will mean we can return multiple AIContent objects from a tool, such as a mixed text/image set

Contributes to #68

* Code review feedback

* Adding tests and some more cases

* More cases in switch and tests
This commit is contained in:
Aaron Powell 2025-03-27 15:25:25 +11:00 • committed by GitHub
commit 3c72c348d6
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -1,7 +1,9 @@
using Microsoft.Extensions.AI;
using ModelContextProtocol.Protocol.Types;
using ModelContextProtocol.Utils;
using ModelContextProtocol.Utils.Json;
using System.Runtime.InteropServices;
using System.Text.Json;
namespace ModelContextProtocol;
@ -101,4 +103,28 @@ public static class AIContentExtensions
Convert.ToBase64String(dataContent.Data.ToArray());
#endif
}
internal static Content ToContent(this AIContent content) =>
content switch
{
TextContent textContent => new()
{
Text = textContent.Text,
Type = "text",
},
DataContent dataContent => new()
{
Data = dataContent.GetBase64Data(),
MimeType = dataContent.MediaType,
Type =
dataContent.HasTopLevelMediaType("image") ? "image" :
dataContent.HasTopLevelMediaType("audio") ? "audio" :
"resource",
},
_ => new()
{
Text = JsonSerializer.Serialize(content, McpJsonUtilities.DefaultOptions.GetTypeInfo(typeof(object))),
Type = "text",
}
};
}