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, }

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