tooluniverse packageΒΆ
- class tooluniverse.ADMETAITool(**kwargs)[source]ΒΆ
Bases:
BaseTool
Tool to predict ADMET properties for a given SMILES string using the admet-ai Python package.
- class tooluniverse.AgenticTool(tool_config: Dict[str, Any])[source]ΒΆ
Bases:
BaseTool
Generic wrapper around LLM prompting supporting JSON-defined configs with prompts and input arguments.
- _get_global_fallback_chain() List[Dict[str, str]] [source]ΒΆ
Get the global fallback chain from environment or use default.
- _try_initialize_api()[source]ΒΆ
Try to initialize the primary API, fallback to secondary if configured.
- static has_any_api_keys() bool [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:
- retry_initialization() bool [source]ΒΆ
Attempt to reinitialize the tool (useful if API keys were updated).
- class tooluniverse.AlphaFoldRESTTool(tool_config)[source]ΒΆ
Bases:
BaseTool
AlphaFold Protein Structure Database API tool. Generic wrapper for AlphaFold API endpoints defined in alphafold_tools.json.
- class tooluniverse.BaseTool(tool_config)[source]ΒΆ
Bases:
object
- classmethod get_default_config_file()[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:
Installed packages: Uses importlib.resources for proper package resource access
Development mode: Falls back to file-based path resolution
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
- class tooluniverse.ChEMBLTool(tool_config, base_url='https://www.ebi.ac.uk/chembl/api/data')[source]ΒΆ
Bases:
BaseTool
Tool to search for molecules similar to a given compound name or SMILES using the ChEMBL Web Services API.
- get_chembl_id_by_name(compound_name)[source]ΒΆ
Search ChEMBL for a compound by name and return the ChEMBL ID of the first match.
- get_chembl_smiles_pref_name_id_by_name(compound_name)[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.ClinicalTrialsDetailsTool(tool_config)[source]ΒΆ
Bases:
ClinicalTrialsTool
- class tooluniverse.ClinicalTrialsSearchTool(tool_config)[source]ΒΆ
Bases:
ClinicalTrialsTool
- class tooluniverse.ComposeTool(tool_config, tooluniverse=None)[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.
- _call_tool(tool_name, arguments)[source]ΒΆ
Helper function to call other tools from within composition code.
- _discover_tool_dependencies()[source]ΒΆ
Automatically discover tool dependencies from composition code.
- Returns:
Set of tool names that this composition calls
- Return type:
- _execute_from_file(arguments)[source]ΒΆ
Execute composition code from external file.
- Parameters:
arguments (dict) β Input arguments
- Returns:
Result from the composition execution
- Return type:
Any
- _execute_inline_code(arguments)[source]ΒΆ
Execute inline composition code (existing behavior).
- Parameters:
arguments (dict) β Input arguments
- Returns:
Result from the composition execution
- Return type:
Any
- _get_tool_category_mapping()[source]ΒΆ
Create a mapping from tool names to their categories.
- Returns:
Mapping of tool names to category names
- Return type:
- _load_code_from_file()[source]ΒΆ
Load composition code from external Python file.
- Returns:
The composition code as a string
- Return type:
- class tooluniverse.DatasetTool(tool_config)[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.
- _drugbank_filter(arguments)[source]ΒΆ
Filter drugs based on specific criteria and field-based conditions.
This function is dedicated to criteria-based filtering using simple field-condition-value parameters. It supports filter types like contains, starts_with, ends_with, exact, not_empty.
- Parameters:
arguments (dict) β Filter parameters including: - field (str): Field name to filter on - condition (str): Type of condition (contains, starts_with, ends_with, exact, not_empty) - value (str): Value to filter by (optional for not_empty condition) - limit (int): Maximum number of results
- Returns:
Filtered results with matched records and applied filters
- Return type:
- _drugbank_search(arguments)[source]ΒΆ
Search drugs by name, ID, synonyms, or other fields using text-based queries.
This function is dedicated to text-based searching across specified fields. It performs substring or exact matching based on user preferences.
- Parameters:
arguments (dict) β Search parameters including: - query (str): Text to search for - search_fields (list): Fields to search in - case_sensitive (bool): Whether search is case sensitive - exact_match (bool): Whether to perform exact matching - limit (int): Maximum number of results
- Returns:
Search results with matched records and metadata
- Return type:
- class tooluniverse.DiseaseTargetScoreTool(tool_config, datasource_id=None)[source]ΒΆ
Bases:
GraphQLTool
Tool to extract disease-target association scores from specific data sources
- class tooluniverse.EFOTool(tool_config, base_url='https://www.ebi.ac.uk/ols4/api/search')[source]ΒΆ
Bases:
BaseTool
Tool to lookup Experimental Factor Ontology (EFO) IDs for diseases via the EMBL-EBI OLS API.
- class tooluniverse.EmbeddingDatabase(tool_config)[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
- _generate_embeddings(texts: List[str], model: str, use_azure: bool = False) List[List[float]] [source]ΒΆ
Generate embeddings using OpenAI or Azure OpenAI API
- class tooluniverse.EmbeddingSync(tool_config)[source]ΒΆ
Bases:
BaseTool
Sync embedding databases with HuggingFace Hub. Supports uploading local databases and downloading shared databases.
- _generate_readme(database_name: str, description: str, db_info: Dict) str [source]ΒΆ
Generate README content for HuggingFace repository
- _merge_databases(source_db: str, target_db: str, source_name: str, target_name: str)[source]ΒΆ
Merge source database into target database (simplified implementation)
- class tooluniverse.EuropePMCTool(tool_config, base_url='https://www.ebi.ac.uk/europepmc/webservices/rest/search')[source]ΒΆ
Bases:
BaseTool
Tool to search for articles on Europe PMC including abstracts.
- class tooluniverse.FDACountAdditiveReactionsTool(tool_config, endpoint_url='https://api.fda.gov/drug/event.json', api_key=None)[source]ΒΆ
Bases:
FDADrugAdverseEventTool
Leverage openFDA API to count adverse reaction events across multiple drugs in one request.
- class tooluniverse.FDADrugAdverseEventTool(tool_config, endpoint_url='https://api.fda.gov/drug/event.json', api_key=None)[source]ΒΆ
Bases:
BaseTool
- class tooluniverse.FDADrugLabelGetDrugGenericNameTool(tool_config=None, api_key=None)[source]ΒΆ
Bases:
FDADrugLabelTool
- class tooluniverse.FDADrugLabelSearchIDTool(tool_config=None, api_key=None)[source]ΒΆ
Bases:
FDATool
- class tooluniverse.GWASAssociationByID(tool_config)[source]ΒΆ
Bases:
GWASRESTTool
Get a specific GWAS association by its ID.
- class tooluniverse.GWASAssociationSearch(tool_config)[source]ΒΆ
Bases:
GWASRESTTool
Search for GWAS associations by various criteria.
- class tooluniverse.GWASAssociationsForSNP(tool_config)[source]ΒΆ
Bases:
GWASRESTTool
Get all associations for a specific SNP.
- class tooluniverse.GWASAssociationsForStudy(tool_config)[source]ΒΆ
Bases:
GWASRESTTool
Get all associations for a specific study.
- class tooluniverse.GWASAssociationsForTrait(tool_config)[source]ΒΆ
Bases:
GWASRESTTool
Get all associations for a specific trait, sorted by p-value.
- class tooluniverse.GWASSNPByID(tool_config)[source]ΒΆ
Bases:
GWASRESTTool
Get a specific GWAS SNP by its rs ID.
- class tooluniverse.GWASSNPSearch(tool_config)[source]ΒΆ
Bases:
GWASRESTTool
Search for GWAS single nucleotide polymorphisms (SNPs).
- class tooluniverse.GWASSNPsForGene(tool_config)[source]ΒΆ
Bases:
GWASRESTTool
Get SNPs mapped to a specific gene.
- class tooluniverse.GWASStudiesForTrait(tool_config)[source]ΒΆ
Bases:
GWASRESTTool
Get studies for a specific trait with optional filters.
- class tooluniverse.GWASStudyByID(tool_config)[source]ΒΆ
Bases:
GWASRESTTool
Get a specific GWAS study by its ID.
- class tooluniverse.GWASStudySearch(tool_config)[source]ΒΆ
Bases:
GWASRESTTool
Search for GWAS studies by various criteria.
- class tooluniverse.GWASVariantsForTrait(tool_config)[source]ΒΆ
Bases:
GWASRESTTool
Get all variants associated with a specific trait.
- class tooluniverse.GetSPLBySetIDTool(tool_config)[source]ΒΆ
Bases:
BaseTool
Get complete SPL label based on SPL Set ID, returns content in XML or JSON format.
- class tooluniverse.HPAGetGeneJSONTool(tool_config)[source]ΒΆ
Bases:
HPAJsonApiTool
Enhanced legacy tool - Get basic gene information using Ensembl Gene ID. Now uses the efficient JSON API instead of search API.
- class tooluniverse.HPAGetGeneXMLTool(tool_config)[source]ΒΆ
Bases:
HPASearchApiTool
Legacy tool - Get gene TSV format data (alternative to XML).
- class tooluniverse.MCPAutoLoaderTool(tool_config)[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.
- async auto_load_and_register(engine) Dict[str, Any] [source]ΒΆ
Automatically discover, load and register all MCP tools
- async call_tool(tool_name: str, arguments: Dict[str, Any]) Dict[str, Any] [source]ΒΆ
Directly call an MCP tool by name
- generate_proxy_tool_configs() List[Dict[str, Any]] [source]ΒΆ
Generate proxy tool configurations for discovered tools
- class tooluniverse.MCPClientTool(tool_config)[source]ΒΆ
Bases:
BaseTool
,BaseMCPClient
A tool that acts as an MCP client to connect to existing MCP servers. Supports both HTTP and WebSocket transports.
- async call_tool(name: str, arguments: Dict[str, Any]) Dict[str, Any] [source]ΒΆ
Call a tool on the MCP server
- class tooluniverse.MedlinePlusRESTTool(tool_config)[source]ΒΆ
Bases:
BaseTool
MedlinePlus REST API tool class. Supports health topic search, code lookup, genetics information retrieval, etc.
- class tooluniverse.MonarchDiseasesForMultiplePhenoTool(tool_config)[source]ΒΆ
Bases:
MonarchTool
- class tooluniverse.MonarchTool(tool_config)[source]ΒΆ
Bases:
RESTfulTool
- class tooluniverse.ODPHPItemList(tool_config)[source]ΒΆ
Bases:
ODPHPRESTTool
Retrieve list of topics or categories.
- class tooluniverse.ODPHPMyHealthfinder(tool_config)[source]ΒΆ
Bases:
ODPHPRESTTool
Search for demographic-specific health recommendations (MyHealthfinder).
- class tooluniverse.ODPHPOutlinkFetch(tool_config)[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.
- class tooluniverse.ODPHPTopicSearch(tool_config)[source]ΒΆ
Bases:
ODPHPRESTTool
Search for health topics by ID, category, or keyword.
- class tooluniverse.OpentargetGeneticsTool(tool_config)[source]ΒΆ
Bases:
GraphQLTool
- class tooluniverse.OpentargetTool(tool_config)[source]ΒΆ
Bases:
GraphQLTool
- class tooluniverse.OpentargetToolDrugNameMatch(tool_config, drug_generic_tool=None)[source]ΒΆ
Bases:
GraphQLTool
- class tooluniverse.PackageTool(tool_config)[source]ΒΆ
Bases:
BaseTool
Universal tool to provide information about Python packages. Fetches real-time data from PyPI API with local fallback.
- _get_local_info(include_examples: bool = True) Dict[str, Any] [source]ΒΆ
Get package information from local configuration
- class tooluniverse.PubChemRESTTool(tool_config)[source]ΒΆ
Bases:
BaseTool
Generic PubChem PUG-REST tool class. Directly concatenates URL from the fields.endpoint template and sends requests to PubChem PUG-REST.
- _build_url(arguments: dict) str [source]ΒΆ
Use regex to replace all {placeholder} in endpoint_template to generate complete URL path. For example endpoint_template=β/compound/cid/{cid}/property/{property_list}/JSONβ arguments={βcidβ:2244}, property_list=[βMolecularWeightβ,βIUPACNameβ] β β/compound/cid/2244/property/MolecularWeight,IUPACName/JSONβ Finally returns βhttps://pubchem.ncbi.nlm.nih.gov/rest/pugβ + concatenated path.
- class tooluniverse.PubTatorTool(tool_config: Dict[str, Any])[source]ΒΆ
Bases:
BaseTool
Generic wrapper around a single PubTator 3 endpoint supporting JSON-defined configs.
- _filter_search_results(result: Dict[str, Any]) Dict[str, Any] [source]ΒΆ
Filter PubTatorSearch results by score threshold and remove facet items that only have βnameβ, βtypeβ, and βvalueβ.
- class tooluniverse.RCSBTool(tool_config)[source]ΒΆ
Bases:
BaseTool
- class tooluniverse.ReactomeRESTTool(tool_config)[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.
- _build_url(arguments: dict) str [source]ΒΆ
Combines endpoint_template (containing {xxx}) with path parameters from arguments to generate complete URL. For example endpoint_template=β/data/pathway/{stId}β, arguments={βstIdβ:βR-HSA-73817β} β Returns βhttps://reactome.org/ContentService/data/pathway/R-HSA-73817β
- 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]ΒΆ
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]ΒΆ
- _add_search_tools()[source]ΒΆ
Register AI-powered tool search and discovery functionality.
This method adds sophisticated tool discovery capabilities to the SMCP server, enabling clients to find relevant tools using natural language queries. It provides both programmatic (MCP tool) and protocol-level (tools/find method) interfaces for tool discovery.
Registered Tools:ΒΆ
- find_tools:
Primary tool discovery interface with AI-powered search capabilities.
Parameters: - query (str): Natural language description of desired functionality - categories (list, optional): Tool categories to filter by - limit (int, default=10): Maximum number of results - use_advanced_search (bool, default=True): Use AI vs keyword search
Returns: JSON string with discovered tools and search metadata
- search_tools:
Backward-compatible alias for find_tools with identical functionality. Maintained for compatibility with existing integrations.
Search Capabilities:ΒΆ
- AI-Powered Search (ToolFinderLLM):
Uses Large Language Model to understand query semantics with optimized context
Pre-filters tools using keyword matching to reduce LLM context cost
Analyzes only essential tool information (name + description) for cost efficiency
Provides relevance scoring and reasoning
Handles complex queries like βanalyze protein interactions in cancerβ
- Embedding-Based Search (Tool_RAG):
Uses vector embeddings for semantic similarity matching
Fast approximate matching for large tool collections
Good balance between speed and semantic understanding
- Keyword Search (Fallback):
Simple text matching against tool names and descriptions
Always available regardless of AI tool availability
Provides basic but reliable tool discovery
Search Strategy:ΒΆ
Preference: ToolFinderLLM (most intelligent, cost-optimized)
Fallback: Tool_RAG (semantic similarity)
Final: Simple keyword matching (always works)
Integration Details:ΒΆ
Automatically initializes available search tools during setup
Shares search logic with tools/find MCP method
Provides consistent results across different interfaces
Handles tool loading and availability detection
Error Handling:ΒΆ
Graceful degradation when AI tools unavailable
Informative error messages for debugging
Fallback mechanisms ensure search always works
Detailed logging of search method selection
Usage Examples:ΒΆ
Via MCP tool interface: ```python result = await find_tools(
query=βprotein structure predictionβ, categories=[βuniprotβ, βhpaβ], limit=5
)ΒΆ
Via tools/find MCP method: ```json {
βmethodβ: βtools/findβ, βparamsβ: {
βqueryβ: βdrug interaction analysisβ, βlimitβ: 3
}
}ΒΆ
- _add_utility_tools()[source]ΒΆ
Register essential server management and diagnostic tools.
This method adds a suite of utility tools that provide server introspection, tool management, and direct execution capabilities. These tools are essential for monitoring server health, understanding available capabilities, and providing administrative functionality.
Registered Utility Tools:ΒΆ
- get_server_info:
Comprehensive server status and capability reporting.
Returns detailed JSON with: - Server identification (name, type, version info) - Tool statistics (total tools, exposed tools, categories) - Feature flags (search enabled, FastMCP status) - Resource usage (max workers, thread pool status)
Use cases: - Health checks and monitoring - Capability discovery by clients - Debugging server configuration issues
- execute_tooluniverse_function:
Direct interface for executing ToolUniverse functions with custom parameters.
Parameters: - function_name (str): Name of the ToolUniverse tool to execute - arguments (str): JSON string containing tool parameters
Features: - Bypasses MCP tool wrappers for direct execution - Supports any loaded ToolUniverse tool - Provides detailed error reporting - Uses thread pool for non-blocking execution
Use cases: - Administrative tool execution - Debugging tool behavior - Custom automation scripts
- list_available_tooluniverse_tools:
Comprehensive inventory of all available ToolUniverse tools.
Returns: - Complete tool catalog with names, descriptions, types - Parameter schemas and requirements for each tool - Tool statistics and categorization
Use cases: - Tool discovery and exploration - Documentation generation - Client capability mapping - Integration planning
Implementation Details:ΒΆ
- Error Handling:
Each tool includes comprehensive try-catch blocks
Detailed error messages with context information
Graceful degradation when tools or data unavailable
JSON-formatted error responses for consistency
- Thread Safety:
All tools use async execution patterns
Thread pool executor for CPU-intensive operations
Proper resource cleanup and management
Non-blocking I/O for network operations
- Security Considerations:
execute_tooluniverse_function provides direct tool access
JSON parsing with proper validation
No file system access beyond ToolUniverse scope
Appropriate error message sanitization
- Performance Optimization:
Lazy loading of tool information
Caching where appropriate
Minimal memory footprint
Efficient JSON serialization
Examples:ΒΆ
Server health check: ```python info = await get_server_info() status = json.loads(info) if status[βtotal_tooluniverse_toolsβ] > 0:
# Server healthy pass
Direct tool execution: ```python result = await execute_tooluniverse_function(
function_name=βUniProt_get_entry_by_accessionβ, arguments=β{βaccessionβ: βP05067β}β
)ΒΆ
Tool inventory:
`python tools = await list_available_tooluniverse_tools() catalog = json.loads(tools) # Available: {catalog['total_tools']} tools `
- _create_mcp_tool_from_tooluniverse(tool_config: Dict[str, Any])[source]ΒΆ
Create an MCP tool from a ToolUniverse tool configuration.
This method creates a function with proper parameter signatures that match the ToolUniverse tool schema, enabling FastMCPβs automatic parameter validation.
- async _custom_handle_request(request: Dict[str, Any]) Dict[str, Any] [source]ΒΆ
Custom MCP request handler that supports enhanced scientific tool operations.
This handler intercepts MCP requests and provides specialized handling for scientific tool discovery methods while maintaining full compatibility with standard MCP protocol operations.
Parameters:ΒΆ
- requestdict
JSON-RPC 2.0 request object containing: - method: The MCP method being called - id: Request identifier for response correlation - params: Method-specific parameters
Returns:ΒΆ
- dict
JSON-RPC 2.0 response object with either: - result: Successful operation result - error: Error information with code and message
Supported Custom Methods:ΒΆ
- tools/find:
Search for tools using natural language queries with AI-powered recommendations. Parameters: - query (required): Natural language description of desired functionality - categories (optional): List of tool categories to filter by - limit (optional): Maximum number of results (default: 10) - use_advanced_search (optional): Use AI vs keyword search (default: True) - search_method (optional): Specific search method - βautoβ, βllmβ, βembeddingβ, βkeywordβ (default: βautoβ) - format (optional): Response format - βdetailedβ or βmcp_standardβ
- tools/search:
Alias for tools/find method with identical parameters and behavior.
- Standard MCP Methods:
All other methods are forwarded to the original FastMCP handler, ensuring full compatibility with MCP specification.
Error Codes:ΒΆ
-32601: Method not found (unknown method)
-32602: Invalid params (missing required parameters)
-32603: Internal error (server-side failures)
Examples:ΒΆ
Request for tool discovery: ```json {
βjsonrpcβ: β2.0β, βidβ: βsearch_123β, βmethodβ: βtools/findβ, βparamsβ: {
βqueryβ: βprotein structure analysisβ, βlimitβ: 5, βformatβ: βmcp_standardβ
}
}ΒΆ
Successful response: ```json {
βjsonrpcβ: β2.0β, βidβ: βsearch_123β, βresultβ: {
βtoolsβ: [β¦], β_metaβ: {
βsearch_queryβ: βprotein structure analysisβ, βsearch_methodβ: βAI-powered (ToolFinderLLM)β, βtotal_matchesβ: 5
}
}
}ΒΆ
- _expose_tooluniverse_tools()[source]ΒΆ
Automatically expose ToolUniverse tools as MCP-compatible tools.
This method performs the critical task of converting ToolUniverseβs tool definitions into FastMCP-compatible tools that can be called via the MCP protocol. It handles the complex mapping between different tool formats while ensuring compatibility and usability.
Process Overview:ΒΆ
Tool Inventory: Enumerate all loaded ToolUniverse tools
Type Filtering: Skip meta-tools that shouldnβt be exposed
Schema Conversion: Transform ToolUniverse schemas to MCP format
Function Wrapping: Create async wrappers for tool execution
Registration: Register tools with FastMCP framework
Tool Type Filtering:ΒΆ
Skips these internal tool types: - MCPAutoLoaderTool: Used for loading other MCP servers - MCPClientTool: Used for connecting to external MCP servers
These are meta-tools that manage other tools rather than providing end-user functionality, so theyβre excluded from the MCP interface.
Schema Transformation:ΒΆ
ToolUniverse Tool Format: ```json {
βnameβ: βtool_nameβ, βparameterβ: {
βtypeβ: βobjectβ, βpropertiesβ: {β¦}, βrequiredβ: [β¦]
}
}ΒΆ
MCP Tool Format: ```python async def tool_function(arguments: str = β{}β) -> str:
# Tool execution logic
Execution Model:ΒΆ
JSON Arguments: All tools accept a single βargumentsβ parameter containing JSON-encoded tool parameters
Async Execution: Tools run in thread pool to prevent blocking
Error Handling: Comprehensive error catching and reporting
Type Safety: Proper argument parsing and validation
Duplicate Prevention:ΒΆ
Tracks exposed tools in self._exposed_tools set
Prevents re-registration of already exposed tools
Handles tool reloading scenarios gracefully
Error Recovery:ΒΆ
Individual tool failures donβt stop the entire process
Detailed error logging for debugging
Continues with remaining tools if some fail to convert
Performance Optimization:ΒΆ
Lazy evaluation of tool schemas
Minimal memory footprint per tool
Efficient tool lookup and execution
Thread pool reuse for all tool executions
Examples:ΒΆ
Original ToolUniverse tool call: ```python tu.run_one_function({
βnameβ: βUniProt_get_entry_by_accessionβ, βargumentsβ: {βaccessionβ: βP05067β}
})ΒΆ
Equivalent MCP tool call:
`python await tool_function('{"accession": "P05067"}') `
- _get_valid_categories()[source]ΒΆ
Get valid tool categories from ToolUniverse.
- Returns:
Set of valid tool category names
- Return type:
Set[str]
- async _handle_tools_find(request_id: str, params: Dict[str, Any]) Dict[str, Any] [source]ΒΆ
Handle the tools/find MCP method for AI-powered tool discovery.
This method implements the core functionality for the custom tools/find MCP method, enabling clients to discover relevant scientific tools using natural language queries. It supports both AI-powered semantic search and simple keyword matching.
Parameters:ΒΆ
- request_idstr
Unique identifier for this request, used in the JSON-RPC response
- paramsdict
Request parameters containing: - query (required): Natural language description of desired functionality - categories (optional): List of tool categories to filter results - limit (optional): Maximum number of tools to return (default: 10) - use_advanced_search (optional): Whether to use AI search (default: True) - search_method (optional): Specific search method - βautoβ, βllmβ, βembeddingβ, βkeywordβ (default: βautoβ) - format (optional): Response format - βdetailedβ or βmcp_standardβ (default: βdetailedβ)
Returns:ΒΆ
- dict
JSON-RPC 2.0 response containing either: - Success: Result with discovered tools and metadata - Error: Error object with appropriate code and message
Response Formats:ΒΆ
- Detailed Format (default):
Returns comprehensive tool information including: - Tool names, descriptions, types - Parameter schemas with detailed property information - Search metadata (query, method used, match count)
- MCP Standard Format:
Returns tools in standard MCP tools/list format: - Simplified tool schema compatible with MCP clients - inputSchema formatted for direct MCP consumption - Metadata included in separate _meta field
Search Methods:ΒΆ
- AI-Powered Search (ToolFinderLLM):
Uses Large Language Model to understand query semantics
Analyzes tool descriptions for intelligent matching
Provides relevance scoring and reasoning
Automatically used when available and use_advanced_search=True
- Simple Keyword Search:
Basic text matching against tool names and descriptions
Case-insensitive substring matching
Used as fallback or when use_advanced_search=False
Error Handling:ΒΆ
Validates required parameters (query must be provided)
Handles search failures gracefully with informative messages
Provides detailed error context for debugging
Examples:ΒΆ
Basic protein analysis search: ```python params = {
βqueryβ: βprotein structure analysisβ, βlimitβ: 3
}ΒΆ
Category-filtered drug search: ```python params = {
βqueryβ: βdrug interactionsβ, βcategoriesβ: [βChEMBLβ, βfda_drug_labelβ], βlimitβ: 5, βformatβ: βmcp_standardβ
}ΒΆ
- _init_tool_finder()[source]ΒΆ
Initialize intelligent tool discovery system with automatic fallback.
This method sets up the tool finder infrastructure that powers AI-driven tool discovery. It implements a tiered approach, trying the most advanced search methods first and falling back to simpler methods if needed.
Initialization Strategy:ΒΆ
- Phase 1 - Detection:
Scans loaded ToolUniverse tools to identify available search tools: - ToolFinderLLM: Advanced LLM-based semantic search - Tool_RAG: Embedding-based similarity search
- Phase 2 - Loading (if needed):
If no search tools are found, attempts to load them: - Loads βtool_finder_llmβ and βtool_finderβ categories - Re-scans for available tools after loading
- Phase 3 - Selection:
Selects the best available search method: 1. ToolFinderLLM (preferred - most intelligent) 2. Tool_RAG (fallback - good semantic understanding) 3. Simple keyword search (always available)
Tool Finder Capabilities:ΒΆ
- ToolFinderLLM:
Uses GPT-4 or similar LLM for query understanding
Analyzes tool descriptions for semantic matching
Provides relevance scoring and selection reasoning
Handles complex, multi-faceted queries effectively
Best for: βFind tools to analyze protein-drug interactions in cancer researchβ
- Tool_RAG:
Uses pre-computed embeddings for fast similarity search
Good semantic understanding without LLM overhead
Faster than LLM-based search for simple queries
Best for: βprotein analysisβ, βdrug discoveryβ
- Simple Search:
Basic keyword matching against names and descriptions
No dependencies, always available
Fast and reliable for exact term matches
Best for: βchemblβ, βuniprotβ, βfdaβ
Configuration Management:ΒΆ
Sets instance attributes: - tool_finder_available (bool): Whether advanced search is available - tool_finder_type (str): Type of search tool loaded (βToolFinderLLMβ | βTool_RAGβ)
Error Handling:ΒΆ
Handles missing dependencies gracefully
Provides informative console output about search capabilities
Ensures search functionality always works (via simple fallback)
Logs detailed information for debugging
Performance Considerations:ΒΆ
Tool loading only happens if search tools arenβt already available
Search tool detection is cached to avoid repeated scans
ToolFinderLLM requires network access and API keys
Tool_RAG requires embedding files but works offline
Dependencies:ΒΆ
ToolFinderLLM: Requires OpenAI API access or compatible endpoint
Tool_RAG: Requires sentence-transformers and embedding data
Simple search: No external dependencies
- async _perform_tool_search(query: str, categories: List[str] | None, limit: int, use_advanced_search: bool, search_method: str = 'auto') str [source]ΒΆ
Execute tool search using the most appropriate search method available.
Simplified unified interface that leverages the consistent tool interfaces. All search tools now return JSON format directly.
Parameters:ΒΆ
- querystr
Natural language query describing the desired tool functionality
- categorieslist of str, optional
Tool categories to filter results by
- limitint
Maximum number of tools to return
- use_advanced_searchbool
Whether to prefer AI-powered search when available
- search_methodstr, default βautoβ
Specific search method: βautoβ, βllmβ, βembeddingβ, βkeywordβ
Returns:ΒΆ
- str
JSON string containing search results
- _register_custom_mcp_methods()[source]ΒΆ
Register custom MCP protocol methods for enhanced functionality.
This method extends the standard MCP protocol by registering custom handlers for scientific tool discovery and search operations. It safely patches the FastMCP request handler to support additional methods while maintaining compatibility with standard MCP operations.
Custom Methods Registered:ΒΆ
tools/find: AI-powered tool discovery using natural language queries
tools/search: Alternative endpoint for tool search (alias for tools/find)
Implementation Details:ΒΆ
Preserves original FastMCP request handler for standard methods
Uses method interception pattern to handle custom methods first
Falls back to original handler for unrecognized methods
Implements proper error handling and JSON-RPC 2.0 compliance
Error Handling:ΒΆ
Gracefully handles missing request handlers
Logs warnings for debugging when handler patching fails
Ensures server continues to function even if custom methods fail to register
Notes:ΒΆ
This method is called automatically during SMCP initialization and should not be called manually. It uses a guard to prevent double-patching.
- _select_search_tool(search_method: str, use_advanced_search: bool) str [source]ΒΆ
Select the appropriate search tool based on method and availability.
- Returns:
Tool name to use for search
- Return type:
- _setup_smcp_tools()[source]ΒΆ
Initialize and configure SMCP-specific tools and features.
This method orchestrates the complete setup of SMCP functionality including ToolUniverse tool loading, validation, automatic tool exposure to the MCP interface, search functionality initialization, and utility tool registration.
The setup process is designed to be robust, handle various edge cases gracefully, and provide informative feedback about the configuration process. It implements intelligent fallback strategies to ensure functionality even when specific components are unavailable.
Setup Process Overview:ΒΆ
Tool Loading Assessment: Check if ToolUniverse already has tools loaded to avoid unnecessary reloading and potential conflicts
Category Validation: If specific categories are requested, validate them against available categories and provide helpful feedback for invalid ones
Tool Loading Strategy: Load tools using the most appropriate method: - Category-specific loading for focused deployments - Full loading for comprehensive access - Graceful fallback when category loading fails
Tool Exposure: Convert loaded ToolUniverse tools to MCP format with proper schema transformation and execution wrapping
Search Setup: Initialize multi-tiered search capabilities including AI-powered and fallback methods
Utility Registration: Add server management and diagnostic tools
Tool Loading Strategy:ΒΆ
Already Loaded Check: If ToolUniverse already contains loaded tools (len(all_tools) > 0), skip the loading phase to prevent duplication and preserve existing configuration. This supports scenarios where users pre-configure ToolUniverse instances.
Category-Specific Loading: When tool_categories is specified: - Validate each category against available tool categories - Log warnings for invalid categories with suggestions - Load only valid categories to optimize performance - Fall back to full loading if no valid categories remain
Full Loading (Default): When auto_expose_tools=True and no specific categories are requested, load all available tools to provide comprehensive functionality.
Graceful Fallback: If category-specific loading fails for any reason, automatically fall back to loading all tools to ensure basic functionality.
Tool Exposure Process:ΒΆ
Schema Transformation: - Convert ToolUniverse parameter schemas to MCP-compatible format - Handle complex parameter types and validation rules - Preserve documentation and examples where available
Execution Wrapping: - Create async wrappers for synchronous ToolUniverse tools - Implement proper error handling and result formatting - Use thread pool execution to prevent blocking
Safety Mechanisms: - Skip meta-tools (MCPAutoLoaderTool, MCPClientTool) that shouldnβt be exposed - Track exposed tools to prevent duplicates - Handle tool conversion failures gracefully without stopping entire process
Search Setup:ΒΆ
Multi-Tiered Search Architecture: 1. ToolFinderLLM (Primary): Cost-optimized AI-powered semantic understanding using LLM 2. Tool_RAG (Secondary): Embedding-based similarity search 3. Keyword Search (Fallback): Simple text matching, always available
Initialization Process: - Check for availability of advanced search tools in loaded tools - Attempt to load search tools if not already present - Configure search capabilities based on whatβs available - Provide clear feedback about search capabilities
Search Tool Loading: Attempts to load tool_finder_llm and tool_finder categories which include: - ToolFinderLLM: Cost-optimized LLM-based intelligent tool discovery - Tool_RAG: Embedding-based semantic search - Supporting utilities and configuration tools
Error Handling:ΒΆ
Category Validation Errors: - Log specific invalid categories with available alternatives - Continue with valid categories only - Fall back to full loading if no valid categories
Tool Loading Errors: - Log detailed error information for debugging - Continue setup process with already loaded tools - Ensure server remains functional even with partial failures
Search Setup Errors: - Gracefully handle missing search tool dependencies - Fall back to simpler search methods automatically - Log informative messages about search capabilities
Tool Exposure Errors: - Handle individual tool conversion failures without stopping process - Log specific tool errors for debugging - Continue with remaining tools to maximize functionality
Performance Considerations:ΒΆ
Lazy Loading: Only load tools when needed to minimize startup time
Efficient Validation: Quick category checks before expensive operations
Parallel Processing: Use thread pools for tool conversion where possible
Memory Management: Efficient tool representation and storage
Diagnostic Output:ΒΆ
Provides informative logging throughout the setup process:
` Tools already loaded in ToolUniverse (356 tools), skipping reload Exposing 356 tools from ToolUniverse β ToolFinderLLM (cost-optimized) available for advanced search Exposed tool: UniProt_get_entry_by_accession (type: uniprot) `
Notes:ΒΆ
This method is called automatically during SMCP initialization
Should not be called manually after server initialization
Setup is idempotent - can be called multiple times safely
All setup phases include comprehensive error handling
Performance scales with the number of tools being loaded and exposed
- add_custom_tool(name: str, function: Callable, description: str | None = None, **kwargs)[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: ```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: ```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: ```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]ΒΆ
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): ```python server = SMCP(βMy Serverβ) try:
server.run_simple() # Cleanup happens automatically on exit
- except KeyboardInterrupt:
pass # run_simple() handles cleanup
Manual Cleanup: ```python server = SMCP(βMy Serverβ) try:
# Custom server logic here pass
- finally:
await server.close() # Explicit cleanup
Context Manager Pattern: ```python async with SMCP(βMy Serverβ) as server:
# Server operations pass
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]ΒΆ
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:ΒΆ
Initialization Summary: Displays server configuration and capabilities
Transport Setup: Configures selected communication method
Service Start: Begins listening for client connections
Graceful Shutdown: Handles interrupts and cleanup
Deployment Scenarios:ΒΆ
Development & Testing:
`python server = SMCP(name="Dev Server") server.run_simple(transport="stdio") # For CLI testing `
Local Web Service:
`python server = SMCP(name="Local API") server.run_simple(transport="http", host="127.0.0.1", port=8000) `
Production Service: ```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:
`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
- class tooluniverse.SearchSPLTool(tool_config)[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).
- class tooluniverse.SemanticScholarTool(tool_config, base_url='https://api.semanticscholar.org/graph/v1/paper/search')[source]ΒΆ
Bases:
BaseTool
Tool to search for papers on Semantic Scholar including abstracts.
- class tooluniverse.ToolFinderEmbedding(tool_config, tooluniverse)[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ΒΆ
The loaded sentence transformer model
- Type:
SentenceTransformer
- tool_desc_embeddingΒΆ
Cached embeddings of tool descriptions
- Type:
torch.Tensor
- tooluniverseΒΆ
Reference to the tool universe containing all tools
- __init__(tool_config, tooluniverse)[source]ΒΆ
Initialize the ToolFinderEmbedding with configuration and RAG model.
- Parameters:
tool_config (dict) β Configuration dictionary for the tool
- find_tools(message=None, picked_tool_names=None, rag_num=5, return_call_result=False, categories=None)[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:
- Raises:
AssertionError β If both message and picked_tool_names are None
- load_rag_model()[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]ΒΆ
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]ΒΆ
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:
- Returns:
List of top-k tool names ranked by relevance to the query
- Return type:
- Raises:
SystemExit β If tool_desc_embedding is not loaded
- run(arguments)[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.ToolFinderKeyword(tool_config, tooluniverse=None)[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.
- 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', '')]ΒΆ
- 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'}ΒΆ
- __init__(tool_config, tooluniverse=None)[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
- _apply_stemming(word: str) str [source]ΒΆ
Apply basic stemming rules to reduce words to their root form.
- _build_tool_index(tools: List[Dict]) None [source]ΒΆ
Build TF-IDF index for all tools to enable efficient relevance scoring.
- Parameters:
tools (List[Dict]) β List of tool configurations
- _calculate_exact_match_bonus(query: str, tool: Dict) float [source]ΒΆ
Calculate bonus score for exact matches in tool name or key phrases.
- _calculate_tfidf_score(query_terms: List[str], tool_name: str) float [source]ΒΆ
Calculate TF-IDF relevance score for a tool given query terms.
- _extract_parameter_text(parameter_schema: Dict) List[str] [source]ΒΆ
Extract searchable text from parameter schema.
- Parameters:
parameter_schema (Dict) β Tool parameter schema
- Returns:
List of text elements from parameters
- Return type:
List[str]
- _extract_phrases(tokens: List[str], max_phrase_length: int = 3) List[str] [source]ΒΆ
Extract meaningful phrases from tokens for better semantic matching.
- _run_json_search(arguments)[source]ΒΆ
Original JSON-based search implementation for backward compatibility.
- _tokenize_and_normalize(text: str) List[str] [source]ΒΆ
Tokenize text and apply normalization including stop word removal and stemming.
- find_tools(message=None, picked_tool_names=None, rag_num=5, return_call_result=False, categories=None)[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:
- Raises:
AssertionError β If both message and picked_tool_names are None
- run(arguments)[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:
- class tooluniverse.ToolFinderLLM(tool_config, tooluniverse=None)[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]ΒΆ
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
- _format_as_json(result, query, limit, categories, return_call_result)[source]ΒΆ
Format the find_tools result as a standardized JSON string.
- Parameters:
result β Result from find_tools method (either string, list, or tuple)
query β Original search query
limit β Requested number of tools
categories β Requested categories filter
return_call_result β Whether return_call_result was True
- Returns:
JSON formatted search results
- Return type:
- _format_tools_for_prompt(tools)[source]ΒΆ
Format tools for inclusion in the LLM prompt with minimal information to reduce context cost. Only includes name and description to minimize token usage.
- _get_available_tools(force_refresh=False)[source]ΒΆ
Get available tools with their descriptions, with caching.
- _get_tool_selection_prompt()[source]ΒΆ
Get the prompt template for tool selection. Optimized for minimal token usage.
- _prefilter_tools_by_keywords(available_tools, query, max_tools=100)[source]ΒΆ
Pre-filter tools using keyword matching to reduce context size before LLM processing.
- find_tools(message=None, picked_tool_names=None, rag_num=5, return_call_result=False, categories=None, return_list_only=None)[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:
- Raises:
AssertionError β If both message and picked_tool_names are None
- find_tools_legacy(query, limit=5, include_reasoning=False, return_format='prompts')[source]ΒΆ
Legacy method for finding tools with different parameter names.
This provides backward compatibility for any code that might use βqueryβ instead of βdescriptionβ.
- find_tools_llm(query, limit=5, include_reasoning=False, categories=None)[source]ΒΆ
Find relevant tools using LLM-based selection.
- Parameters:
- Returns:
Dictionary containing selected tools and metadata
- Return type:
- run(arguments)[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
- class tooluniverse.ToolUniverse(tool_files={'ChEMBL': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/chembl_tools.json', 'EFO': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/efo_tools.json', 'Enrichr': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/enrichr_tools.json', 'EuropePMC': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/europe_pmc_tools.json', 'HumanBase': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/humanbase_tools.json', 'OpenAlex': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/openalex_tools.json', 'admetai': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/admetai_tools.json', 'adverse_event': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/adverse_event_tools.json', 'agents': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/agentic_tools.json', 'alphafold': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/alphafold_tools.json', 'clinical_trials': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/clinicaltrials_gov_tools.json', 'compose': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/compose_tools.json', 'dailymed': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/dailymed_tools.json', 'dataset': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/dataset_tools.json', 'disease_target_score': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/disease_target_score_tools.json', 'embedding': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/embedding_tools.json', 'fda_drug_adverse_event': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/fda_drug_adverse_event_tools.json', 'fda_drug_label': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/fda_drug_labeling_tools.json', 'go': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/gene_ontology_tools.json', 'gwas': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/gwas_tools.json', 'hpa': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/hpa_tools.json', 'idmap': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/idmap_tools.json', 'mcp_auto_loader_boltz': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/boltz_tools.json', 'mcp_auto_loader_expert_feedback': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/expert_feedback_tools.json', 'mcp_auto_loader_txagent': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/txagent_client_tools.json', 'mcp_auto_loader_uspto_downloader': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/uspto_downloader_tools.json', 'medlineplus': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/medlineplus_tools.json', 'monarch': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/monarch_tools.json', 'odphp': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/odphp_tools.json', 'opentarget': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/opentarget_tools.json', 'output_summarization': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/output_summarization_tools.json', 'pubchem': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/pubchem_tools.json', 'pubtator': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/pubtator_tools.json', 'rcsb_pdb': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/rcsb_pdb_tools.json', 'reactome': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/reactome_tools.json', 'semantic_scholar': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/semantic_scholar_tools.json', 'software_bioinformatics': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/packages/bioinformatics_core_tools.json', 'software_cheminformatics': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/packages/cheminformatics_tools.json', 'software_earth_sciences': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/packages/earth_sciences_tools.json', 'software_genomics': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/packages/genomics_tools.json', 'software_image_processing': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/packages/image_processing_tools.json', 'software_machine_learning': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/packages/machine_learning_tools.json', 'software_neuroscience': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/packages/neuroscience_tools.json', 'software_physics_astronomy': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/packages/physics_astronomy_tools.json', 'software_scientific_computing': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/packages/scientific_computing_tools.json', 'software_single_cell': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/packages/single_cell_tools.json', 'software_structural_biology': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/packages/structural_biology_tools.json', 'software_visualization': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/packages/visualization_tools.json', 'special_tools': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/special_tools.json', 'tool_composition': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/tool_composition_tools.json', 'tool_finder': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/finder_tools.json', 'uniprot': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/uniprot_tools.json', 'url': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/url_fetch_tools.json', 'uspto': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/uspto_tools.json', 'xml': '/home/runner/work/ToolUniverse/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]ΒΆ
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.
- __init__(tool_files={'ChEMBL': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/chembl_tools.json', 'EFO': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/efo_tools.json', 'Enrichr': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/enrichr_tools.json', 'EuropePMC': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/europe_pmc_tools.json', 'HumanBase': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/humanbase_tools.json', 'OpenAlex': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/openalex_tools.json', 'admetai': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/admetai_tools.json', 'adverse_event': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/adverse_event_tools.json', 'agents': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/agentic_tools.json', 'alphafold': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/alphafold_tools.json', 'clinical_trials': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/clinicaltrials_gov_tools.json', 'compose': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/compose_tools.json', 'dailymed': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/dailymed_tools.json', 'dataset': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/dataset_tools.json', 'disease_target_score': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/disease_target_score_tools.json', 'embedding': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/embedding_tools.json', 'fda_drug_adverse_event': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/fda_drug_adverse_event_tools.json', 'fda_drug_label': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/fda_drug_labeling_tools.json', 'go': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/gene_ontology_tools.json', 'gwas': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/gwas_tools.json', 'hpa': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/hpa_tools.json', 'idmap': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/idmap_tools.json', 'mcp_auto_loader_boltz': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/boltz_tools.json', 'mcp_auto_loader_expert_feedback': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/expert_feedback_tools.json', 'mcp_auto_loader_txagent': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/txagent_client_tools.json', 'mcp_auto_loader_uspto_downloader': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/uspto_downloader_tools.json', 'medlineplus': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/medlineplus_tools.json', 'monarch': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/monarch_tools.json', 'odphp': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/odphp_tools.json', 'opentarget': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/opentarget_tools.json', 'output_summarization': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/output_summarization_tools.json', 'pubchem': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/pubchem_tools.json', 'pubtator': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/pubtator_tools.json', 'rcsb_pdb': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/rcsb_pdb_tools.json', 'reactome': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/reactome_tools.json', 'semantic_scholar': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/semantic_scholar_tools.json', 'software_bioinformatics': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/packages/bioinformatics_core_tools.json', 'software_cheminformatics': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/packages/cheminformatics_tools.json', 'software_earth_sciences': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/packages/earth_sciences_tools.json', 'software_genomics': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/packages/genomics_tools.json', 'software_image_processing': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/packages/image_processing_tools.json', 'software_machine_learning': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/packages/machine_learning_tools.json', 'software_neuroscience': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/packages/neuroscience_tools.json', 'software_physics_astronomy': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/packages/physics_astronomy_tools.json', 'software_scientific_computing': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/packages/scientific_computing_tools.json', 'software_single_cell': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/packages/single_cell_tools.json', 'software_structural_biology': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/packages/structural_biology_tools.json', 'software_visualization': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/packages/visualization_tools.json', 'special_tools': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/special_tools.json', 'tool_composition': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/tool_composition_tools.json', 'tool_finder': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/finder_tools.json', 'uniprot': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/uniprot_tools.json', 'url': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/url_fetch_tools.json', 'uspto': '/home/runner/work/ToolUniverse/ToolUniverse/src/tooluniverse/data/uspto_tools.json', 'xml': '/home/runner/work/ToolUniverse/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]ΒΆ
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.
- _check_api_key_requirements(tool_config)[source]ΒΆ
Check if a toolβs required API keys are available. Also supports optional_api_keys where at least one key from the list must be available.
- _create_hook_config_from_type(hook_type)[source]ΒΆ
Create hook configuration from simple hook_type parameter.
- _filter_and_deduplicate_tools(exclude_tools_set, include_tools_set, include_tool_types_set=None, exclude_tool_types_set=None)[source]ΒΆ
Filter tools based on inclusion/exclusion criteria and remove duplicates.
- Parameters:
exclude_tools_set (set) β Set of tool names to exclude
include_tools_set (set or None) β Set of tool names to include (if None, include all)
include_tool_types_set (set or None) β Set of tool types to include (if None, include all)
exclude_tool_types_set (set or None) β Set of tool types to exclude (if None, exclude none)
- _load_auto_discovered_configs()[source]ΒΆ
Load auto-discovered configs from the decorator registry.
This method loads tool configurations that were registered automatically via the @register_tool decorator with config parameter.
- _load_tool_names_from_file(file_path)[source]ΒΆ
Load tool names from a text file (one tool name per line).
- _load_tools_from_mcp_server(server_url: str, config: Dict[str, Any]) Dict[str, Any] ΒΆ
Load tools from a specific MCP server.
- _process_mcp_auto_loaders()[source]ΒΆ
Process any MCPAutoLoaderTool instances to automatically discover and register MCP tools.
This method scans through all loaded tools for MCPAutoLoaderTool instances and runs their auto-discovery process to find and register MCP tools from configured servers. It handles async operations properly with cleanup and error handling.
- Side Effects:
May add new tools to the tool registry
Prints debug information about the discovery process
Updates tool counts after MCP registration
- _scan_all_json_files()[source]ΒΆ
Recursively scan all JSON files in the data directory and its subdirectories.
- Returns:
- (all_tools, all_tool_names) where all_tools is a list of tool configs
and all_tool_names is a set of tool names for deduplication
- Return type:
- _scan_predefined_files()[source]ΒΆ
Scan predefined tool files (original behavior).
- Returns:
- (all_tools, all_tool_names) where all_tools is a list of tool configs
and all_tool_names is a set of tool names for deduplication
- Return type:
- call_id_gen()[source]ΒΆ
Generate a random call ID for function calls.
- Returns:
A random 9-character string composed of letters and digits.
- Return type:
- check_function_call(fcall_str, function_config=None, format='llama')[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:
- 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:
- discover_mcp_tools(server_urls: List[str] | None = None, **kwargs) Dict[str, Any] ΒΆ
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:ΒΆ
# 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β]}β)
- export_tool_names(output_file, category_filter=None)[source]ΒΆ
Export tool names to a text file (one per line).
- extract_function_call_json(lst, return_message=False, verbose=True, format='llama')[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:
- filter_tool_lists(tool_name_list, tool_desc_list, include_names=None, exclude_names=None, include_categories=None, exclude_categories=None)[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:
- find_tools_by_pattern(pattern, search_in='name', case_sensitive=False)[source]ΒΆ
Find tools matching a pattern in their name or description.
- force_full_discovery()[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:
- generate_env_template(all_missing_keys, output_file: str = '.env.template')[source]ΒΆ
Generate a template .env file with all required API keys
- get_available_tools(category_filter=None, name_only=True)[source]ΒΆ
Get available tools, optionally filtered by category.
- get_lazy_loading_status()[source]ΒΆ
Get information about lazy loading status and available tools.
- Returns:
Dictionary with lazy loading status and tool counts
- Return type:
- get_one_tool_by_one_name(tool_name, return_prompt=True)[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.
- get_tool_by_name(tool_names, format='default')[source]ΒΆ
Retrieve tool configurations by their names.
- Parameters:
- Returns:
- List of tool configurations for the specified names.
Tools not found will be reported but not included in the result.
- Return type:
- get_tool_description(tool_name)[source]ΒΆ
Get the description of a tool by its name.
This is a convenience method that calls get_one_tool_by_one_name.
- get_tool_specification_by_names(tool_names, format='default')[source]ΒΆ
Retrieve tool specifications by their names using tool_specification method.
- Parameters:
- Returns:
- List of tool specifications for the specified names.
Tools not found will be reported but not included in the result.
- Return type:
- get_tool_types()[source]ΒΆ
Get the types of tools available in the tool files.
- Returns:
A list of tool type names (category keys).
- Return type:
- init_tool(tool=None, tool_name=None, add_to_cache=True)[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:
- Returns:
Initialized tool instance.
- Return type:
- Raises:
KeyError β If the tool type is not found in tool_type_mappings.
- list_built_in_tools(mode='config', scan_all=False)[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:
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
- list_mcp_connections() Dict[str, Any] ΒΆ
List all active MCP connections and loaded tools.
Returns:ΒΆ
- dict
Information about MCP connections, auto-loaders, and loaded tools
Examples:ΒΆ
```python 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)ΒΆ
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:
[βhttp://localhost:8001β, βhttp://analysis-server:8002β]
[βws://localhost:9000β] # WebSocket MCP servers
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: ```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: ```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:
`python # If you have registered MCP tools locally, auto-discover their servers tu.load_mcp_tools() # Uses servers from mcp_tool_registry `
- 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]ΒΆ
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β}
)
- load_tools_from_names_list(tool_names, clear_existing=True)[source]ΒΆ
Load only specific tools by their names.
- prepare_one_tool_prompt(tool)[source]ΒΆ
Prepare a single tool configuration for prompt usage by filtering to essential keys.
- prepare_tool_examples(tool_list)[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.
- refresh_tool_name_desc(enable_full_desc=False, include_names=None, exclude_names=None, include_categories=None, exclude_categories=None)[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:
- register_custom_tool(tool_class, tool_name=None, tool_config=None)[source]ΒΆ
Register a custom tool class at runtime.
- remove_keys(tool_list, invalid_keys)[source]ΒΆ
Remove specified keys from a list of tool configurations.
- return_all_loaded_tools()[source]ΒΆ
Return a deep copy of all loaded tools.
- Returns:
A deep copy of the all_tools list to prevent external modification.
- Return type:
- run(fcall_str, return_message=False, verbose=True, format='llama')[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:
- run_one_function(function_call_json)[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.
- select_tools(include_names=None, exclude_names=None, include_categories=None, exclude_categories=None)[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:
- toggle_hooks(enabled: bool)[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
- tool_specification(tool_name, return_prompt=False, format='default')[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
- class tooluniverse.URLHTMLTagTool(tool_config)[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β: ββ¦β}
- class tooluniverse.URLToPDFTextTool(tool_config)[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β: ββ¦β}
- class tooluniverse.USPTOOpenDataPortalTool(tool_config, api_key=None, base_url='https://api.uspto.gov/api/v1')[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]ΒΆ
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.
- assign_by_path(d, path, value)[source]ΒΆ
Create nested dicts for a dotβpath and set the final key to value.
- run(arguments)[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.UniProtRESTTool(tool_config: Dict)[source]ΒΆ
Bases:
BaseTool
- class tooluniverse.XMLDatasetTool(tool_config: Dict[str, Any])[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.
- _extract_field_value(element: Element, xpath_expr: str) str [source]ΒΆ
Extract field value using XPath expression.
- _extract_record_data(record_element: Element) Dict[str, Any] [source]ΒΆ
Extract data from a record element with caching.
- _filter(arguments: Dict[str, Any]) Dict[str, Any] [source]ΒΆ
Filter records based on field criteria.
- _find_matches(record_data: Dict[str, Any], search_query: str, search_fields: List[str], case_sensitive: bool, exact_match: bool) List[str] [source]ΒΆ
Find matching fields in a record.
- _get_filter_description(field: str, condition: str, value: str) str [source]ΒΆ
Get human-readable filter description.
- _get_filter_function(condition: str, value: str)[source]ΒΆ
Get the appropriate filter function for the condition.
- _get_searchable_value(record_data: Dict[str, Any], field: str, case_sensitive: bool) str [source]ΒΆ
Get searchable string value for a field.
- _is_match(field_value: str, search_query: str, exact_match: bool) bool [source]ΒΆ
Check if field value matches search query.
- _search(arguments: Dict[str, Any]) Dict[str, Any] [source]ΒΆ
Search records by text content across multiple fields.
- tooluniverse.create_smcp_server(name: str = 'SMCP Server', tool_categories: List[str] | None = None, search_enabled: bool = True, **kwargs) SMCP [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):
`python server = create_smcp_server("Research Server") server.run_simple() `
Focused Server (specific domains): ```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: ```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: ```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: ```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
- tooluniverse.register_tool(tool_type_name=None, config=None)[source]ΒΆ
Decorator to automatically register tool classes and their configs.
- Usage:
@register_tool(βCustomToolNameβ, config={β¦}) class MyTool:
pass
SubpackagesΒΆ
SubmodulesΒΆ
- tooluniverse.agentic_tool module
AgenticTool
AgenticTool.__init__()
AgenticTool._format_prompt()
AgenticTool._get_global_fallback_chain()
AgenticTool._try_api()
AgenticTool._try_initialize_api()
AgenticTool._validate_arguments()
AgenticTool._validate_model_config()
AgenticTool.estimate_token_usage()
AgenticTool.get_availability_status()
AgenticTool.get_input_arguments()
AgenticTool.get_model_info()
AgenticTool.get_prompt_preview()
AgenticTool.get_prompt_template()
AgenticTool.has_any_api_keys()
AgenticTool.is_available()
AgenticTool.retry_initialization()
AgenticTool.run()
AgenticTool.validate_configuration()
- tooluniverse.base_tool module
- tooluniverse.chem_tool module
- tooluniverse.ctg_tool module
- tooluniverse.dataset_tool module
- tooluniverse.efo_tool module
- tooluniverse.enrichr_tool module
- tooluniverse.europe_pmc_tool module
- tooluniverse.execute_function module
ToolUniverse
ToolUniverse.all_tools
ToolUniverse.all_tool_dict
ToolUniverse.tool_category_dicts
ToolUniverse.tool_files
ToolUniverse.callable_functions
ToolUniverse.__init__()
ToolUniverse._check_api_key_requirements()
ToolUniverse._create_hook_config_from_type()
ToolUniverse._filter_and_deduplicate_tools()
ToolUniverse._get_api_key()
ToolUniverse._load_auto_discovered_configs()
ToolUniverse._load_tool_names_from_file()
ToolUniverse._load_tools_from_mcp_server()
ToolUniverse._process_mcp_auto_loaders()
ToolUniverse._scan_all_json_files()
ToolUniverse._scan_predefined_files()
ToolUniverse.call_id_gen()
ToolUniverse.check_function_call()
ToolUniverse.discover_mcp_tools()
ToolUniverse.export_tool_names()
ToolUniverse.extract_function_call_json()
ToolUniverse.filter_tool_lists()
ToolUniverse.find_tools_by_pattern()
ToolUniverse.force_full_discovery()
ToolUniverse.generate_env_template()
ToolUniverse.get_available_tools()
ToolUniverse.get_lazy_loading_status()
ToolUniverse.get_one_tool_by_one_name()
ToolUniverse.get_tool_by_name()
ToolUniverse.get_tool_description()
ToolUniverse.get_tool_specification_by_names()
ToolUniverse.get_tool_type_by_name()
ToolUniverse.get_tool_types()
ToolUniverse.init_tool()
ToolUniverse.list_built_in_tools()
ToolUniverse.list_mcp_connections()
ToolUniverse.load_mcp_tools()
ToolUniverse.load_tools()
ToolUniverse.load_tools_from_names_list()
ToolUniverse.prepare_one_tool_prompt()
ToolUniverse.prepare_tool_examples()
ToolUniverse.prepare_tool_prompts()
ToolUniverse.refresh_tool_name_desc()
ToolUniverse.register_custom_tool()
ToolUniverse.remove_keys()
ToolUniverse.return_all_loaded_tools()
ToolUniverse.run()
ToolUniverse.run_one_function()
ToolUniverse.select_tools()
ToolUniverse.toggle_hooks()
ToolUniverse.tool_specification()
ToolUniverse.tool_to_str()
- tooluniverse.graphql_tool module
- tooluniverse.humanbase_tool module
- tooluniverse.mcp_client_tool module
BaseMCPClient
MCPAutoLoaderTool
MCPClientTool
MCPClientTool.__init__()
MCPClientTool._run_call_tool()
MCPClientTool._run_get_prompt()
MCPClientTool._run_list_prompts()
MCPClientTool._run_list_resources()
MCPClientTool._run_list_tools()
MCPClientTool._run_read_resource()
MCPClientTool.call_tool()
MCPClientTool.get_prompt()
MCPClientTool.list_prompts()
MCPClientTool.list_resources()
MCPClientTool.list_tools()
MCPClientTool.read_resource()
MCPClientTool.run()
MCPProxyTool
MCPServerDiscovery
- tooluniverse.openalex_tool module
- tooluniverse.openfda_adv_tool module
- tooluniverse.openfda_tool module
- tooluniverse.pubtator_tool module
- tooluniverse.restful_tool module
- tooluniverse.semantic_scholar_tool module
- tooluniverse.utils module