Skip to main content

ToolDispatcher

ToolDispatcher routes LLM tool/function calls to your Scala implementations using Scala 3 macros. It lives in constellations-common (also pulled transitively by constellations-core).

libraryDependencies += "io.github.serhiip" %% "constellations-common" % "0.1.33-SNAPSHOT"

API​

trait ToolDispatcher[F[_]]:
def prepare(call: FunctionCall): ValidatedNec[AgentError, F[ToolDispatcher.Result]]
def dispatch(call: FunctionCall): F[ToolDispatcher.Result]
def dispatchAll(calls: List[FunctionCall]): F[ValidatedNec[AgentError, List[ToolDispatcher.Result]]]
def getFunctionDeclarations: F[List[FunctionDeclaration]]
def declarationOf(component: String, method: String): Option[FunctionDeclaration]

// extension — preferred lookup by method reference
dispatcher.getDeclaration[Calculator](_.add) // Option[FunctionDeclaration]

enum ToolDispatcher.Result:
case Response(result: FunctionResponse)
case HumanInTheLoop

dispatchAll validates every call first (name lookup + argument decoding), aggregating failures with ValidatedNec. If any call is invalid it returns Invalid and executes nothing. If all are valid it executes each call reusing the arguments already parsed during validation (no second decode). Prefer dispatchAll for batches; dispatch remains for single calls and raises the first AgentError in F.

getDeclaration[T](_.method) is a compile-time-checked debug helper: it looks up the generated declaration for a real trait method (a typo is a compile error). Prefer it over declarationOf, which takes raw Scala names. Methods with an empty parameter list must be written _.method().

Trait rules​

  1. Define an effectful trait Api[F[_]]
  2. Public methods must return F[A] (not bare A)
  3. Parameter and return types must have Decoder / ResultEncoder support (see Encoding & decoding)
  4. Method/parameter docstrings become LLM descriptions and schema descriptions
import cats.effect.IO
import io.github.serhiip.constellations.ToolDispatcher
import io.github.serhiip.constellations.common.*

trait Calculator[F[_]]:
/** Adds two integers together */
def add(a: Int, b: Int): F[Int]

/** Multiplies two integers */
def multiply(a: Int, b: Int): F[Int]

/** Divides a by b */
def divide(a: Double, b: Double): F[Double]

val calculator = new Calculator[IO]:
def add(a: Int, b: Int): IO[Int] = IO.pure(a + b)
def multiply(a: Int, b: Int): IO[Int] = IO.pure(a * b)
def divide(a: Double, b: Double): IO[Double] =
if b == 0 then IO.raiseError(ArithmeticException("Division by zero"))
else IO.pure(a / b)

Building a dispatcher​

generate — one or more components​

Pass concrete instances as explicit arguments (not a Seq). Requires MonadThrow[F] in scope so unknown tools and decode failures raise AgentError inside F:

val dispatcher: ToolDispatcher[IO] =
ToolDispatcher.generate[IO](calculator)

The instance you pass is inline, so its term is spliced into the generated dispatcher. Always pass a stable reference (a val or object). Passing a fresh expression such as ToolDispatcher.generate[IO](makeCalculator()) would re-evaluate that expression on every dispatch — bind it to a val first.

to — single trait as a factory​

val fromTrait: Calculator[IO] => ToolDispatcher[IO] =
ToolDispatcher.to[IO, Calculator]

val typedDispatcher: ToolDispatcher[IO] =
fromTrait(calculator)

generate vs to​

Both are macros that expand at compile time and emit the same dispatcher code (the same routing map, dispatch / dispatchAll / getFunctionDeclarations). There is no runtime performance difference between them; choose based on ergonomics:

generate[F](component, others*)to[F, T]
ComponentsOne or many (varargs)Exactly one trait
Trait typeInferred from the valueWritten explicitly (T)
ReturnsToolDispatcher[F]T[F] => ToolDispatcher[F] (reusable factory)
Instance terminline — pass a stable val/objectSupplied at apply time as a stable lambda parameter (immune to re-evaluation)
When the macro runsAt the generate(...) call site, using the component's type and termAt the to[F, T] call site, using only the types; the instance is applied later at runtime

Rule of thumb: reach for generate (the default in these docs) — especially to merge multiple components. Prefer to when you want a reusable T[F] => ToolDispatcher[F] factory, want the trait fixed explicitly in the type, or want to build from a non-stable expression without the re-evaluation caveat.

Multi-component​

trait Greeting[F[_]]:
/** Greets someone by name */
def greet(name: String): F[String]

val greeting = new Greeting[IO]:
def greet(name: String): IO[String] = IO.pure(s"Hello, $name")

val multi: ToolDispatcher[IO] =
ToolDispatcher.generate[IO](calculator, greeting)

Declarations from each trait are merged; tool names stay unique via the trait prefix.

Combining dispatchers​

Use combine to merge already-built ToolDispatcher values (for example a local dispatcher plus an MCP one). It loads declarations once, builds a name→dispatcher index, and returns F[ToolDispatcher[F]]. Earlier dispatchers win on name clashes.

val local: ToolDispatcher[IO] =
ToolDispatcher.generate[IO](calculator)

val greetingOnly: ToolDispatcher[IO] =
ToolDispatcher.generate[IO](greeting)

// merged: IO[ToolDispatcher[IO]]
val mergedIO = ToolDispatcher.combine(local, greetingOnly)

This is different from multi-arg generate, which merges trait components at compile time. Wrap the result with ToolDispatcher.observed(...) if you want a single observability layer on the composite.

Naming contract​

ToolDispatcher takes a circe-style Configuration (default Configuration.snakeCase) and applies it to tool names, top-level parameters, and nested case-class fields in one pass:

ScalaDefault (Configuration.snakeCase)
Trait Calculatorcalculator → prefix calculator
Method addadd → tool calculator_add
Method mixedTypesmixed_types → calculator_mixed_types
Param intValint_val
Nested field zipCodezip_code
import io.github.serhiip.constellations.naming.Configuration

val identityDispatcher =
ToolDispatcher.generate[IO](calculator)(using Configuration.default)

Ambient givens also work:

given Configuration = Configuration.default.withKebabCaseMemberNames
val kebabDispatcher = ToolDispatcher.generate[IO](calculator)

Configuration.default is all-identity (like circe). Builders such as withSnakeCaseMemberNames / withKebabCaseMethodNames / withDiscriminator("kind") customize transforms. Member naming covers both method parameters and nested product fields.

import cats.effect.unsafe.implicits.global

val call = FunctionCall(
name = "calculator_add",
args = Struct(Map(
"a" -> Value.number(10),
"b" -> Value.number(5)
))
)
// call: FunctionCall = FunctionCall(
// name = "calculator_add",
// args = Struct(Map("a" -> NumberValue(10.0), "b" -> NumberValue(5.0))),
// callId = None
// )

val result = dispatcher.dispatch(call).unsafeRunSync()
// result: Result = Response(
// FunctionResponse(
// call = FunctionCall(
// name = "calculator_add",
// args = Struct(Map("a" -> NumberValue(10.0), "b" -> NumberValue(5.0))),
// callId = None
// ),
// response = Struct(Map("value" -> NumberValue(15.0)))
// )
// )
result match
case ToolDispatcher.Result.Response(response) =>
println(s"Response: ${response.response}")
case ToolDispatcher.Result.HumanInTheLoop =>
println("Human approval required")
// Response: Struct(Map(value -> NumberValue(15.0)))

Function declarations​

getFunctionDeclarations returns schemas built from your traits (names, docstrings, parameter schemas). Those values are easy to print while debugging — show renders each declaration as pretty-printed JSON, so you can inspect exactly what will be registered with the model:

import cats.syntax.show.*

(for
declarations <- dispatcher.getFunctionDeclarations
rendered = declarations.map(_.show).mkString("\n")
yield rendered).unsafeRunSync()
// res1: String = """{
// "name" : "calculator_add",
// "description" : "Adds two integers together",
// "parameters" : {
// "type" : "object",
// "properties" : {
// "a" : {
// "type" : "integer",
// "format" : "int32",
// "minimum" : -2.147483648E9,
// "maximum" : 2.147483647E9
// },
// "b" : {
// "type" : "integer",
// "format" : "int32",
// "minimum" : -2.147483648E9,
// "maximum" : 2.147483647E9
// }
// },
// "required" : [
// "a",
// "b"
// ]
// }
// }
// {
// "name" : "calculator_multiply",
// "description" : "Multiplies two integers",
// "parameters" : {
// "type" : "object",
// "properties" : {
// "a" : {
// "type" : "integer",
// "format" : "int32",
// "minimum" : -2.147483648E9,
// "maximum" : 2.147483647E9
// },
// "b" : {
// "type" : "integer",
// "format" : "int32",
// "minimum" : -2.147483648E9,
// "maximum" : 2.147483647E9
// }
// },
// "required" : [
// "a",
// "b"
// ]
// }
// ...

To inspect a single tool by its Scala method (without hard-coding the rendered name), use getDeclaration. Lookup keys are the raw trait and method names, so it stays correct regardless of the Configuration used when the dispatcher was built. Empty-parameter methods need the () form:

dispatcher.getDeclaration[Calculator](_.add).map(_.show).get
// res2: String = """{
// "name" : "calculator_add",
// "description" : "Adds two integers together",
// "parameters" : {
// "type" : "object",
// "properties" : {
// "a" : {
// "type" : "integer",
// "format" : "int32",
// "minimum" : -2.147483648E9,
// "maximum" : 2.147483647E9
// },
// "b" : {
// "type" : "integer",
// "format" : "int32",
// "minimum" : -2.147483648E9,
// "maximum" : 2.147483647E9
// }
// },
// "required" : [
// "a",
// "b"
// ]
// }
// }"""

@llmHint does not annotate trait methods. It annotates parameter types (case-class fields and the class itself) and is applied through ToSchema when the declaration schema is built. Use it for field descriptions, bounds, patterns, and examples — @llmHint(description = …) wins over a type-level docstring:

trait Catalog[F[_]]:
/** Look up a product by SKU. */
def lookup(item: CatalogItem): F[String]

/** Register a shopper email. */
def register(contact: ShopperContact): F[String]

final case class CatalogItem(
@llmHint(
description = Some("Stock-keeping unit"),
minLength = Some(3L),
maxLength = Some(12L),
pattern = Some("[A-Z0-9]+"),
example = Some("SKU12")
)
sku: String,
@llmHint(description = Some("Quantity to reserve"), minimum = Some(1.0), maximum = Some(99.0))
quantity: Int
)

/** Overridden by the class-level @llmHint description. */
@llmHint(description = Some("Shopper contact details"), title = Some("contact"))
final case class ShopperContact(
@llmHint(
description = Some("Email address"),
format = Some("email"),
example = Some("ada@example.com")
)
email: String
)

val catalog = new Catalog[IO]:
def lookup(item: CatalogItem): IO[String] = IO.pure(item.sku)
def register(contact: ShopperContact): IO[String] = IO.pure(contact.email)

val catalogDispatcher: ToolDispatcher[IO] =
ToolDispatcher.generate[IO](catalog)
catalogDispatcher.getDeclaration[Catalog](_.lookup).map(_.show).get
// res3: String = """{
// "name" : "catalog_lookup",
// "description" : "Look up a product by SKU.",
// "parameters" : {
// "type" : "object",
// "properties" : {
// "item" : {
// "type" : "object",
// "properties" : {
// "sku" : {
// "type" : "string",
// "description" : "Stock-keeping unit",
// "minLength" : 3,
// "maxLength" : 12,
// "pattern" : "[A-Z0-9]+",
// "example" : "SKU12"
// },
// "quantity" : {
// "type" : "integer",
// "format" : "int32",
// "description" : "Quantity to reserve",
// "minimum" : 1.0,
// "maximum" : 99.0
// }
// },
// "required" : [
// "sku",
// "quantity"
// ]
// }
// },
// "required" : [
// "item"
// ]
// }
// }"""
catalogDispatcher.getDeclaration[Catalog](_.register).map(_.show).get
// res4: String = """{
// "name" : "catalog_register",
// "description" : "Register a shopper email.",
// "parameters" : {
// "type" : "object",
// "properties" : {
// "contact" : {
// "type" : "object",
// "title" : "contact",
// "description" : "Shopper contact details",
// "properties" : {
// "email" : {
// "type" : "string",
// "format" : "email",
// "description" : "Email address",
// "example" : "ada@example.com"
// }
// },
// "required" : [
// "email"
// ]
// }
// },
// "required" : [
// "contact"
// ]
// }
// }"""

See Values & schemas for the full @llmHint field list.

Pass these to your LLM provider as tools, or convert them with MCP via create.

Overloaded methods share one entry (they already collide on tool name today); the first declaration wins. Methods with using parameter lists eta-expand by applying the given, so a selector for those needs the givens in scope.

Results and HumanInTheLoop​

  • Ordinary return types are encoded via ResultEncoder (usually wrapping scalars as Struct("value" → …)).
  • Return ToolDispatcher.Result (or FunctionResponse) from a method when you need to signal human-in-the-loop or a custom response shape.
trait Approval[F[_]]:
def requestReview(summary: String): F[ToolDispatcher.Result]

val approval = new Approval[IO]:
def requestReview(summary: String): IO[ToolDispatcher.Result] =
IO.pure(ToolDispatcher.Result.HumanInTheLoop)

val withApproval: ToolDispatcher[IO] =
ToolDispatcher.generate[IO](approval)

Errors​

ToolDispatcher.dispatch raises AgentError inside F. dispatchAll returns the same errors aggregated as ValidatedNec[AgentError, List[Result]] without executing any call when invalid (requires MonadThrow[F] when using generate / to / combine):

CaseError
Unknown tool nameAgentError.UnknownFunction(call)
Missing/invalid argumentsAgentError.ArgumentDecodingFailed(call, errors)

Both cases carry the original FunctionCall (including callId when the provider set one). Successful FunctionResponses also embed that same FunctionCall (response.call), so providers read call.callId — there is no separate id field. | Implementation failure | Error propagates in F (only after a successful validation in dispatch / dispatchAll) |

Stateful uses dispatchAll (validate-then-execute). On Invalid it posts tool-results for the whole batch (error for bad calls, skipped for valid siblings that were not run), retries up to agentErrorRetryLimit, then returns Failure.AgentRetriesExhausted with the aggregated NonEmptyChain[AgentError].

Observability​

ToolDispatcher.observed wraps a delegate with tracing, logging, and success/error counters. It returns F[ToolDispatcher[F]] and needs:

  • Tracer[F]
  • LoggerFactory[F]
  • Meter[F]
  • MonadCancelThrow[F]
import cats.effect.kernel.MonadCancelThrow
import org.typelevel.log4cats.LoggerFactory
import org.typelevel.otel4s.metrics.Meter
import org.typelevel.otel4s.trace.Tracer
import io.github.serhiip.constellations.ToolDispatcher

def observe[F[_]: Tracer: LoggerFactory: Meter: MonadCancelThrow](
raw: ToolDispatcher[F]
): F[ToolDispatcher[F]] =
ToolDispatcher.observed(raw)
KindName
Spanconstellations-tool-dispatcher-dispatch
Spanconstellations-tool-dispatcher-get-function-declarations
Counterconstellations/tool_dispatcher_dispatch_success_count
Counterconstellations/tool_dispatcher_dispatch_error_count

See Observability.

mapK and noop​

import cats.~>
import scala.concurrent.Future

val futureDispatcher: ToolDispatcher[Future] =
ToolDispatcher.mapK(dispatcher)(new (IO ~> Future) {
def apply[A](fa: IO[A]): Future[A] = fa.unsafeToFuture()
})

val stub: ToolDispatcher[IO] = ToolDispatcher.noop[IO]

noop returns empty declarations; dispatch throws.

Schema generation (parameters)​

From method signatures the macro supports:

  • Primitives: Int, Long, Double, Float, String, Boolean
  • Option (nullable / optional)
  • List / Seq
  • Case classes (nested objects)
  • Sealed traits / enums (string enums)

Method and parameter docstrings become the declaration / top-level parameter descriptions. Nested field metadata comes from @llmHint (and type-level docstrings) via ToSchema — see the examples above and Values & schemas.

Next​