Skip to content

.Net: Propagate FunctionResult.Metadata to AgentRole.Tool ChatMessageContent.Metadata - #13855

Open
Gustavo Torres (gmtorres) wants to merge 6 commits into
microsoft:mainfrom
gmtorres:gmtorres/propagate_functioncall_metadata
Open

Gustavo Torres (gmtorres) wants to merge 6 commits into
microsoft:mainfrom
gmtorres:gmtorres/propagate_functioncall_metadata

Conversation

@gmtorres

@gmtorres Gustavo Torres (gmtorres) commented Apr 9, 2026 •

Copy link
Copy Markdown

Motivation and Context

There is currently no way to propagate custom metadata from function invocation filters to OrchestrationResponseCallback. Right now AddFunctionCallResultToChatHistory discards FunctionResult.Metadata and it is not exposed to OrchestrationResponseCallback.

This enables scenarios where we want to consume user-defined metadata in invocation filters, such as function result token count ReductionFilter, exception handling, etc

Description

FunctionResult.Metadata is now copied to the Metadata of the FunctionResultContent item that represents the function result. From there it reaches the chat history and OrchestrationResponseCallback.

The metadata is placed on the result item and not on the tool ChatMessageContent, for these reasons:

  • Connectors read reserved keys from tool message metadata. The OpenAI connector takes ChatCompletionsToolCall.Id from it to build the tool reply, so a function metadata key with that name would change the request.
  • Agent services can forward message metadata.
  • Item metadata belongs to exactly one function result. The tool message metadata and the function output stay unchanged.

Reading the metadata from a message:

foreach (var result in message.Items.OfType<FunctionResultContent>())
{
    IReadOnlyDictionary<string, object?>? metadata = result.Metadata;
}

Coverage

Path Behavior
Automatic function calling in connectors that use FunctionCallsProcessor The result item added to the chat history carries the metadata, for sequential and concurrent invocation.
Agents that use FunctionCallsProcessor.InvokeFunctionCallsAsync The returned result items carry the metadata. The OpenAI Responses agent yields those items.
Automatic function calling through IChatClient (UseKernelFunctionInvocation), streaming and non streaming KernelFunctionInvokingChatClient attaches the metadata to the result content that it builds for the tool message. The value returned by the function, which is also what telemetry records, is not changed.
Manual invocation with FunctionCallContent.InvokeAsync A FunctionResultContent created from a FunctionResult copies the metadata.

Not covered

  • The OpenAI Assistant and Azure AI agents rebuild their result items, so those items do not carry the metadata.
  • Metadata keys that differ only by letter case are not supported on the FunctionCallsProcessor paths. The existing conversion to Microsoft.Extensions.AI messages throws for such keys.

Tests

  • FunctionCallsProcessorTests: sequential and concurrent invocation, a reserved OpenAI key that stays on the item, and the path without chat history.
  • FunctionResultContentTests: the constructor copies the metadata.
  • ServiceConversionExtensionsTests: the IChatClient path, streaming and non streaming. The function output and its trace log are unchanged. Keys that differ only by letter case are accepted. Calls that share one call ID keep their own metadata. A result content returned by the function is copied and not modified.

Validation

Run on Windows with the .NET SDK 10.0.404, Debug configuration.

Command Result
dotnet build dotnet\src\SemanticKernel.Abstractions\SemanticKernel.Abstractions.csproj -c Debug --no-restore --tl:off --warnaserror Succeeded for net10.0, net8.0 and netstandard2.0
dotnet build dotnet\src\SemanticKernel.UnitTests\SemanticKernel.UnitTests.csproj -c Debug -f net10.0 --no-restore --tl:off --warnaserror Succeeded
dotnet test dotnet\src\SemanticKernel.UnitTests\SemanticKernel.UnitTests.csproj -c Debug -f net10.0 --no-build --no-restore 1619 passed
dotnet test dotnet\src\Connectors\Connectors.OpenAI.UnitTests\Connectors.OpenAI.UnitTests.csproj -c Debug -f net10.0 474 passed, 1 skipped. An earlier run failed KernelTests.FunctionUsageMetricsAreCapturedByTelemetryAsExpected, which passed on five reruns and does not use the changed code.
dotnet format <project> --no-restore --verify-no-changes --include <changed files> for SemanticKernel.Abstractions and SemanticKernel.UnitTests No changes needed
Build and test of SemanticKernel.UnitTests on a local merge of this branch with main at aa46eddff. Source link was disabled because the merge was built from an exported copy. Built without warnings, 1627 passed

Contribution Checklist

@gmtorres Gustavo Torres (gmtorres) changed the title Propagate FunctionResult Metadata to Tool ChatMessageContent Propagate FunctionResult.Metadata to AgentRole.Tool ChatMessageContent.Metadata Apr 9, 2026
@gmtorres Gustavo Torres (gmtorres) changed the title Propagate FunctionResult.Metadata to AgentRole.Tool ChatMessageContent.Metadata .NET: Propagate FunctionResult.Metadata to AgentRole.Tool ChatMessageContent.Metadata Apr 9, 2026
@gmtorres
Gustavo Torres (gmtorres) marked this pull request as ready for review April 9, 2026 11:45
@gmtorres
Gustavo Torres (gmtorres) requested a review from a team as a code owner April 9, 2026 11:45
Copilot AI review requested due to automatic review settings April 9, 2026 11:45

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR enables propagation of user defined FunctionResult.Metadata created or modified in auto function invocation filters into the ChatHistory tool message metadata, making it accessible to downstream consumers like OrchestrationResponseCallback.

Changes:

  • Populate ChatMessageContent.Metadata for tool messages with AutoFunctionInvocationContext.Result.Metadata when adding function results to chat history.
  • Add a unit test validating metadata flow from a filter set FunctionResult.Metadata to the resulting tool ChatMessageContent.Metadata.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated no comments.

File Description
dotnet/src/InternalUtilities/connectors/AI/FunctionCalling/FunctionCallsProcessor.cs Propagates FunctionResult.Metadata into the tool ChatMessageContent added to ChatHistory.
dotnet/src/SemanticKernel.UnitTests/Utilities/AIConnectors/FunctionCallsProcessorTests.cs Adds coverage to verify function result metadata is preserved on the tool message in chat history.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Automated Code Review

Reviewers: 4 | Confidence: 91%

✓ Correctness

This PR propagates FunctionResult.Metadata to the ChatMessageContent added to chat history after function call execution. The implementation accesses resultContext.Context.Result.Metadata to pass as the metadata parameter to the ChatMessageContent constructor. The code is correct: Result is a non-nullable property on AutoFunctionInvocationContext (always initialized), Metadata is nullable IReadOnlyDictionary which the ChatMessageContent constructor accepts as nullable, and the test properly validates the round-trip through a filter that sets metadata on the FunctionResult. The change is minimal and well-tested.

✓ Security Reliability

This PR propagates FunctionResult.Metadata from function invocation results to the ChatMessageContent added to chat history. The change is minimal and safe. The metadata parameter on the ChatMessageContent constructor is nullable (IReadOnlyDictionary<string, object?>?), so null metadata in the error path (when ExecuteFunctionCallAsync catches an exception and the FunctionResult retains its initial null metadata) is handled gracefully. No injection risks, resource leaks, or unsafe deserialization are introduced. The metadata is user-controlled (set by function implementations or auto-invocation filters), so propagating it to chat history is an intentional and appropriate design choice. The test adequately verifies the new behavior by exercising a filter that sets custom metadata and asserting it appears on the tool message.

✓ Test Coverage

The PR adds metadata propagation from FunctionResult to ChatMessageContent in the tool message added to chat history. The test covers the key scenario where a filter sets metadata on the FunctionResult and verifies it appears on the resulting ChatMessageContent. The test is well-structured with meaningful assertions. However, there are two missing edge-case tests: (1) the default case where no filter modifies metadata (metadata should be null), and (2) the error/exception path where AddFunctionCallResultToChatHistory is also called but the FunctionResult has no metadata. These are not blocking since the null-metadata case is implicitly covered by all existing tests that don't set metadata, but an explicit null-metadata assertion would strengthen confidence.

✗ Design Approach

The single-line change propagates FunctionResult.Metadata to the ChatMessageContent that wraps the tool response, which is the intended behavior. However, the implementation has a subtle design flaw: by passing metadata to the ChatMessageContent constructor together with content, the metadata is inadvertently copied into the auto-created TextContent item inside Items. This happens because the Content property setter (called from the constructor after this.Metadata is already set) creates a new TextContent(metadata: this.Metadata). As a result, the function result metadata ends up on both message.Metadata and message.Items[0] (the TextContent), but not on message.Items[1] (the FunctionResultContent), which is the semantically correct carrier for function-invocation metadata. The fix is simple: construct the message without metadata (so the TextContent is created with null metadata), then assign message.Metadata separately. The test is well-structured and validates the right observable behavior.

Flagged Issues

  • Passing metadata in the ChatMessageContent constructor causes the same metadata dictionary to be copied into the auto-created TextContent item (via the Content setter's new TextContent(metadata: this.Metadata) path). Function-result metadata is semantically tied to the function invocation, not to a text representation item. The correct approach is to set message.Metadata after construction, so the TextContent stays metadata-free while the message-level metadata still propagates correctly.

Suggestions

  • Consider adding a test for the error/exception path (function throws) to verify that AddFunctionCallResultToChatHistory does not surface unexpected metadata on the tool message—currently the error path still flows through this method and will propagate whatever metadata exists on the FunctionResult at the time of failure.
  • Consider adding a test that verifies ChatMessageContent.Metadata is null when no filter modifies the FunctionResult metadata (the default path), ensuring the change doesn't accidentally introduce non-null metadata where none existed before.

Automated review by gmtorres's agents

@gmtorres

Copy link
Copy Markdown
Author

@microsoft-github-policy-service agree

@moonbox3 Evan Mattson (moonbox3) added .NET Issue or Pull requests regarding .NET code kernel Issues or pull requests impacting the core kernel labels Apr 20, 2026
@github-actions github-actions Bot changed the title .NET: Propagate FunctionResult.Metadata to AgentRole.Tool ChatMessageContent.Metadata .Net: Propagate FunctionResult.Metadata to AgentRole.Tool ChatMessageContent.Metadata Apr 20, 2026
Move FunctionResult.Metadata from the tool message to the generated
FunctionResultContent. The metadata is then scoped to one function result,
and it can no longer collide with keys that connectors read from the tool
message metadata.

- FunctionCallsProcessor sets the metadata on the result item, with and
  without chat history.
- FunctionResultContent copies the metadata when created from a
  FunctionResult.
- KernelFunctionInvokingChatClient attaches the metadata to the result
  content built for the tool message. The function output is unchanged.

This branch was previously deployed

1 inactive deployment
github-app-auth — 235ded89 Deployed Nov 21, 2026 by rogerbarreto via add_label #29780
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

kernel Issues or pull requests impacting the core kernel .NET Issue or Pull requests regarding .NET code

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants