anthropic4s
GitHub

Unofficial community project · pre-release

anthropic4s A pure-Scala SDK for the Claude API, built on Cats Effect and fs2.

It talks to the API directly instead of wrapping the Java SDK. No Kotlin runtime, no Jackson version to pin, and nothing for a Play app to override.

Not affiliated with or endorsed by Anthropic. Apache 2.0 · Scala 2.13 · JDK 17+ · not on Maven Central yet.

Trace of one agent run: a tool_runner span of 7.55 seconds holding three messages.create spans and two tool spans.
8
sbt modules, about 7,500 lines of Scala
84
tests, all of them run offline
0
Kotlin or Jackson jars on the default artifact's runtime classpath
2
retries by default, honouring retry-after and x-should-retry
§ 01 / Why it exists

No Kotlin runtime. No Jackson version to pin.

anthropic4s talks to the Claude API directly. It does not wrap the official Java SDK, so it brings neither. What you get instead:

  1. No Kotlin, no Jackson

    The default artifact's runtime classpath has no Kotlin and no Jackson jars. A Play app needs zero dependencyOverrides.

  2. Case classes in, case classes out

    Structured outputs and tool arguments are derived from your types.

  3. A typed agent loop

    Tools are functions; the runner calls them, in parallel, until the model is done.

  4. Streaming as fs2.Stream

    Resource-safe and cancellable. Stopping early closes the connection.

  5. Typed errors, retries and timeouts

    They match the official SDKs. Failures are subtypes of AnthropicError, raised in F.

  6. OpenTelemetry tracing

    Through otel4s. One tree per agent run, a span per request and per tool call.

  7. Play-friendly

    A Future facade, and structured outputs driven by your Play JSON Formats.

Streaming

README.md · Streaming
import anthropic4s.syntax._

client.messages
  .stream(request)
  .textDeltas                       // just the text, piece by piece
  .evalMap(IO.print)
  .compile
  .drain

client.messages.stream(request).finalMessage   // or: stream, and keep only the complete reply

Stopping early (take, cancellation, a timeout around it) closes the connection.

Errors, retries and timeouts

README.md · Errors
client.messages.create(request).recover {
  case e: AnthropicError.RateLimited => s"retry in ${e.retryAfter}"
  case e: AnthropicError.Api         => s"${e.status} ${e.errorType}: ${e.errorMessage} (${e.requestId})"
  case _: AnthropicError.Timeout     => "timed out"
}

Connection errors, timeouts, 408, 409, 429 and 5xx are retried twice with exponential backoff, honouring the server's retry-after and x-should-retry headers. A request is never retried once a response has started.

§ 02 / Quick start

One client, one question.

Every snippet on this page is copied from the repository's README or examples/, which is compiled with the build and was run against the live API.

README.md · Quick start
import anthropic4s._
import cats.effect.{IO, IOApp}

object Hello extends IOApp.Simple {
  def run: IO[Unit] =
    Anthropic4s.fromEnv[IO].use { client =>            // reads ANTHROPIC_API_KEY
      val request = MessageRequest(Model.ClaudeOpus5_5, maxTokens = 16000, MessageParam.user("Why do cats purr?"))
      client.messages.create(request).flatMap(reply => IO.println(reply.text))
    }
}

Anthropic4s.fromEnv[IO] is a Resource: the block inside use runs with an open client, and the connections are closed afterwards, even if it fails. Create one client and share it.

§ 03 / Structured outputs

Ask for a case class and get one back.

The JSON Schema is derived from the type and sent as the response format, so the API guarantees a reply that fits. One derivation yields the schema, the decoder and the encoder, so they cannot disagree.

From a case class

README.md · Structured outputs
import anthropic4s.schema.description

sealed trait Difficulty
object Difficulty { case object Easy extends Difficulty; case object Hard extends Difficulty }

final case class Recipe(
    name: String,
    @description("Total time in minutes") minutes: Int,
    difficulty: Difficulty,
    pairing: Option[String]
)

client.messages.parse[Recipe](request).map(_.value)   // IO[Recipe]

No instance to declare: case classes and sealed traits get a Schema automatically. To avoid deriving it at every use, cache it: object Recipe { implicit val schema: Schema[Recipe] = Schema.derived }.

With Play JSON

README.md · anthropic4s-play-json
object Recipe {
  implicit val config: JsonConfiguration = PlaySchema.configuration
  implicit val format: OFormat[Recipe]   = Json.format[Recipe]
  implicit val schema: Schema[Recipe]    = PlaySchema.derived[Recipe]
}

Add anthropic4s-play-json and pair the schema with your Format. PlaySchema.configuration makes Json.format write a missing Option as null and tag sealed traits with a type field: the shape the schema promises the model will send.

§ 04 / Tools and agents

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.

README.md · Tools and agents
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
  • 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.
  • RunnerConfig adds 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.
One turn, three tool calls, measured in the test suite
tool 1300 ms
tool 2100 ms
tool 3200 ms
the turn300 ms

Results are returned in order, in one message.

The WeatherAgent example, start to finish

examples/…/Agents.scala · the tools
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}.")
    }
}
examples/…/Agents.scala · the agent
/** 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
  }
}
What it printed · the run traced in § 05
[tool] get_weather {"city":"Brussels"}
[tool] -> {"city":"Brussels","celsius":7.5,"conditions":"light rain"}
It's 7.5°C with light rain in Brussels, so eating outside isn't a good idea. I'll book Chez Leon as you asked.
[approval] booking requested: {"restaurant":"Chez Leon","date":"2026-12-24","guests":2}

[tool] book_table {"restaurant":"Chez Leon","date":"2026-12-24","guests":2}
[tool] -> Booked Chez Leon on 2026-12-24 for 2.
I wouldn't eat outside tonight. It's 7.5°C and lightly raining in Brussels.

So I booked a table for two at Chez Leon on 2026-12-24, as you asked. If tonight isn't the 24th and you meant this evening, tell me and I'll book for tonight instead.

done in 3 turns, Usage(in=2123, out=364, cacheWrite=0, cacheRead=0)

A live run against the API on 22 November 2026, claude-opus-5-5. The text is replayed from that run's recorded spans through the example's own printlns.

§ 05 / Observability

An agent run is one trace.

Each API request is a CLIENT span, retries included. An agent run is one tree with a span per request and per tool call. These are Grafana Tempo screenshots of the run above.

The whole run. tool_runner, three messages.create, two tool spans: 6 spans, 7.55 s. The tools took 4.53 ms and 1.51 ms; the rest is the model.
README.md · Tracing
for {
  telemetry <- OtelTelemetry[IO](otel.tracerProvider)
  client     = Anthropic4s.resource[IO](config, telemetry)
} yield client
  • Add anthropic4s-otel4s and pass a telemetry to the client. Nothing else changes.
  • Model, token usage, stop reason and request ids are recorded as gen_ai.* and anthropic.* attributes.
  • With default settings no prompt or reply text is put on a span, and a test asserts it. Content capture is opt-in with ContentMode.Content.
One request span. HTTP status, route, beta flags, stop reason and the request id to quote in a support ticket. The prompt is visible here because this demo opted in to ContentMode.Content.
Model and usage. Requested and served model, the stream flag, time to first chunk and token counts are recorded as gen_ai.* attributes.
§ 06 / From Play

From Play, with Future.

Play code works with Future; the SDK is written against Cats Effect. FutureAnthropic sits between the two, so a Play application never has to touch IO.

README.md · From Play, with Future
@Singleton
class Claude @Inject() (lifecycle: ApplicationLifecycle)(implicit ec: ExecutionContext) {
  private val anthropic = FutureAnthropic.fromEnv()
  lifecycle.addStopHook(() => anthropic.close())

  def ask(question: String): Future[String] =
    anthropic.create(MessageRequest(Model.ClaudeOpus5_5, 16000, MessageParam.user(question))).map(_.text)
}
  • Unlike the Java SDK, this needs no dependencyOverrides: there is no Kotlin runtime and no Jackson module to keep in step with Play's.
  • Starting the client opens no connection, so it is safe in a constructor.
  • A failed call is a failed Future holding an AnthropicError.
  • anthropic.client is the full AnthropicClient[IO] when you want it.
Read the Play guide

Streaming to the browser, tools with Future handlers, structured outputs with your Format.

§ 07 / Testing

Test your agents with no network.

anthropic4s-testkit has a scripted model: you list the replies, run your real tools and runner against it, then inspect what your code sent.

README.md · Testing your agents
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.")

The SDK is tested the same way. Its 84 tests need no network and no API key, including the one that checks no prompt text reaches a span by default.

README.md · Development
sbt test                 # everything, no network and no API key needed
sbt "examples/runMain anthropic4s.examples.Hello"     # needs ANTHROPIC_API_KEY, uses real tokens
sbt prePR                # format, license headers, CI workflow
§ 08 / Modules

Seven artifacts. Most applications need one.

The eighth sbt module is examples, compiled with the build and never published.

ArtifactWhat it is
anthropic4sThe one most applications need: the client on http4s Ember, plus FutureAnthropic
anthropic4s-coreThe client on any http4s Client, the tool runner, the telemetry SPI
anthropic4s-modelRequest and response types with their JSON codecs. No Cats Effect
anthropic4s-schemaSchema[A]: JSON Schema, decoder and encoder from one derivation
anthropic4s-play-jsonStructured outputs and tool arguments from Play JSON Formats
anthropic4s-otel4sOpenTelemetry tracing
anthropic4s-testkitScriptedModel and reply builders for tests

Covered

  • Messages: create, stream, count tokens
  • Tools
  • Structured outputs
  • Batches
  • Files
  • Models

Not yet

  • Bedrock / Vertex / Foundry
  • Managed Agents
  • The Admin API
  • Scala 3
§ 09 / Design notes

Four decisions you will feel as a user.

The API ships new fields and block types constantly. Most of the design is about not breaking when it does.

Forward compatible
Unknown content blocks and stream events are kept and sent back untouched; every object carries unmodeled fields in extras; enums are open (Model.of("..."), StopReason.of("...")). request.withExtra(key, json) sends anything this SDK does not model yet.
Binary compatible by construction
SDK types have private constructors and withX methods, so a new API field does not break code compiled against an older version. Your own case classes are untouched.
One type tree
Beta features are flags (RequestOptions.withBetas), not a parallel set of types.
No sampling parameters
temperature, top_p and top_k are rejected by the current API version, so they are not modeled.
More decisions, from the build log
Pure Scala
No dependency on the Java SDK, so no Kotlin runtime and no Jackson version pinning in Play apps.
Effects
Tagless-final F[_] on Cats Effect 3. Streams are fs2.Stream, the client is a Resource.
Codecs
Hand-written circe codecs through a small field DSL. Same source on Scala 2.13 and 3, no macros.
Telemetry
Traces only in v1. Prompt and response content is exported only in opt-in content mode.
§ 10 / Status and roadmap

Pre-release. Here is exactly where it stands.

Nothing is published to Maven Central. Binary compatibility is proven at the source level; MiMa starts comparing once a first version exists.

Verified against the live API

  • messages.create
  • Streaming
  • Structured outputs
  • Typed errors
  • A 3-turn agent with two strict tools

Built and tested offline

  • Retries, timeouts, request options, beta flags
  • Token counting, Models, Batches, Files, pagination
  • OpenTelemetry tracing
  • The Future facade and the testkit
  • The wire model, which also compiles on Scala 3

Not yet

  • A release on Maven Central
  • Bedrock, Vertex and Foundry
  • Managed Agents
  • The Admin API
  • Scala 3 beyond the wire model

Issues and pull requests are welcome on GitHub.