AWS Builder Center

Agents for Humans: Strands hooks as a runtime policy gate (and two other surfaces worth your time)

cancel_tool, invocation_state, the BeforeToolCallEvent naming trap, structured_output as a type boundary, and a Graph where most nodes have no LLM at all.

Series: Standing Order — Agents for Humans Hackathon (3 articles)

  1. 2
    Agents for Humans: Strands hooks as a runtime policy gate (and two other surfaces worth your time) This article

Agents for Humans: Strands hooks as a runtime policy gate (and two other surfaces worth your time)

Field notes from building Standing Order for the AWS Agents for Humans Hackathon, part 2 of 3.
Most Strands Agents projects I've read stop at  Agent(model, tools=[...])  plus a handful of  @tool  functions. That's the quickstart surface. The three surfaces below are past the quickstart, and each one carried a load-bearing part of my hackathon entry: hooks,  structured_output , and the multiagent Graph.

1. Hooks: turning "please don't" into "physically can't"

My product's invariant is one sentence: no tool call can exceed the scope of the standing order that authorized it. You cannot enforce that in a system prompt. A prompt is a request; I needed a wall.
Strands hooks are an event system that intercepts the agent loop. The event I needed fires right before tool execution:
from strands.hooks import BeforeToolCallEvent, HookProvider, HookRegistry

class PolicyGate(HookProvider):
def register_hooks(self, registry: HookRegistry, **kwargs):
registry.add_callback(BeforeToolCallEvent, self.enforce_scope)

def enforce_scope(self, event: BeforeToolCallEvent):
tool_name = event.tool_use["name"]
rule_id = event.invocation_state.get("authorizing_rule_id")
rule = self.rules.get(rule_id) if rule_id else None
if rule is None or rule.status != "approved" or tool_name not in rule.scope:
event.cancel_tool = f"BLOCKED: {tool_name} — authorizing rule {rule_id} scope={rule.scope if rule else None}"
self.store.incr("blocked_calls")
self.store.log_blocked(tool_name, rule_id, ...)
Three mechanics made this work, and none of them were obvious from a skim:
  •  cancel_tool  cancels before execution. Setting it to a string turns the tool result into an error carrying your message. The tool function never runs — my tests assert the database is untouched after a blocked call.
  •  invocation_state  is the context channel. Extra kwargs you pass at the call site ( agent.tool.categorize_expense(..., authorizing_rule_id="RULE-0031") ) arrive in  event.invocation_state . That's how the authorizing rule travels from the orchestrator to the gate without touching the tool signature.
  • Hooks fire on direct tool calls too.  agent.tool.x(...)  with  model=None  goes through the same gate as model-initiated calls. My replay path executes rules deterministically, and every one of those calls is still inspected.
The naming trap: hook event class names changed across SDK versions. Older docs and blog posts reference  BeforeToolInvocationEvent ; in the version I pinned (strands-agents 1.53.0) that class does not exist. I burned zero hours on this only because my plan said "never trust remembered names — check the installed version first":
uv run python -c "import strands.hooks as h; print([n for n in dir(h) if 'Tool' in n])"
# ['AfterToolCallEvent', 'AfterToolsEvent', 'BeforeToolCallEvent', 'BeforeToolsEvent']
Thirty seconds of  dir()  beats an afternoon of AttributeError.
There's a reproduction script in the repo ( scripts/demo_blocked_call.py ) and an API flag that pushes one out-of-scope call through a real agent so the demo shows an actual block, not a mock: the counter increments, the reason lands in a log table, and the UI's Blocked tab renders it in red.

2. structured_output: the LLM proposes, the type system disposes

When the human answers a queue item, an LLM turns that single answer into a reusable rule candidate. Free-text parsing here would have been a disaster — the rule spec is what the policy engine compiles and the gate enforces, so it has to be exactly right or not exist.
 Agent.structured_output(RuleSpecDraft, prompt)  forces the model's answer through a Pydantic model:
class RuleSpecDraft(BaseModel):
sentence: str
conditions: list[Condition] # field/op/value triples, AND-only
scope: list[ToolName] # Literal of exactly five tool names
actions: list[ToolAction]

@model_validator(mode="after")
def actions_within_scope(self): ...
Because  ToolName  is a  Literal , the model cannot invent a sixth tool. Because the validator runs at the boundary, a draft whose actions exceed its own scope never exists as an object. Note what the draft lacks: id, version, status, effective date. The system assigns those; the model can't promote its own candidate. And there is a deterministic template fallback for the same signature, so the demo survives a Bedrock outage — worth having, as part 3 will show.
Anecdotally, output quality was better than I expected. Given one answer about a ₩42,000 cafe charge on a client-meeting day, Sonnet 4.6 returned: merchant pinned with  eq , amount capped with  lte 42000 , a  has_client_meeting eq true  condition, and a scope of exactly the two tools needed. Narrow by default, which is what the approval gate wants to see.

3. Graph: deterministic pipeline, agent nodes only where they earn it

 strands.multiagent.GraphBuilder  runs a dependency graph with conditional edges. My pipeline is  ingest → match → (act | escalate) → learn , and the trick is that most nodes have no LLM in them. A deterministic node is just a  MultiAgentBase  subclass:
class _DeterministicNode(MultiAgentBase):
async def invoke_async(self, task, invocation_state=None, **kwargs):
self.fn() # mutate the day's context
return MultiAgentResult(status=Status.COMPLETED, results={})
Conditional edges decide the fork —  builder.add_edge(match, act, condition=lambda state: bool(ctx.acts))  — so on a day with no matches the act node genuinely doesn't execute (there's a test asserting it's absent from  result.execution_order ). The 60-day replay runs through this graph in about 1.4 seconds locally, zero model calls, and a  FileSessionManager  on the act agent means a killed and restarted process still remembers its tool-call history.

The shape of the whole thing

The pattern across all three surfaces is the same: put the LLM only where judgment is needed (compiling a rule from a human answer), and put typed, deterministic, testable machinery everywhere else — with hooks as the enforcement layer that holds even when the model does something surprising. 110 tests, including one that replays all 60 days with  socket.socket  monkeypatched to raise. The agent that needs you least is the one whose boundaries you can prove.



Series: Standing Order — Agents for Humans Hackathon (3 articles)

  1. 2
    Agents for Humans: Strands hooks as a runtime policy gate (and two other surfaces worth your time) This article
Any opinions in this article are those of the individual author and may not reflect the opinions of AWS.
Enjoyed reading this content? Let the author know!

Your likes, comments, shares, and saves help creators reach more builders.

Loading recommendations

Loading article