# Tools

https://ailoy.co/docs/guides/tools/

The built-in tools, functions of your own, and the tools of MCP servers and the browser.

An agent calls the tools you give it on the `AgentBuilder`: the built-in ones on this page, functions of your own, the tools of an [MCP server](https://ailoy.co/docs/guides/using-mcp/) or of the [browser](https://ailoy.co/docs/guides/using-browser/), and [the one `memory(...)` adds](#memory).

## Built-in tools

### A shell and files

An agent given a sandbox with `sandbox(...)` gets a shell and tools to read and change files in it, with nothing else to call. Which tools come with the shell depends on the model's org:

| Org | Tools |
| --- | --- |
| `openai` | `shell`, `apply_patch`, `imgread` |
| `google` | `shell`, `read_file`, `write`, `edit`, `imgread` |
| `deepseek-ai`, `moonshotai`, `zai-org`, `Qwen`, `LGAI-EXAONE` | `shell`, `read`, `write`, `edit` |
| Any other, `anthropic` included | `shell`, `read`, `write`, `edit`, `imgread` |

| Tool | What it does |
| --- | --- |
| `shell` | Runs a command, with an optional timeout in seconds. |
| `read` | Reads up to 2,000 numbered lines of a text file, or `limit` lines from line `offset`. |
| `read_file` | Reads up to 2,000 lines of a text file, or the lines from `start_line` to `end_line`. |
| `write` | Writes a text file, replacing one already at that path. |
| `edit` | Replaces an exact string that occurs once in a text file, or, with `replace_all`, every occurrence of it. |
| `apply_patch` | Adds, deletes, updates and moves files, from a patch in the format Codex uses. |
| `imgread` | Reads a PNG, JPEG, GIF or WebP image of up to 5 MB and gives it to the model as an image. |

`imgread` is left out for `deepseek-ai`, `moonshotai`, `zai-org`, `Qwen` and `LGAI-EXAONE` because their backends pass a tool result to the model as text, so the model would get a label in place of the image.

The seven tools in the table come with `sandbox(...)` and run in that sandbox, as in [Giving an agent a sandbox](https://ailoy.co/docs/guides/sandbox/); an agent without one does not get them. The agent does not start, stop or remove its sandbox. virtx stops an idle sandbox's VM and boots it again over what it wrote when it is next needed, so a later call finds the files as the last one left them.

### The web

`web_search_tool` and `web_fetch_tool` (`webSearchTool`, `webFetchTool`) do not come with the sandbox. The two tools run in your program's process, not in the sandbox, so they work without one.

- `web_search` sends the query to several search engines at once and merges what they find, one result per URL, best first. It answers with up to 10 results, or up to 30 when the model asks for more. `web_search_tool` takes the engines to use: `Bing`, `Brave`, `DuckDuckGo`, `Google`, `Mojeek`, `Naver`, `Startpage`, `Yahoo` and `Yandex`. None, or an empty list, uses them all.
- `web_fetch` fetches one URL. An HTML page comes back as its visible text (the default), as Markdown, or as the HTML itself; any other body, such as JSON, comes back as it is. A long body comes in pieces, and the model asks for the next one with `offset`; only the body's first 2 MiB are read. It makes at most one request a second to a host, and only to addresses on the public internet: loopback, the local network and cloud metadata addresses are refused.

**Python**

```python
agent = await (
    AgentBuilder("anthropic/claude-haiku-5-5")
    .web_search_tool(["DuckDuckGo", "Brave"])
    .web_fetch_tool()
    .build()
)
```

**Node.js**

```js
const agent = await new AgentBuilder('anthropic/claude-haiku-5-5')
  .webSearchTool(['DuckDuckGo', 'Brave'])
  .webFetchTool()
  .build()
```

**Rust**

```rust
use ailoy::tool::WebSearchEngineKind;

let agent = AgentBuilder::new("anthropic/claude-haiku-5-5")
    .web_search_tool(vec![WebSearchEngineKind::DuckDuckGo, WebSearchEngineKind::Brave])
    .web_fetch_tool()
    .build()
    .await?;
```

## Your own functions

A function of your program becomes a tool once it is registered with a **tool description**: the name the model calls it by, what it does, and a JSON schema for its arguments. The agent gets the description from `tool(...)`, or a list of them from `tools(...)`. In Python and Node.js, registering returns it; in Rust you build it with `ToolDescBuilder` and register the function under its name.

This gives the agent `order_status`, which looks an order up by its id:

**Python**

```python
import asyncio

from ailoy import AgentBuilder, register_tool

ORDERS = {"A-1001": {"status": "shipped", "eta": "2026-10-24"}}

def order_status(order_id: str) -> dict:
    if order_id not in ORDERS:
        raise KeyError(f"no order {order_id}")
    return ORDERS[order_id]

async def main() -> None:
    desc = register_tool(
        {
            "name": "order_status",
            "description": "Look up an order's status and expected delivery date by its id.",
            "parameters": {
                "type": "object",
                "properties": {"order_id": {"type": "string", "description": "The order id, such as A-1001"}},
                "required": ["order_id"],
            },
        },
        order_status,
    )

    agent = await AgentBuilder("anthropic/claude-haiku-5-5").tool(desc).build()

    async for output in agent.run("When does order A-1001 arrive?"):
        for part in output["message"]["contents"]:
            if part["type"] == "text":
                print(part["text"])

asyncio.run(main())
```

**Node.js**

```js
const { AgentBuilder, registerTool } = require('@brekkylab/ailoy')

async function main() {
  const orders = { 'A-1001': { status: 'shipped', eta: '2026-10-24' } }

  const desc = registerTool(
    {
      name: 'order_status',
      description: "Look up an order's status and expected delivery date by its id.",
      parameters: {
        type: 'object',
        properties: { order_id: { type: 'string', description: 'The order id, such as A-1001' } },
        required: ['order_id'],
      },
    },
    ({ order_id }) => {
      if (!(order_id in orders)) throw new Error(`no order ${order_id}`)
      return orders[order_id]
    },
  )

  const agent = await new AgentBuilder('anthropic/claude-haiku-5-5').tool(desc).build()

  try {
    for await (const { message } of agent.run('When does order A-1001 arrive?')) {
      for (const part of message.contents) {
        if (part.type === 'text') console.log(part.text)
      }
    }
  } finally {
    await agent.close()
  }
}

main()
```

**Rust**

```rust
use ailoy::{
    agent::AgentBuilder,
    datatype::Value,
    message::{Message, Part, Role},
    to_value, tool_func,
    tool::{ToolDescBuilder, set_tool_provider},
};
use futures::StreamExt as _;

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let desc = ToolDescBuilder::new("order_status")
        .description("Look up an order's status and expected delivery date by its id.")
        .parameters(to_value!({
            "type": "object",
            "properties": {"order_id": {"type": "string", "description": "The order id, such as A-1001"}},
            "required": ["order_id"]
        }))
        .build();
    set_tool_provider(
        "order_status",
        tool_func!(|args: Value| -> Value {
            match args.pointer("/order_id").and_then(Value::as_str) {
                Some("A-1001") => to_value!({"status": "shipped", "eta": "2026-10-24"}),
                Some(id) => Value::string(format!("error: no order {id}")),
                None => Value::string("error: no order_id"),
            }
        }),
    );

    let mut agent = AgentBuilder::new("anthropic/claude-haiku-5-5")
        .tool(desc)
        .build()
        .await?;

    let query = Message::new(Role::User).with_contents([Part::text("When does order A-1001 arrive?")]);
    let mut stream = agent.run(query);
    while let Some(output) = stream.next().await {
        let message = output?.message;
        if message.role == Role::Assistant {
            for text in message.contents.iter().filter_map(Part::as_text) {
                println!("{text}");
            }
        }
    }
    Ok(())
}
```

How the function is called:

- **Python**: the arguments come as keyword arguments, named as in the schema, and the function may be `async`.
- **Node.js**: they come as one object, and the function may return a promise.
- **Rust** registers a `ToolFunc` with `set_tool_provider`, under the name in the description. `tool_func!` builds one from a closure that takes the arguments as a `Value`; with `async` before the closure, its body can `.await`.

The function returns what a message can hold: null, a boolean, a number, a string, or a list or object of those. In Python and Node.js an exception, or a rejected promise, does not end the run: the model gets it as the result, such as `error: KeyError: 'no order B-9'` from the Python function above, and can try something else.

Tool calls the model makes in one step run at the same time, the seven built-in tools above among them: a sandbox runs many processes at once. A function of yours may be called again before its last call has returned.

A Python or Node.js function runs in your program, not in the sandbox. To run a command or read a file there, it calls the virtx `Sandbox` you made, such as `sandbox.exec(...)` or `sandbox.read_file(...)`. In Rust, a closure that also takes `sandbox: &Sandbox` gets the agent's sandbox, as the built-in tools do, and `ailoy::tool::{exec, read, write}` run a command and read and write a file in it.

Tools are registered by name for the whole process, the built-in ones included. Registering a name again, `shell` among them, replaces its function for every agent built after that. `set_tool_provider(name, func)` (`setToolProvider` in Node.js) replaces only the function, for a tool whose description a spec already has. The exception is `web_search` in an agent given a non-empty list of engines, which builds its own. `remove_tool_provider` (`removeToolProvider`) takes a name out.

## Memory

`memory(dir)` gives the agent notes on the user that outlast a session. They are kept on this host, in `MEMORY.md` in the folder `dir`, so they need no sandbox. The folder, and those on the way to it, are made when the agent is built; the file is made by the first note.

The notes go at the end of the system message as they were when the agent was built, and the agent changes them with the `memory` tool: it adds a fact as an entry of its own, replaces an entry when its fact changes, or removes one. The changes in one call are made in order, all or none. Each entry is led by this host's date when it was last written, as `[2026-11-17] Drinks barley tea`. A change shows in the next agent built on the folder, not in the one that made it.

The entries hold at most 3,000 characters unless `limit` says otherwise. A change that would make them larger is refused, and the agent shortens or removes entries to make room. A person can edit the file too: its entries are paragraphs, a blank line apart.

**Python**

```python
from ailoy import Agent, AgentBuilder

agent = await AgentBuilder("anthropic/claude-haiku-5-5").memory("./memory/user1", limit=2000).build()

# The same folder for an agent from a spec.
agent = await Agent.from_spec(
    {"model": "anthropic/claude-haiku-5-5", "memory": {"dir": "./memory/user1", "limit": 2000}}
)
```

**Node.js**

```js
const agent = await new AgentBuilder('anthropic/claude-haiku-5-5')
  .memory('./memory/user1', { limit: 2000 })
  .build()

// The same folder for an agent from a spec.
const again = await Agent.fromSpec({
  model: 'anthropic/claude-haiku-5-5',
  memory: { dir: './memory/user1', limit: 2000 },
})
```

**Rust**

```rust
use ailoy::agent::Memory;

let agent = AgentBuilder::new("anthropic/claude-haiku-5-5")
    .memory(Memory::new("./memory/user1").with_limit(2000))
    .build()
    .await?;
```

An agent built with a history that already holds a system message keeps that message as it is: it gets the `memory` tool, but its notes are not added. A spec that lists a `memory` tool of its own beside a memory fails to build.

## How much of a result the model reads

The agent keeps at most 30,000 characters of each part of a tool result, for built-in tools and your own alike:

- A longer part keeps its first and last 15,000 characters around a note of how many were cut, so a file read whole may reach the model with its middle missing.
- A Python or Node.js function's result, a string included, becomes a value part. A value part is measured in characters of its JSON, and once that passes 30,000, the model gets the JSON text as a string with its middle cut.
- `web_fetch` and `shell` size their results to fit: a long page comes in pieces that each reach the model whole, and `shell` cuts a long stdout or stderr itself, keeping its start and end around a note of how many characters it lost.
