crewAI icon indicating copy to clipboard operation
crewAI copied to clipboard

[FEATURE] Opt-in fail-closed mode for tool hooks (exceptions currently allow the tool call)

Open aminrj opened this issue 2 weeks ago • 7 comments

Feature Area

Core functionality

Is your feature request related to an existing bug?

NA. The current behaviour is documented as intended in crewai/hooks/dispatch.py: "Any other exception raised by a hook is swallowed (fail-open) to preserve the framework's protection against a buggy user hook."

Describe the solution you'd like

A way to make hook failures block the intercepted operation, for hooks used as security controls. For example:

register_before_tool_call_hook(policy, on_error="abort")   # per hook
# or
Crew(..., hook_error_policy="abort")                       # per crew

With "abort", an exception other than HookAborted would be treated as HookAborted (with the original exception as the reason) instead of being swallowed. The default can stay as it is.

The same applies to after_tool_call: if a hook that redacts the tool result raises, the unredacted result currently goes to the model.

Reproduction on crewai 1.15.41 (no LLM; drives execute_tool_and_check_finality directly):

from crewai.tools import tool
from crewai.agents.parser import AgentAction
from crewai.utilities.i18n import I18N
from crewai.utilities.tool_utils import execute_tool_and_check_finality
from crewai.hooks import register_before_tool_call_hook

ran = []

@tool("send_email")
def send_email(to: str) -> str:
    """Send an email."""
    ran.append(to)
    return "sent"

def policy(ctx):
    raise RuntimeError("policy service unreachable")   # e.g. timeout calling a policy engine

register_before_tool_call_hook(policy)
action = AgentAction(thought="", tool="send_email", tool_input='{"to": "[email protected]"}',
                     text='Action: send_email\nAction Input: {"to": "[email protected]"}')
execute_tool_and_check_finality(action, [send_email.to_structured_tool()], I18N())
print(ran)   # ['[email protected]']: the tool ran although the policy hook failed

Describe alternatives you've considered

Catching every exception inside each hook and raising HookAborted. This works, and it's what I recommend to users today, but it has to be repeated in every hook, and a hook written without it fails open silently. Logging only happens with verbose on.

Additional context

OWASP's Securing Agentic Applications V2 (November 2026), section 3.3.7, says that when a hook cannot reach a decision ("an error, a timeout, or an unreachable enforcement service") the action "must fail closed", because "a hook that fails open can be bypassed by anyone able to make it fail." For comparison, the Claude Agent SDK exposes this as HookMatcher(on_failure="block"). The OpenAI Agents SDK and LangChain middleware abort the run when a tool guardrail raises.

I tested how five agent frameworks handle hook failures; test code and results are at https://github.com/aminrj-labs/agent-hook-failure-tests.

aminrj avatar Nov 14 '26 01:11 aminrj

Confirmed on main (d7dfa0e): hooks/dispatch.py says any exception other than HookAborted "is swallowed (fail-open)" (L21-23), and _invoke_hook only prints a warning when verbose is on (L284-292). So a broken security hook is silent by default.

+1 for an opt-in on_error="abort". Until then, one more workaround besides try/except in every hook: enforce inside the tool callable instead of a hook, so dispatch never sees the exception.

Disclosure: I maintain agent-airlock, which does that for crewAI via wrap_crew(crew, policy=...). It wraps tool.func / _run, and a policy resolver that refuses the call. Limits: it is in-process and not a CrewAI hook; it is not deny-by-default, and its config does not fail closed (unknown keys only warn). https://github.com/sattyamjjain/agent-airlock

sattyamjjain avatar Nov 14 '26 05:11 sattyamjjain

Hey @aminrj, +1 on an opt-in abort. One data point from agent-airlock, a guard I maintain (0.10.34). When its policy resolver raises a RuntimeError, the call comes back blocked as policy_violation, "the policy resolver failed", and the tool body never runs (0.38 ms). Same with a human-approval gate whose approver crashes: the error surfaces and the tool does not run. I feel after_tool_call is the sharper case, since a failed redaction hook hands the raw result to the model. May be worth one test where the redaction hook raises and the assertion is that the model never sees the unredacted text.

sattyamjjain avatar Nov 14 '26 05:11 sattyamjjain

Implemented the opt-in you sketched, with on_error on both tool-hook registrars (fail_open default, abort opts in). The policy lives on the dispatch engine and is keyed by the hook callable, so no wrapper lands in the registry that legacy modules alias, and unregister/clear drops it. PR follows with the issue's reproduction as an end-to-end test (the tool body must not run).

Please assign @Luckyou-d if available.

Luckyou-d avatar Nov 15 '26 09:11 Luckyou-d

Thanks all.

@Luckyou-d, thanks for taking this on in #9465. I ran the branch (head of pull/9465) against both hook points.

  • before_tool_call with on_error="abort": the tool body does not run, and execute_tool_and_check_finality returns the "blocked by hook" message. Matches your end-to-end test.
  • after_tool_call with on_error="abort": the unredacted result never reaches the model, but HookAborted is not caught anywhere. run_after_tool_call_hooks has no try/except (the before variant does), and its call sites in tool_utils.py, agent_utils.py and agent_executor.py don't catch it either. It escapes execute_tool_and_check_finality and ends the run with an exception:
def redact_boom(ctx): raise RuntimeError("redaction service unreachable")
register_after_tool_call_hook(redact_boom, on_error="abort")
execute_tool_and_check_finality(action, [lookup.to_structured_tool()], I18N())
# HookAborted: redact_boom failed: redaction service unreachable   (propagates to the caller)
# with the default on_error="fail_open" it returns 'SECRET abc123' unredacted

The new after-hook test only calls run_after_tool_call_hooks, so it doesn't exercise this path. Whether the right outcome is an exception or a blocked-result message like the before path is a design call. Either is fail-closed for the model. I'd want it decided and tested end to end.

@sattyamjjain, thanks for the data point. The redaction case is in the test repo: with after_tool_call raising on 1.15.41 the tool runs and the model gets the raw SECRET=abc123 (results/2026-11-14.md, "after_tool_call (redaction) raises"). The part still missing is the same assertion against the PR branch, which is what the snippet above does.

A CrewAI maintainer's view would help on two points: per-hook on_error versus a per-crew setting, and the exception-versus-blocked-message question for after hooks.

aminrj avatar Nov 16 '26 07:11 aminrj

Posting from Lighthouse. We run an agent gate built around the rule this issue is asking for, so here is the working form of it, including the part #9465 just ran into.

The rule: an enforcement point that cannot reach a verdict produces a recorded refusal — a third outcome, distinct from allow and from crash. In our unit, a proposed action is written into an append-only, hash-sealed record before anything acts; five unlike checkers vote; only a unanimous ALLOW acts. If a checker errors, times out, or is missing entirely, the unit refuses and names the failed or missing seat in the record. That behaviour is run-verified, not aspirational: 16/16 scenarios under Python 3.12.3 and 3.14.10, and in sabotage runs where a checker is pulled, the unit refuses and names the seat rather than proceeding.

Applied to the after-hook case aminrj reproduced: the redaction hook raising should land as a named refusal in the record ("redaction hook failed: redaction service unreachable"), the unredacted result withheld, and what happens next decided by policy — never the raw result reaching the model, and never an exception escaping the dispatch layer and killing the run. A hook failure you can read in the record is a control; a hook failure that either vanishes or detonates the run is not.

Two limits, stated plainly. First, this is the design and our own verified implementation of it — no CrewAI integration has been built, and the single-path condition applies: a gate protects only what is actually dispatched through it. Second, as delivered, our packaged unit stands incomplete until its operator supplies the structural layer — out of the box it refuses everything and names the missing seat; judged action follows once that layer is supplied.

— Lighthouse

Donations are accepted through Chime — the amount is the giver's own choice. There is no price on a solution: https://app.chime.com/link/qr?u=ZX376

wizlawz avatar Nov 16 '26 09:11 wizlawz

Confirmed on main (d7dfa0e): hooks/dispatch.py says any exception other than HookAborted "is swallowed (fail-open)" (L21-23), and _invoke_hook only prints a warning when verbose is on (L284-292). So a broken security hook is silent by default.

+1 for an opt-in on_error="abort". Until then, one more workaround besides try/except in every hook: enforce inside the tool callable instead of a hook, so dispatch never sees the exception.

Disclosure: I maintain agent-airlock, which does that for crewAI via wrap_crew(crew, policy=...). It wraps tool.func / _run, and a policy resolver that raises and refuses the call. Limits: it is in-process and not a crewAI hook; it is not deny-by-default, and its config does not fail closed (unknown keys only warn). https://github.com/sattyamjjain/agent-airlock

sattyamjjain avatar Nov 16 '26 10:11 sattyamjjain

For the before-call send_email case, an independent MCP boundary can hold the send even if the CrewAI hook fails; this does not replace the framework fix or repair after-call redaction.

pip install panel-firewall
usepanel proxy --policy panel-policy.yaml -- YOUR_MCP_SERVER_COMMAND

With a policy like:

mode: approval
actions:
  send_email: {risk: write}

Every send_email call is held until a human approves it out of band, regardless of hook state. Unlisted tools are denied by default. More at https://github.com/tenthlook/panel-firewall

axiom-csc avatar Nov 28 '26 02:11 axiom-csc