Tool / Function-Calling System

DeskBot's tool system allows the LLM to invoke robot actions (change emotion, move servos, play sounds, speak text) through a structured function-calling interface compatible with OpenAI, Ollama, and other LLM providers.

The system has three layers:

  1. Schema - ToolDefinition and ToolParameter define the shape of a tool and serialise to the OpenAI function-calling JSON format.
  2. Registry - ToolRegistry holds definitions and their handler functions, and can execute tool calls by name.
  3. Executor - ToolExecutor dispatches LLM tool calls to robot actions via the event bus and hardware controllers.

Tool definition schema

Each tool is described by a ToolDefinition with a name, description, and a tuple of ToolParameter objects:

from robot.ai.tools.schema import ToolDefinition, ToolParameter, ToolParameterType

my_tool = ToolDefinition(
    name="change_emotion",
    description="Change the robot's emotional expression.",
    parameters=(
        ToolParameter(
            name="emotion",
            type=ToolParameterType.STRING,
            description="The emotion to express.",
            enum=("neutral", "happy", "curious", "thinking", "sleepy",
                   "embarrassed", "excited", "sad", "surprised", "angry"),
        ),
        ToolParameter(
            name="intensity",
            type=ToolParameterType.NUMBER,
            description="Intensity of the emotion (0.0 to 1.0).",
            required=False,
            default=1.0,
        ),
    ),
)

OpenAI-compatible schema

Every ToolDefinition can produce an OpenAI function-calling schema:

schema = my_tool.to_openai_schema()
# {
#   "type": "function",
#   "function": {
#     "name": "change_emotion",
#     "description": "Change the robot's emotional expression.",
#     "parameters": { ... }
#   }
# }

This schema can be passed directly to any OpenAI-compatible LLM as a tool definition.


Tool registry

The ToolRegistry manages tool definitions and their handler functions:

from robot.ai.tools.registry import ToolRegistry, BUILTIN_TOOLS

registry = ToolRegistry()

# Register a built-in tool with its handler
registry.add(BUILTIN_TOOLS["change_emotion"], my_handler)

# Get all OpenAI schemas for an LLM prompt
schemas = registry.get_schemas()

# Execute a tool call from the LLM
result = await registry.execute("change_emotion", {"emotion": "happy"})

Methods

Method Description
add(definition, handler) Register a tool and its async handler
remove(name) Remove a tool by name
get(name) Return a tool definition by name
get_handler(name) Return a tool handler by name
list_tools() Return all registered tool definitions
get_schemas() Return OpenAI-compatible schemas for all tools
execute(name, arguments) Execute a tool by name with arguments

Built-in tools

DeskBot ships with 5 built-in tools defined in BUILTIN_TOOLS:

Tool Description Parameters
change_emotion Change the robot's emotional expression emotion (enum), intensity (number, optional)
play_sound Play a sound effect through the speaker name (string)
set_state Transition the robot to a new state state (enum)
move_servo Move a servo to a target angle servo (enum), angle (number), duration_s (number, optional)
speak Make the robot say something using TTS text (string)

Tool executor

The ToolExecutor validates arguments, dispatches built-in tool calls to the event bus, and delegates custom tool calls to their registered handlers:

from robot.ai.tools.executor import ToolExecutor

executor = ToolExecutor(
    registry=registry,
    bus=event_bus,
    servo_controller=servo_ctrl,
    tts=tts_engine,
    action_executor=action_executor,  # optional: route learnable tools through the executor
)

result = await executor.execute_tool_call("change_emotion", {"emotion": "happy"})
# {"status": "ok", "emotion": "happy", "intensity": 1.0}

Built-in tool dispatch

When an action_executor is not wired (the legacy path), built-in tools dispatch directly to the event bus and hardware controllers:

Tool Dispatch target (legacy)
change_emotion Publishes EmotionChanged + BlinkRequested on the event bus
play_sound Publishes SoundEffectPlayed on the event bus
set_state Publishes StateChanged on the event bus
move_servo Calls ServoController.get(name).move_to() + publishes ServoMoved
speak Calls TextToSpeech.speak(text)

Learning-aware routing

When an action_executor is wired (the default once learning is enabled in DeskBotApp), the learnable builtins — change_emotion, set_state, move_servo, and speak — are routed through the canonical ActionExecutor instead of going directly to the bus/hardware. Each call is translated into the matching BehaviorAction (ChangeEmotionAction, SetStateAction, RequestServoMoveAction, SpeakAction) and dispatched via ActionExecutor.execute_one, so the LLM tool call is recorded as a real learning transition with the same lifecycle, safety checks, and interaction tagging as any other action (see Services). play_sound is intentionally not routed (it is not in the action space) and is logged as action_not_learnable.

Argument validation

The executor validates required parameters and coerces types. If a required parameter is missing or an unknown tool name is provided, a ToolExecutionError is raised.


Registering custom tools

To add a new tool:

from robot.ai.tools.schema import ToolDefinition, ToolParameter, ToolParameterType
from robot.ai.tools.registry import ToolRegistry

registry = ToolRegistry()

# Define the tool
my_tool = ToolDefinition(
    name="set_led_color",
    description="Set the LED strip to a specific colour.",
    parameters=(
        ToolParameter(
            name="color",
            type=ToolParameterType.STRING,
            description="Hex colour code (e.g. '#ff0000').",
        ),
    ),
)

# Define the handler
async def handle_set_led(color: str) -> dict:
    # ... drive hardware ...
    return {"status": "ok", "color": color}

# Register
registry.add(my_tool, handle_set_led)

The tool's OpenAI schema will automatically appear in registry.get_schemas() for inclusion in LLM prompts.


API reference

robot.ai.tools.schema

Tool definition schema for LLM function calling.

Follows the OpenAI function-calling format so tools can be passed directly to compatible LLMs (OpenAI, Ollama, etc.).

ToolDefinition dataclass

A complete tool definition that can be serialised for an LLM.

Attributes

name: The tool name (e.g. "change_emotion"). description: A human-readable description of what the tool does. parameters: The list of parameters the tool accepts.

Source code in src/robot/ai/tools/schema.py
@dataclass(slots=True, frozen=True)
class ToolDefinition:
    """A complete tool definition that can be serialised for an LLM.

    Attributes
    ----------
    name:
        The tool name (e.g. ``"change_emotion"``).
    description:
        A human-readable description of what the tool does.
    parameters:
        The list of parameters the tool accepts.
    """

    name: str
    description: str
    parameters: tuple[ToolParameter, ...] = ()

    def to_openai_schema(self) -> dict[str, Any]:
        """Serialise to the OpenAI function-calling schema format."""
        properties: dict[str, Any] = {}
        required: list[str] = []

        for param in self.parameters:
            prop: dict[str, Any] = {
                "type": param.type.value,
                "description": param.description,
            }
            if param.enum:
                prop["enum"] = list(param.enum)
            if param.default is not None:
                prop["default"] = param.default
            properties[param.name] = prop
            if param.required:
                required.append(param.name)

        return {
            "type": "function",
            "function": {
                "name": self.name,
                "description": self.description,
                "parameters": {
                    "type": "object",
                    "properties": properties,
                    "required": required,
                },
            },
        }

to_openai_schema()

Serialise to the OpenAI function-calling schema format.

Source code in src/robot/ai/tools/schema.py
def to_openai_schema(self) -> dict[str, Any]:
    """Serialise to the OpenAI function-calling schema format."""
    properties: dict[str, Any] = {}
    required: list[str] = []

    for param in self.parameters:
        prop: dict[str, Any] = {
            "type": param.type.value,
            "description": param.description,
        }
        if param.enum:
            prop["enum"] = list(param.enum)
        if param.default is not None:
            prop["default"] = param.default
        properties[param.name] = prop
        if param.required:
            required.append(param.name)

    return {
        "type": "function",
        "function": {
            "name": self.name,
            "description": self.description,
            "parameters": {
                "type": "object",
                "properties": properties,
                "required": required,
            },
        },
    }

ToolParameter dataclass

A single parameter in a tool definition.

Source code in src/robot/ai/tools/schema.py
@dataclass(slots=True, frozen=True)
class ToolParameter:
    """A single parameter in a tool definition."""

    name: str
    type: ToolParameterType = ToolParameterType.STRING
    description: str = ""
    required: bool = True
    enum: tuple[str, ...] = ()
    default: Any = None

ToolParameterType

Bases: str, Enum

JSON Schema types for tool parameters.

Source code in src/robot/ai/tools/schema.py
class ToolParameterType(str, Enum):
    """JSON Schema types for tool parameters."""

    STRING = "string"
    NUMBER = "number"
    INTEGER = "integer"
    BOOLEAN = "boolean"
    ARRAY = "array"
    OBJECT = "object"

robot.ai.tools.registry

Tool registry - manages available LLM-callable tools.

The registry holds :class:ToolDefinition instances and their corresponding handler functions. When the LLM produces a tool call, the :class:ToolExecutor looks up the tool by name and invokes the handler.

ToolError

Bases: DeskBotError

Error during tool registration or execution.

Source code in src/robot/ai/tools/registry.py
class ToolError(DeskBotError):
    """Error during tool registration or execution."""

ToolRegistry

Registry of available LLM tools and their handlers.

Usage::

registry = ToolRegistry()


@registry.register_tool
async def change_emotion(emotion: str, intensity: float = 1.0) -> dict:
    ...
    return {"status": "ok", "emotion": emotion}


# Get schemas for the LLM prompt
schemas = registry.get_schemas()

# Execute a tool call from the LLM
result = await registry.execute("change_emotion", {"emotion": "happy"})
Source code in src/robot/ai/tools/registry.py
class ToolRegistry:
    """Registry of available LLM tools and their handlers.

    Usage::

        registry = ToolRegistry()


        @registry.register_tool
        async def change_emotion(emotion: str, intensity: float = 1.0) -> dict:
            ...
            return {"status": "ok", "emotion": emotion}


        # Get schemas for the LLM prompt
        schemas = registry.get_schemas()

        # Execute a tool call from the LLM
        result = await registry.execute("change_emotion", {"emotion": "happy"})
    """

    def __init__(self) -> None:
        self._tools: OrderedDict[str, ToolDefinition] = OrderedDict()
        self._handlers: dict[str, ToolHandler] = {}

    def add(
        self,
        definition: ToolDefinition,
        handler: ToolHandler,
    ) -> None:
        """Register a tool and its handler."""
        name = definition.name
        if name in self._tools:
            raise ToolError(f"tool {name!r} is already registered")
        self._tools[name] = definition
        self._handlers[name] = handler
        _log.info("tool.registered", name=name)

    def remove(self, name: str) -> None:
        """Remove a tool by name."""
        if name not in self._tools:
            raise ToolError(f"tool {name!r} is not registered")
        del self._tools[name]
        del self._handlers[name]

    def get(self, name: str) -> ToolDefinition:
        """Return a tool definition by name."""
        if name not in self._tools:
            raise ToolError(f"tool {name!r} is not registered")
        return self._tools[name]

    def get_handler(self, name: str) -> ToolHandler:
        """Return a tool handler by name."""
        if name not in self._handlers:
            raise ToolError(f"no handler for tool {name!r}")
        return self._handlers[name]

    def list_tools(self) -> list[ToolDefinition]:
        """Return all registered tool definitions."""
        return list(self._tools.values())

    def get_schemas(self) -> list[dict[str, Any]]:
        """Return OpenAI-compatible tool schemas for all registered tools."""
        return [t.to_openai_schema() for t in self._tools.values()]

    async def execute(self, name: str, arguments: dict[str, Any]) -> dict[str, Any]:
        """Execute a tool by name with the given arguments.

        Returns the handler's result dict. Raises :class:`ToolError`
        if the tool is not found, and propagates any handler exceptions.
        """
        if name not in self._handlers:
            raise ToolError(f"unknown tool {name!r}")
        handler = self._handlers[name]
        try:
            result = await handler(**arguments)
            _log.info("tool.executed", name=name, args_count=len(arguments))
            return result
        except Exception as exc:
            _log.exception("tool.execution_failed", name=name)
            return {"error": str(exc), "tool": name}

    @property
    def tool_count(self) -> int:
        return len(self._tools)

    def __contains__(self, name: str) -> bool:
        return name in self._tools

add(definition, handler)

Register a tool and its handler.

Source code in src/robot/ai/tools/registry.py
def add(
    self,
    definition: ToolDefinition,
    handler: ToolHandler,
) -> None:
    """Register a tool and its handler."""
    name = definition.name
    if name in self._tools:
        raise ToolError(f"tool {name!r} is already registered")
    self._tools[name] = definition
    self._handlers[name] = handler
    _log.info("tool.registered", name=name)

execute(name, arguments) async

Execute a tool by name with the given arguments.

Returns the handler's result dict. Raises :class:ToolError if the tool is not found, and propagates any handler exceptions.

Source code in src/robot/ai/tools/registry.py
async def execute(self, name: str, arguments: dict[str, Any]) -> dict[str, Any]:
    """Execute a tool by name with the given arguments.

    Returns the handler's result dict. Raises :class:`ToolError`
    if the tool is not found, and propagates any handler exceptions.
    """
    if name not in self._handlers:
        raise ToolError(f"unknown tool {name!r}")
    handler = self._handlers[name]
    try:
        result = await handler(**arguments)
        _log.info("tool.executed", name=name, args_count=len(arguments))
        return result
    except Exception as exc:
        _log.exception("tool.execution_failed", name=name)
        return {"error": str(exc), "tool": name}

get(name)

Return a tool definition by name.

Source code in src/robot/ai/tools/registry.py
def get(self, name: str) -> ToolDefinition:
    """Return a tool definition by name."""
    if name not in self._tools:
        raise ToolError(f"tool {name!r} is not registered")
    return self._tools[name]

get_handler(name)

Return a tool handler by name.

Source code in src/robot/ai/tools/registry.py
def get_handler(self, name: str) -> ToolHandler:
    """Return a tool handler by name."""
    if name not in self._handlers:
        raise ToolError(f"no handler for tool {name!r}")
    return self._handlers[name]

get_schemas()

Return OpenAI-compatible tool schemas for all registered tools.

Source code in src/robot/ai/tools/registry.py
def get_schemas(self) -> list[dict[str, Any]]:
    """Return OpenAI-compatible tool schemas for all registered tools."""
    return [t.to_openai_schema() for t in self._tools.values()]

list_tools()

Return all registered tool definitions.

Source code in src/robot/ai/tools/registry.py
def list_tools(self) -> list[ToolDefinition]:
    """Return all registered tool definitions."""
    return list(self._tools.values())

remove(name)

Remove a tool by name.

Source code in src/robot/ai/tools/registry.py
def remove(self, name: str) -> None:
    """Remove a tool by name."""
    if name not in self._tools:
        raise ToolError(f"tool {name!r} is not registered")
    del self._tools[name]
    del self._handlers[name]

robot.ai.tools.executor

Tool executor - dispatches LLM tool calls to robot actions.

ToolExecutionError

Bases: DeskBotError

Error during tool execution.

Source code in src/robot/ai/tools/executor.py
class ToolExecutionError(DeskBotError):
    """Error during tool execution."""

ToolExecutor dataclass

Dispatches LLM tool calls to robot actions.

Source code in src/robot/ai/tools/executor.py
@dataclass(slots=True)
class ToolExecutor:
    """Dispatches LLM tool calls to robot actions."""

    registry: ToolRegistry
    bus: InMemoryEventBus
    servo_controller: ServoController | None = None
    tts: TextToSpeech | None = None
    audio: AudioOutput | None = None
    #: Optional canonical action executor. When set, learnable builtin tools
    #: route through it so each call is recorded as a learning transition
    #: (single execution point). When ``None``, the direct ``_handle_*`` paths
    #: are used (preserves the pre-teaching-loop behaviour and all tests).
    action_executor: ActionExecutor | None = None

    async def execute_tool_call(
        self,
        tool_name: str,
        arguments: dict[str, Any],
    ) -> dict[str, Any]:
        """Execute a single tool call."""
        _log.info("tool_executor.call", tool=tool_name, args=arguments)

        if tool_name not in self.registry:
            raise ToolExecutionError(f"unknown tool: {tool_name!r}")

        definition = self.registry.get(tool_name)
        validated = self._validate_arguments(definition, arguments)

        handler_name = _BUILTIN_HANDLER_MAP.get(tool_name)
        if handler_name is not None:
            # Learnable builtins route through the ActionExecutor when one is
            # wired, so the call becomes a learning transition. ``play_sound``
            # is not registered in the ActionSpace - it stays a direct bus
            # publish and is logged as not-learnable.
            if self.action_executor is not None and tool_name in _LEARNABLE_TOOLS:
                return await self._route_to_action_executor(tool_name, validated)
            if tool_name == "play_sound":
                _log.info(
                    "tool_executor.action_not_learnable",
                    tool=tool_name,
                    reason="not registered in ActionSpace",
                )
            handler = getattr(self, handler_name)
            return cast("dict[str, Any]", await handler(validated))

        return await self.registry.execute(tool_name, validated)

    async def _route_to_action_executor(  # noqa: PLR0911
        self, tool_name: str, args: dict[str, Any]
    ) -> dict[str, Any]:
        """Route a learnable builtin tool through the ActionExecutor.

        Builds the matching :class:`BehaviorAction` and executes it via the
        canonical executor, returning a status dict shaped like the direct
        ``_handle_*`` handlers. Validation errors (unknown emotion/state) and
        hardware failures (e.g. out-of-range servo) are returned as error dicts
        rather than raised, matching the direct handlers' contract.
        """
        assert self.action_executor is not None  # guarded by caller
        try:
            if tool_name == "change_emotion":
                emotion_name = str(args.get("emotion", "neutral"))
                intensity = max(0.0, min(1.0, float(args.get("intensity", 1.0))))
                try:
                    EmotionName(emotion_name)
                except ValueError:
                    return {
                        "error": f"unknown emotion {emotion_name!r}",
                        "valid": [e.value for e in EmotionName],
                    }
                await self.action_executor.execute_one(
                    ChangeEmotionAction(emotion=emotion_name, intensity=intensity)
                )
                return {"status": "ok", "emotion": emotion_name, "intensity": intensity}

            if tool_name == "set_state":
                from robot.behavior.state_machine import RobotState

                state_name = str(args.get("state", "idle"))
                try:
                    RobotState(state_name)
                except ValueError:
                    return {
                        "error": f"unknown state {state_name!r}",
                        "valid": [s.value for s in RobotState],
                    }
                await self.action_executor.execute_one(SetStateAction(state=state_name))
                return {"status": "ok", "state": state_name}

            if tool_name == "move_servo":
                if self.servo_controller is None:
                    return {"error": "no servo controller available"}
                servo_name = str(args.get("servo", "pan"))
                angle = float(args.get("angle", 90.0))
                try:
                    await self.action_executor.execute_one(
                        RequestServoMoveAction(servo=servo_name, angle=angle)
                    )
                    return {"status": "ok", "servo": servo_name, "angle": angle}
                except Exception as exc:
                    return {"error": str(exc), "servo": servo_name}

            if tool_name == "speak":
                text = str(args.get("text", ""))
                if not text:
                    return {"error": "empty text"}
                await self.action_executor.execute_one(SpeakAction(text=text))
                return {"status": "ok", "text": text[:100]}

            return {"error": f"tool {tool_name!r} not routable to action executor"}
        except Exception as exc:
            _log.exception("tool_executor.route_failed", tool=tool_name)
            return {"error": str(exc), "tool": tool_name}

    def _validate_arguments(
        self, definition: ToolDefinition, arguments: dict[str, Any]
    ) -> dict[str, Any]:
        """Validate and coerce arguments against the tool's parameters."""
        validated: dict[str, Any] = {}

        for param in definition.parameters:
            value = arguments.get(param.name, param.default)
            if param.required and value is None:
                raise ToolExecutionError(
                    f"tool {definition.name!r}: missing required parameter {param.name!r}"
                )
            if value is not None:
                value = self._coerce_type(param, value)
            validated[param.name] = value

        return validated

    @classmethod
    def _coerce_type(cls, param: ToolParameter, value: Any) -> Any:
        """Coerce a value to the expected parameter type."""
        if isinstance(value, str):
            return cls._coerce_string(param.type, value)
        if isinstance(value, (int, float)):
            return cls._coerce_number(param.type, value)
        return value

    @staticmethod
    def _coerce_string(ptype: ToolParameterType, value: str) -> Any:
        if ptype == ToolParameterType.NUMBER:
            try:
                return float(value)
            except ValueError:
                return value
        if ptype == ToolParameterType.INTEGER:
            try:
                return int(value)
            except ValueError:
                return value
        if ptype == ToolParameterType.BOOLEAN:
            lower = value.lower()
            return (
                True
                if lower in ("true", "1", "yes")
                else False
                if lower in ("false", "0", "no")
                else None
            )
        return value

    @staticmethod
    def _coerce_number(ptype: ToolParameterType, value: int | float) -> Any:
        if ptype == ToolParameterType.STRING:
            return str(value)
        if ptype == ToolParameterType.INTEGER:
            return int(value)
        return value

    async def _handle_change_emotion(self, args: dict[str, Any]) -> dict[str, Any]:
        """Dispatch an emotion change through the event bus."""
        emotion_name = str(args.get("emotion", "neutral"))
        intensity = max(0.0, min(1.0, float(args.get("intensity", 1.0))))

        try:
            emotion = EmotionName(emotion_name)
        except ValueError:
            valid = [e.value for e in EmotionName]
            return {"error": f"unknown emotion {emotion_name!r}", "valid": valid}

        await self.bus.publish(
            EmotionChanged(previous=EmotionName.NEUTRAL, current=emotion, intensity=intensity)
        )
        await self.bus.publish(BlinkRequested(speed=1.0))
        return {"status": "ok", "emotion": emotion_name, "intensity": intensity}

    async def _handle_play_sound(self, args: dict[str, Any]) -> dict[str, Any]:
        """Play a sound effect via the event bus."""
        name = str(args.get("name", ""))
        await self.bus.publish(SoundEffectPlayed(name=name, filename=f"{name}.wav"))
        return {"status": "ok", "sound": name}

    async def _handle_set_state(self, args: dict[str, Any]) -> dict[str, Any]:
        """Transition the robot to a new state via the event bus."""
        from robot.behavior.state_machine import RobotState
        from robot.events.events import StateChanged

        state_name = str(args.get("state", "idle"))
        try:
            state = RobotState(state_name)
        except ValueError:
            valid = [s.value for s in RobotState]
            return {"error": f"unknown state {state_name!r}", "valid": valid}

        await self.bus.publish(StateChanged(previous=RobotState.IDLE, current=state))
        return {"status": "ok", "state": state_name}

    async def _handle_move_servo(self, args: dict[str, Any]) -> dict[str, Any]:
        """Move a servo to a target angle."""
        if self.servo_controller is None:
            return {"error": "no servo controller available"}

        servo_name = str(args.get("servo", "pan"))
        angle = float(args.get("angle", 90.0))
        duration_s = float(args.get("duration_s", 0.4))

        try:
            servo = self.servo_controller.get(servo_name)
            await servo.move_to(angle, duration_s=duration_s)
            await self.bus.publish(ServoMoved(name=servo_name, angle=angle))
            return {"status": "ok", "servo": servo_name, "angle": angle}
        except Exception as exc:
            return {"error": str(exc), "servo": servo_name}

    async def _handle_speak(self, args: dict[str, Any]) -> dict[str, Any]:
        """Speak text through TTS and play via the audio output."""
        if self.tts is None:
            return {"error": "no TTS engine available"}
        text = str(args.get("text", ""))
        if not text:
            return {"error": "empty text"}
        buffer = await self.tts.speak(text)
        if buffer is not None and not buffer.is_empty and self.audio is not None:
            await self.audio.play(buffer)
        return {"status": "ok", "text": text[:100]}

execute_tool_call(tool_name, arguments) async

Execute a single tool call.

Source code in src/robot/ai/tools/executor.py
async def execute_tool_call(
    self,
    tool_name: str,
    arguments: dict[str, Any],
) -> dict[str, Any]:
    """Execute a single tool call."""
    _log.info("tool_executor.call", tool=tool_name, args=arguments)

    if tool_name not in self.registry:
        raise ToolExecutionError(f"unknown tool: {tool_name!r}")

    definition = self.registry.get(tool_name)
    validated = self._validate_arguments(definition, arguments)

    handler_name = _BUILTIN_HANDLER_MAP.get(tool_name)
    if handler_name is not None:
        # Learnable builtins route through the ActionExecutor when one is
        # wired, so the call becomes a learning transition. ``play_sound``
        # is not registered in the ActionSpace - it stays a direct bus
        # publish and is logged as not-learnable.
        if self.action_executor is not None and tool_name in _LEARNABLE_TOOLS:
            return await self._route_to_action_executor(tool_name, validated)
        if tool_name == "play_sound":
            _log.info(
                "tool_executor.action_not_learnable",
                tool=tool_name,
                reason="not registered in ActionSpace",
            )
        handler = getattr(self, handler_name)
        return cast("dict[str, Any]", await handler(validated))

    return await self.registry.execute(tool_name, validated)