hca-anndata-mcp

v0.10.0
hca-anndata-mcp Checked 3 hours ago Published 9 days ago

MCP server for interactive exploration of AnnData h5ad files

These tools were reported by the server itself during our smoke test (tools/list), not copied from the README.

get_summary

Get a structural summary of an .h5ad file. Returns cell/gene counts, obs/var column names and dtypes, obsm/varm/obsp/varp keys, layers, uns keys, and whether raw data is present. Args: path: Absolute path to an .h5ad file.

ParameterTypeDescription
path *string

get_storage_info

Get HDF5 storage details for an AnnData .h5ad file. Returns file size, compression settings, chunk sizes, and sparse format for X, raw/X, and all layers, plus the string encodings used by the ``obs``, ``var``, ``raw.var`` and obsm dataframes — indexes, plain nullable-string columns, and categoricals. The ``encodings`` block exists so an incompatible on-disk representation surfaces during inspection rather than as an opaque HDF5 error partway through a curation run on a multi-gigabyte file. Its ``unsupported`` list names the nullable-string paths in the file — informational: since #641 no…

ParameterTypeDescription
path *string

get_descriptive_stats

Get descriptive statistics for columns of an AnnData attribute. For numeric columns: count, mean, std, min, 25%, 50%, 75%, max. For categorical columns: count, unique, top, freq. Optionally returns full value_counts for categorical columns. Args: path: Absolute path to an .h5ad file. attribute: One of 'obs', 'var'. Defaults to 'obs'. columns: Column names to describe. If None, describes all columns. value_counts: If True, include full value counts for categorical columns. filter_column: Column name to filter rows by before computing stats. filter_operator: Operator fo…

ParameterTypeDescription
path *string
attributestring
columns
filter_column
filter_operator
filter_value
value_countsboolean

view_data

View a slice of data from an AnnData attribute. For dataframe attributes (obs, var): returns rows as records with column selection. For array attributes (X, layers, obsm, etc.): returns a numeric slice. For uns: returns the value directly (dicts, strings, arrays). Args: path: Absolute path to an .h5ad file. attribute: One of 'obs', 'var', 'X', 'obsm', 'varm', 'obsp', 'varp', 'layers', 'uns'. key: Key within the attribute. Required for obsm, varm, obsp, varp, layers. Optional for uns (omit for a summarized view). columns: Column names to include (for obs/var only).…

ParameterTypeDescription
path *string
attributestring
col_endinteger
col_startinteger
columns
key
row_endinteger
row_startinteger

locate_files

Find all .h5ad files in a directory. Args: directory: Absolute path to the directory to search. recursive: Whether to search subdirectories. Defaults to True. Returns: A dict with 'h5ad' list of absolute file paths.

ParameterTypeDescription
directory *string
recursiveboolean

plot_embedding

Plot a 2D embedding (UMAP, PCA, etc.) colored by an obs column or gene. Returns a dict with base64-encoded PNG data on success, or an error dict. Args: path: Absolute path to an .h5ad file. color: Column in obs or gene name to color by. Defaults to 'cell_type_atlas'. embedding: Key in obsm to use for coordinates (e.g. 'X_umap', 'X_pca'). Defaults to 'X_umap'. title: Plot title. Defaults to '{color} — {embedding}'. palette: Matplotlib colormap or scanpy palette name. legend_loc: Legend location. One of 'right margin', 'on data', 'none'. frameon: Whether to show a…

ParameterTypeDescription
path *string
colorstring
dpiinteger
embeddingstring
frameonboolean
heightnumber
legend_locstring
palette
title
widthnumber

get_cap_annotations

Inspect CAP (Cell Annotation Platform) annotations in an AnnData file. Detects CAP-formatted annotation sets, lists cell labels with their ontology mappings, marker genes, and rationale. Reports schema compliance. Args: path: Absolute path to an .h5ad file. annotation_set: Specific annotation set name to inspect. If None, lists all sets found.

ParameterTypeDescription
path *string
annotation_set

list_uns_fields

List all HCA uns fields with current values and schema metadata. Args: path: Path to an .h5ad file. Returns: Dict with 'filename', 'fields' (list of field info), 'set_count', 'missing_required', 'missing_required_bionetwork', 'extra_uns_keys', 'obs_columns', 'obsm_keys', or 'error'.

ParameterTypeDescription
path *string

set_uns

Set a single HCA uns field with schema validation. Validates the field name and value against the HCA schema, then writes the updated file via write_h5ad() with edit log tracking. Output is written to the same directory as the input file. Args: path: Path to an .h5ad file. field: The uns field name (e.g. 'title', 'study_pi'). value: The value to set. Returns: Dict with 'output_path', 'editing', 'wrote', 'field', 'old_value', 'new_value' on success, or 'error' on failure.

ParameterTypeDescription
field *string
path *string
value *

set_producer_uns

Overwrite scalar values at nested ``uns`` paths outside the HCA schema. All-or-nothing: every requested write is validated against the file before anything is copied, and the file is left untouched if any check fails. The whole batch then lands in one snapshot with one edit-log entry, which matters when the alternative is one full rewrite per field on a file of tens of gigabytes. Addresses by path segments (``["ihbca_provenance", "git_dirty"]``) rather than a slash-joined string, because ``/`` is how h5py spells a link path: a string form would make the checks and the walk capable of disagre…

ParameterTypeDescription
path *string
updates *array

convert_cellxgene_to_hca

Convert a CellxGENE h5ad file to HCA schema format. Uses a hybrid anndata + h5py approach: reads uns via AnnData (backed mode), writes a temp file via anndata for correct encoding, then copies the source and transplants new data via h5py.copy(). Avoids loading the expression matrix into memory. Preserves cellxgene provenance in uns['provenance']['cellxgene'], broadcasts organism from uns to obs, strips HCA-forbidden obs columns (``self_reported_ethnicity_ontology_term_id`` and ``self_reported_ethnicity``) for privacy (see #370), and renames the output from the dataset title. Args: path:…

ParameterTypeDescription
path *string
output_dir

strip_forbidden_obs_columns

Strip HCA-forbidden obs columns from an HCA-layout h5ad file. Removes ``self_reported_ethnicity_ontology_term_id`` and ``self_reported_ethnicity`` from ``obs`` (whichever are present), updates ``obs[column-order]``, and writes a new timestamped edit snapshot with the operation logged in ``uns['provenance']['edit_history']``. Refuses to run on CellxGENE-layout inputs (presence of ``uns['schema_version']``): on those, use :func:`convert_cellxgene_to_hca` instead, which strips these columns as a side-effect of converting to HCA layout. The strip-only path here exists specifically for HCA-layout…

ParameterTypeDescription
path *string

drop_obs_columns

Drop the named obs columns from an h5ad file. All-or-nothing: the whole request is validated before anything is written, and if any column fails any check the file is left untouched and every problem is reported together. There is no partial drop and no ``skipped`` state — unlike :func:`~hca_anndata_tools.strip.strip_forbidden_obs_columns`, whose built-in column list makes "neither present" a normal outcome. Here the caller named the columns, so a name that isn't there is a mistake worth failing on. Drops any obs column the caller names, including schema-named ones — a dropped required c…

ParameterTypeDescription
columns *array
path *string

merge_obs_categories

Recode every cell in ``from_value`` to ``to_value`` and drop the empty category. All-or-nothing: the request is validated before anything is written, and the file is left untouched if any check fails. Both values must already be categories — creating one is a different operation, and a missing value is a caller mistake worth failing on rather than a silent no-op. Exactly one category disappears: the merged-away one. Categories that are empty for their own reasons are left alone, so the result differs from the file only where the caller asked. Merging a ``*_ontology_term_id`` column leaves…

ParameterTypeDescription
column *string
from_value *string
path *string
to_value *string

rename_obs_column

Rename one obs column, preserving everything except its name. The column keeps its position in ``obs[column-order]``, its dtype, its categories and its compression — an HDF5 link rename moves no data, so there is nothing to preserve by hand. ``uns['<column>_colors']`` travels with it, the mirror of :func:`~hca_anndata_tools.drop.drop_obs_columns` deleting that palette: scanpy writes it for any categorical it plots, the palette belongs to the column rather than standing alone, and one left under the old key is orphaned — which the schema validator reports as "Colors field uns[...] does not…

ParameterTypeDescription
column *string
new_name *string
path *string

rename_cell_ids

Rename the cell IDs of rows selected by an obs column value. Selects the rows whose obs ``column`` equals ``value`` and rewrites their obs-index entries from ``prefix_from + <rest>`` to ``prefix_to + <rest>``. All-or-nothing: every gate runs before anything is written, and any failure leaves the file untouched with all problems reported together. The gates, in the order a caller hits them: * **HCA-layout files only.** A file declaring a CellxGENE ``uns['schema_version']`` is refused outright. The motivating case is the CAP export of an atlas: CAP — not the exported file — is the sys…

ParameterTypeDescription
column *string
path *string
prefix_from *string
prefix_to *string
value *string

backfill_obs_from_source

Copy obs values from a source h5ad into a target, filling only gaps. Joins source cells to target cells on the obs index and, for each requested column, writes the source value into every matched target cell whose current value is missing — NaN, empty, or a recognized placeholder such as "unknown" (the same list replace_placeholder_values uses). Values already set in the target are never touched: where a set value disagrees with the source it is counted as a conflict and reported with examples, not overwritten and not an error. Source cells with no matching target cell are skipped silently…

ParameterTypeDescription
columns *array
source_path *string
target_path *string

validate_marker_genes

Validate that CAP marker genes exist in an h5ad file's var. Expects an HCA integrated object with organism_ontology_term_id in obs. Rejects non-human organisms. Checks marker gene symbols from CAP annotation obs columns against var gene names (feature_name, gene_name, or var index as fallback). Missing genes are classified as GENCODE renames, unmeasured genes, or probable typos. Args: path: Absolute path to an HCA .h5ad file. annotation_set: Specific annotation set to validate. If None, validates all. Returns: Dict with validation results, or 'error' on failure.

ParameterTypeDescription
path *string
annotation_set

copy_cap_annotations

Copy CAP cell annotations from source to target h5ad file. Refuses on the first failed check in :mod:`cap_pair`, reading the source's CAP uns and obs columns via h5py, then writes a temp file via anndata for correct encoding, copies the target and transplants the new data via h5py.copy(). Avoids loading either file's expression matrix into memory. Args: source_path: Path to source h5ad with CAP annotations. target_path: Path to target HCA h5ad to receive annotations. overwrite: If True, existing CAP data in the target is first removed by strip_cap_annotations (its own edi…

ParameterTypeDescription
source_path *string
target_path *string
overwriteboolean

copy_matrix_from_file

Copy a count matrix from a source h5ad into a new layer of an HCA-layout target. The target's obs index and var index decide the layer's cells and genes and their order: cells are matched by ID and genes by exact Ensembl ID, and source cells and genes the target lacks are ignored. Every copied value must be a whole, non-negative count that float32 holds exactly and, when the target has ``raw.X``, no greater than it and zero where it is zero. The layer is written as float32 CSR, gzip 4, in a new snapshot, then read back and compared with what was copied. Args: source_path: The h5ad to cop…

ParameterTypeDescription
layer *string
source_matrix *string
source_path *string
target_path *string
chunk_nnzinteger

strip_cap_annotations

Remove all CAP annotation material from an HCA-layout h5ad file. Deletes whichever CAP-written uns keys are present — the legacy top-level ``cellannotation_metadata`` / ``cellannotation_schema_version`` pair, the nested ``cap_metadata`` block, the still-older CAP provenance (``uns['provenance']['cap']`` and unambiguous top-level ``cap_*`` keys), or any mix of those eras — and every obs column whose name contains ``--``, the separator only CAP's serializer uses, along with any ``uns['<column>_colors']`` palette a removed column owns (an orphaned palette breaks the schema validator). A remo…

ParameterTypeDescription
path *string

replace_placeholder_values

Replace placeholder values with NaN in categorical obs columns. Uses direct h5py modification on a copy — does not load the expression matrix into memory. Sets codes to -1 for any value matching the placeholders (case-insensitive). Removes unused categories after replacement. Only categorical columns are supported. Args: path: Path to an .h5ad file. columns: Obs columns to fix. placeholders: Values to replace. Defaults to the HCA placeholder list. Returns: Dict with 'output_path', 'columns_fixed', 'total_cells_affected' and 'palettes_remapped' (the uns palette keys rea…

ParameterTypeDescription
columns *array
path *string
placeholders

compress_h5ad

Rewrite an h5ad file with HDF5 compression applied to chunked datasets. Uses anndata to read the source and write a new file with the requested compression filter applied to all chunked datasets (X, layers, obsm, obsp, varm, varp, and categorical codes in obs/var). The output is written as an edit snapshot (`<stem>-edit-<ts>.h5ad`) and the operation is logged in `uns['provenance']['edit_history']`. Skips by default if X/data already has a compression filter; pass force=True to rewrite anyway (e.g. to change the level). Args: path: Path to an .h5ad file. compression: Compression filt…

ParameterTypeDescription
path *string
compressionstring
compression_levelinteger
forceboolean

normalize_raw

Normalize raw counts in X, moving originals to raw.X. Produces the standard CXG layout: raw integer counts in raw.X, and library-size-normalized, log1p-transformed values in X. Uses the scanpy recipe `normalize_total(target_sum=1e4)` + `log1p`. Classifying each of X and raw.X as empty, counts, or normalized gives nine states. Three are actionable and this handles two of them (#532); the third — counts in raw.X with an empty X — is #572:: raw.X X outcome -------- ----------- -------------------------------------------- absent counts promote + normali…

ParameterTypeDescription
path *string

view_edit_log

Return the edit-log entries recorded in an h5ad file. Args: path: Path to an .h5ad file. Returns: Dict with 'filename', 'edit_count', 'entries' on success, or 'error'. If no edits have been recorded, also includes 'message'.

ParameterTypeDescription
path *string

check_x_normalization

Sample X and report whether it looks like raw counts or normalized data. Reads a small slice via h5py without loading the full matrix. The heuristic is fail-fast, not a full-matrix guarantee: a file whose first entries are integers but whose later entries are fractional will be classified as ``raw_counts``. Args: path: Path to an .h5ad file. sample_size: Requested maximum number of X entries to inspect (default 2000). Must be >= 1. The returned ``sample_size`` is the actual number sampled, which may be less when fewer entries are available (e.g. sparse X with…

ParameterTypeDescription
path *string
sample_sizeinteger

check_raw_counts

Walk the raw count matrix once and report the values a count cannot hold. Gates ``raw.X`` when present, otherwise ``X``. Read-only: never writes, never loads the matrix — one streaming pass in chunks of at most ``chunk_nnz`` stored entries. ``raw.X`` is asserted to be counts, not classified: the schema gives it no other meaning, so a ``raw.X`` holding normalized values is a defect and comes back as ``non_integer_values`` with ``count`` equal to every stored entry. (``normalize_raw`` samples the same matrix and refuses instead — it is about to write on top of it; this tool exists to repor…

ParameterTypeDescription
path *string
chunk_nnzinteger

check_duplicate_cells

Find cells whose raw count rows are identical. A port of Lattice's ``evaluate_dup_counts`` (see the module docstring for provenance and deviations). Hashes the matrix ``check_raw_counts`` gates — ``raw.X`` when present, otherwise ``X`` — once, in bounded chunks, then re-reads only the rows whose hash collides and groups those that are byte-identical after canonicalization. Read-only. Two rows are duplicates only when their sorted column indices and values match exactly. Cells with no stored values are never grouped. CSC storage is refused by name: a row slab cannot be read from it in bou…

ParameterTypeDescription
path *string
chunk_nnzinteger

check_embeddings

Check every embedding in ``obsm`` for the shapes an embedding cannot have. Read-only: one pass per array-encoded ``obsm`` key, in row chunks sized to about ``chunk_nnz`` values and never less than one full row, so the scan's own memory is bounded whatever the array's size. The gate's anndata open (#667) materialises ``obsm`` once before that, as it does for every tool. The count matrix is never touched. Args: path: Path to an .h5ad file. chunk_nnz: Values per chunk; bounds peak memory. Must be >= 1. Returns: Dict with ``filename``, ``n_obs``, ``embeddings`` (each checked key…

ParameterTypeDescription
path *string
chunk_nnzinteger

check_donor_sex

Infer each donor's sex from Y-linked and X-escapee expression and compare it with obs. A port of Lattice's ``evaluate_donors_sex`` (see the module docstring for provenance and deviations). Sums raw counts over seven Y-linked and ten X-escapee genes per donor in one streaming pass over the matrix ``check_raw_counts`` gates — ``raw.X`` when present, otherwise ``X`` — and calls male when ``male / female`` exceeds 0.35, female below 0.05. Read-only. Report-only: nothing here is a validator error. Args: path: Path to an .h5ad file. chunk_nnz: Stored entries per chunk on the streaming…

ParameterTypeDescription
path *string
chunk_nnzinteger

check_barcodes

Report which cells carry a 10x barcode in their ID. Read-only. The body reads the obs index and nothing else — no obs column, no matrix, no ``obsm`` — so its own cost is a regex pass over the IDs, a few seconds on a two-million-cell object. The gate's anndata open (#667) materialises the file's obs, obsm, and uns once before that, as it does for every tool, and on a wide obs that open is the larger share of the wall time. Needs no reference data; whether a barcode is on a 10x whitelist, and which chemistry it implies, is #696. Args: path: Path to an .h5ad file. Returns: Dict wit…

ParameterTypeDescription
path *string

find_source_datasets

Report which tracker source datasets an integrated object's cells come from. Read-only. Locates the candidates from the tracker layout — the sibling ``source-datasets/tracker-source/`` of the nearest ``integrated-objects`` ancestor of ``path`` — and intersects each candidate's obs index with the target's. No matrix in any file is touched: beyond the anndata open that gates each file (which materialises its obs, var, and uns), only the obs index is read. Refuses by name when ``path`` is not under an ``integrated-objects`` directory, when the source directory does not exist or holds no ``.…

ParameterTypeDescription
path *string

set_source_dataset

Write ``obs['source_dataset']``: each cell's tracker source dataset, matched by cell ID. Refuses an export, which we never write to: a file whose name is not a tracker download name (a CAP export is named by its title), or one declaring a CellxGENE schema version or the legacy CAP layout. Recomputes :func:`~hca_anndata_tools.sources.find_source_datasets`'s match and refuses what it refuses; on top of that it writes only a partition, naming the cells that match no source or more than one. The value is each source's tracker name (``hgca-v1-burclaff-2022`` for ``hgca-v1-burclaff-2022-r1-wip-8.h5…

ParameterTypeDescription
path *string

check_cap_currency

Report whether an integrated object's CAP annotations are current with CAP. Read-only; reads uns, no matrix. ``cap_url`` is the tracker's ``cap_url`` for the object. The export carrying it is found by ``cap_dataset_url`` among the ``.h5ad`` files in ``cap-source/`` under the nearest ``integrated-objects`` ancestor. ``behind`` means re-import with ``copy_cap_annotations``; ``export_stale`` means download the current export first. Refuses a path outside the tracker layout or inside ``cap-source/``, an object or matched export in the deprecated top-level CAP layout, and two exports carrying ``c…

ParameterTypeDescription
cap_url *string
path *string

compare_cap_export

Report whether ``copy_cap_annotations`` would accept a CAP export and a target, and how they differ. Writes nothing, and reads no matrix. ``source_path`` is the CAP export and ``target_path`` the file it would annotate, as in the copy; the target resolves to its latest snapshot. The copy stops at its first refusal; this runs every check whose input could be read, and reports the rest as not_run. An obs or var index that cannot be read, or a missing obs group, returns only ``{"error": ...}``, the copy's refusal. Returns: Dict with ``cells`` (overlap and ``within_copy_limit``), ``genes`` (…

ParameterTypeDescription
source_path *string
target_path *string

check_source_obs

Compare an integrated object's obs metadata with its source datasets', cell by cell. Read-only; reads obs, no matrix. Each object cell is matched by ID to the source dataset that holds it, found as ``find_source_datasets`` finds them (the sibling ``source-datasets/tracker-source/`` under the tracker layout), and every field the HCA schema stores in ``obs``, except its deprecated ones, is compared between the two rows by exact value. One allowance: a whole number stored as an int, a float or ``.0`` text compares as its integer text, so ``"2021.0"`` agrees with 2021 and is reported as ``"2021"`…

ParameterTypeDescription
path *string

check_schema_type

Report whether an h5ad file declares the CellxGENE or HCA schema. Detection is conservative: the presence of a non-empty ``uns['schema_version']`` is the CellxGENE signal. HCA-authored files (or anything else) fall through to ``"hca"``. Reads via h5py without loading the matrix. Args: path: Path to an .h5ad file. Returns: Dict with ``filename``, ``schema`` (``"cellxgene"`` or ``"hca"``), and ``schema_version`` (string when CellxGENE, ``None`` otherwise). On failure, ``error`` is returned instead.

ParameterTypeDescription
path *string

validate_schema

Validate an .h5ad file against the HCA schema. Wraps :class:`hca_schema_validator.HCAValidator` and returns a structured verdict. Auto-resolves to the latest timestamped edit snapshot before validating. ``object_kind`` is required: say whether the tracker lists the file as a source dataset or an integrated object. It is never read off the path. The kind chooses the closing sentence of some gene_annotation_version warnings (#774), never which findings fire; the result reports it. Args: path: Path to an .h5ad file. object_kind: ``"source"`` or ``"integrated"``. Returns: Dict with…

ParameterTypeDescription
object_kind *string
path *string

validate_cell_annotation

Validate an .h5ad file against the HCA Cell Annotation schema. Wraps :class:`hca_schema_validator.HCACellAnnotationValidator` — Phase 1 structural checks only (presence of at least one CAP annotation set under ``uns['cap_metadata']``, well-formed ``cellannotation_schema_version``, per-set metadata is a dict, required per-set ``--<suffix>`` obs columns are present). Marker-gene coverage (Phase 2, #363) and CL-term validity (Phase 3, #364) are not checked here; per-set required metadata fields (``description``, ``algorithm_name``, ...) are the upstream CAP-side validator's responsibility. Co…

ParameterTypeDescription
path *string

label_h5ad

Populate derived HCA labels in var (feature_*) and obs from `_ontology_term_id` columns. Wraps :class:`hca_schema_validator.HCALabeler`. Writes a new timestamped edit snapshot and appends to ``uns['provenance']['edit_history']``. **Prefer :func:`populate_labels` for HCA curation.** This tool fills the same labels but also writes ``obs['observation_joinid']``, which HCA does not use and which ``populate_labels`` refuses on — so once this has run, the populator rejects the file from then on, and the labels cannot be refreshed after an ontology update. (The populator reads that column as a Ce…

ParameterTypeDescription
path *string

populate_labels

Fill the HCA label columns on an HCA-layout h5ad, verifying as it goes. The labeler for HCA curation, whatever state the controlled columns are in: it fills missing and all-NaN columns from canonical, and on a partly filled one it verifies every populated row first, filling only the NaN rows. Canonical means two different sources. The 7 obs label columns are checked against the ontology label for their ``*_ontology_term_id``; the 5 ``var['feature_*']`` columns, and their ``raw.var`` mirrors, against GENCODE via the Ensembl ID in the index. A populated value disagreeing with either one is a r…

ParameterTypeDescription
path *string