Skip to content

.NET: Propagate FunctionResult.Metadata to AgentRole.Tool ChatMessageContent.Metadata#13855

Open
gmtorres wants to merge 3 commits intomicrosoft:mainfrom
gmtorres:gmtorres/propagate_functioncall_metadata
Open

.NET: Propagate FunctionResult.Metadata to AgentRole.Tool ChatMessageContent.Metadata#13855
gmtorres wants to merge 3 commits intomicrosoft:mainfrom
gmtorres:gmtorres/propagate_functioncall_metadata

Conversation

@gmtorres
Copy link
Copy Markdown

@gmtorres gmtorres commented Apr 9, 2026

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

Pass resultContext.Context.Result.Metadata to the ChatMessageContent constructor in
AddFunctionCallResultToChatHistory, so that metadata set on FunctionResult during the filter pipeline flows through to
the chat history message and ultimately to OrchestrationResponseCallback.

Contribution Checklist

@gmtorres gmtorres changed the title Propagate FunctionResult Metadata to Tool ChatMessageContent Propagate FunctionResult.Metadata to AgentRole.Tool ChatMessageContent.Metadata Apr 9, 2026
@gmtorres gmtorres changed the title Propagate FunctionResult.Metadata to AgentRole.Tool ChatMessageContent.Metadata .NET: Propagate FunctionResult.Metadata to AgentRole.Tool ChatMessageContent.Metadata Apr 9, 2026
@microsoft-github-policy-service
Copy link
Copy Markdown

@gmtorres please read the following Contributor License Agreement(CLA). If you agree with the CLA, please reply with the following information.

@microsoft-github-policy-service agree [company="{your company}"]

Options:

  • (default - no company specified) I have sole ownership of intellectual property rights to my Submissions and I am not making Submissions in the course of work for my employer.
@microsoft-github-policy-service agree
  • (when company given) I am making Submissions in the course of work for my employer (or my employer has intellectual property rights in my Submissions by contract or applicable law). I have permission from my employer to make Submissions and enter into this Agreement on behalf of my employer. By signing below, the defined term “You” includes me and my employer.
@microsoft-github-policy-service agree company="Microsoft"
Contributor License Agreement

Contribution License Agreement

This Contribution License Agreement (“Agreement”) is agreed to by the party signing below (“You”),
and conveys certain license rights to Microsoft Corporation and its affiliates (“Microsoft”) for Your
contributions to Microsoft open source projects. This Agreement is effective as of the latest signature
date below.

  1. Definitions.
    “Code” means the computer software code, whether in human-readable or machine-executable form,
    that is delivered by You to Microsoft under this Agreement.
    “Project” means any of the projects owned or managed by Microsoft and offered under a license
    approved by the Open Source Initiative (www.opensource.org).
    “Submit” is the act of uploading, submitting, transmitting, or distributing code or other content to any
    Project, including but not limited to communication on electronic mailing lists, source code control
    systems, and issue tracking systems that are managed by, or on behalf of, the Project for the purpose of
    discussing and improving that Project, but excluding communication that is conspicuously marked or
    otherwise designated in writing by You as “Not a Submission.”
    “Submission” means the Code and any other copyrightable material Submitted by You, including any
    associated comments and documentation.
  2. Your Submission. You must agree to the terms of this Agreement before making a Submission to any
    Project. This Agreement covers any and all Submissions that You, now or in the future (except as
    described in Section 4 below), Submit to any Project.
  3. Originality of Work. You represent that each of Your Submissions is entirely Your original work.
    Should You wish to Submit materials that are not Your original work, You may Submit them separately
    to the Project if You (a) retain all copyright and license information that was in the materials as You
    received them, (b) in the description accompanying Your Submission, include the phrase “Submission
    containing materials of a third party:” followed by the names of the third party and any licenses or other
    restrictions of which You are aware, and (c) follow any other instructions in the Project’s written
    guidelines concerning Submissions.
  4. Your Employer. References to “employer” in this Agreement include Your employer or anyone else
    for whom You are acting in making Your Submission, e.g. as a contractor, vendor, or agent. If Your
    Submission is made in the course of Your work for an employer or Your employer has intellectual
    property rights in Your Submission by contract or applicable law, You must secure permission from Your
    employer to make the Submission before signing this Agreement. In that case, the term “You” in this
    Agreement will refer to You and the employer collectively. If You change employers in the future and
    desire to Submit additional Submissions for the new employer, then You agree to sign a new Agreement
    and secure permission from the new employer before Submitting those Submissions.
  5. Licenses.
  • Copyright License. You grant Microsoft, and those who receive the Submission directly or
    indirectly from Microsoft, a perpetual, worldwide, non-exclusive, royalty-free, irrevocable license in the
    Submission to reproduce, prepare derivative works of, publicly display, publicly perform, and distribute
    the Submission and such derivative works, and to sublicense any or all of the foregoing rights to third
    parties.
  • Patent License. You grant Microsoft, and those who receive the Submission directly or
    indirectly from Microsoft, a perpetual, worldwide, non-exclusive, royalty-free, irrevocable license under
    Your patent claims that are necessarily infringed by the Submission or the combination of the
    Submission with the Project to which it was Submitted to make, have made, use, offer to sell, sell and
    import or otherwise dispose of the Submission alone or with the Project.
  • Other Rights Reserved. Each party reserves all rights not expressly granted in this Agreement.
    No additional licenses or rights whatsoever (including, without limitation, any implied licenses) are
    granted by implication, exhaustion, estoppel or otherwise.
  1. Representations and Warranties. You represent that You are legally entitled to grant the above
    licenses. You represent that each of Your Submissions is entirely Your original work (except as You may
    have disclosed under Section 3). You represent that You have secured permission from Your employer to
    make the Submission in cases where Your Submission is made in the course of Your work for Your
    employer or Your employer has intellectual property rights in Your Submission by contract or applicable
    law. If You are signing this Agreement on behalf of Your employer, You represent and warrant that You
    have the necessary authority to bind the listed employer to the obligations contained in this Agreement.
    You are not expected to provide support for Your Submission, unless You choose to do so. UNLESS
    REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING, AND EXCEPT FOR THE WARRANTIES
    EXPRESSLY STATED IN SECTIONS 3, 4, AND 6, THE SUBMISSION PROVIDED UNDER THIS AGREEMENT IS
    PROVIDED WITHOUT WARRANTY OF ANY KIND, INCLUDING, BUT NOT LIMITED TO, ANY WARRANTY OF
    NONINFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
  2. Notice to Microsoft. You agree to notify Microsoft in writing of any facts or circumstances of which
    You later become aware that would make Your representations in this Agreement inaccurate in any
    respect.
  3. Information about Submissions. You agree that contributions to Projects and information about
    contributions may be maintained indefinitely and disclosed publicly, including Your name and other
    information that You submit with Your Submission.
  4. Governing Law/Jurisdiction. This Agreement is governed by the laws of the State of Washington, and
    the parties consent to exclusive jurisdiction and venue in the federal courts sitting in King County,
    Washington, unless no federal subject matter jurisdiction exists, in which case the parties consent to
    exclusive jurisdiction and venue in the Superior Court of King County, Washington. The parties waive all
    defenses of lack of personal jurisdiction and forum non-conveniens.
  5. Entire Agreement/Assignment. This Agreement is the entire agreement between the parties, and
    supersedes any and all prior agreements, understandings or communications, written or oral, between
    the parties relating to the subject matter hereof. This Agreement may be assigned by Microsoft.

@gmtorres gmtorres marked this pull request as ready for review April 9, 2026 11:45
@gmtorres 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
Copy link
Copy Markdown
Contributor

Copilot AI left a comment

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.

Copy link
Copy Markdown
Contributor

@github-actions github-actions bot left a comment

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

private void AddFunctionCallResultToChatHistory(ChatHistory chatHistory, FunctionResultContext resultContext)
{
var message = new ChatMessageContent(role: AuthorRole.Tool, content: resultContext.Result);
var message = new ChatMessageContent(role: AuthorRole.Tool, content: resultContext.Result, metadata: resultContext.Context.Result.Metadata);
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.

Passing metadata to the constructor causes the Content setter (called inside the constructor after this.Metadata is already set) to forward the same metadata to the auto-created TextContent item via new TextContent(metadata: this.Metadata). Function-result metadata doesn't belong on the text item. Assign Metadata after construction to avoid this leakage.

Suggested change
var message = new ChatMessageContent(role: AuthorRole.Tool, content: resultContext.Result, metadata: resultContext.Context.Result.Metadata);
var message = new ChatMessageContent(role: AuthorRole.Tool, content: resultContext.Result);
message.Metadata = resultContext.Context.Result.Metadata;

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Good catch, addressed

Assert.Equal(42, toolMessage.Metadata["key2"]);
}

[Fact]
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.

The test only covers the case where metadata is explicitly set by a filter. Consider adding analogous test without the filter (or with a no-op filter) to assert that toolMessage.Metadata is null when no metadata is provided, validating the change doesn't regress default behavior.

Suggested change
[Fact]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants