Core concepts · Module 2

Tools and actions

Tools are functions that agents can call to interact with the world.

45 min 3 outcomes Core concepts

Previously

How AI agents think

ReAct stands for reasoning and acting .

This module

Tools and actions

Tools are functions that agents can call to interact with the world.

Next

Memory and context

Short-Term Memory.

Progress

Mark this module complete when you can explain it without rereading every paragraph.

Why this matters

Tool.

What you will be able to do

  • 1 Define what a tool is in agent terms and why description quality matters.
  • 2 Design a tool schema that is precise enough for safe use.
  • 3 Handle tool failures without letting the agent spiral.

Before you begin

  • Foundations-level understanding of this course
  • Confidence with key terms introduced in Stage 1

Common ways people get this wrong

  • Wrong tool selection. If the agent calls the wrong tool, it can create bad side effects or leak data.
  • Unbounded capability. A tool that can do anything becomes a security incident waiting for a prompt.

2.2.1 What Are Tools?

Tools are functions that agents can call to interact with the world. They are the bridge between thinking and doing.

Tool

A function with a name, description, and defined parameters that an AI agent can choose to execute. Tools extend the agent's capabilities beyond text generation to real-world actions.

Common Tool Categories:

2.2.2 Designing Good Tool Schemas

The schema tells the agent what a tool does and how to use it. A well-designed schema reduces errors and improves tool selection.

"""
Tool Schema Design
==================
How to define tools that agents can use effectively.
"""

from dataclasses import dataclass
from typing import Any, Dict, Callable


@dataclass
class Tool:
    """
    A tool that an AI agent can use.
    
    Attributes:
        name: Unique identifier (use snake_case)
        description: What the tool does (be specific!)
        function: The Python function to execute
        parameters: JSON Schema defining expected inputs
    """
    name: str
    description: str
    function: Callable
    parameters: Dict[str, Any]
    
    def to_prompt_format(self) -> str:
        """Format for inclusion in agent prompts."""
        params = ", ".join(
            f"{k}: {v.get('description', 'no description')}"
            for k, v in self.parameters.get("properties", {}).items()
        )
        return f"- {self.name}({params}): {self.description}"


# Example: Well-designed tool

def search_web(query: str, num_results: int = 5) -> dict:
    """Search the web and return results."""
    # Implementation would go here
    return {"results": []}


search_tool = Tool(
    name="search_web",
    description="Search the internet for current information. Use for facts, news, or data you do not know. Returns titles, snippets, and URLs.",
    function=search_web,
    parameters={
        "type": "object",
        "properties": {
            "query": {
                "type": "string",
                "description": "The search query. Be specific and include relevant keywords."
            },
            "num_results": {
                "type": "integer",
                "description": "Number of results to return (1-10)",
                "default": 5
            }
        },
        "required": ["query"]
    }
)

Tool Description Best Practices:

  1. Be specific: "Search the internet for current information" is better than "Search"

  2. Explain when to use it: "Use for facts, news, or data you do not know"

  3. Describe outputs: "Returns titles, snippets, and URLs"

  4. Mention limitations: If the tool only works for certain inputs, say so

2.2.3 Tool Input Validation

Never trust agent-generated inputs. Always validate.

"""
Tool Input Validation
=====================
Validate inputs before executing tools.
"""

from typing import Any, Optional, Tuple
import re


class ToolInputValidator:
    """Validates tool inputs before execution."""
    
    @staticmethod
    def validate_search_query(query: Any) -> Tuple[bool, Optional[str]]:
        """
        Validate a search query.
        
        Args:
            query: The query to validate
            
        Returns:
            Tuple of (is_valid, error_message)
        """
        # Must be a string
        if not isinstance(query, str):
            return False, "Query must be a string"
        
        # Must not be empty
        if not query.strip():
            return False, "Query cannot be empty"
        
        # Length limits
        if len(query) > 500:
            return False, "Query too long (max 500 characters)"
        
        # No potential injection patterns
        suspicious = [
            r"<script",
            r"javascript:",
            r"data:",
            r"vbscript:",
        ]
        for pattern in suspicious:
            if re.search(pattern, query, re.IGNORECASE):
                return False, "Query contains suspicious content"
        
        return True, None
    
    @staticmethod
    def validate_file_path(path: Any, allowed_dirs: list) -> Tuple[bool, Optional[str]]:
        """
        Validate a file path is within allowed directories.
        
        Args:
            path: The file path to validate
            allowed_dirs: List of allowed directory prefixes
            
        Returns:
            Tuple of (is_valid, error_message)
        """
        import os
        
        if not isinstance(path, str):
            return False, "Path must be a string"
        
        # Normalise path to prevent directory traversal
        normalised = os.path.normpath(os.path.abspath(path))
        
        # Check if within allowed directories
        for allowed in allowed_dirs:
            if normalised.startswith(os.path.abspath(allowed)):
                return True, None
        
        return False, f"Path not in allowed directories: {allowed_dirs}"

Mental model

Tools as controlled capability

Tools turn text into real actions. That is powerful, and it is where most safety work lives.

  1. 1

    Need

  2. 2

    Choose tool

  3. 3

    Call tool

  4. 4

    Validate output

  5. 5

    Decide next step

Assumptions to keep in mind

  • Tool schemas are accurate. If the schema is wrong, the agent calls tools incorrectly and error handling becomes guesswork.
  • Outputs are validated. Treat tool output as untrusted input. Validate types, ranges, and permission scope.

Failure modes to notice

  • Wrong tool selection. If the agent calls the wrong tool, it can create bad side effects or leak data.
  • Unbounded capability. A tool that can do anything becomes a security incident waiting for a prompt.

Key terms

Tool
A function with a name, description, and defined parameters that an AI agent can choose to execute. Tools extend the agent's capabilities beyond text generation to real-world actions.

Check yourself

Quick check. Tools and actions

0 of 4 opened

What is a tool in an agent system

A function the agent can call with defined inputs to take an action or fetch evidence.

Why does a tool description matter so much

Because the description guides selection and correct use. Vague descriptions cause misuse and wrong tool choice.

Scenario. A tool accepts a file path. What is the first security risk to consider

Path traversal and unauthorised access. Validate paths and restrict to allowed directories.

What is a safe default when a tool call fails

Return a clear error and prompt the agent to ask for clarification or choose a different action rather than retrying forever.

Artefact and reflection

Artefact

One tool schema you would trust in a real workflow.

Reflection

Where in your work would define what a tool is in agent terms and why description quality matters. change a decision, and what evidence would make you trust that change?

Optional practice

Write one tool description that prevents misuse by default.