Variable Management and Substitution
Relevant source files
The following files were used as context for generating this wiki page:
The Variable Management and Substitution system provides a flexible mechanism for dynamically replacing placeholders in UTCP configurations, such as CallTemplate definitions. This allows for sensitive data (like API keys) and environment-specific values to be managed outside of the main configuration files, enhancing security and portability. The system supports multiple variable sources, namespacing to prevent conflicts, and recursive substitution in complex data structures.
Variables can be referenced using either ${VAR_NAME} or $VAR_NAME syntax. This system is integral to the UtcpClient's setup process, ensuring that all configurations are resolved before tools are registered and used.
Sources: core/src/utcp/implementations/default_variable_substitutor.py:8-14, README.md:100-103
Architecture
The system is designed around the VariableSubstitutor abstract interface, with DefaultVariableSubstitutor providing the concrete implementation. This implementation orchestrates the discovery and replacement of variables by querying different sources in a predefined order.
Core Components
The diagram below shows the relationship between the main interface and its default implementation.
VariableSubstitutor Interface
This abstract base class defines the contract for all variable substitution implementations. It ensures that any substitutor provides two key functionalities.
| Method | Description |
|---|---|
substitute() | Recursively substitutes variables in a given object (dict, list, or string) using values from the UtcpClientConfig. |
find_required_variables() | Recursively discovers all variable references within an object and returns them as a list of fully-qualified names. |
Sources: core/src/utcp/interfaces/variable_substitutor.py:5-32
DefaultVariableSubstitutor Implementation
This is the default implementation used by the UtcpClient. It provides a hierarchical variable resolution system and supports namespacing to avoid conflicts between different CallTemplate configurations.
Key Features:
- Hierarchical Resolution: Searches for variables in a specific order: configuration variables, custom loaders, and then environment variables.
- Namespacing: Automatically prefixes variables with the
CallTemplatename (manual name) to ensure uniqueness. - Recursive Substitution: Can substitute variables in nested dictionaries and lists.
- Variable Discovery: Includes a method to find all required variables for validation purposes before substitution.
Sources: core/src/utcp/implementations/default_variable_substitutor.py:16-35
Variable Resolution
The DefaultVariableSubstitutor resolves variables by searching through multiple sources in a specific order of precedence.
Resolution Hierarchy
The following flowchart illustrates the search order for a variable key. The first source that contains the key is used.
This diagram shows the logic within the _get_variable method.
Sources: core/src/utcp/implementations/default_variable_substitutor.py:36-53
Variable Syntax
The substitution mechanism recognizes two formats for variable placeholders in strings:
${VAR_NAME}$VAR_NAME
Both formats are found using the regular expression \${(\w+)}|\$(\w+).
Sources: core/src/utcp/implementations/default_variable_substitutor.py:89-93
Namespacing
To prevent variable name collisions between different CallTemplates, the system applies a namespace based on the name of the manual (CallTemplate). A variable like API_KEY within a CallTemplate named my_api is resolved as my__api_API_KEY.
The namespacing logic replaces each underscore _ in the manual name with a double underscore __ before appending the variable name.
# core/src/utcp/implementations/default_variable_substitutor.py:37-38
if variable_namespace:
key = variable_namespace.replace("_", "!").replace("!", "__") + "_" + key
Note: The implementation uses a replace chain that effectively turns _ into __.
The following example from a test case demonstrates this. For a CallTemplate named http_template, the variables BASE_URL and API_KEY are defined in the configuration with the http__template_ prefix.
{
"variables": {
"http__template_BASE_URL": "https://api.example.com",
"http__template_API_KEY": "secret_key"
},
"manual_call_templates": [
{
"name": "http_template",
"call_template_type": "http",
"url": "$BASE_URL/tools",
"auth": {
"auth_type": "api_key",
"api_key": "$API_KEY",
"var_name": "Authorization"
}
}
]
}
Sources: core/tests/client/test_utcp_client.py:488-510, README.md:100-103, core/src/utcp/implementations/default_variable_substitutor.py:37-38
Variable Loading
Variables can be loaded from sources other than the main configuration file via the load_variables_from list in UtcpClientConfig. This is an extensible system that can support various loaders.
load_variables_from Configuration
This configuration property in config.json or UtcpClientConfig accepts a list of variable loader configurations.
| Field | Type | Description |
|---|---|---|
variable_loader_type | string | The type of loader to use (e.g., "dotenv"). |
env_file_path | string | For the dotenv loader, the path to the .env file. |
An example configuration:
"load_variables_from": [
{
"variable_loader_type": "dotenv",
"env_file_path": ".env"
}
]
Sources: core/README.md:173-179, core/src/utcp/data/variable_loader_implementations/dot_env_variable_loader.py
Usage
The variable substitution process is mostly internal to the UtcpClient's initialization but can also be used directly for validation.
Substitution Flow
The following sequence diagram shows how the UtcpClient uses the DefaultVariableSubstitutor when loading CallTemplates from its configuration.
Discovering Required Variables
The find_required_variables method is useful for validating configurations and identifying dependencies without performing substitution. It scans a data structure and returns a list of all fully-qualified variable names it finds.
# core/src/utcp/implementations/default_variable_substitutor.py:96-146
def find_required_variables(self, obj: dict | list | str, variable_namespace: Optional[str] = None) -> List[str]:
"""REQUIRED
Recursively discover all variable references in a data structure.
...
"""
# ... implementation ...
if isinstance(obj, str):
# Find all variables in the string, supporting ${VAR} and $VAR formats
variables = []
pattern = r'\${(\w+)}|\$(\w+)'
for match in re.finditer(pattern, obj):
# The first group that is not None is the one that matched
var_name = next(g for g in match.groups() if g is not None)
if variable_namespace:
full_var_name = variable_namespace.replace("_", "!").replace("!", "__") + "_" + var_name
else:
full_var_name = var_name
variables.append(full_var_name)
return variables
# ... more implementation for dicts and lists ...
Example Usage:
substitutor = DefaultVariableSubstitutor()
config_part = {"url": "https://${HOST}/api", "key": "$API_KEY"}
required_vars = substitutor.find_required_variables(
config_part,
"web_api"
)
# required_vars will be: ["web__api_HOST", "web__api_API_KEY"]
Sources: core/src/utcp/implementations/default_variable_substitutor.py:96-146
Summary
The Variable Management and Substitution system is a cornerstone of UTCP's configuration flexibility. By abstracting away the source of configuration values and providing a robust, namespaced substitution mechanism, it allows developers to create secure, portable, and easily maintainable tool integrations. The hierarchical resolution order and support for custom loaders make it adaptable to a wide range of deployment environments and security requirements.
Sources: core/src/utcp/implementations/default_variable_substitutor.py, README.md