← Back to Pull requests

fix(agent-os): refuse run_tool before executing when post_tool_call is unbound #4428

Closed
unknown closed this pull request without merging on Nov 11, 2026 20:15 UTC
View on GitHub
unknown unknown commented on Oct 27, 2026 01:38 UTC
Author

Related Issue


Fixes #4424

Problem & Solution


Problem: with pre_tool_call bound and post_tool_call not, AgentControl.run_tool ran the tool and only then raised AgentControlBlocked for post_tool_call with runtime_error:intervention_point_unknown. The engine's fail-closed rule for an unbound point is right, but the check came after the side effect. The caller was told the call was blocked while the tool had already run, and a retry could run it again. protect_tool and the SDK adapters that call run_tool (MCP, LangChain, Semantic Kernel, Foundry, the generic guard_tool) had the same order.

Solution: the fail-closed rule stays. In enforce mode run_tool now reads the bound points from the runtime client's policy_labels map (which covers parents of an extends chain) and, once the pre-check permits the call, raises the same block with the same verdict and reason before calling the tool. The run_tool and protect_tool docstrings, the Python SDK README, the quickstart, the tutorial and the policy-engine README manifest now say both tool points must be bound.

Behaviour change, in full. Only in enforce mode, only through AgentControl.run_tool (and so protect_tool and the SDK adapters that call it: MCP, LangChain, Semantic Kernel, Foundry, generic guard_tool), and only when the runtime client reports bound points (every native-backed constructor: from_native, from_path, from_url, from_manifest_chain): if the merged manifest does not bind post_tool_call, the tool callable is no longer invoked. The caller still gets the same AgentControlBlocked for post_tool_call with the same verdict (deny, reason runtime_error:intervention_point_unknown, message "Request blocked by Agent Control Specification.", no policy input, no identities), the same str(exc), and the same telemetry events (pre_tool_call then post_tool_call). Differences for such callers: execute is not called; a SnapshotBuilder tool-call slot reserved for the call is released instead of staying charged; the post_tool_call telemetry event has a near-zero duration.

Everything else is unchanged: a pre_tool_call deny still wins and is reported as pre_tool_call; manifests binding both points behave exactly as before; a manifest binding neither still denies at pre_tool_call before the tool runs; evaluate_only mode still runs the tool and returns the engine's unknown-point result; a custom RuntimeClient without policy_labels (or one that returns an empty map) keeps the old order (tool runs, then the engine's post-check deny); run() with an unbound output point and evaluate_intervention_point are untouched; agent-os NativeAdapterRuntime and its adapters are untouched.

Impact on Your Work


A manifest that binds only pre_tool_call is an easy mistake to make, and until now it let a blocked tool call run anyway. That breaks the promise that a deny stops the action, and a payment, write or send could repeat on retry. This change makes the block happen before the tool runs, so the fail-closed rule holds in practice and not only in the returned verdict.

Timeline


None

Alternatives Considered


Docs only: state that both tool points must be bound and leave the order alone. Rejected because the side effect still happens before the block; the docs change is included, but on its own it does not close the gap.

Type of Change


  • Bug fix (non-breaking change that fixes an issue)

  • New feature (non-breaking change that adds functionality)

  • Breaking change (fix or feature that would cause existing functionality to change)

  • Documentation update

  • Maintenance (dependency updates, CI/CD, refactoring)

  • Security fix
  • Package(s) Affected


    Core & runtime:
  • agent-governance-toolkit-core

  • agent-primitives

  • agent-os

  • agent-mesh

  • agent-runtime

  • agent-sre

  • agent-compliance
  • Governance & security:

  • agent-mcp-governance

  • agent-rag-governance

  • agent-sandbox

  • agent-discovery

  • agt-policies

  • policy-engine
  • Platform & tooling:

  • agent-hypervisor

  • agent-lightning

  • agent-marketplace

  • agent-governance-toolkit-cli

  • agent-governance-toolkit-integrations

  • agent-governance-toolkit-protocols

  • agentmesh-integrations (framework integrations)
  • CLI plugins:

  • agent-governance CLI plugins (copilot-cli / claude-code / opencode / antigravity-cli)
  • Shared / other:

  • schemas

  • action (GitHub Action)

  • examples

  • docs / root
  • Testing

    Unit Testing


    New file policy-engine/sdk/python/tests/test_run_tool_unbound_post.py, 13 tests.

    Environment: native SDK built with maturin 1.8.7 (uv venv --python 3.12, maturin develop --release in policy-engine/sdk/python), ACS_OPA_PATH=/home/mhabuomar/.local/bin/opa.

    On this branch:

    cd policy-engine/sdk/python && pytest tests/test_run_tool_unbound_post.py
    13 passed in 0.11s
    

    Same file against main's _orchestration.py (the one file stashed, and again copied into a throwaway worktree of origin/main with the native .so copied over, run with PYTHONPATH=. so main's package loaded, confirmed via __file__):

    4 failed, 9 passed
    

    The 4 that fail on main are the bug:

  • test_pre_only_manifest_blocks_before_the_tool_runs (Lists differ: [{'amount': 100}] != [], the spy recorded the tool call)

  • test_pre_only_manifest_releases_the_tool_call_slot (1 != 0)

  • test_pre_only_manifest_through_protect_tool ([{'amount': 5}] != [])

  • CustomClientTests.test_client_reporting_bound_points_blocks_before_the_tool_runs (AgentControlBlocked not raised)
  • The other 9 guard unchanged behaviour and pass on both trees by design: both bound allow, both bound deny at post, pre deny wins, neither bound, chain parent binds post, extends parent binds post, evaluate_only, early block equals the engine's own result, custom client without policy_labels keeps the old order.

    Full Python SDK suite:

    cd policy-engine/sdk/python && pytest tests
    318 passed, 42 skipped, 50 subtests passed in 3.57s
    

    (Excluding test_real_packages.py: 318 passed, 3 skipped, 50 subtests passed.)

    agent-os suite, run because its adapters sit on the same SDK (agent-governance-python/agent-os, PYTHONPATH=src:../agent-sre/src; agent-sre is needed for tests/test_spec_mcp_gateway_conformance.py to collect):

    branch:      3 failed, 3742 passed, 57 skipped, 12 subtests passed in 47.64s
    origin/main: 3 failed, 3742 passed, 57 skipped, 12 subtests passed in 41.84s
    

    The 3 failures are the same on both trees and unrelated: tests/test_new_features_batch2.py::TestSandboxProvider::test_subprocess_echo, test_subprocess_timeout, test_subprocess_failure. The focused agent-os files (tests/test_native_adapter_runtime.py tests/test_adapter_mediation_contract.py tests/test_adapter_enforcement.py tests/test_transform_never_dropped.py): 204 passed, 1 skipped.

    Manual Testing


    A probe script run against both trees (branch package and origin/main package), outputs diffed:

    1. Manifest chain, post_tool_call bound only in the child: tool runs, value returned, both verdicts allow. Same on both.
    2. Bound only in the parent (from_manifest_chain and an extends file): tool runs. Same on both.
    3. Bound in neither (parent binds input, child binds pre): branch blocks at post_tool_call with tool.calls == []; main raised the same exception after tool.calls == [{'amount': 100}].
    4. No tool points at all: blocked at pre_tool_call with runtime_error:intervention_point_unknown, tool never runs. Same on both.
    5. post_tool_call bound to an always-deny policy: tool runs, result withheld, AgentControlBlocked(post_tool_call, reason 'nope') with full policy_input. Same on both.
    6. Tool raises with both bound: RuntimeError propagates, SnapshotBuilder tool_call_count stays 1. Same on both.
    7. Tool raises with pre-only: branch never calls it (blocked first); main let it raise after running.
    8. Pre deny: tool not run, blocked at pre_tool_call reason pre_no. Same on both.
    9. EVALUATE_ONLY (enum and the string 'evaluate_only'): tool runs, post result deny with the unknown reason returned for inspection. Same on both.
    10. Mode 'enforce' as a string: early block works.
    11. Pre escalate approved by the resolver, then pre-only: blocked before the tool on branch; after on main.
    12. Byte identity: the early block's result equals the engine's own evaluate_intervention_point result for the unbound point (dataclass eq and repr eq both true); exception type agent_control_specification._types.AgentControlBlocked, MRO [AgentControlBlocked, AgentControlInterruption, RuntimeError], str 'Agent Control Specification blocked post_tool_call (runtime_error:intervention_point_unknown).', message 'Request blocked by Agent Control Specification.', policy_input None. The only differing field across main and branch in every blocked line is tool.calls.
    13. Telemetry with a sink, pre-only enforce: two events (pre_tool_call allow with policy_id 'tools'; post_tool_call deny, error_class runtime_error, reason_code runtime_error:intervention_point_unknown, policy_id None), identical in every field except duration on both trees.
    14. protect_tool with SnapshotBuilder, pre-only: branch count 0 after the block; main 1.

    Source review: the engine decides "unknown" by manifest.intervention_points.get(point) (agent-control-spec 0.4.0-alpha.4 runtime.rs:294-301) and policy_labels iterates the same map (sdk/rust/src/host/mod.rs:346-358), so "key present in policy_labels" is exactly "bound"; no drift path. _bound_points_from_client returns None on a missing accessor, an exception, a non-mapping or an empty map, so a custom client keeps the old order. No new imports. The raise sits inside the try that releases the builder slot.

    Static checks: ruff check src/ --select E,F,W --ignore E501 clean in agent-os and on the two changed SDK files; license headers present (new test file has the MIT header); python3 scripts/check_v4_ratchet.py OK (grand total 4); cspell on added lines 0 issues.

    Checklist


  • I have linked a related issue above, or completed "Problem & Solution", "Impact on Your Work", and "Alternatives Considered"

  • My code follows the project style guidelines (ruff check)

  • I have added tests that prove my fix/feature works

  • All new and existing tests pass (pytest)

  • I have updated documentation as needed

  • I have signed the Microsoft CLA
  • Attribution & Prior Art


  • This contribution does not contain code copied or derived from other projects without attribution

  • Any external projects that inspired this design are credited in code comments or documentation

  • If this PR implements functionality similar to an existing open-source project, I have listed it below
  • Prior art / related projects (if any):
    The analysis of the ordering bug and the pre-only reproduction come from @ricjhill's report in #4424.

    AI Assistance


  • I can explain every meaningful change in this PR: what it does, why, and what tradeoffs were considered

  • I have run tests and verification appropriate for this change

  • No part of this PR was autonomously submitted by an AI agent without my review

  • I have not used AI to generate review comments on others' PRs
  • If AI tools materially shaped this change, briefly note what was used:
    Claude Code drafted the fix and tests under my direction; an independent verification pass re-ran the tests on main and on the branch and probed the chain and deny cases, and I reviewed the result.

    IP, Patents, and Licensing


  • This contribution does not implement patent-pending or patent-encumbered techniques

  • This contribution does not require an NDA or licensing agreement to understand or use

  • Any AI tools used have terms compatible with the MIT License
  • Diff: 650 lines (+487 / -163) across 8 files Reviewer: prayagupa Review duration: 22717m
    All Vouch review confidence checks passed
    Residual risk 0.22 = Change Risk (0.52) × (1 − Review Confidence (0.57)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.52 · 650 lines diff across 8 files
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.17 · 1 substantive comment(s)
    0.17
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    56%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.388
    Shallow Review Depth shallow_review_depth
    0.289
    Real PR Conversation Timeline
    1 comments
    "Review active on #4428"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 56.8% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 52% (MEDIUM) · Higher = larger blast radius
    52%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 56.8% · Lower = rushed or shallow review
    56.8%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 22.5% · Safe to merge
    22.5%