# Add a tool (/docs/plugins/guides/tool)

A tool is a function in your plugin's engine part that the agent can call. This guide builds `ticket_read`, which
reads a ticket from your tracker by its id.

<AgentPrompt prompt="tool" />

## Write the tool [#write-the-tool]

Add tools inside `ctx.tool.transform`. Each `tools.add` call adds one:

```ts twoslash title="conciv/plugins/tickets/server.ts" tab="Promise" tab-group="plugin-api"
import {z} from 'zod'
import {Plugin, Tool} from '@conciv/backend-plugin-api'

const Ticket = z.object({title: z.string(), status: z.string()})

export default Plugin.define({
  id: 'tickets',
  async setup(ctx) {
    await ctx.tool.transform((tools) => {
      tools.add({
        name: 'ticket_read', // <- letters, digits and _
        description: 'Read a ticket from the tracker by its id, such as OPS-42.',
        input: z.object({id: z.string().regex(/^OPS-[0-9]+$/)}), // <- checked before your code runs
        output: Ticket,
        options: {codemode: false},
        execute: async ({id}, context) => {
          try {
            const response = await fetch(`https://tickets.example.com/api/${id}`, {signal: context.signal})
            return {output: Ticket.parse(await response.json())}
          } catch {
            throw Tool.toolError({message: `The tracker did not answer for ${id}.`})
          }
        },
      })
    })
  },
})
```

```ts twoslash title="conciv/plugins/tickets/server.ts" tab="Effect" tab-group="plugin-api"
import {Effect} from 'effect'
import {z} from 'zod'
import {Plugin} from '@conciv/backend-plugin-api/effect'
import * as Tool from '@conciv/protocol/schema/tool'

const Ticket = z.object({title: z.string(), status: z.string()})

export default Plugin.define({
  id: 'tickets',
  effect: (ctx) =>
    ctx.tool.transform((tools) => {
      tools.add({
        name: 'ticket_read', // <- letters, digits and _
        description: 'Read a ticket from the tracker by its id, such as OPS-42.',
        input: z.object({id: z.string().regex(/^OPS-[0-9]+$/)}), // <- checked before your code runs
        output: Ticket,
        options: {codemode: false},
        execute: ({id}) =>
          Effect.tryPromise({
            try: async (signal) => {
              const response = await fetch(`https://tickets.example.com/api/${id}`, {signal})
              return Ticket.parse(await response.json())
            },
            catch: () => Tool.toolError({message: `The tracker did not answer for ${id}.`}),
          }).pipe(Effect.map((ticket) => ({output: ticket}))),
      })
    }),
})
```

Ask the agent "What is the status of OPS-42?". It calls `ticket_read` and answers from the ticket.

A few things to notice:

- `description` is how the agent decides when to call the tool. Say what it does and what input it expects.
- What you return as `output` is what the agent reads. It must match the `output` schema.
- A network error and a bad shape both fail the call with the same message, in both tabs.
- The signal aborts when the user stops the turn. Pass it to `fetch` so the request stops too.

## Direct or code mode [#direct-or-code-mode]

A tool is a code-mode tool unless you set `codemode: false`. In code mode the agent writes a short TypeScript program
that calls your tool as `external_ticket_read`. The call shows inside its code card. The agent calls a direct tool by
its name. Each call gets its own card.

<Playground
  page="vite-react"
  script="plugins/tool-direct-vs-codemode"
  caption="The same tool in code mode, then as a direct tool"
/>

Pick direct when the user should see each call, or when you draw a card for it. Learn more in
[Tools and code mode](/docs/tools-and-code-mode).

## Group tools under a namespace [#group-tools-under-a-namespace]

A namespace puts related tools under one name and one description:

```ts twoslash title="conciv/plugins/tickets/server.ts" tab="Promise" tab-group="plugin-api"
import {z} from 'zod'
import {Plugin} from '@conciv/backend-plugin-api'

export default Plugin.define({
  id: 'tickets',
  async setup(ctx) {
    await ctx.tool.transform((tools) => {
      tools.namespace({name: 'ticket', description: 'The team tracker: read and search tickets.'})
      tools.add({
        name: 'read',
        description: 'Read a ticket by its id, such as OPS-42.',
        input: z.object({id: z.string()}),
        options: {namespace: 'ticket'}, // <- the full name becomes ticket_read
        execute: async ({id}) => ({content: `${id} is open.`}),
      })
    })
  },
})
```

```ts twoslash title="conciv/plugins/tickets/server.ts" tab="Effect" tab-group="plugin-api"
import {Effect} from 'effect'
import {z} from 'zod'
import {Plugin} from '@conciv/backend-plugin-api/effect'

export default Plugin.define({
  id: 'tickets',
  effect: (ctx) =>
    ctx.tool.transform((tools) => {
      tools.namespace({name: 'ticket', description: 'The team tracker: read and search tickets.'})
      tools.add({
        name: 'read',
        description: 'Read a ticket by its id, such as OPS-42.',
        input: z.object({id: z.string()}),
        options: {namespace: 'ticket'}, // <- the full name becomes ticket_read
        execute: ({id}) => Effect.succeed({content: `${id} is open.`}),
      })
    }),
})
```

The agent reads the namespace's description to decide which group to look at. `content` is plain text for the
agent, in place of an output. A result can carry both.

## Fail a call [#fail-a-call]

Fail a call when the tool cannot do what was asked. The agent reads the message and can try something else:

```ts twoslash title="conciv/plugins/tickets/server.ts" tab="Promise" tab-group="plugin-api"
import {z} from 'zod'
import {Plugin, Tool} from '@conciv/backend-plugin-api'

export default Plugin.define({
  id: 'tickets',
  async setup(ctx) {
    await ctx.tool.transform((tools) => {
      tools.add({
        name: 'ticket_close',
        description: 'Close a ticket by its id.',
        input: z.object({id: z.string()}),
        execute: async ({id}) => {
          if (id.startsWith('SEC-'))
            throw Tool.toolError({message: 'Security tickets are closed by the security team.'})
          return {content: `${id} is closed.`}
        },
      })
    })
  },
})
```

```ts twoslash title="conciv/plugins/tickets/server.ts" tab="Effect" tab-group="plugin-api"
import {Effect} from 'effect'
import {z} from 'zod'
import {Plugin} from '@conciv/backend-plugin-api/effect'
import * as Tool from '@conciv/protocol/schema/tool'

export default Plugin.define({
  id: 'tickets',
  effect: (ctx) =>
    ctx.tool.transform((tools) => {
      tools.add({
        name: 'ticket_close',
        description: 'Close a ticket by its id.',
        input: z.object({id: z.string()}),
        execute: ({id}) =>
          id.startsWith('SEC-')
            ? Effect.fail(Tool.toolError({message: 'Security tickets are closed by the security team.'}))
            : Effect.succeed({content: `${id} is closed.`}),
      })
    }),
})
```

`Tool.toolError` makes the error. Its `message` is what the agent sees. In the Promise tab, any other thrown
error also fails the call, with that error's message. In the Effect tab the failure type is `Tool.Error`.

Errors of your own come from one evlog error catalog, in your plugin's `errors.ts`. Each entry has a `message`, and
`why` and `fix` where someone can act on it:

```ts title="conciv/plugins/tickets/errors.ts"
import {defineErrorCatalog} from 'evlog'

export const ticketErrors = defineErrorCatalog('tickets', {
  TRACKER_DOWN: {
    message: ({id}: {id: string}) => `The tracker did not answer for ${id}.`,
    fix: 'Check that the tracker is up, then ask again.',
  },
})

declare module 'evlog' {
  interface RegisteredErrorCatalogs {
    tickets: typeof ticketErrors
  }
}
```

Fail with `Effect.fail(ticketErrors.TRACKER_DOWN({id}))`. Turn it into a `Tool.Error` once, at the edge, and branch
on `error.code`, never on a tag:

```ts
Effect.catchIf(
  (error) => error.code === ticketErrors.TRACKER_DOWN.code,
  (error) => Effect.fail(Tool.toolError({message: error.message, error})),
)
```

## Draw a card [#draw-a-card]

Each call of a direct tool shows as a card in the chat. Your plugin's browser part can draw its own. You write the
browser part in Solid, React, Preact or plain DOM:

<Tabs groupId="ui-framework" persist items={['Solid', 'React', 'Preact', 'Plain DOM']}>
<Tab value="Solid">

```tsx twoslash title="conciv/plugins/tickets/plugin-experimental.tsx"
// @jsx: preserve
// @jsxImportSource: solid-js
// ---cut---
import {Plugin, ToolRegistry} from '@conciv/frontend-plugin-api'
import {z} from 'zod'

const Ticket = z.object({title: z.string(), status: z.string()})

function readTicket(output: string | undefined) {
  try {
    return Ticket.safeParse(JSON.parse(output ?? '')).data
  } catch {
    return undefined
  }
}

export default Plugin.define({
  setup(ctx) {
    ctx.add(ToolRegistry, {
      name: 'ticket_read',
      render: (props) => {
        const ticket = () => readTicket(props.output) // <- output is JSON text once the call ends
        return (
          <p>
            {ticket()
              ? `${ticket()?.title}: ${ticket()?.status}`
              : props.output === undefined
                ? 'Reading the ticket'
                : 'No ticket to show'}
          </p>
        )
      },
      errorComponent: (props) => <p>The ticket could not be read: {props.error}</p>, // <- a failed call
    })
  },
})
```

</Tab>
<Tab value="React">

The card lives in your app. Give it to `<ConcivWidget>` as in
[Build your first plugin](/docs/plugins/first-plugin#build-or-wire-the-browser-part).

```tsx twoslash title="src/conciv/tickets.tsx"
// @jsx: react-jsx
// @jsxImportSource: react
// ---cut---
import {ToolRegistry, type Plugin, type ToolProps} from '@conciv/frontend-plugin-api'
import {reactRender} from '@conciv/react'
import {z} from 'zod'

const Ticket = z.object({title: z.string(), status: z.string()})

function readTicket(output: string | undefined) {
  try {
    return Ticket.safeParse(JSON.parse(output ?? '')).data
  } catch {
    return undefined
  }
}

function TicketCard(props: ToolProps) {
  const ticket = readTicket(props.output) // <- output is JSON text once the call ends
  if (ticket) return <p>{`${ticket.title}: ${ticket.status}`}</p>
  return <p>{props.output === undefined ? 'Reading the ticket' : 'No ticket to show'}</p>
}

function TicketError(props: ToolProps) {
  return <p>The ticket could not be read: {props.error}</p>
}

export const tickets: Plugin.Setup = (ctx) => {
  ctx.add(ToolRegistry, {
    name: 'ticket_read',
    render: reactRender(TicketCard),
    errorComponent: reactRender(TicketError), // <- a failed call
  })
}
```

</Tab>
<Tab value="Preact">

The card lives in your app. Give it to `<ConcivWidget>` as in
[Build your first plugin](/docs/plugins/first-plugin#build-or-wire-the-browser-part).

```tsx twoslash title="src/conciv/tickets.tsx"
// @jsx: react-jsx
// @jsxImportSource: preact
// ---cut---
import {ToolRegistry, type Plugin, type ToolProps} from '@conciv/frontend-plugin-api'
import {preactRender} from '@conciv/preact'
import {z} from 'zod'

const Ticket = z.object({title: z.string(), status: z.string()})

function readTicket(output: string | undefined) {
  try {
    return Ticket.safeParse(JSON.parse(output ?? '')).data
  } catch {
    return undefined
  }
}

function TicketCard(props: ToolProps) {
  const ticket = readTicket(props.output) // <- output is JSON text once the call ends
  if (ticket) return <p>{`${ticket.title}: ${ticket.status}`}</p>
  return <p>{props.output === undefined ? 'Reading the ticket' : 'No ticket to show'}</p>
}

function TicketError(props: ToolProps) {
  return <p>The ticket could not be read: {props.error}</p>
}

export const tickets: Plugin.Setup = (ctx) => {
  ctx.add(ToolRegistry, {
    name: 'ticket_read',
    render: preactRender(TicketCard),
    errorComponent: preactRender(TicketError), // <- a failed call
  })
}
```

</Tab>
<Tab value="Plain DOM">

```ts twoslash title="conciv/plugins/tickets/plugin-experimental.ts"
import {mountRender, Plugin, ToolRegistry, type ToolProps} from '@conciv/frontend-plugin-api'
import {z} from 'zod'

const Ticket = z.object({title: z.string(), status: z.string()})

function describeCall(output: string | undefined) {
  try {
    const ticket = Ticket.parse(JSON.parse(output ?? '')) // <- output is JSON text once the call ends
    return `${ticket.title}: ${ticket.status}`
  } catch {
    return output === undefined ? 'Reading the ticket' : 'No ticket to show'
  }
}

function drawLine(text: (props: ToolProps) => string) {
  return mountRender<ToolProps>((element, props) => {
    const line = element.appendChild(document.createElement('p'))
    const stop = props.subscribe(() => {
      line.textContent = text(props.current())
    })
    return () => {
      stop()
      line.remove()
    }
  })
}

export default Plugin.define({
  setup(ctx) {
    ctx.add(ToolRegistry, {
      name: 'ticket_read',
      render: drawLine((props) => describeCall(props.output)),
      errorComponent: drawLine((props) => `The ticket could not be read: ${props.error}`), // <- a failed call
    })
  },
})
```

</Tab>
</Tabs>

A few things to notice:

- `render` draws one call. It runs again as the call moves on. `props.input` is the input the agent sent.
- A denied or cancelled call reaches `render` too, with text that is not JSON. The guarded parse keeps the card up.
- `errorComponent` draws a failed call, with the message in `props.error`. Without it the widget shows its error
  card.
- A card that pulls in a large library can load on its first call: give `render` a component made with Solid's
  `lazy()`. Learn more in [Load a part lazily](/docs/plugins/reference#load-a-part-lazily).

Build or wire it as in [Build or wire the browser part](/docs/plugins/first-plugin#build-or-wire-the-browser-part),
then reload.

<Accordions>
<Accordion title="The schemas a tool can take">

A tool's input and output schemas can be:

- a zod schema
- any other Standard Schema, such as Valibot or ArkType
- an Effect Schema
- a raw JSON Schema object

</Accordion>
</Accordions>

## Next steps [#next-steps]

- **[Ask for permission](/docs/plugins/guides/permission)**: make the user approve a call before it runs.
- **[Test your plugin](/docs/plugins/guides/testing)**: call your tool on a real engine in a test.
- **[Plugin API reference](/docs/plugins/reference)**: every field of a tool and its context.
