# Sequence Alignment & Phylogenetic Tree API (MAFFT, FastTree) (`jumblemog/sequence-alignment-tree`) Actor

Align DNA, RNA or protein sequences with MAFFT, MUSCLE or Clustal Omega and build a phylogenetic tree with FastTree. Send FASTA, links or NCBI and UniProt accessions; get the alignment, percent identity, mutations against a reference, a Newick tree and pictures.

- **URL**: https://apify.com/jumblemog/sequence-alignment-tree.md
- **Developed by:** [Jumble Mog](https://apify.com/jumblemog) (community)
- **Categories:** AI, Developer tools, Automation
- **Features:** Limited permissions
- **Stats:** 2 total users, 1 monthly users, 100.0% runs succeeded, 0 bookmarks
- **User rating**: No ratings yet

## Pricing

Pay per event

This Actor is paid per event. You are not charged for the Apify platform usage, but only a fixed price for specific events.

Learn more: https://docs.apify.com/actors/running/actors-in-store.md#pay-per-event

## What's an Apify Actor?

An Actor is a serverless cloud program that runs on the Apify platform. It has two run modes.
In Batch mode, an Actor accepts a well-defined JSON input, performs an action which can take anything from a few seconds to a few hours,
and optionally produces a well-defined JSON output, datasets with results, or files in key-value store.
In Standby mode, an Actor provides a web server which can be used as a website, API, or an MCP server.

Apify vocabulary and the platform model are defined once, in the agent quickstart at https://apify.com/agents.md.

## How to integrate an Actor?

If asked about integration, you help developers integrate Actors into their projects.
You adapt to their stack and deliver integrations that are safe, well-documented, and production-ready.

Do not guess an integration path. Every one of them is in the agent quickstart at https://apify.com/agents.md: the Apify MCP server, Agent Skills with the Apify CLI, the JavaScript and Python clients, the REST API, and the account-free path for an agent with no human to sign in. It also carries the rule on stating cost before the first paid run.

For examples already wired to this Actor's own input schema, see the [API](#api) section below.

Each client library has reference documentation the quickstart does not restate: [JavaScript/TypeScript](https://docs.apify.com/api/client/js/docs.md) (`npm install apify-client`) and [Python](https://docs.apify.com/api/client/python/docs.md) (`pip install apify-client`).

# README

## Sequence Alignment & Phylogenetic Tree API (MAFFT, FastTree)

**Align DNA, RNA or protein sequences and get their phylogenetic tree from one API call.** Send FASTA, a link to a file, or UniProt and NCBI accessions, and you get back:

- **The multiple sequence alignment**, made by [MAFFT](https://mafft.cbrc.jp/alignment/software/) (or MUSCLE 5 or Clustal Omega if you prefer), as text and as FASTA, Clustal, PHYLIP and Stockholm files.
- **Percent identity** for every pair, each sequence's closest relative, and counts of identical, similar, variable and parsimony-informative columns.
- **Differences from a reference**, in the reference's own numbering: substitutions (`P5G`), deletions (`del 44-46`) and insertions (`ins 100^101 GGA`) for every other sequence.
- **A phylogenetic tree** by [FastTree](https://morgannprice.github.io/fasttree/) (approximate maximum likelihood, with support values) or neighbor joining, rooted at the midpoint or at your outgroup, as Newick, as groups in JSON, and as a text drawing.
- **Pictures**: the alignment as colored letters with a conservation bar, and the tree as PNG and SVG.
- **A sentence that says the result**, and a Markdown report with all of the above.

![Seven hemoglobin alpha proteins aligned, with their phylogenetic tree](https://api.apify.com/v2/key-value-stores/Km5b4PG3kYHdZSb1E/records/sequence-alignment-tree-example.png?signature=1Lgct8s6JTRjbZGNhPLlM)

The aligners and the tree builder are the programs researchers install and cite, run here with their published methods. Nothing is estimated by a language model.

It's made for:

- AI agents and research assistants asked "how similar are these proteins?", "which mutations does this clone have?" or "how are these sequences related?". A language model can't align sequences in its head; this gives it a real alignment and tree as JSON.
- Bioinformatics pipelines and notebooks that want MAFFT and FastTree without installing them, in one HTTP call.
- Lab teams who check sequenced clones, variants or isolates against a reference.
- Teachers and students who want an alignment, a tree and pictures of both from a list of accessions.

### How to use it

1. Paste your sequences into **FASTA text**, or list links, accessions or single sequences under **Links, accessions or single sequences**. At least two sequences, all of one kind.
2. Optionally name a **Reference sequence** to get every other sequence's differences from it, and an outgroup under **Root**.
3. Click **Start**. The result is one row with the summary, the figures, the alignment, the tree and links to the files and pictures.

The form opens with a worked example: hemoglobin alpha from seven vertebrates, compared with the human protein.

#### What you can send

| You send | What happens |
|---|---|
| FASTA text (in `fasta`, or as an entry of `sequences` over the API) | Each `>` record is a sequence, named by the first word of its header. UniProt headers get short names: `sp\|P69905\|HBA_HUMAN` becomes `HBA_HUMAN` |
| UniProt accessions or entry names: `P69905`, `HBA_HUMAN`, or several in one entry: `P69905, P01942 P01966` | Fetched from UniProt |
| NCBI accessions: `NP_000549.1` (protein), `NM_000518.5` (nucleotide) | Fetched from NCBI. Write `protein:` or `nuccore:` in front if an accession is read as the wrong kind |
| One sequence as `name: LETTERS` | A sequence with that name |
| A link to a file: FASTA (plain or gzipped), GenBank, or a Clustal or Stockholm alignment | The file's records are read. GitHub, Google Drive and Dropbox share links work. Files up to 8 MB |
| An alignment you already have (rows of one length, gaps as `-`) with `"aligner": "none"` | Kept as it is, then measured and given a tree |
| `example` | The built-in example |

DNA, RNA or protein is recognized from the letters; set `type` for short peptides made only of A, C, G and T.

### Examples

- `{"sequences": ["example"]}` → "Aligned 7 protein sequences over 143 columns with MAFFT (--auto): 33.6% of the columns are identical, and pairs are 67.0% identical on average (45.1% to 88.0%). Closest pair: HBA_HUMAN and HBA_BOVIN (88.0%). Differences from HBA_HUMAN: 17 to 67 per sequence. Tree: FastTree 2, LG+CAT, rooted at the midpoint."
- `{"sequences": ["P69905 P01942 P01966 P01958 P01994 P02012 Q90487"], "root": "HBA_DANRE"}` → the same seven proteins fetched from UniProt, with the tree rooted on the zebrafish protein.
- `{"fasta": ">a\nACGTACGT-ACGGATCCA\n>b\nACGTACGTTACGGATCCA\n>c\nACGAACGT-ACCGATCCA\n>d\nACGAACGT-ACCGATGCA", "aligner": "none", "tree": "nj", "root": "a"}` → "The alignment sent has 4 DNA sequences over 18 columns: 77.8% of the columns are identical, and pairs are 89.2% identical on average (82.3% to 100.0%). Closest pair: a and b (100.0%). Tree: neighbor joining on Jukes-Cantor distances, rooted at the outgroup a."

### How-to examples

The result lines are from runs of these inputs.

#### How to align proteins from UniProt accessions and build a phylogenetic tree

```json
{
  "sequences": ["P69905 P01942 P01966 P01958 P01994 P02012 Q90487"],
  "root": "HBA_DANRE", "labels": "organism", "order": "tree", "title": "Alpha globins"
}
```

Result: seven hemoglobin alpha proteins aligned over 143 columns, 48 of them identical. The tree, rooted on the zebrafish protein, groups human with horse (support 0.792), then cow, then mouse (0.989 for the four mammals), then chicken, then frog. `tree.ascii` draws it with the organisms' names:

```
┌────────────────── Danio rerio (HBA_DANRE)
│
│                 ┌────────────────────────── Xenopus laevis (HBA1_XENLA)
└─────────────────┤
                  │  ┌─────────── Gallus gallus (HBA_CHICK)
                  └──┤
                     │         ┌──── Mus musculus (HBA_MOUSE)
                     └─────────┤
                               │  ┌──── Bos taurus (HBA_BOVIN)
                               └──┤
                                  │ ┌── Homo sapiens (HBA_HUMAN)
                                  └─┤
                                    └──── Equus caballus (HBA_HORSE)
```

#### How to find the mutations in sequenced clones against a reference

```json
{
  "sequences": [
    "wild: ATGGTGAGCAAGGGCGAGGAGCTGTTCACCGGGGTGGTGCCCATCCTGGTCGAGCTGGACGGCGACGTAAACGGCCACAAGTTCAGCGTGTCCGGCGAGGGCGAGGGCGATGCCACCTACGGCAAGCTGACCCTGAAGTTC",
    "clone1: ATGGTGAGCAAGGGCGAGGAGCTGTTCACCGGGGTGGTGCCCATCCTGGTCGAGCTGGACGGTGACGTAAACGGCCACAAGTTCAGCGTGTCCGGCGAGGGCGAGGGCGATGCCACCTACGGCAAGCTGACCCTGAAGTTC",
    "clone2: ATGGTGAGCAAGGGCGAGGAGCTGTTCACCGGGGTGGTGCCCATGGTCGAGCTGGACGGCGACGTAAACGGCCACAAGTTCAGCGTGTCCGGCGAGGGCGAGGGCGATGCCACCTACGGCAAGCTGACCCTGAAGTTC",
    "clone3: GAACTTCAGGGTCAGCTTGCCGTAGGTGGCATCGCCCTCGCCCTCGCCGGACACGCTGAACTTGTGGCCGTTTACGTCGCCGTCCAGCTCGACCAGGATGGGCACCACCCCGGTGAACAGCTCCTCGCCCTTGCTCACCAT",
    "clone4: ATGGTGAGCAAGGGCGAGGAGCTGTTCACCGGGGTGGTGCCCATCCTGGTCGAGCTGGACGGCGACGTAAACGGCCACAAGTTCAGCGTGTCCGGCGAGGGGAGCGAGGGCGATGCCACCTACGGCAAGCTGACCCTGAAGTTC"
  ],
  "reference": "wild", "tree": "none"
}
```

Result: each clone's `differences` from the wild type, numbered on the wild type: clone1 `C63T`, clone2 `del 44-46`, clone3 none, clone4 `ins 100^101 GGA`. clone3 was read on the opposite strand, so it was aligned as its reverse complement, and a note says so: "1 sequence was on the opposite strand and aligned as the reverse complement: clone3."

#### How to build a phylogenetic tree of mRNAs from NCBI accessions

```json
{
  "sequences": ["NM_000518.5 NM_001304883.1 NM_008220.5 NM_173917.2 NM_001246752.1"],
  "aligner": "accurate", "trimGaps": 50, "labels": "organism"
}
```

Result: "Aligned 5 DNA sequences over 646 columns with MAFFT L-INS-i: 55.6% of the columns are identical, and pairs are 80.1% identical on average (74.9% to 87.1%). Closest pair: NM_001304883.1 and NM_173917.2 (87.1%). Tree: FastTree 2, GTR+CAT, rooted at the midpoint." These are beta-globin mRNAs of human, giant panda, mouse, cow and Chinese hamster; the tree puts the two rodents on one side (support 1) and human, panda and cow on the other. A note says 16 of 662 columns were mostly gaps and were taken out.

#### How to let an AI agent align sequences

Add this Actor to the [Apify MCP server](https://mcp.apify.com) with `https://mcp.apify.com/?tools=jumblemog/sequence-alignment-tree`. The agent passes accessions or sequences, and a `reference` if it wants mutations, then reads `summary`, `identity`, `sequences[].differences` and `tree.groups` instead of guessing how similar the sequences are.

### FAQ

**Which aligner should I use?** Leave it on auto. MAFFT then picks its most accurate method (L-INS-i) for small sets and a faster one for large sets. `accurate` asks for L-INS-i outright, for up to 200 sequences of up to 2,000 letters. `fast` is MAFFT FFT-NS-2, for thousands of sequences. MUSCLE 5 and Clustal Omega are there if your protocol names them.

**How is percent identity calculated?** For each pair: the columns where both sequences have the same letter, as a share of the columns where both have a letter. Columns where either has a gap aren't counted, so a sequence with an extra stretch can still be 100% identical to another over what they share. U and T count as the same letter.

**How are the differences from the reference written?** In the reference's numbering, counting its first letter as 1. `P5G` is a substitution: P in the reference at position 5, G in the other sequence. `del 44-46` means the other sequence lacks the reference's positions 44 to 46. `ins 100^101 GGA` means it has GGA between positions 100 and 101. Stretches before a shorter sequence starts or after it ends aren't counted as deletions; `covers` gives the reference positions it spans.

**What do the numbers on the tree's branches mean?** They are FastTree's local support values (a Shimodaira-Hasegawa-like test), from 0 to 1: how well the data backs that group against the nearest alternatives. Above about 0.9 is strong. They aren't bootstrap percentages. Neighbor-joining trees have none.

**Which substitution model does the tree use?** GTR for DNA and RNA and LG for proteins, each with FastTree's CAT approximation for rate variation between sites. `treeModel` switches to Jukes-Cantor, WAG or JTT.

**How is the tree rooted?** At the midpoint of the longest path between two sequences, unless `root` names a sequence to use as the outgroup. Rooting changes how the tree is drawn, not which sequences group together.

**Can it build a tree from an alignment I already have?** Yes. Send the aligned sequences (or a link to a FASTA, Clustal or Stockholm file) with `"aligner": "none"`.

**My sequences are in different directions. Does that matter?** Not for DNA and RNA with MAFFT: a sequence that only fits as its reverse complement is turned around, its row says `reverseComplemented: true` and a note names it. Set `fixDirection` to false to stop that.

**Is this a BLAST search?** No. It compares the sequences you send with each other. It doesn't search a database for similar ones.

**Are my sequences kept or shared?** They are used for your run only and stored in your own Apify run storage, under your account's retention settings. Accessions are looked up at UniProt and NCBI; pasted sequences go nowhere else.

**Does it work with Zapier, Make or n8n?** Yes. Call the Actor with its Apify app or an HTTP request and pass the summary, the files or the pictures on.

### Input

| Field | What it is |
|---|---|
| `fasta` | FASTA text (or Clustal, Stockholm or GenBank text) |
| `sequences` | A list of entries: links, accessions, `name: LETTERS`, FASTA text, or objects `{"name": ..., "sequence": ...}`. Read together with `fasta` |
| `reference` | Name or position (1 is the first) of the sequence to compare the others with |
| `title` | A title for the result and the report |
| `aligner` | `auto` (default), `accurate`, `fast`, `muscle`, `clustalo` or `none` |
| `type` | `auto` (default), `dna`, `rna` or `protein` |
| `fixDirection` | Turn DNA and RNA sequences on the opposite strand (on by default; MAFFT only) |
| `trimGaps` | Take out columns where more than this percent of the sequences have a gap, before the figures and the tree |
| `tree` | `auto` (default: FastTree with three or more sequences), `fasttree`, `nj` or `none` |
| `treeModel` | `auto` (default), `gtr`, `jc`, `lg`, `wag` or `jtt` |
| `root` | `midpoint` (default) or the name of the outgroup sequence |
| `order` | Rows `input` (default: as given) or `tree` (relatives next to each other) |
| `labels` | What the tree picture and text drawing call each sequence: `name` (default), `organism` or `description` |
| `pictures` | Draw the alignment and the tree (on by default) |
| `timeLimitSeconds` | Time the aligner and tree builder may take for one alignment (120 by default, up to 1,800) |
| `jobs` | Several alignments in one run: a list of objects, each with its own `sequences` or `fasta` and any field above. Up to 100 |

### Output

One dataset item per alignment. The run's `OUTPUT` record holds them all: `{"status", "aligned", "failed", "alignments": [...]}`. The built-in example, shortened:

```json
{
  "job": 1, "title": "Hemoglobin alpha in seven vertebrates", "status": "ok",
  "summary": "Aligned 7 protein sequences over 143 columns with MAFFT (--auto): 33.6% of the columns are identical, and pairs are 67.0% identical on average (45.1% to 88.0%). Closest pair: HBA_HUMAN and HBA_BOVIN (88.0%). Differences from HBA_HUMAN: 17 to 67 per sequence. Tree: FastTree 2, LG+CAT, rooted at the midpoint.",
  "sequenceType": "protein", "sequenceCount": 7, "alignmentLength": 143, "aligner": "MAFFT (--auto)",
  "identity": {"mean": 67.0, "min": 45.07, "max": 88.03,
    "mostSimilar": {"a": "HBA_HUMAN", "b": "HBA_BOVIN", "identity": 88.03},
    "leastSimilar": {"a": "HBA1_XENLA", "b": "HBA_DANRE", "identity": 45.07}},
  "columns": {"identical": 48, "identicalPercent": 33.57, "similar": 27, "variable": 94, "parsimonyInformative": 27, "withGaps": 1, "gapPercent": 0.6},
  "consensus": "MVLSAADKTNVKAAWGKIGGHAXEYGAEALERMFLSFPTTKTYFPHF-DLSHGSAQVKGH...",
  "reference": "HBA_HUMAN",
  "sequences": [
    {"name": "HBA_HUMAN", "description": "sp|P69905|HBA_HUMAN Hemoglobin subunit alpha OS=Homo sapiens OX=9606 GN=HBA1 PE=1 SV=2", "organism": "Homo sapiens", "length": 142, "reverseComplemented": false, "differences": [], "differenceCount": 0, "covers": [1, 142], "gaps": 1, "closest": {"name": "HBA_BOVIN", "identity": 88.03}, "meanIdentity": 73.71, "identityToReference": 100.0},
    {"name": "HBA_MOUSE", "organism": "Mus musculus", "length": 142, "differences": ["P5G", "A6E", "T9S", "V11I", "V18I", "A20G", "A22G", "G23A", "L35A", "L49V", "T68A", "N69S", "V71A", "A72G", "V74L", "M77L", "N79G", "A112S", "L114H", "E117D"], "differenceCount": 20, "covers": [1, 142], "gaps": 1, "closest": {"name": "HBA_BOVIN", "identity": 86.62}, "meanIdentity": 73.59, "identityToReference": 85.92, "...": "..."},
    "..."
  ],
  "identityMatrix": {"names": ["HBA_HUMAN", "HBA_MOUSE", "..."], "percent": [[100.0, 85.9, "..."], [85.9, 100.0, "..."], "..."]},
  "tree": {
    "method": "FastTree 2, LG+CAT", "rooting": "midpoint",
    "newick": "(HBA_DANRE:0.50865,(HBA1_XENLA:0.435453,(HBA_CHICK:0.179709,(HBA_MOUSE:0.0559836,(HBA_BOVIN:0.0693965,(HBA_HUMAN:0.0603889,HBA_HORSE:0.0884815)0.792:0.0160003)0.837:0.0365366)0.989:0.170268)0.801:0.0587274):0.0731972);",
    "ascii": "┌──────────── HBA_DANRE\n│ ...",
    "tips": ["HBA_DANRE", "HBA1_XENLA", "HBA_CHICK", "HBA_MOUSE", "HBA_BOVIN", "HBA_HUMAN", "HBA_HORSE"],
    "groups": [{"members": ["HBA_HUMAN", "HBA_HORSE"], "size": 2, "support": 0.792, "branchLength": 0.016}, "..."],
    "support": "SH-like local support, 0 to 1 (FastTree)", "branchLengths": "substitutions per site"
  },
  "alignment": ">HBA_HUMAN\nMVLSPADKTNVKAAWGKVGAHAGEYGAEALERMFLSFPTTKTYFPHF-DLSHGSAQVKGH\n...",
  "alignmentFastaUrl": "https://api.apify.com/v2/key-value-stores/.../records/001-alignment.fasta",
  "alignmentClustalUrl": "...", "alignmentPhylipUrl": "...", "alignmentStockholmUrl": "...",
  "identityCsvUrl": "...", "treeNewickUrl": "...",
  "alignmentImageUrl": "...", "treeImageUrl": "...", "treeSvgUrl": "...",
  "report": "# Hemoglobin alpha in seven vertebrates\n\n...",
  "toolSeconds": 0.4, "notes": [], "error": null
}
```

`tree.groups` lists every inner branch as the set of sequences below it, with its support and length, so a program or an agent can ask "do these sequences group together?" without parsing Newick. `consensus` has the most common letter of each column, with `X` (or `N` for DNA and RNA) where no letter has a majority.

An alignment that can't be made has `"status": "failed"` and the reason in `error`, written so you can tell what to change. One that runs out of time has `"status": "timeout"`.

### How it works

1. **Read the input**: fetch links and accessions, split FASTA, GenBank, Clustal and Stockholm records, clean the letters and decide whether the set is DNA, RNA or protein.
2. **Align** with MAFFT, MUSCLE 5 or Clustal Omega. The program runs in a sandbox: as an unprivileged user, in an empty folder, with no access to tokens, and with limits on time, memory and file size. It only ever sees your sequences under made-up names (`s00001`, `s00002`), so nothing written in a name reaches a command line. Afterwards each row is checked letter by letter against the sequence you sent.
3. **Measure**: pairwise identity, column counts, consensus, and the differences from the reference read off the alignment.
4. **Build the tree** with FastTree, or by neighbor joining on Jukes-Cantor (DNA, RNA) or Kimura (protein) distances, then root it and sort its branches.
5. **Write the files and draw the pictures**, and put the links in the result.

### Pricing

You pay per alignment, at the price shown on this page. One alignment event covers up to 30 seconds of aligner and tree-builder time, which is far more than most sets need; a long alignment costs one more event for each further 30 seconds it starts. An alignment that runs out of time counts for the time it used. Sequences that can't be read or fetched are never charged. If you set a maximum cost per run, the Actor stops before an alignment that wouldn't fit.

### Speed

Measured on one CPU core, aligner and tree together:

| Set | Time |
|---|---|
| Up to a dozen genes or proteins | under 1 second |
| 100 proteins of 350 letters | about 13 seconds |
| 500 proteins of 300 letters | about 30 seconds |
| 60 DNA sequences of 30,000 letters | about 70 seconds |
| 2,000 sequences of 250 letters with `"aligner": "fast"` | about 90 seconds |

Apify gives a run one core for every 4 GB of memory, so the default 2 GB runs at about half these speeds and 4 GB at these speeds. A run through the API adds a few seconds for the cloud container to start, and each database lookup about a second.

### Tips and limits

- **Sizes**: up to 2,000 sequences, 200,000 letters each and 5,000,000 letters in all per alignment; up to 100 alignments per run. Large sets need more time (`timeLimitSeconds`) and may need 4 GB of memory.
- **Identity figures** compare every pair up to 1,000 sequences. The item's `identityMatrix` is included up to 60 sequences; the CSV file has the full matrix.
- **Pictures**: the alignment picture shows up to 80 sequences and 60,000 letters; the tree is drawn up to 400 tips and as text up to 150. The files always have everything.
- **Differences** are listed up to 300 per sequence; `differenceCount` is the full count.
- **The alignment text** is in the item up to 200,000 characters; past that, `alignment` is null and the files have it.
- **Trees need three sequences**, and one sequence per name: repeated names get `_2`, `_3` added.
- **FastTree is fast and approximate.** For a publication tree, take the alignment file to IQ-TREE or RAxML-NG for a full maximum-likelihood search with bootstraps.
- **An alignment is a hypothesis.** Sequences that aren't related, or that share only a short stretch, still come back aligned; low identity and many gaps are the sign. Whole genomes with rearrangements need a genome aligner, not this.
- **NCBI and UniProt lookups** depend on those services; an accession they don't know is named in the error.
- **For research and teaching.** Not for diagnostic or clinical decisions.

### For AI agents and developers

- **Input**: `sequences` alone is enough: accessions, links, FASTA text or `name: LETTERS` entries. Add `reference` for mutations.
- **Output**: `summary` says the result in a sentence; `identity`, `columns` and `sequences` have the figures; `tree.newick` and `tree.groups` have the tree; `report` is Markdown you can show a person.
- **Errors**: `status` is "ok", "timeout" or "failed", with an `error` that says what to change.
- **Cost**: one event per alignment that takes under 30 seconds, nothing for input that can't be read.

Get the results from one HTTP call:

```bash
curl -X POST "https://api.apify.com/v2/acts/jumblemog~sequence-alignment-tree/run-sync-get-dataset-items?token=YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"sequences": ["P69905 P01942 P01966 P01958"], "reference": "HBA_HUMAN"}'
```

`run-sync` instead returns the run's `OUTPUT`: every alignment as JSON.

In Python, with the `apify-client` package:

```python
from apify_client import ApifyClient

client = ApifyClient("YOUR_TOKEN")
run = client.actor("jumblemog/sequence-alignment-tree").call(run_input={
    "fasta": open("my_sequences.fasta").read(), "reference": "1",
})
for item in client.dataset(run["defaultDatasetId"]).iterate_items():
    print(item["summary"])
    for s in item["sequences"]:
        print(s["name"], s["identityToReference"], s["differences"])
    print(item["tree"]["newick"])
```

### Credits

- Alignment: [MAFFT](https://mafft.cbrc.jp/alignment/software/) (BSD). Katoh K, Standley DM. MAFFT multiple sequence alignment software version 7. Molecular Biology and Evolution 2013.
- [MUSCLE 5](https://github.com/rcedgar/muscle) (GPL-3.0). Edgar RC. Muscle5: high-accuracy alignment ensembles enable unbiased assessments of sequence homology and phylogeny. Nature Communications 2022.
- [Clustal Omega](http://www.clustal.org/omega/) (GPL-2.0). Sievers F, et al. Fast, scalable generation of high-quality protein multiple sequence alignments using Clustal Omega. Molecular Systems Biology 2011.
- Trees: [FastTree 2](https://morgannprice.github.io/fasttree/) (GPL-2.0). Price MN, Dehal PS, Arkin AP. FastTree 2: approximately maximum-likelihood trees for large alignments. PLoS ONE 2010.
- Sequences by accession: [UniProt](https://www.uniprot.org/) (CC BY 4.0) and NCBI Protein and Nucleotide, through the E-utilities.

# Actor input Schema

## `fasta` (type: `string`):

Paste the sequences as FASTA: each starts with a > line that names it. At least two sequences in all, of one kind: DNA, RNA or protein, recognized from the letters. Clustal, Stockholm and GenBank text work too.

## `sequences` (type: `array`):

One entry each: a link to a sequence file (FASTA, gzipped FASTA, GenBank, or a Clustal or Stockholm alignment), accessions of public records (UniProt such as P69905 or HBA_HUMAN, NCBI protein such as NP_000549.1, NCBI nucleotide such as NM_000518.5; several in one entry, separated by spaces or commas), or one sequence written as name: LETTERS. Over the API an entry can also be FASTA text. Used together with the FASTA box below. Put example here to run the built-in example.

## `reference` (type: `string`):

Compare every sequence with this one: its name, or its position in the list (1 is the first). Each other sequence then gets its differences in the reference's numbering: substitutions (P5G), deletions (del 45-47) and insertions (ins 88^89 AG). Empty: no comparison.

## `title` (type: `string`):

A title for the result and the report.

## `aligner` (type: `string`):

The program that aligns. Auto suits almost every set. None keeps an alignment you send (every sequence the same length, gaps as -) and only measures it and builds the tree.

## `type` (type: `string`):

Auto reads it from the letters. Set it for short peptides made only of A, C, G and T, which look like DNA.

## `fixDirection` (type: `boolean`):

For DNA and RNA aligned with MAFFT: a sequence that only fits as its reverse complement is turned around, and the result says which ones were.

## `trimGaps` (type: `integer`):

Take out the columns where more than this share of the sequences have a gap, before the figures and the tree. 50 is a common choice for trees. Empty: keep every column.

## `tree` (type: `string`):

How the phylogenetic tree is built. FastTree gives branch support values; neighbor joining is instant and has none.

## `treeModel` (type: `string`):

The model FastTree uses.

## `root` (type: `string`):

Where the tree is rooted: midpoint (halfway along the longest path between two sequences), or the name of a sequence to use as the outgroup.

## `order` (type: `string`):

The order of the rows in the alignment, the files and the picture.

## `labels` (type: `string`):

What the tree picture and the text drawing call each sequence. Organisms are read from database headers (OS=Homo sapiens, \[Homo sapiens]). Data fields and files always use the names.

## `pictures` (type: `boolean`):

Draw the alignment (PNG) and the tree (PNG and SVG).

## `timeLimitSeconds` (type: `integer`):

How long the aligner and the tree builder may run for one alignment. Most sets take a second or two. Time past 30 seconds is billed per started 30 seconds.

## `jobs` (type: `array`):

Several alignments in one run: a list of objects, each with its own sequences (a list of entries as above, or FASTA text in fasta) and any other field: \[{"title": "globins", "sequences": \["P69905 P01942 P01966"]}, {"sequences": \["https://example.org/spike.fasta"], "reference": 1}]. Fields not given come from above. An entry of sequences can also be an object: {"name": "mine", "sequence": "ACGT..."}.

## Actor input object example

```json
{
  "fasta": ">sp|P69905|HBA_HUMAN Hemoglobin subunit alpha OS=Homo sapiens OX=9606 GN=HBA1 PE=1 SV=2\nMVLSPADKTNVKAAWGKVGAHAGEYGAEALERMFLSFPTTKTYFPHFDLSHGSAQVKGHGKKVADALTNAVAHVDDMPNALSALSDLHAHKLRVDPVNFKLLSHCLLVTLAAHLPAEFTPAVHASLDKFLASVSTVLTSKYR\n>sp|P01942|HBA_MOUSE Hemoglobin subunit alpha OS=Mus musculus OX=10090 GN=Hba PE=1 SV=2\nMVLSGEDKSNIKAAWGKIGGHGAEYGAEALERMFASFPTTKTYFPHFDVSHGSAQVKGHGKKVADALASAAGHLDDLPGALSALSDLHAHKLRVDPVNFKLLSHCLLVTLASHHPADFTPAVHASLDKFLASVSTVLTSKYR\n>sp|P01966|HBA_BOVIN Hemoglobin subunit alpha OS=Bos taurus OX=9913 GN=HBA PE=1 SV=2\nMVLSAADKGNVKAAWGKVGGHAAEYGAEALERMFLSFPTTKTYFPHFDLSHGSAQVKGHGAKVAAALTKAVEHLDDLPGALSELSDLHAHKLRVDPVNFKLLSHSLLVTLASHLPSDFTPAVHASLDKFLANVSTVLTSKYR\n>sp|P01958|HBA_HORSE Hemoglobin subunit alpha OS=Equus caballus OX=9796 GN=HBA PE=1 SV=2\nMVLSAADKTNVKAAWSKVGGHAGEYGAEALERMFLGFPTTKTYFPHFDLSHGSAQVKAHGKKVGDALTLAVGHLDDLPGALSNLSDLHAHKLRVDPVNFKLLSHCLLSTLAVHLPNDFTPAVHASLDKFLSSVSTVLTSKYR\n>sp|P01994|HBA_CHICK Hemoglobin subunit alpha-A OS=Gallus gallus OX=9031 GN=HBAA PE=1 SV=2\nMVLSAADKNNVKGIFTKIAGHAEEYGAETLERMFTTYPPTKTYFPHFDLSHGSAQIKGHGKKVVAALIEAANHIDDIAGTLSKLSDLHAHKLRVDPVNFKLLGQCFLVVVAIHHPAALTPEVHASLDKFLCAVGTVLTAKYR\n>sp|P02012|HBA1_XENLA Hemoglobin subunit alpha-1 OS=Xenopus laevis OX=8355 GN=hba1 PE=2 SV=2\nMLLSADDKKHIKAIMPAIAAHGDKFGGEALYRMFIVNPKTKTYFPSFDFHHNSKQISAHGKKVVDALNEASNHLDNIAGSMSKLSDLHAYDLRVDPGNFPLLAHNILVVVAMNFPKQFDPATHKALDKFLATVSTVLTSKYR\n>sp|Q90487|HBA_DANRE Hemoglobin subunit alpha OS=Danio rerio OX=7955 GN=hbaa1 PE=2 SV=3\nMSLSDTDKAVVKAIWAKISPKADEIGAEALARMLTVYPQTKTYFSHWADLSPGSGPVKKHGKTIMGAVGEAISKIDDLVGGLAALSELHAFKLRVDPANFKILSHNVIVVIAMLFPADFTPEVHVSVDKFFNNLALALSEKYR",
  "reference": "HBA_HUMAN",
  "aligner": "auto",
  "type": "auto",
  "fixDirection": true,
  "tree": "auto",
  "treeModel": "auto",
  "root": "midpoint",
  "order": "input",
  "labels": "name",
  "pictures": true,
  "timeLimitSeconds": 120
}
```

# Actor output Schema

## `results` (type: `string`):

One row per alignment: the summary, the pictures and the main files.

## `output` (type: `string`):

The OUTPUT record: every alignment's result in one JSON object.

## `files` (type: `string`):

The alignment files, the trees and the pictures, in the run's key-value store.

# API

You can run this Actor programmatically using our API. Below are code examples in JavaScript, Python, and CLI, as well as the OpenAPI specification and MCP server setup.

## JavaScript example

```javascript
import { ApifyClient } from 'apify-client';

// Initialize the ApifyClient with your Apify API token
// Replace the '<YOUR_API_TOKEN>' with your token
const client = new ApifyClient({
    token: '<YOUR_API_TOKEN>',
});

// Prepare Actor input
const input = {
    "fasta": `>sp|P69905|HBA_HUMAN Hemoglobin subunit alpha OS=Homo sapiens OX=9606 GN=HBA1 PE=1 SV=2
MVLSPADKTNVKAAWGKVGAHAGEYGAEALERMFLSFPTTKTYFPHFDLSHGSAQVKGHGKKVADALTNAVAHVDDMPNALSALSDLHAHKLRVDPVNFKLLSHCLLVTLAAHLPAEFTPAVHASLDKFLASVSTVLTSKYR
>sp|P01942|HBA_MOUSE Hemoglobin subunit alpha OS=Mus musculus OX=10090 GN=Hba PE=1 SV=2
MVLSGEDKSNIKAAWGKIGGHGAEYGAEALERMFASFPTTKTYFPHFDVSHGSAQVKGHGKKVADALASAAGHLDDLPGALSALSDLHAHKLRVDPVNFKLLSHCLLVTLASHHPADFTPAVHASLDKFLASVSTVLTSKYR
>sp|P01966|HBA_BOVIN Hemoglobin subunit alpha OS=Bos taurus OX=9913 GN=HBA PE=1 SV=2
MVLSAADKGNVKAAWGKVGGHAAEYGAEALERMFLSFPTTKTYFPHFDLSHGSAQVKGHGAKVAAALTKAVEHLDDLPGALSELSDLHAHKLRVDPVNFKLLSHSLLVTLASHLPSDFTPAVHASLDKFLANVSTVLTSKYR
>sp|P01958|HBA_HORSE Hemoglobin subunit alpha OS=Equus caballus OX=9796 GN=HBA PE=1 SV=2
MVLSAADKTNVKAAWSKVGGHAGEYGAEALERMFLGFPTTKTYFPHFDLSHGSAQVKAHGKKVGDALTLAVGHLDDLPGALSNLSDLHAHKLRVDPVNFKLLSHCLLSTLAVHLPNDFTPAVHASLDKFLSSVSTVLTSKYR
>sp|P01994|HBA_CHICK Hemoglobin subunit alpha-A OS=Gallus gallus OX=9031 GN=HBAA PE=1 SV=2
MVLSAADKNNVKGIFTKIAGHAEEYGAETLERMFTTYPPTKTYFPHFDLSHGSAQIKGHGKKVVAALIEAANHIDDIAGTLSKLSDLHAHKLRVDPVNFKLLGQCFLVVVAIHHPAALTPEVHASLDKFLCAVGTVLTAKYR
>sp|P02012|HBA1_XENLA Hemoglobin subunit alpha-1 OS=Xenopus laevis OX=8355 GN=hba1 PE=2 SV=2
MLLSADDKKHIKAIMPAIAAHGDKFGGEALYRMFIVNPKTKTYFPSFDFHHNSKQISAHGKKVVDALNEASNHLDNIAGSMSKLSDLHAYDLRVDPGNFPLLAHNILVVVAMNFPKQFDPATHKALDKFLATVSTVLTSKYR
>sp|Q90487|HBA_DANRE Hemoglobin subunit alpha OS=Danio rerio OX=7955 GN=hbaa1 PE=2 SV=3
MSLSDTDKAVVKAIWAKISPKADEIGAEALARMLTVYPQTKTYFSHWADLSPGSGPVKKHGKTIMGAVGEAISKIDDLVGGLAALSELHAFKLRVDPANFKILSHNVIVVIAMLFPADFTPEVHVSVDKFFNNLALALSEKYR`,
    "reference": "HBA_HUMAN"
};

// Run the Actor and wait for it to finish
const run = await client.actor("jumblemog/sequence-alignment-tree").call(input);

// Fetch and print Actor results from the run's dataset (if any)
console.log('Results from dataset');
console.log(`💾 Check your data here: https://console.apify.com/storage/datasets/${run.defaultDatasetId}`);
const { items } = await client.dataset(run.defaultDatasetId).listItems();
items.forEach((item) => {
    console.dir(item);
});

// 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/js/docs

```

## Python example

```python
from apify_client import ApifyClient

# Initialize the ApifyClient with your Apify API token
# Replace '<YOUR_API_TOKEN>' with your token.
client = ApifyClient("<YOUR_API_TOKEN>")

# Prepare the Actor input
run_input = {
    "fasta": """>sp|P69905|HBA_HUMAN Hemoglobin subunit alpha OS=Homo sapiens OX=9606 GN=HBA1 PE=1 SV=2
MVLSPADKTNVKAAWGKVGAHAGEYGAEALERMFLSFPTTKTYFPHFDLSHGSAQVKGHGKKVADALTNAVAHVDDMPNALSALSDLHAHKLRVDPVNFKLLSHCLLVTLAAHLPAEFTPAVHASLDKFLASVSTVLTSKYR
>sp|P01942|HBA_MOUSE Hemoglobin subunit alpha OS=Mus musculus OX=10090 GN=Hba PE=1 SV=2
MVLSGEDKSNIKAAWGKIGGHGAEYGAEALERMFASFPTTKTYFPHFDVSHGSAQVKGHGKKVADALASAAGHLDDLPGALSALSDLHAHKLRVDPVNFKLLSHCLLVTLASHHPADFTPAVHASLDKFLASVSTVLTSKYR
>sp|P01966|HBA_BOVIN Hemoglobin subunit alpha OS=Bos taurus OX=9913 GN=HBA PE=1 SV=2
MVLSAADKGNVKAAWGKVGGHAAEYGAEALERMFLSFPTTKTYFPHFDLSHGSAQVKGHGAKVAAALTKAVEHLDDLPGALSELSDLHAHKLRVDPVNFKLLSHSLLVTLASHLPSDFTPAVHASLDKFLANVSTVLTSKYR
>sp|P01958|HBA_HORSE Hemoglobin subunit alpha OS=Equus caballus OX=9796 GN=HBA PE=1 SV=2
MVLSAADKTNVKAAWSKVGGHAGEYGAEALERMFLGFPTTKTYFPHFDLSHGSAQVKAHGKKVGDALTLAVGHLDDLPGALSNLSDLHAHKLRVDPVNFKLLSHCLLSTLAVHLPNDFTPAVHASLDKFLSSVSTVLTSKYR
>sp|P01994|HBA_CHICK Hemoglobin subunit alpha-A OS=Gallus gallus OX=9031 GN=HBAA PE=1 SV=2
MVLSAADKNNVKGIFTKIAGHAEEYGAETLERMFTTYPPTKTYFPHFDLSHGSAQIKGHGKKVVAALIEAANHIDDIAGTLSKLSDLHAHKLRVDPVNFKLLGQCFLVVVAIHHPAALTPEVHASLDKFLCAVGTVLTAKYR
>sp|P02012|HBA1_XENLA Hemoglobin subunit alpha-1 OS=Xenopus laevis OX=8355 GN=hba1 PE=2 SV=2
MLLSADDKKHIKAIMPAIAAHGDKFGGEALYRMFIVNPKTKTYFPSFDFHHNSKQISAHGKKVVDALNEASNHLDNIAGSMSKLSDLHAYDLRVDPGNFPLLAHNILVVVAMNFPKQFDPATHKALDKFLATVSTVLTSKYR
>sp|Q90487|HBA_DANRE Hemoglobin subunit alpha OS=Danio rerio OX=7955 GN=hbaa1 PE=2 SV=3
MSLSDTDKAVVKAIWAKISPKADEIGAEALARMLTVYPQTKTYFSHWADLSPGSGPVKKHGKTIMGAVGEAISKIDDLVGGLAALSELHAFKLRVDPANFKILSHNVIVVIAMLFPADFTPEVHVSVDKFFNNLALALSEKYR""",
    "reference": "HBA_HUMAN",
}

# Run the Actor and wait for it to finish
run = client.actor("jumblemog/sequence-alignment-tree").call(run_input=run_input)

# Fetch and print Actor results from the run's dataset (if there are any)
print(f"💾 Check your data here: https://console.apify.com/storage/datasets/{run.default_dataset_id}")
for item in client.dataset(run.default_dataset_id).iterate_items():
    print(item)

# 📚 Want to learn more 📖? Go to → https://docs.apify.com/api/client/python/docs/quick-start

```

## CLI example

```bash
echo '{
  "fasta": ">sp|P69905|HBA_HUMAN Hemoglobin subunit alpha OS=Homo sapiens OX=9606 GN=HBA1 PE=1 SV=2\\nMVLSPADKTNVKAAWGKVGAHAGEYGAEALERMFLSFPTTKTYFPHFDLSHGSAQVKGHGKKVADALTNAVAHVDDMPNALSALSDLHAHKLRVDPVNFKLLSHCLLVTLAAHLPAEFTPAVHASLDKFLASVSTVLTSKYR\\n>sp|P01942|HBA_MOUSE Hemoglobin subunit alpha OS=Mus musculus OX=10090 GN=Hba PE=1 SV=2\\nMVLSGEDKSNIKAAWGKIGGHGAEYGAEALERMFASFPTTKTYFPHFDVSHGSAQVKGHGKKVADALASAAGHLDDLPGALSALSDLHAHKLRVDPVNFKLLSHCLLVTLASHHPADFTPAVHASLDKFLASVSTVLTSKYR\\n>sp|P01966|HBA_BOVIN Hemoglobin subunit alpha OS=Bos taurus OX=9913 GN=HBA PE=1 SV=2\\nMVLSAADKGNVKAAWGKVGGHAAEYGAEALERMFLSFPTTKTYFPHFDLSHGSAQVKGHGAKVAAALTKAVEHLDDLPGALSELSDLHAHKLRVDPVNFKLLSHSLLVTLASHLPSDFTPAVHASLDKFLANVSTVLTSKYR\\n>sp|P01958|HBA_HORSE Hemoglobin subunit alpha OS=Equus caballus OX=9796 GN=HBA PE=1 SV=2\\nMVLSAADKTNVKAAWSKVGGHAGEYGAEALERMFLGFPTTKTYFPHFDLSHGSAQVKAHGKKVGDALTLAVGHLDDLPGALSNLSDLHAHKLRVDPVNFKLLSHCLLSTLAVHLPNDFTPAVHASLDKFLSSVSTVLTSKYR\\n>sp|P01994|HBA_CHICK Hemoglobin subunit alpha-A OS=Gallus gallus OX=9031 GN=HBAA PE=1 SV=2\\nMVLSAADKNNVKGIFTKIAGHAEEYGAETLERMFTTYPPTKTYFPHFDLSHGSAQIKGHGKKVVAALIEAANHIDDIAGTLSKLSDLHAHKLRVDPVNFKLLGQCFLVVVAIHHPAALTPEVHASLDKFLCAVGTVLTAKYR\\n>sp|P02012|HBA1_XENLA Hemoglobin subunit alpha-1 OS=Xenopus laevis OX=8355 GN=hba1 PE=2 SV=2\\nMLLSADDKKHIKAIMPAIAAHGDKFGGEALYRMFIVNPKTKTYFPSFDFHHNSKQISAHGKKVVDALNEASNHLDNIAGSMSKLSDLHAYDLRVDPGNFPLLAHNILVVVAMNFPKQFDPATHKALDKFLATVSTVLTSKYR\\n>sp|Q90487|HBA_DANRE Hemoglobin subunit alpha OS=Danio rerio OX=7955 GN=hbaa1 PE=2 SV=3\\nMSLSDTDKAVVKAIWAKISPKADEIGAEALARMLTVYPQTKTYFSHWADLSPGSGPVKKHGKTIMGAVGEAISKIDDLVGGLAALSELHAFKLRVDPANFKILSHNVIVVIAMLFPADFTPEVHVSVDKFFNNLALALSEKYR",
  "reference": "HBA_HUMAN"
}' |
apify call jumblemog/sequence-alignment-tree --silent --output-dataset

```

## MCP server setup

```json
{
    "mcpServers": {
        "apify": {
            "type": "http",
            "url": "https://mcp.apify.com/?tools=fetch-actor-details,jumblemog/sequence-alignment-tree"
        }
    }
}
```

The hosted server signs you in with OAuth on first connect, so no API token belongs in this config. Clients without OAuth support can send an `Authorization: Bearer <APIFY_API_TOKEN>` header instead, using a token from API & Integrations in Apify Console (https://console.apify.com/settings/integrations).

## OpenAPI specification

Download the OpenAPI definition: https://api.apify.com/v2/actors/b4LFARegzuzlozJUQ/builds/mutubeHWpd0JelIzq/openapi.json
