tooluniverse package

class tooluniverse.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

class tooluniverse.BaseTool(tool_config)[source][source]

Bases: object

__init__(tool_config)[source][source]
classmethod get_default_config_file()[source][source]

Get the path to the default configuration file for this tool type.

This method uses a robust path resolution strategy that works across different installation scenarios:

  1. Installed packages: Uses importlib.resources for proper package resource access

  2. Development mode: Falls back to file-based path resolution

  3. Legacy Python: Handles importlib.resources and importlib_resources

Override this method in subclasses to specify a custom defaults file.

Returns:

Path or resource object pointing to the defaults file

classmethod load_defaults_from_file()[source][source]

Load defaults from the configuration file

run(arguments=None)[source][source]

Execute the tool.

The default BaseTool implementation accepts an optional arguments mapping to align with most concrete tool implementations which expect a dictionary of inputs.

check_function_call(function_call_json)[source][source]
get_required_parameters()[source][source]

Retrieve required parameters from the endpoint definition. Returns: list: List of required parameters for the given endpoint.

tooluniverse.register_tool(tool_type_name=None, config=None)[source][source]

Decorator to automatically register tool classes and their configs.

Usage:

@register_tool(‘CustomToolName’, config={…}) class MyTool:

pass

tooluniverse.get_tool_registry()[source][source]

Get a copy of the current tool registry.

class tooluniverse.MonarchTool(tool_config)[source][source]

Bases: RESTfulTool

__init__(tool_config)[source][source]
run(arguments)[source][source]

Execute the tool.

The default BaseTool implementation accepts an optional arguments mapping to align with most concrete tool implementations which expect a dictionary of inputs.

class tooluniverse.MonarchDiseasesForMultiplePhenoTool(tool_config)[source][source]

Bases: MonarchTool

__init__(tool_config)[source][source]
run(arguments)[source][source]

Execute the tool.

The default BaseTool implementation accepts an optional arguments mapping to align with most concrete tool implementations which expect a dictionary of inputs.

class tooluniverse.ClinicalTrialsSearchTool(tool_config)[source][source]

Bases: ClinicalTrialsTool

__init__(tool_config)[source][source]
run(arguments)[source][source]

Executes the search query for clinical trials.

Parameters:

arguments (dict) – A dictionary containing parameters provided by the user/LLM

Returns:

The JSON response from the API as a dictionary,

or raw text for non-JSON responses, or an error dictionary.

Return type:

dict or str

class tooluniverse.ClinicalTrialsDetailsTool(tool_config)[source][source]

Bases: ClinicalTrialsTool

__init__(tool_config)[source][source]
run(arguments)[source][source]

Execute the tool.

The default BaseTool implementation accepts an optional arguments mapping to align with most concrete tool implementations which expect a dictionary of inputs.

class tooluniverse.OpentargetTool(tool_config)[source][source]

Bases: GraphQLTool

__init__(tool_config)[source][source]
run(arguments)[source][source]

Execute the tool.

The default BaseTool implementation accepts an optional arguments mapping to align with most concrete tool implementations which expect a dictionary of inputs.

class tooluniverse.OpentargetGeneticsTool(tool_config)[source][source]

Bases: GraphQLTool

__init__(tool_config)[source][source]
class tooluniverse.OpentargetToolDrugNameMatch(tool_config, drug_generic_tool=None)[source][source]

Bases: GraphQLTool

__init__(tool_config, drug_generic_tool=None)[source][source]
run(arguments)[source][source]

Execute the tool.

The default BaseTool implementation accepts an optional arguments mapping to align with most concrete tool implementations which expect a dictionary of inputs.

class tooluniverse.DiseaseTargetScoreTool(tool_config, datasource_id=None)[source][source]

Bases: GraphQLTool

Tool to extract disease-target association scores from specific data sources

__init__(tool_config, datasource_id=None)[source][source]
run(arguments)[source][source]

Extract disease-target scores for a specific datasource Arguments should contain: efoId, datasourceId (optional), pageSize (optional)

class tooluniverse.FDADrugLabelTool(tool_config, api_key=None)[source][source]

Bases: FDATool

__init__(tool_config, api_key=None)[source][source]
class tooluniverse.FDADrugLabelSearchTool(tool_config=None, api_key=None)[source][source]

Bases: FDATool

__init__(tool_config=None, api_key=None)[source][source]
run(arguments)[source][source]

Execute the tool.

The default BaseTool implementation accepts an optional arguments mapping to align with most concrete tool implementations which expect a dictionary of inputs.

class tooluniverse.FDADrugLabelSearchIDTool(tool_config=None, api_key=None)[source][source]

Bases: FDATool

__init__(tool_config=None, api_key=None)[source][source]
run(arguments)[source][source]

Execute the tool.

The default BaseTool implementation accepts an optional arguments mapping to align with most concrete tool implementations which expect a dictionary of inputs.

class tooluniverse.FDADrugLabelGetDrugGenericNameTool(tool_config=None, api_key=None)[source][source]

Bases: FDADrugLabelTool

__init__(tool_config=None, api_key=None)[source][source]
run(arguments)[source][source]

Execute the tool.

The default BaseTool implementation accepts an optional arguments mapping to align with most concrete tool implementations which expect a dictionary of inputs.

class tooluniverse.FDADrugAdverseEventTool(tool_config, endpoint_url='https://api.fda.gov/drug/event.json', api_key=None)[source][source]

Bases: BaseTool

__init__(tool_config, endpoint_url='https://api.fda.gov/drug/event.json', api_key=None)[source][source]
run(arguments)[source][source]

Execute the tool.

The default BaseTool implementation accepts an optional arguments mapping to align with most concrete tool implementations which expect a dictionary of inputs.

validate_enum_arguments(arguments)[source][source]

Validate that enum-based arguments match the allowed values

class tooluniverse.FDACountAdditiveReactionsTool(tool_config, endpoint_url='https://api.fda.gov/drug/event.json', api_key=None)[source][source]

Bases: FDADrugAdverseEventTool

Leverage openFDA API to count adverse reaction events across multiple drugs in one request.

__init__(tool_config, endpoint_url='https://api.fda.gov/drug/event.json', api_key=None)[source][source]
run(arguments)[source][source]

Execute the tool.

The default BaseTool implementation accepts an optional arguments mapping to align with most concrete tool implementations which expect a dictionary of inputs.

class tooluniverse.ChEMBLTool(tool_config, base_url='https://www.ebi.ac.uk/chembl/api/data')[source][source]

Bases: BaseTool

Tool to search for molecules similar to a given compound name or SMILES using the ChEMBL Web Services API.

__init__(tool_config, base_url='https://www.ebi.ac.uk/chembl/api/data')[source][source]
run(arguments)[source][source]

Execute the tool.

The default BaseTool implementation accepts an optional arguments mapping to align with most concrete tool implementations which expect a dictionary of inputs.

get_chembl_id_by_name(compound_name)[source][source]

Search ChEMBL for a compound by name and return the ChEMBL ID of the first match.

get_smiles_pref_name_by_chembl_id(query)[source][source]

Given a ChEMBL ID, return a dict with canonical SMILES and preferred name.

get_chembl_smiles_pref_name_id_by_name(compound_name)[source][source]

Search ChEMBL for a compound by name and return a list of dicts with ChEMBL ID, canonical SMILES, and preferred name for the top 5 matches.

class tooluniverse.ComposeTool(tool_config, tooluniverse=None)[source][source]

Bases: BaseTool

A flexible tool that can compose other tools using custom code logic. Supports both inline composition_code and external Python files. Features intelligent dependency management with automatic tool loading.

__init__(tool_config, tooluniverse=None)[source][source]
run(arguments)[source][source]

Execute the composed tool with custom code logic.

Parameters:

arguments (dict) – Input arguments for the composition

Returns:

Result from the composition execution

Return type:

Any

class tooluniverse.EuropePMCTool(tool_config, base_url='https://www.ebi.ac.uk/europepmc/webservices/rest/search')[source][source]

Bases: BaseTool

Tool to search for articles on Europe PMC including abstracts.

__init__(tool_config, base_url='https://www.ebi.ac.uk/europepmc/webservices/rest/search')[source][source]
run(arguments)[source][source]

Execute the tool.

The default BaseTool implementation accepts an optional arguments mapping to align with most concrete tool implementations which expect a dictionary of inputs.

class tooluniverse.SemanticScholarTool(tool_config, base_url='https://api.semanticscholar.org/graph/v1/paper/search')[source][source]

Bases: BaseTool

Tool to search for papers on Semantic Scholar including abstracts.

__init__(tool_config, base_url='https://api.semanticscholar.org/graph/v1/paper/search')[source][source]
run(arguments)[source][source]

Execute the tool.

The default BaseTool implementation accepts an optional arguments mapping to align with most concrete tool implementations which expect a dictionary of inputs.

class tooluniverse.PubTatorTool(tool_config: Dict[str, Any])[source][source]

Bases: BaseTool

Generic wrapper around a single PubTator 3 endpoint supporting JSON-defined configs.

__init__(tool_config: Dict[str, Any])[source][source]
run(arguments: Dict[str, Any])[source][source]

Execute the tool.

The default BaseTool implementation accepts an optional arguments mapping to align with most concrete tool implementations which expect a dictionary of inputs.

class tooluniverse.EFOTool(tool_config, base_url='https://www.ebi.ac.uk/ols4/api/search')[source][source]

Bases: BaseTool

Tool to lookup Experimental Factor Ontology (EFO) IDs for diseases via the EMBL-EBI OLS API.

__init__(tool_config, base_url='https://www.ebi.ac.uk/ols4/api/search')[source][source]
run(arguments)[source][source]

Execute the tool.

The default BaseTool implementation accepts an optional arguments mapping to align with most concrete tool implementations which expect a dictionary of inputs.

class tooluniverse.AgenticTool(tool_config: Dict[str, Any])[source][source]

Bases: BaseTool

Generic wrapper around LLM prompting supporting JSON-defined configs with prompts and input arguments.

static has_any_api_keys() bool[source][source]

Check if any API keys are available across all supported API types.

Returns:

True if at least one API type has all required keys, False otherwise

Return type:

bool

__init__(tool_config: Dict[str, Any])[source][source]
run(arguments: Dict[str, Any]) Dict[str, Any][source][source]

Execute the tool.

The default BaseTool implementation accepts an optional arguments mapping to align with most concrete tool implementations which expect a dictionary of inputs.

get_prompt_preview(arguments: Dict[str, Any]) str[source][source]
get_model_info() Dict[str, Any][source][source]
is_available() bool[source][source]

Check if the tool is available for use.

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

Get detailed availability status of the tool.

retry_initialization() bool[source][source]

Attempt to reinitialize the tool (useful if API keys were updated).

get_prompt_template() str[source][source]
get_input_arguments() List[str][source][source]
validate_configuration() Dict[str, Any][source][source]
estimate_token_usage(arguments: Dict[str, Any]) Dict[str, int][source][source]
class tooluniverse.DatasetTool(tool_config)[source][source]

Bases: BaseTool

Tool to search and filter the DrugBank vocabulary dataset. Provides functionality to search drugs by name, ID, synonyms and filter by various criteria.

__init__(tool_config)[source][source]
run(arguments)[source][source]

Main entry point for the tool.

get_dataset_info()[source][source]

Get information about the loaded dataset.

class tooluniverse.SearchSPLTool(tool_config)[source][source]

Bases: BaseTool

Search SPL list based on multiple filter conditions (drug_name/ndc/rxcui/setid/published_date). Returns original DailyMed API JSON (including metadata + data array).

__init__(tool_config)[source][source]
run(arguments)[source][source]

Execute the tool.

The default BaseTool implementation accepts an optional arguments mapping to align with most concrete tool implementations which expect a dictionary of inputs.

class tooluniverse.GetSPLBySetIDTool(tool_config)[source][source]

Bases: BaseTool

Get complete SPL label based on SPL Set ID, returns content in XML or JSON format.

__init__(tool_config)[source][source]
run(arguments)[source][source]

Execute the tool.

The default BaseTool implementation accepts an optional arguments mapping to align with most concrete tool implementations which expect a dictionary of inputs.

class tooluniverse.HPAGetGeneJSONTool(tool_config)[source][source]

Bases: HPAJsonApiTool

Enhanced legacy tool - Get basic gene information using Ensembl Gene ID. Now uses the efficient JSON API instead of search API.

run(arguments: Dict[str, Any]) Dict[str, Any][source][source]

Execute the tool.

The default BaseTool implementation accepts an optional arguments mapping to align with most concrete tool implementations which expect a dictionary of inputs.

class tooluniverse.HPAGetGeneXMLTool(tool_config)[source][source]

Bases: HPASearchApiTool

Legacy tool - Get gene TSV format data (alternative to XML).

run(arguments: Dict[str, Any]) Dict[str, Any][source][source]

Execute the tool.

The default BaseTool implementation accepts an optional arguments mapping to align with most concrete tool implementations which expect a dictionary of inputs.

class tooluniverse.ReactomeRESTTool(tool_config)[source][source]

Bases: BaseTool

Generic Reactome Content Service REST tool. If there is no “fields.extract_path” in config or its value is empty, returns complete JSON; Otherwise, drills down according to the “dot-separated path” in extract_path and returns corresponding sub-node.

__init__(tool_config)[source][source]
run(arguments: dict)[source][source]

Execute the tool.

The default BaseTool implementation accepts an optional arguments mapping to align with most concrete tool implementations which expect a dictionary of inputs.

class tooluniverse.PubChemRESTTool(tool_config)[source][source]

Bases: BaseTool

Generic PubChem PUG-REST tool class. Directly concatenates URL from the fields.endpoint template and sends requests to PubChem PUG-REST.

__init__(tool_config)[source][source]
run(arguments: dict)[source][source]

Execute the tool.

The default BaseTool implementation accepts an optional arguments mapping to align with most concrete tool implementations which expect a dictionary of inputs.

class tooluniverse.MedlinePlusRESTTool(tool_config)[source][source]

Bases: BaseTool

MedlinePlus REST API tool class. Supports health topic search, code lookup, genetics information retrieval, etc.

__init__(tool_config)[source][source]
run(arguments: dict)[source][source]

Execute tool call

search_topics_by_keyword(term: str, db: str, rettype: str = 'brief') Dict[str, Any][source][source]
connect_lookup_by_code(cs: str, c: str, dn: str | None = None, language: str = 'en', format: str = 'json') Any[source][source]
get_genetics_condition_by_name(condition: str, format: str = 'json') Any[source][source]
get_genetics_gene_by_name(gene: str, format: str = 'json') Any[source][source]
get_genetics_index() Any[source][source]
class tooluniverse.UniProtRESTTool(tool_config: Dict)[source][source]

Bases: BaseTool

__init__(tool_config: Dict)[source][source]
run(arguments: Dict[str, Any]) Any[source][source]

Execute the tool.

The default BaseTool implementation accepts an optional arguments mapping to align with most concrete tool implementations which expect a dictionary of inputs.

get_entry_by_accession(accession: str) Any[source][source]
get_function_by_accession(accession: str) Any[source][source]
get_names_taxonomy_by_accession(accession: str) Any[source][source]
get_subcellular_location_by_accession(accession: str) Any[source][source]
get_disease_variants_by_accession(accession: str) Any[source][source]
get_ptm_processing_by_accession(accession: str) Any[source][source]
get_sequence_isoforms_by_accession(accession: str) Any[source][source]
class tooluniverse.PackageTool(tool_config)[source][source]

Bases: BaseTool

Universal tool to provide information about Python packages. Fetches real-time data from PyPI API with local fallback.

__init__(tool_config)[source][source]
run(arguments)[source][source]

Get comprehensive package information.

Parameters:

arguments (dict) – Optional parameters for customization

Returns:

Package information including name, description, installation, docs, usage

Return type:

dict

class tooluniverse.SMCP(name: str | None = None, tooluniverse_config: ToolUniverse | Dict[str, Any] | None = None, tool_categories: List[str] | None = None, exclude_tools: List[str] | None = None, exclude_categories: List[str] | None = None, include_tools: List[str] | None = None, tools_file: str | None = None, tool_config_files: Dict[str, str] | None = None, include_tool_types: List[str] | None = None, exclude_tool_types: List[str] | None = None, auto_expose_tools: bool = True, search_enabled: bool = True, max_workers: int = 5, hooks_enabled: bool = False, hook_config: Dict[str, Any] | None = None, hook_type: str | None = None, **kwargs)[source][source]

Bases: FastMCP

Scientific Model Context Protocol (SMCP) Server

SMCP is an enhanced MCP (Model Context Protocol) server that seamlessly integrates ToolUniverse’s extensive collection of scientific and scientific tools with the FastMCP framework. It provides a unified, AI-accessible interface for scientific computing, data analysis, and research workflows.

The SMCP server extends standard MCP capabilities with scientific domain expertise, intelligent tool discovery, and optimized configurations for research applications. It automatically handles the complex task of exposing hundreds of specialized tools through a consistent, well-documented interface.

Key Features:

🔬 Scientific Tool Integration: Native access to 350+ specialized tools covering

scientific databases, literature search, clinical data, genomics, proteomics, chemical informatics, and AI-powered analysis capabilities.

🧠 AI-Powered Tool Discovery: Multi-tiered intelligent search system using:
  • ToolFinderLLM: Cost-optimized LLM-based semantic understanding with pre-filtering

  • Tool_RAG: Embedding-based similarity search

  • Keyword Search: Simple text matching as reliable fallback

📡 **Full MCP Protocol Support**: Complete implementation of MCP specification with:
  • Standard methods (tools/list, tools/call, resources/, prompts/)

  • Custom scientific methods (tools/find, tools/search)

  • Multi-transport support (stdio, HTTP, SSE)

  • JSON-RPC 2.0 compliance with proper error handling

High-Performance Architecture: Production-ready features including:
  • Configurable thread pools for concurrent tool execution

  • Intelligent tool loading and caching

  • Resource management and graceful degradation

  • Comprehensive error handling and recovery

🔧 Developer-Friendly: Simplified configuration and deployment with:
  • Sensible defaults for scientific computing

  • Flexible customization options

  • Comprehensive documentation and examples

  • Built-in diagnostic and monitoring tools

Custom MCP Methods:

tools/find:

AI-powered tool discovery using natural language queries. Supports semantic search, category filtering, and flexible response formats.

tools/search:

Alternative endpoint for tool discovery with identical functionality to tools/find, provided for compatibility and convenience.

Parameters:

namestr, optional

Human-readable server name used in logs and identification. Default: “SMCP Server” Examples: “Scientific Research API”, “Drug Discovery Server”

tooluniverse_configToolUniverse or dict, optional

Either a pre-configured ToolUniverse instance or configuration dict. If None, creates a new ToolUniverse with default settings. Allows reuse of existing tool configurations and customizations.

tool_categorieslist of str, optional

Specific ToolUniverse categories to load. If None and auto_expose_tools=True, loads all available tools. Common combinations: - Scientific: [“ChEMBL”, “uniprot”, “opentarget”, “pubchem”, “hpa”] - Literature: [“EuropePMC”, “semantic_scholar”, “pubtator”, “agents”] - Clinical: [“fda_drug_label”, “clinical_trials”, “adverse_events”]

exclude_toolslist of str, optional

Specific tool names to exclude from loading. These tools will not be exposed via the MCP interface even if they are in the loaded categories. Useful for removing specific problematic or unwanted tools.

exclude_categorieslist of str, optional

Tool categories to exclude from loading. These entire categories will be skipped during tool loading. Can be combined with tool_categories to first select categories and then exclude specific ones.

include_toolslist of str, optional

Specific tool names to include. If provided, only these tools will be loaded regardless of categories. Overrides category-based selection.

tools_filestr, optional

Path to a text file containing tool names to include (one per line). Alternative to include_tools parameter. Comments (lines starting with #) and empty lines are ignored.

tool_config_filesdict of str, optional

Additional tool configuration files to load. Format: {“category_name”: “/path/to/config.json”}. These files will be loaded in addition to the default tool files.

include_tool_typeslist of str, optional

Specific tool types to include. If provided, only tools of these types will be loaded. Available types include: ‘OpenTarget’, ‘ToolFinderEmbedding’, ‘ToolFinderKeyword’, ‘ToolFinderLLM’, etc.

exclude_tool_typeslist of str, optional

Tool types to exclude from loading. These tool types will be skipped during tool loading. Useful for excluding entire categories of tools (e.g., all ToolFinder types or all OpenTarget tools).

auto_expose_toolsbool, default True

Whether to automatically expose ToolUniverse tools as MCP tools. When True, all loaded tools become available via the MCP interface with automatic schema conversion and execution wrapping.

search_enabledbool, default True

Enable AI-powered tool search functionality via tools/find method. Includes ToolFinderLLM (cost-optimized LLM-based), Tool_RAG (embedding-based), and simple keyword search capabilities with intelligent fallback.

max_workersint, default 5

Maximum number of concurrent worker threads for tool execution. Higher values allow more parallel tool calls but use more resources. Recommended: 5-20 depending on server capacity and expected load.

hooks_enabledbool, default False

Whether to enable output processing hooks for intelligent post-processing of tool outputs. When True, hooks can automatically summarize long outputs, save results to files, or apply other transformations.

hook_configdict, optional

Custom hook configuration dictionary. If provided, overrides default hook settings. Should contain ‘hooks’ list with hook definitions. Example: {“hooks”: [{“name”: “summarization_hook”, “type”: “SummarizationHook”, …}]}

hook_typestr, optional

Simple hook type selection. Can be ‘SummarizationHook’, ‘FileSaveHook’, or a list of both. Provides an easy way to enable hooks without full configuration. Takes precedence over hooks_enabled when specified.

**kwargs

Additional arguments passed to the underlying FastMCP server instance. Supports all FastMCP configuration options for advanced customization.

Raises:

ImportError

If FastMCP is not installed. FastMCP is a required dependency for SMCP. Install with: pip install fastmcp

Notes:

  • SMCP automatically handles ToolUniverse tool loading and MCP conversion

  • Tool search uses ToolFinderLLM (optimized for cost) when available, gracefully falls back to simpler methods

  • All tools support JSON argument passing for maximum flexibility

  • Server supports graceful shutdown and comprehensive resource cleanup

  • Thread pool execution ensures non-blocking operation for concurrent requests

  • Built-in error handling provides informative debugging information

__init__(name: str | None = None, tooluniverse_config: ToolUniverse | Dict[str, Any] | None = None, tool_categories: List[str] | None = None, exclude_tools: List[str] | None = None, exclude_categories: List[str] | None = None, include_tools: List[str] | None = None, tools_file: str | None = None, tool_config_files: Dict[str, str] | None = None, include_tool_types: List[str] | None = None, exclude_tool_types: List[str] | None = None, auto_expose_tools: bool = True, search_enabled: bool = True, max_workers: int = 5, hooks_enabled: bool = False, hook_config: Dict[str, Any] | None = None, hook_type: str | None = None, **kwargs)[source][source]
add_custom_tool(name: str, function: Callable, description: str | None = None, **kwargs)[source][source]

Add a custom Python function as an MCP tool to the SMCP server.

This method provides a convenient way to extend SMCP functionality with custom tools beyond those provided by ToolUniverse. Custom tools are automatically integrated into the MCP interface and can be discovered and used by clients alongside existing tools.

Parameters:

namestr

Unique name for the tool in the MCP interface. Should be descriptive and follow naming conventions (lowercase with underscores preferred). Examples: “analyze_protein_sequence”, “custom_data_processor”

functionCallable

Python function to execute when the tool is called. The function: - Can be synchronous or asynchronous - Should have proper type annotations for parameters - Should include a comprehensive docstring - Will be automatically wrapped for MCP compatibility

descriptionstr, optional

Human-readable description of the tool’s functionality. If provided, this will be set as the function’s __doc__ attribute. If None, the function’s existing docstring will be used.

**kwargs

Additional FastMCP tool configuration options: - parameter_schema: Custom JSON schema for parameters - return_schema: Schema for return values - examples: Usage examples for the tool - tags: Categorization tags

Returns:

Callable

The decorated function registered with FastMCP framework.

Usage Examples:

Simple synchronous function: .. code-block:: python

def analyze_text(text: str, max_length: int = 100) -> str:

‘’’Analyze text and return summary.’’’ return text[:max_length] + “…” if len(text) > max_length else text

server.add_custom_tool(

name=”text_analyzer”, function=analyze_text, description=”Analyze and summarize text content”

)

Asynchronous function with complex parameters: .. code-block:: python

async def process_data(

data: List[Dict[str, Any]], processing_type: str = “standard”

) -> Dict[str, Any]:

‘’’Process scientific data with specified method.’’’ # Custom processing logic here return {“processed_items”: len(data), “type”: processing_type}

server.add_custom_tool(

name=”data_processor”, function=process_data

)

Function with custom schema: .. code-block:: python

def calculate_score(values: List[float]) -> float:

‘’’Calculate composite score from values.’’’ return sum(values) / len(values) if values else 0.0

server.add_custom_tool(

name=”score_calculator”, function=calculate_score, parameter_schema={

“type”: “object”, “properties”: {

“values”: {

“type”: “array”, “items”: {“type”: “number”}, “description”: “List of numeric values to process”

}

}, “required”: [“values”]

}

)

Integration with ToolUniverse:

Custom tools work seamlessly alongside ToolUniverse tools: - Appear in tool discovery searches - Follow same calling conventions - Include in server diagnostics and listings - Support all MCP client interaction patterns

Best Practices:

  • Use descriptive, unique tool names

  • Include comprehensive docstrings

  • Add proper type annotations for parameters

  • Handle errors gracefully within the function

  • Consider async functions for I/O-bound operations

  • Test tools thoroughly before deployment

Notes:

  • Custom tools are registered immediately upon addition

  • Tools can be added before or after server startup

  • Function signature determines parameter schema automatically

  • Custom tools support all FastMCP features and conventions

async close()[source][source]

Perform comprehensive cleanup and resource management during server shutdown.

This method ensures graceful shutdown of the SMCP server by properly cleaning up all resources, stopping background tasks, and releasing system resources. It’s designed to be safe to call multiple times and handles errors gracefully.

Cleanup Operations:

Thread Pool Shutdown: - Gracefully stops the ThreadPoolExecutor used for tool execution - Waits for currently running tasks to complete - Prevents new tasks from being submitted - Times out after reasonable wait period to prevent hanging

Resource Cleanup: - Releases any open file handles or network connections - Clears internal caches and temporary data - Stops background monitoring tasks - Frees memory allocated for tool configurations

Error Handling: - Continues cleanup even if individual operations fail - Logs cleanup errors for debugging without raising exceptions - Ensures critical resources are always released

Usage Patterns:

Automatic Cleanup (Recommended): .. code-block:: python

server = SMCP(“My Server”) try:

server.run_simple() # Cleanup happens automatically on exit

except KeyboardInterrupt:

pass # run_simple() handles cleanup

Manual Cleanup: .. code-block:: python

server = SMCP(“My Server”) try:

# Custom server logic here pass

finally:

await server.close() # Explicit cleanup

**Context Manager Pattern:** .. code-block:: python

async with SMCP(“My Server”) as server:

# Server operations pass

# Cleanup happens automatically

Performance Considerations:

  • Cleanup operations are typically fast (< 1 second)

  • Thread pool shutdown may take longer if tasks are running

  • Network connections are closed immediately

  • Memory cleanup depends on garbage collection

Error Recovery:

  • Individual cleanup failures don’t stop the overall process

  • Critical errors are logged but don’t raise exceptions

  • Cleanup is idempotent - safe to call multiple times

  • System resources are guaranteed to be released

Notes:

  • This method is called automatically by run_simple() on shutdown

  • Can be called manually for custom server lifecycle management

  • Async method to properly handle async resource cleanup

  • Safe to call even if server hasn’t been fully initialized

run_simple(transport: Literal['stdio', 'http', 'sse'] = 'http', host: str = '0.0.0.0', port: int = 7000, **kwargs)[source][source]

Start the SMCP server with simplified configuration and automatic setup.

This method provides a convenient way to launch the SMCP server with sensible defaults for different deployment scenarios. It handles transport configuration, logging setup, and graceful shutdown automatically.

Parameters:

transport{“stdio”, “http”, “sse”}, default “http”

Communication transport protocol:

  • “stdio”: Standard input/output communication * Best for: Command-line tools, subprocess integration * Pros: Low overhead, simple integration * Cons: Single client, no network access

  • “http”: HTTP-based communication (streamable-http) * Best for: Web applications, REST API integration * Pros: Wide compatibility, stateless, scalable * Cons: Higher overhead than stdio

  • “sse”: Server-Sent Events over HTTP * Best for: Real-time applications, streaming responses * Pros: Real-time communication, web-compatible * Cons: Browser limitations, more complex

hoststr, default “0.0.0.0”

Server bind address for HTTP/SSE transports: - “0.0.0.0”: Listen on all network interfaces (default) - “127.0.0.1”: localhost only (more secure) - Specific IP: Bind to particular interface

portint, default 7000

Server port for HTTP/SSE transports. Choose ports: - 7000-7999: Recommended range for SMCP servers - Above 1024: No root privileges required - Check availability: Ensure port isn’t already in use

**kwargs

Additional arguments passed to FastMCP’s run() method: - debug (bool): Enable debug logging - access_log (bool): Log client requests - workers (int): Number of worker processes (HTTP only)

Server Startup Process:

  1. Initialization Summary: Displays server configuration and capabilities

  2. Transport Setup: Configures selected communication method

  3. Service Start: Begins listening for client connections

  4. Graceful Shutdown: Handles interrupts and cleanup

Deployment Scenarios:

Development & Testing: .. code-block:: python

server = SMCP(name=”Dev Server”) server.run_simple(transport=”stdio”) # For CLI testing

Local Web Service: .. code-block:: python

server = SMCP(name=”Local API”) server.run_simple(transport=”http”, host=”127.0.0.1”, port=8000)

Production Service: .. code-block:: python

server = SMCP(

name=”Production SMCP”, tool_categories=[“ChEMBL”, “uniprot”, “opentarget”], max_workers=20

) server.run_simple(

transport=”http”, host=”0.0.0.0”, port=7000, workers=4

)

Real-time Applications: .. code-block:: python

server = SMCP(name=”Streaming API”) server.run_simple(transport=”sse”, port=7001)

Error Handling:

  • KeyboardInterrupt: Graceful shutdown on Ctrl+C

  • Port in Use: Clear error message with suggestions

  • Transport Errors: Detailed debugging information

  • **Cleanup**: Automatic resource cleanup on exit

Logging Output:

Provides informative startup messages:

🚀 Starting SMCP server ‘My Server’… 📊 Loaded 356 tools from ToolUniverse 🔍 Search enabled: True 🌐 Server running on http://0.0.0.0:7000

Security Considerations:

  • Use host=”127.0.0.1” for local-only access

  • Configure firewall rules for production deployment

  • Consider HTTPS termination with reverse proxy

  • Validate all client inputs through MCP protocol

Performance Notes:

  • HTTP transport supports multiple concurrent clients

  • stdio transport is single-client but lower latency

  • SSE transport enables real-time bidirectional communication

  • Thread pool size affects concurrent tool execution capacity

tooluniverse.create_smcp_server(name: str = 'SMCP Server', tool_categories: List[str] | None = None, search_enabled: bool = True, **kwargs) SMCP[source][source]

Create a configured SMCP server with common defaults and best practices.

This convenience function simplifies SMCP server creation by providing sensible defaults for common use cases while still allowing full customization through additional parameters.

Parameters:

namestr, default “SMCP Server”

Human-readable server name used in logs and server identification. Choose descriptive names like: - “Scientific Research API” - “Drug Discovery Server” - “Proteomics Analysis Service”

tool_categorieslist of str, optional

Specific ToolUniverse categories to load. If None, loads all available tools (350+ tools). Common category combinations:

Scientific Research: [“ChEMBL”, “uniprot”, “opentarget”, “pubchem”, “hpa”]

Drug Discovery: [“ChEMBL”, “fda_drug_label”, “clinical_trials”, “pubchem”]

Literature Analysis: [“EuropePMC”, “semantic_scholar”, “pubtator”, “agents”]

Minimal Setup: [“tool_finder_llm”, “special_tools”]

search_enabledbool, default True

Enable AI-powered tool discovery via tools/find method. Recommended to keep enabled unless you have specific performance requirements or want to minimize dependencies.

**kwargs

Additional SMCP configuration options:

  • tooluniverse_config: Pre-configured ToolUniverse instance

  • auto_expose_tools (bool, default True): Auto-expose ToolUniverse tools

  • max_workers (int, default 5): Thread pool size for tool execution

  • Any FastMCP server options (debug, logging, etc.)

Returns:

SMCP

Fully configured SMCP server instance ready to run.

Usage Examples:

Quick Start (all tools): .. code-block:: python

server = create_smcp_server(“Research Server”) server.run_simple()

Focused Server (specific domains): .. code-block:: python

server = create_smcp_server(

name=”Drug Discovery API”, tool_categories=[“ChEMBL”, “fda_drug_label”, “clinical_trials”], max_workers=10

) server.run_simple(port=8000)

Custom Configuration: .. code-block:: python

server = create_smcp_server(

name=”High-Performance Server”, search_enabled=True, max_workers=20, debug=True

) server.run_simple(transport=”http”, host=”0.0.0.0”, port=7000)

Pre-configured ToolUniverse: .. code-block:: python

tu = ToolUniverse() tu.load_tools(tool_type=[“uniprot”, “ChEMBL”]) server = create_smcp_server(

name=”Protein-Drug Server”, tooluniverse_config=tu, search_enabled=True

)

Benefits of Using This Function:

  • Simplified Setup: Reduces boilerplate code for common configurations

  • Best Practices: Applies recommended settings automatically

  • Consistent Naming: Encourages good server naming conventions

  • Future-Proof: Will include new recommended defaults in future versions

  • Documentation: Provides clear examples and guidance

Equivalent Manual Configuration:

This function is equivalent to: .. code-block:: python

server = SMCP(

name=name, tool_categories=tool_categories, search_enabled=search_enabled, auto_expose_tools=True, max_workers=5, **kwargs

)

When to Use Manual Configuration:

  • Need precise control over all initialization parameters

  • Using custom ToolUniverse configurations

  • Implementing custom MCP methods or tools

  • Advanced deployment scenarios with specific requirements

class tooluniverse.USPTOOpenDataPortalTool(tool_config, api_key=None, base_url='https://api.uspto.gov/api/v1')[source][source]

Bases: BaseTool

A tool for interacting with the USPTO Open Data Portal API to search for and retrieve patent information. The run method dynamically constructs API requests based on the provided tool configuration.

__init__(tool_config, api_key=None, base_url='https://api.uspto.gov/api/v1')[source][source]

Initializes the USPTOOpenDataPortalTool.

Parameters:
  • tool_config – The configuration for the specific tool being run.

  • api_key – Your USPTO Open Data Portal API key.

  • base_url – The base URL for the USPTO API.

get_by_path(d, keys)[source][source]

Safely navigate nested dicts by a list of keys.

assign_by_path(d, path, value)[source][source]

Create nested dicts for a dot‑path and set the final key to value.

prune_item(item, return_fields)[source][source]
run(arguments)[source][source]

Runs the specified tool by constructing and executing an API call based on the tool’s configuration.

Parameters:

arguments – A dictionary of arguments for the tool, matching the parameters in the tool definition.

Returns:

The result of the API call, either as a dictionary (for JSON) or a string (for CSV).

class tooluniverse.XMLDatasetTool(tool_config: Dict[str, Any])[source][source]

Bases: BaseTool

Tool to search and filter XML datasets that are organized as a collection of searchable records (e.g., dataset of medical subjects or drug descriptions). Supports user-friendly queries without requiring XPath knowledge.

__init__(tool_config: Dict[str, Any])[source][source]
run(arguments: Dict[str, Any]) Dict[str, Any][source][source]

Main entry point for the tool.

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

Get comprehensive information about the loaded XML dataset.

class tooluniverse.ToolFinderKeyword(tool_config, tooluniverse=None)[source][source]

Bases: BaseTool

Advanced keyword-based tool finder that uses sophisticated text processing and TF-IDF scoring.

This class implements natural language processing techniques for tool discovery including: - Tokenization and normalization - Stop word removal - Basic stemming - TF-IDF relevance scoring - Semantic phrase matching

The search operates by parsing user queries to extract key terms, processing them through NLP pipelines, and matching against pre-built indices of tool metadata for efficient and relevant tool discovery.

STOP_WORDS = {'a', 'all', 'an', 'and', 'any', 'are', 'as', 'at', 'be', 'boy', 'but', 'by', 'came', 'can', 'day', 'did', 'do', 'down', 'each', 'find', 'for', 'from', 'get', 'had', 'has', 'have', 'he', 'how', 'if', 'in', 'is', 'it', 'its', 'long', 'made', 'may', 'new', 'no', 'now', 'number', 'of', 'old', 'on', 'part', 'said', 'see', 'that', 'the', 'their', 'they', 'this', 'time', 'to', 'two', 'up', 'use', 'was', 'way', 'what', 'which', 'who', 'will', 'with', 'your'}[source]
STEMMING_RULES = [('ies', 'y'), ('ied', 'y'), ('ying', 'y'), ('ing', ''), ('ly', ''), ('ed', ''), ('ies', 'y'), ('ier', 'y'), ('iest', 'y'), ('s', ''), ('es', ''), ('er', ''), ('est', ''), ('tion', 't'), ('sion', 's'), ('ness', ''), ('ment', ''), ('able', ''), ('ible', ''), ('ful', ''), ('less', ''), ('ous', ''), ('ive', ''), ('al', ''), ('ic', ''), ('ize', ''), ('ise', ''), ('ate', ''), ('fy', ''), ('ify', '')][source]
__init__(tool_config, tooluniverse=None)[source][source]

Initialize the Advanced Keyword-based Tool Finder.

Parameters:
  • tool_config (dict) – Configuration dictionary for the tool

  • tooluniverse – Reference to the ToolUniverse instance containing all tools

find_tools(message=None, picked_tool_names=None, rag_num=5, return_call_result=False, categories=None)[source][source]

Find relevant tools based on a message or pre-selected tool names.

This method matches the interface of other tool finders to ensure seamless replacement. It uses keyword-based search instead of embedding similarity.

Parameters:
  • message (str, optional) – Query message to find tools for. Required if picked_tool_names is None.

  • picked_tool_names (list, optional) – Pre-selected tool names to process. Required if message is None.

  • rag_num (int, optional) – Number of tools to return after filtering. Defaults to 5.

  • return_call_result (bool, optional) – If True, returns both prompts and tool names. Defaults to False.

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

Returns:

  • If return_call_result is False: Tool prompts as a formatted string

  • If return_call_result is True: Tuple of (tool_prompts, tool_names)

Return type:

str or tuple

Raises:

AssertionError – If both message and picked_tool_names are None

run(arguments)[source][source]

Find tools using advanced keyword-based search with NLP processing and TF-IDF scoring.

This method provides a unified interface compatible with other tool finders.

Parameters:

arguments (dict) – Dictionary containing: - description (str): Search query string (unified parameter name) - categories (list, optional): List of categories to filter by - limit (int, optional): Maximum number of results to return (default: 10) - picked_tool_names (list, optional): Pre-selected tool names to process - return_call_result (bool, optional): Whether to return both prompts and names. Defaults to False.

Returns:

  • If return_call_result is False: Tool prompts as a formatted string

  • If return_call_result is True: Tuple of (tool_prompts, tool_names)

Return type:

str or tuple

class tooluniverse.ToolFinderLLM(tool_config, tooluniverse=None)[source][source]

Bases: BaseTool

LLM-based tool finder that uses natural language processing to select relevant tools.

This class leverages AgenticTool’s LLM capabilities to analyze tool descriptions and match them with user queries. It’s optimized for minimal context window cost by only sending essential information (tool name and description) to the LLM, providing an intelligent alternative to embedding-based similarity search.

Cost optimizations: - Only includes tool name and description in LLM prompt - Uses compact formatting to minimize token usage - Excludes unnecessary tool metadata and parameters - Implements caching to avoid repeated tool processing

__init__(tool_config, tooluniverse=None)[source][source]

Initialize the LLM-based Tool Finder.

Parameters:
  • tool_config (dict) – Configuration dictionary containing LLM settings and prompts

  • tooluniverse – Reference to the ToolUniverse instance containing all tools

find_tools_llm(query, limit=5, include_reasoning=False, categories=None)[source][source]

Find relevant tools using LLM-based selection.

Parameters:
  • query (str) – User query describing needed functionality

  • limit (int) – Maximum number of tools to return

  • include_reasoning (bool) – Whether to include selection reasoning

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

Returns:

Dictionary containing selected tools and metadata

Return type:

dict

find_tools(message=None, picked_tool_names=None, rag_num=5, return_call_result=False, categories=None, return_list_only=None)[source][source]

Find relevant tools based on a message or pre-selected tool names.

This method matches the interface of the original ToolFinderEmbedding to ensure seamless replacement. It uses LLM-based selection instead of embedding similarity.

Parameters:
  • message (str, optional) – Query message to find tools for. Required if picked_tool_names is None.

  • picked_tool_names (list, optional) – Pre-selected tool names to process. Required if message is None.

  • rag_num (int, optional) – Number of tools to return after filtering. Defaults to 5.

  • return_call_result (bool, optional) – If True, returns both prompts and tool names. Defaults to False.

  • categories (list, optional) – List of tool categories to filter by. Applied before LLM selection.

  • return_list_only (bool, optional) – If True, returns only a list of tool specifications. Overrides other return options.

Returns:

  • If return_list_only is True: List of tool specifications

  • If return_call_result is False: Tool prompts as a formatted string

  • If return_call_result is True: Tuple of (tool_prompts, tool_names)

Return type:

str, tuple, or list

Raises:

AssertionError – If both message and picked_tool_names are None

get_tool_stats()[source][source]

Get statistics about available tools.

clear_cache()[source][source]

Clear the tool cache to force refresh on next access.

run(arguments)[source][source]

Run the tool finder with given arguments following the standard tool interface.

This method now returns JSON format by default to ensure consistency with other search tools and simplify integration with SMCP.

Parameters:

arguments (dict) – Dictionary containing: - description (str, optional): Query message to find tools for (maps to ‘message’) - limit (int, optional): Number of tools to return (maps to ‘rag_num’). Defaults to 5. - picked_tool_names (list, optional): Pre-selected tool names to process - return_call_result (bool, optional): Whether to return both prompts and names. Defaults to False. - return_format (str, optional): ‘json’ (default) or ‘legacy’ for old format - return_list_only (bool, optional): Whether to return only tool specifications as a list - categories (list, optional): List of tool categories to filter by

find_tools_legacy(query, limit=5, include_reasoning=False, return_format='prompts')[source][source]

Legacy method for finding tools with different parameter names.

This provides backward compatibility for any code that might use ‘query’ instead of ‘description’.

class tooluniverse.URLHTMLTagTool(tool_config)[source][source]

Bases: BaseTool

Fetches a webpage and extracts the content of a specified HTML tag. Expects: {“url”: “https://…”} The tag to extract is specified in the tool’s configuration. The tag to extract is specified in the tool’s configuration. Optional: {“timeout”: <seconds>} (default 20) Returns: {“content”: “<extracted content>”} or {“error”: “…”}

__init__(tool_config)[source][source]
run(arguments: dict)[source][source]

Execute the tool.

The default BaseTool implementation accepts an optional arguments mapping to align with most concrete tool implementations which expect a dictionary of inputs.

class tooluniverse.URLToPDFTextTool(tool_config)[source][source]

Bases: BaseTool

Loads a webpage (with JavaScript), exports it as a PDF, and extracts text. Expects: {“url”: “https://…”} Optional: {“timeout”: <seconds>} (default 30) Returns: {“text”: “<extracted text>”} or {“error”: “…”}

__init__(tool_config)[source][source]
run(arguments: dict)[source][source]

Execute the tool.

The default BaseTool implementation accepts an optional arguments mapping to align with most concrete tool implementations which expect a dictionary of inputs.

class tooluniverse.RCSBTool(tool_config)[source][source]

Bases: BaseTool

__init__(tool_config)[source][source]
validate_params(params: dict)[source][source]
prepare_input_ids(params: dict)[source][source]
run(params: dict)[source][source]

Execute the tool.

The default BaseTool implementation accepts an optional arguments mapping to align with most concrete tool implementations which expect a dictionary of inputs.

class tooluniverse.GWASAssociationSearch(tool_config)[source][source]

Bases: GWASRESTTool

Search for GWAS associations by various criteria.

__init__(tool_config)[source][source]
run(arguments: Dict[str, Any]) Dict[str, Any][source][source]

Search for associations with optional filters.

class tooluniverse.GWASStudySearch(tool_config)[source][source]

Bases: GWASRESTTool

Search for GWAS studies by various criteria.

__init__(tool_config)[source][source]
run(arguments: Dict[str, Any]) Dict[str, Any][source][source]

Search for studies with optional filters.

class tooluniverse.GWASSNPSearch(tool_config)[source][source]

Bases: GWASRESTTool

Search for GWAS single nucleotide polymorphisms (SNPs).

__init__(tool_config)[source][source]
run(arguments: Dict[str, Any]) Dict[str, Any][source][source]

Search for SNPs with optional filters.

class tooluniverse.GWASAssociationByID(tool_config)[source][source]

Bases: GWASRESTTool

Get a specific GWAS association by its ID.

__init__(tool_config)[source][source]
run(arguments: Dict[str, Any]) Dict[str, Any][source][source]

Get association by ID.

class tooluniverse.GWASStudyByID(tool_config)[source][source]

Bases: GWASRESTTool

Get a specific GWAS study by its ID.

__init__(tool_config)[source][source]
run(arguments: Dict[str, Any]) Dict[str, Any][source][source]

Get study by ID.

class tooluniverse.GWASSNPByID(tool_config)[source][source]

Bases: GWASRESTTool

Get a specific GWAS SNP by its rs ID.

__init__(tool_config)[source][source]
run(arguments: Dict[str, Any]) Dict[str, Any][source][source]

Get SNP by rs ID.

class tooluniverse.GWASVariantsForTrait(tool_config)[source][source]

Bases: GWASRESTTool

Get all variants associated with a specific trait.

__init__(tool_config)[source][source]
run(arguments: Dict[str, Any]) Dict[str, Any][source][source]

Get variants for a trait with pagination support.

class tooluniverse.GWASAssociationsForTrait(tool_config)[source][source]

Bases: GWASRESTTool

Get all associations for a specific trait, sorted by p-value.

__init__(tool_config)[source][source]
run(arguments: Dict[str, Any]) Dict[str, Any][source][source]

Get associations for a trait, sorted by significance.

class tooluniverse.GWASAssociationsForSNP(tool_config)[source][source]

Bases: GWASRESTTool

Get all associations for a specific SNP.

__init__(tool_config)[source][source]
run(arguments: Dict[str, Any]) Dict[str, Any][source][source]

Get associations for a SNP.

class tooluniverse.GWASStudiesForTrait(tool_config)[source][source]

Bases: GWASRESTTool

Get studies for a specific trait with optional filters.

__init__(tool_config)[source][source]
run(arguments: Dict[str, Any]) Dict[str, Any][source][source]

Get studies for a trait with optional filters.

class tooluniverse.GWASSNPsForGene(tool_config)[source][source]

Bases: GWASRESTTool

Get SNPs mapped to a specific gene.

__init__(tool_config)[source][source]
run(arguments: Dict[str, Any]) Dict[str, Any][source][source]

Get SNPs for a gene.

class tooluniverse.GWASAssociationsForStudy(tool_config)[source][source]

Bases: GWASRESTTool

Get all associations for a specific study.

__init__(tool_config)[source][source]
run(arguments: Dict[str, Any]) Dict[str, Any][source][source]

Get associations for a study.

class tooluniverse.MCPClientTool(tool_config)[source][source]

Bases: BaseTool, BaseMCPClient

A tool that acts as an MCP client to connect to existing MCP servers. Supports both HTTP and WebSocket transports.

__init__(tool_config)[source][source]
async list_tools() List[Dict[str, Any]][source][source]

List available tools from the MCP server

async call_tool(name: str, arguments: Dict[str, Any]) Dict[str, Any][source][source]

Call a tool on the MCP server

async list_resources() List[Dict[str, Any]][source][source]

List available resources from the MCP server

async read_resource(uri: str) Dict[str, Any][source][source]

Read a resource from the MCP server

async list_prompts() List[Dict[str, Any]][source][source]

List available prompts from the MCP server

async get_prompt(name: str, arguments: Dict[str, Any] | None = None) Dict[str, Any][source][source]

Get a prompt from the MCP server

run(arguments)[source][source]

Main run method for the tool. Supports different operations based on the ‘operation’ argument.

class tooluniverse.MCPAutoLoaderTool(tool_config)[source][source]

Bases: BaseTool, BaseMCPClient

An advanced MCP tool that automatically discovers and loads all tools from an MCP server. It can register discovered tools as individual ToolUniverse tools for seamless usage.

__init__(tool_config)[source][source]
async discover_tools() Dict[str, Any][source][source]

Discover all available tools from the MCP server

async call_tool(tool_name: str, arguments: Dict[str, Any]) Dict[str, Any][source][source]

Directly call an MCP tool by name

generate_proxy_tool_configs() List[Dict[str, Any]][source][source]

Generate proxy tool configurations for discovered tools

register_tools_in_engine(engine)[source][source]

Register discovered tools directly in the ToolUniverse engine

async auto_load_and_register(engine) Dict[str, Any][source][source]

Automatically discover, load and register all MCP tools

run(arguments)[source][source]

Main run method for the auto-loader tool

__del__()[source][source]

Cleanup when object is destroyed

class tooluniverse.ADMETAITool(**kwargs)[source][source]

Bases: BaseTool

Tool to predict ADMET properties for a given SMILES string using the admet-ai Python package.

__init__(**kwargs)[source][source]
run(arguments: dict) dict[source][source]

Predicts ADMET properties for a given SMILES string.

Parameters:

smiles – The SMILES string(s) of the molecule(s).

Returns:

A dictionary mapping each SMILES string to a subdictionary of selected ADMET properties and their predicted values.

class tooluniverse.EmbeddingDatabase(tool_config)[source][source]

Bases: BaseTool

Unified embedding database tool supporting multiple operations: - create_from_docs: Create new database from documents - add_docs: Add documents to existing database - search: Search for similar documents - load_database: Load existing database from path

__init__(tool_config)[source][source]
run(arguments)[source][source]

Main entry point for the tool

class tooluniverse.EmbeddingSync(tool_config)[source][source]

Bases: BaseTool

Sync embedding databases with HuggingFace Hub. Supports uploading local databases and downloading shared databases.

__init__(tool_config)[source][source]
run(arguments)[source][source]

Main entry point for the tool

class tooluniverse.ToolFinderEmbedding(tool_config, tooluniverse)[source][source]

Bases: BaseTool

A tool finder model that uses RAG (Retrieval-Augmented Generation) to find relevant tools based on user queries using semantic similarity search.

This class leverages sentence transformers to encode tool descriptions and find the most relevant tools for a given query through embedding-based similarity matching.

rag_model_name[source]

Name of the sentence transformer model for embeddings

Type:

str

rag_model[source]

The loaded sentence transformer model

Type:

SentenceTransformer

tool_desc_embedding[source]

Cached embeddings of tool descriptions

Type:

torch.Tensor

tool_name[source]

List of available tool names

Type:

list

tool_embedding_path[source]

Path to cached tool embeddings file

Type:

str

special_tools_name[source]

List of special tools to exclude from results

Type:

list

tooluniverse[source]

Reference to the tool universe containing all tools

__init__(tool_config, tooluniverse)[source][source]

Initialize the ToolFinderEmbedding with configuration and RAG model.

Parameters:

tool_config (dict) – Configuration dictionary for the tool

load_rag_model()[source][source]

Load the sentence transformer model for RAG-based tool retrieval.

Configures the model with appropriate sequence length and tokenizer settings for optimal performance in tool description encoding.

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

Load or generate embeddings for tool descriptions from the tool universe.

This method either loads cached embeddings from disk or generates new ones by encoding all tool descriptions. Embeddings are cached to disk for faster subsequent loads. Memory is properly cleaned up after embedding generation to avoid OOM issues.

Parameters:
  • tooluniverse – ToolUniverse instance containing all available tools

  • include_names (list, optional) – Specific tool names to include

  • exclude_names (list, optional) – Tool names to exclude

  • include_categories (list, optional) – Tool categories to include

  • exclude_categories (list, optional) – Tool categories to exclude

rag_infer(query, top_k=5)[source][source]

Perform RAG inference to find the most relevant tools for a given query.

Uses semantic similarity between the query embedding and pre-computed tool embeddings to identify the most relevant tools.

Parameters:
  • query (str) – User query or description of desired functionality

  • top_k (int, optional) – Number of top tools to return. Defaults to 5.

Returns:

List of top-k tool names ranked by relevance to the query

Return type:

list

Raises:

SystemExit – If tool_desc_embedding is not loaded

find_tools(message=None, picked_tool_names=None, rag_num=5, return_call_result=False, categories=None)[source][source]

Find relevant tools based on a message or pre-selected tool names.

This method either uses RAG inference to find tools based on a message or processes a list of pre-selected tool names. It filters out special tools and returns tool prompts suitable for use in agent workflows.

Parameters:
  • message (str, optional) – Query message to find tools for. Required if picked_tool_names is None.

  • picked_tool_names (list, optional) – Pre-selected tool names to process. Required if message is None.

  • rag_num (int, optional) – Number of tools to return after filtering. Defaults to 5.

  • return_call_result (bool, optional) – If True, returns both prompts and tool names. Defaults to False.

  • categories (list, optional) – List of tool categories to filter by. Currently not implemented for embedding-based search.

Returns:

  • If return_call_result is False: Tool prompts as a formatted string

  • If return_call_result is True: Tuple of (tool_prompts, tool_names)

Return type:

str or tuple

Raises:

AssertionError – If both message and picked_tool_names are None

run(arguments)[source][source]

Run the tool finder with given arguments following the standard tool interface.

This is the main entry point for using ToolFinderEmbedding as a standard tool. It extracts parameters from the arguments dictionary and delegates to find_tools().

Parameters:

arguments (dict) – Dictionary containing: - description (str, optional): Query message to find tools for (maps to ‘message’) - limit (int, optional): Number of tools to return (maps to ‘rag_num’). Defaults to 5. - picked_tool_names (list, optional): Pre-selected tool names to process - return_call_result (bool, optional): Whether to return both prompts and names. Defaults to False. - categories (list, optional): List of tool categories to filter by

class tooluniverse.AlphaFoldRESTTool(tool_config)[source][source]

Bases: BaseTool

AlphaFold Protein Structure Database API tool. Generic wrapper for AlphaFold API endpoints defined in alphafold_tools.json.

__init__(tool_config)[source][source]
run(arguments: Dict[str, Any])[source][source]

Execute the tool with provided arguments.

class tooluniverse.ODPHPMyHealthfinder(tool_config)[source][source]

Bases: ODPHPRESTTool

Search for demographic-specific health recommendations (MyHealthfinder).

run(arguments: Dict[str, Any]) Dict[str, Any][source][source]

Execute the tool.

The default BaseTool implementation accepts an optional arguments mapping to align with most concrete tool implementations which expect a dictionary of inputs.

class tooluniverse.ODPHPItemList(tool_config)[source][source]

Bases: ODPHPRESTTool

Retrieve list of topics or categories.

run(arguments: Dict[str, Any]) Dict[str, Any][source][source]

Execute the tool.

The default BaseTool implementation accepts an optional arguments mapping to align with most concrete tool implementations which expect a dictionary of inputs.

class tooluniverse.ODPHPTopicSearch(tool_config)[source][source]

Bases: ODPHPRESTTool

Search for health topics by ID, category, or keyword.

run(arguments: Dict[str, Any]) Dict[str, Any][source][source]

Execute the tool.

The default BaseTool implementation accepts an optional arguments mapping to align with most concrete tool implementations which expect a dictionary of inputs.

class tooluniverse.ODPHPOutlinkFetch(tool_config)[source][source]

Bases: BaseTool

Fetch article pages referenced by AccessibleVersion / RelatedItems.Url and return readable text. - HTML: extracts main/article/body text; strips nav/aside/footer/script/style. - PDF or non-HTML: returns metadata + URL so the agent can surface it.

__init__(tool_config)[source][source]
run(arguments: Dict[str, Any]) Dict[str, Any][source][source]

Execute the tool.

The default BaseTool implementation accepts an optional arguments mapping to align with most concrete tool implementations which expect a dictionary of inputs.

Subpackages

Submodules