ToolCall (ToolCall v0.4.0)
Copy MarkdownDerive LLM tool-call schemas from @spec and @doc.
defmodule MyApp.Tools.Weather do
use ToolCall
@doc """
Get the forecast for a city.
## Parameters
* `city` - city name
* `days` - how many days ahead
"""
@spec get_weather(city :: String.t(), days :: pos_integer() | nil) ::
{:ok, %{temp: float()}} | {:error, String.t()}
def get_weather(city, days \\ 3)
end
ToolCall.emit(MyApp.Tools.Weather, :openai)
ToolCall.run(MyApp.Tools.Weather, :get_weather, %{"city" => "Shanghai"})Everything is generated at compile time from module attributes. No runtime
path reads the Docs or Dbgi chunks, because release builds strip them.
Visible local @typedoc text is recovered in a second compile phase
(@after_compile) and embedded in a generated companion module; runtime code
never calls Code.fetch_docs/1. The companion is ordinary compiled code,
loaded on first use like any other module.
Type source
The current type source is the internal typespec provider. It may be replaced
by a future compiler-signature source. The wire schema and IR do not depend on
the typespec AST shape; the current provider still requires @spec to declare
a tool.
Supported typespec subset
See docs/design.md. @type, @typep and @opaque declarations in the same
module are resolved before mapping, including parameterised ones. Unknown
types degrade to {} (any value) rather than failing compilation unless a
ToolCall.TypeProvider registered with use ToolCall, types: [...] resolves
them; types that JSON cannot express at all (functions, pids, refs) are
flagged with a compile-time warning.
Summary
Functions
Returns a provider-neutral description of every tool in module.
Emits schemas for target (:openai, :anthropic, :mcp or :gemini).
Runs a tool by name. args uses string keys, as decoded from JSON.
Returns the tool names derived from a module, in declaration order.
Returns the tools derived from a module.
Validates the module-level timeout, approval and audit policies.
Functions
@spec describe(module(), keyword()) :: [ %{ module: module(), name: String.t(), description: String.t(), parameters: map() } ]
Returns a provider-neutral description of every tool in module.
Each entry has :module, :name, :description and :parameters, where
:parameters is the JSON Schema object for the arguments with no provider
envelope around it. Use this when your client owns the request format; use
emit/3 when you want the OpenAI or Anthropic envelope.
Options
:strict- render the strict JSON Schema subset (seeemit/3).
@spec emit( module() | [ToolCall.IR.Tool.t()] | ToolCall.IR.Tool.t(), :openai | :anthropic | :mcp | :gemini, keyword() ) :: map() | [map()]
Emits schemas for target (:openai, :anthropic, :mcp or :gemini).
For a module the OpenAI and Anthropic variants are rendered at compile time
and embedded as a literal, so this is a direct or guarded map lookup and
strict may be a runtime boolean. MCP and Gemini are rendered on demand. MCP
because its inputSchema is the parameters object the other targets already
embed; Gemini because its OpenAPI subset differs (uppercase types, no
additionalProperties). A module returns a list with one schema per tool; a
single ToolCall.IR.Tool returns one schema map and a list of them a list,
rendered on demand, which is what dynamically built tools need. Runtime IR is
validated before rendering; invalid types raise ArgumentError.
Gemini's parameters cannot express $ref/$defs, additionalProperties
or non-string enums, and it has no positional tuples; a recursive parameter
raises, and the other losses are documented in ToolCall.Emit.Gemini.
Options
:strict- OpenAI strict mode:true, or:fine_tunedfor the subset fine-tuned models accept. Both make every property required, optional values nullable and every object closed.:fine_tunedalso dropspattern,format, numeric bounds and array bounds, which fine-tuned models reject. For:mcpit renders the same closed subset without a flag (MCP has none);:fine_tunedis OpenAI-only and raises for MCP. Ignored for:anthropicand:gemini.
@spec run(module(), atom() | String.t(), term(), keyword()) :: {:ok, term()} | {:pending, ToolCall.Approval.Request.t()} | {:error, term()}
Runs a tool by name. args uses string keys, as decoded from JSON.
Options
:validate_result- when true, the function's raw return value is validated against the declared@specreturn type before{:ok, value}/{:error, reason}is unwrapped. A mismatch returns{:error, {:invalid_result, reason}}. Defaults to false, which is the generated fast path. Validation uses the generic runner path.:timeout- a per-invocation timeout in milliseconds or:infinity; defaults to the module'suse ToolCall, timeout: ...policy. A finite timeout answers{:error, {:timeout, ms}}and runs the function in a task;:infinityruns in the caller unless:task_supervisoris given, which starts a task.:task_supervisor- aTask.Supervisorname or pid for a timed invocation, including one supplied by the module timeout. With:infinitya supervisor still starts a task; without a supervisor a finite timeout uses a task linked to the caller and:infinityruns in the caller. An unreachable or invalid supervisor answers{:error, {:task_supervisor, reason}}.:context- passed to the timeout, approval and audit policies. It is also stored on the call byRunner.resolve/4forexecute/2.:approval-:granted,:denied, or aToolCall.Approvalpolicy module;nildisables the module policy for one call. A policy may answer{:required, reason}, which returns{:pending, %ToolCall.Approval.Request{}}; the call is not invoked.:audit- aToolCall.Auditpolicy module;nildisables the module policy for one call. The hook receives one%ToolCall.Audit.Entry{}per dispatch attempt, including a resolve/execute exception. An approval or other dispatch exception is recorded as:errorwitherror: {:exception, message}; a timeout policy failure is recorded as:errorwitherror: {:invalid_timeout, reason}.
Returns the tool names derived from a module, in declaration order.
@spec tools(module()) :: [ToolCall.IR.Tool.t()]
Returns the tools derived from a module.
The embedded IR keeps the atom Type.source values (string sub-kinds drive
dispatch and result validation) and drops non-atom sources, the spec and the
parameter ASTs, which are compile-time provenance only.
@spec validate_policies!(module()) :: :ok
Validates the module-level timeout, approval and audit policies.
Call this at application startup to reject a bad use ToolCall policy before
the first dispatch instead of waiting for resolve or execute. One-off
run/4 options are validated when the call is made. Raises ArgumentError
for an unknown callback or an invalid mode.
:ok = ToolCall.validate_policies!(MyApp.Tools)Or add {ToolCall.PolicyValidation, [MyApp.Tools]} to the supervision tree
as a one-shot startup child.