tooluniverse.smcp_server module¶
SMCP Server Entry Point
This module provides the command-line entry point for running the SMCP (Scientific Model Context Protocol) server. It creates a minimal SMCP server that exposes all ToolUniverse tools as MCP tools.
- class tooluniverse.smcp_server.SMCP(name: str | None = None, tooluniverse_config: ToolUniverse | Dict[str, Any] | None = None, tool_categories: List[str] | None = None, exclude_tools: List[str] | None = None, exclude_categories: List[str] | None = None, include_tools: List[str] | None = None, tools_file: str | None = None, tool_config_files: Dict[str, str] | None = None, include_tool_types: List[str] | None = None, exclude_tool_types: List[str] | None = None, auto_expose_tools: bool = True, search_enabled: bool = True, max_workers: int = 5, hooks_enabled: bool = False, hook_config: Dict[str, Any] | None = None, hook_type: str | None = None, **kwargs)[source][source]¶
Bases:
FastMCP
Scientific Model Context Protocol (SMCP) Server
SMCP is an enhanced MCP (Model Context Protocol) server that seamlessly integrates ToolUniverseâs extensive collection of scientific and scientific tools with the FastMCP framework. It provides a unified, AI-accessible interface for scientific computing, data analysis, and research workflows.
The SMCP server extends standard MCP capabilities with scientific domain expertise, intelligent tool discovery, and optimized configurations for research applications. It automatically handles the complex task of exposing hundreds of specialized tools through a consistent, well-documented interface.
Key Features:¶
- đŹ Scientific Tool Integration: Native access to 350+ specialized tools covering
scientific databases, literature search, clinical data, genomics, proteomics, chemical informatics, and AI-powered analysis capabilities.
- đ§ AI-Powered Tool Discovery: Multi-tiered intelligent search system using:
ToolFinderLLM: Cost-optimized LLM-based semantic understanding with pre-filtering
Tool_RAG: Embedding-based similarity search
Keyword Search: Simple text matching as reliable fallback
- đĄ **Full MCP Protocol Support**: Complete implementation of MCP specification with:
Standard methods (tools/list, tools/call, resources/, prompts/)
Custom scientific methods (tools/find, tools/search)
Multi-transport support (stdio, HTTP, SSE)
JSON-RPC 2.0 compliance with proper error handling
- ⥠High-Performance Architecture: Production-ready features including:
Configurable thread pools for concurrent tool execution
Intelligent tool loading and caching
Resource management and graceful degradation
Comprehensive error handling and recovery
- đ§ Developer-Friendly: Simplified configuration and deployment with:
Sensible defaults for scientific computing
Flexible customization options
Comprehensive documentation and examples
Built-in diagnostic and monitoring tools
Custom MCP Methods:¶
- tools/find:
AI-powered tool discovery using natural language queries. Supports semantic search, category filtering, and flexible response formats.
- tools/search:
Alternative endpoint for tool discovery with identical functionality to tools/find, provided for compatibility and convenience.
Parameters:¶
- namestr, optional
Human-readable server name used in logs and identification. Default: âSMCP Serverâ Examples: âScientific Research APIâ, âDrug Discovery Serverâ
- tooluniverse_configToolUniverse or dict, optional
Either a pre-configured ToolUniverse instance or configuration dict. If None, creates a new ToolUniverse with default settings. Allows reuse of existing tool configurations and customizations.
- tool_categorieslist of str, optional
Specific ToolUniverse categories to load. If None and auto_expose_tools=True, loads all available tools. Common combinations: - Scientific: [âChEMBLâ, âuniprotâ, âopentargetâ, âpubchemâ, âhpaâ] - Literature: [âEuropePMCâ, âsemantic_scholarâ, âpubtatorâ, âagentsâ] - Clinical: [âfda_drug_labelâ, âclinical_trialsâ, âadverse_eventsâ]
- exclude_toolslist of str, optional
Specific tool names to exclude from loading. These tools will not be exposed via the MCP interface even if they are in the loaded categories. Useful for removing specific problematic or unwanted tools.
- exclude_categorieslist of str, optional
Tool categories to exclude from loading. These entire categories will be skipped during tool loading. Can be combined with tool_categories to first select categories and then exclude specific ones.
- include_toolslist of str, optional
Specific tool names to include. If provided, only these tools will be loaded regardless of categories. Overrides category-based selection.
- tools_filestr, optional
Path to a text file containing tool names to include (one per line). Alternative to include_tools parameter. Comments (lines starting with #) and empty lines are ignored.
- tool_config_filesdict of str, optional
Additional tool configuration files to load. Format: {âcategory_nameâ: â/path/to/config.jsonâ}. These files will be loaded in addition to the default tool files.
- include_tool_typeslist of str, optional
Specific tool types to include. If provided, only tools of these types will be loaded. Available types include: âOpenTargetâ, âToolFinderEmbeddingâ, âToolFinderKeywordâ, âToolFinderLLMâ, etc.
- exclude_tool_typeslist of str, optional
Tool types to exclude from loading. These tool types will be skipped during tool loading. Useful for excluding entire categories of tools (e.g., all ToolFinder types or all OpenTarget tools).
- auto_expose_toolsbool, default True
Whether to automatically expose ToolUniverse tools as MCP tools. When True, all loaded tools become available via the MCP interface with automatic schema conversion and execution wrapping.
- search_enabledbool, default True
Enable AI-powered tool search functionality via tools/find method. Includes ToolFinderLLM (cost-optimized LLM-based), Tool_RAG (embedding-based), and simple keyword search capabilities with intelligent fallback.
- max_workersint, default 5
Maximum number of concurrent worker threads for tool execution. Higher values allow more parallel tool calls but use more resources. Recommended: 5-20 depending on server capacity and expected load.
- hooks_enabledbool, default False
Whether to enable output processing hooks for intelligent post-processing of tool outputs. When True, hooks can automatically summarize long outputs, save results to files, or apply other transformations.
- hook_configdict, optional
Custom hook configuration dictionary. If provided, overrides default hook settings. Should contain âhooksâ list with hook definitions. Example: {âhooksâ: [{ânameâ: âsummarization_hookâ, âtypeâ: âSummarizationHookâ, âŠ}]}
- hook_typestr, optional
Simple hook type selection. Can be âSummarizationHookâ, âFileSaveHookâ, or a list of both. Provides an easy way to enable hooks without full configuration. Takes precedence over hooks_enabled when specified.
- **kwargs
Additional arguments passed to the underlying FastMCP server instance. Supports all FastMCP configuration options for advanced customization.
Raises:¶
- ImportError
If FastMCP is not installed. FastMCP is a required dependency for SMCP. Install with: pip install fastmcp
Notes:¶
SMCP automatically handles ToolUniverse tool loading and MCP conversion
Tool search uses ToolFinderLLM (optimized for cost) when available, gracefully falls back to simpler methods
All tools support JSON argument passing for maximum flexibility
Server supports graceful shutdown and comprehensive resource cleanup
Thread pool execution ensures non-blocking operation for concurrent requests
Built-in error handling provides informative debugging information
- __init__(name: str | None = None, tooluniverse_config: ToolUniverse | Dict[str, Any] | None = None, tool_categories: List[str] | None = None, exclude_tools: List[str] | None = None, exclude_categories: List[str] | None = None, include_tools: List[str] | None = None, tools_file: str | None = None, tool_config_files: Dict[str, str] | None = None, include_tool_types: List[str] | None = None, exclude_tool_types: List[str] | None = None, auto_expose_tools: bool = True, search_enabled: bool = True, max_workers: int = 5, hooks_enabled: bool = False, hook_config: Dict[str, Any] | None = None, hook_type: str | None = None, **kwargs)[source][source]¶
- add_custom_tool(name: str, function: Callable, description: str | None = None, **kwargs)[source][source]¶
Add a custom Python function as an MCP tool to the SMCP server.
This method provides a convenient way to extend SMCP functionality with custom tools beyond those provided by ToolUniverse. Custom tools are automatically integrated into the MCP interface and can be discovered and used by clients alongside existing tools.
Parameters:¶
- namestr
Unique name for the tool in the MCP interface. Should be descriptive and follow naming conventions (lowercase with underscores preferred). Examples: âanalyze_protein_sequenceâ, âcustom_data_processorâ
- functionCallable
Python function to execute when the tool is called. The function: - Can be synchronous or asynchronous - Should have proper type annotations for parameters - Should include a comprehensive docstring - Will be automatically wrapped for MCP compatibility
- descriptionstr, optional
Human-readable description of the toolâs functionality. If provided, this will be set as the functionâs __doc__ attribute. If None, the functionâs existing docstring will be used.
- **kwargs
Additional FastMCP tool configuration options: - parameter_schema: Custom JSON schema for parameters - return_schema: Schema for return values - examples: Usage examples for the tool - tags: Categorization tags
Returns:¶
- Callable
The decorated function registered with FastMCP framework.
Usage Examples:¶
Simple synchronous function: .. code-block:: python
- def analyze_text(text: str, max_length: int = 100) -> str:
âââAnalyze text and return summary.âââ return text[:max_length] + ââŠâ if len(text) > max_length else text
- server.add_custom_tool(
name=âtext_analyzerâ, function=analyze_text, description=âAnalyze and summarize text contentâ
)
Asynchronous function with complex parameters: .. code-block:: python
- async def process_data(
data: List[Dict[str, Any]], processing_type: str = âstandardâ
- ) -> Dict[str, Any]:
âââProcess scientific data with specified method.âââ # Custom processing logic here return {âprocessed_itemsâ: len(data), âtypeâ: processing_type}
- server.add_custom_tool(
name=âdata_processorâ, function=process_data
)
Function with custom schema: .. code-block:: python
- def calculate_score(values: List[float]) -> float:
âââCalculate composite score from values.âââ return sum(values) / len(values) if values else 0.0
- server.add_custom_tool(
name=âscore_calculatorâ, function=calculate_score, parameter_schema={
âtypeâ: âobjectâ, âpropertiesâ: {
- âvaluesâ: {
âtypeâ: âarrayâ, âitemsâ: {âtypeâ: ânumberâ}, âdescriptionâ: âList of numeric values to processâ
}
}, ârequiredâ: [âvaluesâ]
}
)
Integration with ToolUniverse:¶
Custom tools work seamlessly alongside ToolUniverse tools: - Appear in tool discovery searches - Follow same calling conventions - Include in server diagnostics and listings - Support all MCP client interaction patterns
Best Practices:¶
Use descriptive, unique tool names
Include comprehensive docstrings
Add proper type annotations for parameters
Handle errors gracefully within the function
Consider async functions for I/O-bound operations
Test tools thoroughly before deployment
Notes:¶
Custom tools are registered immediately upon addition
Tools can be added before or after server startup
Function signature determines parameter schema automatically
Custom tools support all FastMCP features and conventions
- async close()[source][source]¶
Perform comprehensive cleanup and resource management during server shutdown.
This method ensures graceful shutdown of the SMCP server by properly cleaning up all resources, stopping background tasks, and releasing system resources. Itâs designed to be safe to call multiple times and handles errors gracefully.
Cleanup Operations:¶
Thread Pool Shutdown: - Gracefully stops the ThreadPoolExecutor used for tool execution - Waits for currently running tasks to complete - Prevents new tasks from being submitted - Times out after reasonable wait period to prevent hanging
Resource Cleanup: - Releases any open file handles or network connections - Clears internal caches and temporary data - Stops background monitoring tasks - Frees memory allocated for tool configurations
Error Handling: - Continues cleanup even if individual operations fail - Logs cleanup errors for debugging without raising exceptions - Ensures critical resources are always released
Usage Patterns:¶
Automatic Cleanup (Recommended): .. code-block:: python
server = SMCP(âMy Serverâ) try:
server.run_simple() # Cleanup happens automatically on exit
- except KeyboardInterrupt:
pass # run_simple() handles cleanup
Manual Cleanup: .. code-block:: python
server = SMCP(âMy Serverâ) try:
# Custom server logic here pass
- finally:
await server.close() # Explicit cleanup
**Context Manager Pattern:** .. code-block:: python
- async with SMCP(âMy Serverâ) as server:
# Server operations pass
# Cleanup happens automatically
Performance Considerations:¶
Cleanup operations are typically fast (< 1 second)
Thread pool shutdown may take longer if tasks are running
Network connections are closed immediately
Memory cleanup depends on garbage collection
Error Recovery:¶
Individual cleanup failures donât stop the overall process
Critical errors are logged but donât raise exceptions
Cleanup is idempotent - safe to call multiple times
System resources are guaranteed to be released
Notes:¶
This method is called automatically by run_simple() on shutdown
Can be called manually for custom server lifecycle management
Async method to properly handle async resource cleanup
Safe to call even if server hasnât been fully initialized
- run_simple(transport: Literal['stdio', 'http', 'sse'] = 'http', host: str = '0.0.0.0', port: int = 7000, **kwargs)[source][source]¶
Start the SMCP server with simplified configuration and automatic setup.
This method provides a convenient way to launch the SMCP server with sensible defaults for different deployment scenarios. It handles transport configuration, logging setup, and graceful shutdown automatically.
Parameters:¶
- transport{âstdioâ, âhttpâ, âsseâ}, default âhttpâ
Communication transport protocol:
âstdioâ: Standard input/output communication * Best for: Command-line tools, subprocess integration * Pros: Low overhead, simple integration * Cons: Single client, no network access
âhttpâ: HTTP-based communication (streamable-http) * Best for: Web applications, REST API integration * Pros: Wide compatibility, stateless, scalable * Cons: Higher overhead than stdio
âsseâ: Server-Sent Events over HTTP * Best for: Real-time applications, streaming responses * Pros: Real-time communication, web-compatible * Cons: Browser limitations, more complex
- hoststr, default â0.0.0.0â
Server bind address for HTTP/SSE transports: - â0.0.0.0â: Listen on all network interfaces (default) - â127.0.0.1â: localhost only (more secure) - Specific IP: Bind to particular interface
- portint, default 7000
Server port for HTTP/SSE transports. Choose ports: - 7000-7999: Recommended range for SMCP servers - Above 1024: No root privileges required - Check availability: Ensure port isnât already in use
- **kwargs
Additional arguments passed to FastMCPâs run() method: - debug (bool): Enable debug logging - access_log (bool): Log client requests - workers (int): Number of worker processes (HTTP only)
Server Startup Process:¶
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: .. code-block:: python
server = SMCP(name=âDev Serverâ) server.run_simple(transport=âstdioâ) # For CLI testing
Local Web Service: .. code-block:: python
server = SMCP(name=âLocal APIâ) server.run_simple(transport=âhttpâ, host=â127.0.0.1â, port=8000)
Production Service: .. code-block:: python
- server = SMCP(
name=âProduction SMCPâ, tool_categories=[âChEMBLâ, âuniprotâ, âopentargetâ], max_workers=20
) server.run_simple(
transport=âhttpâ, host=â0.0.0.0â, port=7000, workers=4
)
Real-time Applications: .. code-block:: python
server = SMCP(name=âStreaming APIâ) server.run_simple(transport=âsseâ, port=7001)
Error Handling:¶
KeyboardInterrupt: Graceful shutdown on Ctrl+C
Port in Use: Clear error message with suggestions
Transport Errors: Detailed debugging information
**Cleanup**: Automatic resource cleanup on exit
Logging Output:¶
Provides informative startup messages:¶
đ Starting SMCP server âMy Serverâ⊠đ Loaded 356 tools from ToolUniverse đ Search enabled: True đ Server running on http://0.0.0.0:7000
Security Considerations:¶
Use host=â127.0.0.1â for local-only access
Configure firewall rules for production deployment
Consider HTTPS termination with reverse proxy
Validate all client inputs through MCP protocol
Performance Notes:¶
HTTP transport supports multiple concurrent clients
stdio transport is single-client but lower latency
SSE transport enables real-time bidirectional communication
Thread pool size affects concurrent tool execution capacity
- tooluniverse.smcp_server.run_http_server()[source][source]¶
Run SMCP server with streamable-http transport on localhost:8000
This function provides compatibility with the original MCP serverâs run_server function.
- tooluniverse.smcp_server.run_stdio_server()[source][source]¶
Run SMCP server with stdio transport for Claude Desktop integration
This function provides compatibility with the original MCP serverâs run_claude_desktop function. It accepts the same arguments as run_smcp_server but forces transport=âstdioâ.