# useFrontendTool

> React hook for registering client-side tool handlers with optional UI rendering

## Overview [#overview]

`useFrontendTool` registers a client-side tool with CopilotKit at component scope. When the agent decides to call the tool, the provided `handler` function executes in the browser. Optionally, you can supply a `render` component to display custom UI in the chat showing the tool's execution progress and results.

The hook manages the full registration lifecycle: it warns if a tool with the same name already exists, registers the tool and its render component on mount, and removes the tool on unmount. The render component stays registered, so past tool calls still render in the chat history. Define `parameters` with a Standard Schema library such as [Zod](https://zod.dev). For a walkthrough, see [Frontend Tools](/frontend-tools).

## Signature [#signature]

```tsx
import { useFrontendTool } from "@copilotkit/react-core/v2";

function useFrontendTool<T extends Record<string, unknown>>(
  tool: ReactFrontendTool<T>,
  deps?: ReadonlyArray<unknown>,
): void;
```

## Parameters [#parameters]

<PropertyReference name="tool" type="ReactFrontendTool<T>" required>
  The tool definition object.

<PropertyReference name="name" type="string" required>
  A unique name for the tool. The agent references this name when deciding to
  call the tool. If a tool with this name is already registered, a warning is
  logged.
</PropertyReference>

<PropertyReference name="description" type="string">
  A natural-language description that tells the agent what the tool does and
  when to use it. If a LangGraph agent skips a mandatory tool, add an explicit
  instruction to its `system_prompt`. See [Common issues](/troubleshooting/common-issues).
</PropertyReference>

<PropertyReference name="parameters" type="StandardSchemaV1">
  A Standard Schema (for example Zod 3.24+, Valibot v1+, or ArkType v2+) that
  defines the tool's input parameters. The schema drives the
  advertised tool schema and type inference. Runtime arguments are JSON-parsed
  but are not validated against that schema.
</PropertyReference>

<PropertyReference
  name="handler"
  type="(args: T, context: FrontendToolHandlerContext) => Promise<unknown>"
>
  An async function that executes when the agent calls the tool. Receives the
  parsed arguments, typed from `parameters` but not validated against it, and
  the context object:

  - `toolCall` (`ToolCall`) -- the raw tool call metadata
  - `agent` (`AbstractAgent | undefined`) -- the agent instance that called
    the tool. Absent when the tool is called through WebMCP.
  - `signal` (`AbortSignal | undefined`) -- an `AbortSignal` that is aborted
    when the user stops the agent (via `stopAgent()` or `agent.abortRun()`).
    Long-running handlers can check `signal.aborted` to exit early.
  - `isReplay` (`boolean | undefined`) -- `true` when the call is run while
    the thread's history is restored (see `reconnectBehavior`); absent for a
    call from a live run.

  `FrontendToolHandlerContext` is exported from `@copilotkit/core`.

  To wait for the user before the tool returns, use [`useHumanInTheLoop`](/reference/hooks/useHumanInTheLoop).
</PropertyReference>

<PropertyReference
  name="render"
  type="React.ComponentType<{ name: string; toolCallId: string; args: Partial<T>; status: ToolCallStatus; result: string | undefined }>"
>
  An optional React component rendered in the chat interface to visualize tool
  execution. The component receives:

  - `name`: the tool name.
  - `toolCallId`: the ID of the tool call.
  - `args`: the arguments. Partial while streaming, complete once execution starts.
  - `status`: one of `ToolCallStatus.InProgress`, `ToolCallStatus.Executing`, or `ToolCallStatus.Complete`.
  - `result`: the string result returned by the handler. Only available when status is `Complete`.

  To render backend tool calls, use [`useRenderTool`](/reference/hooks/useRenderTool). To show a component from the tool arguments, use [`useComponent`](/reference/hooks/useComponent).
</PropertyReference>

  <PropertyReference name="available" type="boolean" default="true">
    Set to `false` to hide the tool from the agent without unregistering it.
  </PropertyReference>

  <PropertyReference name="reconnectBehavior" type='"passive" | "resume-pending"' default='"passive"'>
    What happens to a call of this tool that is still unanswered when the thread's history is restored, for example after a page reload. With `"passive"`, the call is shown but the handler does not run. With `"resume-pending"`, the handler runs for that call with `isReplay: true` in its context, and the run then continues as usual. Opt in only for a handler that is safe to run more than once. A call does not start twice at the same time on one page. A call can run again after a stop or a thread switch, if its result never reached the agent. Two tabs that restore the same thread can each run the call. If the agent calls this tool together with a tool that stays passive, the follow-up run sends the passive call without a result, which some model providers reject.
  </PropertyReference>

  <PropertyReference name="webmcp" type="boolean | { annotations?: { readOnlyHint?: boolean; untrustedContentHint?: boolean } }">
    Also expose the tool to browser agents through the WebMCP API
    (`document.modelContext`). Pass `true` to register with default
    annotations, or an object to register with WebMCP annotations. The same
    `handler` runs when a browser agent calls the tool; the context then has
    no `agent`. This is a no-op where WebMCP is not available (SSR, React
    Native, or browsers without the API enabled).
  </PropertyReference>
</PropertyReference>

<PropertyReference name="deps" type="ReadonlyArray<unknown>">
  An optional dependency array. When provided, the tool registration is
  refreshed whenever a value in the array changes. Use this when your handler
  or render function captures external state.

  `deps` compares plain data (strings, numbers, booleans, `null`, dates, and
  plain objects and arrays of those) by value, so an inline literal such as
  `[{ status }]` re-registers only when its contents change. A function never counts as changed, so keep a changing callback
  in a ref. Class instances and other objects compare by identity, so a
  circular value such as the `agent` from `useAgent` is safe to pass. Adding or removing an entry counts as a change.
</PropertyReference>

## Usage [#usage]

### Basic Tool with Zod Parameters [#basic-tool-with-zod-parameters]

```tsx
function TodoManager() {
  const [todos, setTodos] = useState<string[]>([]);

  useFrontendTool(
    {
      name: "addTodo",
      description: "Add a new item to the user's todo list",
      parameters: z.object({
        text: z.string().describe("The todo item text"),
        priority: z.enum(["low", "medium", "high"]).describe("Priority level"),
      }),
      handler: async ({ text, priority }) => {
        setTodos((prev) => [...prev, text]);
        return `Added "${text}" with ${priority} priority`;
      },
    },
    [],
  );

  return (
    <ul>
      {todos.map((t, i) => (
        <li key={i}>{t}</li>
      ))}
    </ul>
  );
}
```

### Tool with Custom Render Component [#tool-with-custom-render-component]

```tsx
import { useFrontendTool, ToolCallStatus } from "@copilotkit/react-core/v2";
import { z } from "zod";

function WeatherWidget() {
  useFrontendTool(
    {
      name: "getWeather",
      description: "Fetch and display weather information for a city",
      parameters: z.object({
        city: z.string().describe("City name"),
        units: z.enum(["celsius", "fahrenheit"]).default("celsius"),
      }),
      handler: async ({ city, units }, { signal }) => {
        const response = await fetch(
          `/api/weather?city=${city}&units=${units}`,
          { signal },
        );
        const data = await response.json();
        return JSON.stringify(data);
      },
      render: ({ args, status, result }) => {
        if (status === ToolCallStatus.InProgress) {
          return (
            <div className="animate-pulse">
              Fetching weather for {args.city}...
            </div>
          );
        }
        if (status === ToolCallStatus.Complete && result) {
          const data = JSON.parse(result);
          return (
            <div className="p-4 border rounded">
              <h3>{data.city}</h3>
              <p>
                {data.temperature}&deg; {data.units}
              </p>
              <p>{data.conditions}</p>
            </div>
          );
        }
        return null;
      },
    },
    [],
  );

  return null;
}
```

### Conditionally Available Tool [#conditionally-available-tool]

```tsx
function AdminPanel({ isAdmin }: { isAdmin: boolean }) {
  useFrontendTool(
    {
      name: "deleteUser",
      description: "Delete a user account by ID (admin only)",
      parameters: z.object({
        userId: z.string().describe("The ID of the user to delete"),
      }),
      handler: async ({ userId }) => {
        await fetch(`/api/users/${userId}`, { method: "DELETE" });
        return `User ${userId} deleted`;
      },
      available: isAdmin,
    },
    [isAdmin],
  );

  return <div>{/* admin UI */}</div>;
}
```

### Expose a Tool to Browser Agents (WebMCP) [#expose-a-tool-to-browser-agents-webmcp]

Pass `webmcp` to also register the tool on `document.modelContext`. Browser
agents that support [WebMCP](https://developer.chrome.com/docs/ai/webmcp) can
then discover and call the tool while the page is open.

```tsx
function OrderSearch() {
  useFrontendTool({
    name: "searchOrders",
    description: "Search the signed-in user's orders by status",
    parameters: z.object({
      status: z.enum(["open", "shipped", "delivered"]),
    }),
    handler: async ({ status }) => {
      const orders = await searchOrders(status);
      return JSON.stringify(orders);
    },
    webmcp: {
      annotations: { readOnlyHint: true },
    },
  });

  return null;
}
```

## Behavior [#behavior]

- **Duplicate detection**: If a tool with the same `name` is already registered, the hook logs a warning. Only one tool per name is active at a time.
- **Mount/Unmount lifecycle**: The tool and its optional render component are registered on mount. On unmount, the hook removes the tool. The render component stays registered, so past tool calls still render in the chat history.
- **Calls after unmount**: If the agent calls the tool after it was removed (for example, the component unmounted while the run was in flight), CopilotKit answers the call with a `Tool not found` error result and reports a `TOOL_NOT_FOUND` error, so the conversation can continue. This applies only to tools that were sent to the agent for that run, and only when the run finishes normally; an interrupted, stopped or failed run leaves the call open. A call to a name that was not sent to the agent for that run stays unanswered; register a wildcard tool (`name: "*"`) to handle those.
- **Dependency tracking**: When `deps` is provided, the tool registration is refreshed whenever a dependency changes. Plain data compares by value. A function never counts as changed. Class instances and other objects compare by identity.
- **WebMCP registration**: With `webmcp` set, the tool is also registered on `document.modelContext` and unregistered on unmount. The tool needs a `description` for this (WebMCP rejects tools without one).
- **Render component lifecycle**: If a `render` function is provided, it is added to the internal render tool calls registry. It receives streaming `args` (partial during `InProgress`, complete during `Executing` and `Complete`).
- **No return value**: The hook returns `void`.
