Skip to content

Index

axm

AXM CLI — Unified command-line interface for the AXM ecosystem.

AXMTool

Bases: Protocol

Structural protocol for AXM deterministic tools.

Implementors must provide: - name (property): unique tool identifier - execute(...) : deterministic execution with explicit params

Optionally provide: - agent_hint (class attribute): optional, free-form one-liner optimized for LLM consumption: what the tool does, key params, and what it replaces. Like the other discovery attributes below, it is not a protocol member and carries no guaranteed fallback — some discovery tooling reads it best-effort via getattr / :func:tool_metadata; absent, nothing is substituted. - expose_directly (class attribute, default False): when True, the MCP server registers this tool directly in tools/list (the hot path). When False (default), the tool is reachable only through the MCP facade (axm_search -> axm_describe -> axm_call), keeping the tools/list payload small. - domain (class attribute, default None): coarse capability group used by the facade for axm_capabilities and to scope axm_search (e.g. "ast", "git", "ticket"). - tags (class attribute, default frozenset()): free-form keywords feeding facade discovery (axm_search).

Uses structural typing (PEP 544) — no inheritance required. @runtime_checkable enables isinstance() checks. The discovery attributes (expose_directly / domain / tags) are not protocol members on purpose: adding data attributes to a runtime_checkable protocol would make them required for isinstance() and break the check for the many tools that satisfy AXMTool structurally without subclassing it. Read them through :func:tool_metadata (or getattr(tool, name, default)) instead, which works for subclasses and structural tools alike.

Example::

Text Only
class MyTool(AXMTool):
    agent_hint = "Frobnicate widgets — use width param."
    expose_directly = True          # hot path (read via tool_metadata)
    domain = "widget"
    tags = frozenset({"frobnicate"})

    @property
    def name(self) -> str:
        return "my-tool"

    def execute(self, *, value: int = 0) -> ToolResult:
        return ToolResult(success=True, data={"result": value})
Source code in packages/axm/src/axm/tools/base.py
Python
@runtime_checkable
class AXMTool(Protocol):
    """Structural protocol for AXM deterministic tools.

    Implementors must provide:
    - ``name`` (property): unique tool identifier
    - ``execute(...)`` : deterministic execution with explicit params

    Optionally provide:
    - ``agent_hint`` (class attribute): optional, free-form one-liner
      optimized for LLM consumption: what the tool does, key params, and
      what it replaces.  Like the other discovery attributes below, it is
      *not* a protocol member and carries no guaranteed fallback — some
      discovery tooling reads it best-effort via ``getattr`` /
      :func:`tool_metadata`; absent, nothing is substituted.
    - ``expose_directly`` (class attribute, default ``False``): when
      ``True``, the MCP server registers this tool directly in
      ``tools/list`` (the *hot path*).  When ``False`` (default), the
      tool is reachable only through the MCP facade
      (``axm_search`` -> ``axm_describe`` -> ``axm_call``), keeping the
      ``tools/list`` payload small.
    - ``domain`` (class attribute, default ``None``): coarse capability
      group used by the facade for ``axm_capabilities`` and to scope
      ``axm_search`` (e.g. ``"ast"``, ``"git"``, ``"ticket"``).
    - ``tags`` (class attribute, default ``frozenset()``): free-form
      keywords feeding facade discovery (``axm_search``).

    Uses structural typing (PEP 544) — no inheritance required.
    ``@runtime_checkable`` enables ``isinstance()`` checks.  The discovery
    attributes (``expose_directly`` / ``domain`` / ``tags``) are *not*
    protocol members on purpose: adding data attributes to a
    ``runtime_checkable`` protocol would make them required for
    ``isinstance()`` and break the check for the many tools that satisfy
    ``AXMTool`` structurally without subclassing it.  Read them through
    :func:`tool_metadata` (or ``getattr(tool, name, default)``) instead,
    which works for subclasses and structural tools alike.

    Example::

        class MyTool(AXMTool):
            agent_hint = "Frobnicate widgets — use width param."
            expose_directly = True          # hot path (read via tool_metadata)
            domain = "widget"
            tags = frozenset({"frobnicate"})

            @property
            def name(self) -> str:
                return "my-tool"

            def execute(self, *, value: int = 0) -> ToolResult:
                return ToolResult(success=True, data={"result": value})
    """

    @property
    def name(self) -> str:
        """Unique tool identifier (e.g., 'esbmc', 'dafny', 'pytest')."""
        ...

    def execute(self, **kwargs: Any) -> ToolResult:
        """Execute the tool with given arguments.

        Subclasses should override with explicit, typed parameters::

            def execute(self, *, title: str = "", body: str = "") -> ToolResult:
                ...

        The ``**kwargs`` signature here is the *structural minimum* —
        any callable accepting keyword arguments satisfies it.

        Returns:
            ToolResult with success status and structured data.
        """
        ...
name property

Unique tool identifier (e.g., 'esbmc', 'dafny', 'pytest').

execute(**kwargs)

Execute the tool with given arguments.

Subclasses should override with explicit, typed parameters::

Text Only
def execute(self, *, title: str = "", body: str = "") -> ToolResult:
    ...

The **kwargs signature here is the structural minimum — any callable accepting keyword arguments satisfies it.

Returns:

Type Description
ToolResult

ToolResult with success status and structured data.

Source code in packages/axm/src/axm/tools/base.py
Python
def execute(self, **kwargs: Any) -> ToolResult:
    """Execute the tool with given arguments.

    Subclasses should override with explicit, typed parameters::

        def execute(self, *, title: str = "", body: str = "") -> ToolResult:
            ...

    The ``**kwargs`` signature here is the *structural minimum* —
    any callable accepting keyword arguments satisfies it.

    Returns:
        ToolResult with success status and structured data.
    """
    ...

DeclarativeTool

Common AXMTool adapter, unavailable without an explicit host binding.

Source code in packages/axm/src/axm/tools/declarative.py
Python
class DeclarativeTool:
    """Common AXMTool adapter, unavailable without an explicit host binding."""

    expose_directly = True
    tags = frozenset({"ui", "declarative"})

    def __init__(
        self,
        definition: DeclarativeToolDefinition,
        invoke: Callable[[str, dict[str, object]], ToolResult] | None = None,
    ) -> None:
        self.definition = definition
        self._invoke = invoke
        self.__doc__ = definition.description

    @property
    def name(self) -> str:
        """Canonical name shared by CLI, nodes and MCP."""
        return self.definition.name

    def execute(self, **kwargs: object) -> ToolResult:
        """Validate and invoke the host binding, never an ambient view."""
        try:
            self.definition.validate_input(kwargs)
            if self._invoke is None:
                return ToolResult(
                    success=False,
                    data={"status": "unavailable"},
                    error="UI tool unavailable: no host view binding",
                )
            return self.definition.validate_result(self._invoke(self.name, kwargs))
        except (ValidationError, ValueError, TypeError) as exc:
            return ToolResult(success=False, error=f"invalid UI tool contract: {exc}")
name property

Canonical name shared by CLI, nodes and MCP.

execute(**kwargs)

Validate and invoke the host binding, never an ambient view.

Source code in packages/axm/src/axm/tools/declarative.py
Python
def execute(self, **kwargs: object) -> ToolResult:
    """Validate and invoke the host binding, never an ambient view."""
    try:
        self.definition.validate_input(kwargs)
        if self._invoke is None:
            return ToolResult(
                success=False,
                data={"status": "unavailable"},
                error="UI tool unavailable: no host view binding",
            )
        return self.definition.validate_result(self._invoke(self.name, kwargs))
    except (ValidationError, ValueError, TypeError) as exc:
        return ToolResult(success=False, error=f"invalid UI tool contract: {exc}")

DeclarativeToolDefinition dataclass

Immutable tool metadata; schemas are detached on every access.

Source code in packages/axm/src/axm/tools/declarative.py
Python
@dataclass(frozen=True, init=False)
class DeclarativeToolDefinition:
    """Immutable tool metadata; schemas are detached on every access."""

    name: str
    description: str
    handler: str
    execution: str
    _input_json: str
    _output_json: str

    def __init__(
        self,
        name: str,
        description: str,
        input_schema: Mapping[str, object],
        output_schema: Mapping[str, object],
        handler: str,
    ) -> None:
        if not _NAME.fullmatch(name) or name in _RESERVED:
            raise ValueError(f"invalid or reserved declarative tool name: {name}")
        if not description.strip() or handler != name:
            raise ValueError("description is required and handler must equal tool name")
        for key, value in (
            ("name", name),
            ("description", description),
            ("handler", handler),
            ("execution", "ui"),
            ("_input_json", _schema_json(input_schema)),
            ("_output_json", _schema_json(output_schema)),
        ):
            object.__setattr__(self, key, value)

    @property
    def input_schema(self) -> dict[str, object]:
        """Detached JSON Schema for functional arguments, without routing fields."""
        return cast(dict[str, object], json.loads(self._input_json))

    @property
    def output_schema(self) -> dict[str, object]:
        """Detached JSON Schema for successful ToolResult.data."""
        return cast(dict[str, object], json.loads(self._output_json))

    def validate_input(self, arguments: Mapping[str, object]) -> None:
        """Reject malformed/non-JSON arguments before contacting any view."""
        detached = json.loads(json.dumps(dict(arguments), allow_nan=False))
        Draft202012Validator(self.input_schema).validate(detached)

    def validate_result(self, result: ToolResult) -> ToolResult:
        """Validate successful data; failures retain their structural signal."""
        if not isinstance(result.success, bool):
            raise ValueError("malformed ToolResult: success must be a boolean")
        if result.success:
            detached = json.loads(json.dumps(result.data, allow_nan=False))
            Draft202012Validator(self.output_schema).validate(detached)
        return result
input_schema property

Detached JSON Schema for functional arguments, without routing fields.

output_schema property

Detached JSON Schema for successful ToolResult.data.

validate_input(arguments)

Reject malformed/non-JSON arguments before contacting any view.

Source code in packages/axm/src/axm/tools/declarative.py
Python
def validate_input(self, arguments: Mapping[str, object]) -> None:
    """Reject malformed/non-JSON arguments before contacting any view."""
    detached = json.loads(json.dumps(dict(arguments), allow_nan=False))
    Draft202012Validator(self.input_schema).validate(detached)
validate_result(result)

Validate successful data; failures retain their structural signal.

Source code in packages/axm/src/axm/tools/declarative.py
Python
def validate_result(self, result: ToolResult) -> ToolResult:
    """Validate successful data; failures retain their structural signal."""
    if not isinstance(result.success, bool):
        raise ValueError("malformed ToolResult: success must be a boolean")
    if result.success:
        detached = json.loads(json.dumps(result.data, allow_nan=False))
        Draft202012Validator(self.output_schema).validate(detached)
    return result

DeclarativeToolManifest dataclass

One addon bundle's closed tool declarations.

Source code in packages/axm/src/axm/tools/declarative.py
Python
@dataclass(frozen=True)
class DeclarativeToolManifest:
    """One addon bundle's closed tool declarations."""

    schema_version: int
    addon_id: str
    bundle_sha256: str
    tools: tuple[DeclarativeToolDefinition, ...]

    def __post_init__(self) -> None:
        _validate_manifest(self)

DependencyEnvironment dataclass

Trusted runner inputs, transported with the phase contract.

Source code in packages/axm/src/axm/tools/dependency_reads.py
Python
@dataclass(frozen=True)
class DependencyEnvironment:
    """Trusted runner inputs, transported with the phase contract."""

    interpreter: str
    package_root: str
    pythonpath: tuple[str, ...] = ()

    @classmethod
    def from_mapping(cls, raw: Mapping[str, object]) -> DependencyEnvironment:
        """Validate absolute runner locations; never infer a service interpreter."""
        interpreter, root = raw.get("interpreter"), raw.get("package_root")
        paths = raw.get("pythonpath", ())
        if not isinstance(interpreter, str) or not Path(interpreter).is_absolute():
            raise ValueError("dependency interpreter must be absolute")
        if not isinstance(root, str) or not Path(root).is_absolute():
            raise ValueError("dependency package_root must be absolute")
        if not isinstance(paths, (list, tuple)) or any(
            not isinstance(p, str) or not Path(p).is_absolute() for p in paths
        ):
            raise ValueError("dependency pythonpath entries must be absolute")
        return cls(interpreter, os.path.realpath(root), tuple(str(p) for p in paths))

    def to_mapping(self) -> dict[str, object]:
        """Serialize the runner inputs without granting any write prefix."""
        return {
            "interpreter": self.interpreter,
            "package_root": self.package_root,
            "pythonpath": list(self.pythonpath),
        }
from_mapping(raw) classmethod

Validate absolute runner locations; never infer a service interpreter.

Source code in packages/axm/src/axm/tools/dependency_reads.py
Python
@classmethod
def from_mapping(cls, raw: Mapping[str, object]) -> DependencyEnvironment:
    """Validate absolute runner locations; never infer a service interpreter."""
    interpreter, root = raw.get("interpreter"), raw.get("package_root")
    paths = raw.get("pythonpath", ())
    if not isinstance(interpreter, str) or not Path(interpreter).is_absolute():
        raise ValueError("dependency interpreter must be absolute")
    if not isinstance(root, str) or not Path(root).is_absolute():
        raise ValueError("dependency package_root must be absolute")
    if not isinstance(paths, (list, tuple)) or any(
        not isinstance(p, str) or not Path(p).is_absolute() for p in paths
    ):
        raise ValueError("dependency pythonpath entries must be absolute")
    return cls(interpreter, os.path.realpath(root), tuple(str(p) for p in paths))
to_mapping()

Serialize the runner inputs without granting any write prefix.

Source code in packages/axm/src/axm/tools/dependency_reads.py
Python
def to_mapping(self) -> dict[str, object]:
    """Serialize the runner inputs without granting any write prefix."""
    return {
        "interpreter": self.interpreter,
        "package_root": self.package_root,
        "pythonpath": list(self.pythonpath),
    }

ToolAccessDenied

Bases: PermissionError

A named dispatch attempted to escape its positive tool scope.

Source code in packages/axm/src/axm/tools/access.py
Python
class ToolAccessDenied(PermissionError):  # noqa: N818
    """A named dispatch attempted to escape its positive tool scope."""

ToolMetadata dataclass

Facade/CLI discovery metadata for a tool, with safe defaults.

Built by :func:tool_metadata from the optional expose_directly / domain / tags attributes a tool may declare. Centralising the defaults here keeps the MCP facade and the CLI reading the same contract.

Attributes:

Name Type Description
expose_directly bool

Whether the tool is on the MCP hot path (registered directly in tools/list). Default False.

domain str | None

Coarse capability group, or None if ungrouped.

tags frozenset[str]

Discovery keywords (possibly empty).

Source code in packages/axm/src/axm/tools/base.py
Python
@dataclass(frozen=True)
class ToolMetadata:
    """Facade/CLI discovery metadata for a tool, with safe defaults.

    Built by :func:`tool_metadata` from the optional ``expose_directly`` /
    ``domain`` / ``tags`` attributes a tool may declare.  Centralising the
    defaults here keeps the MCP facade and the CLI reading the same contract.

    Attributes:
        expose_directly: Whether the tool is on the MCP hot path
            (registered directly in ``tools/list``).  Default ``False``.
        domain: Coarse capability group, or ``None`` if ungrouped.
        tags: Discovery keywords (possibly empty).
    """

    expose_directly: bool = False
    domain: str | None = None
    tags: frozenset[str] = frozenset()

ToolNodeError

Bases: RuntimeError

A tool invoked as a DAG node failed (ToolResult.success was False).

Source code in packages/axm/src/axm/tools/node.py
Python
class ToolNodeError(RuntimeError):
    """A tool invoked as a DAG node failed (``ToolResult.success`` was ``False``)."""

ToolResult dataclass

Immutable result of a tool execution.

Attributes:

Name Type Description
success bool

Whether the tool execution succeeded.

data dict[str, Any]

Structured output data (backend-specific).

error str | None

Human-readable error message, if any.

hint str | None

Optional next-step suggestion for the agent.

text str | None

Optional pre-rendered text representation (e.g. Markdown).

Source code in packages/axm/src/axm/tools/base.py
Python
@dataclass(frozen=True)
class ToolResult:
    """Immutable result of a tool execution.

    Attributes:
        success: Whether the tool execution succeeded.
        data: Structured output data (backend-specific).
        error: Human-readable error message, if any.
        hint: Optional next-step suggestion for the agent.
        text: Optional pre-rendered text representation (e.g. Markdown).
    """

    success: bool
    data: dict[str, Any] = field(default_factory=dict)
    error: str | None = None
    hint: str | None = None
    text: str | None = None

ValidationFeedback dataclass

Structured feedback for validation failures.

Attributes:

Name Type Description
what str

What failed (brief description)

why str

Why it failed (expected vs actual)

how str

How to fix it (actionable guidance)

Source code in packages/axm/src/axm/witnesses.py
Python
@dataclass(frozen=True)
class ValidationFeedback:
    """Structured feedback for validation failures.

    Attributes:
        what: What failed (brief description)
        why: Why it failed (expected vs actual)
        how: How to fix it (actionable guidance)
    """

    what: str
    why: str
    how: str

    def to_dict(self) -> dict[str, str]:
        """Serialize to dictionary."""
        return {"what": self.what, "why": self.why, "how": self.how}
to_dict()

Serialize to dictionary.

Source code in packages/axm/src/axm/witnesses.py
Python
def to_dict(self) -> dict[str, str]:
    """Serialize to dictionary."""
    return {"what": self.what, "why": self.why, "how": self.how}

WitnessResult dataclass

Result of a witness validation.

Attributes:

Name Type Description
passed bool

Whether validation passed

feedback ValidationFeedback | None

Feedback if validation failed

verdict str | None

Optional routing decision for Gates

metadata dict[str, Any]

Optional execution metadata

Source code in packages/axm/src/axm/witnesses.py
Python
@dataclass(frozen=True)
class WitnessResult:
    """Result of a witness validation.

    Attributes:
        passed: Whether validation passed
        feedback: Feedback if validation failed
        verdict: Optional routing decision for Gates
        metadata: Optional execution metadata
    """

    passed: bool
    feedback: ValidationFeedback | None = None
    verdict: str | None = None
    metadata: dict[str, Any] = field(default_factory=dict)

    @classmethod
    def success(
        cls,
        verdict: str | None = None,
        metadata: dict[str, Any] | None = None,
    ) -> WitnessResult:
        """Create a passing result."""
        return cls(passed=True, verdict=verdict, metadata=metadata or {})

    @classmethod
    def failure(
        cls,
        feedback: ValidationFeedback,
        verdict: str | None = None,
        metadata: dict[str, Any] | None = None,
    ) -> WitnessResult:
        """Create a failing result with feedback."""
        return cls(
            passed=False, feedback=feedback, verdict=verdict, metadata=metadata or {}
        )
failure(feedback, verdict=None, metadata=None) classmethod

Create a failing result with feedback.

Source code in packages/axm/src/axm/witnesses.py
Python
@classmethod
def failure(
    cls,
    feedback: ValidationFeedback,
    verdict: str | None = None,
    metadata: dict[str, Any] | None = None,
) -> WitnessResult:
    """Create a failing result with feedback."""
    return cls(
        passed=False, feedback=feedback, verdict=verdict, metadata=metadata or {}
    )
success(verdict=None, metadata=None) classmethod

Create a passing result.

Source code in packages/axm/src/axm/witnesses.py
Python
@classmethod
def success(
    cls,
    verdict: str | None = None,
    metadata: dict[str, Any] | None = None,
) -> WitnessResult:
    """Create a passing result."""
    return cls(passed=True, verdict=verdict, metadata=metadata or {})

WitnessRule

Bases: Protocol

Protocol for witness validation rules.

Source code in packages/axm/src/axm/witnesses.py
Python
@runtime_checkable
class WitnessRule(Protocol):
    """Protocol for witness validation rules."""

    def validate(self, content: str, **kwargs: Any) -> WitnessResult:
        """Validate content.

        Args:
            content: The content to validate
            **kwargs: Additional validation parameters

        Returns:
            WitnessResult indicating pass/fail with feedback
        """
        ...
validate(content, **kwargs)

Validate content.

Parameters:

Name Type Description Default
content str

The content to validate

required
**kwargs Any

Additional validation parameters

{}

Returns:

Type Description
WitnessResult

WitnessResult indicating pass/fail with feedback

Source code in packages/axm/src/axm/witnesses.py
Python
def validate(self, content: str, **kwargs: Any) -> WitnessResult:
    """Validate content.

    Args:
        content: The content to validate
        **kwargs: Additional validation parameters

    Returns:
        WitnessResult indicating pass/fail with feedback
    """
    ...

load_declarative_manifest(raw)

Validate a JSON manifest from a trusted installed package.

Extra fields, remote schema references, versions and collisions are refused. This validates metadata only: the host verifies the mounted bundle.

Source code in packages/axm/src/axm/tools/declarative.py
Python
def load_declarative_manifest(raw: Mapping[str, object]) -> DeclarativeToolManifest:
    """Validate a JSON manifest from a trusted installed package.

    Extra fields, remote schema references, versions and collisions are refused.
    This validates metadata only: the host verifies the mounted bundle.
    """
    data = _object(dict(raw), {"schema_version", "addon_id", "bundle_sha256", "tools"})
    if not isinstance(data["tools"], list):
        raise ValueError("manifest tools must be a list")
    version = data["schema_version"]
    if type(version) is not int:
        raise ValueError("schema_version must be an integer")
    return DeclarativeToolManifest(
        schema_version=version,
        addon_id=_string(data["addon_id"]),
        bundle_sha256=_string(data["bundle_sha256"]),
        tools=tuple(_definition(tool) for tool in data["tools"]),
    )

require_read_path(path)

Require read authority before opening a service's persisted target.

Both explicit caller targets and implicit configured targets must pass here after canonical service resolution. Relative paths use the active contract's execution root, and symlinks use its canonical readable decision. Transport None explicitly denies reads and suppresses the ambient environment. Only legacy local callers with neither transport binding nor contract stay unrestricted; this helper never grants write authority.

Source code in packages/axm/src/axm/tools/read_authority.py
Python
def require_read_path(path: str | Path) -> None:
    """Require read authority before opening a service's persisted target.

    Both explicit caller targets and implicit configured targets must pass here
    after canonical service resolution. Relative paths use the active contract's
    execution root, and symlinks use its canonical readable decision. Transport
    None explicitly denies reads and suppresses the ambient environment. Only
    legacy local callers with neither transport binding nor contract stay
    unrestricted; this helper never grants write authority.
    """
    contract = current_read_contract()
    if contract is None:
        if read_context_bound():
            raise PermissionError("read authority missing for persisted target")
        return
    resolved = contract.resolve(contract.execution_root, str(path))
    if not contract.readable(resolved):
        raise PermissionError(f"persisted target outside read authority: {resolved}")

require_write_path(path)

Require active write authority for a persisted target, or raise PermissionError.

Use this before the canonical business mutation, with the host-configured path, not a path chosen by the model. Only allowed write prefixes count: readable roots/dependency aliases never grant writes. Resolution is relative to the contract execution root and follows symlinks through its canonical resolver. Missing authority is refused, including headless calls without an explicit contract. Local CLI callers may use their explicit AXM_WRITE_CONTRACT.

Source code in packages/axm/src/axm/tools/write_authority.py
Python
def require_write_path(path: str | Path) -> None:
    """Require active write authority for a persisted target, or raise PermissionError.

    Use this before the canonical business mutation, with the host-configured
    path, not a path chosen by the model. Only allowed write prefixes count:
    readable roots/dependency aliases never grant writes. Resolution is relative
    to the contract execution root and follows symlinks through its canonical
    resolver. Missing authority is refused, including headless calls without an
    explicit contract. Local CLI callers may use their explicit AXM_WRITE_CONTRACT.
    """
    contract = current_read_contract()
    if contract is None:
        raise PermissionError("write authority missing for persisted target")
    resolved = contract.resolve(contract.execution_root, str(path))
    if not contract.permits(resolved):
        raise PermissionError(f"persisted target outside write authority: {resolved}")

session_dependency_environment(project_path)

Resolve a declared runtime, refusing implicit execution via read authority.

Return None only without a transport/local contract. Under a contract a matching declared environment is mandatory, including for readable roots. Keep the interpreter's lexical venv path; resolving its symlink loses venv activation semantics.

Source code in packages/axm/src/axm/tools/dependency_reads.py
Python
def session_dependency_environment(
    project_path: str | Path,
) -> DependencyEnvironment | None:
    """Resolve a declared runtime, refusing implicit execution via read authority.

    Return None only without a transport/local contract. Under a contract a
    matching declared environment is mandatory, including for readable roots.
    Keep the interpreter's lexical venv path; resolving its symlink loses venv
    activation semantics.
    """
    contract = current_read_contract()
    if contract is None:
        return None
    environments = contract.dependency_environments
    if contract.dependency_environment is not None:
        environments = (contract.dependency_environment, *environments)
    root = Path(project_path).resolve()
    matches = [
        env
        for env in environments
        if root.is_relative_to(Path(env.package_root).resolve())
    ]
    if not matches:
        raise ValueError(f"no declared runtime for: {root}")
    selected = _unambiguous_runtime(matches, root)
    if not Path(selected.interpreter).is_file():
        raise ValueError(
            f"declared runtime interpreter missing: {selected.interpreter}"
        )
    return selected

tool_access_scope(names)

Apply an immutable allowlist; nested scopes can only narrow it.

Source code in packages/axm/src/axm/tools/access.py
Python
@contextmanager
def tool_access_scope(names: frozenset[str]) -> Iterator[None]:
    """Apply an immutable allowlist; nested scopes can only narrow it."""
    if not isinstance(names, frozenset):
        raise ValueError("tool scope must be an immutable frozenset")
    outer = _ALLOWED.get()
    token = _ALLOWED.set(names if outer is None else outer & names)
    try:
        yield
    finally:
        _ALLOWED.reset(token)

tool_execution_guard(guard)

Install a neutral execution guard; inner scopes cannot remove outer guards.

Guards validate the current lease and may normalize detached keyword args. They run immediately before execution, including cached and injected tools. A transport owns its callback: the SDK does not import the transport.

Source code in packages/axm/src/axm/tools/access.py
Python
@contextmanager
def tool_execution_guard(guard: ExecutionGuard) -> Iterator[None]:
    """Install a neutral execution guard; inner scopes cannot remove outer guards.

    Guards validate the current lease and may normalize detached keyword args.
    They run immediately before execution, including cached and injected tools.
    A transport owns its callback: the SDK does not import the transport.
    """
    token = _GUARDS.set((*_GUARDS.get(), guard))
    try:
        yield
    finally:
        _GUARDS.reset(token)

tool_metadata(tool)

Read a tool's optional discovery attributes into a :class:ToolMetadata.

Works for tools that subclass :class:AXMTool, tools that satisfy it structurally, and plain callables — anything missing an attribute falls back to the default. tags is coerced to a frozenset so callers can rely on set semantics regardless of how the tool declared it.

Parameters:

Name Type Description Default
tool object

The tool instance (or plain callable) to introspect.

required

Returns:

Name Type Description
A ToolMetadata

class:ToolMetadata with resolved values.

Source code in packages/axm/src/axm/tools/base.py
Python
def tool_metadata(tool: object) -> ToolMetadata:
    """Read a tool's optional discovery attributes into a :class:`ToolMetadata`.

    Works for tools that subclass :class:`AXMTool`, tools that satisfy it
    structurally, and plain callables — anything missing an attribute falls
    back to the default.  ``tags`` is coerced to a ``frozenset`` so callers
    can rely on set semantics regardless of how the tool declared it.

    Args:
        tool: The tool instance (or plain callable) to introspect.

    Returns:
        A :class:`ToolMetadata` with resolved values.
    """
    raw_tags = getattr(tool, "tags", None) or ()
    return ToolMetadata(
        expose_directly=bool(getattr(tool, "expose_directly", False)),
        domain=getattr(tool, "domain", None),
        tags=frozenset(raw_tags),
    )

tool_node(name, *, args=None, returns=None, allow_failure_data=False)

Build a DAG python-node fn(payload) -> dict around an axm.tools tool.

Parameters:

Name Type Description Default
name str

The tool's axm.tools entry-point name (e.g. "ast_impact").

required
args Mapping[str, str] | None

Optional {param_name: mem_key} rename map for params whose mem key differs from the execute parameter name. Params absent from args are read from payload by their own name when present.

None
returns Mapping[str, str] | None

{write_key: source} where source is "text" (the ToolResult.text) or a key inside ToolResult.data. Defaults to {name: "text"} is not assumed — supply it so the node's writes are explicit (decision: writes nommés par clé).

Precedence / collision: the literal "text" is a sentinel that always routes to ToolResult.text, checked before any lookup in ToolResult.data. A tool whose data carries its own "text" key therefore cannot surface that field through this shortcut — source="text" yields ToolResult.text, never data["text"] (which is unreachable via returns). Route such a field under a different write source, or rename the data key upstream.

None
allow_failure_data bool

Opt-in for observation tools whose success=False is itself measured domain data (for example audit_test returning exact failed cases). When true, shape ToolResult.data through returns instead of raising solely on the success flag. Missing declared data still raises, so an empty/tool failure cannot become evidence. Defaults to the existing fail-fast behaviour.

False

Returns:

Type Description
Callable[[Mapping[str, object]], dict[str, object]]

A callable mapping the node's payload to a dict keyed by returns.

Raises:

Type Description
ToolNodeError

At call time, if the tool is unknown, returns success=False without the explicit observation opt-in, or omits one of the declared return fields.

Source code in packages/axm/src/axm/tools/node.py
Python
def tool_node(
    name: str,
    *,
    args: Mapping[str, str] | None = None,
    returns: Mapping[str, str] | None = None,
    allow_failure_data: bool = False,
) -> Callable[[Mapping[str, object]], dict[str, object]]:
    """Build a DAG python-node ``fn(payload) -> dict`` around an ``axm.tools`` tool.

    Args:
        name: The tool's ``axm.tools`` entry-point name (e.g. ``"ast_impact"``).
        args: Optional ``{param_name: mem_key}`` rename map for params whose mem
            key differs from the ``execute`` parameter name. Params absent from
            *args* are read from ``payload`` by their own name when present.
        returns: ``{write_key: source}`` where *source* is ``"text"`` (the
            ``ToolResult.text``) or a key inside ``ToolResult.data``. Defaults to
            ``{name: "text"}`` is **not** assumed — supply it so the node's writes
            are explicit (decision: writes nommés par clé).

            Precedence / collision: the literal ``"text"`` is a sentinel that
            **always** routes to ``ToolResult.text``, checked *before* any lookup
            in ``ToolResult.data``. A tool whose ``data`` carries its own
            ``"text"`` key therefore cannot surface that field through this
            shortcut — ``source="text"`` yields ``ToolResult.text``, never
            ``data["text"]`` (which is unreachable via *returns*). Route such a
            field under a different write source, or rename the data key upstream.
        allow_failure_data: Opt-in for observation tools whose ``success=False``
            is itself measured domain data (for example ``audit_test`` returning
            exact failed cases).  When true, shape ``ToolResult.data`` through
            *returns* instead of raising solely on the success flag. Missing
            declared data still raises, so an empty/tool failure cannot become
            evidence. Defaults to the existing fail-fast behaviour.

    Returns:
        A callable mapping the node's ``payload`` to a dict keyed by *returns*.

    Raises:
        ToolNodeError: At call time, if the tool is unknown, returns
            ``success=False`` without the explicit observation opt-in, or omits
            one of the declared return fields.
    """
    rename = dict(args or {})
    out_spec = dict(returns or {})
    cache: dict[str, AXMTool] = {}

    def _run(payload: Mapping[str, object]) -> dict[str, object]:
        require_tool_access(name)
        overrides = _OVERRIDES.get()
        if overrides and name in overrides:
            # A substitute shadows even a memoized real tool and never enters
            # the cache: it lives exactly as long as its block.
            tool: AXMTool = overrides[name]
        else:
            cached = cache.get(name)
            if cached is None:
                # Resolve entry points + instantiate once, lazily on first call
                # (late-binding): building the node scans nothing.
                cached = _load_tool(name)
                cache[name] = cached
            tool = cached
        kwargs = _kwargs_from_payload(payload, rename)
        try:
            result = guard_tool(name, tool).execute(**kwargs)
        except TypeError as exc:
            # A payload key with no matching ``execute`` parameter (strict
            # signature, no ``**kwargs``) must surface as the documented
            # ToolNodeError, not a raw TypeError.
            msg = f"tool {name!r}: bad payload for execute(): {exc}"
            raise ToolNodeError(msg) from exc
        if not result.success and not allow_failure_data:
            msg = f"tool {name!r} failed: {result.error or '<no error message>'}"
            raise ToolNodeError(msg)
        try:
            return _shape_output(name, result.data, result.text, out_spec)
        except ToolNodeError as exc:
            if not result.success and result.error:
                msg = f"tool {name!r} failed: {result.error}; {exc}"
                raise ToolNodeError(msg) from exc
            raise

    return _run

tool_scope_sha256(names)

Fingerprint a positive tool list; no provider-specific spelling.

Source code in packages/axm/src/axm/tools/declarative.py
Python
def tool_scope_sha256(names: frozenset[str]) -> str:
    """Fingerprint a positive tool list; no provider-specific spelling."""
    wire = json.dumps(sorted(names), ensure_ascii=False, separators=(",", ":"))
    return hashlib.sha256(wire.encode()).hexdigest()

validate_declarative_schema(schema)

Return a detached object schema validated offline for tools or snapshots.

Only the supported 2020-12 dialect and local references are accepted. Remote IDs/vocabularies and legacy recursive dialect keywords cannot weaken it.

Source code in packages/axm/src/axm/tools/declarative.py
Python
def validate_declarative_schema(schema: Mapping[str, object]) -> dict[str, object]:
    """Return a detached object schema validated offline for tools or snapshots.

    Only the supported 2020-12 dialect and local references are accepted. Remote
    IDs/vocabularies and legacy recursive dialect keywords cannot weaken it.
    """
    encoded = json.dumps(dict(schema), allow_nan=False)
    detached = json.loads(encoded)
    if detached.get("type") != "object":
        raise ValueError("tool schema root must be an object")
    _local_references(detached)
    try:
        Draft202012Validator.check_schema(detached)
    except SchemaError as exc:
        raise ValueError(f"invalid tool schema: {exc.message}") from exc
    return cast(dict[str, object], detached)