Docs Learn
Tools and agents
A tool is a function from a case class to an effect. The tool runner sends your tools to the model, runs the ones it calls, and keeps going until the model is done.
You will learn
- How to define a tool with
Tool - How to run an agent loop with
toolRunner, as one result or as a stream of events - How to put an approval gate in front of a tool that spends money
- How a run ends, and why that is a value, not an exception
- How to test an agent with no network
Define a tool#
The tool's argument schema is derived from the case class, sent to the API as a strict tool, and the arguments
are decoded before your function runs. The function may return a String or a case class, in
IO:
final case class GetWeather(@description("City name") city: String)
val weather = Tool("get_weather", "Current weather for a city") { (in: GetWeather) =>
weatherService.lookup(in.city) // IO[String], IO[SomeCaseClass], ...
}
val runner = client.messages.toolRunner(List(weather))
runner.run(request) // IO[RunResult]: the final reply, the transcript, total usage, why it stopped
runner.events(request) // Stream[IO, RunEvent]: text deltas, tool starts and results, as they happen
run waits for the end of the run; events shows you what happens while it happens.
How the runner behaves#
- Tool calls of one turn run concurrently, and their results go back in order in one message.
- A tool that throws, or gets bad arguments, becomes an error result the model can react to.
RunnerConfigadds an approval gate (withBeforeTool), an iteration limit and request hooks.- How a run ended is a value (
Completed,MaxIterations,Refused,MaxTokens,Aborted), not an exception.
A complete agent#
The WeatherAgent example has two tools. One only reads; the other books a table, which costs money,
and says so in its description:
final case class GetWeather(@description("City name, e.g. Brussels") city: String)
final case class Weather(city: String, celsius: Double, conditions: String)
final case class BookTable(
restaurant: String,
@description("ISO date, e.g. 2026-12-24") date: String,
guests: Int
)
object Tools {
// A tool is a function from a case class to an effect. The argument schema is derived from the case
// class, sent to the API as a strict tool, and the arguments are decoded before the function runs.
val weather: Tool[IO] =
Tool("get_weather", "Current weather for a city")((in: GetWeather) =>
IO.pure(Weather(in.city, 7.5, "light rain"))
)
val bookTable: Tool[IO] =
Tool("book_table", "Books a restaurant table. Costs money; only call when the user asked for a booking.") {
(in: BookTable) =>
IO.pure(s"Booked ${in.restaurant} on ${in.date} for ${in.guests}.")
}
}
The agent caps the run at ten iterations, checks every booking in withBeforeTool before it runs, and
prints the run's events as they arrive. The last event, RunEvent.Finished, carries how the run
stopped:
/** An agent loop: the model calls tools until it can answer. Prints what happens as it happens. */
object WeatherAgent extends IOApp.Simple {
def run: IO[Unit] = Anthropic4s.fromEnv[IO].use(agent)
/** The agent itself, for any client; `Traced` runs the same code with tracing switched on. */
def agent(client: AnthropicClient[IO]): IO[Unit] = {
val request = MessageRequest(
Model.ClaudeOpus5_5,
maxTokens = 64000,
MessageParam.user(
"Should I eat outside in Brussels tonight? If not, book Chez Leon for two on 2026-12-24."
)
).withThinking(ThinkingConfig.adaptive)
// If a safety classifier declines the request, let the API retry on a fallback model.
.withFallbacks(Fallbacks.Default)
val config = RunnerConfig
.default[IO]
.withMaxIterations(10)
.withRequestOptions(RequestOptions.default.withBetas(Beta.ServerSideFallback))
// An approval gate: anything that spends money is checked before it runs.
.withBeforeTool { call =>
if (call.name == "book_table")
IO.println(s"\n[approval] booking requested: ${call.input.asJson.noSpaces}")
.as(ToolDecision.Allow)
else IO.pure(ToolDecision.Allow)
}
client.messages
.toolRunner(List(Tools.weather, Tools.bookTable), config)
.events(request)
.evalMap {
case RunEvent.Model(_, StreamEvent.ContentBlockDelta(_, Delta.Text(text))) => IO.print(text)
case RunEvent.ToolStarted(call) =>
IO.println(s"\n[tool] ${call.name} ${call.input.asJson.noSpaces}")
case RunEvent.ToolFinished(_, result) => IO.println(s"[tool] -> ${result.text}")
case RunEvent.Finished(result) =>
// How the run ended is a value: a refusal or a token limit is handled here, not caught.
result.stop match {
case RunStop.Completed =>
IO.println(s"\n\ndone in ${result.iterations} turns, ${result.usage.show}")
case RunStop.Refused(_) => IO.println("\nThe model declined.")
case other => IO.println(s"\nStopped early: $other")
}
case _ => IO.unit
}
.compile
.drain
}
}
The overview page shows what this run printed against the live API, and Tracing shows the same code with spans switched on.
Testing your agents#
anthropic4s-testkit has a scripted model that needs no network. List the replies, run your real
tools and runner against it, then inspect what your code sent:
for {
model <- ScriptedModel.of[IO](Replies.toolUse("get_weather", Json.obj("city" -> "Ghent".asJson)), Replies.text("Rainy."))
result <- model.toolRunner(List(weather)).run(request)
sent <- model.requests // inspect what your code sent
} yield assertEquals(result.text, "Rainy.")
Recap
Tool(name, description)((in: A) => ...)derives the arguments fromA.client.messages.toolRunner(tools), thenrunfor the result oreventsfor the stream.RunnerConfigholds the approval gate and the iteration limit.- Test with
ScriptedModel, no network needed.
Every snippet on this page is copied, character for character, from the
anthropic4s repository: its README, docs/play.md or examples/,
which compiles with the build.