Agent Assurance for your AI Deployment

Test how your agents actually behave across workflows, tools, and actions. Catch failures and vulnerabilities before they ship.

npm install -g @testmuai/rook@latest

Start Free Trial
AIAI Testing

How to Test Strands Agents: Tools, Unit Tests and Evals

How to test Strands Agents: unit test @tool functions and the agent loop with a fake model, check tool arguments and records, and gate CI with Strands Evals.

Published on:

The Strands Agents course states the testing problem in its own words. Lesson 13 on evaluating agents says the same input can produce a different but equally valid response or tool ordering, so assert output == expected doesn't work.

The strands-agents package also ships no public test double for the model, so a unit test has to bring its own. And the code under your tests moves fast: the strands-agents release history on PyPI shows 53 releases uploaded in 2026, the latest being 1.66.0 on 23 November.

The steps below start at the tools and work outward. Every output shown was printed by a run on strands-agents 1.66.0 on 2026-11-25.

Overview

To test Strands Agents, call each @tool as a plain Python function, then run the real agent loop with a fake Model subclass that scripts the tool calls. Assert the tool arguments and the record the run changed, not the reply. Strands Evals then scores many cases in CI.

What Does a Strands Agents Test Suite Cover?

  • Strands @tool functions: A Strands @tool is a plain Python function, so a unit test calls it directly and asserts the return value. The test also asserts the tool spec built from the docstring and type hints, because a docstring edit changes what the model reads.
  • Strands fake model provider: A Strands fake model provider subclasses the Model interface and yields stream events from a fixed script, so the real Agent loop runs your tools between scripted turns. API keys needed: no (the script replaces the model), and every run returns the same result.
  • Strands record checks: A Strands record check reads the stored state a tool changed after the run ends, together with the tool arguments in agent.messages. It catches the right tool called with a wrong argument, a failure that both a reply check and a tool-name check pass.
  • Strands Evals: Strands Evals is a separate open source package, strands-agents-evals, that scores output and trajectory across many cases. Its deterministic evaluators suit CI/CD pipelines, and its run command exits non-zero when a case fails or the overall score falls below a set threshold.
  • Strands OpenTelemetry traces: Strands builds its traces on OpenTelemetry, covering every model call, tool call and event loop cycle. A console exporter shows the spans in a local test, and the metrics on each AgentResult give tool call counts that a test can assert on.
  • Agent Assurance: TestMu AI's Agent Assurance tests an agent that acts before release, when you can invoke it as a command or HTTP endpoint. It derives functional and adversarial scenarios from your code, PRD or spec, confirms records with read-only checks, and offers a 14-day free trial.

What Is Strands Agents?

The Strands Agents SDK is an open source library for building AI agents, introduced by AWS on 16 May 2025. The AWS launch post describes a model-driven approach, puts the project under the Apache License 2.0, and names Amazon Q Developer, AWS Glue and VPC Reachability Analyzer as AWS teams running Strands agents in production.

Per the Strands site index, an agent runs inside your own process, with no hosted control plane. Amazon Bedrock is only the default model provider: Anthropic, OpenAI, Google, Ollama and others work through the same agent code. The harness-sdk repository on GitHub lists MCP, streaming, multi-agent patterns and structured output as built in.

  • Package - pip install strands-agents installs the Python SDK, which needs Python 3.10 or newer; a TypeScript SDK exists beside it.
  • Naming - the docs now call the SDK the Strands Harness SDK, and the old sdk-python repository redirects to harness-sdk. The PyPI package is still strands-agents.
  • Deprecated tools package - the docs' guide to migrating off strands-agents-tools says that community package is deprecated and its tools raise errors at import time, so older tutorials that import it break.

What Should You Test in a Strands Agent?

The Strands agent loop docs describe one rule: invoke the model, run any tool it asks for, invoke the model again with the result, and repeat until it produces a final response. No turn limit applies unless you pass one in the limits argument of the agent call. A test should assert the stop reason it expects: end_turn for a finished answer, or limit_turns when you set a turn limit.

In Strands Agents testing, put exact assertions where behaviour is deterministic and scoring where it is not; the guide to testing non-deterministic AI outputs covers the scoring side. If you also ship Claude agents, the layers match the ones in testing Claude Agent SDK agents, with Strands APIs in place of Claude's.

LayerWhat breaksTestEvidence
@tool functionsTool logic, error strings, or a docstring edit that changes the spec the model readsCall the function directly and assert the generated tool specReturn values and spec fields
Agent loopA tool result that never reaches the model, the wrong stop reason, no turn limitA fake Model subclass that replays scripted turnsModel call count and stop_reason
Tool arguments and recordsThe right tool with a wrong argument, or a reply that claims an effect the run never producedRead the toolUse blocks in agent.messages, then read the recordArgument values and stored state
Multi-agent handoffsAgents passing work back and forth, an exhausted handoff budget, a skipped nodeAssert the Swarm or Graph result fieldsstatus, node_history, execution_order
Behaviour across casesRegressions after a prompt, model or SDK upgradeStrands Evals experiments in CIScores and pass or fail per case
TracesFailures that only show up across a long, multi-tool runAn OpenTelemetry exporter switched on in testsSpans and AgentResult metrics

The Strands FAQ says that when one model response requests several tools, they run concurrently by default, and it recommends a sequential executor when order matters or tools share mutable state. That default needs a test of its own: if two of your tools write the same record, script a turn that requests both and assert the final state.

Step 1: Test Each Strands @tool as a Plain Function

A Strands tool is a Python function with the @tool decorator. According to the Strands custom tools guide, the decorator builds the tool specification from the docstring's first paragraph, its Args section and the type hints, so editing a docstring changes what the model reads.

For every tool, call the function with plain arguments and assert the result, then assert the generated spec, so a renamed parameter or a dropped description fails in review instead of in production. This script ran on 2026-11-25 against strands-agents 1.66.0:

"""Step 1 checks: the @tool as a plain function."""
from strands import tool

ORDERS = {"A-1042": "open"}


@tool
def cancel_order(order_id: str) -> str:
    """Cancel an open order.

    Args:
        order_id: The order to cancel, e.g. A-1042.
    """
    if ORDERS.get(order_id) != "open":
        return f"{order_id} cannot be cancelled"
    ORDERS[order_id] = "cancelled"
    return f"{order_id} cancelled"


print(cancel_order("A-1042"))
print(cancel_order("A-1042"))
spec = cancel_order.tool_spec["inputSchema"]["json"]
assert spec["required"] == ["order_id"]
print("spec check: PASS")
A-1042 cancelled
A-1042 cannot be cancelled
spec check: PASS

The second call shows the tool refusing a repeat cancellation, which is the behaviour to pin down for any tool that writes. Retry safety, permissions and schema design are covered in depth under agent tools, and the model's side of the exchange under tool calling.

Inside an agent, every tool also becomes a method on agent.tool. The Strands tool usage docs give agent.tool.notebook(mode="read", name="ideas") as the example and say to always use keyword arguments, because positional arguments are not supported.

Step 2: Unit Test the Strands Agent Loop With a Fake Model

Strands has no built-in fake model, but it documents the interface every provider implements. The custom model provider guide lists four methods, stream(), update_config(), get_config() and structured_output(), and the events stream() yields, including contentBlockStart carrying a tool name and id, and messageStop carrying a stop reason.

The SDK's own tests take the same route: the MockedModelProvider fixture subclasses Model and returns pre-defined responses in sequence, but it lives in the repository's tests folder and is absent from the installed package. That is a difference from testing OpenAI Agents SDK agents, where the SDK ships a scripted test model you can import.

The fake model below replays a list of turns. A tool turn emits a toolUse block and stops with tool_use; a text turn emits the answer and stops with end_turn.

import json

from strands import Agent, tool
from strands.models import Model


class FakeModel(Model):
    """Replays fixed turns as Strands stream events."""

    def __init__(self, turns):
        self.turns = list(turns)
        self.calls = 0
        self.seen_tools = []

    def update_config(self, **kw):
        pass

    def get_config(self):
        return {"model_id": "scripted"}

    async def structured_output(
            self, output_model, prompt,
            system_prompt=None, **kw):
        raise NotImplementedError
        yield  # pragma: no cover

    async def stream(self, messages, tool_specs=None,
                     system_prompt=None, **kw):
        self.calls += 1
        specs = tool_specs or []
        self.seen_tools = [t["name"] for t in specs]
        turn = self.turns.pop(0)
        yield {"messageStart": {"role": "assistant"}}
        if "tool" in turn:
            name, args = turn["tool"]
            use = {"name": name,
                   "toolUseId": f"t{self.calls}"}
            yield {"contentBlockStart":
                   {"start": {"toolUse": use}}}
            yield {"contentBlockDelta": {"delta": {
                "toolUse": {"input": json.dumps(args)}}}}
            yield {"contentBlockStop": {}}
            yield {"messageStop":
                   {"stopReason": "tool_use"}}
        else:
            yield {"contentBlockStart": {"start": {}}}
            yield {"contentBlockDelta": {"delta": {
                "text": turn["text"]}}}
            yield {"contentBlockStop": {}}
            yield {"messageStop":
                   {"stopReason": "end_turn"}}

The full script, saved as fake_model.py, also holds the cancel_order tool from Step 1, with ORDERS now holding three open orders: A-1042, A-2001 and A-2002. Its test helper builds a real Agent with the fake model, that tool and callback_handler=None so nothing streams to the console, then reads every toolUse block back out of agent.messages. The print lines are trimmed here; the full script printed the output that follows.

def tool_calls(agent):
    out = []
    for m in agent.messages:
        for block in m["content"]:
            if "toolUse" in block:
                tu = block["toolUse"]
                out.append((tu["name"], tu["input"]))
    return out


def run(label, turns, order_id):
    model = FakeModel(turns)
    agent = Agent(model=model, tools=[cancel_order],
                  callback_handler=None)
    result = agent(f"Please cancel order {order_id}")
    reply = str(result).strip()
    calls = tool_calls(agent)
    said_ok = "cancelled" in reply.lower()
    did_ok = ORDERS[order_id] == "cancelled"
    # ... prints model calls, tools seen, tool calls,
    # stop reason, reply, record and both checks ...
    return said_ok, did_ok, calls


# Run 1: the model asks for the tool, then answers.
s1, d1, c1 = run("run 1: calls the tool", [
    {"tool": ("cancel_order",
              {"order_id": "A-1042"})},
    {"text": "Done. Order A-1042 is cancelled."},
], "A-1042")
assert c1 == [("cancel_order",
               {"order_id": "A-1042"})]
assert s1 and d1
print("asserts:      3 checks passed")

The run started by printing the SDK version and the spec the decorator generated, then run 1:

strands-agents 1.66.0
tool spec generated by @tool:
  name: cancel_order
  description: Cancel an open order.
  required: ['order_id']
  order_id: type=string
  order_id doc: The order to cancel, e.g. A-1042.
--- run 1: calls the tool ---
model calls:  2
tools seen:   ['cancel_order']
tool call:    cancel_order({"order_id": "A-1042"})
stop reason:  end_turn
final text:   Done. Order A-1042 is cancelled.
record now:   A-1042 = cancelled
reply check:  PASS
record check: PASS
asserts:      3 checks passed

When I ran it, the model was called twice, once to request the tool and once to answer after seeing its result, and the loop stopped with end_turn. The model is scripted, so this proves the test setup and the loop wiring, not the quality of any real model.

Step 3: Assert Tool Arguments and the Record the Run Changed

A reply check and a tool-name check both trust weak evidence. In run 2 the user asks to cancel A-2002, the scripted model calls cancel_order with A-2001, and then it replies that A-2002 is cancelled. The failure is scripted on purpose, to show which assertion catches it.

# Run 2: the model cancels the wrong order, then
# reports the order the user asked about.
s2, d2, c2 = run("run 2: wrong argument", [
    {"tool": ("cancel_order",
              {"order_id": "A-2001"})},
    {"text": "Done. Order A-2002 is cancelled."},
], "A-2002")
named = [n for n, _ in c2] == ["cancel_order"]
print(f"name check:   {'PASS' if named else 'FAIL'}")
print(f"side effect:  A-2001 = {ORDERS['A-2001']}")
--- run 2: wrong argument ---
model calls:  2
tools seen:   ['cancel_order']
tool call:    cancel_order({"order_id": "A-2001"})
stop reason:  end_turn
final text:   Done. Order A-2002 is cancelled.
record now:   A-2002 = open
reply check:  PASS
record check: FAIL
name check:   PASS
side effect:  A-2001 = cancelled

The reply check passed because the text says cancelled, and the name check passed because the right tool ran. Only the record check failed: A-2002 is still open, and A-2001, an order nobody mentioned, is now cancelled. A reply that reports an effect the run never produced is a form of agent action hallucination, and a read of the record is what exposes it.

  • Arguments - compare each argument value in the toolUse blocks, the way tool_calls() collects them, not only the tool name.
  • Records - read the system of record after the run: the fake store in a unit test, a read-only query in staging.
  • Collateral changes - check that nothing else changed, since run 2 damaged an order the request never named.

Strands Evals has the same trap. Its deterministic evaluators page defines ToolCalled with one required parameter, the tool name, so it would pass run 2. StateEquals, which compares a named environment state with an expected value, is the evaluator the docs recommend for side effects.

Step 4: Test Strands Multi-Agent Handoffs in Swarm and Graph

Each Strands multi-agent pattern exposes different result fields, so each gets its own assertion. Give every agent in the pattern its own fake model, so the handoff order is scripted and the test is repeatable.

  • Agents as tools - passing an agent in another agent's tools list turns it into a tool that accepts an input string and returns the agent's text response, per the Strands docs. Test it as in Step 1, with the inner agent on a fake model.
  • Swarm - the Strands Swarm docs describe agents handing work to one another with no fixed path. max_handoffs defaults to 20, and ping-pong detection stays off until both repetitive_handoff_detection_window and repetitive_handoff_min_unique_agents are positive, for example 8 and 3; when it fires, the swarm returns a FAILED result. Set those limits in tests, then assert result.status and the order in result.node_history.
  • Graph - a Graph gives deterministic control over which agent runs when, in acyclic or cyclic topologies. Assert result.status and result.execution_order against the order you designed, and give each cycle a test that proves it exits.

Agents can also work across processes: Strands documents serving and calling agents over the Agent2Agent (A2A) protocol and connecting to MCP servers for tools. How those two protocols divide the work is explained in A2A vs MCP. Handoff failure patterns that apply beyond one framework are in multi-agent testing.

Step 5: Evaluate Strands Agents With Strands Evals in CI

Strands Evals is a separate package for Strands Agents evaluation, installed with pip install strands-agents-evals and meant for use both before release and after it. The Strands Evals overview builds an evaluation from cases, a task that runs the agent and one or more evaluators. On PyPI the package reached 1.12.1 on 24 November 2026, under Apache-2.0.

  • Deterministic evaluators - exact checks on outputs, trajectories and environment state with no LLM judge, which the docs describe as a good fit for regression testing and CI/CD pipelines.
  • OutputEvaluator - scores a response against a rubric you write, using a model as the judge; read LLM as a judge before trusting those scores in a gate.
  • TrajectoryEvaluator - scores the sequence of tool calls, with helpers for exact, in-order and any-order matching plus an LLM judge. The same match ideas appear in testing a LangChain or LangGraph agent.
  • ToolSimulator - per the tool simulation docs, an LLM generates a schema-valid response each time the agent calls a simulated tool. That saves writing fixtures but costs a model call per tool call, so it does not replace the fake model from Step 2.
  • Chaos testing - ChaosPlugin injects tool timeouts, network errors and corrupted responses without changing agent code, which tests the error paths Step 1 cannot reach.
  • Red teaming - the red teaming module runs attack strategies such as Crescendo, GOAT and PAIR against the agent and scores whether each breached its guardrails; background is in red teaming LLMs.

How Do You Gate CI on Strands Evals Results?

Run experiments with strands-evals run and let its exit code fail the build. The strands-evals run reference sets the rule with --fail-on: any (the default) exits non-zero on any failed case, none always exits 0, and threshold:0.X exits non-zero when the overall score falls below the threshold.

The reference's regression example, trimmed to the flags a gate needs:

strands-evals run experiments/regression.json \
  --agent my_pkg.agents:build_agent \
  --fail-on threshold:0.8 \
  -o reports/regression.json

Keep deterministic evaluators in the per-commit job, and run judge-based evaluators nightly or before a release, since every judge call is a model call whose score can vary between runs.

How Do You Trace Strands Agent Runs With OpenTelemetry?

Strands builds its traces on OpenTelemetry, and the Strands traces guide says they cover every model interaction, retriever call, tool call and event loop cycle. Locally, the console exporter prints spans; in CI, setup_otlp_exporter() sends them to the collector set in OTEL_EXPORTER_OTLP_ENDPOINT.

from strands.telemetry import StrandsTelemetry

strands_telemetry = StrandsTelemetry()
strands_telemetry.setup_console_exporter()

Assertions do not need the spans. The Strands metrics docs put call counts, success rates and execution times for each tool on the AgentResult every invocation returns, and this check read them after a fake-model run on 2026-11-25:

"""Read tool metrics from AgentResult after a fake run."""
from strands import Agent
from fake_model import FakeModel, cancel_order

model = FakeModel([
    {"tool": ("cancel_order", {"order_id": "A-1042"})},
    {"text": "Done. Order A-1042 is cancelled."},
])
agent = Agent(model=model, tools=[cancel_order],
              callback_handler=None)
result = agent("Please cancel order A-1042")
tm = result.metrics.tool_metrics
print("tools used:", list(tm.keys()))
m = tm["cancel_order"]
print("calls:", m.call_count, "ok:", m.success_count)
assert m.call_count == 1
print("metrics check: PASS")
tools used: ['cancel_order']
calls: 1 ok: 1
metrics check: PASS

A call-count assertion like this one catches a loop that calls a write tool twice. Span naming, sampling and what to keep for debugging are covered in AI agent tracing.

Testing Strands Agents With Agent Assurance

Steps 1 to 5 check your code against expectations you wrote. Before a release you also want a staged run judged on what it changed, which is what TestMu AI's Agent Assurance does for agents that act. It tests before you ship and blocks nothing at runtime, unlike Strands guardrails, which screen what reaches the model and what it returns while the agent runs.

Agent Assurance does not need to know the agent is built with Strands. It invokes an agent through a profile, and a Strands agent is ordinary Python, so wrap it in a small command-line script or an HTTP endpoint. The profiles and hooks guide covers the hook scripts that sign in, send each turn and collect evidence.

  • Scenarios from your sources - scenarios are derived from your code, PRD or spec, and rook generate produces the functional and adversarial classes by default. One adversarial category is prompt_injection; prompt injection explains the attack against an agent with tools.
  • Records confirmed read-only - if the agent reports that it cancelled an order, a judge checks the orders database with a read-only query through a tool you approve. The criterion might read "The order is marked cancelled in the orders database after the run." Without a read-only check, the criterion is never a pass.
  • Staging only - point the profile at staging, because the agent's own writes during a run are real.

Most eval and observability tools score what your agent said and recorded. Agent Assurance checks what the run changed, and reports what it could not verify. Run 2 in Step 3 is why that matters for a Strands agent: the reply and the tool name passed, and only the record showed the wrong order cancelled.

The command-line tool is Rook CLI. Its npm route needs Node.js 20 or newer, while Homebrew and the shell installer need no Node. The skill installer, npx @testmuai/rook-skill, adds the skill to a coding agent and needs Node.js 22 or newer.

npm install -g @testmuai/rook@latest
rook --version

To run it in your pipeline, follow Agent Assurance in CI. The trial runs 14 days, carries 4,000 credits, unlocks the Pro features and begins at the Start Trial button in the Agent Assurance web app; the pricing page lists the plans.

Start a 14-day free trial of Agent Assurance by TestMu AI, with 4,000 credits, to test how your AI agents behave across workflows, tools, and actions

Where Should You Start Testing a Strands Agent?

Start with the record. Copy the FakeModel class from Step 2 into your test folder, and for each tool that writes, script one run with the right argument and one with a wrong one, asserting the stored state in both. The strands-agents release history on PyPI shows five minor releases, 1.62.0 to 1.66.0, between 21 October and 23 November 2026, so run that suite on every upgrade before trusting a new version.

When the agent is ready for a staged run, the Agent Assurance quickstart walks through the first profile and suite.

To run your first test, install Agent Assurance with npm install -g @testmuai/rook@latest, or
for a full walkthrough of the product.

Author

...

Samyak Goyal

Blogs: 53

  • Linkedin

Samyak Goyal is a Senior Member of Technical Staff at TestMu AI engineering Kane CLI, the command-line tool that runs browser automation from the terminal, where a flow described in natural language executes in a real Chrome browser and returns pass or fail with shareable proof. He is a backend engineer with 4+ years of experience, previously an SDE at Innovaccer, where he built APIs, introduced Kafka, and cut deployment from weeks to hours. Samyak also builds multi-agent systems, skill-orchestration frameworks, and a personal copilot that indexes 200+ microservice repositories.

Reviewer

...

Sirajuddin Khan

Reviewer

  • Linkedin

Sirajuddin Khan is Vice President of Product Management at TestMu AI, where he drives the company's agentic AI product strategy, building a suite of autonomous agents that includes Agentic Browsers and Agentic Visual Testing and shifting the unit of work from test execution to autonomous outcomes. One of the company's earliest product leaders, he has owned the roadmap for the high-performance execution cloud and grew the cross-browser testing products from early adoption to market leadership. He brings over a decade of experience across SaaS, B2B, and eCommerce, with earlier product roles at Wydr and ShopClues, where his catalog and search work cut delivery SLAs and lifted seller activity. Sirajuddin holds an MBA in Information Technology from Sikkim Manipal University and a B.Tech in Computer Science Engineering from Maharshi Dayanand University.

Add to Google preferred sources

Summarise with AI

Copied to Clipboard!
...

3000+ Browsers. One Platform.

See exactly how your site performs everywhere.

Try it free
...

Write Tests in Plain English with KaneAI

Create, debug, and evolve tests using natural language.

Try for free

Strands Agents Testing FAQs

Did you find this page helpful?

TestMu AI forEnterprise

Get access to solutions built on Enterprise
grade security, privacy, & compliance

  • Advanced access controls
  • Advanced data retention rules
  • Advanced Local Testing
  • Premium Support options
  • Early access to beta features
  • Private Slack Channel
  • Unlimited Manual Accessibility DevTools Tests