Available on crate feature
tool-loop only.Expand description
Tool calling: a model, the tools it may call, and the bounded loop
between them, run as an A2A task (ADR 0022; feature tool-loop).
A2A has no tool concept. It carries messages, tasks and artifacts between agents; tool calling happens inside one task, between the executor and its model. This module is that layer:
A2A client ──SendMessage──→ ToolLoopExecutor one A2A task
│
▼
ToolLoop::run many model turns
┌──────┴───────┐
model turn N ──→ tool calls? ──no──→ answer + trace
▲ │ yes
└── results ── ToolSetToolModel: one completion turn, provider-neutral.OpenAiChatModelis the bundled one, for the chat-completions API (OpenAI, llama.cpp’s llama-server, vLLM, Ollama).ToolandToolSet: what the model may call. Each call carries an idempotency key, and a call repeated within a run to a tool that is not read-only is answered from the first (ADR 0026).ToolLoop: turns until the model answers without a call, bounded bywith_max_turns, with a tool’s error sent back to the model as that call’s result, and a call written as text recovered as a call.InferenceLimitandLimitedModel: at most so many turns in flight at one provider, shared by every loop that uses it; andModelRetry, a rate-limited turn sent again after the provider’sRetry-After, inside the caller’s budget (ADR 0048).ToolLoopExecutor: the loop as anAgentExecutor, with the answer and atool-traceartifact.
Each model turn and each tool call has its own span, named as the
OpenTelemetry GenAI conventions name them (chat {model},
execute_tool {name}) and opened inside the executor’s invoke_agent
span. They record no prompt, argument or result.
use std::future::Future;
use std::pin::Pin;
use a2a_protocol_server::tool_loop::{
OpenAiChatModel, Tool, ToolError, ToolInvocation, ToolLoop, ToolLoopExecutor, ToolSet,
};
use a2a_protocol_server::RequestHandlerBuilder;
struct Clock;
impl Tool for Clock {
fn name(&self) -> &str { "utc_now" }
fn description(&self) -> &str { "The current UTC time, RFC 3339." }
fn parameters(&self) -> serde_json::Value {
serde_json::json!({"type": "object", "properties": {}})
}
fn read_only(&self) -> bool { true }
fn call<'a>(
&'a self,
_call: ToolInvocation,
) -> Pin<Box<dyn Future<Output = Result<String, ToolError>> + Send + 'a>> {
Box::pin(async { Ok("2026-10-20T12:00:00Z".to_owned()) })
}
}
let model = OpenAiChatModel::new("http://127.0.0.1:8080/v1", "qwen3:1.7b")?;
let tools = ToolSet::new().with(Clock)?;
let executor = ToolLoopExecutor::new(
ToolLoop::new(model, tools).with_preamble("Call the tools yourself to answer."),
);
let handler = RequestHandlerBuilder::new(executor).without_agent_card().build()?;Structs§
- Action
Receipt - One call’s record.
- Answer
- What a run produced.
- Approval
Needed - A call a person has to approve before the run can go on.
- Audited
Policy - A
ToolPolicythat records every call before it runs. - Chat
Request - Everything one turn is asked with.
- Duplicate
Tool - Two tools in one
ToolSetwith the same name. - Final
Answer - What a finished run answered.
- InMemory
Step Journal - A journal in this process’s memory, for tests and for a deployment that keeps a run on one replica and accepts losing it with the process.
- Inference
Limit - How many turns may be in flight at once at one model provider.
- Journal
Entry - One run as a
StepJournalstores it. The journal readsrevision,owner,completedandupdated_at_ms;bodyis opaque to it. - Limited
Model - A
ToolModelthat takes a slot of anInferenceLimitfor each turn and gives it back when the turn ends, however it ends. - Model
Retry - How a loop retries a turn the provider refused as rate limited
(
ModelError::RateLimited); set withToolLoop::with_model_retry. - Model
Turn - What one turn produced.
- Open
AiChat Model - A
ToolModelthat sends each turn asPOST {base}/chat/completions. - Pending
Approval - A call parked for a person’s decision.
- Pins
- What a run was begun with, which a resume must still be.
- Policy
Request - One call, as a
ToolPolicyis asked about it: the tool and arguments the model chose, and the request’s identity, taken from the authenticated request and not from anything the model wrote. - Postgres
Step Journal - Checkpoints in a PostgreSQL table,
a2a_run_journal, created if absent. - RunCheckpoint
- Everything a run needs to carry on.
- RunOwner
- Whose run an entry is: from the authenticated request, never from what the
model wrote. What
StepJournal::runs_ofandStepJournal::erasefind a run by. - RunSummary
- What
StepJournal::runs_oflists of a run: everything but its content. - Sqlite
Step Journal - Checkpoints in a SQLite table,
a2a_run_journal, created if absent. - Text
Sink - Where a streaming turn sends its text as it arrives: see
ToolModel::complete_streaming. Cheap to call for every piece; a piece sent after the run ended is dropped. - Token
Usage - The tokens one turn used, as the provider reported them.
- Tool
Call - One call a model asked for.
- Tool
Invocation - One call, as a
Toolis given it. - Tool
Loop - A model, the tools it may call, and the bounded loop between them.
- Tool
Loop Executor - An
AgentExecutorthat answers each message by running aToolLoop. - ToolSet
- The tools a
ToolLoopoffers its model, in the order they were added. Names are unique: a model asking for a name two tools share could not be answered. - Tool
Spec - What the model is told about one tool.
- Trusted
Identity - The authenticated request’s identity, handed to the loop by its executor.
Enums§
- Argument
Check - Whether, and how strictly, a call’s arguments are checked against the
tool’s schema (
Tool::parameters); seeToolLoop::with_argument_check. - Chat
Message - One message of the conversation a
ToolModelis given. - Journal
Error - Why a journal did not do what it was asked.
- Loop
Error - Why a run produced no answer.
- Model
Error - Why a turn produced nothing. Each is the provider’s failure, not the model’s: a model’s mistakes are fed back to it by the loop.
- Policy
Decision - The policy’s answer.
- Receipt
State - Where a call stands.
- Text
Call Recovery - Whether a reply that is exactly one JSON object naming a tool in the set is
run as that call (see
ToolLoop::with_text_call_recovery). - Tool
Error - Why a call produced no result.
- Trace
Content - What a run’s trace, the artifact the caller reads, carries for each call.
Constants§
- ANSWER_
ARTIFACT_ ID - The id of the artifact carrying the answer.
- CHECKPOINT_
VERSION - The checkpoint format’s version. A checkpoint of another version is refused.
- DEFAULT_
CHECKPOINT_ LIMIT - The bytes of one checkpoint body: 32 MiB.
- DEFAULT_
MAX_ CALLS_ PER_ TURN - The tool calls one model reply may make when none is set.
- DEFAULT_
MAX_ RESPONSE_ BYTES - The most of a response body read when no cap is set. A chat completion is kilobytes; the cap exists so an endpoint does not get to choose how much memory a turn takes.
- DEFAULT_
MAX_ TURNS - The turn bound when none is set.
- DEFAULT_
REQUEST_ LIMIT - The bytes one model request may hold: 8 MiB, the size the bundled adapter
accepts back from a provider
(
DEFAULT_MAX_RESPONSE_BYTES). - DEFAULT_
RESULT_ LIMIT - The bytes of one tool result the model is shown: 1 MiB.
- DEFAULT_
TIMEOUT - How long one turn may take, request and whole response, by default.
- ERROR_
BODY_ LIMIT - The most of an error response’s body kept in
ModelError::Status. - FINISH_
REASON_ LENGTH - The
finish_reasonof a reply that stopped at the model’s output limit. - FINISH_
REASON_ METADATA_ KEY - The
metadatakey that marks an answer cut off at the output limit. - FLUSH_
AFTER - How long text waits before it is appended, however little there is.
- FLUSH_
BYTES - The fewest bytes one append carries, unless
FLUSH_AFTERhas passed. - SEALED_
CHECKPOINT_ PREFIX - The prefix of a checkpoint body sealed by the loop’s journal cipher.
- TRACE_
ARTIFACT_ ID - The id of the artifact carrying the tool trace.
- TRACE_
LINE_ LIMIT - The most bytes of one trace line: name, arguments and result together.
Traits§
- Step
Journal - Where a run’s checkpoints are kept.
- Tool
- Something a model may call.
- Tool
Model - One completion turn of a model that can call tools.
- Tool
Policy - Asked before every tool call runs, whatever kind it is (native, recovered
from text, or repeated after a retry), and able to refuse it. Install with
ToolLoop::with_policy.
Functions§
- call_
digest sha256:<hex>of a call as an action: the tool, its arguments in canonical form, and who it is for (tenant, requester, task).- draft_
artifact_ id - The id of the artifact
turn’s text streams to:draft-1for the first.
Type Aliases§
- Journal
Future - What a journal’s methods return.