Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
348 changes: 348 additions & 0 deletions .agents/context.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,348 @@
<!-- GENERATED by installer/ from AGENTS.md + skills/. Do not edit by hand; edit AGENTS.md / skills/ and re-run `spatialai-install`. -->

# AGENTS.md — OpenProblems Spatial Transcriptomics Co-pilot

> Canonical, provider-neutral instructions for any AI coding agent working in this
> repository (Claude Code, OpenAI Codex, Cursor, GitHub Copilot, and others).
> This is the single source of truth. Tool-specific files (`CLAUDE.md`,
> `.cursor/rules/`, `.github/copilot-instructions.md`) are **generated** from this
> file and the `skills/` directory by `installer/` — do not edit them by hand.

## What this project is

A co-pilot for computational biologists working on the
[OpenProblems](https://openproblems.bio) spatial transcriptomics benchmarks. It
ships two things:

1. **An MCP server** (`src/openproblems_mcp/`) — domain-aware validation and
analysis tools for spatial data and bioinformatics workflows, exposed over the
Model Context Protocol so any MCP-capable agent can call them.
2. **A provider-agnostic skill installer** (`skills/`, `context/`, `installer/`) —
author rules/skills/context once here, then project them into whichever agent
the user runs.

## Ground truth: which MCP tools actually exist

Only call tools that are registered. As of now the server is **read-only
analysis** — it validates and inspects, it does **not** execute pipelines.

**Available now:**
`health_check`, `list_tools_status`, `get_server_info`,
`validate_spatial_data`, `validate_multiple_spatial_files`,
`analyze_spatial_metadata`, `check_spatial_data_compatibility`,
`extract_bioinformatics_metadata`, `analyze_workflow_configuration`,
`assess_data_quality`, `analyze_workflow_dependencies`.

**Roadmap — NOT implemented, do not call:**
`run_nextflow_workflow`, `run_viash_component`, `build_docker_image`,
`run_nf_test`, `analyze_nextflow_log`, `create_spatial_component`,
`setup_spatial_environment`, and the OpenProblems build/benchmark/submission
tools. For these actions, drive the user's local `nextflow` / `viash` / `docker`
CLIs directly via the terminal instead, and say so plainly.

## Domain rules (spatial transcriptomics)

- **Validate before processing.** Run `validate_spatial_data` on any input before
reasoning about it. Distinguish raw counts vs. normalized/log-transformed data —
methods have explicit expectations.
- **Prefer SpatialData/zarr.** The current OpenProblems imaging-based spatial
transcriptomics (iST) benchmark is built on the `SpatialData` (zarr) format;
`.h5ad` AnnData is still used for some tables. See
`context/data-formats.md`.
- **Know the pipeline stages.** The `task_ist_preprocessing` benchmark is a
pipeline: preprocessing → segmentation → transcript assignment → cell-type
annotation → expression correction → normalization → QC filtering → count
aggregation → metrics. See `context/ist-preprocessing-pipeline.md`.
- **Components are Viash.** Methods are packaged as Viash components with a
`config.vsh.yaml` and a script; the namespace is built with `viash ns build`.
See `skills/viash-component-authoring/SKILL.md`.

## Coding standards

- **Python**: target 3.10+ (the `fastmcp` dependency requires ≥3.10), format with
`black` (line length 88), lint with `ruff`, type-check with `mypy`. Match
existing module style.
- **Viash components (OpenProblems conventions)**: use the modern flat config
(top-level `name`, `arguments`, `resources`, `engines`, `runners`) — not the
legacy `functionality:` / `platforms:` blocks. Conform to the task's component
API via `__merge__: /src/api/comp_<stage>.yaml`. Build on the shared base
images (e.g. `openproblems/base_python:1`) with `__merge__`-ed setup partials,
not raw `python:*` images. Include the standard metadata (`label`, `summary`,
`description`, `links`, `references`). In scripts, keep the
`## VIASH START` / `## VIASH END` block, use `SpatialData` objects for I/O,
handle coordinate systems explicitly, and fail loudly with a non-zero exit.
- **Reproducibility & verification**: pin package versions and base-image tags
(no unpinned `latest`); add a `viash test` unit test (`test_resources`) per
component; document parameters with biological rationale. See
`skills/viash-component-authoring/SKILL.md` and
`skills/openproblems-submission/SKILL.md`.

## Working in this repo

- Install dev environment: `pip install -e ".[dev]"` (add `[spatial]` for the
heavy scientific stack: spatialdata, zarr, anndata, h5py).
- Run tests: `python -m pytest` (config lives in `pyproject.toml`; there is no
separate `pytest.ini` or `setup.py`).
- Lint/format/type-check: `ruff check src/`, `black src/`, `mypy src/`.
- Health check the server: `openproblems-mcp check`.
- Run the server (normally launched by the agent host over stdio):
`openproblems-mcp-server`.

## Skills

Task-specific playbooks live in `skills/<name>/SKILL.md` (shared Claude/Codex
format: YAML frontmatter + markdown). Load the one matching the task:

- `spatial-data-validation` — validating and inspecting spatial data files.
- `viash-component-authoring` — writing a new Viash method component.
- `nextflow-debugging` — diagnosing Nextflow pipeline failures.
- `openproblems-submission` — preparing a method for an OpenProblems benchmark.

## Conventions for changes

- Keep `README.md` and this file honest about what is actually implemented. If
you add or remove a tool, update both (and the tool lists above).
- Do not advertise execution tools as available until they have code and tests.
- New skills go in `skills/` and are surfaced everywhere by re-running the
installer; do not hand-edit the generated provider files.


# Skill playbooks

Load the one matching your task; full text follows.

---

<!-- skill: nextflow-debugging -->
# Nextflow debugging

The server does not yet parse logs for you (`analyze_nextflow_log` is roadmap), so
triage the logs directly. Be systematic.

## Steps

1. **Find the failing task.** From the run output, note the process name and the
work directory hash (`work/ab/cdef...`). The per-task files there are the
ground truth:
- `.command.sh` — the exact command run.
- `.command.err` / `.command.out` — stderr/stdout.
- `.command.log`, `.exitcode` — exit status.

2. **Classify the error by exit code / message:**
- **137 / OOM-killed** → memory limit. Increase the process `memory` directive
or add a dynamic retry (`memory { 8.GB * task.attempt }`).
- **127 / "command not found"** → tool missing in the container; fix the
component's engine/setup or the image.
- **126 / permission denied** → executable bit / entrypoint issue.
- **File/path errors** → check channel wiring and input staging; confirm the
input file actually exists and matches the expected format
(run `validate_spatial_data`).
- **Config/DSL errors** → confirm DSL2 syntax; OpenProblems pipelines are DSL2.

3. **Add resilience** where appropriate: `errorStrategy 'retry'`, `maxRetries`,
and dynamic resources by `task.attempt`. Don't paper over a real bug with
retries.

4. **Reproduce in isolation.** Re-run a single component with `viash run` on the
test data before re-running the whole pipeline. Use `-resume` to avoid
recomputing successful tasks.

5. **Validate inputs** with `validate_spatial_data` / `analyze_spatial_metadata`
when the failure looks data-shaped (wrong format, missing elements,
raw-vs-normalized mismatch).

## Output

Report: the failing process, the root-cause class, the evidence (the log line),
and the specific fix — plus whether it's a data problem, an environment problem,
or a code problem.

---

<!-- skill: openproblems-submission -->
# OpenProblems submission

Goal: a Viash component that conforms to a task's API, builds cleanly, passes the
test profile, and is reproducible — ready for a PR.

## Checklist

1. **Repo setup.** Clone the target `task_*` repo and initialize the `common/`
git submodule (`git submodule update --init --recursive`). Read the repo's
`CONTRIBUTING` / `README` for current conventions.

2. **Conform to the component API.** Your `config.vsh.yaml` must `__merge__` the
correct `comp_<stage>.yaml` interface and match its inputs/outputs and
`info`/metadata fields. Run `analyze_workflow_configuration` on the config.

3. **Data contract.** Inputs/outputs are SpatialData (zarr) / AnnData as the stage
requires. Validate test data with `validate_spatial_data` and confirm the
elements the stage needs are present (`check_spatial_data_compatibility` for
multi-file). State raw-vs-normalized expectations explicitly.

4. **Reproducibility.** Build on the shared base images
(`openproblems/base_python:1` / `base_r:1`) with `__merge__`-ed setup
partials rather than raw `python:*`/`r-base` images. Pin base-image tags and
package versions — no unpinned `latest`. Provide the standard metadata
(`label`, `summary`, `description`, `links`, `references`/doi) and document
every parameter with a default and biological rationale.

5. **Build & test locally** (server doesn't run these — use the terminal):
- `viash ns build`
- `viash run config.vsh.yaml -- --input <test>.zarr --output tmp/out.zarr`
- `viash test config.vsh.yaml` — a unit test (`test_resources`) is expected
for every component
- `nextflow run main.nf -profile test,docker`

6. **Dependency sanity.** Run `analyze_workflow_dependencies` across the workflow
files to catch missing/conflicting containers or libraries.

7. **PR hygiene.** Include test data + expected output, document parameter
choices, and confirm CI (GitHub Actions) builds and runs the component.

## Don't

- Don't claim the server can build/benchmark/validate-submission automatically —
`build_openproblems_method`, `run_openproblems_benchmark`, and
`validate_openproblems_submission` are roadmap. Use the validation/analysis
tools that exist, and run the build/benchmark steps via local CLIs.

---

<!-- skill: spatial-data-validation -->
# Spatial data validation

Validate first, reason second. Never assume a file's format or contents from its
extension.

## Steps

1. **Detect & validate format.** Call the MCP tool `validate_spatial_data` with
the file path. Choose `validation_level`:
- `basic` — extension/existence only.
- `structure` (default) — format + structural integrity.
- `integrity` — deeper content checks.
- `domain` — spatial-biology-specific expectations.
For several files, use `validate_multiple_spatial_files`.

2. **Read the metadata.** Call `analyze_spatial_metadata` to extract dimensions,
spatial coordinates, and gene/feature info. Confirm `obsm['spatial']` (AnnData)
or coordinate systems (SpatialData) are present when spatial analysis is
intended.

3. **Check raw vs. processed.** Integer-valued matrices are likely raw counts;
non-integer/log-scaled values are processed. State which the downstream method
expects and flag a mismatch.

4. **Check compatibility** when combining files: `check_spatial_data_compatibility`
(coordinate systems + gene overlap).

## Key facts (see `context/data-formats.md`)

- A `.zarr` store is SpatialData **only** if it has SpatialData markers or ≥2 of
`images/ labels/ points/ shapes/ tables/`. Otherwise it's a plain zarr array.
- iST datasets can be terabytes. Default to lightweight structural checks; avoid
loading whole objects. The heavy scientific stack (`pip install -e ".[spatial]"`)
is optional — the validators degrade gracefully without it.

## Don't

- Don't claim a file is valid SpatialData without inspecting contents.
- Don't call execution tools (e.g. `run_nextflow_workflow`) — they aren't
implemented. Drive local CLIs directly if execution is needed.

---

<!-- skill: viash-component-authoring -->
# Viash component authoring

A Viash component = a `config.vsh.yaml` (metadata: arguments, resources, engines)
+ a script (Python/R/Bash). Viash compiles it into a CLI, a Docker image, and a
Nextflow module.

## Steps

1. **Identify the stage and its interface.** OpenProblems components conform to a
`comp_*` API merged in via `__merge__: /src/api/comp_<stage>.yaml`. Find the
right interface for the pipeline stage you're implementing (see
`context/ist-preprocessing-pipeline.md`) and match its inputs/outputs exactly.

2. **Write `config.vsh.yaml`.** Use the modern **flat** config (no
`functionality:` wrapper) with `engines:` / `runners:` (not the legacy
`platforms:`). Follow OpenProblems conventions: merge the stage API, build on
the shared base image with a setup partial, include the standard metadata
block, and label the nextflow runner with resource directives. This mirrors a
real `task_ist_preprocessing` component:

```yaml
__merge__: /src/api/comp_<stage>.yaml

name: my_method
label: "My Method"
summary: "One-line biological purpose."
description: "Longer description with method context."
links:
documentation: "https://github.com/openproblems-bio/task_ist_preprocessing"
repository: "https://github.com/openproblems-bio/task_ist_preprocessing"
references:
doi: "10.xxxx/xxxxx" # the method's paper

arguments:
- name: "--some_param"
type: double
default: 1.0
description: "Biologically meaningful parameter."
# Note: --input/--output are usually inherited from the merged comp_<stage> API.

resources:
- type: python_script
path: script.py

engines:
- type: docker
image: openproblems/base_python:1 # shared base, not raw python:*
__merge__:
- /src/base/setup_spatialdata_partial.yaml # extra deps via setup partial
- type: native

runners:
- type: executable
- type: nextflow
directives:
label: [ midtime, lowcpu, lowmem ] # resource labels
```

Confirm the exact `__merge__` paths (the stage API and the base setup partial)
and the current Viash schema against the live repo before building — keys
evolve between major Viash versions.

3. **Write the script** with the dev parameter block:

```python
import spatialdata as sd

## VIASH START
par = {"input": "resources_test/.../dataset.zarr", "output": "output.zarr", "some_param": 1.0}
## VIASH END

sdata = sd.read_zarr(par["input"])
# ... implement; keep coordinate systems consistent ...
result.write(par["output"])
```

Fail loudly: log the error and `sys.exit(1)` on failure.

4. **Validate before building.** Run `analyze_workflow_configuration` on the
`config.vsh.yaml` to catch structural/dependency issues.

5. **Build & test** with the user's local Viash (the server does not run it):
- `viash ns build`
- `viash run config.vsh.yaml -- --input <test>.zarr --output tmp/out.zarr`
- unit test: add a `test_resources` script (e.g. `test.py`) to the config and
run `viash test config.vsh.yaml` — every OpenProblems component ships a test.
- integration: `nextflow run main.nf -profile test,docker`

## Don't

- Don't invent `create_spatial_component` / `build_viash_component` tool calls —
they're roadmap, not implemented. Generate files and run `viash` in the terminal.
11 changes: 11 additions & 0 deletions .agents/mcp_config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"mcpServers": {
"openproblems-spatial": {
"command": "openproblems-mcp-server",
"args": [],
"env": {
"OPENPROBLEMS_MCP_LOG_LEVEL": "INFO"
}
}
}
}
Loading
Loading