Skip to main content
Glama

neighbors

Compute nearest neighbors distance matrix and neighborhood graph for single-cell RNA sequencing analysis to identify local cellular relationships and enable downstream manifold learning.

Instructions

Compute nearest neighbors distance matrix and neighborhood graph

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
n_neighborsNoSize of local neighborhood used for manifold approximation.
n_pcsNoNumber of PCs to use. If None, automatically determined.
use_repNoKey for .obsm to use as representation.
knnNoWhether to use hard threshold for neighbor restriction.
methodNoMethod for computing connectivities ('umap' or 'gauss').umap
transformerNoApproximate kNN search implementation ('pynndescent' or 'rapids').
metricNoDistance metric to use.euclidean
metric_kwdsNoOptions for the distance metric.
random_stateNoRandom seed for reproducibility.
key_addedNoKey prefix for storing neighbor results.

Implementation Reference

  • Generic handler that executes the 'neighbors' tool by dispatching to sc.pp.neighbors via the pp_func mapping on the active AnnData object.
    def run_pp_func(ads, func, arguments):
        adata = ads.adata_dic[ads.active]
        if func not in pp_func:
            raise ValueError(f"不支持的函数: {func}")
        
        run_func = pp_func[func]
        parameters = inspect.signature(run_func).parameters
        arguments["inplace"] = True
        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 KeyError as e:
            raise KeyError(f"Can not foud {e} column in adata.obs or adata.var")
        except Exception as e:
           raise e
        return res
  • Pydantic input schema (NeighborsModel) for validating parameters of the 'neighbors' tool.
    class NeighborsModel(JSONParsingModel):
        """Input schema for the neighbors graph construction tool."""
        
        n_neighbors: int = Field(
            default=15,
            description="Size of local neighborhood used for manifold approximation.",
            gt=1,
            le=100
        )
        
        n_pcs: Optional[int] = Field(
            default=None,
            description="Number of PCs to use. If None, automatically determined.",
            ge=0
        )
        
        use_rep: Optional[str] = Field(
            default=None,
            description="Key for .obsm to use as representation."
        )
        
        knn: bool = Field(
            default=True,
            description="Whether to use hard threshold for neighbor restriction."
        )
        
        method: Literal['umap', 'gauss'] = Field(
            default='umap',
            description="Method for computing connectivities ('umap' or 'gauss')."
        )
        
        transformer: Optional[str] = Field(
            default=None,
            description="Approximate kNN search implementation ('pynndescent' or 'rapids')."
        )
        
        metric: str = Field(
            default='euclidean',
            description="Distance metric to use."
        )
        
        metric_kwds: Dict[str, Any] = Field(
            default_factory=dict,
            description="Options for the distance metric."
        )
        
        random_state: int = Field(
            default=0,
            description="Random seed for reproducibility."
        )
        
        key_added: Optional[str] = Field(
            default=None,
            description="Key prefix for storing neighbor results."
        )
        
        @field_validator('n_neighbors', 'n_pcs')
        def validate_positive_integers(cls, v: Optional[int]) -> Optional[int]:
            """Validate positive integers where applicable"""
            if v is not None and v <= 0:
                raise ValueError("must be a positive integer")
            return v
        
        @field_validator('method')
        def validate_method(cls, v: str) -> str:
            """Validate method is supported"""
            if v not in ['umap', 'gauss']:
                raise ValueError("method must be either 'umap' or 'gauss'")
            return v
        
        @field_validator('transformer')
        def validate_transformer(cls, v: Optional[str]) -> Optional[str]:
            """Validate transformer option is supported"""
            if v is not None and v not in ['pynndescent', 'rapids']:
                raise ValueError("transformer must be either 'pynndescent' or 'rapids'")
            return v
  • MCP tool registration for 'neighbors' using types.Tool with schema reference.
    neighbors = types.Tool(
        name="neighbors",
        description="Compute nearest neighbors distance matrix and neighborhood graph",
        inputSchema=NeighborsModel.model_json_schema(),
    )
  • Dictionary mapping 'neighbors' tool name to the actual scanpy.pp.neighbors function implementation.
    pp_func = {
        "filter_genes": sc.pp.filter_genes,
        "filter_cells": sc.pp.filter_cells,
        "calculate_qc_metrics": partial(sc.pp.calculate_qc_metrics, inplace=True),
        "log1p": sc.pp.log1p,
        "normalize_total": sc.pp.normalize_total,
        "pca": sc.pp.pca,
        "highly_variable_genes": sc.pp.highly_variable_genes,
        "regress_out": sc.pp.regress_out,
        "scale": sc.pp.scale,
        "combat": sc.pp.combat,
        "scrublet": sc.pp.scrublet,
        "neighbors": sc.pp.neighbors,
    }
  • Dispatch in top-level call_tool handler to route 'neighbors' (pp tools) to run_pp_func.
    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)
Behavior2/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It states what the tool does but lacks critical behavioral details: it doesn't specify if this is a read-only or mutating operation, what data structures it modifies (e.g., updates an AnnData object), performance characteristics, or error conditions. For a complex tool with 10 parameters, this is a significant gap.

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 and front-loaded: a single sentence that directly states the tool's function without any fluff. Every word earns its place, making it easy for an agent to parse quickly. This is an example of efficient communication.

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?

Given the tool's complexity (10 parameters, no output schema, and no annotations), the description is insufficient. It doesn't explain what the tool returns (e.g., modifies an AnnData object in place or returns a new object), how results are stored, or common pitfalls. For a tool that likely performs critical data analysis steps, more context is needed.

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%, meaning all parameters are documented in the schema itself. The description adds no additional parameter semantics beyond what's already in the schema (e.g., it doesn't explain how parameters interact or typical values). This meets the baseline of 3 when the schema does the heavy lifting, but no extra value is provided.

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: 'Compute nearest neighbors distance matrix and neighborhood graph.' It specifies the verb ('compute') and the resources ('distance matrix and neighborhood graph'), making the function unambiguous. However, it doesn't differentiate from sibling tools like 'umap' or 'tsne' that might also involve neighbor computations, which prevents a perfect score.

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. It doesn't mention prerequisites (e.g., data preprocessing), typical use cases (e.g., for clustering or visualization), or how it relates to sibling tools like 'pca' or 'umap'. This lack of context leaves the agent without clear usage instructions.

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