/aws:strands-steering-hooksfrom aws
Strands Agents (`strands-agents` Python SDK): steer, not just observe, an agent run at runtime. Block or redirect tool calls, rewrite tool args, override results, retry the model, gate on human approval, inject per-turn context, or nudge the model back on track. Also scaffolds a hook, intervention or steering handler and introspects which hook events the installed SDK exposes. Use for Strands hooks, interventions, steering, guardrails, human-in-the-loop, tool approval, PII redaction, retries or agent observability. Triggers on: HookProvider, @hook, register_hooks, BeforeToolCallEvent / AfterToolCallEvent / BeforeModelCallEvent / AfterModelCallEvent / BeforeInvocationEvent, cancel_tool, selected_tool, InterventionHandler, Agent(interventions=...), LLMSteeringHandler, SteeringHandler, strands.vended_plugins.steering, event.interrupt(), multi-agent node hooks (Graph / Swarm, BeforeNodeCallEvent, cancel_node), BidiAgent streaming hooks, StrandsTelemetry, "scaffold a Strands hook".
Ships in aws. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them; scripts run unread.
Strands lets you intercept an agent's lifecycle and change what it does mid-run, not merely watch it. This skill covers the current (2026), source-verified way to do that.
⚠️ The SDK ships weekly and renames things. Your training memory is likely stale (e.g. the events were once
*InvocationEvent; steering was onceexperimental). Before writing code, pin the facts to the installed version:python scripts/introspect_strands_hooks.pyIt prints the installed
strands-agentsversion, every hook event with its writable fields, theHookOrderconstants, and whether steering lives at the stablestrands.vended_plugins.steeringor only the deprecatedstrands.experimental.steering. Trust its output over this document if they disagree.
"Steering hooks" is an umbrella for three stacked tiers. Pick the lowest tier that expresses your intent cleanly — higher tiers are sugar over the same events.
Raw Hooks mutate writable event fields directly strands.hooks Agent(hooks=[...])
│ maximal control, no decision typing
▼
Interventions typed actions: Proceed/Deny/Guide/ strands.interventions Agent(interventions=[...])
│ Confirm/Transform — ordered, short-circuit (STABLE, Py + TS)
▼
Steering LLM- or code-driven contextual guidance strands.vended_plugins Agent(plugins=[...])
"steer, don't block" (Guide → retry) .steering (STABLE, Py)
@hook / HookProvider. (If you already
use OpenTelemetry, prefer StrandsTelemetry for standard spans over hand-rolled hook tracing.)Deny / Confirm). Stable, composable, Python + TypeScript. Default choice for guardrails.LLMSteeringHandler for natural-language rules; SteeringHandler subclass
for code). This is the "steer, don't block" tier.Rule of thumb: anything that must be unignorable belongs in a hook/intervention, never the system prompt — the model can reason around prose but never sees an interception.
Before writing any hook, confirm three things: (1) policy or adaptation? — a hard rule
→ Intervention Deny/Confirm; a "you're drifting, retry" nudge → Steering Guide. (2)
must it be unignorable? — yes → hook/intervention, not the system prompt. (3) does it
hold per-request state? — keep that state in event.invocation_state, never on self
(see anti-patterns #3).
from strands import Agent
from strands.hooks import BeforeToolCallEvent, HookProvider, HookRegistry, HookOrder
# 1. Bare typed function — event type inferred from the annotation
def log_tool(event: BeforeToolCallEvent) -> None:
print("calling", event.tool_use["name"])
agent = Agent(hooks=[log_tool])
# 2. HookProvider — bundle related callbacks (the workhorse)
class Guard(HookProvider):
def register_hooks(self, registry: HookRegistry, **kwargs) -> None:
registry.add_callback(BeforeToolCallEvent, self.check, order=HookOrder.DEFAULT)
def check(self, event: BeforeToolCallEvent) -> None: ...
agent = Agent(hooks=[Guard()])
# 3. Plugin + @hook — shareable/distributable bundle (also auto-registers @tool, init_agent)
from strands.plugins import Plugin, hook
class GuardPlugin(Plugin):
name = "guard"
@hook
def check(self, event: BeforeToolCallEvent) -> None: ...
agent = Agent(plugins=[GuardPlugin()])
Runtime registration: agent.hooks.add_hook(Guard()) or
agent.hooks.add_callback(BeforeToolCallEvent, fn). (Too late for AgentInitializedEvent,
which already fired during construction — pass it via hooks= instead.)
This table is how you steer with raw hooks. Each lever is one writable field on one
event; mutate it inside the callback and the SDK reads it back. Mutating any other field
raises AttributeError.
Event (from strands.hooks import …) | Fires | Writable levers → effect |
|---|---|---|
AgentInitializedEvent | once, post-construction | — (seed event.agent.state / system prompt in place) |
BeforeInvocationEvent | start of each agent(...) | messages (rewrite/redact input) · cancel (str/True → abort request) |
AfterInvocationEvent | end of request (reverse order) | resume (feed new input → agent loops again) — result is read-only |
MessageAddedEvent | every message appended | — (observe only; highest-frequency event) |
BeforeModelCallEvent | before each model call | cancel (skip this model call) — also mutate messages/tool_specs to shape the request |
AfterModelCallEvent | after each model call (reverse) | retry (True → re-run the model call) |
BeforeToolCallEvent | before each tool call | cancel_tool (block, send msg to model) · selected_tool (swap impl) · tool_use (rewrite name/input) · event.interrupt(...) (HITL) |
AfterToolCallEvent | after each tool call (reverse) | result (override ToolResult the model sees) · retry (True → re-run the tool) |
Multi-agent (graphs/swarms, also in strands.hooks): BeforeNodeCallEvent (cancel_node,
event.interrupt(...)), AfterNodeCallEvent, Before/AfterMultiAgentInvocationEvent,
MultiAgentInitializedEvent.
Every event except AgentInitializedEvent/MessageAddedEvent carries invocation_state —
a per-request mutable dict (seeded by agent("q", user_id="u1", db=conn)), the right place
for cross-hook coordination and non-serializable per-request objects.
HookOrder: SDK_FIRST=-100, INTERVENTION_OUTPUT=-90, DEFAULT=0, INTERVENTION_INPUT=90,
SDK_LAST=100 (lower runs first; After* events reverse order within each group).
Most levers are one-liners (mutate the field from the table). The only pattern with
caller-side control flow is interrupt + resume. event.interrupt(name, reason=None) pauses
the run and returns the caller-supplied response value (whatever you placed in
interruptResponse.response — compare against that exact value/type):
def approve(event: BeforeToolCallEvent): # Agent(hooks=[approve])
if event.tool_use["name"] == "issue_refund":
answer = event.interrupt("refund", reason=event.tool_use["input"]) # pauses here
if answer != "APPROVE":
event.cancel_tool = "Refund not approved."
result = agent("refund order 7")
while result.stop_reason == "interrupt": # caller drives the resume loop
responses = [{"interruptResponse": {"interruptId": i.id, "response": ask_human(i)}}
for i in result.interrupts]
result = agent(responses)
Read references/recipes.md in full before writing any other
steering hook (block a tool, rewrite args, override/retry a result, tool budget,
debounce/loop-break, dynamic tool filtering, PII redaction, dry-run tool swap, autonomous
resume, observability). Do not reconstruct these from memory — the bookkeeping (counter keys,
HookOrder, streaming caveats) lives only there. Skip the file only for a one-liner the table
already covers.
Return a typed action instead of mutating fields. Composable, ordered, short-circuiting.
from strands import Agent, InterventionHandler
from strands.interventions import Proceed, Deny
from strands.hooks import BeforeToolCallEvent
class ToolPolicy(InterventionHandler):
name = "tool-policy"
# on_error: "throw" (default) | "proceed" (fail-open) | "deny" (fail-closed)
def before_tool_call(self, event: BeforeToolCallEvent, **kwargs):
if event.tool_use["name"] in BLOCKED:
return Deny(reason="Not permitted here.")
return Proceed()
agent = Agent(interventions=[ToolPolicy()])
Actions: Proceed, Deny, Guide(feedback=...), Confirm(...), Transform(apply=...).
Lifecycle methods: before_invocation, before_tool_call, after_tool_call,
before_model_call, after_model_call. Deny/denied-Confirm short-circuit; Guide
actions accumulate across handlers. Vended: from strands.vended_interventions import HumanInTheLoop, CedarAuthorization.
Read references/interventions-and-steering.md in
full before implementing any InterventionHandler OR SteeringHandler — the
action-compatibility matrix (which action is valid on which event), on_error semantics, the
two non-interchangeable Guide types, LedgerProvider, and cost notes are there and easy to
get wrong from memory.
Instead of blocking a wrong move, Guide the model with context and let it retry. In Strands' own published benchmark, steering scored 100% accuracy vs 82.5% (prompt instructions) and 80.8% (graph workflows) over 3,000 runs (vendor-reported — treat as directional, not independently replicated).
from strands import Agent
from strands.vended_plugins.steering import LLMSteeringHandler # NOT experimental.steering
handler = LLMSteeringHandler(system_prompt="Renewals ≤30 days; never renew recalled books; "
"guide the agent to retry if a rule is violated.")
agent = Agent(tools=[renew_book], plugins=[handler]) # note: plugins=, not hooks=
Actions are Proceed/Guide/Interrupt (Pydantic, reason required — different
classes from the intervention actions). LLMSteeringHandler runs a fresh isolated agent
per evaluation (a real per-tool-call cost — gate it or prefer a SteeringHandler subclass
for cheap, rule-based checks). Override steer_before_tool / steer_after_model; context
comes from LedgerProvider (tool-call history). The full API + a SteeringHandler subclass
are in the same reference flagged above — read it before subclassing.
AttributeError at runtime. Only the table's levers
are writable; e.g. AfterInvocationEvent.result is read-only (only resume is).InterruptException is caught; any other exception
aborts the whole run. Wrap external calls in try/except and decide fail-open vs
fail-closed explicitly (guardrails especially).HookProvider/handler instance across concurrent requests. Instance
attributes leak across users. Build per request (as this repo's agent/main.py does) or
keep per-request state in invocation_state, not self.event.agent.messages in BeforeInvocationEvent — the new turn isn't there
yet. Read/write event.messages.retry=True while streaming — chunks from the discarded attempt were already emitted;
make stream consumers retry-aware.resume/retry loops with no counter → infinite loop. Always gate with a counter in
invocation_state or agent.state.strands.experimental.steering → DeprecationWarning; use
strands.vended_plugins.steering.async def on AgentInitializedEvent → ValueError at registration (it's sync-only).Guide(feedback=...) with steering Guide(reason=...) — they
are different, non-interchangeable types.Full catalog with symptoms/causes/fixes: read
references/anti-patterns.md.
references/event-catalog.md — read in full before relying
on any event's exact attributes or writable fields: every event (single-agent, multi-agent,
bidi), the steering levers, lifecycle order, and the *InvocationEvent → *CallEvent
migration map.references/interventions-and-steering.md —
read before building an InterventionHandler or SteeringHandler (see trigger above): full
APIs, action-compatibility matrix, on_error, LedgerProvider, cost notes.references/recipes.md — read before writing a non-trivial
steering hook: copy-paste production hooks (HITL, PII redaction, tool budget, debounce,
dynamic tool filtering, dry-run swap, autonomous resume, multi-agent node guard, observability).references/anti-patterns.md — read in full before shipping
any hook: the failure-mode catalog (symptom → cause → fix); #2 (a raised hook aborts the
whole run) is catastrophic if missed.Do NOT load any reference for a single writable-field tweak the steering-levers table already covers — load on demand only at the decision points flagged above.
scripts/introspect_strands_hooks.py — introspect the installed SDK (run first).scripts/scaffold_steering.py — generate a correct skeleton:
python scripts/scaffold_steering.py {hook|intervention|steering|plugin} > my_handler.py.references/anti-patterns.md (opens in a new tab)references/event-catalog.md (opens in a new tab)references/interventions-and-steering.md (opens in a new tab)references/recipes.md (opens in a new tab)scripts/introspect_strands_hooks.py (opens in a new tab)scripts/scaffold_steering.py (opens in a new tab)What SKILL.md sets; muted values are Claude Code's defaults
Other plugins' skills for the same job
npx claudepluginhub tomaspalsson/flow --plugin aws6 skills in this plugin
/agui-strandsBuild or debug generative-UI chat apps on the AG-UI × Strands × Bedrock AgentCore × Vercel AI SDK (useChat) stack. Use WHEN: scaffolding an ag_ui_strands agent server (StrandsAgent, @tool, BedrockModel, EventEncoder, RunAgentInput, /invocations, /ping, 0.0.0.0:8080, arm64); writing the createUIMessageStream bridge (RUN_STARTED→start-step, TOOL_CALL_RESULT→tool-output-available, start/finish envelope, SSE buffer flush); building generative-UI card renderers (useChat, dynamic-tool parts, tool-input-available, tool-output-available, AI SDK v5/v6); deploying to Bedrock AgentCore Runtime (InvokeAgentRuntime, runtimeSessionId, ECR, OpenNext streaming, Terraform); or debugging: blank chat bubble, tool chip spins forever, text part not found, agent forgets context after message 1, frozen pane, runtimeSessionId length errors, manifest-list/image-not-found on deploy./aws-exploreToken-efficient AWS resource exploration during debugging. Use when: (1) debugging live AWS resources — S3 access issues, DynamoDB query patterns, Bedrock/AgentCore failures, (2) the user asks what's in their AWS account, (3) you need to understand the shape/config of AWS resources before making changes. Covers S3, DynamoDB, and Bedrock/AgentCore. Do NOT use for: creating/modifying AWS resources (use sst skill), deploying agents (use strands-agentcore skill), or general AWS documentation questions. Trigger keywords: s3, bucket, dynamodb, table, bedrock, agentcore, aws, 403, access denied, describe, explore, scan./aws-lambda-microvmsBuilds, runs, debugs, and operates applications on AWS Lambda MicroVMs — Firecracker-isolated, snapshot-resumable serverless compute environments running inside a container with up to 8 hr lifetimes. Applicable when workloads need strong isolation between tenants, isolated serverless compute, sandbox compute, or secure multi-tenant execution. Also suited for AI/agent code-execution sandboxes, interactive code playgrounds and notebooks (Jupyter, REPLs, dev environments running user-supplied code), reinforcement-learning environments, multi-tenant CI executors and build runners, sessionful game or simulation servers, or isolated security scanners. Also applicable when the workload needs long-lived sessions, a real port-listening server (gRPC, WebSocket, custom TCP protocols), state preserved across periods of inactivity (suspend/resume), container-level access (FUSE, eBPF, custom syscalls), or session-affine routing./sstBuild and deploy full-stack applications on AWS using SST v3 (Ion). Use whenever the user mentions SST, Serverless Stack, sst.config.ts, sst dev, sst deploy, or builds serverless TypeScript apps on AWS. Also trigger on imports like `import { Resource } from 'sst'`, `sst.aws.*` components, or Lambda + API Gateway + DynamoDB + S3 patterns. Covers component selection, resource linking, secrets, deployment stages, CI/CD, cost optimization, and troubleshooting./strands-agentcoreBuild production-quality AI agents using AWS Strands Agents SDK and deploy them to Amazon Bedrock AgentCore. Use this skill whenever the user mentions Strands agents, Bedrock AgentCore, AgentCore Runtime, AgentCore Identity, Bedrock Identity, workload identity, MCP servers on AWS, agent deployment to AWS, or building AI agents with Python on AWS. Also trigger when you see imports like `from strands import Agent`, `from bedrock_agentcore`, `from strands.models import BedrockModel`, or discussions about OAuth/auth in agent contexts, agent-to-user authentication flows, or deploying agents with identity providers (Google, GitHub, Cognito, Okta). This skill covers the full lifecycle: agent creation, tool design, Bedrock Identity with programmatic OAuth (custom auth URLs, workload identities), MCP server patterns, multi-agent orchestration, and production deployment with observability.