Skip to main content
Glama

leiden

Detect communities in single-cell RNA sequencing data using the Leiden clustering algorithm to identify cell types and biological patterns.

Instructions

Leiden clustering algorithm for community detection

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
resolutionNoA parameter value controlling the coarseness of the clustering. Higher values lead to more clusters.
random_stateNoChange the initialization of the optimization.
key_addedNo`adata.obs` key under which to add the cluster labels.leiden
directedNoWhether to treat the graph as directed or undirected.
use_weightsNoIf `True`, edge weights from the graph are used in the computation (placing more emphasis on stronger edges).
n_iterationsNoHow many iterations of the Leiden clustering algorithm to perform. -1 runs until optimal clustering.
neighbors_keyNoUse neighbors connectivities as adjacency. If specified, leiden looks .obsp[.uns[neighbors_key]['connectivities_key']] for connectivities.
obspNoUse .obsp[obsp] as adjacency. You can't specify both `obsp` and `neighbors_key` at the same time.
flavorNoWhich package's implementation to use.igraph
clustering_argsNoAny further arguments to pass to the clustering algorithm.

Implementation Reference

  • MCP tool registration for 'leiden' with name, description, and schema reference.
    # Add leiden tool
    leiden_tool = types.Tool(
        name="leiden",
        description="Leiden clustering algorithm for community detection",
        inputSchema=LeidenModel.model_json_schema(),
    )
  • Pydantic model defining input schema and validation for leiden tool parameters.
    class LeidenModel(JSONParsingModel):
        """Input schema for the Leiden clustering algorithm."""
        
        resolution: float = Field(
            default=1.0,
            description="A parameter value controlling the coarseness of the clustering. Higher values lead to more clusters."
        )
        
        random_state: int = Field(
            default=0,
            description="Change the initialization of the optimization."
        )
        
        key_added: str = Field(
            default='leiden',
            description="`adata.obs` key under which to add the cluster labels."
        )
        
        directed: Optional[bool] = Field(
            default=None,
            description="Whether to treat the graph as directed or undirected."
        )
        
        use_weights: bool = Field(
            default=True,
            description="If `True`, edge weights from the graph are used in the computation (placing more emphasis on stronger edges)."
        )
        
        n_iterations: int = Field(
            default=-1,
            description="How many iterations of the Leiden clustering algorithm to perform. -1 runs until optimal clustering."
        )
        
        neighbors_key: Optional[str] = Field(
            default=None,
            description="Use neighbors connectivities as adjacency. If specified, leiden looks .obsp[.uns[neighbors_key]['connectivities_key']] for connectivities."
        )
        
        obsp: Optional[str] = Field(
            default=None,
            description="Use .obsp[obsp] as adjacency. You can't specify both `obsp` and `neighbors_key` at the same time."
        )
        
        flavor: Literal['leidenalg', 'igraph'] = Field(
            default='igraph',
            description="Which package's implementation to use."
        )
        
        clustering_args: Optional[Dict[str, Any]] = Field(
            default=None,
            description="Any further arguments to pass to the clustering algorithm."
        )
        
        @field_validator('resolution')
        def validate_resolution(cls, v: float) -> float:
            """Validate resolution is positive"""
            if v <= 0:
                raise ValueError("resolution must be a positive number")
            return v
        
        @field_validator('obsp', 'neighbors_key')
        def validate_graph_source(cls, v: Optional[str], info: ValidationInfo) -> Optional[str]:
            """Validate that obsp and neighbors_key are not both specified"""
            values = info.data
            if v is not None and 'obsp' in values and 'neighbors_key' in values:
                if values['obsp'] is not None and values['neighbors_key'] is not None:
                    raise ValueError("Cannot specify both obsp and neighbors_key")
            return v
        
        @field_validator('flavor')
        def validate_flavor(cls, v: str) -> str:
            """Validate flavor is supported"""
            if v not in ['leidenalg', 'igraph']:
                raise ValueError("flavor must be either 'leidenalg' or 'igraph'")
            return v
  • Generic execution handler for tl tools including 'leiden'; resolves sc.tl.leiden from tl_func dict, validates parameters via signature, executes on active adata, and logs operation.
    def run_tl_func(ads, func, arguments):
        adata = ads.adata_dic[ads.active]
        if func not in tl_func:
            raise ValueError(f"Unsupported function: {func}")
        run_func = tl_func[func]
        parameters = inspect.signature(run_func).parameters
        kwargs = {k: arguments.get(k) for k in parameters if k in arguments}    
        try:
            res = run_func(adata, **kwargs)
            add_op_log(adata, run_func, kwargs)
        except Exception as e:
            logger.error(f"Error running function {func}: {e}")
            raise
        return 
  • Mapping dictionary tl_func that associates 'leiden' tool name with scanpy.tl.leiden function for execution.
    tl_func = {
        "tsne": sc.tl.tsne,
        "umap": sc.tl.umap,
        "draw_graph": sc.tl.draw_graph,
        "diffmap": sc.tl.diffmap,
        "embedding_density": sc.tl.embedding_density,
        "leiden": sc.tl.leiden,
        "louvain": sc.tl.louvain,
        "dendrogram": sc.tl.dendrogram,
        "dpt": sc.tl.dpt,
        "paga": sc.tl.paga,
        "ingest": sc.tl.ingest,
        "rank_genes_groups": sc.tl.rank_genes_groups,
        "filter_rank_genes_groups": sc.tl.filter_rank_genes_groups,
        "marker_gene_overlap": sc.tl.marker_gene_overlap,
        "score_genes": sc.tl.score_genes,
        "score_genes_cell_cycle": sc.tl.score_genes_cell_cycle,
    }
  • tl_tools dictionary that includes the 'leiden' tool object for listing and dispatch.
    tl_tools = {
        "tsne": tsne_tool,
        "umap": umap_tool,
        "draw_graph": draw_graph_tool,
        "diffmap": diffmap_tool,
        "embedding_density": embedding_density_tool,
        "leiden": leiden_tool,
        "louvain": louvain_tool,
        "dendrogram": dendrogram_tool,
        "dpt": dpt_tool,
        "paga": paga_tool,
        "ingest": ingest_tool,
        "rank_genes_groups": rank_genes_groups_tool,
        "filter_rank_genes_groups": filter_rank_genes_groups_tool,
        "marker_gene_overlap": marker_gene_overlap_tool,
        "score_genes": score_genes_tool,
        "score_genes_cell_cycle": score_genes_cell_cycle_tool,
    }
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries full burden for behavioral disclosure but offers minimal information. It doesn't mention whether this is a read-only or mutating operation, what data structure it operates on (though implied from parameters), performance characteristics, or what the output looks like. The description only names the algorithm without explaining its behavior.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is extremely concise at just 6 words, with zero wasted language. It's front-loaded with the essential information (algorithm name and purpose) in a single, efficient phrase.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a complex clustering algorithm with 10 parameters and no output schema, the description is inadequate. It doesn't explain what data structure it operates on (AnnData objects implied from parameters), what the output format is, typical use cases, or how results integrate with the analysis workflow. The description is too minimal given the tool's complexity.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so the schema already fully documents all 10 parameters. The description adds no additional parameter information beyond what's in the schema. According to scoring rules, when schema coverage is high (>80%), the baseline is 3 even with no param info in description.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose as 'Leiden clustering algorithm for community detection', which identifies both the algorithm and its function. It distinguishes itself from siblings like 'louvain' (another clustering algorithm) by naming the specific algorithm, but doesn't explicitly differentiate when to use Leiden vs Louvain.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives. With sibling tools like 'louvain' (another community detection algorithm) and 'paga' (graph abstraction), there's no indication of when Leiden clustering is preferred, what data prerequisites exist, or typical use cases.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/huang-sh/scmcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server