# Frontend Tools

> Let your agent interact with and update your React Native app's UI.

## What is this? [#what-is-this]

A frontend tool is a function that you register in your app. Your agent can call it, and the function runs on the device. Because the handler runs in your app, it has direct access to component state, native modules, and any library the app already uses. That's how an agent can "reach into" the app: update React state, switch a screen, open a sheet, or read local storage.

This page covers the "agent drives the UI" shape of frontend tools. To render a component for a tool call, see [Components as Tools](/react-native/deepagents/generative-ui/tool-based). To ask the user before a tool runs, see [Human-in-the-loop](/react-native/deepagents/human-in-the-loop).

## When should I use this? [#when-should-i-use-this]

Use frontend tools when your agent needs to:

- Read or modify React component state
- Call device APIs through native modules, such as haptics, the clipboard, or storage
- Navigate between screens
- Show alerts, toasts, or bottom sheets
- Interact with third-party libraries in your app

## How it works in code [#how-it-works-in-code]

<Steps>
  <Step>
    ### Wire CopilotKit middleware into your agent

    Deep Agents compile to LangGraph graphs, and `CopilotKitMiddleware` is the
    bridge. It reads the frontend tools from the request. It adds them to the
    tool list that the model sees. Without the middleware, a tool that you
    register with `useFrontendTool` or `useComponent` never reaches the model.

    <Tabs groupId="agent_language" items={['Python', 'TypeScript']} persist>
      <Tab value="Python">
        ```python title="agent.py"
        from deepagents import create_deep_agent
        from copilotkit import CopilotKitMiddleware

        agent = create_deep_agent(
            model="openai:gpt-6-luna",
            tools=[],  # Backend tools go here
            middleware=[CopilotKitMiddleware()],
            system_prompt=SYSTEM_PROMPT,
        )
        ```
      </Tab>
      <Tab value="TypeScript">
        In TypeScript, define your custom state as a middleware with
        `createMiddleware`, and pass it to `createDeepAgent` together with
        `copilotkitMiddleware`:

        ```ts title="agent.ts"
        import { createMiddleware } from "langchain";
        import { copilotkitMiddleware } from "@copilotkit/sdk-js/langgraph";
        import { z } from "zod";

        export const yourStateMiddleware = createMiddleware({
          name: "YourAgentState",
          stateSchema: z.object({
            yourAdditionalProperty: z.string().optional(),
          }),
        });

        // Pass both middlewares when constructing the agent:
        // createDeepAgent({ middleware: [yourStateMiddleware, copilotkitMiddleware], ... })
        ```
      </Tab>
    </Tabs>

    Without the middleware the run still completes, and the tool is never
    called, because the model was never told the tool exists. You do not
    write code to call a frontend tool: the middleware adds it to every model
    call, and the agent calls it like any other tool.

  </Step>
  <Step>
    ### Tell the model when to call it

    The forwarded tool arrives on every run, but a model with no instruction
    about it will answer in prose and never call it. Name the tool in
    `system_prompt` and say what it is for.

    ```python title="agent.py"
    SYSTEM_PROMPT = """
    You are a data visualization assistant.

    When the user asks for a chart, call `render_bar_chart` with a concise
    title and a `data` array of `{label, value}` items.

    Keep chat responses brief and let the chart do the talking.
    """
    ```

  </Step>
  <Step>
    ### Register a tool in the browser

    Deep Agents has no live demo on these pages yet, so the demo code below
    does not show for it. Here is a minimal frontend tool to start from. It
    says hello to the user:

    ```tsx title="page.tsx"
    import { z } from "zod";
    import { useFrontendTool } from "@copilotkit/react-core/v2";

    export function Page() {
      // ...

      useFrontendTool({
        name: "sayHello",
        description: "Say hello to the user",
        parameters: z.object({
          name: z.string().describe("The name of the user to say hello to"),
        }),
        handler: async ({ name }) => {
          alert(`Hello, ${name}!`);
          return `Said hello to ${name}!`;
        },
      });

      // ...
    }
    ```

    Ask the agent: `Say hello to Ada.` The browser shows an alert with
    `Hello, Ada!`, and the agent replies after it gets the result.

  </Step>
</Steps>

Register a frontend tool with `useFrontendTool`. Give it a name, a schema for its parameters, and a handler. The agent can then call it like any other tool, and your app runs it on the device.

`parameters` takes any [Standard Schema](https://standardschema.dev), such as a `zod` schema. `zod` is an optional peer dependency of `@copilotkit/react-native`, so add it to your app:

```bash
npm install zod
```

```tsx title="src/TaskScreen.tsx"
import { useState } from "react";
import { Text, View } from "react-native";
import { useFrontendTool } from "@copilotkit/react-native/headless";
import { z } from "zod";

export function TaskScreen() {
  const [filter, setFilter] = useState<"all" | "open" | "done">("all");

  useFrontendTool({ // [!code highlight:11]
    name: "filter_tasks",
    description: "Filter the visible task list by status.",
    parameters: z.object({
      status: z.enum(["all", "open", "done"]),
    }),
    handler: async ({ status }) => {
      setFilter(status);
      return { applied: true, status };
    },
  });

  return (
    <View style={{ padding: 16 }}>
      <Text>Current filter: {filter}</Text>
    </View>
  );
}
```

The handler receives the parsed, type-safe parameters and can do anything your app can do: update state, call an API, or call a native module. Its return value is sent back to the agent as the tool result, so the model can reason about what happened.

Mount the component under `CopilotKitProvider`, next to your chat. This example uses the prebuilt chat from `@copilotkit/react-native/components`. A chat you build yourself, like the one in the [quickstart](/react-native/deepagents/quickstart), works the same way.

```tsx title="App.tsx"
import { View } from "react-native";
import { CopilotKitProvider } from "@copilotkit/react-native/headless";
import { CopilotChat } from "@copilotkit/react-native/components";
import { TaskScreen } from "./src/TaskScreen";

// See the quickstart for emulator and device hosts.
const runtimeUrl = "http://localhost:8200/api/copilotkit";

export default function App() {
  return (
    <CopilotKitProvider runtimeUrl={runtimeUrl}>
      <View style={{ flex: 1 }}>
        <TaskScreen />
        <CopilotChat />
      </View>
    </CopilotKitProvider>
  );
}
```

<Callout type="info" title="Peer dependencies of the prebuilt chat">
  `@copilotkit/react-native/components` needs `@gorhom/bottom-sheet`, `react-native-gesture-handler`, `react-native-reanimated`, and `react-native-streamdown`. If you only use the hooks, import from `/headless` and skip them. See [Import surfaces](/react-native/deepagents/quickstart#import-surfaces).
</Callout>

Ask the agent to show only open tasks. "Current filter" changes to `open`, and the agent replies after it reads the `{ applied: true }` result.

## Handlers read the values from registration [#handlers-read-the-values-from-registration]

`useFrontendTool` registers the tool once and keeps that `handler`. If the handler reads a value from props or state, it sees the value from the last registration. Pass those values as the second argument, so the tool registers again when they change:

```tsx
useFrontendTool(
  {
    name: "add_task",
    description: "Add a task to the list that is open on screen.",
    parameters: z.object({ title: z.string() }),
    handler: async ({ title }) => {
      await saveTask(listId, title); // your own storage call
      return { added: title, listId };
    },
  },
  [listId], // [!code highlight]
);
```

A state setter from `useState` never changes, so the first example needs no second argument.

## Register one tool per call [#register-one-tool-per-call]

`useFrontendTool` registers one tool per call. The React package also has `useFrontendTools` for a list of tools that changes between renders. `@copilotkit/react-native` does not export it, so call `useFrontendTool` once per tool, with the same number of calls on every render.

To hide a tool from the agent without removing it, set `available: false`. To offer a tool to one agent only, set `agentId`.

## Draw the call in the chat [#draw-the-call-in-the-chat]

Add `render` to the same `useFrontendTool` call to show UI for the call in the chat. The prebuilt chat draws it, and so does a chat you build with `useRenderToolCall`. `render` must return a React Native element or `null`. A bare string type-checks, then throws inside the chat's `FlatList`. See [Tool Call Rendering](/react-native/deepagents/generative-ui/tool-rendering) for the full pattern.

## Before you ship [#before-you-ship]

Your agent discovers the name, description, and parameter schema through the runtime connection. Before you ship a tool:

- Keep the description narrow.
- Validate the inputs.
- Ask the user before an action that cannot be undone. Use [`useHumanInTheLoop`](/react-native/deepagents/human-in-the-loop) for that.
- Keep privileged changes, secret API calls, and authorization checks on your backend.

For every option, see the [`useFrontendTool` reference](/reference/react-native/hooks/useFrontendTool).

<IntegrationGrid path="frontend-tools" />
