Skip to content

Python: [Bug]: FoundryToolbox invocation-time OAuth consent is returned as a generic function error #9903

Description

Observed Behavior

When a Python Foundry-hosted agent invokes an OAuth-protected tool through FoundryToolbox, the Toolbox MCP endpoint can return the Foundry consent envelope during tools/call:

MCP error code: -32006
errors[].error.code: CONSENT_REQUIRED
errors[].error.message: <consent URL>

Python does not translate this invocation-time consent condition into the Foundry Responses extension:

{
  "type": "oauth_consent_request",
  "consent_link": "https://..."
}

Instead, the MCP error is wrapped as ToolExecutionException, the core function loop treats it as an ordinary tool failure, and the hosted response contains a generic terminal result:

{
  "type": "function_call_output",
  "call_id": "call_1",
  "output": "Error: Function failed."
}

The caller cannot obtain the consent URL or know that interactive authorization is required. The response is reported as completed rather than incomplete with a consent action.

This differs from discovery-time consent during tools/list, which ResponsesHostServer already translates into oauth_consent_request for store=true requests.

Expected Behavior

Invocation-time Toolbox consent should be returned to the caller as a validated, structured oauth_consent_request, while preserving function-call integrity and the selected history/storage contract.

The expected matrix is:

Mode Expected behavior
store=true, history_source="agent_server" Return the consent action, persist one terminal output for every function call, and allow previous_response_id or conversation continuation after consent.
store=true, history_source="service" Return the consent action and reconcile the complete function-result batch with the downstream model-service conversation before returning.
store=false Return an ephemeral consent action, persist no response/session state, and require a fresh retry after authorization rather than using the incomplete response as a continuation anchor.
Sequential or concurrent batches Preserve completed results, do not execute later protected calls after consent interruption, and provide one terminal output for every emitted function call.

A direct conversion to UserInputRequiredException(Content.from_oauth_consent_request(...)) is not sufficient. In an offline replay, that produced [function_call, oauth_consent_request] without a matching function_call_output; continuation then failed with No tool output found for function call call_1 for both AgentServer-managed and service-managed history. With store=false, the current host rejected the pause with Approval and user-input continuation requires store=true.

The behavior should be analyzed against the function-calling loop contract and the reconciliation approach in #9738 before implementation.

Steps to Reproduce

  1. Use current main at b7884ad88eb85c27b2a7bf40c0e15948e7ccc28d.
  2. Configure the Python hosted Toolbox sample with an OAuth connection, for example change the GitHub MCP connection from ghmcppat to ghmcpoauth.
  3. Use a user who has not completed consent for that connection.
  4. Invoke a protected Toolbox tool after tools/list has succeeded.
  5. Inspect the hosted Responses output.
  6. Observe a paired generic function_call_output error and no oauth_consent_request or caller-visible consent URL.
  7. Repeat with history_source="agent_server" and history_source="service", and with outer store=true and store=false.

A deterministic offline reproduction can replace the remote Toolbox connection with a fake MCP connection whose tools/call raises the same structured MCPError(-32006, ...). The real MCP-generated FunctionTool, core function loop, ResponsesHostServer, response persistence, and a strict continuation client can then be exercised without external resources.

Minimal Reproduction

The essential MCP error shape used by the deterministic replay is:

import json

from mcp import MCPError

payload = json.dumps(
    {
        "errors": [
            {
                "name": "protected_tool",
                "type": "mcp",
                "error": {
                    "code": "CONSENT_REQUIRED",
                    "message": "https://consent.example.com/authorize",
                },
            }
        ]
    }
)

raise MCPError(
    -32006,
    f"tools/call failed for 1 tool source(s), succeeded for 0 tool source(s) {payload}",
)

When this is raised by the MCP connection behind a generated Toolbox FunctionTool, the full hosted response is completed with function_call + generic function_call_output + assistant message. It contains no oauth_consent_request.

For comparison, replacing the generic error path with:

raise UserInputRequiredException(
    contents=[
        Content.from_oauth_consent_request(
            "https://consent.example.com/authorize"
        )
    ]
)

surfaces the consent item but leaves the function call unresolved, reproducing the continuation failure described above.

Error Messages and Stack Traces

Current invocation-time public output:
  status: completed
  output types: function_call, function_call_output, message
  function_call_output: Error: Function failed.
  oauth_consent_request count: 0

Naive dedicated-consent replay on the next stored turn:
  RuntimeError: No tool output found for function call call_1.

Naive dedicated-consent replay with store=false:
  ValueError: Approval and user-input continuation requires store=true.

Package Versions

agent-framework-core: 1.24.0; agent-framework-foundry: 1.16.0; agent-framework-openai: 1.18.0; agent-framework-foundry-hosting: 1.0.0b261030

Python Version

Python 3.13.16

Operating System

Windows

Regression

Unknown

Additional Context

Relevant source paths:

  • python/packages/core/agent_framework/_mcp.py: non-connection-loss MCPError is wrapped as ToolExecutionException during tools/call.
  • python/packages/core/agent_framework/_tools.py: ordinary tool exceptions become generic terminal function_result content; UserInputRequiredException can propagate oauth_consent_request but does not settle the originating call.
  • python/packages/foundry_hosting/agent_framework_foundry_hosting/_responses.py: connect-time consent is parsed and emitted; already-produced oauth_consent_request content is serialized to OAuthConsentRequestOutputItem; store=false rejects approval/user-input continuation.
  • python/packages/foundry/agent_framework_foundry/_oauth_helpers.py: provider-issued oauth_consent_request output items and events are parsed into Agent Framework content.

The Python and upstream Foundry Toolbox samples use GitHub PAT authentication by default. OAuth is presented as an optional connection switch, but neither sample validates invocation-time consent delivery or continuation.

Official Foundry guidance says a client must recognize the interactive authorization request, present the consent URL, and continue after sign-in; a generic MCP client does not handle this automatically. The managed OAuth sample documents that the first protected invocation returns MCP -32006 with the consent URL.

The numeric code alone must not be treated as consent. Detection should require the Foundry Toolbox context and the structured CONSENT_REQUIRED payload, reusing or extracting the existing connect-time parser and consent-link validation.

Initial assignment is for analysis and design confirmation. No implementation has been started.

Acknowledgements

  • I searched existing issues and did not find a duplicate.
  • I personally verified this behavior and the reproduction details are authentic.
  • I will wait for explicit maintainer agreement before starting implementation of a non-trivial change.

Activity

  1. added
    bug
    python
    foundry
    on Oct 30, 2026
  2. lj1166 commented on Nov 2, 2026

    @lj1166

    I traced the current Python paths and propose treating invocation-time Foundry Toolbox consent as a host-owned paused function-call result, rather than propagating it as a bare UserInputRequiredException.

    The invariant should be: every emitted function_call receives exactly one terminal function_call_output, even when that output also requires OAuth consent. The response can then include a validated oauth_consent_request and finish as incomplete. This preserves the function-call transcript required by both agent-server and service-managed continuation.

    Suggested implementation boundaries:

    1. At the Foundry Toolbox invocation boundary, recognize only the structured MCPError(-32006) payload for a Foundry Toolbox source with errors[].error.code == "CONSENT_REQUIRED". Reuse the existing payload parser and consent-link validation; do not classify arbitrary MCP -32006 failures as consent.
    2. Convert the recognized outcome into a paired terminal function result plus an OAuth-consent content item in the same function-call result group. Do not raise UserInputRequiredException without settling the originating call, because that leaves an unmatched function_call in persisted history.
    3. Stop later protected calls after the first consent result while retaining completed sibling results. Persist the complete group through the same host-owned mixed-pause/session path used for other pauses.
    4. For store=true, serialize the paired function output and consent item, persist the session/checkpoint according to history_source, and emit incomplete. For history_source="service", reconcile the entire settled result batch with the downstream conversation before returning.
    5. For store=false, expose the consent item ephemerally but do not create a continuation anchor or persist session/checkpoint state; retry after consent is a fresh request.

    I would validate this with a fake Toolbox MCP connection that raises the documented structured error and cover: agent-server and service history continuation, store=false non-persistence, concurrent batches preserving completed results while halting later protected calls, and malformed/untrusted -32006 payloads remaining ordinary tool failures.

    Before implementation, can you confirm whether the host-owned mixed-pause path is the intended contract for consent, and whether store=false should expose the ephemeral consent action instead of the current validation failure?

  3. eavanvalkenburg commented on Nov 2, 2026

    @eavanvalkenburg
    Member

    /plan Plan the confirmed invocation-time FoundryToolbox OAuth consent handling gap across MCP-generated FunctionTool execution, the core function loop, and ResponsesHostServer. Evaluate the contributor proposal in #9903 (comment) rather than assuming a bare UserInputRequiredException is sufficient. Recognize consent only in Toolbox context with the structured CONSENT_REQUIRED payload and validated links; arbitrary MCP -32006 failures must remain ordinary tool failures. Preserve exactly one terminal result per emitted call, completed sibling results, and exactly-once behavior for sequential/concurrent batches. Establish host ownership and service-history reconciliation for store=true, and evaluate ephemeral store=false consent without persisted response/session/checkpoint state or a continuation anchor. Check existing consent/parser helpers and the function-calling-loop specification; map affected scenarios and test streaming/final/non-streaming caller output plus both history sources with offline fake-MCP replay. Cross-check #9738 for interoperability without treating it as a Python implementation. No ready label or new assignment until this multi-boundary contract is settled.

  4. eavanvalkenburg commented on Nov 9, 2026

    @eavanvalkenburg
    Member

    Decision: structured consent, paired results, and store=true

    Use the structured invocation-time consent direction, not a generic completed tool failure. Recognize the validated Toolbox consent condition, return the consent action with an incomplete response, and preserve exactly one terminal function result per emitted call. Keep completed sibling results and stop later protected calls; reconcile the settled batch with inference-service history.

    Require store=true for this handling. This supersedes the ephemeral store=false alternative in the issue's expected matrix and earlier proposal/planning comment. Do not persist unstored requests implicitly or advertise an ephemeral incomplete response as a continuation anchor. Unsupported unstored consent must fail explicitly.

    A bare UserInputRequiredException is not sufficient if it leaves unmatched function calls. Keep arbitrary MCP failures distinct from validated Toolbox consent and preserve consent-link validation. Coordinate #10020, current native/agent pending authority, and the function-calling-loop contract.

    Necessary breaking Core/hosting changes are allowed in the coordinated python-foundry-hosting-rc work, with shared Core release compatibility/versioning handled explicitly. Exact mechanics and regression coverage remain implementation work; this does not claim implementation completion, safe automatic side-effect replay, or a new checkpoint/retry contract.

  5. eavanvalkenburg commented on Nov 9, 2026

    @eavanvalkenburg
    Member

    Dependency update: structured consent integration follows split hosts

    #10010 is now decided: separate agent-host and native-workflow-host classes. Implement the host-facing portion of #10020/#9903 against that split; the host-shape decision is no longer deferred.

    Keep the agreed behavior: validated structured consent and incomplete status, a terminal result paired with each emitted function call, completed sibling results preserved, later protected calls stopped, and store=true required. This does not select the former ephemeral-consent proposal or claim that consent handling has already been implemented.

  6. moved this from In Progress to Done in Agent Frameworkon Nov 27, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

bugfoundrypython

Type

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions