Error Handling
Relevant source files
The following files were used as context for generating this wiki page:- core/src/utcp/exceptions/utcp_serializer_validation_error.py
- core/src/utcp/exceptions/utcp_variable_not_found_exception.py
- core/tests/client/test_utcp_client.py
- plugins/communication_protocols/cli/README.md
- plugins/communication_protocols/http/README.md
- plugins/communication_protocols/http/tests/test_http_communication_protocol.py
The UTCP framework employs a robust, exception-based error handling strategy to manage issues arising during client configuration, tool registration, and tool execution. Errors are categorized into custom exception classes, allowing developers to implement granular error handling logic. This system distinguishes between configuration-time failures, such as invalid settings or missing variables, and runtime failures that occur during a tool call.
The core principle is to raise specific exceptions for predictable error conditions, providing clear context about what went wrong. For unexpected or protocol-specific issues, generic exceptions are wrapped to maintain a consistent error handling API for the client, while still allowing access to the underlying cause.
Custom Exception Classes
UTCP defines several custom exception classes to signal specific error conditions. These exceptions inherit from Python's base Exception class.
The diagram below illustrates the key custom exception classes within the UTCP framework.
The following table summarizes the primary custom exceptions and their triggers.
| Exception | Description | When It's Raised |
|---|---|---|
UtcpVariableNotFound | Raised when a required variable (e.g., ${API_KEY}) is referenced in a configuration but not found in the provided variables. | During UtcpClient initialization or manual registration when substituting variables in a CallTemplate. |
UtcpSerializerValidationError | Raised when a configuration object (like UtcpClientConfig) fails Pydantic validation due to incorrect structure or types. | During UtcpClient initialization from a dictionary or file with an invalid format. |
ToolCallError | A generic wrapper for errors that occur during the execution of client.call_tool(). The original exception is available via the __cause__ attribute. | When a communication protocol plugin (e.g., HTTP, CLI) encounters an error while executing a tool. |
ValueError | Raised for various invalid argument or state issues, such as calling a non-existent tool or providing a duplicate manual name. | During client.call_tool(), client.register_manual(), or when path parameters are missing. |
Sources: core/src/utcp/exceptions/utcp_variable_not_found_exception.py, core/src/utcp/exceptions/utcp_serializer_validation_error.py, plugins/communication_protocols/cli/README.md:112, core/tests/client/test_utcp_client.py:421-424, plugins/communication_protocols/http/tests/test_http_communication_protocol.py:465-475
Configuration-Time Errors
These errors occur during the instantiation of the UtcpClient via UtcpClient.create(). They typically relate to invalid configuration files, missing environment variables, or malformed data structures.
The flowchart below shows the client initialization process and where configuration errors are typically raised.
UtcpVariableNotFound
This exception is raised if a manual_call_template in the configuration references a variable (e.g., $BASE_URL) that has not been defined in the variables block or loaded from an environment file.
# Example from core/tests/client/test_utcp_client.py
config_data = {
"manual_call_templates": [{
"name": "http_template",
"call_template_type": "http",
"url": "$MISSING_VAR/tools",
"http_method": "GET"
}]
}
# ... create temp file with config_data ...
try:
with pytest.raises(UtcpVariableNotFound, match="Variable http__template_MISSING_VAR referenced in provider configuration not found"):
await UtcpClient.create(config=temp_file)
finally:
os.unlink(temp_file)
Sources: core/tests/client/test_utcp_client.py:530-543
UtcpSerializerValidationError
This occurs if the configuration dictionary or file does not conform to the UtcpClientConfig Pydantic model. For example, if manual_call_templates is an object instead of a list.
# Example from core/tests/client/test_utcp_client.py
config_data = {
"manual_call_templates": { # Should be a list, not a dict
"http_template": {
"call_template_type": "http",
"url": "https://api.example.com/tools",
"http_method": "GET"
}
}
}
# ... create temp file with config_data ...
try:
with pytest.raises(UtcpSerializerValidationError):
await UtcpClient.create(config=temp_file)
finally:
os.unlink(temp_file)
Sources: core/tests/client/test_utcp_client.py:603-621
Runtime Errors
Runtime errors occur during tool interaction, primarily when calling client.call_tool() or client.register_manual().
Tool Call Failures
When a tool call fails within a communication protocol plugin, the plugin's implementation is expected to raise an exception. The UtcpClient catches this and often wraps it in a ToolCallError to provide a consistent failure interface.
The following sequence diagram illustrates the error flow for a failed HTTP tool call.
Handling ToolCallError
It is best practice to wrap call_tool invocations in a try...except block to handle potential failures. The original exception from the protocol layer (e.g., httpx.HTTPStatusError for the HTTP plugin) is available in the __cause__ attribute of the ToolCallError.
HTTP Plugin Example:
from utcp.exceptions import ToolCallError
import httpx
try:
result = await client.call_tool("api.get_data", {"id": "123"})
except ToolCallError as e:
if isinstance(e.__cause__, httpx.HTTPStatusError):
print(f"HTTP {e.__cause__.response.status_code}: {e.__cause__.response.text}")
Sources: [plugins/communication_protocols/http/README.md:100-107]
CLI Plugin Example:
from utcp.exceptions import ToolCallError
try:
result = await client.call_tool("cli_tool.multi_command", {
"repo_url": "https://github.com/example/repo.git%22%2C
"target_dir": "analysis_temp"
})
except ToolCallError as e:
print(f"CLI tool execution failed: {e}")
# Script execution failed - check individual command outputs
Sources: [plugins/communication_protocols/cli/README.md:112-120]
Invalid Operations
Calling a non-existent tool or attempting to register a manual with a name that is already in use will raise a ValueError.
# Calling a non-existent tool
with pytest.raises(ValueError, match="Tool not found: test_manual.nonexistent"):
await client.call_tool("test_manual.nonexistent", {"param": "value"})
# Registering a manual with a duplicate name
with pytest.raises(ValueError, match="Manual duplicate_name already registered"):
await client.register_manual(template2)
Sources: [core/tests/client/test_utcp_client.py:421-424, 588-601]
A ValueError is also raised by the HTTP protocol if a required path parameter is missing from the tool arguments.
# Missing 'post_id' path parameter
with pytest.raises(ValueError, match="Missing required path parameter: post_id"):
await http_transport.call_tool(
None,
"test_tool",
{"user_id": "123"},
call_template
)
Sources: [plugins/communication_protocols/http/tests/test_http_communication_protocol.py:465-475]
Summary
Error handling in python-utcp is designed to be explicit and informative. By using custom exceptions for configuration issues and wrapping runtime errors from protocol plugins, the framework provides a clear and consistent mechanism for developers to build resilient applications. Correctly handling UtcpVariableNotFound and UtcpSerializerValidationError at startup, and ToolCallError or ValueError at runtime, is essential for robust integration with the UTCP client.