# Tools

**What you will learn:** what a tool is in gvn, where tools live during a run, the two
names every tool has (the short name the model sees and the identity gvn stores and matches
on), how a run is checked against the tools it needs before it starts, and what you do as a
tool's author, an agent's builder and a workflow's author.

**Read first:** [Actors and events](actors-and-events.md). The tutorial
[4. Adding a tool](../tutorials/adding-a-tool.md) writes a tool by hand.
**Time:** about 10 minutes.

**Where this sits.** In the [loop that runs](index.md#picture-1-the-loop-that-runs), a tool
is work done in the **fulfillers** box: an actor asks for tool calls, and the Governor's tool
fulfiller runs them. The `Tool` interface and the `Toolbox` live in the
[harness layer](index.md#picture-2-the-layers-of-code); running them is the runtime's job.

## The picture: actors know which tools, the runtime holds them

A **tool** is work a model (or code) can ask for: an object with a short name, a description
written for the model, a schema for its arguments, and an `async run` that does the work.
Because a tool does I/O, it never runs inside an actor. The actor and the runtime each hold
a different part of it:

```mermaid
flowchart LR
    subgraph code ["Your code, when it builds the run"]
        direction TB
        objects["Tool objects<br/>look_up_order, issue_refund"]
    end
    subgraph actor_side ["Actor (stored in the journal)"]
        actor["Agent<br/>holds the tools' identities"]
    end
    subgraph runtime ["Runtime"]
        direction TB
        governor["Governor"]
        toolbox["Toolbox<br/>the Tool objects, by identity"]
    end
    objects -- "tools=[...]" --> actor
    objects -- "Toolbox([...])" --> toolbox
    governor -- "1. before the run: does the toolbox hold every tool the actor needs?" --> toolbox
    actor -- "2. invoke_tools: these calls, these identities" --> governor
    governor -- "3. runs them from" --> toolbox
```

- Your code builds each tool **once**, as an object, and passes that object everywhere a
  tool is meant: to the agent that may offer it to a model, to the `Toolbox` the runtime
  runs from, to a policy rule, to an evaluation check. A string where a tool is expected
  is a `TypeError` that says to pass the tool.
- The actor keeps only what identifies each tool, never the object, because an actor is
  stored in the journal and must not hold code.
- The runtime keeps the objects in a **toolbox**, and runs a call by looking its tool up
  there.

## Two names: the short name and the identity

Every tool has two names, for two readers:

- `name()`, the **short name**, is what the model sees and writes in its tool calls:
  `look_up_order`. It is chosen for the model, so it is short and plain.
- `identity()` is what gvn stores and matches on: the tool's **namespace**, a dot, and its
  short name: `shop.orders.look_up_order`. The namespace says where the tool comes from;
  by default it is the Python module that defines the tool's class (`namespace()` returns
  `type(self).__module__`). You never override `identity()`.

Two packages may both ship a tool called `look_up_order`; their identities still differ.
That is what the identity is for: everything that refers to a tool after the run is built
(the actor's stored list of tools, the calls in each request, the outcome's record of
calls, a policy rule, an evaluation check) refers to it by identity, so two tools that share
a short name are never confused. The short name appears only in what is exchanged with the
model and in what is shown to people.

Here are two such tools, one from the shop and one from billing.
[`FunctionTool`](../guides/shortcuts.md) wraps a plain function as a tool; one class backs
every `FunctionTool`, so it takes the namespace from the function's module, or from
`namespace=` as here:

```python
import typing

from gvn.kernel.schema import Record, Text
from gvn.shortcuts import FunctionTool


def find_order(order_id: str) -> dict[str, typing.Any]:
    return {"order_id": order_id, "status": "shipped"}


def find_invoice(order_id: str) -> dict[str, typing.Any]:
    return {"order_id": order_id, "paid": True}


shop_look_up = FunctionTool(
    "look_up_order", "Look up one order of the shop.", Record({"order_id": Text()}),
    find_order, namespace="shop.orders",
)
billing_look_up = FunctionTool(
    "look_up_order", "Look up the invoice of one order.", Record({"order_id": Text()}),
    find_invoice, namespace="billing.orders",
)
print(shop_look_up.name())       # look_up_order
print(shop_look_up.namespace())  # shop.orders
print(shop_look_up.identity())   # shop.orders.look_up_order
```

## One toolbox for the deployment, one name per agent

The two names come with two rules about uniqueness.

**A toolbox is unique by identity.** One deployment's toolbox may hold both tools: they are
different tools, and the runtime finds each by its identity.

```python
from gvn.harness.tools import Toolbox

toolbox = Toolbox([shop_look_up, billing_look_up])
print(toolbox.identities())  # ('billing.orders.look_up_order', 'shop.orders.look_up_order')
print(shop_look_up in toolbox)  # True
```

**One agent is offered one tool per short name.** The model calls a tool by its short name,
so an agent offered both could not tell them apart. Building it fails at once, naming both
identities:

```python
from gvn.harness.agent import Agent

try:
    Agent(name="clerk", instructions="Help.", tools=[shop_look_up, billing_look_up])
except ValueError as error:
    print(error)
```

```text
tools: two tools have the short name 'look_up_order': 'billing.orders.look_up_order' and 'shop.orders.look_up_order'; one actor may be offered only one of them
```

Give each agent the one it needs; the deployment's toolbox serves both agents.

## Checked before the run starts

Every actor answers `tool_identities()`: the identities of every tool it, and anything it
will build beneath it, may offer a model or ask to run. Before the Governor hands an actor
its first event (and on every later `deliver`, `answer`, `resume` and `wake`), it asks each
fulfiller whether it can serve that actor. The tool fulfiller and the model fulfiller
answer with the identities their toolbox does not hold, and the Governor refuses the call
with `Unfulfillable`, naming the actor and the missing identities. Nothing is journaled and
the actor is unchanged: a wrong wiring is found before any work is done, not halfway through
a run.

The same check refuses a toolbox that holds only a **same-named tool from another
package**. Here the agent is offered the shop's lookup, and the runtime holds only
billing's:

```python
import asyncio

from gvn.harness.events import Event
from gvn.runtime.fulfillers import ModelFulfiller, ToolFulfiller
from gvn.runtime.governor import Governor, Unfulfillable
from gvn.testing.fakes import ManualClock, MemoryJournal, RecordingOutput, ScriptedModel

clerk = Agent(name="clerk", instructions="Help.", tools=[shop_look_up])
print(clerk.tool_identities())  # frozenset({'shop.orders.look_up_order'})

billing_only = Toolbox([billing_look_up])
governor = Governor(
    fulfillers={
        "invoke_model": ModelFulfiller(model=ScriptedModel(script=[]), toolbox=billing_only),
        "invoke_tools": ToolFulfiller(toolbox=billing_only),
    },
    journal=MemoryJournal(),
    output=RecordingOutput(),
    clock=ManualClock(),
)
try:
    asyncio.run(
        governor.deliver(actor=clerk, event=Event("started", {"prompt": "Where is A-17?"}))
    )
except Unfulfillable as error:
    print(error)
```

```text
frozenset({'shop.orders.look_up_order'})
actor 'clerk' cannot be driven: the 'invoke_model' fulfiller lacks what it needs: the tool 'shop.orders.look_up_order', which the toolbox does not hold; it holds 'billing.orders.look_up_order' under the same short name
```

So a deployment's toolbox must hold every tool of every actor it drives. With the deployment
toolbox built earlier, which holds both lookups, the same agent runs.

## Who refers to tools, and how

Everything that names a tool takes the tool object, and everything that compares tools
compares identities:

| Where | What you pass | Page |
|---|---|---|
| An agent or a conversation | `tools=[...]`, Tool objects or a `Toolbox` | [The reference agent](reference-agent.md), [Conversations](conversations.md) |
| An errand's fixed calls | `FixedCall(call_id, tool, arguments)` | [Errands](errands.md) |
| A workflow | `Plan(..., tools=...)`: every tool any child may be offered or call | [Workflows in depth](workflows-in-depth.md#declared-tools) |
| A policy | `consultation.calls_to(tool)`; with `gvn-tools`, `Rules().approve(tool)` | [Rules](../tools/rules.md) |
| An evaluation check | `Gated([tool])`, `By(tool, when)`, `ApprovedFirst(stage, [tool])` | [Replay and evaluation](../guides/replay-and-evaluation.md) |
| A judge reading what a child did | `calls_to(outcome["tools"], tool)`, `is_call_to(entry, tool)` | [Workflows in depth](workflows-in-depth.md) |
| The short path | `run_agent(..., tools=[...])` | [The short path](../guides/shortcuts.md) |

A ready-made tool family of `gvn-tools` returns its tools as a named tuple, so you pick one
by attribute (`file_tools.write_file`) and pass the whole tuple where several are expected;
see [Tools](../tools/index.md).

### What a workflow declares

A workflow builds its children while it runs, so the Governor cannot look at them before the
run starts. Its **plan** declares them instead: `Plan(..., tools=...)` lists every tool any
child, or anything nested beneath a child, may be offered or call, the same way
`model_roles=` lists the model roles. The workflow answers those identities for
`tool_identities()`, so the runtime's toolbox is checked against them before the run, and
building a child that needs a tool the plan does not declare is a `ValueError` naming the
workflow, the stage, the child and the identities. Children of one plan may use different
tools with one short name; each child is still offered one tool per short name.

## For a tool's author

- **One class, one tool**: do nothing. The namespace is the module that defines the class,
  so a `LookUpOrder` defined in `shop/orders.py` is `shop.orders.look_up_order`. Define tools
  in a module of your package, not in the script you run: a class defined in a script run
  as `python script.py` lives in the module `__main__`, so its identity starts with
  `__main__`.
- **One class, many tools** (one per configuration, like `FunctionTool`, or the tools of an
  MCP server): take a `namespace=` in the constructor, check it with
  `gvn.harness.tools.namespace_checked`, and return it from `namespace()`. `FunctionTool`
  defaults to the function's module; the [MCP](../tools/mcp.md#identities) tools default to
  `gvn_tools.mcp.<prefix>`, and the deployer can set the namespace of each server.
- **A tool that wraps another** (to add a check, or to make an effect run once) and stands
  in for it returns the wrapped tool's `namespace()` and `name()`, so it keeps the wrapped
  tool's identity. Otherwise its identity is its own module's, and agents, policies and
  stored runs that refer to the wrapped tool no longer match it.
- **Say whether the results are untrusted.** A tool whose results may hold text written by
  someone the deployer does not control (a web page, a ticket, an issue, a server's answer)
  returns `True` from `untrusted()`; the default is `False`. An agent or a conversation that
  hands such a result to its model records the tool in its *exposure*, and its policy and
  its approver see that record with every later call. [Trust](trust.md) shows it at work.
- A namespace is a dotted identifier, like a module name. Choose it once: identities are
  stored in the journal, so renaming a namespace is renaming every stored reference to the
  tool.
- **Check the tool** with `gvn.testing.contracts.ToolContract`. Subclass it in a test module
  and return the tool as you would deploy it; pytest then checks that its short name is
  valid, its namespace is a dotted identifier, its identity is the namespace and the name
  joined by a dot and the same on every build, that it describes itself to the model, and
  that a toolbox finds it by its identity:

```python
from gvn.harness.tools import Tool
from gvn.testing.contracts import ToolContract


class TestShopLookUp(ToolContract):
    def make_tool(self) -> Tool:
        return shop_look_up
```

## Deeper: what is stored

The identity is the only form of a tool that is ever stored. An agent's
[durable form](reference-agent.md#deeper-durable-form) holds the sorted identities of its
tools; each `consult_policy`, `request_approval` and `invoke_tools` request carries
`"identities"`, one per call; every entry of an outcome's `"attempts"` and `"tools"` carries
`"identity"` beside the short `"name"` (see [outcomes](reference-agent.md#outcomes)). The
model's own replies keep short names, because that is what the model wrote. An identity is a
label that is compared, never imported or resolved to code: the runtime finds the tool by
looking the identity up in its toolbox.

Runs stored before tools had identities hold short names only; reading them needs the tools
they were offered, `Forms(tools=toolbox)`. See [Stability](../reference/stability.md).

## Recap

- A tool has a short `name()`, which the model sees, and an `identity()`, namespace plus
  name, which gvn stores and matches on.
- You pass tools as objects (or a `Toolbox`) everywhere; a string is refused.
- A deployment's toolbox may hold same-named tools from different packages; one agent is
  offered one tool per short name.
- Before a run starts, the Governor refuses an actor whose tools the toolbox does not hold,
  including when it holds only a same-named tool from another package.
- Workflows declare their children's tools on the plan with `Plan(tools=...)`.
- A tool class that backs many tools takes `namespace=`; `ToolContract` checks a tool.
- A tool whose results may hold text from outside the deployment declares `untrusted()`.

**Next:** [Sensors](sensors.md), the fixed measurements a harness takes after a tool
succeeds; then [The reference agent](reference-agent.md) puts tools to work in the agent gvn
ships.
