/

Ambitwin · source-available, not open source · © 2026 Nicolò Ghignatti

Agent

Keywords on this page
WordMeaningExample
ToolA function the model may ask the service to run, described by a JSON schemaget_room(building_id, room_id)
Tool callThe model saying “please run this tool with these arguments”list_rooms({"building_id":"b1"})
CedarThe shared rule language that decides who may do whatRead = member of the domain
ArgsThe Pydantic class that describes a tool’s arguments. It is also what the model readsGetRoomArgs
PydanticA Python library that checks data against a class and can print its JSON SchemaBaseModel, Field
JSON SchemaA standard description of a JSON shape: names, types, limits{"type":"object","properties":{…}}
RegistryThe one list of tools. The loop looks tools up hereREGISTRY
ProtocolA Python way to say “anything with these attributes counts”, with no base class to inheritTool[ArgsT]
ProjectionKeeping only the fields the model needs from a bigger answerdrop color, keep capacity
Untrusted dataText that may contain instructions meant to fool the model. It is data, never ordersa document that says “ignore the rules”

How to add a tool to agent, from an empty file to a passing test. How the service works inside, and where tools sit in the loop: Agent. Its role in the system: Agent.


A tool is something the language model can ask agent to do: search the docs, read a building, read a sensor. This page shows how to add one, from an empty file to a passing test.

The short version of how it works:


What happens to a tool, in pictures

sequenceDiagram
    autonumber
    participant M as Model
    participant L as loop.py
    participant R as REGISTRY
    participant T as YourTool
    L->>R: schemas()
    R->>R: for each tool: Args.model_json_schema(), cleaned
    R-->>L: name, description, parameters
    L->>M: messages + tool schemas
    M-->>L: tool call: name + JSON arguments
    L->>R: get(name)
    R-->>L: the tool
    L->>T: Args(**arguments)  (Pydantic check)
    T-->>L: Args, or a validation error
    L->>T: run(args, ctx)
    T-->>L: ToolResult
    L->>M: "tool" message with the result

If the name is unknown, the arguments fail the check, or run raises, the loop turns that into an error message for the model. Nothing is thrown at the caller. See Running one tool call in Agent.


1. Pick the shape

Before writing code, answer four questions.

  1. What does the tool do, in one sentence? That sentence becomes the description the model reads.
  2. What inputs does it need? Each input becomes a field of the Args class.
  3. What does it return? Keep it small. The result goes back into the model’s context as JSON, where it costs tokens and can distract the model. Drop every field the model does not need.
  4. Read-only, or does it change something? There is no confirmation flow for write actions. Keep tools read-only unless authorization, confirmation, audit logging and retry behaviour are designed on purpose.

Worked example for this page. A new tool count_rooms:

QuestionAnswer
One sentence“Count the rooms of one building.”
Inputsbuilding_id
Returns{"building_id": "b1", "room_count": 4}
Read-only?Yes

(count_rooms is made up for this guide. It is not in the codebase. The code below is the real pattern the existing tools follow.)

Note

The twin tools (app/agent/tools/twin.py) are the reference for a tool that touches real data. Each one checks the caller’s rights first, either can_access_domain(ctx.user, args.domain) or get_authorized_building(...), and forwards the caller’s identity downstream with auth_headers(ctx.user), instead of calling digital-twin as nobody. Follow the same shape for any tool that reads or writes real data.


2. Where the file lives

Inside a multi-tool file, a divider comment keeps it easy to scan:

# ─── list_buildings ─────────────────────────────────────────────────────────

For the example, count_rooms joins the other building tools, so it goes in twin.py.


3. Write the Args class

from pydantic import BaseModel, Field


class CountRoomsArgs(BaseModel):
    building_id: str = Field(description="Unique id of the building (NOT its name).")

This class does two jobs at once:

  1. It checks what the model sends. Args(**call.arguments) raises if a field is missing or has the wrong type.
  2. It is what the model reads. The registry calls Args.model_json_schema() and hands the result to the model. The class is the model-facing contract.

What the schema of this class looks like to the model (after cleaning):

{"type": "object",
 "properties": {"building_id": {"type": "string", "description": "Unique id of the building (NOT its name)."}},
 "required": ["building_id"]}

Rules that make the model call the tool well:

What the registry does to the schema

def _sanitize_tool_schema(schema: dict) -> dict:
    drop = {"title", "$defs", "definitions", "additionalProperties"}
    if isinstance(schema, dict):
        return {k: _sanitize_tool_schema(v) for k, v in schema.items() if k not in drop}
    if isinstance(schema, list):
        return [_sanitize_tool_schema(v) for v in schema]
    return schema

Pydantic adds a title to everything and sometimes $defs and additionalProperties. Function-calling APIs do not need them, so the registry strips them, deep inside the schema too. It keeps the parameter schema as short as possible.


4. Write the tool class

from app.agent.tools.access import get_authorized_building
from app.agent.tools.base import ToolContext, ToolResult


class CountRoomsTool:
    name = "count_rooms"
    description = (
        "Count the rooms of one building. Use when the building_id is known and only the "
        "number of rooms is needed. For the rooms themselves, use list_rooms."
    )
    Args = CountRoomsArgs

    async def run(self, args: CountRoomsArgs, ctx: ToolContext) -> ToolResult:
        ...
AttributeWhat it is
nameThe stable id the model writes in a tool call. snake_case and unique
descriptionWhat the tool does and when to use it instead of its neighbours. See below
ArgsThe Pydantic class from step 3. The registry turns it into the schema
runAn async method with the signature (self, args: <YourArgs>, ctx: ToolContext) -> ToolResult

Writing a good description

The model reads this to choose between tools. So say what the tool does and when to pick it over its neighbours. Compare:

For a tool with a sibling that does something close, say what it is not for. SearchDocsTool does: “Do NOT use for live operational state — use the twin tools for building structure and the sensor tools for live measurements.”

What ToolContext and ToolResult hold

@dataclass
class ToolContext:
    user: AuthUser
    session: AsyncSession
    citations: list[Any] = field(default_factory=list)

@dataclass
class ToolResult:
    content: Any
    is_error: bool = False
    citations: list[Any] = field(default_factory=list)

About the generic protocol

class Tool(Protocol[ArgsT]):
    name: str
    description: str
    Args: type[ArgsT]

    async def run(self, args: ArgsT, ctx: ToolContext) -> ToolResult: ...

Tool is a Protocol that is generic over the tool’s Args type. A tool does not inherit from it. As long as a class has name, description, Args and a matching run, it already counts as a Tool[YourArgs]. The type variable is what lets the type checker see that run(args: CountRoomsArgs, ...) is a valid fit, not a mismatch.

Note

Do not widen the run parameter to BaseModel to “match the protocol”. That defeats the point and loses type safety. Keep it narrow.


5. Implement run

The rights check and the downstream call already exist as helpers. For a building tool, one call does both:

async def run(self, args: CountRoomsArgs, ctx: ToolContext) -> ToolResult:
    building, error = await get_authorized_building(args.building_id, ctx)
    if error is not None:
        return error
    assert building is not None

    rooms = building.get("rooms")
    return ToolResult(
        content={
            "building_id": args.building_id,
            "room_count": len(rooms) if isinstance(rooms, list) else 0,
        }
    )

Line by line:

  1. get_authorized_building asks digital-twin for the building with the caller’s own claims, then checks with Cedar that the caller shares a domain with it. It returns (building, None) or (None, an error ToolResult).
  2. If there is an error, return it as it is. The model reads messages like building unavailable or inaccessible and can try something else. A missing building and a foreign building give the same message, so a stranger cannot learn that an id exists.
  3. assert building is not None is for the type checker: after error is None, the building is there.
  4. Project the answer: only the id and a count go back to the model. Not the rooms, not the domains.

If the tool talks to a backend by itself

When there is no helper that fits, follow the same pattern as list_buildings:

async def run(self, args: ListBuildingsArgs, ctx: ToolContext) -> ToolResult:
    if not can_access_domain(ctx.user, args.domain):
        return ToolResult(content="domain unavailable or inaccessible", is_error=True)

    try:
        domain = quote(args.domain, safe="")
        r = await get_with_retry(get_twin_client(), f"/buildings/{domain}", headers=auth_headers(ctx.user))
    except httpx.HTTPError:
        return ToolResult(content="digital-twin is unavailable", is_error=True)
    if r.status_code >= 400:
        return ToolResult(content=downstream_error("digital-twin", r), is_error=True)
    try:
        data = r.json() or []
    except ValueError:
        return ToolResult(content="digital-twin returned invalid data", is_error=True)
    if not isinstance(data, list):
        return ToolResult(content="digital-twin returned invalid data", is_error=True)
    # … keep only id, name, accessible domains and room_count of each building
    return ToolResult(content={"buildings": slim})

The order is the lesson:

  1. Authorize first, before any network call.
  2. Escape any model-written text that goes into a URL (quote(..., safe="")), so it cannot climb out of the route.
  3. Forward the caller’s identity (auth_headers) and use get_with_retry, which retries a network error or a 502, 503, 504 once.
  4. Check the answer’s shape before using it. A downstream that returns something odd becomes ... returned invalid data, not a crash.
  5. Project the result.

Rules for run


6. Register the tool

Open app/agent/tools/__init__.py and add two lines. Today it looks like this:

from app.agent.tools.twin import (
    GetBuildingTool,
    GetRoomTool,
    ListBuildingsTool,
    ListRoomsTool,
)

REGISTRY.register(SearchDocsTool())
REGISTRY.register(ListBuildingsTool())
REGISTRY.register(GetBuildingTool())
REGISTRY.register(ListRoomsTool())
REGISTRY.register(GetRoomTool())
# …

Add CountRoomsTool to the import, and one more REGISTRY.register(CountRoomsTool()).

The order does not matter. A duplicate name raises ValueError: tool 'count_rooms' already registered when the app imports, which is on purpose: it catches a copy-paste clash at start, not in the middle of an answer.

After this, the tool appears in REGISTRY.schemas() and the model can call it. Nothing else needs to change: not the loop, not the route.

Note

If the system prompt lists tools by group (it does: building structure, sensor data, devices, platform docs), check that the new tool fits one of the groups in app/agent/prompts.py. A tool the prompt does not mention can still be called, but the model chooses worse.


7. Test it

Three layers, lightest first.

The Args class

If the class has non-trivial checks (a regex, a range, a custom validator), unit-test them under tests/unit/. Skip this for trivial fields.

import pytest
from pydantic import ValidationError

def test_count_rooms_needs_a_building_id():
    with pytest.raises(ValidationError):
        CountRoomsArgs()

run against a fake backend

Mock the boundary (the HTTP call, the database session), not the tool itself. Then assert on the ToolResult:

Look at tests/unit/test_twin_tool_auth.py and test_twin_tool_failure_modes.py for how the existing tools do it.

Through the agent loop

The integration suite has no reusable scripted LLMClient yet. For now, test run at the backend boundary and smoke-test the dispatch through /ask. When a reusable fake model exists, assert the whole tool-call and recovery sequence through Agent.answer.


8. Run the checks

just lint affected
just test agent

Tools go through just (or mise exec --), never the ambient PATH. The checks catch many common mistakes: invalid return annotations and ordinary type errors inside run.

The generic Tool[ArgsT] protocol documents the intended link between Args and the run parameter, but the registry stores tools as Tool[Any]. Do not rely on the type checker alone to catch a mismatch between those two. For a non-trivial tool, exercise schema generation and dispatch in a test.


Quick checklist