---
title: "Give an Agent your app's tools"
description: "Write tools in your Convex backend with defineTools from @usehercules/agents, so a Hercules Agent can read and change your app's data for the user it helps."
image: "https://hercules.app/og/home"
---

# Give an Agent your app's tools

> Write tools in your Convex backend with defineTools from @usehercules/agents, so a Hercules Agent can read and change your app's data for the user it helps.

> **Note:** The 
>
> `@usehercules/agents`
>
>  package is in beta, so things may change.

App tools let a Hercules Agent work with your app's own data: look up an order, create a task, book a slot. You write them next to your Convex functions with `defineTools`, and your app serves them to the Agent. Every call names who it is for, checked by your app's Hercules Auth, so a tool acts for the right user.

- Hercules writes the tools and connects them to the Agent when you ask for them in the App Builder
- A tool's handler gets the verified caller. It never takes a user id from the model
- `returns` lists the fields an Agent may see, and everything else is removed

Your app needs Hercules Auth for app tools. See [Does my app need Hercules Auth?](#does-my-app-need-hercules-auth)

### How do I write a tool?

```ts convex/tools.ts
import { defineTools, tool } from "@usehercules/agents/convex";
import { v } from "convex/values";
import { internal } from "./_generated/api";

export const tools = defineTools({
  tools: {
    create_task: tool({
      description: "Creates a task for the signed-in user.",
      args: { title: v.string(), dueAt: v.optional(v.number()) },
      returns: v.object({ id: v.string(), title: v.string() }),
      annotations: { readOnlyHint: false },
      handler: (ctx, args, caller) =>
        ctx.runMutation(internal.tasks.createFor, {
          tokenIdentifier: caller.tokenIdentifier,
          ...args,
        }),
    }),
  },
});
```

```ts convex/http.ts
import { httpRouter } from "convex/server";
import { tools } from "./tools";

const http = httpRouter();
tools.registerRoutes(http);
export default http;
```

The tools are served at `https://<deployment>.convex.site/mcp`, as an MCP server (Model Context Protocol, the open standard Agents use to call tools). That path is fixed: it is where Hercules calls.

If `convex/http.ts` already routes the Agent's events with `support.registerRoutes(http)`, keep that line and add the two `tools` lines. Export your tools as `tools`, never as `support`: `convex/agent.ts` exports the Agent under that name, and `convex/http.ts` imports both.

A handler can call your app's queries, mutations, and actions with `ctx.runQuery`, `ctx.runMutation`, and `ctx.runAction`. Nothing else from Convex's context is offered. A tool's name can use letters, digits, `_`, and `-`, up to 64 characters.

### Who is calling?

A tool handler has no `ctx.auth`. The package checks the call's token itself, and passes the verified caller as the handler's third argument:

| `caller.principal` | Who                               | Fields                                                                                                                                                 |
| ------------------ | --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `"user"`           | A signed-in user of your app      | `tokenIdentifier` (the same `<issuer>\|<subject>` your app stores for their sign-in), `issuer`, `subject`, and `agentId` of the Agent calling for them |
| `"agent"`          | A Hercules Agent with no end user | `agentId`                                                                                                                                              |

Pass the caller to an internal function. Never take a user id from the tool's arguments: the model writes those.

```ts convex/tasks.ts
import { ConvexError, v } from "convex/values";
import { internalMutation } from "./_generated/server";

export const createFor = internalMutation({
  args: { tokenIdentifier: v.string(), title: v.string(), dueAt: v.optional(v.number()) },
  handler: async (ctx, { tokenIdentifier, ...task }) => {
    const user = await ctx.db
      .query("users")
      .withIndex("by_token", (q) => q.eq("tokenIdentifier", tokenIdentifier))
      .unique();
    if (user === null) throw new ConvexError("No account found for this user.");
    const id = await ctx.db.insert("tasks", { ...task, ownerId: user._id });
    return { id, title: task.title };
  },
});
```

### Can a tool run with no signed-in user?

Tools accept signed-in users only, unless they say otherwise. A tool an Agent may run with no end user, such as in a background job your app starts with `support.run`, lists both callers, and its handler handles both:

```ts
list_open_hours: tool({
  description: "Lists the shop's opening hours.",
  args: {},
  principals: ["user", "agent"],
  handler: (ctx) => ctx.runQuery(internal.shop.openHours, {}),
}),
```

A caller never sees, and cannot call, a tool that does not accept them.

### How are arguments and results checked?

- `args` are checked before the handler runs. Unknown fields are refused, and the model is told which field was wrong
- `returns` is enforced. Object fields it does not name are removed before the result leaves your app, so it is also the list of fields an Agent may see. Declare it on any tool that reads user data
- A `returns` that is a `v.object` or a `v.record` is also listed as the tool's output shape, and its result is sent as structured content. Any other `returns` is enforced the same way and sent as text
- `v.int64()` travels as a decimal string, and `v.bytes()` as base64

### Where does a tool's result go?

- To the Agent, which reads it to write its reply
- To your backend, on the call's `tool_call.completed` [event](https://hercules.app/docs/agents/run-events#what-does-a-tool-call-carry). `@usehercules/agents` stores it, and `support.readThreadDetails` reads it. A result over 32,000 characters of JSON is delivered as a preview
- Not to the chat. The `thread` query and the chat hooks show the tool's name and a one-line summary, such as "Ran create task", and never its result
- Not to the browser at all, by default. With `exposeToolDetails: true`, the run's live stream carries each result to the browser, where the user can read it in the network tools, though the chat still does not show it. See [Convex backend](https://hercules.app/docs/agents/convex-backend#what-does-the-page-see-of-tools)

### How does a tool report an error?

Throw `ToolError`, or a `ConvexError` with a string, to tell the model what went wrong in words it can act on. Any other error is logged, and reaches the model as a general failure, so internal details do not leak.

### Can an app have more than one set of tools?

Yes. Name each set when your app splits its tools by data or risk. Each one is its own MCP server with its own URL, and a token for one is refused by the others:

```ts
export const supportTools = defineTools({ name: "support", tools: { lookup_order } }); // served at /mcp/support
export const billingTools = defineTools({ name: "billing", tools: { refund_order } }); // served at /mcp/billing
```

Here `lookup_order` and `refund_order` are tools made with `tool(...)`. A name can use lowercase letters, digits, and dashes, and decides the path: a server is at `/mcp`, or at `/mcp/<name>` when it has a name. Call `registerRoutes(http)` on each set in `convex/http.ts`.

### How is each call checked?

Every call carries an RS256 JWT signed by your app's Hercules Auth (`HERCULES_OIDC_AUTHORITY`), issued for this server's own URL, and not expired. It must say who is calling in its `hercules_principal` claim. A token for your MCP server works nowhere else: not on your app's other functions, and not on another server. The claims are listed in [Event delivery](https://hercules.app/docs/agents/event-delivery#how-do-i-check-the-token).

- The package reads the issuer's keys from its OpenID discovery document, and keeps them for five minutes. While it cannot fetch them, it answers `503` with `Retry-After`, never `401`
- Hercules calls the server on your deployment's own `https://<deployment>.convex.site` address, and signs its tokens for that URL. The package accepts that address from `CONVEX_SITE_URL`, and from `CONVEX_CLOUD_URL` when `CONVEX_SITE_URL` is a custom domain
- A deployment that overrides both with custom domains must pass `audiences` to `defineTools`, with its `https://<deployment>.convex.site/mcp` URL, or every call is refused with `401`

Pass `issuer` or `audiences` to `defineTools` to change either.

### Additional FAQ

#### Does my app need Hercules Auth?

Yes. Hercules signs each call with your app's own Hercules Auth, so the app needs Hercules Auth
2.0, where each app has its own sign-in setup. Without it, Hercules has nothing to sign a call
with, and the Agent cannot use your tools. A tool also knows who a user is only when your app's
own Hercules Auth signed them in. See [Upgrade to Hercules Auth
2.0](https://hercules.app/docs/apps/users-auth/upgrade-to-hercules-auth-2).

#### Can I serve tools from a backend that isn't Convex?

The root `@usehercules/agents` export has the backend-neutral core: `createMcpHandler` and
`createTokenVerifier`, a function from a web `Request` to a `Response`. This release has an
adapter for Convex only.

#### What do app tools not support yet?

Server-sent events, resources, prompts, sampling, and elicitation.

Previous: [Embed an Agent chat in your app](https://hercules.app/docs/agents/embed-chat)

Next: [Agents API reference](https://hercules.app/docs/agents/api-reference)

Every docs page is listed in [llms.txt](https://hercules.app/docs/llms.txt).

```json
{
  "@context": "https://schema.org",
  "@graph": [
    {
      "@type": "Organization",
      "@id": "https://hercules.app/#organization",
      "name": "Hercules",
      "url": "https://hercules.app",
      "logo": {
        "@type": "ImageObject",
        "url": "https://hercules.app/logo-128.png"
      }
    },
    {
      "@type": "WebSite",
      "@id": "https://hercules.app/docs#website",
      "name": "Hercules",
      "url": "https://hercules.app/docs",
      "publisher": {
        "@id": "https://hercules.app/#organization"
      }
    },
    {
      "@type": "WebPage",
      "@id": "https://hercules.app/docs/agents/app-tools#webpage",
      "url": "https://hercules.app/docs/agents/app-tools",
      "name": "Give an Agent your app's tools",
      "description": "Write tools in your Convex backend with defineTools from @usehercules/agents, so a Hercules Agent can read and change your app's data for the user it helps.",
      "dateModified": "2026-11-16T18:50:30.000Z",
      "isPartOf": {
        "@id": "https://hercules.app/docs#website"
      },
      "breadcrumb": {
        "@id": "https://hercules.app/docs/agents/app-tools#breadcrumb"
      }
    },
    {
      "@type": "BreadcrumbList",
      "@id": "https://hercules.app/docs/agents/app-tools#breadcrumb",
      "itemListElement": [
        {
          "@type": "ListItem",
          "position": 1,
          "name": "Hercules",
          "item": "https://hercules.app/docs"
        },
        {
          "@type": "ListItem",
          "position": 2,
          "name": "Give an Agent your app's tools",
          "item": "https://hercules.app/docs/agents/app-tools"
        }
      ]
    },
    {
      "@type": [
        "Article",
        "TechArticle"
      ],
      "@id": "https://hercules.app/docs/agents/app-tools#article",
      "headline": "Give an Agent your app's tools",
      "name": "Give an Agent your app's tools",
      "description": "Write tools in your Convex backend with defineTools from @usehercules/agents, so a Hercules Agent can read and change your app's data for the user it helps.",
      "url": "https://hercules.app/docs/agents/app-tools",
      "mainEntityOfPage": {
        "@id": "https://hercules.app/docs/agents/app-tools#webpage"
      },
      "image": "https://hercules.app/og/home",
      "dateModified": "2026-11-16T18:50:30.000Z",
      "keywords": "app tools, defineTools, agent tools, tool handler, ToolError, tool caller, tokenIdentifier",
      "publisher": {
        "@id": "https://hercules.app/#organization"
      },
      "isPartOf": {
        "@id": "https://hercules.app/docs#website"
      },
      "inLanguage": "en-US"
    }
  ]
}
```
