Add CallToolResult.ToChatMessage extension method (#575)

To simplify non-AIFunction usage getting a ChatMessage with the appropriate FunctionResultContent.
This commit is contained in:
Stephen Toub 2025-07-01 07:09:49 -04:00 • committed by GitHub
commit 4e290f8de9
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 51 additions and 0 deletions

View file

@ -39,6 +39,29 @@ public static class AIContentExtensions
};
}
/// <summary>
/// Converts a <see cref="CallToolResult"/> to a <see cref="ChatMessage"/> object.
/// </summary>
/// <param name="result">The tool result to convert.</param>
/// <param name="callId">The identifier for the function call request that triggered the tool invocation.</param>
/// <returns>A <see cref="ChatMessage"/> object created from the tool result.</returns>
/// <remarks>
/// This method transforms a protocol-specific <see cref="CallToolResult"/> from the Model Context Protocol
/// into a standard <see cref="ChatMessage"/> object that can be used with AI client libraries. It produces a
/// <see cref="ChatRole.Tool"/> message containing a <see cref="FunctionResultContent"/> with result as a
/// serialized <see cref="JsonElement"/>.
/// </remarks>
public static ChatMessage ToChatMessage(this CallToolResult result, string callId)
{
Throw.IfNull(result);
Throw.IfNull(callId);
return new(ChatRole.Tool, [new FunctionResultContent(callId, JsonSerializer.SerializeToElement(result, McpJsonUtilities.JsonContext.Default.CallToolResult))
{
RawRepresentation = result,
}]);
}
/// <summary>
/// Converts a <see cref="GetPromptResult"/> to a list of <see cref="ChatMessage"/> objects.
/// </summary>

View file

@ -0,0 +1,28 @@
using Microsoft.Extensions.AI;
using ModelContextProtocol.Protocol;
using System.Text.Json;
namespace ModelContextProtocol.Tests;
public class AIContentExtensionsTests
{
[Fact]
public void CallToolResult_ToChatMessage_ProducesExpectedAIContent()
{
CallToolResult toolResult = new() { Content = [new TextContentBlock { Text = "This is a test message." }] };
Assert.Throws<ArgumentNullException>(() => AIContentExtensions.ToChatMessage(null!, "call123"));
Assert.Throws<ArgumentNullException>(() => AIContentExtensions.ToChatMessage(toolResult, null!));
ChatMessage message = AIContentExtensions.ToChatMessage(toolResult, "call123");
Assert.NotNull(message);
Assert.Equal(ChatRole.Tool, message.Role);
FunctionResultContent frc = Assert.IsType<FunctionResultContent>(Assert.Single(message.Contents));
Assert.Same(toolResult, frc.RawRepresentation);
Assert.Equal("call123", frc.CallId);
JsonElement result = Assert.IsType<JsonElement>(frc.Result);
Assert.Contains("This is a test message.", result.ToString());
}
}