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
Tool call template
This tool declares no required parameters. Add optional parameters from the input schema as needed.
{
"id": 1,
"jsonrpc": "2.0",
"method": "tools/call",
"params": {
"arguments": {},
"name": "leiden"
}
}Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| resolution | No | A parameter value controlling the coarseness of the clustering. Higher values lead to more clusters. | |
| random_state | No | Change the initialization of the optimization. | |
| key_added | No | `adata.obs` key under which to add the cluster labels. | leiden |
| directed | No | Whether to treat the graph as directed or undirected. | |
| use_weights | No | If `True`, edge weights from the graph are used in the computation (placing more emphasis on stronger edges). | |
| n_iterations | No | How many iterations of the Leiden clustering algorithm to perform. -1 runs until optimal clustering. | |
| neighbors_key | No | Use neighbors connectivities as adjacency. If specified, leiden looks .obsp[.uns[neighbors_key]['connectivities_key']] for connectivities. | |
| obsp | No | Use .obsp[obsp] as adjacency. You can't specify both `obsp` and `neighbors_key` at the same time. | |
| flavor | No | Which package's implementation to use. | igraph |
| clustering_args | No | Any further arguments to pass to the clustering algorithm. |
Implementation Reference
- src/scmcp/tool/tl.py:47-52 (registration)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(), ) - src/scmcp/schema/tl.py:267-342 (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 - src/scmcp/tool/tl.py:164-177 (handler)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 - src/scmcp/tool/tl.py:125-142 (helper)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, } - src/scmcp/tool/tl.py:145-162 (helper)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, }