ExAgent.Tool (ExAgent v3.0.0)

View Source

A tool the model may call.

Stability — Stable.

ExAgent.Tool bundles everything: the serialisable ToolDefinition (name, description, JSON-Schema parameters) and the actual callable that runs when the model invokes it. Use definition/1 to project the shape a provider sends to the model.

Tools are normally built via the deftool macro (see ExAgent.Tools), which derives the JSON-Schema from the function's @spec. They can also be built by hand with new/1.

:max_retries is a non-negative integer (default 1). Set it to zero to exhaust the tool's retry budget on the first retryable failure.

:result_schema validates a successful JSON result after result hooks and before shortening or offloading it. A mismatch becomes a confirmed :tool_error with a fixed notice. The rejected value and schema diagnostics stay out of the model request. Use result_mode: :multimodal with a nil result schema for typed image results.

MCP and Sandbox carry private adapter identity into persisted continuation fingerprints. Configure it through ExAgent.MCP.Client.start_link/1 or ExAgent.Sandbox.tools/2. definition/1 projects the provider-facing tool.

Execution controls

The :reservation_cents and :max_heap_bytes controls are candidate, as is the :mcp_input field that MCP July clients set.

:effect defaults to :write. Declare :read for a tool that only queries data. An authorized continuation recovery can repeat an uncertain read. A context-aware write can declare reconcile: fn key -> ... end to look up its original result through ExAgent.Continuation.reconcile_tool/4. The callback defaults to nil; arities one and two are accepted. The lookup must be read-only and receives the original RunContext.idempotency_key. Effect controls are part of the continuation fingerprint and private to the host.

Set :reservation_cents to quote a positive per-invocation price to the shared spend account. This host control applies before dispatch and uses the active tool definition after a resume. Report a complete or partial price with ExAgent.Message.Usage.with_estimated_cost/2 in a tool result. Unknown prices keep the quote held for reconciliation. Tools that already reserve the same charge internally, such as ExAgent.Media.tools/1, need no separate quote.

Set :requires_deferral to true for a callable that needs to return {:defer, meta}. Frame3 agents and their durable delegates can execute it. Volatile runs and durable workflow leaves reject the call before recording an intent. Declare it for timer tools so PostgreSQL can require its timer index before dispatch. These tools require unified migration 1 on PostgreSQL. The flag defaults to false and is part of the continuation fingerprint. The provider sees only the ordinary definition.

Calls from one model response run concurrently by default, bounded by the agent's :tool_timeout. Optional fields refine that per tool:

  • timeout — milliseconds for this tool's calls instead of the agent's :tool_timeout (still capped by the run deadline). It counts from the call's dispatch. The admission before it (preparation hooks, argument validation, permissions and a synchronous :approve) has a separate budget of the same length: a call stopped there is :not_executed and fails the run with {:tool_admission_timeout, name}. A call that exceeds the timeout after its dispatch is killed and reported :unknown, which fails the run, as with :tool_timeout. A call can take up to twice its timeout end to end.
  • concurrency — :parallel (default) or :exclusive. An exclusive call runs alone: calls before it finish first and calls after it start only once it has finished. Use it for tools that mutate shared state (writing files, running migrations) while read-only tools keep running in parallel.
  • max_heap_bytes — the BEAM heap threshold for the tool task, including shared binaries. The default, nil, inherits the VM's policy. A task terminated by the VM reports an exit and retains any confirmed effect. The threshold is checked at garbage collection and applies to the task's heap. Allocations in other processes, ETS and native resources have their own lifecycles.

Consecutive parallel calls run together even when their timeouts differ. Results always keep the model's call order. A call that pauses for approval does not hold back later calls in the same response: ordering applies to the calls executed in one attempt. These controls stay off the model wire and out of persisted continuation fingerprints, so a resumed run uses the current definition, even when its timeout exceeds the persisted :tool_timeout.

tool = ExAgent.Tool.new(name: "apply_patch", call: &patch/2, concurrency: :exclusive)
tools = Enum.map(MyApp.Tools.tools(), &%{&1 | timeout: 5_000})

Summary

Types

A read-only lookup of a context-aware write's recorded result by its key. A confirmed outcome uses the status and JSON data of ExAgent.Continuation.reconcile/5. Use :not_executed only when the service certifies that the write did not run. Use :unknown when the service cannot establish its outcome.

What a tool callback returns. The contract is closed: any other shape is an invalid result, never a success.

t()

A JSON-portable success value that is neither a tuple nor the atom :error.

Functions

Serialisable projection sent to the model: name + description + params.

Build a tool by hand from a keyword list of its public fields. Unknown or duplicate options, a name that is neither nil nor a non-empty string and invalid execution controls raise ArgumentError. A tool given to an agent needs a name and a valid parameter schema; those are checked when a request offers it. Set :result_schema to validate successful JSON results. Use an object schema with an explicit type: "object" when exporting this tool with ExAgent.MCP.Server.

Validate arguments without invoking the callable or changing the original map.

Check a successful result payload, preserving the original term.

Types

callback()

@type callback() :: (ExAgent.RunContext.t(), map() -> result()) | (map() -> result())

effect()

@type effect() :: :read | :write

kind()

@type kind() :: :function | :output | :external

reconciler()

@type reconciler() ::
  (String.t() -> {:confirmed, map()} | :not_executed | :unknown)
  | (String.t(), map() -> {:confirmed, map()} | :not_executed | :unknown)

A read-only lookup of a context-aware write's recorded result by its key. A confirmed outcome uses the status and JSON data of ExAgent.Continuation.reconcile/5. Use :not_executed only when the service certifies that the write did not run. Use :unknown when the service cannot establish its outcome.

An arity-two lookup receives the key and the stored metadata of an external deferral. For a successful multimodal result, its data can be ExAgent.Tool.Content. The runtime only calls this form after the deferral has been recorded.

result()

@type result() ::
  value()
  | {:ok, value()}
  | {:ok, value(), ExAgent.Message.Usage.t()}
  | {:content, [map()]}
  | {:content, [map()], ExAgent.Message.Usage.t()}
  | {:tool_error, String.t()}
  | {:tool_error, String.t(), ExAgent.Message.Usage.t()}
  | {:retry, String.t()}
  | {:error, term()}
  | {:unknown, term()}
  | {:unknown, term(), ExAgent.Message.Usage.t()}
  | {:defer, map()}
  | {:defer, map(), [{:kind, :external | :input}]}
  | {:defer, map(), kind: :timer, wake_at: non_neg_integer()}

What a tool callback returns. The contract is closed: any other shape is an invalid result, never a success.

ReturnStatusThe model seesThe run
value, {:ok, value}, {:ok, value, %Usage{}}:succeededthe valuecontinues; usage is added; the tool's retry count resets
{:content, parts}, {:content, parts, %Usage{}}:succeededtext and inline imagesrequires result_mode: :multimodal; see ExAgent.Tool.Content
a success value rejected by a declared result schema:tool_errora fixed noticecontinues and preserves the confirmed effect and reported usage
{:tool_error, message}, {:tool_error, message, %Usage{}}:tool_errormessage, as an errorcontinues; uses no max_retries; the retry count resets
{:retry, message}, raise ExAgent.ModelRetry:validation_errormessage, as an errorcontinues while max_retries consecutive retries remain
{:error, reason}:failedthe fixed notice "The tool failed."fails with {:tool_execution_failed, name, reason}
{:unknown, reason}, an unconfirmed {:error, reason}, an exception, throw, exit or timeout:unknownthe fixed notice "The tool did not return a confirmed result."fails; the host reconciles the effect
{:unknown, reason, %Usage{}}:unknownthe same fixed noticeretains the usage report and still requires reconciliation
any other tuple, a bare :error, a returned %ExAgent.ModelRetry{} (alone or in {:error, _}), a non-UTF-8 or non-binary message:unknownthe same fixed noticefails with {:invalid_tool_result, name, :unsupported_return}
a value that is not JSON-portable, with no declared result schema:unknownthe same fixed noticefails with {:invalid_tool_result, name, errors}
{:defer, meta}, {:defer, meta, kind: :external | :input}:deferrednothing until a result is suppliedpauses with a durable :continuation; otherwise :unknown and fails with {:deferral_unsupported, name}
{:defer, meta, kind: :timer, wake_at: utc_ms} (candidate):deferrednothing until a result is supplied or the timer elapsespauses with a durable :continuation
no return: the admission (hooks, validation, permissions, :approve) outlived the timeout:not_executedthe fixed notice "The tool call was stopped before it ran."fails with {:tool_admission_timeout, name}

Use {:retry, message} when the model's input can be corrected and repeating the call is safe, before any effect. Use {:tool_error, message} for a known, final outcome the model can act on ("not found", "conflict", a business rule); it is a confirmed result and is never re-executed on resume. Use {:error, reason} for a host or configuration failure the model cannot fix, and {:unknown, reason} when the effect may have happened. A fatal reason never enters the history or the provider request: read it from ExAgent.RunError.

Return {:defer, meta} when the callable handed its work to the outside (a render job, a human form) and the result arrives later. meta is a JSON object of at most 64 KiB that the host sees in ExAgent.Continuation.pending/2, never the model. kind: :external (the default) means the outside work may have effects; kind: :input only waits for data. Use {:defer, meta, kind: :timer, wake_at: utc_ms} to wait for a supplied result until the Store clock reaches an absolute UTC millisecond timestamp. The two timer options may appear in either order. An elapsed timer supplies a local :not_executed result. Input and timer deferrals can be cancelled cleanly. The callable is never invoked again: the host records what happened with ExAgent.Continuation.supply_result/4 and resumes. Frame3 agents and delegates use the root run's durable :continuation. Composition and Flow nodes do not support deferrals.

t()

@type t() :: %ExAgent.Tool{
  call: callback() | nil,
  code_mode: term(),
  concurrency: :parallel | :exclusive,
  delegation: term(),
  description: String.t() | nil,
  effect: effect(),
  execution_binding: term(),
  kind: kind(),
  max_heap_bytes: pos_integer() | nil,
  max_retries: non_neg_integer(),
  mcp_input: term(),
  mcp_legacy_result: term(),
  mcp_pinned: term(),
  name: String.t(),
  parameters_json_schema: map() | boolean(),
  prepared_result_validator: term(),
  prepared_validator: term(),
  reconcile: reconciler() | nil,
  requires_approval: boolean(),
  requires_deferral: boolean(),
  reservation_cents: ExAgent.UsageLimits.Budget.cents() | nil,
  result_mode: :json | :multimodal,
  result_schema: map() | boolean() | nil,
  takes_ctx: boolean(),
  timeout: pos_integer() | nil
}

validation_error()

@type validation_error() :: %{
  path: String.t(),
  keyword: String.t(),
  message: String.t()
}

value()

@type value() :: nil | boolean() | number() | String.t() | atom() | list() | map()

A JSON-portable success value that is neither a tuple nor the atom :error.

Functions

definition(tool)

@spec definition(t()) :: map()

Serialisable projection sent to the model: name + description + params.

new(opts)

@spec new(keyword()) :: t()

Build a tool by hand from a keyword list of its public fields. Unknown or duplicate options, a name that is neither nil nor a non-empty string and invalid execution controls raise ArgumentError. A tool given to an agent needs a name and a valid parameter schema; those are checked when a request offers it. Set :result_schema to validate successful JSON results. Use an object schema with an explicit type: "object" when exporting this tool with ExAgent.MCP.Server.

validate_args(tool, args)

@spec validate_args(t(), term()) :: {:ok, map()} | {:error, [validation_error()]}

Validate arguments without invoking the callable or changing the original map.

Atom and string object keys are compared as JSON strings; collisions and values outside the JSON data model are rejected. Values are never coerced and defaults are never inserted. Error paths are JSON pointers (the root is "").

validate_result(tool, result)

@spec validate_result(t(), term()) :: {:ok, term()} | {:error, [validation_error()]}

Check a successful result payload, preserving the original term.

Pass the business value after unwrapping {:ok, payload} and applying any transformations. With a result schema, JSV checks the JSON emitted by Jason, including encodable structs and atoms. Duplicate object keys and encoding failures reject. A declared multimodal result is checked as typed content. Diagnostics are for the host and can include details of the rejected value.