Skip to content

Python: bind tool-approval responses to surfaced approval requests (#7383) - #7581

Draft
Tony Dzi (Anton Dziatkovskii) (tonydzi) wants to merge 1 commit into
microsoft:mainfrom
tonydzi:fix/bind-approval-responses-to-surfaced-requests
Draft

Python: bind tool-approval responses to surfaced approval requests (#7383)#7581
Tony Dzi (Anton Dziatkovskii) (tonydzi) wants to merge 1 commit into
microsoft:mainfrom
tonydzi:fix/bind-approval-responses-to-surfaced-requests

Conversation

@tonydzi

Copy link
Copy Markdown

Summary

Closes the gap tracked in #7383 by mirroring the .NET behavior from #7111 in the Python core: a function_approval_response is treated as a decision token bound to the approval request that was actually surfaced, not as a work order carrying its own function call.

Opened as a draft deliberately: #7383 is assigned to Eduard van Valkenburg (@eavanvalkenburg), and this is the working draft I offered on #7345 — please treat it as raw material, not a claim on the issue. Close it freely in favor of your own implementation, or tell me what to change and I'll iterate.

What changes

  • When an approval batch pauses, the surfaced (visible) approval requests are recorded in the session tool-approval state bag (surfaced_approval_requests), with the same session gating as the existing already-approved-siblings mechanism.
  • On resume, _resolve_approval_responses binds each inbound decision back to its recorded request: the recorded function call is what executes. An embedded call that differs from the recorded one is logged (logger.warning) and ignored, so an edited or replayed response cannot execute a call that was never surfaced.
  • Records are one-time-use: consumed by the first decision for that request id, approved or rejected — a rejected request cannot be re-approved from a stale response later.
  • Sessionless flows are unchanged: with no session there is no record, and responses pass through exactly as before. No public API changes.

Known edges (reviewer input welcome)

  • Reused call ids: the record store is keyed by approval-request id (= call_id), so if the same call id is surfaced again in a later turn the newer record wins. That matches the correlate-by-latest intuition but differs from _collect_unanswered_approval_requests, which keeps the first occurrence — happy to align either way.
  • State restore semantics: restoring an older session state snapshot restores the approval records that existed then (same as the existing already-approved groups). If time-travel restore should invalidate prior approval state, that seems like a property of the state layer rather than this binding.

Testing

  • Two new tests in test_harness_tool_approval.py: an approval response carrying an edited call executes the surfaced call (the edited arguments never reach the tool), and the record is consumed on first decision.
  • Full runs of test_harness_tool_approval.py (27 passed), plus test_function_invocation_logic.py, test_sessions.py, test_security.py: 475 passed, 3 skipped, 4 failed — the 4 failures are environment-dependent (aiohttp / MCP extras) and fail identically on clean main in the same environment.

Disclosure

Architecture and validation are mine; the code and text were drafted in pair with Claude (commit carries Assisted-by:).

Mirrors the .NET behavior from microsoft#7111 for the Python core, closing the
gap tracked in microsoft#7383: an inbound function_approval_response previously
executed whatever function_call it carried, so an edited or replayed
response could execute a call that was never surfaced for approval.

- surfaced approval requests are recorded in the session tool-approval
  state bag when the batch pauses (same gating as the existing
  already-approved-siblings mechanism)
- on resume, each decision is bound back to its recorded request: the
  recorded function call is executed, a differing embedded call is
  logged and ignored
- records are one-time-use: consumed by the first decision, approved
  or rejected
- sessionless flows are unchanged (nothing recorded, responses pass
  through as before)

Tests: two new cases in test_harness_tool_approval.py (edited response
executes the surfaced call; record consumed on decision). Full runs of
test_harness_tool_approval.py, test_function_invocation_logic.py,
test_sessions.py and test_security.py: 475 passed, 4 pre-existing
environment failures (aiohttp/mcp deps) that also fail on clean main.

Assisted-by: Claude (Anthropic)
@microsoft-github-policy-service

Copy link
Copy Markdown

Tony Dzi (Anton Dziatkovskii) (@tonydzi) 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.

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

Binds Python tool-approval decisions to session-recorded approval requests to prevent edited calls and replay.

Changes:

  • Records surfaced approval requests in session state.
  • Rebinds approved responses and consumes stored requests.
  • Adds binding and consumption tests.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 1 comment.

File Description
python/packages/core/agent_framework/_tools.py Implements approval recording, binding, and consumption.
python/packages/core/tests/core/test_harness_tool_approval.py Tests edited responses and record consumption.
Suppressed comments (4)

python/packages/core/agent_framework/_tools.py:2159

  • A session with no surfaced_approval_requests map is currently treated like a sessionless invocation. After the final record is removed below—or when resuming state serialized before this change—a stale/fabricated approved response is therefore executed unchanged, defeating one-time consumption. Only state is None should retain passthrough behavior; a session-backed response without a recorded unresolved request must be ignored or rejected, with all supported local approval paths recorded first.
    state = _get_tool_approval_state(invocation_session)
    raw_surfaced = state.get(_SURFACED_APPROVAL_REQUESTS_KEY) if state is not None else None
    if state is None or not isinstance(raw_surfaced, dict):
        return [response for response in approval_responses if response.approved]

python/packages/core/agent_framework/_tools.py:2172

  • An approved response whose ID is absent from the record is still appended and executed from its caller-supplied function call. This permits an unsurfaced approval to execute whenever the session happens to contain records for other requests. Unknown or malformed records must be ignored/rejected rather than passed through.
        if recorded is None or recorded.type != "function_call":
            responses_to_execute.append(response)
            continue

python/packages/core/agent_framework/_tools.py:2185

  • Reconstructing the response drops its annotations, additional properties, and raw representation. Function middleware receives this response through context.metadata["approval_response"], so session-backed approvals now lose caller metadata that previously passed through. Preserve the original decision content and replace only its untrusted function_call.
        responses_to_execute.append(
            Content.from_function_approval_response(
                id=response.id,  # type: ignore[arg-type]
                function_call=recorded,
                approved=True,
            )

python/packages/core/agent_framework/_tools.py:2831

  • Only the list sent to the executor is rebound; _replace_approval_contents_with_results still receives the original edited responses. If an embedded call_id was changed, execution produces a result under the recorded call ID, but normalization looks it up under the edited ID and emits no terminal result, leaving the approval wrapper in the transcript. Bind the pending response map itself (including rejected decisions), then derive approved executions from that canonical map.
    responses_to_execute = _bind_approval_responses_to_surfaced_requests(
        invocation_session,
        list(pending_approval_responses.values()),
    )

💡 Add a code-review agent skill for context-aware, tailored reviews. Learn more in the docs.

Comment on lines +2139 to +2142
def _bind_approval_responses_to_surfaced_requests(
invocation_session: AgentSession | None,
approval_responses: Sequence[Content],
) -> list[Content]:
@babyblueviper1

Copy link
Copy Markdown

Good, this closes the specific gap cleanly -- rebind-to-recorded-call is the right primitive regardless of how the state-restore question eventually gets answered.

On the state-restore known edge: agreed on the layering (staleness-invalidation belongs to the state layer, not this binding) -- but worth naming the concrete residual explicitly, since "that's a property of the state layer" can read as "not a real problem" if it's left implicit. As written, a surfaced_approval_requests record has no expiry of its own, so a session resumed from a week-old snapshot can still consume a record that's a week stale -- correctly bound to the correct call, but arguably to a decision nobody should still be honoring. If the state layer doesn't already carry a TTL/staleness concept for other record types in the same bag, this PR is probably the right trigger to open that as its own explicit follow-up rather than something this binding needs to solve inline.

@babyblueviper1

Copy link
Copy Markdown

Real, well-tested implementation of the shape from #7383 -- the record/rebind/consume discipline holds up exactly as discussed, and the one-time-use consumption (approved OR rejected) closes the replay gap cleanly.

On the open question (newest-record-wins vs first-occurrence): newest wins is the right call, and here's the concrete reasoning from our own analogous case. Our /review verdicts bind to an intended_verifier/context at issuance time specifically because a verdict issued for one context shouldn't silently authorize a different one later -- and the same logic applies here in reverse: if the same call_id gets RE-surfaced in a later turn, that's the system asking the approver to look at it again, presumably because something about the context changed. The approver's decision on THAT most recent surfacing is what they actually saw and reasoned about. Binding to the first occurrence would risk executing a call the approver technically "approved" once, but under conditions that no longer hold by the time it actually runs -- the same staleness risk a decision_ref without a fresh binding would have. _collect_unanswered_approval_requests keeping the first occurrence is answering a different question (what's still outstanding), not which decision is authoritative -- I wouldn't align them.

Nice, concrete edge case caught in the tests (edited call args never reaching the tool) -- that's the actual security property, not just the happy path.

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

Labels

python Usage: [Issues, PRs], Target: Python

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants