tooluniverse.execute_function module

ToolUniverse Function Execution Module

This module provides the core ToolUniverse class for managing and executing various scientific and data tools. It supports loading tools from JSON configurations, organizing them by categories, validating function calls, and executing tools with proper error handling and caching.

The module includes support for: - GraphQL tools (OpenTarget, OpenTarget Genetics) - RESTful API tools (Monarch, ChEMBL, PubChem, etc.) - FDA drug labeling and adverse event tools - Clinical trials tools - Literature search tools (EuropePMC, Semantic Scholar, PubTator) - Biological databases (HPA, Reactome, UniProt) - MCP (Model Context Protocol) clients and auto-loaders - Enrichment analysis tools - Package management tools

Classes:

ToolUniverse: Main class for tool management and execution

Constants:

default_tool_files: Default mapping of tool categories to JSON file paths tool_type_mappings: Mapping of tool type strings to their implementation classes

tooluniverse.execute_function.read_json_list(file_path)[source][source]

Reads a list of JSON objects from a file.

Parameters: file_path (str): The path to the JSON file.

Returns: list: A list of dictionaries containing the JSON objects.

tooluniverse.execute_function.evaluate_function_call(tool_definition, function_call)[source][source]
tooluniverse.execute_function.extract_function_call_json(lst, return_message=False, verbose=True, format='llama')[source][source]
tooluniverse.execute_function.auto_discover_tools(package_name=None, lazy=True)[source][source]

Automatically discover and import all tool modules. If lazy=True, only builds the mapping without importing any modules. If lazy=False, imports all tool modules immediately.

tooluniverse.execute_function.get_tool_registry()[source][source]

Get a copy of the current tool registry.

tooluniverse.execute_function.register_external_tool(tool_name, tool_class)[source][source]

Allow external registration of tool classes.

tooluniverse.execute_function.get_tool_class_lazy(tool_name)[source][source]

Get a tool class by name, using lazy loading if possible. Only imports the specific module needed, not all modules.

tooluniverse.execute_function.get_logger(name: str | None = None) Logger[source][source]

Get a logger instance

Parameters:

name (str, optional) – Logger name (usually __name__)

Returns:

Logger instance

Return type:

logging.Logger

tooluniverse.execute_function.debug(msg, *args, **kwargs)[source][source]

Log debug message

tooluniverse.execute_function.info(msg, *args, **kwargs)[source][source]

Log info message

tooluniverse.execute_function.warning(msg, *args, **kwargs)[source][source]

Log warning message

tooluniverse.execute_function.error(msg, *args, **kwargs)[source][source]

Log error message

tooluniverse.execute_function.set_log_level(level: str) None[source][source]

Set global log level

class tooluniverse.execute_function.HookManager(config: Dict[str, Any], tooluniverse)[source][source]

Bases: object

Manages and coordinates all output hooks.

The HookManager is responsible for loading hook configurations, creating hook instances, and applying hooks to tool outputs. It provides a unified interface for hook management and supports dynamic configuration updates.

Parameters:
  • config (Dict[str, Any]) – Hook manager configuration

  • tooluniverse – Reference to the ToolUniverse instance

config[source]

Hook manager configuration

Type:

Dict[str, Any]

tooluniverse[source]

ToolUniverse instance for tool execution

hooks[source]

List of loaded hook instances

Type:

List[OutputHook]

enabled[source]

Whether hook processing is enabled

Type:

bool

config_path[source]

Path to hook configuration file

Type:

str

__init__(config: Dict[str, Any], tooluniverse)[source][source]

Initialize the hook manager.

Parameters:
  • config (Dict[str, Any]) – Configuration for hook manager

  • tooluniverse – ToolUniverse instance for executing tools

apply_hooks(result: Any, tool_name: str, arguments: Dict[str, Any], context: Dict[str, Any]) Any[source][source]

Apply all applicable hooks to the tool output.

This method iterates through all loaded hooks, checks if they should be applied to the current output, and processes the output through each applicable hook in priority order.

Parameters:
  • result (Any) – The tool output to process

  • tool_name (str) – Name of the tool that produced the output

  • arguments (Dict[str, Any]) – Arguments passed to the tool

  • context (Dict[str, Any]) – Additional context information

Returns:

The processed output after applying all applicable hooks

Return type:

Any

enable_hook(hook_name: str)[source][source]

Enable a specific hook by name.

Parameters:

hook_name (str) – Name of the hook to enable

disable_hook(hook_name: str)[source][source]

Disable a specific hook by name.

Parameters:

hook_name (str) – Name of the hook to disable

toggle_hooks(enabled: bool)[source][source]

Enable or disable all hooks globally.

Parameters:

enabled (bool) – True to enable all hooks, False to disable

reload_config(config_path: str | None = None)[source][source]

Reload hook configuration from file.

Parameters:

config_path (Optional[str]) – Path to configuration file. If None, uses the current config_path

get_hook(hook_name: str) OutputHook | None[source][source]

Get a hook instance by name.

Parameters:

hook_name (str) – Name of the hook to retrieve

Returns:

Hook instance if found, None otherwise

Return type:

Optional[OutputHook]

tooluniverse.execute_function.get_default_hook_config()[source][source]

Get default hook configuration.

Returns:

Default hook configuration with basic settings

Return type:

dict

class tooluniverse.execute_function.ToolUniverse(tool_files={'ChEMBL': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/chembl_tools.json', 'EFO': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/efo_tools.json', 'Enrichr': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/enrichr_tools.json', 'EuropePMC': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/europe_pmc_tools.json', 'HumanBase': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/humanbase_tools.json', 'OpenAlex': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/openalex_tools.json', 'admetai': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/admetai_tools.json', 'adverse_event': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/adverse_event_tools.json', 'agents': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/agentic_tools.json', 'alphafold': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/alphafold_tools.json', 'clinical_trials': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/clinicaltrials_gov_tools.json', 'compose': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/compose_tools.json', 'dailymed': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/dailymed_tools.json', 'dataset': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/dataset_tools.json', 'disease_target_score': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/disease_target_score_tools.json', 'embedding': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/embedding_tools.json', 'fda_drug_adverse_event': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/fda_drug_adverse_event_tools.json', 'fda_drug_label': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/fda_drug_labeling_tools.json', 'go': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/gene_ontology_tools.json', 'gwas': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/gwas_tools.json', 'hpa': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/hpa_tools.json', 'idmap': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/idmap_tools.json', 'mcp_auto_loader_boltz': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/boltz_tools.json', 'mcp_auto_loader_expert_feedback': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/expert_feedback_tools.json', 'mcp_auto_loader_txagent': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/txagent_client_tools.json', 'mcp_auto_loader_uspto_downloader': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/uspto_downloader_tools.json', 'medlineplus': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/medlineplus_tools.json', 'monarch': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/monarch_tools.json', 'odphp': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/odphp_tools.json', 'opentarget': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/opentarget_tools.json', 'output_summarization': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/output_summarization_tools.json', 'pubchem': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/pubchem_tools.json', 'pubtator': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/pubtator_tools.json', 'rcsb_pdb': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/rcsb_pdb_tools.json', 'reactome': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/reactome_tools.json', 'semantic_scholar': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/semantic_scholar_tools.json', 'software_bioinformatics': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/packages/bioinformatics_core_tools.json', 'software_cheminformatics': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/packages/cheminformatics_tools.json', 'software_earth_sciences': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/packages/earth_sciences_tools.json', 'software_genomics': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/packages/genomics_tools.json', 'software_image_processing': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/packages/image_processing_tools.json', 'software_machine_learning': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/packages/machine_learning_tools.json', 'software_neuroscience': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/packages/neuroscience_tools.json', 'software_physics_astronomy': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/packages/physics_astronomy_tools.json', 'software_scientific_computing': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/packages/scientific_computing_tools.json', 'software_single_cell': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/packages/single_cell_tools.json', 'software_structural_biology': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/packages/structural_biology_tools.json', 'software_visualization': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/packages/visualization_tools.json', 'special_tools': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/special_tools.json', 'tool_composition': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/tool_composition_tools.json', 'tool_finder': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/finder_tools.json', 'uniprot': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/uniprot_tools.json', 'url': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/url_fetch_tools.json', 'uspto': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/uspto_tools.json', 'xml': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/xml_tools.json'}, keep_default_tools=True, log_level: str | None = None, hooks_enabled: bool = False, hook_config: dict | None = None, hook_type: str | None = None)[source][source]

Bases: object

A comprehensive tool management system for loading, organizing, and executing various scientific and data tools.

The ToolUniverse class provides a centralized interface for managing different types of tools including GraphQL tools, RESTful APIs, MCP clients, and specialized scientific tools. It handles tool loading, filtering, caching, and execution.

all_tools[source]

List of all loaded tool configurations

Type:

list

all_tool_dict[source]

Dictionary mapping tool names to their configurations

Type:

dict

tool_category_dicts[source]

Dictionary organizing tools by category

Type:

dict

tool_files[source]

Dictionary mapping category names to their JSON file paths

Type:

dict

callable_functions[source]

Cache of instantiated tool objects

Type:

dict

__init__(tool_files={'ChEMBL': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/chembl_tools.json', 'EFO': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/efo_tools.json', 'Enrichr': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/enrichr_tools.json', 'EuropePMC': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/europe_pmc_tools.json', 'HumanBase': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/humanbase_tools.json', 'OpenAlex': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/openalex_tools.json', 'admetai': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/admetai_tools.json', 'adverse_event': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/adverse_event_tools.json', 'agents': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/agentic_tools.json', 'alphafold': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/alphafold_tools.json', 'clinical_trials': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/clinicaltrials_gov_tools.json', 'compose': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/compose_tools.json', 'dailymed': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/dailymed_tools.json', 'dataset': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/dataset_tools.json', 'disease_target_score': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/disease_target_score_tools.json', 'embedding': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/embedding_tools.json', 'fda_drug_adverse_event': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/fda_drug_adverse_event_tools.json', 'fda_drug_label': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/fda_drug_labeling_tools.json', 'go': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/gene_ontology_tools.json', 'gwas': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/gwas_tools.json', 'hpa': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/hpa_tools.json', 'idmap': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/idmap_tools.json', 'mcp_auto_loader_boltz': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/boltz_tools.json', 'mcp_auto_loader_expert_feedback': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/expert_feedback_tools.json', 'mcp_auto_loader_txagent': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/txagent_client_tools.json', 'mcp_auto_loader_uspto_downloader': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/uspto_downloader_tools.json', 'medlineplus': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/medlineplus_tools.json', 'monarch': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/monarch_tools.json', 'odphp': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/odphp_tools.json', 'opentarget': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/opentarget_tools.json', 'output_summarization': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/output_summarization_tools.json', 'pubchem': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/pubchem_tools.json', 'pubtator': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/pubtator_tools.json', 'rcsb_pdb': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/rcsb_pdb_tools.json', 'reactome': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/reactome_tools.json', 'semantic_scholar': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/semantic_scholar_tools.json', 'software_bioinformatics': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/packages/bioinformatics_core_tools.json', 'software_cheminformatics': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/packages/cheminformatics_tools.json', 'software_earth_sciences': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/packages/earth_sciences_tools.json', 'software_genomics': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/packages/genomics_tools.json', 'software_image_processing': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/packages/image_processing_tools.json', 'software_machine_learning': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/packages/machine_learning_tools.json', 'software_neuroscience': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/packages/neuroscience_tools.json', 'software_physics_astronomy': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/packages/physics_astronomy_tools.json', 'software_scientific_computing': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/packages/scientific_computing_tools.json', 'software_single_cell': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/packages/single_cell_tools.json', 'software_structural_biology': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/packages/structural_biology_tools.json', 'software_visualization': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/packages/visualization_tools.json', 'special_tools': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/special_tools.json', 'tool_composition': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/tool_composition_tools.json', 'tool_finder': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/finder_tools.json', 'uniprot': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/uniprot_tools.json', 'url': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/url_fetch_tools.json', 'uspto': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/uspto_tools.json', 'xml': '/home/runner/work/bioagent/bioagent/ToolUniverse/src/tooluniverse/data/xml_tools.json'}, keep_default_tools=True, log_level: str | None = None, hooks_enabled: bool = False, hook_config: dict | None = None, hook_type: str | None = None)[source][source]

Initialize the ToolUniverse with tool file configurations.

Parameters:
  • tool_files (dict, optional) – Dictionary mapping category names to JSON file paths. Defaults to default_tool_files.

  • keep_default_tools (bool, optional) – Whether to keep default tools when custom tool_files are provided. Defaults to True.

  • log_level (str, optional) – Log level for this instance. Can be ‘DEBUG’, ‘INFO’, ‘WARNING’, ‘ERROR’, ‘CRITICAL’. If None, uses global setting.

  • hooks_enabled (bool, optional) – Whether to enable output hooks. Defaults to False.

  • hook_config (dict, optional) – Configuration for hooks. If None, uses default config.

  • hook_type (str or list, optional) – Simple hook type selection. Can be ‘SummarizationHook’, ‘FileSaveHook’, or a list of both. Defaults to ‘SummarizationHook’. If both hook_config and hook_type are provided, hook_config takes precedence.

register_custom_tool(tool_class, tool_name=None, tool_config=None)[source][source]

Register a custom tool class at runtime.

Parameters:
  • tool_class – The tool class to register

  • tool_name (str, optional) – Name to register under. Uses class name if None.

  • tool_config (dict, optional) – Tool configuration dictionary to add to all_tools

Returns:

The name the tool was registered under

Return type:

str

force_full_discovery()[source][source]

Force full tool discovery, importing all tool modules immediately.

This can be useful when you need to ensure all tools are available immediately, bypassing lazy loading.

Returns:

Updated tool registry with all discovered tools

Return type:

dict

get_lazy_loading_status()[source][source]

Get information about lazy loading status and available tools.

Returns:

Dictionary with lazy loading status and tool counts

Return type:

dict

get_tool_types()[source][source]

Get the types of tools available in the tool files.

Returns:

A list of tool type names (category keys).

Return type:

list

generate_env_template(all_missing_keys, output_file: str = '.env.template')[source][source]

Generate a template .env file with all required API keys

load_tools(tool_type=None, exclude_tools=None, exclude_categories=None, include_tools=None, tool_config_files=None, tools_file=None, include_tool_types=None, exclude_tool_types=None)[source][source]

Loads tool definitions from JSON files into the instance’s tool registry.

If tool_type is None, loads all available tool categories from self.tool_files. Otherwise, loads only the specified tool categories.

After loading, deduplicates tools by their ‘name’ field and updates the internal tool list. Also refreshes the tool name and description mapping.

Parameters:
  • tool_type (list, optional) – List of tool category names to load. If None, loads all categories.

  • exclude_tools (list, optional) – List of specific tool names to exclude from loading.

  • exclude_categories (list, optional) – List of tool categories to exclude from loading.

  • include_tools (list or str, optional) – List of specific tool names to include, or path to a text file containing tool names (one per line). If provided, only these tools will be loaded regardless of categories.

  • tool_config_files (dict, optional) – Additional tool configuration files to load. Format: {“category_name”: “/path/to/config.json”}

  • tools_file (str, optional) – Path to a text file containing tool names to include (one per line). Alternative to include_tools when providing a file path.

  • include_tool_types (list, optional) – List of tool types to include (e.g., [“OpenTarget”, “ChEMBLTool”]). If provided, only tools with these types will be loaded.

  • exclude_tool_types (list, optional) – List of tool types to exclude (e.g., [“ToolFinderEmbedding”]). Tools with these types will be excluded.

Side Effects:
  • Updates self.all_tools with loaded and deduplicated tools.

  • Updates self.tool_category_dicts with loaded tools per category.

  • Calls self.refresh_tool_name_desc() to update tool name/description mapping.

  • Prints the number of tools before and after loading.

Examples

# Load specific tools by name tu.load_tools(include_tools=[“UniProt_get_entry_by_accession”, “ChEMBL_get_molecule_by_chembl_id”])

# Load tools from a file tu.load_tools(tools_file=”/path/to/tool_names.txt”)

# Include only specific tool types tu.load_tools(include_tool_types=[“OpenTarget”, “ChEMBLTool”])

# Exclude specific tool types tu.load_tools(exclude_tool_types=[“ToolFinderEmbedding”, “Unknown”])

# Load additional config files tu.load_tools(tool_config_files={“custom_tools”: “/path/to/custom_tools.json”})

# Combine multiple options tu.load_tools(

tool_type=[“uniprot”, “ChEMBL”], exclude_tools=[“problematic_tool”], exclude_tool_types=[“Unknown”], tool_config_files={“custom”: “/path/to/custom.json”}

)

select_tools(include_names=None, exclude_names=None, include_categories=None, exclude_categories=None)[source][source]

Select tools based on tool names and/or categories (tool_files keys).

Parameters:
  • include_names (list, optional) – List of tool names to include. If None, include all.

  • exclude_names (list, optional) – List of tool names to exclude.

  • include_categories (list, optional) – List of categories (tool_files keys) to include. If None, include all.

  • exclude_categories (list, optional) – List of categories (tool_files keys) to exclude.

Returns:

List of selected tool configurations.

Return type:

list

filter_tool_lists(tool_name_list, tool_desc_list, include_names=None, exclude_names=None, include_categories=None, exclude_categories=None)[source][source]

Directly filter tool name and description lists based on names and/or categories.

This method takes existing tool name and description lists and filters them according to the specified criteria using the select_tools method for category-based filtering.

Parameters:
  • tool_name_list (list) – List of tool names to filter.

  • tool_desc_list (list) – List of tool descriptions to filter (must correspond to tool_name_list).

  • include_names (list, optional) – List of tool names to include.

  • exclude_names (list, optional) – List of tool names to exclude.

  • include_categories (list, optional) – List of categories to include.

  • exclude_categories (list, optional) – List of categories to exclude.

Returns:

A tuple containing (filtered_tool_name_list, filtered_tool_desc_list).

Return type:

tuple

return_all_loaded_tools()[source][source]

Return a deep copy of all loaded tools.

Returns:

A deep copy of the all_tools list to prevent external modification.

Return type:

list

list_built_in_tools(mode='config', scan_all=False)[source][source]

List all built-in tool categories and their statistics with different modes.

This method provides a comprehensive overview of all available tools in the ToolUniverse, organized by categories. It reads directly from the default tool files to gather statistics, so it works even before calling load_tools().

Parameters:
  • mode (str, optional) – Organization mode for tools. Defaults to ‘config’. - ‘config’: Organize by config file categories (original behavior) - ‘type’: Organize by tool types (implementation classes) - ‘list_name’: Return a list of all tool names - ‘list_spec’: Return a list of all tool specifications

  • scan_all (bool, optional) – Whether to scan all JSON files in data directory recursively. If True, scans all JSON files in data/ and its subdirectories. If False (default), uses predefined tool file mappings.

Returns:

  • For ‘config’ and ‘type’ modes: A dictionary containing tool statistics

  • For ‘list_name’ mode: A list of all tool names

  • For ‘list_spec’ mode: A list of all tool specifications

Return type:

dict or list

Example

>>> tool_universe = ToolUniverse()
>>> # Group by config file categories (predefined files only)
>>> stats = tool_universe.list_built_in_tools(mode='config')
>>> # Scan all JSON files in data directory recursively
>>> stats = tool_universe.list_built_in_tools(mode='config', scan_all=True)
>>> # Get all tool names from all JSON files
>>> tool_names = tool_universe.list_built_in_tools(mode='list_name', scan_all=True)

Note

  • This method reads directly from tool files and works without calling load_tools()

  • Tools are deduplicated across categories, so the same tool won’t be counted multiple times

  • The summary is automatically printed to console when this method is called (except for list_name and list_spec modes)

  • When scan_all=True, all JSON files in data/ and subdirectories are scanned

refresh_tool_name_desc(enable_full_desc=False, include_names=None, exclude_names=None, include_categories=None, exclude_categories=None)[source][source]

Refresh the tool name and description mappings with optional filtering.

This method rebuilds the internal tool dictionary and generates filtered lists of tool names and descriptions based on the provided filter criteria.

Parameters:
  • enable_full_desc (bool, optional) – If True, includes full tool JSON as description. If False, uses “name: description” format. Defaults to False.

  • include_names (list, optional) – List of tool names to include.

  • exclude_names (list, optional) – List of tool names to exclude.

  • include_categories (list, optional) – List of categories to include.

  • exclude_categories (list, optional) – List of categories to exclude.

Returns:

A tuple containing (tool_name_list, tool_desc_list) after filtering.

Return type:

tuple

prepare_one_tool_prompt(tool)[source][source]

Prepare a single tool configuration for prompt usage by filtering to essential keys.

Parameters:

tool (dict) – Tool configuration dictionary.

Returns:

Tool configuration with only essential keys for prompting.

Return type:

dict

prepare_tool_prompts(tool_list)[source][source]

Prepare a list of tool configurations for prompt usage.

Parameters:

tool_list (list) – List of tool configuration dictionaries.

Returns:

List of tool configurations with only essential keys for prompting.

Return type:

list

remove_keys(tool_list, invalid_keys)[source][source]

Remove specified keys from a list of tool configurations.

Parameters:
  • tool_list (list) – List of tool configuration dictionaries.

  • invalid_keys (list) – List of keys to remove from each tool configuration.

Returns:

Deep copy of tool list with specified keys removed.

Return type:

list

prepare_tool_examples(tool_list)[source][source]

Prepare tool configurations for example usage by keeping extended set of keys.

This method is similar to prepare_tool_prompts but includes additional keys useful for examples and documentation.

Parameters:

tool_list (list) – List of tool configuration dictionaries.

Returns:

Deep copy of tool list with only example-relevant keys.

Return type:

list

get_tool_specification_by_names(tool_names, format='default')[source][source]

Retrieve tool specifications by their names using tool_specification method.

Parameters:
  • tool_names (list) – List of tool names to retrieve.

  • format (str, optional) – Output format. Options: ‘default’, ‘openai’. If ‘openai’, returns OpenAI function calling format. Defaults to ‘default’.

Returns:

List of tool specifications for the specified names.

Tools not found will be reported but not included in the result.

Return type:

list

get_tool_by_name(tool_names, format='default')[source][source]

Retrieve tool configurations by their names.

Parameters:
  • tool_names (list) – List of tool names to retrieve.

  • format (str, optional) – Output format. Options: ‘default’, ‘openai’. If ‘openai’, returns OpenAI function calling format. Defaults to ‘default’.

Returns:

List of tool configurations for the specified names.

Tools not found will be reported but not included in the result.

Return type:

list

get_one_tool_by_one_name(tool_name, return_prompt=True)[source][source]

Retrieve a single tool specification by name, optionally prepared for prompting.

This is a convenience method that calls get_one_tool_by_one_name.

Parameters:
  • tool_name (str) – Name of the tool to retrieve.

  • return_prompt (bool, optional) – If True, returns tool prepared for prompting. If False, returns full tool configuration. Defaults to True.

Returns:

Tool configuration if found, None otherwise.

Return type:

dict or None

tool_specification(tool_name, return_prompt=False, format='default')[source][source]

Retrieve a single tool configuration by name.

Parameters:
  • tool_name (str) – Name of the tool to retrieve.

  • return_prompt (bool, optional) – If True, returns tool prepared for prompting. If False, returns full tool configuration. Defaults to False.

  • format (str, optional) – Output format. Options: ‘default’, ‘openai’. If ‘openai’, returns OpenAI function calling format. Defaults to ‘default’.

Returns:

Tool configuration if found, None otherwise.

Return type:

dict or None

get_tool_description(tool_name)[source][source]

Get the description of a tool by its name.

This is a convenience method that calls get_one_tool_by_one_name.

Parameters:

tool_name (str) – Name of the tool.

Returns:

Tool configuration if found, None otherwise.

Return type:

dict or None

get_tool_type_by_name(tool_name)[source][source]

Get the type of a tool by its name.

Parameters:

tool_name (str) – Name of the tool.

Returns:

The type of the tool.

Return type:

str

Raises:

KeyError – If the tool name is not found in loaded tools.

tool_to_str(tool_list)[source][source]

Convert a list of tool configurations to a formatted string.

Parameters:

tool_list (list) – List of tool configuration dictionaries.

Returns:

JSON-formatted string representation of the tools, with each tool

separated by double newlines.

Return type:

str

extract_function_call_json(lst, return_message=False, verbose=True, format='llama')[source][source]

Extract function call JSON from input data.

This method delegates to the utility function extract_function_call_json.

Parameters:
  • lst – Input data containing function call information.

  • return_message (bool, optional) – Whether to return message along with JSON. Defaults to False.

  • verbose (bool, optional) – Whether to enable verbose output. Defaults to True.

  • format (str, optional) – Format type for extraction. Defaults to ‘llama’.

Returns:

Function call JSON, optionally with message if return_message is True.

Return type:

dict or tuple

call_id_gen()[source][source]

Generate a random call ID for function calls.

Returns:

A random 9-character string composed of letters and digits.

Return type:

str

run(fcall_str, return_message=False, verbose=True, format='llama')[source][source]

Execute function calls from input string or data.

This method parses function call data, validates it, and executes the corresponding tools. It supports both single function calls and multiple function calls in a list.

Parameters:
  • fcall_str – Input string or data containing function call information.

  • return_message (bool, optional) – Whether to return formatted messages. Defaults to False.

  • verbose (bool, optional) – Whether to enable verbose output. Defaults to True.

  • format (str, optional) – Format type for parsing. Defaults to ‘llama’.

Returns:

  • For multiple function calls: List of formatted messages with tool responses

  • For single function call: Direct result from the tool

  • None: If the input is not a valid function call

Return type:

list or str or None

run_one_function(function_call_json)[source][source]

Execute a single function call.

This method validates the function call, initializes the tool if necessary, and executes it with the provided arguments. If hooks are enabled, it also applies output hooks to process the result.

Parameters:

function_call_json (dict) – Dictionary containing function name and arguments.

Returns:

Result from the tool execution, or error message if validation fails.

Return type:

str or dict

toggle_hooks(enabled: bool)[source][source]

Enable or disable output hooks globally.

This method allows runtime control of the hook system. When enabled, it initializes the HookManager if not already present. When disabled, it deactivates the HookManager.

Parameters:

enabled (bool) – True to enable hooks, False to disable

init_tool(tool=None, tool_name=None, add_to_cache=True)[source][source]

Initialize a tool instance from configuration or name.

This method creates a new tool instance using the tool type mappings and optionally caches it for future use. It handles special cases like the OpentargetToolDrugNameMatch which requires additional dependencies.

Parameters:
  • tool (dict, optional) – Tool configuration dictionary. Either this or tool_name must be provided.

  • tool_name (str, optional) – Name of the tool type to initialize. Either this or tool must be provided.

  • add_to_cache (bool, optional) – Whether to cache the initialized tool. Defaults to True.

Returns:

Initialized tool instance.

Return type:

object

Raises:

KeyError – If the tool type is not found in tool_type_mappings.

check_function_call(fcall_str, function_config=None, format='llama')[source][source]

Validate a function call against tool configuration.

This method checks if a function call is valid by verifying the function name exists and the arguments match the expected parameters.

Parameters:
  • fcall_str – Function call string or data to validate.

  • function_config (dict, optional) – Specific function configuration to validate against. If None, uses the loaded tool configuration.

  • format (str, optional) – Format type for parsing. Defaults to ‘llama’.

Returns:

A tuple of (is_valid, message) where:
  • is_valid (bool): True if the function call is valid, False otherwise

  • message (str): Error message if invalid, empty if valid

Return type:

tuple

export_tool_names(output_file, category_filter=None)[source][source]

Export tool names to a text file (one per line).

Parameters:
  • output_file (str) – Path to the output file

  • category_filter (list, optional) – List of categories to filter by

discover_mcp_tools(server_urls: List[str] | None = None, **kwargs) Dict[str, Any][source]

Discover available tools from MCP servers without loading them.

This method connects to MCP servers to discover what tools are available without actually registering them in ToolUniverse. Useful for exploration and selective tool loading.

Parameters:

server_urlslist of str, optional

List of MCP server URLs to discover from

**kwargs

Additional options: - timeout (int): Connection timeout (default: 30) - include_schemas (bool): Include tool parameter schemas (default: True)

Returns:

dict

Discovery results with tools organized by server

Examples:

tu = ToolUniverse()

# Discover what's available
discovery = tu.discover_mcp_tools([
    "http://localhost:8001",
    "http://ml-server:8002"
])

# Show available tools
for server, info in discovery["servers"].items():
    print(f"\n{server}:")
    for tool in info.get("tools", []):
        print(f"  - {tool['name']}: {tool['description']}")
get_available_tools(category_filter=None, name_only=True)[source][source]

Get available tools, optionally filtered by category.

Parameters:
  • category_filter (list, optional) – List of categories to filter by

  • name_only (bool) – If True, return only tool names; if False, return full configs

Returns:

List of tool names or tool configurations

Return type:

list

list_mcp_connections() Dict[str, Any][source]

List all active MCP connections and loaded tools.

Returns:

dict

Information about MCP connections, auto-loaders, and loaded tools

Examples:

tu = ToolUniverse()
tu.load_mcp_tools(["http://localhost:8001"])

connections = tu.list_mcp_connections()
print(f"Active MCP connections: {len(connections['connections'])}")
load_mcp_tools(server_urls: List[str] | None = None, **kwargs)[source]

Load MCP tools from remote servers into this ToolUniverse instance.

This method automatically discovers tools from MCP servers and registers them as ToolUniverse tools, enabling seamless usage of remote capabilities.

Parameters:

server_urlslist of str, optional

List of MCP server URLs to load tools from. Examples:

If None, attempts to discover from local MCP tool registry.

**kwargs

Additional configuration options:

  • tool_prefix (str): Prefix for loaded tool names (default: “mcp_”)

  • timeout (int): Connection timeout in seconds (default: 30)

  • auto_register (bool): Whether to auto-register discovered tools (default: True)

  • selected_tools (list): Specific tools to load from each server

  • categories (list): Tool categories to filter by

Returns:

dict

Summary of loaded tools with counts and any errors encountered.

Examples:

Load from specific servers: .. code-block:: python

tu = ToolUniverse()

# Load tools from multiple MCP servers result = tu.load_mcp_tools([

http://localhost:8001”, # Local analysis server “http://ml-server:8002”, # Remote ML server “ws://realtime:9000” # WebSocket server

])

print(f”Loaded {result[‘total_tools’]} tools from {result[‘servers_connected’]} servers”)

Load with custom configuration: .. code-block:: python

tu.load_mcp_tools(

server_urls=[”http://localhost:8001”], tool_prefix=”analysis_”, timeout=60, selected_tools=[“protein_analysis”, “drug_interaction”]

)

Auto-discovery from local registry: .. code-block:: python

# If you have registered MCP tools locally, auto-discover their servers tu.load_mcp_tools() # Uses servers from mcp_tool_registry

find_tools_by_pattern(pattern, search_in='name', case_sensitive=False)[source][source]

Find tools matching a pattern in their name or description.

Parameters:
  • pattern (str) – Pattern to search for

  • search_in (str) – Where to search - ‘name’, ‘description’, or ‘both’

  • case_sensitive (bool) – Whether search should be case sensitive

Returns:

List of matching tool configurations

Return type:

list

load_tools_from_names_list(tool_names, clear_existing=True)[source][source]

Load only specific tools by their names.

Parameters:
  • tool_names (list) – List of tool names to load

  • clear_existing (bool) – Whether to clear existing tools first

Returns:

Number of tools successfully loaded

Return type:

int