Skip to main content
Glama

pl_heatmap

Visualize gene expression patterns across cell groups using color-coded heatmaps to identify biological trends in single-cell RNA sequencing data.

Instructions

Heatmap of the expression values of genes.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
figsizeNoFigure size. Format is (width, height).
color_mapNoColor map to use for continuous variables.
paletteNoColors to use for plotting categorical annotation groups.
vmaxNoThe value representing the upper limit of the color scale.
vminNoThe value representing the lower limit of the color scale.
vcenterNoThe value representing the center of the color scale.
legend_fontsizeNoNumeric size in pt or string describing the size.
legend_fontweightNoLegend font weight. A numeric value in range 0-1000 or a string.bold
legend_locNoLocation of legend, either 'on data', 'right margin' or a valid keyword for the loc parameter.right margin
legend_fontoutlineNoLine width of the legend font outline in pt.
var_namesNovar_names should be a valid subset of adata.var_names or a mapping where the key is used as label to group the values.
groupbyYesThe key of the observation grouping to consider.
use_rawNoUse raw attribute of adata if present.
logNoPlot on logarithmic axis.
dendrogramNoIf True or a valid dendrogram key, a dendrogram based on the hierarchical clustering between the groupby categories is added.
gene_symbolsNoColumn name in .var DataFrame that stores gene symbols.
var_group_positionsNoUse this parameter to highlight groups of var_names with brackets or color blocks between the given start and end positions.
var_group_labelsNoLabels for each of the var_group_positions that want to be highlighted.
layerNoName of the AnnData object layer that wants to be plotted.
num_categoriesNoOnly used if groupby observation is not categorical. This value determines the number of groups into which the groupby observation should be subdivided.
var_group_rotationNoLabel rotation degrees. By default, labels larger than 4 characters are rotated 90 degrees.
standard_scaleNoWhether or not to standardize that dimension between 0 and 1.
swap_axesNoBy default, the x axis contains var_names and the y axis the groupby categories. By setting swap_axes then x are the groupby categories and y the var_names.
show_gene_labelsNoBy default gene labels are shown when there are 50 or less genes. Otherwise the labels are removed.

Implementation Reference

  • Generic handler function that executes the Scanpy plotting function for 'pl_heatmap' (sc.pl.heatmap) using validated input arguments from the schema, saves the figure, and logs the operation.
    def run_pl_func(ads, func, arguments):
        """
        Execute a Scanpy plotting function with the given arguments.
        
        Parameters
        ----------
        adata : AnnData
            Annotated data matrix.
        func : str
            Name of the plotting function to execute.
        arguments : dict
            Arguments to pass to the plotting function.
            
        Returns
        -------
        The result of the plotting function.
        """
        adata = ads.adata_dic[ads.active]
        if func not in pl_func:
            raise ValueError(f"Unsupported function: {func}")
    
        run_func = pl_func[func]
        parameters = inspect.signature(run_func).parameters
        kwargs = {k: arguments.get(k) for k in parameters if k in arguments}    
    
        if "title" not in parameters:
            kwargs.pop("title", False)    
        kwargs.pop("return_fig", True)
        kwargs["show"] = False
        kwargs["save"] = ".png"
        try:
            fig = run_func(adata, **kwargs)
            fig_path = set_fig_path(func, **kwargs)
            add_op_log(adata, run_func, kwargs)
            return fig_path 
        except Exception as e:
            raise e
        return fig_path
  • Pydantic model defining the input schema and validation for the pl_heatmap tool, extending BaseMatrixModel with specific heatmap parameters.
    # 重构 HeatmapModel
    class HeatmapModel(BaseMatrixModel):
        """Input schema for the heatmap plotting tool."""
        
        num_categories: int = Field(
            default=7,
            description="Only used if groupby observation is not categorical. This value determines the number of groups into which the groupby observation should be subdivided.",
            gt=0
        )
        
        var_group_rotation: Optional[float] = Field(
            default=None,
            description="Label rotation degrees. By default, labels larger than 4 characters are rotated 90 degrees."
        )
        
        standard_scale: Optional[Literal['var', 'obs']] = Field(
            default=None,
            description="Whether or not to standardize that dimension between 0 and 1."
        )
        
        swap_axes: bool = Field(
            default=False,
            description="By default, the x axis contains var_names and the y axis the groupby categories. By setting swap_axes then x are the groupby categories and y the var_names."
        )
        
        show_gene_labels: Optional[bool] = Field(
            default=None,
            description="By default gene labels are shown when there are 50 or less genes. Otherwise the labels are removed."
        )
        
        @field_validator('num_categories')
        def validate_num_categories(cls, v: int) -> int:
            """Validate num_categories is positive"""
            if v <= 0:
                raise ValueError("num_categories must be a positive integer")
            return v
  • Creation and definition of the pl_heatmap Tool object using MCP types, linking to the HeatmapModel schema.
    pl_heatmap = types.Tool(
        name="pl_heatmap",
        description="Heatmap of the expression values of genes.",
        inputSchema=HeatmapModel.model_json_schema(),
    )
  • Dictionary mapping pl_heatmap tool name to the underlying Scanpy function sc.pl.heatmap, used by the handler.
    pl_func = {
        "pl_pca": sc.pl.pca,
        "pl_embedding": sc.pl.embedding,  # Add the new embedding function
        "diffmap": sc.pl.diffmap,
        "pl_violin": sc.pl.violin,
        "pl_stacked_violin": sc.pl.stacked_violin,
        "pl_heatmap": sc.pl.heatmap,
        "pl_dotplot": sc.pl.dotplot,
        "pl_matrixplot": sc.pl.matrixplot,
        "pl_tracksplot": sc.pl.tracksplot,
        "pl_scatter": sc.pl.scatter,
        "embedding_density": sc.pl.embedding_density,
        "rank_genes_groups": sc.pl.rank_genes_groups,
        "pl_rank_genes_groups_dotplot": sc.pl.rank_genes_groups_dotplot,  # Add function mapping
        "pl_clustermap": sc.pl.clustermap,
        "pl_highly_variable_genes": sc.pl.highly_variable_genes,
        "pl_pca_variance_ratio": sc.pl.pca_variance_ratio,
    }
  • MCP server call_tool handler that dispatches pl_heatmap calls (via pl_tools check) to run_pl_func.
    @server.call_tool()
    async def call_tool(
        name: str, arguments
    ):
        try:
            logger.info(f"Running {name} with {arguments}")
            if name in io_tools.keys():            
                res = run_io_func(ads, name, arguments)
            elif name in pp_tools.keys():
                res = run_pp_func(ads, name, arguments)
            elif name in tl_tools.keys():
                res = run_tl_func(ads, name, arguments) 
            elif name in pl_tools.keys():
                res = run_pl_func(ads, name, arguments)
            elif name in util_tools.keys():            
                res = run_util_func(ads, name, arguments)
            elif name in ccc_tools.keys():            
                res = run_ccc_func(ads.adata_dic[ads.active], name, arguments)
            output = str(res) if res is not None else str(ads.adata_dic[ads.active])
            return [
                types.TextContent(
                    type="text",
                    text=str({"output": output})
                )
            ]
        except Exception as error:
            logger.error(f"{name} with {error}")
            return [
                types.TextContent(
                    type="text",
                    text=str({"Error": error})
                )
            ]
Behavior1/5

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

No annotations are provided, so the description carries full burden for behavioral disclosure. The description reveals nothing about what the tool actually does (generates a plot? returns data?), what happens when invoked (creates output file? displays visualization?), error conditions, or performance characteristics. It's completely inadequate for a tool with 24 parameters.

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

Conciseness2/5

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

While technically concise (one short sentence), this is under-specification rather than effective conciseness. The single sentence doesn't earn its place by providing meaningful information beyond the tool name. No structure or front-loading of key information is present.

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

Completeness1/5

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

For a complex tool with 24 parameters, no annotations, and no output schema, the description is completely inadequate. It doesn't explain what the tool produces (plot? image? data?), how results are returned, or provide any context for when and why to use it. The description fails to compensate for the lack of structured metadata.

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 documents all 24 parameters thoroughly. The description adds zero parameter information beyond what's in the schema. According to guidelines, 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.

Purpose2/5

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

The description 'Heatmap of the expression values of genes' restates the tool name 'pl_heatmap' in slightly different words (tautology). It doesn't specify what action the tool performs (e.g., 'generate', 'plot', 'create') or distinguish it from sibling plotting tools like pl_dotplot, pl_matrixplot, or pl_scatter. The purpose is vague beyond stating it's a heatmap visualization.

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

Usage Guidelines1/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. There are multiple sibling plotting tools (pl_dotplot, pl_matrixplot, pl_scatter, etc.) with no indication of when a heatmap is preferred. No context, prerequisites, or exclusions are mentioned.

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