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).

spacestr or list of str, optional

Space configuration URI(s) to load. Can be a single URI string or a list of URIs for loading multiple Space configurations. Supported formats: - Local file: “./config.yaml” or “/path/to/config.yaml” - HuggingFace: “hf:username/repo” or “hf:username/repo/file.yaml” - HTTP URL: “https://example.com/config.yaml”

When provided, Space configurations are loaded after tool initialization, applying LLM settings, hooks, and tool selections from the configuration files. Multiple spaces can be loaded sequentially, with later configurations potentially overriding earlier ones.

Example: space=”./my-workspace.yaml” Example: space=[“hf:community/bio-tools”, “./custom-tools.yaml”]

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.

compact_modebool, default False

Enable compact mode that only exposes core tools to prevent context window overflow. When True: - Only exposes search tools (find_tools), execute tool (execute_tool),

and tool discovery tools (list_tools, grep_tools, get_tool_info)

  • All tools are still loaded in background for execute_tool to work

  • Prevents automatic exposure of all tools, reducing context window usage

  • Maintains full functionality through search and execute capabilities

  • Tool discovery tools enable progressive disclosure: start with minimal info, request details when needed

  • Agent-friendly features: simple text search (no regex required), natural language task discovery, combined search+detail tools to reduce tool call overhead

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, space=None, auto_expose_tools=True, search_enabled=True, max_workers=5, hooks_enabled=False, hook_config=None, hook_type=None, compact_mode=False, **kwargs)[source]
get_llm_config()[source]

Get the current Space LLM configuration.

Returns:

LLM configuration dictionary or None if not set

Return type:

Dict[str, Any] | None

async handle_tasks_get(task_id, auth_context=None)[source]

Get current task status.

async handle_tasks_list(auth_context=None, cursor=None)[source]

List all tasks.

async handle_tasks_cancel(task_id, auth_context=None)[source]

Cancel a running task.

async handle_tasks_result(task_id, auth_context=None, timeout=None)[source]

Wait for task completion and return its result.

add_custom_tool(name, function, description=None, **kwargs)[source]

Add a custom Python function as an MCP tool.

Parameters:
  • name (str) – Unique tool name for the MCP interface.

  • function (Callable) – Sync or async callable to register.

  • description (str | None) – If provided, overrides the function’s docstring.

  • **kwargs – Additional FastMCP tool configuration options.

Returns:

The decorated function registered with FastMCP.

async close()[source]

Gracefully shut down the SMCP server, stopping the task manager and thread pool.

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 the given transport.

Parameters:
  • transport (Literal['stdio', 'http', 'sse']) – Communication protocol - “stdio”, “http”, or “sse”.

  • host (str) – Bind address for HTTP/SSE transports.

  • port (int) – Port for HTTP/SSE transports.

  • **kwargs – Additional arguments passed to FastMCP’s run().

tooluniverse.smcp.create_smcp_server(name='SMCP Server', tool_categories=None, search_enabled=True, **kwargs)[source]

Create a configured SMCP server instance.

Convenience wrapper around SMCP(...) with sensible defaults.

Parameters:
  • name (str) – Human-readable server name.

  • tool_categories (List[str] | None) – ToolUniverse categories to load (None loads all).

  • search_enabled (bool) – Enable AI-powered tool discovery.

  • **kwargs – Additional SMCP / FastMCP configuration options.

Returns:

Configured SMCP server instance ready to run.

Return type:

SMCP