tooluniverse.smcp module

Scientific Model Context Protocol (SMCP) - Enhanced MCP Server with ToolUniverse Integration

SMCP is a sophisticated MCP (Model Context Protocol) server that bridges the gap between AI agents and scientific tools. It seamlessly integrates ToolUniverse’s extensive collection of 350+ scientific tools with the MCP protocol, enabling AI systems to access scientific databases, perform complex analyses, and execute scientific workflows.

The SMCP module provides a complete solution for exposing scientific computational resources through the standardized MCP protocol, making it easy for AI agents to discover, understand, and execute scientific tools in a unified manner.

Usage Patterns:

Quick Start:

```python # High-performance server with custom configuration server = SMCP(

name=”Production Scientific API”, tool_categories=[“uniprot”, “ChEMBL”, “opentarget”, “hpa”], max_workers=20, search_enabled=True

) server.run_simple(

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

)

Client Integration: ```python # Using MCP client to discover and use tools import json

# Discover protein analysis tools response = await client.call_tool(“find_tools”, {

“query”: “protein structure analysis”, “limit”: 5

})

# Use discovered tool result = await client.call_tool(“UniProt_get_entry_by_accession”, {

“arguments”: json.dumps({“accession”: “P05067”})

})

Architecture:

┌─────────────────┐ ┌──────────────────┐ ┌─────────────────┐ │ MCP Client │◄──►│ SMCP │◄──►│ ToolUniverse │ │ (AI Agent) │ │ Server │ │ (350+ Tools) │ └─────────────────┘ └──────────────────┘ └─────────────────┘

│ ▼

┌──────────────────┐ │ Scientific │ │ Databases & │ │ Services │ └──────────────────┘

The SMCP server acts as an intelligent middleware layer that: 1. Receives MCP requests from AI agents/clients 2. Translates requests to ToolUniverse tool calls 3. Executes tools against scientific databases/services 4. Returns formatted results via MCP protocol 5. Provides intelligent tool discovery and recommendation

Integration Points:

MCP Protocol Layer:
  • Standard MCP methods (tools/list, tools/call, etc.)

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

  • Transport-agnostic communication (stdio, HTTP, SSE)

  • Proper error codes and JSON-RPC 2.0 compliance

ToolUniverse Integration:
  • Dynamic tool loading and configuration

  • Schema transformation and validation

  • Execution wrapper with error handling

  • Category-based tool organization

AI Agent Interface:
  • Natural language tool discovery

  • Contextual tool recommendations

  • Structured parameter schemas

  • Comprehensive tool documentation

class tooluniverse.smcp.SMCP[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=None, tooluniverse_config=None, tool_categories=None, exclude_tools=None, exclude_categories=None, include_tools=None, tools_file=None, tool_config_files=None, include_tool_types=None, exclude_tool_types=None, auto_expose_tools=True, search_enabled=True, max_workers=5, hooks_enabled=False, hook_config=None, hook_type=None, **kwargs)[source]
add_custom_tool(name, function, description=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

# 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(*args, **kwargs)[source]

Override run method to display ToolUniverse banner after FastMCP banner.

This method intercepts the parent’s run() call to inject our custom banner immediately after FastMCP displays its startup banner.

run_simple(transport='http', host='0.0.0.0', port=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:

  1. Initialization Summary: Displays server configuration and capabilities

  2. Transport Setup: Configures selected communication method

  3. Service Start: Begins listening for client connections

  4. Graceful Shutdown: Handles interrupts and cleanup

Deployment Scenarios:

Development & Testing: `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

tooluniverse.smcp.create_smcp_server(name='SMCP Server', tool_categories=None, search_enabled=True, **kwargs)[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