///
This page provides a comprehensive API reference for the core `tool()` factory function and the `Tool` class, which are central to defining and managing AI-first tools in Better UI. For a broader unde
50 views
~50 views from guests
Guest views are estimated from total page views. These include anonymous visitors and users who weren't logged in when they viewed the page.
This page provides a comprehensive API reference for the core tool() factory function and the Tool class, which are central to defining and managing AI-first tools in Better UI. For a broader understanding of how these concepts fit into the framework, refer to the [Core Concepts] page.
Before diving into the tool() factory and Tool class, it's helpful to understand the related types that define their structure and behavior.
ToolContextThe ToolContext object provides environment-specific utilities and data to tool handlers. It intelligently strips server-only fields when executed on the client, ensuring security.
cache: A Map instance for in-memory caching, primarily used for deduplication of tool calls.fetch: The global fetch function, which can be overridden for custom requests (e.g., adding authentication headers).isServer: A boolean indicating whether the tool is currently executing in a server environment (true) or a client (browser) environment (false).env: (Server-only) Environment variables available to the server. Never accessible on the client.headers: (Server-only) Request headers from the incoming API call on the server. Never accessible on the client.cookies: (Server-only) Parsed cookies from the incoming API call on the server. Never accessible on the client.user: (Server-only) Authenticated user data, if available in the server context. Never accessible on the client.session: (Server-only) Session data, if available in the server context. Never accessible on the client.optimistic: (Client-only) A function to perform optimistic UI updates. Only available when running on the client.CacheConfig<TInput>Configuration for caching tool results.
ttl: Time-to-live for cache entries in milliseconds.key: An optional function to generate a custom cache key from the tool's input. If not provided, a default key is generated using JSON.stringify of the input.ClientFetchConfigConfiguration for the default client-side fetch behavior when no explicit .client() handler is defined.
endpoint: The API endpoint to which the client should make a POST request to execute the tool on the server. Defaults to /api/tools/execute.ToolConfig<TInput, TOutput>The object-based configuration for defining a tool.
name: A unique identifier for the tool.description: A human-readable description of the tool's purpose, used by AI models.input: A ZodSchema defining the expected input structure and types.output: An optional ZodSchema defining the expected output structure and types.tags: An array of strings for categorizing or tagging the tool.cache: Optional CacheConfig for caching tool results.clientFetch: Optional ClientFetchConfig to customize client-side auto-fetching.ServerHandler<TInput, TOutput>The type definition for a function that implements a tool's server-side logic.
ClientHandler<TInput, TOutput>The type definition for a function that implements a tool's client-side logic.
ViewState<TInput>The state object passed to a tool's view component, providing information about the tool's execution status and interactive capabilities.
loading: A boolean indicating if the tool is currently executing.error: An Error object if the tool execution failed, otherwise null.onAction: An optional callback function that can be triggered by user interactions within the view. This allows the view to re-execute the tool with new inputs (e.g., an increment button on a counter tool).ViewComponent<TOutput, TInput>The type definition for a React component that renders a tool's output.
tool() Factory FunctionThe tool() function is used to create new Tool instances. It supports two main patterns: object configuration and a fluent builder.
tool(config)Creates a new Tool instance using a configuration object.
config: An object conforming to ToolConfig<TInput, TOutput> specifying the tool's properties and schemas.Tool instance.tool(name)Initializes a ToolBuilder for a fluent API-based tool definition.
name: The unique name of the tool.ToolBuilder instance.Tool ClassThe Tool class represents a defined AI-first capability, encapsulating its definition, execution logic, and UI rendering.
name: readonly string
The unique identifier for the tool.description?: readonly string
A human-readable description of the tool's purpose.inputSchema: readonly z.ZodType<TInput>
The Zod schema defining the tool's input.outputSchema?: readonly z.ZodType<TOutput>
The Zod schema defining the tool's output.tags: readonly string[]
An array of tags for categorizing the tool.cacheConfig?: readonly CacheConfig<TInput>
The caching configuration for the tool, if defined.clientFetchConfig?: readonly ClientFetchConfig
The client-side fetch configuration for the tool, if defined.View: React.NamedExoticComponent<{ data: TOutput | null; loading?: boolean; error?: Error | null; onAction?: (input: TInput) => void | Promise<void>; }>
A memoized React component for rendering the tool's results. This component is automatically generated or wrapped around the custom ViewComponent provided via .view(). If no custom view is provided, it defaults to rendering raw JSON output.hasView: boolean
Returns true if a custom view component has been defined for the tool, false otherwise.hasServer: boolean
Returns true if a server-side implementation has been defined for the tool, false otherwise.hasClient: boolean
Returns true if a custom client-side implementation has been defined for the tool, false otherwise..server(handler)Defines the server-side implementation logic for the tool. This handler runs in a secure backend environment.
handler: A function conforming to ServerHandler<TInput, TOutput> that takes the validated input and a ToolContext object.Tool instance for chaining..client(handler)Defines the client-side implementation logic for the tool. This handler runs directly in the browser. If not defined, the client will automatically trigger a fetch to a server API endpoint to execute the tool's server logic.
handler: A function conforming to ClientHandler<TInput, TOutput> that takes the validated input and a ToolContext object.Tool instance for chaining..view(component)Defines the React component responsible for rendering the tool's results in the UI. This is a core differentiator of Better UI.
component: A React functional component conforming to ViewComponent<TOutput> that receives the tool's output data and current state.Tool instance for chaining..run(input, ctx?)Executes the tool with the given input. This method automatically determines whether to run the server-side or client-side handler based on the execution environment (isServer in ToolContext). It handles input validation, caching, and output validation.
input: The data to pass to the tool, which will be validated against inputSchema.ctx: An optional partial ToolContext object to override default context values.Promise that resolves with the tool's output data..call(input, ctx?)An alias for the .run() method, allowing for a more natural function-call syntax.
input: Same as run's input.ctx: Same as run's ctx.run's return..toJSON()Converts the tool instance into a plain JavaScript object, suitable for serialization. This method intentionally excludes sensitive information like handlers and schemas to prevent accidental exposure.
.toAITool()Converts the tool into a format compatible with the Vercel AI SDK (version 5 and later), allowing AI models to discover and execute it.
description, inputSchema, and an execute function for AI SDK integration. The execute function automatically calls the tool's .run() method with isServer: true.ToolBuilder ClassThe ToolBuilder class provides a fluent API for constructing Tool instances, offering a more readable and step-by-step definition process compared to the object-based configuration.
All builder methods return this (the ToolBuilder instance) for chaining, except input and output which return a new ToolBuilder type to update the generic TInput and TOutput parameters for improved type inference.
description(desc)Sets the description for the tool.
input<T>(schema)Sets the Zod schema for the tool's input. This method is crucial as it informs the TypeScript types for subsequent handler definitions.
output<O>(schema)Sets the Zod schema for the tool's output. This method updates the output type inference.
tags(...tags)Adds one or more tags to the tool.
cache(config)Configures caching for the tool.
clientFetch(config)Configures the default client-side fetch behavior.
server(handler)Sets the server-side implementation handler.
client(handler)Sets the client-side implementation handler.
view(component)Sets the React view component for the tool.
build()Finalizes the fluent definition and constructs the immutable Tool instance. This method must be called explicitly if you are using the builder pattern and need the final Tool object.
input schema has not been defined.ToolBuilder)For convenience, the ToolBuilder class also provides direct access to several methods that implicitly call build() and then delegate to the resulting Tool instance.
async run(input: TInput, ctx?: Partial<ToolContext>): Promise<TOutput>
Executes the tool (implicitly calling build() first).get View: React.NamedExoticComponent<{ data: TOutput | null; loading?: boolean; error?: Error | null; onAction?: (input: TInput) => void | Promise<void>; }>
Accesses the View component of the built tool.toJSON(): Delegates to the built tool's toJSON method.toAITool(): Delegates to the built tool's toAITool method.