Introduction
In our last lesson, we built a crucial reliability layer for our agent's knowledge system by implementing a relevance grader for RAG. This moved us from a naive retrieval pipeline to an intelligent, self-correcting one—a system that can be encapsulated as a single, robust "tool." This naturally leads to our next challenge: how do we build an agent that can manage and orchestrate not just one, but a diverse and growing set of tools?
This lesson addresses that question by tackling a foundational piece of agentic engineering: the tool registry. You will learn to design and implement a system for the dynamic registration, discovery, and schema validation of agent tools. We will move away from simple, hardcoded lists of functions and build a centralized, scalable catalog for your agent's capabilities. Your background in distributed systems will be particularly relevant here, as we'll see that a tool registry serves a purpose analogous to a service registry in a microservices architecture.
By the end of this lesson, you will have designed and implemented a ToolRegistry class from first principles, capable of automatically generating tool schemas, providing them to the LLM for discovery, and validating tool calls before execution.
The Problem of Tool Management
As an agent's capabilities expand, managing its tools with simple lists or dictionaries becomes untenable. Consider an agent that can search a database, send emails, schedule meetings, and analyze data. Manually defining the JSON schema for each function and keeping it synchronized with the Python code is tedious and error-prone. This ad-hoc approach introduces several problems:
- Maintainability: Adding, removing, or updating a tool requires modifying multiple parts of the core agent logic.
- Discovery: How does the LLM reliably discover the available tools and their correct usage? A static list passed at runtime is inflexible.
- Validation: How do you protect your system from malformed arguments generated by the LLM? Executing a tool with incorrect argument types or values can lead to runtime errors or unpredictable behavior.
The solution is to abstract tool management into a dedicated component: a tool registry.
The Registry Pattern: Service Discovery for Agents
In a microservices architecture, a service registry (like Consul or Zookeeper) provides a central catalog of available services, their locations, and their health. Clients don't need to know the specific address of a service instance; they query the registry to discover it. A tool registry plays the same role for an agent.

This diagram illustrates a service discovery pattern. A central "Service Registry" holds information about available service instances. Clients query the registry to discover and connect to them. Our tool registry will function similarly for our agent, acting as a central catalog of capabilities.
The tool registry becomes the single source of truth for all available tools. It is responsible for:
- Registration: Allowing new tools to be added to the agent's toolkit, ideally dynamically.
- Discovery: Providing a list of tool schemas for the LLM, enabling it to decide which tool to use.
- Execution & Validation: Locating the correct tool implementation and validating the LLM's proposed arguments against the tool's schema before execution.
The Tool Schema: A Contract with the LLM
The foundation of the registry is the tool schema. As we've seen before, this is typically a JSON Schema object that acts as a contract, describing a tool's interface to the LLM.

This image shows the direct correspondence between a Python function (left) and its JSON Schema representation (right). The schema captures the function's name, description, parameters, and their types, creating a machine-readable "API documentation" for the LLM.
A well-designed schema is critical for reliable tool use. The article "Function Calling: Structured Tool Use for Large Language Models" provides excellent best practices for schema design.
Function Calling: Structured Tool Use for Large Language Models
This article explains the core components of a function schema and provides principles for designing them effectively.
First, read the section JSON Schema Structure. This details the roles of the name, description, and parameters fields. Pay close attention to the point about the description guiding the model's judgment. Next, review the principles in Schema Design Best Practices. The advice on specificity, consistency, and minimizing required parameters is directly applicable to building a robust registry.
Manually creating and maintaining these schemas is not scalable. The first step in building our registry is to automate their generation.
Automating Schema Generation with Introspection
Python's runtime introspection capabilities allow us to inspect live objects, including functions, and extract their properties. We can use this to automatically generate a JSON schema from a Python function definition.
The article "The Anatomy of Tool Calling" provides a superb, from-scratch guide to this process. It demonstrates how to use the inspect module to build a schema generator.
Introspection for Function Calling - JSON schema for LLMs
This article provides a first-principles walkthrough of converting Python functions to JSON schemas.
First, read the sections under "Object Introspection" to understand the core mechanics: Extracting parameters and types using inspect.signature. Extracting the docstring using __doc__. Extracting the function name using __name__. Then, study the section Approach 1: Pure Python. The function_to_json utility presented here is a perfect example of a lightweight, dependency-free schema generator built on these introspection principles. We will base our initial registry implementation on this concept.
This introspection-based approach is powerful, but for production-grade validation, we can do better.
Enhancing Validation with Pydantic
The pure-Python schema generator is excellent for basic types, but it lacks robust validation for complex constraints (e.g., string patterns, numeric ranges) and doesn't handle type coercion gracefully. For this, we turn to Pydantic, the de facto standard for data validation in Python.
Pydantic uses Python type hints to define data models that automatically validate, serialize, and deserialize data. For our purposes, it offers two key advantages:
- Robust Schema Generation: Pydantic can generate a rich JSON Schema directly from a model, including complex validation rules.
- Data Validation and Coercion: It can parse raw data (like the arguments from an LLM) and validate it against the model, coercing types where appropriate (e.g., converting the string
"123"to the integer123).
Pydantic is an extensive library. The following video provides a comprehensive overview. Focus on the core concepts of creating models and defining fields with constraints.
Python Pydantic Tutorial: Complete Data Validation Course (Used by FastAPI)
This video by Corey Schafer is a complete course on Pydantic. We'll focus on the parts most relevant to our tool registry.
First, watch the introduction to understand what Pydantic is and why it's used: Why Pydantic?. Next, see how to create a basic model and how Pydantic handles validation errors: Creating Models. To see how to define more robust validation rules, watch the section on adding constraints using Annotated and Field: Adding Constraints. This is key for creating precise schemas. Finally, look at how Pydantic provides specialized types for common formats, which simplifies schema definition immensely: Specialized Types. Using types like EmailStr and HttpUrl gives us powerful validation for free.
Pydantic models can replace raw dictionaries for defining our tool parameters, giving us a much more powerful and secure way to handle schema generation and argument validation. The article "The Anatomy of Tool Calling" also demonstrates how to generate schemas using Pydantic, providing a more direct code example.
Introspection for Function Calling - JSON schema for LLMs
Let's revisit this article to see the Pydantic-based approach.
Read the section Approach 2: Pydantic. It shows how to dynamically create a Pydantic model from a function's signature and then generate a JSON schema from that model. This is a more robust alternative to the pure-Python method.
Implementing the ToolRegistry Class
Now we have all the components to design our ToolRegistry. Its structure will centralize the registration, discovery, and execution logic. The "Function Calling" article we looked at earlier provides an excellent, clear implementation of this pattern.
Function Calling: Structured Tool Use for Large Language Models
This section of the article provides a full code implementation of a function calling system, including a ToolRegistry class.
Focus on the ToolRegistry class definition in the section Code Implementation. Analyze its methods: __init__: Notice how it uses two dictionaries, one for schemas (tools) and one for the actual Python functions (implementations). register: This method adds a tool's schema and its implementation to the registry. get_schemas: This method formats the stored schemas into the list structure that LLM APIs expect. This is the discovery mechanism. execute: This is the most critical method. It finds the function, calls it with the provided arguments, and wraps the execution in a try-except block for robust error handling. After studying the class, look at how it's used in the section that begins just after the calculator_tool function definition, where tools are instantiated and registered.
Our own implementation will combine these ideas. We will create a ToolRegistry that can automatically generate a schema from a Python function upon registration and use Pydantic for argument validation during execution.
Here is a conceptual implementation of such a ToolRegistry:
import inspect
from pydantic import create_model, ValidationError
class ToolRegistry:
def __init__(self):
self.functions = {}
self.schemas = {}
def _generate_pydantic_model(self, func):
# Use introspection to create a Pydantic model for the function's arguments
params = inspect.signature(func).parameters
fields = {
name: (param.annotation, ... if param.default == inspect.Parameter.empty else param.default)
for name, param in params.items()
}
return create_model(f"{func.__name__}Model", **fields)
def register(self, func):
name = func.__name__
self.functions[name] = func
# Generate and store schema
model = self._generate_pydantic_model(func)
schema = model.model_json_schema()
# We only need the parameters part of the schema
self.schemas[name] = {
"name": name,
"description": inspect.getdoc(func),
"parameters": schema
}
print(f"Registered tool: {name}")
def get_schemas(self):
return [
{"type": "function", "function": schema}
for schema in self.schemas.values()
]
def execute(self, name, arguments):
if name not in self.functions:
return {"status": "error", "error": f"Tool '{name}' not found."}
func = self.functions[name]
model = self._generate_pydantic_model(func)
try:
# Validate and coerce arguments using the Pydantic model
validated_args = model(**arguments).model_dump()
except ValidationError as e:
return {"status": "error", "error": f"Invalid arguments for tool '{name}': {e}"}
try:
# Execute the function with validated arguments
result = func(**validated_args)
return {"status": "success", "result": result}
except Exception as e:
return {"status": "error", "error": f"Error executing tool '{name}': {str(e)}"}
A More Ergonomic Approach: Class-based Registration
While registering individual functions is flexible, a more organized and scalable approach is to group related tools as methods within a class. We can then add a helper method to our registry to register all public methods of a given class instance.
The video "How to Build LLM Agents with Function Calling in Python" demonstrates this powerful pattern.
How to Build LLM Agents with Function Calling in Python | Step-by-Step Guide
This video refactors a simple agent to use a Tools class for managing functions.
First, watch the segment where a Tools class is introduced to encapsulate function descriptions and invocation logic: Creating a Tools Class. Next, see how this is extended to automatically generate descriptions from docstrings and type hints: Automating Description Generation. Finally, and most importantly, watch the section that implements a way to register all methods from a class instance at once: Registering a Class of Tools. This pattern is extremely convenient for organizing your toolset.
This class-based registration pattern is highly recommended for production systems as it encourages better code organization and separation of concerns.
Conclusion
In this lesson, you have designed the architecture for a production-grade tool registry, a critical component for any sophisticated agent. We've moved beyond hardcoded functions to a dynamic, scalable system for managing agent capabilities.
Here are the key takeaways:
- The Registry Pattern: A tool registry acts as a central catalog for an agent's capabilities, analogous to a service registry in distributed systems. It decouples the agent's core logic from its tools.
- Automated Schema Generation: Using Python's
inspectmodule, we can automatically generate JSON schemas from function signatures, docstrings, and type hints, eliminating manual and error-prone work. - Robust Validation with Pydantic: Pydantic provides a powerful framework for validating and coercing LLM-generated arguments before tool execution, preventing runtime errors and enhancing security.
- Organized Registration: Grouping related tools as methods within a class and registering the entire class provides a clean and scalable way to manage your agent's toolset.
You now possess the first-principles knowledge to build a flexible and reliable foundation for your agent's interactions with external systems.
In our next lesson, we will build directly upon this foundation. With a registry full of tools, the next challenge is execution. We will learn how to implement an async tool executor capable of running multiple independent tools in parallel, a key step toward building performant and responsive agents.