This guide demonstrates how to develop an MCP (Model Context Protocol) based scmcphub API using Tool Mode. Tool Mode allows you to create custom tools that can be integrated into the scmcphub ecosystem for single-cell analysis workflows.
The schema file defines the input parameters for your tools using Pydantic models. This ensures type safety and provides automatic validation:
Copy
from pydantic import Field, BaseModelclass UNSKeyParam(BaseModel): """Input schema for the uns_key tool.""" key: str = Field(..., description="Key in adata.uns")
Key Points:
Field(...) indicates this is a required parameter
The description provides documentation for the tool
The server file contains the core logic of your MCP tools. Here’s a detailed breakdown:
Copy
from fastmcp import FastMCP, Contextfrom fastmcp.exceptions import ToolErrorfrom scmcp_shared.schema import AdataInfofrom scmcp_shared.util import get_adsfrom scanpy_mcp.server import ScanpyMCPManagerfrom scmcp_shared.backend import AdataManager # Import the schema we definedfrom .schema import UNSKeyParam# Create MCP instance using FastMCP# mcp = FastMCP("mcp-demo")## if you want to add this tool in scanpy-mcp, you can use thismcp = ScanpyMCPManager(name="mcp-demo", backend=AdataManager).mcp@mcp.tool()def uns_key( request: UNSKeyParam, adinfo: AdataInfo = AdataInfo()): """ Get value from adata.uns with specified key. """ try: # Get the AnnData object manager ads = get_ads() adata = ads.get_adata(adinfo=adinfo) # Validate that the key exists if request.key not in adata.uns: raise ToolError(f"Key '{request.key}' not found in adata.uns") # Retrieve the value result = adata.uns[request.key] # Return structured response return { "key": request.key, "value": result } except Exception as e: raise ToolError(str(e))@mcp.tool()def list_uns_keys( adinfo: AdataInfo = AdataInfo()): """ List all available keys in adata.uns. """ try: ads = get_ads() adata = ads.get_adata(adinfo=adinfo) keys = list(adata.uns.keys()) return { "keys": keys, "count": len(keys) } except Exception as e: logger.error(f"Error in list_uns_keys: {e}") raise ToolError(f"Unexpected error: {e}")
Important Concepts:
AdataInfo: Standard parameter for specifying which AnnData object to use
get_ads(): Utility function to access the AnnData manager
The CLI file provides a command-line interface for your MCP tools in scmcphub:
Copy
"""Command-line interface for mcp-demo.This module provides a CLI entry point for the mcp-demo package.The CLI allows users to run the MCP server and access the toolsthrough command-line arguments."""from scmcp_shared.cli import MCPCLIfrom .server import mcp# Create CLI instance using the shared CLI frameworkcli = MCPCLI( name="mcp-demo", help_text="MCP Demo Server CLI - A simple example of MCP tool development", mcp=mcp)
Benefits of using MCPCLI:
Standardized CLI interface across all scmcphub tools