Skip to content

Building AXIs

This page covers each part of a command: what it returns, the extras around its output, its fields, errors, arguments and help. The output samples come from the example app, a todo tracker called todo-axi.

Return plain data

Commands return ordinary values; fastaxi converts them. A record can be a pydantic model, a dataclass, a TypedDict, a NamedTuple, or a plain class with annotated attributes:

@dataclass
class Book:
    id: Annotated[int, Default]
    title: Annotated[str, Default]
    published: date
    blurb: Annotated[str, Truncate(300)] = ""


@app.command()
def books() -> list[Book]:
    """List books."""
    return db.books()

The return annotation decides the output:

Return type Output
list[R], where every field of the record R is a plain value CSV, with the count and suggestions on stderr
list[R], where R has nested fields TOON table
R (one record) TOON detail view
anything else (dict, str, ...) TOON (a str is printed as-is)

A list of flat records is CSV, so agents can pipe it through grep, cut or awk. The rows go to stdout, and the count and suggested next commands go to stderr, where they don't get in the way of the data:

$ todo-axi list
id,title,status,due
41,Fix login redirect,open,2026-11-24
42,"Write docs, examples",open,2026-12-01
45,Upgrade pydantic,open,
count: 3 of 3 total
help[1]: todo-axi view <id>

Annotate the return type: default fields, --fields, --full and CSV all come from it. An unannotated command that returns a list is shown in full, as TOON.

You can override the choice. The order of precedence is: the --format flag, then @app.command(response_format="toon"), then AXI(response_format=...), then the inferred format. The home view is always TOON.

With --format toon, the same list is a TOON table, with the count and suggestions in the output itself:

$ todo-axi list --format toon --limit 2
count: 2 of 3 total
todos[2]{id,title,status,due}:
  41,Fix login redirect,open,2026-11-24
  42,"Write docs, examples",open,2026-12-01
help[1]: todo-axi view <id>

Totals, suggestions and empty results

Static extras go on the decorator. {bin} becomes the tool name, and <placeholders> stand for values the agent fills in:

@app.command(
    name="list",
    next_steps=["{bin} view <id>"],
    empty="no todos match",
)
def list_todos(limit: int = 50) -> list[Todo]:
    """List todos."""
    return db.query(limit=limit)

Without anything else, fastaxi works out the rest itself: the count is the number of items returned. When you want to set any of it yourself, return a Response as a second value. The fields you set replace fastaxi's; the ones you leave out keep their defaults:

from fastaxi import Response


@app.command(name="list", next_steps=["{bin} view <id>"])
def list_todos(
    status: str = "open", limit: int = 50
) -> tuple[list[Todo], Response]:
    """List todos."""
    todos = db.query(status)
    return todos[:limit], Response(
        # "count: 50 of 213 total" instead of "50 of 50"
        total=len(todos),
        # extra aggregates, shown as keys
        summary={"overdue": count_overdue(todos)},
        # shown if the list is empty (exit 0)
        empty=f"no {status} todos",
    )
$ todo-axi list
id,title,status
...
count: 50 of 213 total
overdue: 3
help[1]: todo-axi view <id>
  • Response has four optional fields: total, summary, next_steps and empty.
  • The command returns plain data either way, so calling it from your own code still gives you the list (plus the Response, when it returns one).
  • fastaxi plans the output from the first part of the return annotation, so tuple[list[Todo], Response] gets the same default fields, --fields and CSV as list[Todo].
  • On an empty list, the decorator's next_steps (such as view <id>) are left out, since they rarely apply when nothing was found. next_steps set on a Response replace the decorator's and are shown even then.

An empty result is said explicitly, and still exits 0, so an agent never mistakes "nothing found" for a failure. The example app builds its message from the filters it was given:

$ todo-axi list --assignee carol
result: no open todos assigned to carol

The home view

@app.home registers what the tool shows when it runs with no arguments. Instead of a usage page, the agent gets live state straight away, along with the next commands to try. The example app's home view lists open todos, with a total and an overdue count from a Response:

@app.home(next_steps=["{bin} view <id>", "{bin} add --title <title>"])
def home() -> tuple[list[Todo], Response]:
    """Open todos, with an overdue count."""
    todos = store.query(status=Status.open)
    overdue = sum(1 for t in todos if t.due and t.due < store.today())
    return todos[:10], Response(
        total=len(todos),
        summary={"overdue": overdue},
    )
$ todo-axi
bin: todo-axi
description: Track todos for the current project
count: 3 of 3 total
overdue: 1
todos[3]{id,title,status,due}:
  41,Fix login redirect,open,2026-11-24
  42,"Write docs, examples",open,2026-12-01
  45,Upgrade pydantic,open,null
help[2]: todo-axi view <id>,todo-axi add --title <title>

The home view is always TOON, and starts with the tool's path and description. Its parameters must all have defaults, since it runs without arguments. A tool without a home view prints its help instead. Session hooks show the home view to an agent when a session starts.

Default fields and --fields

AXI lists show three or four fields by default. Choose them by marking fields with Default:

class Todo(BaseModel):
    id: Annotated[int, Default]
    title: Annotated[str, Default]
    status: Annotated[str, Default]
    assignee: str | None = None
    priority: int = 3

Alternatively, pass @app.command(default_fields=["id", "title"]). If you set neither, fastaxi picks an id-like field, a title or name, a status, and then other required fields. More than four defaults is an error when the command is registered; raise the limit with max_default_fields=.

Agents get the other fields with --fields id,assignee or --fields all, and reach nested models with dotted paths such as --fields id,author.login. The columns follow the order asked for:

$ todo-axi list --assignee alice --fields id,title,due
id,title,due
41,Fix login redirect,2026-11-24
45,Upgrade pydantic,
count: 2 of 2 total
help[1]: todo-axi view <id>

Long text

body: Annotated[str, Truncate(200)] = ""

Long values are cut to 200 characters, and the command gets a --full flag automatically. In a single record, a cut value ends with how much of it is shown, and the output suggests the same command with --full. This is the example app's detail view, whose body has the field above:

$ todo-axi view 42
id: 42
title: "Write docs, examples"
status: open
due: 2026-12-01
assignee: bob
priority: 2
body: "Cover the quickstart, the --fields flag and CSV output.\nAdd a section on hooks so agents pick up the dashboard at session start, plus a short FAQ comparing TOON with JSON and explaining when CSV is ch… (200 of 347 chars)"
comments[2]{author,at,text}:
  bob,"2026-11-20T14:02:00Z",Started on the quickstart
  alice,"2026-11-21T09:15:00Z","Can we add a TOON primer, too?"
help[1]: todo-axi view 42 --full

It also shows how a single record looks: one TOON key per field, with lists of records, such as comments, as compact tables.

Errors and idempotent actions

class CloseResult(BaseModel):
    result: str
    id: int


@app.command()
def close(id: int) -> CloseResult:
    """Mark a todo done. Safe to repeat."""
    todo = db.get(id)
    if todo is None:
        raise AxiError(
            f"todo {id} not found",
            hint="ids come from `todo-axi list`",
            help=["todo-axi list"],
        )
    if todo.closed:
        # repeating the action is a no-op that still exits 0
        return CloseResult(result="already closed", id=id)
    db.close(id)
    return CloseResult(result="closed", id=id)

AxiError exits with 1, or with code=. Any other exception becomes error: internal error (TypeName) without leaking details. Set AXI_DEBUG=1 to print the traceback to stderr.

Errors are printed on stdout, where the agent is already reading, together with the commands in help= that fix or work around the problem:

$ todo-axi view 99
error: todo 99 not found
help[1]: todo-axi list

Exit code 1 means the command ran and failed. Exit code 2 means it was called wrongly, as in the next section.

Arguments and flags

Parameters without a default are positional arguments, and parameters with a default are flags. Values are converted and validated by Pydantic, including Literal, Enum, dates, lists (--tag a,b or a repeated --tag) and Field constraints. bool flags also accept --no-<name>.

from fastaxi import Arg, Flag


@app.command()
def assign(
    id: Annotated[int, Arg(help="Todo id")],
    to: Annotated[str, Flag(aliases=["-t"])],
    notify: bool = True,
) -> Todo: ...

aliases are extra spellings that work exactly like the flag itself.

A Pydantic model parameter becomes one flag per field:

class NewTodo(BaseModel):
    title: str = Field(description="Short summary")
    priority: int = Field(default=3, ge=1, le=5, description="1 (highest) to 5")


@app.command()
def add(todo: NewTodo) -> Todo:
    """Create a todo."""
    return db.create(todo)
$ todo-axi add --title "Ship v1" --priority 2

Wrong input never reaches your function. fastaxi rejects it with exit code 2 and an error that names the flag and says what is valid. A misspelled flag gets the closest match and the list of valid ones, and a value outside a Field constraint, like le=5 above, says what it should be:

$ todo-axi list --state done
error: unknown flag --state
hint: did you mean --status?
flags[5]: "--status","--assignee","--limit","--fields","--format"

$ todo-axi add --title "Ship v1" --priority 9
error: invalid value for --priority
hint: Input should be less than or equal to 5 (got 9)

Help text

fastaxi takes help text from these sources, highest priority first:

  1. Arg(help=...) and Flag(help=...)
  2. The function's docstring, in Google, NumPy or Sphinx style. An Examples: section becomes the examples in --help, and {bin} is replaced with the tool's name.
  3. Field(description=...) on model parameters

The example app's list command has a Google-style docstring with Args: and Examples: sections, and --help is built from it:

$ todo-axi list --help
todo-axi list - List todos.

usage: todo-axi list [flags]

flags:
  --status <open|done>       Filter by status (default: open)
  --assignee, -a <assignee>  Filter by assignee login
  --limit <limit>            Maximum rows (default: 50)
  --fields <a,b,...|all>     Fields to show (default: id,title,status,due)
  --format <csv|toon>        Output format (default: csv)

available fields: id,title,status,due,assignee,priority

examples:
  todo-axi list --status done
  todo-axi list --assignee alice --fields id,title,due
  • The first line is the docstring's summary.
  • Each flag's description comes from Args:, and its default from the function signature. --status lists its allowed values because it is an Enum.
  • --fields and --format are added by fastaxi, because the command returns a list of flat records. The available fields are listed so an agent can ask for them.
  • The examples come from the Examples: section.

Groups and async

repo = app.group("repo", help="Repository commands")


@repo.command(name="ls")
async def repo_ls() -> list[Repo]:  # async commands work too
    ...
$ my-axi repo ls