defineTool():
the argument and result types are inferred from its zod input, the arguments
are validated before execute runs, and the result drops in anywhere tools are
accepted (createAgent({ tools: [...] }), ToolRegistry.register(tool),
AgentBuilder.addTool(tool)).
Snippets on this page leave some names to you:provideris anyLLMProvider(offline:createMockProvider()).
tools list; see Hosted provider tools.
With many tools, mark them deferLoading so the model finds them with a built-in tool_search tool instead of receiving every definition on every call; see Tool search.
Tools written for the Vercel AI SDK (tool({ description, inputSchema, execute })) convert with fromAiSdkTools({ weather, sendEmail }), needsApproval included; see Migrating from the AI SDK.
defineTool() options
defineTool() checks the name, the description and the zod input when it is
called, and throws an error that says how to fix a bad value. Registering two
tools with the same name throws an error naming the conflict.
An option not in the table above is an error (LOUSHO_CONFIG_INVALID) with a
suggestion, so a misspelled safety option cannot leave a tool running without
approval: requireApproval: true gives 'requireApproval' is not a known option (did you mean 'needsApproval'?),
and inputSchema or parameters points to input. A defined tool spread back
in (defineTool({ ...tool, execute })) is accepted.
It also refuses (LOUSHO_CONFIG_INVALID) an input no model can satisfy:
- The root must be an object. Providers send tool arguments as a JSON
object, so
z.string()orz.array(...)at the root is rejected. Wrap it:z.object({ value: z.string() }). - No
z.date()orz.bigint()fields. A model writes an ISO string or a number there, and those schemas reject both, so every call would fail. Usez.coerce.date()(orz.iso.datetime()to keep the string) andz.coerce.bigint()(orz.number().int()).
ToolDescriptor: it carries its schema as
inputSchema (the same schema as input) and its execute function directly.
The .tool field (an ai v4 { description, parameters, execute } object) is
legacy: it is still built for compatibility, and is read per field — a
hand-written descriptor without inputSchema falls back to tool.parameters,
and one without execute falls back to tool.execute, independently.
What happens when the model calls a tool
- Validation first. The model’s arguments are parsed with
inputSchema(defaults, coercions and transforms applied) before hooks,needsApprovalandexecutesee them. Arguments that do not match never reachexecute: the model gets a structuredToolArgumentsValidationErrorresult and can retry. - Errors are results. A tool that throws gives the model
{ error, toolName, message, kind }(no stack trace) and the run continues. See Errors. - Parallel calls. Several calls in one model turn run concurrently; cap
them with
toolConcurrency(1for strictly sequential). Results reach the transcript in the model’s call order. See Parallel tool calls. - Size cap. A result whose JSON is longer than
maxToolResultChars(createAgent({ maxToolResultChars }), default50_000characters, about 12k tokens) reaches the model, and the transcript, as its head and tail with a marker saying how many characters were cut.Infinityturns the cap off.onToolResult, hooks andtool.doneevents still get the whole result. - Cancellation. A run’s
AbortSignalreaches each call asctx.abortSignal, so long-running work can stop early. - Progress. An
executewritten asasync function*streams snapshots of its output while it runs; the last one is the result. See Streaming partial results. - Many calls in one step. With
createAgent({ codeMode })the model can also call tools from a short JavaScript program (run_code), each call going through the same checks. See Code mode. - Retries after a crash. With durable execution a tool can run more than
once across a crash; use
ctx.toolCallIdas an idempotency key. See Durable execution.
Execute context
execute(args, ctx) always gets a real second argument, typed
ToolExecutionContext (exported from the package root; it replaces the ai
SDK’s ToolExecutionOptions), on every path that
runs a tool: the main loop, the call that runs after an approval, tools that
run in a sandbox (sandboxExecute(args, sandbox, ctx)) and a flow’s tool-call
node.
A
sandboxExecute(args, sandbox) that ignores the third argument keeps working.
Errors
Every way a tool call can fail reaches the model as the same result, so one check works everywhere (including the call that runs after an approval):error: the error’s name (TypeError,ToolArgumentsValidationError, …), or the kind’s default name for a failure that is not a thrown error.toolNameandmessage: the message only, never a stack, capped at 2,000 characters (... (truncated)marks a cut).kind: why the call failed.- Some kinds add fields:
issuesforvalidation,noteforrejected,reasonfordenied.
isError: true; tool-result events, onToolResult, postToolCall hooks and tool.error events see the call as failed.
Hiding exception text. A thrown error’s message goes to the model as it is, so
new Error('DB password=hunter2 connection refused') reaches it verbatim. Pass
toolErrorMessage to createAgent to replace the text of execution errors:
message in the result above (kind stays execution). The same text
reaches tool.error events, onToolResult and postToolCall hooks, so a client-facing stream
never carries the original; only your function sees the thrown error. Sub-agents inherit it. It
does not touch validation errors (they describe the model’s own bad arguments) or the other
kinds. If the function throws or returns a non-string, the message is The tool failed. and the run
carries on. Without the option, nothing changes.
Argument validation. The model’s arguments are parsed with the tool’s zod
inputSchema (for a legacy descriptor, tool.parameters) before the tool runs, so pre-tool hooks, the
needsApproval predicate and execute all receive the parsed value. Tools without a zod schema are
passed through unchanged. If the arguments do not match, execute is not called and preToolCall hooks are
skipped, because there is no valid call. The model gets a validation result it can retry from:
ToolArgumentsValidationError (with a typed issues array) is exported from the package root.
toolErrorResult({ toolName, error, kind?, toolCallId?, details? }) builds this
result; use it in your own tool wrappers so they match. A thrown error can pick
its kind by carrying a toolErrorKind property. An error extending
PropagatingToolError is not a result: it aborts the run.
Failed calls in the result
The model sees each failed call and may still answer as if it had worked, ending the run withfinishReason: 'stop'. result.toolErrors counts the
run’s tool calls whose result is an error (any kind above except not-run);
it is absent when none failed. It counts only the run’s own calls: the calls
that failed inside its sub-agents are counted on
result.usage.delegated.toolErrors. Check it before trusting text, or cap it with
limits.maxToolErrors: once that many calls have failed, the run stops before
its next model call with finishReason: 'budget-exceeded' and
result.budget.limit 'maxToolErrors' (or rejects with BudgetExceededError
under onExceeded: 'throw', see Budgets).
Built-in tools
Built-in descriptors are passed keyed by the name the agent uses:
createAgent({ tools: { current_date: currentDateTool } }). Spec files refer to
http, web-fetch, current-date and day-name by name (see
Configuration).
How http_request and web_fetch refuse private destinations: an IP-literal
host is checked before the request; a host name is resolved once, when the
connection is opened, every address it resolves to is checked (loopback,
RFC 1918, link-local including the cloud metadata address, CGNAT, multicast
and reserved ranges, IPv4-mapped IPv6, NAT64 and 6to4), and the socket
connects to the address that was checked. Redirects are followed by hand and
each hop is checked the same way. A DNS-rebinding name, one that answers a
public address first and a private one later, has no second lookup to answer.
When http_request runs through a sandbox, the host is resolved and checked
in the agent’s process and the sandboxed process connects to that address.
Both tools take allowPrivate (host patterns such as intranet.example or
*.corp.example) for hosts that may resolve to private addresses.
web_fetch takes { url } (http: or https:, no user:password@) and
returns { url, finalUrl, status, contentType, content, truncated }. It only
sends GET, with no body, cookies or caller-chosen headers. HTML becomes
plain text (scripts, styles and similar removed, block elements on their own
lines, link URLs in parentheses, entities decoded); JSON and text/* are
returned as sent; other types (images, PDFs, binaries) return a note instead
of content. A 4xx or 5xx response is returned with its body, not thrown, so
the model can read an error page. Refusals, timeouts, too many redirects and
bad URLs are tool errors that name the host. The page is untrusted input: the
tool’s description tells the model so, and readOnlyHint and openWorldHint
are set. Options of createWebFetchTool() (the vendor/ model prefix chooses
the provider; with OpenRouter use openrouter/<vendor>/<model>, e.g.
openrouter/openai/gpt-4o-mini):
createWebFetchTool() has its own connection pool, kept for as long as
the tool exists and released with it by garbage collection (there is no close
method). web_fetch does not exist in the Cloudflare Worker build, and the
Worker’s http_request is a different tool that reaches only the host names
listed in its LOUSHO_HTTP_ALLOW binding; see
Cloudflare Workers.
Todo tools
createTodoTools(options?) gives long-running agents a plan to track:
todo_write replaces the whole list ({ id?, content, status } items, status
pending | in_progress | completed, at most one in_progress) and returns
the list plus counts; todo_read returns it. Ids are assigned automatically and
stay stable when a later write repeats an item’s content. Invalid lists (for
example two in_progress) reach the model as a structured tool error so it can
retry. The list lives in memory per call; pass store ({ get, set }) to
persist it, and onChange to update a UI. Every successful todo_write also
emits a todo.updated stream event with the new list and its counts (see
Stream events), which the React,
Vue and Svelte bindings turn into
useTodos() / loushoTodos(), so a UI shows the plan live without onChange.
Advanced: ToolRegistry
createAgent() builds a registry for you; fill one yourself only with
AgentExecutor.execute() (see the executor API) or to
share tools between agents:
register(tool) for a defineTool() result, register(name, descriptor) for a
raw ToolDescriptor (a built-in tool, an MCP tool, or an existing tool() from
the ai SDK), and registerMany() for a record of descriptors or an array of defined tools.
toolRegistry to AgentExecutor.execute(); the agent config’s
tools map names the tools it may use.
Streaming partial results
A long tool (a report builder, a search over many sources) can show progress while it runs: writeexecute as an async function*. Every yield is a
complete snapshot of the output so far, which replaces the previous one, and
reaches the run’s events as tool.partial (see
Stream events). The last yielded value is the tool’s
result: the model gets it, and it is the result of the call’s tool.done, so
the final snapshot appears twice (as the last tool.partial and in
tool.done). A return value is ignored; a generator that yields nothing has
the result null, as does any tool that returns undefined: the transcript, the
model and tool.done all see null.
- Only the result is kept. Snapshots are not sent to the model, not added
to the transcript or the session, not checkpointed and not recorded in trace
spans. Hooks (
postToolCall,onToolResult) see only the result. - A crash loses them. Partial output is not durable: after a crash the
call has no result yet and runs again from the start (a new
tool.start,indexfrom 0). A pause for a sign-in inside the generator re-runs it from the start too, but the continued run reportstool.resumerather than a secondtool.start, again withindexfrom 0. Snapshots already streamed stay in the event log; a UI should drop them when the call pauses or starts again (the UI bindings do). - Approvals and permissions apply first. A generator tool that needs
approval runs, and streams, only after the decision (also on a streamed
resume,
agent.approvals.streamResolve()). - Cancellation. When the run is aborted, the SDK stops reading the
generator at once, settles the call as aborted and calls its
return(), so itsfinallyblocks run - once theawaitit is in settles, so passctx.abortSignalto the work you await. - Tokens are redacted in snapshots too. A snapshot that contains a token
the tool got from
ctx.getToken()has it replaced with[REDACTED], like the result. ApostToolCallhook that rewrites the result does not see the snapshots: if a tool’s output must be filtered by a hook, filter it in the tool or do not stream it. - Which values stream. Only a value with a
next()method that is also async iterable (what anasync function*returns) is streamed. A result that is only async iterable, such as aReadableStream, is an ordinary result. - The whole run counts.
toolConcurrencyholds the slot until the generator ends. Calling the tool’sexecuteyourself returns the generator. - Where. The main loop, the call that runs after an approval, and a flow’s
tool-call node (which keeps only the result) all iterate the generator; a
tool’s
sandboxExecutedoes not stream. In the AI SDK UI stream, snapshots are preliminary tool outputs (see AI SDK UI).