Core

Tools

Tool definitions, tool sets, serialization, and tool errors.

Import from @anvia/core or @anvia/core/tool.

Tool

interface Tool<Args = unknown, Output = unknown> {
  readonly name: string;
  readonly approval?: ToolApprovalPolicy<Args>;
  definition(prompt: string): ToolDefinition | Promise<ToolDefinition>;
  call(args: Args, context?: ToolCallContext): Output | Promise<Output>;
  parseApprovalArgs?(args: unknown): Args;
}

type AnyTool = Omit<Tool<unknown, unknown>, "approval"> & {
  readonly approval?: unknown;
};

type ToolCallStreamEvent = {
  agentId: string;
  agentName?: string;
  event: unknown;
};

type ToolCallContext = {
  emitStreamEvent?(event: ToolCallStreamEvent): void | Promise<void>;
};

Purpose: normalized callable tool contract.

Return behavior: definition(...) exposes provider JSON schema; call(...) executes local logic. The optional context is used by runtime-managed tools such as streaming agent-tools. Approval metadata is passive and is not included in provider tool definitions.

Notable errors: tool implementations can throw arbitrary errors.

createTool and CreateToolOptions

type CreateToolOptions<InputSchema extends ZodSchema, OutputSchema extends ZodSchema | undefined = undefined> = {
  name: string;
  description: string;
  input: InputSchema;
  output?: OutputSchema;
  approval?: ToolApprovalPolicy<z.output<InputSchema>>;
  execute(args: z.output<InputSchema>, context: ToolCallContext): unknown | Promise<unknown>;
};

function createTool<InputSchema extends ZodSchema, OutputSchema extends ZodSchema | undefined = undefined>(
  options: CreateToolOptions<InputSchema, OutputSchema>,
): Tool<z.output<InputSchema>, ToolOutput<OutputSchema>>;

Purpose: create a typed tool from Zod input and optional output schemas.

Return behavior: parses arguments before execution and parses output when an output schema is supplied.

Notable errors: input or output validation errors throw from call(...); schema conversion can throw during creation.

ToolApprovalPolicy

type ToolApprovalContext<Args = unknown> = {
  toolName: string;
  args: Args;
  rawArgs: string;
  toolCallId?: string;
  internalCallId: string;
  run: ToolApprovalRunContext;
};

type ToolApprovalRunContext = {
  agentId: string;
  runId: string;
  sessionId?: string;
  metadata?: JsonObject;
};

type ToolApprovalPolicy<Args = unknown> = {
  when(ctx: ToolApprovalContext<Args>): boolean | Promise<boolean>;
  reason?: string | ((ctx: ToolApprovalContext<Args>) => string | Promise<string>);
  rejectMessage?: string | ((ctx: ToolApprovalContext<Args>) => string | Promise<string>);
};

type ToolApprovalRequest<Args = unknown> = ToolApprovalContext<Args> & {
  reason?: string;
  rejectMessage?: string;
};

Purpose: declare when a tool call requires approval and what approval prompt/rejection text should be used.

Return behavior: core prompt execution evaluates when(...) before running the tool. When approval is required, the active ToolApprovalsOptions.handler decides whether the tool runs or is skipped.

Notable errors: approval evaluators can surface errors thrown by when(...), reason(...), or rejectMessage(...); missing approval handlers throw ToolApprovalRequiredError.

AgentMiddleware

type CompletionRequestMiddlewareArgs = {
  turn: number;
  request: CompletionRequest;
  originalRequest: CompletionRequest;
};

type CompletionRequestMiddlewareResult =
  | { request: CompletionRequest }
  | undefined
  | void;

type CompletionResponseMiddlewareArgs = {
  turn: number;
  request: CompletionRequest;
  response: CompletionResponse;
  originalResponse: CompletionResponse;
};

type CompletionResponseMiddlewareResult =
  | { response: CompletionResponse }
  | undefined
  | void;

type ToolInputMiddlewareArgs = {
  toolName: string;
  args: string;
  originalArgs: string;
  turn: number;
  toolCallId?: string;
  internalCallId: string;
};

type ToolInputMiddlewareResult =
  | { args: JsonValue | string }
  | undefined
  | void;

type ToolResultMiddlewareArgs = {
  toolName: string;
  args: string;
  result: string;
  originalResult: string;
  turn: number;
  toolCallId?: string;
  internalCallId: string;
};

type ToolOutputMiddlewareArgs = ToolResultMiddlewareArgs;

type ToolOutputMiddlewareResult =
  | string
  | { result?: string; structuredResult?: ToolResultContent[] }
  | undefined
  | void;

interface AgentMiddleware {
  onCompletionRequest?(args: CompletionRequestMiddlewareArgs): CompletionRequestMiddlewareResult | Promise<CompletionRequestMiddlewareResult>;
  onCompletionResponse?(args: CompletionResponseMiddlewareArgs): CompletionResponseMiddlewareResult | Promise<CompletionResponseMiddlewareResult>;
  onToolInput?(args: ToolInputMiddlewareArgs): ToolInputMiddlewareResult | Promise<ToolInputMiddlewareResult>;
  onToolOutput?(args: ToolOutputMiddlewareArgs): ToolOutputMiddlewareResult | Promise<ToolOutputMiddlewareResult>;
  /** @deprecated Use onToolOutput instead. */
  onResult?(args: ToolResultMiddlewareArgs): string | undefined | Promise<string | undefined>;
}

function createMiddleware(middleware: AgentMiddleware): AgentMiddleware;

/** @deprecated Use AgentMiddleware instead. */
type ToolMiddleware = AgentMiddleware;

/** @deprecated Use createMiddleware instead. */
function createToolMiddleware(middleware: ToolMiddleware): ToolMiddleware;

Purpose: transform model requests, model responses, tool inputs, and tool outputs during agent runs.

Return behavior: returning undefined keeps the current value. Returning a replacement from onCompletionRequest, onCompletionResponse, onToolInput, or onToolOutput passes that value to later middleware and the runtime. Multiple middleware callbacks run in registration order. Agent-level middleware runs before request-level middleware. Skill runtime tools are excluded from tool output middleware.

Notable errors: errors thrown by middleware surface as prompt run errors.

ToolSet

class ToolSet {
  static fromTools(tools: Tool[]): ToolSet;
  addTool(tool: Tool): this;
  addTools(tools: Tool[] | ToolSet): this;
  deleteTool(toolName: string): boolean;
  contains(toolName: string): boolean;
  get(toolName: string): Tool | undefined;
  values(): Tool[];
  getToolDefinitions(prompt?: string): Promise<ToolDefinition[]>;
  call(toolName: string, args: string, context?: ToolCallContext): Promise<string>;
}

Purpose: storage and execution boundary for concrete tool implementations.

Return behavior: call(...) parses JSON args, executes the matching tool, and serializes the output as a string.

Notable errors: throws ToolNotFoundError, ToolJsonError, or ToolCallError.

Dynamic Tool Selection

type ToolSearchDocument = {
  toolName: string;
  definition: ToolDefinition;
  text: string;
  metadata?: VectorMetadata;
};

type EmbedToolsOptions = {
  content?: (tool: Tool, definition: ToolDefinition) => string | string[];
  metadata?: (tool: Tool, definition: ToolDefinition) => VectorMetadata | undefined;
  concurrency?: number;
};

interface DynamicToolIndex extends VectorSearchIndex<ToolSearchDocument> {
  readonly toolSet: ToolSet;
}

function embedTools(model: EmbeddingModel, tools: Tool[] | ToolSet, options?: EmbedToolsOptions): Promise<EmbeddedDocument<ToolSearchDocument>[]>;

function createToolIndex(model: EmbeddingModel, tools: Tool[] | ToolSet, options?: EmbedToolsOptions): Promise<DynamicToolIndex>;

function isDynamicToolIndex(value: unknown): value is DynamicToolIndex;

Purpose: build a searchable index of tool capabilities for AgentBuilder.dynamicTools(...).

Return behavior: embedTools(...) returns embedded tool records; createToolIndex(...) returns an in-memory vector index that also carries the executable ToolSet; isDynamicToolIndex(...) checks for that ToolSet marker.

Notable errors: tool definition or embedding failures reject the returned promise.

createThinkTool

type CreateThinkToolOptions = {
  name?: string;
  description?: string;
};

function createThinkTool(options?: CreateThinkToolOptions): Tool<{ thought: string }, string>;

Purpose: create a built-in private reasoning tool that echoes a thought string.

Return behavior: returns a tool named think unless overridden.

Notable errors: validation errors can occur if the model calls it with invalid arguments.

Serialization Helpers

type NormalizedToolOutput = string | ToolResultContent[];

function serializeToolOutput(output: unknown): string;
function isToolResultContentArray(value: unknown): value is ToolResultContent[];
function normalizeToolResultOutput(output: unknown): NormalizedToolOutput;
function toolResultContentToText(content: ToolResultContent[]): string;
function parseToolArgs(args: string): JsonValue;

Purpose: convert tool outputs and model-supplied argument strings.

Return behavior: parseToolArgs("") returns {}; serializeToolOutput(...) returns strings unchanged and JSON-stringifies other values. normalizeToolResultOutput(...) preserves ToolResultContent[] for multimodal tool results and serializes other values to text. toolResultContentToText(...) creates a display string for structured tool result content, rendering image blocks as media-type placeholders.

Notable errors: parseToolArgs(...) throws SyntaxError for invalid JSON. isToolResultContentArray(...) only recognizes text and image tool result blocks.

Error Classes

class ToolCallError extends Error {
  readonly cause?: unknown;
}

class ToolNotFoundError extends Error {
  readonly toolName: string;
}

class ToolJsonError extends Error {
  readonly cause?: unknown;
}

Purpose: typed failures from ToolSet.call(...).

Return behavior: thrown errors.

Notable errors: these are the notable tool errors.

For workflow guidance, see Creating Tools.