---
title: "Defining Tools"
description: "Every field of defineTool and the two schema rules it enforces. Plus the one import you must never write"
canonical_url: "https://tools.agntn.dev/guide/defining-tools"
---
# Defining Tools

> Every field of defineTool and the two schema rules it enforces. Plus the one import you must never write

`defineTool` takes one object and hands it back typed. It also checks the schema on the spot, so a mistake shows up when the module loads, not when a model finally calls the tool.

```ts [tools.ts]
import { defineTool, Type } from "@agntn/tools";

export const slugTool = defineTool({
  name: "text_slug",
  title: "Text Slug",
  description: "Turn a title into a lowercase URL slug.",
  snippet: "Use text_slug to turn a title into a URL slug.",
  guidelines: ["Pass separator '_' for identifiers. The default '-' is for URLs."],
  effect: "read",
  input: Type.Object(
    {
      text: Type.String({ minLength: 1, maxLength: 200, pattern: "\\S" }),
      separator: Type.Optional(Type.Enum(["-", "_", "."])),
    },
    { additionalProperties: false },
  ),
  execute: ({ text, separator = "-" }) => slugify(text, separator),
});
```

## The fields

<table>
<thead>
  <tr>
    <th>
      Field
    </th>
    
    <th>
      What it's for
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        name
      </code>
    </td>
    
    <td>
      The wire name. Lowercase letters, digits and <code>
        _
      </code>
      
      , starting with a letter, up to 64 characters. <code>
        <package>_<operation>
      </code>
      
       reads best. Say one twice in a list and every adapter throws, instead of letting each host pick its favourite
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        title
      </code>
    </td>
    
    <td>
      The human label. MCP calls it <code>
        title
      </code>
      
      , Pi and OMP call it <code>
        label
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        description
      </code>
    </td>
    
    <td>
      The whole instruction for the model. An MCP client sees nothing else, so don't save it for the guidelines
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        icons
      </code>
    </td>
    
    <td>
      Pictures for MCP clients that draw tools: <code>
        src
      </code>
      
      , then optional <code>
        mimeType
      </code>
      
      , <code>
        sizes
      </code>
      
       and <code>
        theme
      </code>
      
      . Optional, and only MCP looks
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        meta
      </code>
    </td>
    
    <td>
      MCP's <code>
        _meta
      </code>
      
       in <code>
        tools/list
      </code>
      
      , for keys like <code>
        ui
      </code>
      
       or <code>
        openai/extensions
      </code>
      
      . Optional, and only MCP sends it
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        output
      </code>
    </td>
    
    <td>
      A <code>
        Type.Object
      </code>
      
       schema of <code>
        details
      </code>
      
      . MCP lists it as <code>
        outputSchema
      </code>
      
       and sends <code>
        details
      </code>
      
       as <code>
        structuredContent
      </code>
      
      . Skip it for a tool only the model reads
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        snippet
      </code>
    </td>
    
    <td>
      Pi's <code>
        promptSnippet
      </code>
      
      . Optional
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        guidelines
      </code>
    </td>
    
    <td>
      Pi's <code>
        promptGuidelines
      </code>
      
      . Optional. They may add advice, never a promise the description doesn't make
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        effect
      </code>
    </td>
    
    <td>
      <code>
        read
      </code>
      
      , <code>
        write
      </code>
      
      , <code>
        destructive
      </code>
      
       or <code>
        exec
      </code>
      
      . Use <code>
        exec
      </code>
      
       for tools that start processes or run code. Drives MCP hints, the OMP approval tier and what happens on cancellation
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        idempotent
      </code>
    </td>
    
    <td>
      Whether calling twice changes nothing more. Defaults to <code>
        effect === "read"
      </code>
      
      . Set it to <code>
        false
      </code>
      
       for a read that draws something random
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        openWorld
      </code>
    </td>
    
    <td>
      Whether the call leaves the machine. Defaults to <code>
        false
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        input
      </code>
    </td>
    
    <td>
      A TypeBox object schema built with <code>
        Type
      </code>
      
       from this package
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        execute
      </code>
    </td>
    
    <td>
      Gets the checked input and <code>
        { signal, progress, ask, host }
      </code>
      
      , returns a <code>
        ToolResult
      </code>
      
       or a promise of one
    </td>
  </tr>
</tbody>
</table>

A `ToolResult` is `{ content, details, isError? }`. `content` is what the model reads, text blocks or an image. `details` is the same facts as data, for the hosts that keep it. `isError` marks an answer that's a failure but not a crash, like "nothing to slug in there".

## Import `Type` from here. Really

```ts
import { Type } from "@agntn/tools"; // yes
import { Type } from "typebox"; // no, and OMP is why
```

OMP rewrites every bare `typebox` import in an extension, and in everything that extension imports, to its own omptype facade. Its schemas are functions, not JSON Schema. A validator from `typebox/value`, which OMP leaves alone, then looks at a function and happily accepts any input you throw at it. No error, no warning, just validation quietly gone.

`@agntn/tools` bundles its own TypeBox, so there's no bare import left for OMP to touch. `defineTool` also refuses a schema that turned out to be a function and tells you where the `Type` came from. The schema types come from here too (`Static`, `TObject` and the rest), so your declarations name the same TypeBox the runtime uses.

## The two schema rules

`defineTool` walks the whole schema: properties, record values, array items and union branches. Two things fail it.

### An open object with properties

Every object that declares keys must say `additionalProperties: false`. Otherwise a misspelled key just disappears. `read_only` instead of `readOnly` once ran a tool with full access, and nothing complained. An empty `Type.Object({})` stays open, because models like to send `{ _: "" }` to a tool without arguments and that's harmless.

### A union of literals

`Type.Union([Type.Literal("a"), Type.Literal("b")])` has to be `Type.Enum(["a", "b"])`. The union serializes as a pile of `anyOf` objects about three times the size, and when it fails TypeBox says "must be equal to constant" about the first literal only. The enum says `must be one of a, b`. The model reads that and picks one. Good model.

## Optional text that may come empty

Some hosts fill every optional field, and an empty string is what they fill it with. If an empty value should mean "not given", let the schema accept it: no `minLength` on an optional string. Then trim in `execute` and treat blank as absent. A schema that refuses `""` pushes the model into inventing something, and invented arguments are worse than missing ones.

## Say it's still working

A tool that waits a minute looks exactly like a hung one. Unless it says something. `progress` in the call context sends one line per update:

```ts [tools.ts]
async execute({ id }, { signal, progress }) {
  for (let check = 1; ; check++) {
    const job = await checkJob(id, signal);
    if (job.done) return { content: [{ type: "text", text: `${id} is done` }], details: job };
    progress?.(`${id} still running, check ${check}`);
    await sleep(5_000, signal);
  }
}
```

Why the `?.`? Because not every host has a place for it:

<table>
<thead>
  <tr>
    <th>
      Host
    </th>
    
    <th>
      Where the line goes
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      MCP
    </td>
    
    <td>
      <code>
        notifications/progress
      </code>
      
      , only when the client sent a <code>
        progressToken
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      Pi
    </td>
    
    <td>
      <code>
        onUpdate
      </code>
      
       with one text block, so the call keeps spinning
    </td>
  </tr>
  
  <tr>
    <td>
      OMP
    </td>
    
    <td>
      Same, and the status line shows it next to the spinner
    </td>
  </tr>
  
  <tr>
    <td>
      CLI
    </td>
    
    <td>
      One stderr line, rewritten in place and wiped before the answer. On a terminal only
    </td>
  </tr>
  
  <tr>
    <td>
      AI SDK
    </td>
    
    <td>
      Nowhere. <code>
        progress
      </code>
      
       is <code>
        undefined
      </code>
    </td>
  </tr>
</tbody>
</table>

The second argument is optional. Know how far along you are? Pass `{ progress, total }`, like milliseconds against a timeout. MCP wants `progress` to grow with every notification. A value that goes back is dropped there, and a line without one counts one step up.

Every line goes through `sanitizeLine`. Once the call has answered, `progress` goes quiet. A forgotten timer can't talk over the result. And if a host chokes on a line, your call doesn't even notice.

## Esc means Esc, mostly

A cancelled `read` returns the abort reason right away. Even an `execute` that ignores `signal` can't hold the agent. A read already cancelled doesn't start.

`signal` aborts when someone hits Esc in Pi or OMP. It also aborts on MCP cancellation or AI SDK `abortSignal`.

The abandoned read keeps running until it finishes. Its late result or failure goes nowhere, and `progress` goes quiet. Want it to actually stop? Pass `signal` to your `fetch` or child process.

`write`, `destructive` and `exec` wait for `execute` after cancellation. The host may already have the write. Tell a model it was cancelled and it may send the write again. That's a bad bet.

## Ask the person, not the model

Three puzzles match the search. Which one did they mean? The model will guess, and it guesses with confidence. `ask` in the call context puts a small form in front of the person instead:

```ts [tools.ts]
async execute({ query }, { ask }) {
  const ids = await search(query);
  if (ids.length > 1 && ask) {
    const answer = await ask({
      message: `${ids.length} puzzles match "${query}". Which one?`,
      schema: Type.Object({ id: Type.Enum(ids) }),
    });
    if (answer.action !== "accept") return nothingPicked(answer.action);
    return await show(answer.content.id);
  }
  return await show(ids[0]);
}
```

`accept` comes with the fields. `decline` and `cancel` come with nothing, a no and a closed form. The fields pass your schema before you see them, and keys you didn't ask for get dropped. So `answer.content.id` really is one of the ids. A client can send back whatever it likes, it just doesn't get past `ask`.

The form is flat, because MCP elicitation is flat. Strings, numbers, booleans, `Type.Enum` picks and arrays of one enum, that's the menu. A nested object fails the call with a `ToolDefinitionError` before anyone sees a form. So does a rule on the form itself, like `minProperties`, since no client would ever enforce it.

<table>
<thead>
  <tr>
    <th>
      Host
    </th>
    
    <th>
      Where the form goes
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      MCP
    </td>
    
    <td>
      <code>
        elicitation/create
      </code>
      
      , only to a client that declared <code>
        elicitation
      </code>
    </td>
  </tr>
  
  <tr>
    <td>
      mcp-toolkit
    </td>
    
    <td>
      The same, once you pass <a href="https://tools.agntn.dev/hosts/mcp#can-it-ask-the-person">
        <code>
          useMcpElicitation
        </code>
      </a>
      
       and turn on sessions
    </td>
  </tr>
  
  <tr>
    <td>
      Pi
    </td>
    
    <td>
      One <code>
        ctx.ui
      </code>
      
       dialog per field, only while <code>
        ctx.hasUI
      </code>
      
       is set
    </td>
  </tr>
  
  <tr>
    <td>
      OMP
    </td>
    
    <td>
      The same dialogs
    </td>
  </tr>
  
  <tr>
    <td>
      CLI, AI SDK
    </td>
    
    <td>
      Nowhere. <code>
        ask
      </code>
      
       is <code>
        undefined
      </code>
    </td>
  </tr>
</tbody>
</table>

### MCP starts over

MCP can't pause a call. The server answers "I need input", the client asks the person, then calls again with the answer. So over MCP `execute` runs from the top for every answer, with the earlier ones replayed in order. Two questions, three runs.

Does that hurt? Only if something happens before the question. Ask first, write later, and ask in the same order every time. Pi and OMP simply wait for the dialog, so a tool written for MCP works there unchanged. The toolkit waits too. SDK v1 sends a real request and sits on it, so there `execute` runs once.

## Borrow what the host knows

Pi and OMP know the login and session. They hand over their own `ctx` untouched. The CLI brings its own [`CliHost`](https://tools.agntn.dev/guide/cli#rows-now-or-json-later). Is `--json` watching? The host can tell you.

MCP brings an [`McpHost`](https://tools.agntn.dev/hosts/mcp#who-called) when there's something to pass. It can contain the HTTP request and the call's `_meta`. That's useful context, not permission. The AI SDK brings nothing. Sometimes the host arrives with empty pockets.

`host` is typed `unknown`, because the core imports none of them. So you narrow it yourself:

```ts [tools.ts]
interface HostContext {
  readonly modelRegistry?: unknown;
  readonly sessionManager?: { getSessionId(): string };
}

async execute({ query }, { signal, host }) {
  const { modelRegistry, sessionManager } = (host ?? {}) as HostContext;
  return await search(query, { signal, modelRegistry, session: sessionManager?.getSessionId() });
}
```

The shapes differ. Pi's `modelRegistry` has `getProviderAuth`, OMP keeps its logins under `modelRegistry.authStorage`. The tool still has to answer on MCP, though. Keep a path that works without them. A shim over `pi.registerTool` would get you the same `ctx`, sure. It's also exactly the wrapper this package is here to delete.

## Keep the executor lazy

A Pi or OMP extension imports your tools at startup to register them. If the tools module imports your whole library, every agent start pays for it, even when nobody calls the tool. Load the heavy part on the first call:

```ts [tools.ts]
let operations: Promise<typeof import("./tool-operations.ts")> | undefined;

function loadOperations() {
  operations ??= import("./tool-operations.ts");
  return operations;
}

export const hashTool = defineTool({
  // …
  execute: async (params) => (await loadOperations()).hashCompute(params),
});
```

Registering the tools then costs the schema and nothing else.


## Sitemap

See the full [sitemap](https://tools.agntn.dev/sitemap.md) for all pages.
