Skip to content

Render

render

Compact ToolResult text primitives (stdlib-strict).

Factored out of the duplicated _render.py copies that lived in axm-backtest, axm-route and friends. Each AXM tool fills data (a Pydantic model_dump) but often leaves text=None, so the MCP server falls back to a verbose JSON dump. These primitives compose into a few-line métier renderer that emits a compact, token-cheap text:

  • :func:header — the {tool} | {summary} first line.
  • :func:labeled_block — a label followed by indented lines.
  • :func:compact_table — an aligned columns table for homogeneous rows.
  • :func:truncate — bounded text with a trailing ellipsis.
  • :func:format_count / :func:format_size — human-readable numbers.
  • :func:render_result — a full compact, lossless text walker over an arbitrary data payload (never raises).
  • :func:record_table — the lossless homogeneous-record key | key table.

Strictly stdlib — no runtime dependency is added by importing this module.

compact_table(rows, headers=None)

Render rows as a column-aligned table, optionally with a headers row.

Tolerates ragged rows (short rows are padded) and arbitrarily wide cells. None cells render as empty, never as the literal "None".

Source code in packages/axm-ingot/src/axm_ingot/render.py
Python
def compact_table(
    rows: Sequence[Sequence[object]],
    headers: Sequence[object] | None = None,
) -> str:
    """Render *rows* as a column-aligned table, optionally with a *headers* row.

    Tolerates ragged rows (short rows are padded) and arbitrarily wide cells.
    ``None`` cells render as empty, never as the literal ``"None"``.
    """
    matrix: list[list[str]] = []
    if headers is not None:
        matrix.append([_cell(h) for h in headers])
    matrix.extend([_cell(c) for c in row] for row in rows)
    if not matrix:
        return ""
    ncols = max(len(row) for row in matrix)
    for row in matrix:
        row.extend([""] * (ncols - len(row)))
    widths = [max(len(row[col]) for row in matrix) for col in range(ncols)]
    out = []
    for row in matrix:
        line = _COL_SEP.join(row[col].ljust(widths[col]) for col in range(ncols))
        out.append(line.rstrip())
    return "\n".join(out)

format_count(n)

Render an item count, abbreviating thousands (1500'1.5K').

Source code in packages/axm-ingot/src/axm_ingot/render.py
Python
def format_count(n: int) -> str:
    """Render an item count, abbreviating thousands (``1500`` → ``'1.5K'``)."""
    magnitude = abs(n)
    if magnitude < _COUNT_STEP:
        return str(n)
    for unit, divisor in (("B", 1_000_000_000), ("M", 1_000_000), ("K", 1_000)):
        if magnitude >= divisor:
            return f"{n / divisor:.1f}{unit}"
    return str(n)

format_size(num_bytes)

Render a byte count in human units (2048'2.0 KB').

Source code in packages/axm-ingot/src/axm_ingot/render.py
Python
def format_size(num_bytes: int) -> str:
    """Render a byte count in human units (``2048`` → ``'2.0 KB'``)."""
    size = float(num_bytes)
    units = ("B", "KB", "MB", "GB", "TB", "PB")
    for unit in units:
        if abs(size) < _SIZE_STEP or unit == units[-1]:
            if unit == "B":
                return f"{int(size)} {unit}"
            return f"{size:.1f} {unit}"
        size /= _SIZE_STEP
    return f"{num_bytes} B"

header(tool, summary)

Render the compact header line {tool} | {summary}.

header("audit", "3 findings") 'audit | 3 findings'

Source code in packages/axm-ingot/src/axm_ingot/render.py
Python
def header(tool: str, summary: str) -> str:
    """Render the compact header line ``{tool} | {summary}``.

    >>> header("audit", "3 findings")
    'audit | 3 findings'
    """
    return f"{tool} | {summary}"

labeled_block(label, lines)

Render label followed by lines, each indented two spaces.

An empty lines yields an empty string so no dangling label is emitted. None entries render as blank lines rather than the literal "None".

Source code in packages/axm-ingot/src/axm_ingot/render.py
Python
def labeled_block(label: str, lines: Sequence[str | None]) -> str:
    """Render *label* followed by *lines*, each indented two spaces.

    An empty *lines* yields an empty string so no dangling label is emitted.
    ``None`` entries render as blank lines rather than the literal ``"None"``.
    """
    if not lines:
        return ""
    body = [f"{_INDENT}{_cell(line)}" for line in lines]
    return "\n".join([label, *body])

record_table(rows, keys, *, indent=0)

Render a homogeneous dict list as key | key header + value rows.

Lossless: emits the shared keys once as a header line then one value row per record. None cells render as an em-dash, bools as yes/no. indent offsets every line by two spaces per level.

Source code in packages/axm-ingot/src/axm_ingot/render.py
Python
def record_table(
    rows: Sequence[object],
    keys: Sequence[str],
    *,
    indent: int = 0,
) -> list[str]:
    """Render a homogeneous dict list as ``key | key`` header + value rows.

    Lossless: emits the shared *keys* once as a header line then one value row
    per record. ``None`` cells render as an em-dash, bools as yes/no. *indent*
    offsets every line by two spaces per level.
    """
    pad = _INDENT * indent
    lines = [f"{pad}{' | '.join(keys)}"]
    for rec in rows:
        row = rec if isinstance(rec, dict) else {}
        lines.append(f"{pad}{' | '.join(_scalar(row.get(k)) for k in keys)}")
    return lines

render_result(tool, data, *, label='')

Render an arbitrary tool result as compact, lossless text.

Header is {tool} (plus | {label} when label is given); the body preserves every field of data. A scalar-only payload collapses to the arrow form {header} → {value}.

Never raises: any object — including an unrenderable or self-referential one — yields a str (falling back to the header line on failure).

Source code in packages/axm-ingot/src/axm_ingot/render.py
Python
def render_result(tool: str, data: object, *, label: str = "") -> str:
    """Render an arbitrary tool result as compact, lossless ``text``.

    Header is ``{tool}`` (plus ``| {label}`` when *label* is given); the body
    preserves every field of *data*. A scalar-only payload collapses to the
    arrow form ``{header} → {value}``.

    Never raises: any object — including an unrenderable or self-referential
    one — yields a ``str`` (falling back to the header line on failure).
    """
    head = header(tool, label) if label else tool
    try:
        body = _fmt_value(data, indent=0)
        if len(body) == 1 and not isinstance(data, (dict, list, tuple)):
            return f"{head}{body[0].strip()}"
        return "\n".join([head, *body])
    except Exception:  # noqa: BLE001 — never-raises contract: any object yields a str
        return head

truncate(text, limit)

Bound text to limit chars, appending an ellipsis when it overflows.

Text at or under limit is returned unchanged. The overflow result has at most limit + 1 characters and ends with the ellipsis marker.

Source code in packages/axm-ingot/src/axm_ingot/render.py
Python
def truncate(text: str, limit: int) -> str:
    """Bound *text* to *limit* chars, appending an ellipsis when it overflows.

    Text at or under *limit* is returned unchanged. The overflow result has at
    most ``limit + 1`` characters and ends with the ellipsis marker.
    """
    bound = max(limit, 0)
    if len(text) <= bound:
        return text
    return text[:bound] + _ELLIPSIS