Tools
Conceptual guide: Tools.
ExecutableTool
import type { ZodObject, z } from "zod";
interface ExecutableTool<TSchema extends ZodObject<any> = ZodObject<any>> {
type?: "function";
kind?: "tool" | "agent";
name: string;
description: string;
schema: TSchema;
execute(input: z.infer<TSchema>, ctx: ToolContext): Promise<string | ToolResultPart[]>;
configure?(config: Record<string, any>): void;
summarize?(input: z.infer<TSchema>): string;
}| Field | Notes |
|---|---|
name | Must be unique across local, MCP, and provider tools. |
description | Sent to the model. This is prompt text. |
schema | Must be a Zod object. Use .describe() on fields. Call arguments are parsed with it before execute runs — execute receives the parsed value (defaults and transforms applied), and a mismatch returns a validation error tool result without calling execute. |
kind | Presentation only. "agent" renders as a subagent; execution is identical. |
summarize | Optional human-readable one-liner for a UI. |
configure | Optional hook for host-supplied configuration. |
ToolContext
interface ToolContext {
signal: AbortSignal;
emit: (chunk: ToolProgressChunk) => void;
reportUsage?: (usage: Stats) => void; // @experimental
span?: Span;
}
type ToolProgressChunk = string | { type: "turn-event"; event: TurnEvent };signal is the batch's signal, not the run's: it aborts when the run's signal aborts, with the run's reason, and when a sibling call in the same batch fails fatally, with that sibling's error as the reason. A tool that rethrows its signal's reason is reported as aborted, not as a second fatal.
emit with a string surfaces as action:progress. Emitting a wrapped TurnEvent is how nested agents forward their own event stream — it becomes action:child-event.
(registry was removed from ToolContext in 0.34.0. A tool that changes the agent it runs under uses that agent in closure scope — agent.registry.add(...), agent.skills.add(...). See Upgrading.)
ToolResultPart
type ToolResultPart =
| { type: "text"; text: string }
| { type: "file"; file: FileInfo };DeferredTool
import type { ZodObject, z } from "zod";
interface DeferredTool<TSchema extends ZodObject<any> = ZodObject<any>> {
type: "deferred";
name: string;
description: string;
schema: TSchema;
summarize?(input: z.infer<TSchema>): string;
timeout?: number; // ms a call may wait for its answer before it fails with `timeout`; unbounded when absent
}A tool definition with no execute: the model calls it like any other tool, and the caller answers. Calls go to the onToolCall handler on stream(), generate(), or agent.onToolCall(), or are answered from outside with toolCall(id).answer() / .fail(). Conceptual guide: Deferred tools.
| Field | Notes |
|---|---|
name | Must be unique across local, deferred, MCP, and provider tools. |
description | Sent to the model. This is prompt text. |
schema | Must be a Zod object. Call arguments are parsed with it before the handler runs — a mismatch returns a validation error tool result without calling it. |
summarize | Optional human-readable one-liner for a UI. |
timeout | Milliseconds a call may wait for its answer before it fails with a timeout error result (No answer for <name> within <ms>ms). Unset, a call waits until answered or cancelled. |
DeferredCall
interface DeferredCall<TInput = Record<string, unknown>> {
id: string; // the tool call id — pass it to toolCall(id)
name: string;
input: TInput; // already validated against the tool's schema
}What an onToolCall handler receives, with the ToolContext an execute would get. Return the result (string | ToolResultPart[]), throw for an execution error with the message as reason, or return nothing and leave the call waiting.
WaitingToolCall
interface WaitingToolCall {
answer(content: string | ToolResultPart[]): void;
fail(message: string): void;
}The deferred call the loop is waiting on, reached through toolCall(id) on a stream handle or an Agent — undefined once it has settled. The first settle wins; later ones do nothing.
isCall / isActionOf
import {
isActionOf,
isCall,
type DeferredCall,
type DeferredTool,
type TurnPart,
} from "@fifthrevision/axle";
declare const tool: DeferredTool;
declare const call: DeferredCall;
declare const part: TurnPart;
isCall(tool, call); // narrows DeferredCall to DeferredCallOf<typeof tool>, input typed
isActionOf(tool, part); // narrows a TurnPart to that tool's deferred action (pending parts excluded)Both are also exported from @fifthrevision/axle/ui.
type AnyTool = ExecutableTool | DeferredTool;StreamParams.tools, AgentConfig.tools, ToolRegistry.add(), and the registry constructor take AnyTool. Code that passes ExecutableTool[] is unaffected. ToolRegistry.get() still returns executable tools only — use getDeferred() / deferred() for the other kind.
ProviderTool
interface ProviderTool {
type: "provider";
name: string;
config?: Record<string, unknown>;
}Portable names and their native mappings:
| Portable | Anthropic | OpenAI | Gemini |
|---|---|---|---|
web_search | web_search_20260318 | web_search | googleSearch |
code_execution | code_execution_20260521 | code_interpreter | codeExecution |
Unmapped names pass through unchanged. config is raw passthrough — field names and placement are not portable. On Anthropic, web_search defaults to allowed_callers: ["direct"]; see Provider tools.
ToolDefinition
type ToolDefinition = Pick<ExecutableTool, "name" | "description" | "schema">;The schema-only shape sent to providers.
ToolRegistry
Conceptual guide: The tool registry.
new ToolRegistry(init?: { tools?: AnyTool[]; providerTools?: ProviderTool[] })| Method | Returns | Notes |
|---|---|---|
add(tool | tools) | void | Local or deferred tools — the kind is on the tool. Throws TOOL_REGISTRY_DUPLICATE on a name collision. |
addMcp(tool | tools) | void | MCP tools. Same duplicate check. |
addProvider(tool | tools) | void | Provider tools. Same duplicate check. |
remove(name) | boolean | Removes from all four maps. |
has(name) | boolean | Across all four. |
get(name) | ExecutableTool | undefined | Local, then MCP. Not provider or deferred tools. |
getDeferred(name) | DeferredTool | undefined | |
getProvider(name) | ProviderTool | undefined | |
executable() | ExecutableTool[] | Local + MCP. |
deferred() | DeferredTool[] | |
local() | ExecutableTool[] | |
mcp() | ExecutableTool[] | |
provider() | ProviderTool[] | |
size | number | Total across all four. |
Names are unique across all four maps — a local tool, a deferred tool, an MCP tool, and a provider tool cannot share a name.
createAgentTool()
createAgentTool<TSchema>(options: CreateAgentToolOptions<TSchema>): ExecutableTool<TSchema>interface CreateAgentToolOptions<TSchema> {
name: string;
description: string;
schema: TSchema;
createAgent: (input: z.infer<TSchema>, ctx: ToolContext) => MaybePromise<Agent>;
prompt?: string | ((input: z.infer<TSchema>) => string);
request?: AxleModelRequestOptions;
}Experimental
Subagent rendering shapes may change in a minor release.
Behavior:
- Returns a tool with
kind: "agent". createAgentruns per call. Return a fresh agent.promptdefaults to`Complete this delegated task. Input: ${JSON.stringify(input)}`.- Child turn events are forwarded via
ctx.emit; the subscription is removed when the call ends. - Child usage is reported via
ctx.reportUsage. - A non-
okchild result throwsError("Subagent failed (<kind>): <message>")naming the failure kind and message. - A non-string child response is
JSON.stringify'd. AxleToolFatalErrorandAxleAbortErrorfrom the child are rebuilt without the child'smessages/partial, so the parent never adopts another conversation's history.usageis preserved.ctx.signalis forwarded to the child send.
parallelize()
parallelize<TSchema>(
tool: ExecutableTool<TSchema>,
options?: ParallelizeOptions,
): ExecutableTool<ZodObject<{ items: z.ZodArray<TSchema> }>>interface ParallelizeOptions {
name?: string; // default `${tool.name}_batch`
description?: string;
maxItems?: number; // default 50
maxConcurrency?: number; // default 8, floor 1
maxResultBytes?: number; // default 20 MiB
}
interface ParallelToolResult<TInput = unknown> {
index: number;
input: TInput;
ok: boolean;
output?: string | ToolResultPart[];
error?: { type: "execution"; message: string };
}Experimental
The generated tool's result parts may change in a minor release.
Results preserve input order. Ordinary execution errors are reported per item; fatal and abort errors propagate and terminate the run. The call's arguments are validated as a whole before anything runs, so one invalid item rejects the call with a validation error naming the item's path (for example items.1.description). The generated schema requires at least one item and at most maxItems. The wrapped tool's kind is inherited, so parallelized subagents still render as subagent activity.
Web search
braveWebSearch(options: BraveWebSearchOptions): ExecutableToolAn executable tool named web_search — pass it as webSearch to the chatCompletions() provider that needs it, and request web_search as a provider tool as usual. (It used to return a backend registered with configureAxle; both are gone in 0.34.0. See Upgrading.)
import { chatCompletions, braveWebSearch } from "@fifthrevision/axle";
const provider = chatCompletions({ baseUrl: "https://api.together.ai/v1",
apiKey,
webSearch: braveWebSearch({ apiKey: braveKey }),
});interface BraveWebSearchOptions {
apiKey: string; // required and non-empty
endpoint?: string; // default https://api.search.brave.com/res/v1/llm/context
maxResults?: number; // default 5, range 1–50
candidateCount?: number;
maxTokens?: number;
maxSnippets?: number;
maxTokensPerUrl?: number;
maxSnippetsPerUrl?: number;
contextThresholdMode?: string;
country?: string;
searchLanguage?: string;
freshness?: "pd" | "pw" | "pm" | "py" | `${string}to${string}`;
timeoutMs?: number;
}interface WebSearchResult {
title: string;
url: string;
snippets: string[];
}Register it on the provider (above). The process-global configureAxle fallback it used to replace was removed in 0.34.0 — see Upgrading.
Custom search tools
Any search API works — write an ExecutableTool named web_search whose execute returns the results as a string, and pass it as webSearch:
import { chatCompletions, type ExecutableTool } from "@fifthrevision/axle";
import * as z from "zod";
declare const searchIndex: (query: string, signal: AbortSignal) => Promise<{ title: string; url: string; passages: string[] }[]>;
const internalSearchSchema = z.object({ query: z.string().trim().min(1).max(400) });
const internalSearch: ExecutableTool<typeof internalSearchSchema> = {
name: "web_search",
description: "Search the internal docs index for current information.",
schema: internalSearchSchema,
async execute({ query }, { signal }) {
const hits = await searchIndex(query, signal);
return JSON.stringify({
query,
results: hits.map((h) => ({ title: h.title, url: h.url, snippets: h.passages })),
});
},
};
const provider = chatCompletions({ baseUrl: "http://localhost:11434/v1",
webSearch: internalSearch,
});This is also how you point web_search at an internal corpus rather than the public web. Your agent code doesn't change at all — only what "search" means.
Do forward signal, so a cancelled send doesn't leave a search running.
The generated tool takes { query: string } (trimmed, 1–400 characters). The Brave tool returns JSON { query, results } where each result is { title, url, snippets }.