Changelog
Copy MarkdownUnreleased
0.4.0 - 2026-11-22
Added
ToolCall.Stream.new/2andaggregate/3acceptchoice:for an OpenAI choice or Gemini candidate; the default remains the first. A choice is matched by itsindexwhen present, otherwise by list position, and a choice that never appears returns{:error, {:choice_not_found, choice}}.Struct
defstructdefaults that are JSON-safe and compatible with the field type are emitted as schemadefaultvalues. An explicit nil is emitted when the field accepts nil; non-JSON and incompatible defaults are skipped, and strict mode drops defaults.Field.has_defaultdistinguishes an explicit nullable nil from no default; a non-nil default does not require it, and a nullable atom field no longer loses its explicit nil default.ToolCall.Schema.Gemini.to_gemini/2exposes the Gemini schema projection for callers that already hold a JSON Schema, without constructingToolCall.IR. Its:on_refoption controls local$defs::raise(the emitter default),:drop, or:inlinefor non-recursive definitions.ToolCall.Emit.Geminidelegates to it, so emitted bytes are unchanged. It raises foroneOf,const,allOfandnot, which Gemini cannot express, requires an object schema at the root, and rejects a multi-typetypearray instead of widening it.
Fixed
Result validation now enforces
minimum/maximumonfloat()andnumber()results, matching dispatch and the emitted schema.ToolCall.IR.Field.descriptionis now rendered as the property description and validated asnilor a UTF-8 string, instead of being silently ignored.Gemini rejects null-only schemas instead of emitting an invalid
"type": "NULL"or an emptyanyOf.no_return()andnone()results are kept as never nodes instead ofnil;validate_result: truenow rejects a value returned by such a function as{:invalid_result, :no_return}.Path.t()results accept raw bytes, matchingbinary(), instead of rejecting a Unix path that is not valid UTF-8.MCP rejects
strict: :fine_tunedinstead of silently droppingpattern, numeric bounds and array bounds;mix tool_call.export --fine-tunedis now rejected outside--format openai.
0.3.0 - 2026-11-18
Changed
$defsnames for parameterized recursive local types now carry a hash derived from the normalizedTypeExprinstead of the typespec AST, for examplerec_integer_381dinstead ofrec_integer_6fee. The readable part is unchanged, names without type arguments are unchanged, and$reftargets stay consistent within a schema. Only the emitted bytes of a parameterized recursive type differ.$defsnames for parameterized recursive struct types now hash the same normalizedTypeExprterm as other recursive types, so one schema no longer mixes two naming schemes. As with the type-level change above, the readable part is unchanged and only the emitted bytes of a parameterized recursive struct differ.
Added
A function-declaration source can return an
:errorseverity diagnostic inToolCall.Diagnostic; the build then fails with that message instead of warning and skipping the tool. The shipped@specsource still reports warnings only.ToolCall.Diagnosticcarries an optionalline/column, and the builder prefers it over the definition location. An overloaded@specwarning now points at the spec it came from rather than at thedefline.ToolCall.TypeExpr.Projectionintersects maps, tuples, numeric primitives and ranges, literals and enums, identical refs and remotes, and narrows stringpattern/formatconstraints; subtraction accepts unions and handles integer ranges, literals, enums, and tuples. Cases JSON Schema cannot express still degrade to:unsupportedwith a warning.
Fixed
ToolCall.TypeExpr.Compiler.to_type/2validates the whole expression before compiling it. A malformed nested field or an uncompilable string pattern now becomes:unsupportedinstead of raising out of the compiler.A tool that hits the type-expansion budget now gets one warning naming the affected parameters and whether the result type was truncated, instead of one message per parameter. Which parameter runs out is an artifact of declaration order, so the per-parameter message blamed the wrong one.
Typespec shapes neither mapper understands (for example a charlist literal) stay
:anyrather than becoming:unsupported, so an unknown nested value still renders as{}and keeps the tool instead of hiding it.Local
$defsnames that collide now take a numeric suffix. Keeping the first and dropping the second left a$refpointing at another type's body.
0.2.0 - 2026-11-12
Breaking changes
A tool with an argument whose root has no JSON type is not exposed.
term(),any(), a remote type without a provider, an@opaquestruct, or a rootfun()/pid()/port()/reference()/mfa()leaves the argument undescribable, so the function is skipped with a compile-time warning instead of shipping a{}schema. Runtime IR may still use:any.Compatibility break: a struct type with a public
@type tis now a closed object that dispatch rebuilds, where 0.1 emitted{}and passed any value. This covers scalar wrappers such asDecimal.t(),URI.t()andRange.t(); add aToolCall.TypeProviderto keep the old permissive shape or to send the value as a scalar.MapSetandRegexhave built-in providers, and@opaquetypes are unchanged.
Added
Derive a tool's
@specreturn type into%ToolCall.IR.Tool{result: ...}, sharing the tool's$defs.ToolCall.run/4withvalidate_result: truevalidates the raw return value against it and answers{:error, {:invalid_result, reason}}on a mismatch. Opt-in;run/3never validates.ToolCall.TypeProvidergains an optionalvalidate(type, value, defs)for the value domain; the built-ins cover the calendar types,KeywordandMapSet(including element types) andRegex. An improper list or an exotic map key in a result is{:invalid_result, ...}, not a raise.ToolCall.emit/3supports:mcp, returning{name, description, inputSchema}tool objects for an MCPtools/listresult. MCP renders on demand from the tool IR;strict: truerenders the closed schema subset without a flag.ToolCall.emit/3supports:gemini, returning{name, description, parameters}declarations forfunctionDeclarations. The parameters object is Gemini's OpenAPI 3.0 subset: uppercase types,nullable: true, noadditionalProperties, noprefixItems; non-string enums are dropped and a recursive$refraises.mix tool_call.export --format geminiwraps them as{"tools": [{"functionDeclarations": [...]}]}.ToolCall.Streamaggregates streaming tool-call deltas:aggregate/2ornew/1+feed/2+finish/1for OpenAI Chat Completions, Anthropic Messages and Gemini function calls.argumentsis decoded; invalid JSON is{:invalid_stream_arguments, {id, name, json}}and a call without a name is{:missing_name, id}. This completes the planned0.3items.strict: :fine_tuned(andmix tool_call.export --fine-tuned) emits the OpenAI strict shape withoutpattern,format, numeric bounds or array bounds, which fine-tuned models reject. It renders on demand.A struct compiled without a typespec chunk (in memory or with
debug_info: false) now falls back to parsing its source file for@type t(simple aliases, multi-aliases, enclosing-module aliases and@typepare expanded in declaration order); a module with no source warns "has no readable typespec" instead of degrading silently.ToolCall.Runner.resolve/4andexecute/2split preparation from the side effect.ToolCall.run/4acceptstimeout:andtask_supervisor:, anduse ToolCall, timeout: ...sets a default or aToolCall.Timeoutpolicy; a timeout answers{:error, {:timeout, ms}}, andcontext:reaches the policy. Timeouts are per invocation and a hard kill, not a cancellation.ToolCall.Approvaladds a policy hook:use ToolCall, approval: Policyorrun/4 approval:;check/3can approve, deny, or return a serializable pending request. No persistence or resume state machine is built in.ToolCall.Auditadds a dispatch audit hook:use ToolCall, audit: Policyorrun/4 audit:receives oneEntryper attempt (ok/error/raised/pending/ denied/timeout/invalid arguments/unknown tool). It is fail-open and does not persist; redact the raw args in the hook.Recursive local types emit
$defs/$refinstead of{}. Cyclicity is decided statically, so the parameter itself is a$refand each type has one canonical body.Concrete struct types (
%Mod{},Mod.t()) expose their fields as a closed object, with field types from the public@type tandrequiredfrom@enforce_keys. Dispatch reconstructs the struct and keepsdefstructdefaults for omitted fields.Recursive struct types use the same
$defs/$refpath.Built-in providers for
MapSet.t/0,MapSet.t/1(an array of elements, rebuilt withMapSet.new/1) andRegex.t/0(its source string, compiled withuat dispatch), so a set or a regex no longer exposes its internal fields.A struct whose only type is
@type t/N, or whoset/0is not a%__MODULE__{}literal, warns at compile time instead of silently untyping every field. An exception struct exposes its payload but not__exception__.$defsnames for a parameterized instantiation carry a short signature (tree_integer_40ca), so adding a parameter never renames an existing entry.Compiling outside a Mix project no longer exits; the typedoc companion is skipped with a warning and the phase-one descriptions are used.
ToolCall.validate_policies!/1validates the module-level timeout, approval and audit policies at startup, including their callback arities and valid module-level approval modes. One-offrun/4options remain validated at the call site.ToolCall.PolicyValidationis a one-shot supervision child that runsvalidate_policies!/1for configured tool modules and returns:ignore, so it does not stay in the tree.ToolCall.Providers.URIandToolCall.Providers.Versionare optional type providers for the standard-library structs, using string wire forms and parsing withURI.new/1andVersion.parse/1.The
[t, ...]non-empty list syntax is supported asminItems: 1and dispatches as a list, equivalent tononempty_list(t).
Changed
- A struct defined in the same module as its tools is now extracted from the
field map in the generated
__struct__/0, with types from@type t/0, anddefstruct's__struct__/0,1no longer warn about a missing@spec. - An enum value that is a boolean no longer accepts its string form (
"true"); booleans are JSON literals, not atoms on the wire. Address.t() | nilkeeps the null branch for a struct parameter and for result validation; the resolved struct object previously droppednullable.- A result type that cannot be validated —
term(), an unknown remote type,fun()/pid(), an@opaquestruct, or a budget-truncated type — now warns thatrun/4withvalidate_result: trueaccepts any value; the budget warning names the same consequence. A providervalidatorsuppresses the warning because the value is checked. - The result warning now walks the type and reports nested untyped paths:
object fields, open-object values (
"*"), array items ("[]"), tuple positions, union variants, struct fields and$refbodies. A providervalidatorstops the walk at its subtree; a budget-truncated result keeps the single budget warning. - The embedded IR drops AST
Type.sourcevalues from parameters, the result and$defs, while keeping the string sub-kind atoms that dispatch and result validation read; this shrinks the beam. - A provider
validatorthat is not exported with arity 3 now raises with the provider and the remote type in the message, like the other provider IR errors. - An explicit provider
validatormay live in a file compiled in parallel with the tool: the build waits for it withCode.ensure_compiled?instead of treating it as missing. Mod.t(integer())now resolves as a struct (the type arguments are not substituted), so a parameter keeps a callable tool and a result is validated as a struct; previously it degraded to{}and hid the tool.- A struct whose
@type tunionsnilkeeps its field types and is nullable wherever it is used; other unions still degrade to{}. - A
@docbullet under## Parametersthat names no parameter now warns with the offending name instead of being dropped silently. - A
@docbullet under## Optionsdocuments the keys of a keyword argument; it is no longer reported as an unknown parameter and no longer names an unannotated parameter by position. - An enum that mixes atoms with booleans or integers stringifies the atoms, so the schema term is JSON-encodable by any encoder.
Fixed
ToolCall.Runner.resolve/4now stores the module'suse ToolCall, timeout:constant or policy instead of dropping it.execute/2evaluates the policy after approval with the validated raw argument map and context, so a pending or denied call does not run the policy; a policy exception returns{:error, {:invalid_timeout, reason}}.run/4honors:task_supervisorwhen the timeout comes from the module default, and:infinitywith a supervisor now starts a supervised task. An unreachable or invalid supervisor answers{:error, {:task_supervisor, reason}}instead of exiting the caller.execute/2validates an explicit:timeoutoverride before approval, so a pending/denied decision cannot hide an invalid timeout.ToolCall.Callstores the:contextgiven toresolve/4, soexecute/2passes it to the approval, timeout and audit hooks (anexecute/2context still overrides it). The struct documents that it is a trusted resolve handoff, not data to deserialize from model output.- Audit outcomes now come from the dispatch path, not from the final error
tuple: a tool returning
{:error, {:timeout, ...}}or{:error, {:approval_denied, ...}}is recorded as:error. Non-map arguments are audited as:invalid_arguments; policy exceptions, invalid timeout overrides and invalid runtime IR are audited as:errorwitherror: {:exception, message}(a timeout policy error is returned as{:invalid_timeout, term});audit: nilno longer constructs an entry. ToolCall.run/4uses the prepared-tool path for compiled modules instead of revalidating every tool on each option-carrying call.Runnervalidates its public option keys and rejects boolean/invalid approval or audit values before dispatch. Approval/audit options are checked forcheck/3/record/1; module-level policies are loaded on demand and checked when resolved. Module-levelapproval: :granted/:deniedremains a valid mode.Runner.execute/2uses the call's stored audit policy when a dispatch exception is audited, not only the module or per-call audit option.:cryptois declared inextra_applications; audit and approval ids work in a release that contains only this library.- An Anthropic stream whose initial
inputis not a map, and has noinput_json_deltafragments, is now:invalid_stream_argumentsinstead of silently becoming{}. - A
## Optionsbullet no longer becomes a same-named parameter's description; Options documents keyword keys, not function parameters. - A parameter whose root type or required nested path is unrepresentable
(
fun(),pid(),port(),reference(),mfa()) now hides the tool instead of exposing a schema the dispatcher can never satisfy. Optional nested unrepresentable fields still render{}and keep the tool because they can be omitted. - An aliased
no_return()result now leavestool.resultasnil, matching the directno_return()path. char()default validation now requires exactly one codepoint, not one grapheme cluster; combining-character defaults can no longer pass compile validation and then fail dispatch.- A literal binary typespec such as
@spec f(x :: "hello")becomes a singleton string enum instead of degrading to:anyand hiding the tool. - Empty enums use the string wire domain during result validation, matching
dispatch and the rendered
"type": "string"schema. - Malformed improper lists in array and tuple arguments return coercion errors
instead of raising
ArgumentErrororFunctionClauseError. - A finite timeout without
task_supervisorno longer links the task to the caller, so a raising task returns{:error, {:exited, reason}}instead of exiting the caller. Runner.execute/2rejects:timeout_policyand:validate_result; those options are meaningful only duringresolve/4, and silently ignoring them was a trap.- Hand-built struct IR is now checked against the struct's actual
__struct__/0fields; mismatched or missing fields and non-niladditionalare rejected before dispatch. ToolCall.Doc.parse/1now returns## Optionsbullets under:optionsinstead of:params, so the parser no longer presents keyword-option docs as function parameters.- A negative
:timeout_policyis rejected during option validation instead of deferring the failure to a later dispatch phase. - Result validation now rejects invalid Unicode scalar values in
char()andcharlist(); a charlist containing an out-of-range or surrogate codepoint no longer passes validation. - The private timeout supervisor stays linked to the caller so caller death tears down its task; its normal termination message is drained for callers that trap exits.
- Streaming calls now check for a missing name before using an already prepared
argument map, so a hand-built accumulator cannot bypass
{:missing_name, id}.
0.1.0 - 2026-11-09
Added
- Derive tool schemas from
@spec,@doc, and@typedocwithout a separate schema DSL. - Emit OpenAI and Anthropic tool schemas, including OpenAI strict mode.
- Dispatch tool calls through
ToolCall.run/3with required and unknown argument checks, coercion, and exception wrapping. - Export schemas as JSON for OpenAI, Anthropic, and MCP with
mix tool_call.export. - Resolve custom application types through
ToolCall.TypeProvider, including an optionalcoerce/1hook. - Recover docs-visible
@typemetadata from a compile-time companion beam so releases keep typedoc descriptions. - Support large integer arguments with the
string_integerwire format.
Changed
- Speed up scalar tool dispatch with generated per-tool runners, falling back
to
ToolCall.Runnerfor complex shapes.
Compatibility
- Requires Elixir
~> 1.18and Erlang/OTP 27.1 or newer.