evo2-mcp-server
Evo2-7B Bioinformatics MCP Server
Сервер, который оборачивает размещённый NVIDIA Evo2-7B Forward API в инструменты MCP (Model Context Protocol), позволяя агентам вроде Claude Code, Cursor, Codex управлять Evo2 на естественном языке:
Agent
↓
MCP Tool
↓
Evo2 MCP Server(本项目)
↓
NVIDIA Evo2-7B Forward API
↓
forward outputs → likelihood / variant scores
↓
AgentPOST https://health.api.nvidia.com/v1/biology/arc/evo2-7b/forward
Authorization: Bearer $NVIDIA_API_KEY1. Описание проекта
Предоставляет 5 MCP-инструментов:
Tool | Назначение |
| Выполняет forward inference Evo2-7B для DNA-последовательности, возвращает статистику выходов указанного слоя (или сохраняет исходный тензор) |
| Вычисляет model-based likelihood Evo2 для DNA-последовательности (total / mean / per-position) |
| Сравнивает влияние одиночного нуклеотидного варианта на likelihood последовательности Evo2 (Δ log-likelihood) |
| Пакетно сравнивает несколько нуклеотидных вариантов (один WT forward переиспользуется, конкурентность ограничена, автоматическая дедупликация) |
| Оценивает каждую запись в FASTA (локальные пути ограничены песочницей |
Этот проект — Bioinformatics MCP Tool Server, а не простой HTTP API-обёртка:
Автоматическая валидация / нормализация DNA-последовательностей (заглавные буквы, удаление пробелов, явная ошибка при недопустимых символах)
Вычисление likelihood на основе официальной семантики (byte-level tokenizer + causal shift, см. §17)
Многоуровневый дизайн вывода (summary / raw / save) для предотвращения раздувания MCP-контекста
Полная классификация ошибок (400/401/403/404/408/413/422/429/5xx/timeout) + retry/backoff
API-ключ читается только из переменных окружения, никогда не захардкожен и не попадает в логи
В комплекте пакетные скрипты:
scripts/score_fasta.py(пакетная оценка FASTA + извлечение эмбеддингов, см. §18) иscripts/analyze_run.py(нисходящий анализ: кластеризация/классификация/регрессия, см. §19)
Related MCP server: bio-mcp-evo2
2. Обзор Evo2 API
Evo2 (Arc Institute / NVIDIA) — это фундаментальная модель DNA (архитектура StripedHyena2), версия 7B имеет 32 слоя, лицензия Apache-2.0, обучающий контекст до 1M bp. NVIDIA предоставляет размещённый сервис NIM:
Forward endpoint:
POST https://health.api.nvidia.com/v1/biology/arc/evo2-7b/forwardТело запроса (официальная OpenAPI-схема
ForwardInputs):{ "sequence": "ACGTACGT...", "output_layers": ["output_layer"] }output_layersподдерживает 1–100 имён слоёв (например,output_layer,decoder.layers.24.mlp.linear_fc2,decoder.layers.3.self_attention,embedding,decoder.final_norm).Тело ответа (официальная OpenAPI-схема
ForwardOutputs):{"data": "<base64-кодированный NPZ>", "elapsed_ms": <int>}; очень большие ответы могут возвращаться сContent-Type: application/zip(сырые байты NPZ).output_layer= финальные logits, форма[seq_len, batch_size, 512](512 — это padded vocabulary size byte-level токенизатора).
⚠️ Предупреждение об устаревании (проверено 2026-08-24): endpoint
arc/evo2-7b, размещённый на build.nvidia.com, помечен как Deprecated (на странице указано "This NIM Endpoint has been deprecated"). API, описанный в официальной документации NIM (docs.nvidia.com/nim/bionemo/evo2/latest/), полностью совпадает с размещённым endpoint'ом; если размещённый endpoint недоступен, можно перейти на самостоятельный контейнер NIM, указавEVO2_MCP_BASE_URLнаhttp://localhost:8000/biology/arc/evo2.
Проверенные официальные факты (основа реализации, 2026-08-24)
Пункт | Вывод | Источник |
Формат ответа | JSON | Документация NVIDIA NIM endpoints + размещённая OpenAPI-схема ( |
Форма |
| Там же ("Final output/logits") |
Размер vocabulary | 512 (padded); byte-level токенизатор, 1 bp = 1 токен | Документация NVIDIA + Arc/vortex |
A/C/G/T → индекс logits | A=65, C=67, T=84, G=71 (значения ASCII-байтов) | Оригинальный текст документации NVIDIA + |
BOS/EOS/offset | По умолчанию без BOS (Arc | Arc |
Вычисление likelihood |
| Arc |
Специальные токены | В выходе значимы только 4 токена A/C/G/T (оригинальный текст документации NIM) | Документация NVIDIA |
Различия между документацией и реальным API (live-проверка 2026-08-24, по заданию зафиксирован фактический интерфейс)
Пробное обращение к размещённому endpoint'у health.api.nvidia.com с реальным ключом показало, что имена слоёв из документации не работают на размещённом endpoint'е:
Запрошенное имя слоя | Фактическое поведение размещённого API |
| ❌ |
| ❌ 422 |
| ✅ Финальные logits: ключ NPZ |
| ✅ |
| ✅ |
| ✅ |
Принятые меры (реализованы и проверены в live-режиме):
Добавлена конфигурация
EVO2_MCP_LOGITS_LAYER(по умолчаниюauto): инструменты оценки сначала пробуют имя из документацииoutput_layer; при получении422 has no attribute(размещённый endpoint) автоматически переключаются наunembedс кэшированием, после чего повторное зондирование не выполняется; самостоятельный контейнер NIM 2.x срабатывает с первого раза, без лишних запросов.Парсер NPZ поддерживает как голые ключи (
output_layer), так и формат<имя>.output(unembed.output), с эвристическим запасным вариантом по признаку "последнее измерение = 512".Сообщение об ошибке
422теперь подсказывает доступные имена атрибутов для размещённого endpoint'а.
Если возвращаемый
seq_lenне совпадает с длиной входной последовательности (например, сервер добавил padding/BOS), этот сервер отказывается вычислять likelihood и возвращает raw-статистику с явным пояснением — никаких догадок о выравнивании.
3. Как получить NVIDIA API Key
Откройте https://build.nvidia.com/, в правом верхнем углу Get API Key (требуется вход в аккаунт NVIDIA).
Создайте ключ (вида
nvapi-xxxxxxxx...).Задайте его в переменной окружения, не записывайте в код / конфигурацию / Git:
export NVIDIA_API_KEY="nvapi-xxxxxxxx"Либо скопируйте
.env.exampleв.envи заполните (.envуже игнорируется в.gitignore).
4. Установка
# 推荐:pip / uv
pip install -e ".[dev]"
# 或
uv sync --extra dev
# 推荐(本项目自带):pixi 项目本地环境
pixi install
pixi run testТребуется Python >= 3.10 (рекомендуется 3.11+). Основные зависимости: mcp>=2.0, httpx>=0.27, numpy>=1.26, pydantic>=2.6, python-dotenv>=1.0. Для аналитических скриптов (scripts/analyze_run.py) дополнительно нужны dev-зависимости: scikit-learn, pandas, matplotlib.
5. Переменные окружения
Переменная | По умолчанию | Описание |
| нет (обязательна) | API-ключ, читается только отсюда |
|
| Адрес сервиса (изменить при самостоятельном размещении NIM) |
|
| HTTP-таймаут чтения (секунды) |
|
| Максимальное число повторов при 408/429/5xx |
|
| Верхний предел конкурентности для batch/FASTA |
| пусто | Каталоги, из которых разрешено читать FASTA (разделитель |
|
| Каталог вывода для |
|
| При значении |
|
| Жёсткий верхний предел длины последовательности |
|
| Верхний предел общего числа элементов тензора для инлайна при |
|
| Верхний предел возвращаемого списка per-position (при превышении — начало и конец) |
|
| Имя слоя logits для оценки: |
6. Запуск из CLI
# 三种方式等价
python -m evo2_mcp
evo2-mcp
uv run evo2-mcp # 用 uv 管理的项目环境
# pixi 环境:
pixi run evo2-mcpСервер общается с MCP-клиентом через stdio; после нормального запуска вывода не будет (ожидание MCP-рукопожатия).
7. Конфигурация MCP
Claude Code (.mcp.json)
{
"mcpServers": {
"evo2": {
"command": "uv",
"args": ["run", "evo2-mcp"],
"env": {
"NVIDIA_API_KEY": "${NVIDIA_API_KEY}"
}
}
}
}Примечание: раскрытие
${NVIDIA_API_KEY}клиентом зависит от реализации клиента. Самый надёжный способ — подставить реальный ключ напрямую:
{
"mcpServers": {
"evo2": {
"command": "uv",
"args": ["run", "evo2-mcp"],
"env": {
"NVIDIA_API_KEY": "YOUR_API_KEY"
}
}
}
}Но ни в коем случае не коммитьте .mcp.json с реальным ключом в Git (добавьте этот файл в .gitignore или используйте переменные окружения / менеджер секретов для инъекции). Можно также не передавать env вовсе — процесс сервера сам прочитает NVIDIA_API_KEY из окружения или .env:
{
"mcpServers": {
"evo2": {
"command": "uv",
"args": ["run", "evo2-mcp"]
}
}
}Cursor (~/.cursor/mcp.json или проектный .cursor/mcp.json)
{
"mcpServers": {
"evo2": {
"command": "uv",
"args": ["run", "evo2-mcp"],
"env": { "NVIDIA_API_KEY": "YOUR_API_KEY" }
}
}
}Codex (~/.codex/config.toml)
[mcp_servers.evo2]
command = "uv"
args = ["run", "evo2-mcp"]
env = { "NVIDIA_API_KEY" = "YOUR_API_KEY" }Самостоятельно размещённый NIM
{
"mcpServers": {
"evo2": {
"command": "uv",
"args": ["run", "evo2-mcp"],
"env": {
"EVO2_MCP_BASE_URL": "http://localhost:8000/biology/arc/evo2"
}
}
}
}8. Список инструментов
evo2_forward(sequence, output_layers=["output_layer"], mode="summary", save_path=None)
Выполняет forward inference Evo2-7B для DNA-последовательности. mode:
"summary"(по умолчанию): для каждого слоя возвращаетshape / dtype / min / max / mean / std, безопасно для контекста;"save": сохраняет исходный тензор в.npz(output/evo2_forward_<временная_метка>.npz), возвращает путь;"raw": инлайн полного тензора (только если общее число элементов ≤EVO2_MCP_RAW_INLINE_MAX, по умолчанию 4096, чтобы не раздувать контекст).
Внимание к именам слоёв: размещённый endpoint
health.api.nvidia.comпринимает имена атрибутов модели (для logits —unembed, также естьembedding_layer,norm,blocks.N.mlp); имена из документацииoutput_layer/decoder.layers.N.*применимы только к самостоятельно размещённому контейнеру NIM 2.x.evo2_score/evo2_variant_score/evo2_batch_score/evo2_score_fastaопределяют это автоматически, указывать вручную не нужно; только при прямом вызовеevo2_forwardимя нужно выбирать по фактическому endpoint'у.
evo2_score(sequence, include_per_position=False)
Вычисляет likelihood Evo2 для последовательности:
{
"sequence_length": 123,
"total_log_likelihood": -123.45,
"mean_log_likelihood": -1.2345,
"scored_positions": 122,
"per_position_log_likelihood": null,
"method_notes": "...",
"disclaimer": "..."
}Семантика (совпадает с официальной реализацией Arc): logits[i] предсказывает основание в позиции i+1; после log-softmax по полному vocabulary из 512 берётся индекс байта целевого основания; позиция 0 не участвует в оценке, поэтому scored_positions = length - 1, а mean — это среднее по этим N-1 значениям. per_position_log_likelihood[k] соответствует 0-based позиции k+1 последовательности (то есть 1-based позиции k+2). Если seq_len, возвращённый API, невозможно выровнять с последовательностью, результат не подделывается — возвращается raw-статистика с явным пояснением:
Likelihood calculation is not supported until the API output format is verified.evo2_variant_score(sequence, position, ref, alt, coordinate="1-based", include_per_position=False)
{
"position": 100,
"ref": "A",
"alt": "G",
"wildtype_log_likelihood": -500.1,
"mutant_log_likelihood": -500.5,
"delta_log_likelihood": -0.4,
"interpretation": "The mutant sequence is less likely than the wildtype under Evo2-7B ... (NOT a clinical pathogenicity call)"
}Цепочка проверок: диапазон position → пересчёт coordinate → ref должен совпадать с основанием последовательности в этой позиции → ref≠alt → позиция 1 в 1-based (0 в 0-based) не подлежит оценке (causal LM не может присвоить вероятность первому токену) → явная ошибка.
evo2_batch_score(sequence, variants, coordinate="1-based")
{
"sequence_length": 300,
"wildtype_log_likelihood": -1200.0,
"variants": [
{ "position": 100, "ref": "A", "alt": "G", "delta_log_likelihood": -0.42 },
{ "position": 200, "ref": "C", "alt": "T", "delta_log_likelihood": 0.13 }
]
}WT forward вычисляется только один раз и переиспользуется для всех вариантов;
мутант с одинаковыми
(position, alt)форвардится только один раз (memoize);конкурентность ограничена
EVO2_MCP_MAX_CONCURRENCY(по умолчанию 2, с учётом rate limit NVIDIA);сбой одного варианта не влияет на весь batch (для каждого возвращается
error).
evo2_score_fasta(fasta_path=None, fasta_text=None)
>sequence_1
ACGTACGT...
>sequence_2
TTGGCCAA...fasta_text: инлайн-FASTA (доступен по умолчанию, с ограничениями по размеру и числу записей);fasta_path: чтение разрешено только если файл находится внутриEVO2_MCP_ALLOWED_DIRS, иначе явный отказ;Для каждой записи возвращается
total_log_likelihood / mean_log_likelihood, ошибка одной записи не влияет на остальные.
9. Примеры использования
{
"sequence": "acgtACGT acgt", // 小写 + 空白自动处理
"output_layers": ["output_layer"],
"mode": "summary"
}Возвращает:
{
"sequence_length": 12,
"requested_output_layers": ["output_layer"],
"returned_layers": ["output_layer"],
"layer_stats": [
{ "name": "output_layer", "shape": [12, 1, 512], "dtype": "float32",
"size": 6144, "min": -3.21, "max": 4.02, "mean": 0.01, "std": 0.98 }
],
"api": { "elapsed_ms": 87 }
}Когда агенту нужны полные logits:
{ "sequence": "ACGT...", "mode": "save" }{
"saved": true,
"path": "/abs/path/output/evo2_forward_20260824_153000.npz",
"bytes_on_disk": 24576,
"layer_stats": [...]
}10. Пример FASTA
{
"fasta_text": ">geneA\nACGTACGTACGT\n>geneB\nTTGGCCAATTGG"
}(или "fasta_path": "/data/genomes/genes.fa", требуется настройка EVO2_MCP_ALLOWED_DIRS=/data/genomes)
Для массовой оценки FASTA (например, enhancer/promoter в целой директории) + извлечения эмбеддингов используйте scripts/score_fasta.py (см. §18) — каждый запуск создаёт отдельную папку run (scores.csv + embeddings.npz).
11. Пример variant scoring
{
"sequence": "ACGTACGTACGTACGTACGT",
"position": 10,
"ref": "A",
"alt": "G"
}12. Пример batch scoring
{
"sequence": "ACGTACGTACGTACGTACGT",
"variants": [
{ "position": 10, "ref": "A", "alt": "G" },
{ "position": 12, "ref": "T", "alt": "C" },
{ "position": 14, "ref": "A", "alt": "T" }
]
}Типичный рабочий процесс агента (соответствует задаче "проанализировать все SNP на последовательности, найти топ-20 по изменению Evo2 score"):
读取输入 → 解析 DNA / VCF → 生成 WT / mutant → evo2_batch_score
→ 按 |delta_log_likelihood| 排序 → 取前 20 → 保存 CSV → 解释结果13. Обработка ошибок
HTTP | Значение | Поведение этого сервера |
400 | Bad Request (включая недопустимую последовательность и т.п.) | Немедленная ошибка с кратким описанием ответа |
401 | Недействительный API Key | Немедленная ошибка с подсказкой проверить |
403 | Нет прав (управляемая конечная точка устарела и т.п.) | Немедленная ошибка с указанием возможных причин |
404 | Путь не существует | Немедленная ошибка с подсказкой проверить |
408 | Таймаут на стороне сервера | Ошибка после ограниченных повторных попыток (backoff) |
413 | Payload слишком большой | Немедленная ошибка с подсказкой уменьшить последовательность или количество слоёв |
422 | Ошибка валидации параметров | Немедленная ошибка с подробностями |
429 | Rate limit | Повторные попытки + exponential backoff (с учётом |
5xx | Ошибка сервера NVIDIA | Ошибка после ограниченных повторных попыток |
timeout | Таймаут запроса ( | Явная ошибка: |
Все ошибки возвращаются через MCP в виде структурированного JSON: {"error": "Evo2APIError", "message": "..."}. В evo2_batch_score при сбое одной записи возвращается {"error": ..., "status": ...}, без прерывания всего батча.
14. Rate limit
У управляемого NIM от NVIDIA есть rate limit. Предусмотренные меры:
EVO2_MCP_MAX_CONCURRENCY(по умолчанию 2) ограничивает параллелизм;429 → exponential backoff (1с, 2с, 4с, 8с, 16с…, с потолком 30с + джиттер; при наличии
Retry-Afterон имеет приоритет, но с потолком 60с);лимит повторных попыток
EVO2_MCP_MAX_RETRIES(по умолчанию 4), бесконечных повторов не будет;в батче WT считается только один раз, одинаковые мутанты дедуплицируются — это сокращает число запросов.
15. Замечания по безопасности
API Key: читается только из переменной окружения
NVIDIA_API_KEY(или.env); в коде нет ни одного захардкоженного ключа; в логах фиксируются только URL, длина последовательности и имя слоя, содержимое последовательностей и ключи не логируются; сообщения об ошибках содержат только краткое описание первых 500 символов ответа.Конфиденциальность последовательностей: все логи/ошибки содержат только
preview(например,ACGT...GCTA (len=12345)).Песочница путей:
чтение FASTA разрешено только из
EVO2_MCP_ALLOWED_DIRS; если не настроено — любые локальные пути отклоняются;save_pathв режимеmode="save"должен находиться внутриEVO2_MCP_OUTPUT_DIR;
.gitignoreуже включает.env,*.env,output/,*.npz.N-основания: по умолчанию отклоняются с явной ошибкой (модель Evo2 не тестировалась на неоднозначных основаниях; документация гарантирует осмысленность только A/C/G/T). Если N действительно нужно пропускать, запускайте с
EVO2_MCP_ALLOW_AMBIGUOUS=1— это явный выбор, а не молчаливое отбрасывание.Don't execute: этот сервер не выполняет никаких shell-команд; через FASTA/входные последовательности агент может инициировать только ограниченные HTTP-запросы.
16. Ограничения биологической интерпретации
Evo2 score — это изменение правдоподобия последовательности на основе модели, а не экспериментальное доказательство и тем более не клинический диагноз патогенности.
delta_log_likelihood < 0можно интерпретировать только как «мутантная последовательность менее вероятна по модели», но не как «патогенна».Для разговора о патогенности необходима downstream-валидация (эксперименты, частоты в популяции, аннотации ClinVar, влияние на структуру белка и т.д.).
В описании каждого Tool присутствует следующее заявление (видимое MCP-клиентам):
This is a DNA foundation model inference tool. It does not provide clinical
diagnosis. Model scores should not be interpreted as pathogenicity labels
without additional validation.17. Основания реализации и источники валидации (2026-08-24)
NVIDIA NIM for Evo 2 — Endpoints: https://docs.nvidia.com/nim/bionemo/evo2/latest/endpoints.html
NVIDIA NIM for Evo 2 — Quickstart: https://docs.nvidia.com/nim/bionemo/evo2/latest/quickstart-guide.html
Справочник управляемого API NVIDIA (OpenAPI-схема arc/evo2-7b-forward): https://docs.api.nvidia.com/nim/reference/arc-evo2-7b-infer
Практическое тестирование управляемой конечной точки (2026-08-24, реальный ключ):
output_layerвозвращает 422StripedHyena has no attribute 'output_layer';unembedвозвращает logits (ключ NPZunembed.output, shape(1, seq, 512), float64) — поэтому инструмент оценки по умолчанию используетEVO2_MCP_LOGITS_LAYER=autoс автоматическим определениемПрактическое тестирование батчами (2026-08-25, реальный ключ, 3800+ записей K562 enhancer/promoter):
при длине последовательности > ~100 kb управляемая сторона возвращает 422 (ограничение PyTorch
canUse32BitIndexMath) — для батчей используйте--skip-longer-than 100000;гонка при автоматическом определении имени слоя в условиях параллелизма исправлена (
forward_logitsиспользует локальную переменную для запоминания испытанных имён) и добавлен регрессионный тест;извлечение эмбеддингов:
norm/embedding_layer/blocks.N— все работают, shape(1, seq, 4096)float64 (после mean-pool — 4096 измерений).
Репозиторий Arc Institute Evo2 (
scoring.py,models.py): https://github.com/ArcInstitute/evo2vortex
CharLevelTokenizer(официальная реализация токенизатора Evo2): исходный код PyPIvtx1.1.0,vortex/model/tokenizer.pyКарточка модели Evo2: https://huggingface.co/ArcInstitute/evo2_7b
Если NVIDIA изменит API, ориентируйтесь на актуальную официальную документацию; EVO2_MCP_BASE_URL можно переключить в любой момент.
18. Пакетная оценка и извлечение эмбеддингов (scripts/score_fasta.py)
MCP Tools подходят для интерактивных вызовов агентом; для пакетной оценки больших FASTA используйте сопутствующий скрипт scripts/score_fasta.py (проверен на реальном API на 3800+ записях K562 enhancer/promoter).
При каждом запуске автоматически создаётся отдельная папка с временной меткой:
output/run_20260825_104403/
├── scores.csv # 每序列一行:id, header, length, total/mean LL, ...
│ # + embedding_key(与 embeddings.npz 的 record_ids 对齐)
└── embeddings.npz # embeddings: (n, 4096) float32 mean-pooled 矩阵
# record_ids: 与矩阵行一一对应的键(来源__序列id)# 小样本(指定 id)
.pixi/envs/dev/bin/python scripts/score_fasta.py \
--fasta /path/cis/enhancers.fa /path/cis/promoters.fa \
--ids K562_TE_629,K562_MPT_6842 --allow-ambiguous
# 全量(跳过 >100kb —— 托管端对该长度返回 422;保留原始 embedding)
.pixi/envs/dev/bin/python scripts/score_fasta.py \
--fasta /path/cis/enhancers.fa /path/cis/promoters.fa \
/path/trans/enhancers.fa /path/trans/promoters.fa \
--skip-longer-than 100000 --allow-ambiguous \
--embedding-layer norm --keep-raw-embeddingsКлючевые параметры:
Параметр | Описание |
| Какой слой эмбеддингов извлекать (по умолчанию |
| Дополнительно сохранять сырые поэлементные эмбеддинги |
| Пропускать последовательности длиннее указанной (ограничение управляемого API, см. §17) |
| Разрешить пропуск N-оснований (5 последовательностей с N выполняются как обычно, с предупреждением caveat) |
| Число параллельных запросов (по умолчанию 2, с учётом rate limit) |
| Переопределить стандартную структуру папок запуска |
Проектирование эффективности: на каждую последовательность отправляется только один запрос (output_layers=["unembed","norm"], logits и эмбеддинги получаются одновременно); имя logits-слоя определяется только один раз за весь запуск; параллелизм ограничивается семафором.
19. Связывание эмбеддингов и последующий анализ (scripts/analyze_run.py)
embeddings.npz — это mean-pooled представления последовательностей (по одному вектору размерности 4096 на последовательность), подходящие напрямую для кластеризации, классификации и регрессии. Загрузка и связывание:
import csv, numpy as np
run = "output/run_20260825_104403"
rows = list(csv.DictReader(open(f"{run}/scores.csv")))
d = np.load(f"{run}/embeddings.npz", allow_pickle=True)
X = d["embeddings"] # (n, 4096) float32
ids = [str(x) for x in d["record_ids"]] # 与 X 行一一对应
key_to_row = {r["embedding_key"]: r for r in rows if r.get("embedding_key")}
scores = [key_to_row[k] for k in ids] # scores[i] ↔ X[i]Полный анализ одной командой (кластеризация KMeans, классификация enhancer-vs-promoter, регрессия embedding→likelihood, PCA-график):
.pixi/envs/dev/bin/python scripts/analyze_run.py output/run_20260825_104403 --k 3Вывод: analysis_<run>.npz (объединённые X + keys) и analysis_<run>.png. Ключевые моменты анализа:
перед вычислением сходства/кластеризацией векторы размерности 4096 необходимо нормализовать до единичной длины (скрипт это уже делает);
при малой выборке классификация/регрессия автоматически пропускаются (защитный порог ≥6 записей); только после полного прогона 3806 записей эти анализы приобретают статистическую значимость;
ключи
cis_enhancers__xxx→ категория enhancers, регион cis;trans_*аналогично (parse_sourceпозволяет менять измерение меток для классификации cis-vs-trans).
Разработка и тестирование
pixi install # 或 pip install -e ".[dev]"
pixi run test # 运行 pytest(全部 mock,不调用真实 API)Офлайн-тесты: 91 passed / 4 skipped (skip = live-гейтинг). Покрытие: валидация последовательностей, нормализация регистра/пробелов, недопустимые символы, отсутствие API key, построение forward-запроса, 401/408/429/5xx/timeout, автоматическое определение имени слоя (включая регрессию гонки при параллелизме), валидация вариантов, математическая корректность оценки вариантов/батчей (независимый пересчёт по семантике Arc), декодирование NPZ (JSON base64 / zip / старый JSON tensor / ключ <layer>.output), песочница FASTA, интеграция MCP-сессии, чистые функции скриптов (pooling/имена ключей) и т.д.
Смоук-тест на реальном API (требуется реальный ключ, по умолчанию пропускается). Ключ автоматически читается из .env (Settings.from_env() уже загружает):
EVO2_MCP_RUN_LIVE=1 .pixi/envs/dev/bin/python -m pytest tests/test_live_api.py -v -sLive-тест выполняет реальные запросы к конечной точке NVIDIA и проверяет: автоматическое определение logits-слоя (unembed), разбор реального NPZ ((1, seq, 512) float64), совпадение evo2_score с ручным пересчётом из сырых logits, оценку вариантов.
Структура проекта
.
├── pyproject.toml
├── README.md
├── .env.example
├── .gitignore
├── src/evo2_mcp/
│ ├── __main__.py # python -m evo2_mcp 入口
│ ├── config.py # 环境变量配置
│ ├── sequence.py # DNA 校验/归一化
│ ├── api_client.py # HTTP 客户端(retry/backoff/错误分类/响应解码 + layer 自动探测)
│ ├── forward_output.py# NPZ 解码 + likelihood 计算 + embedding 提取
│ ├── fasta.py # FASTA 解析 + 读取沙箱
│ ├── tools.py # 5 个 Tool 的实现
│ └── server.py # MCP server(stdio)
├── scripts/
│ ├── score_fasta.py # 批量 FASTA 评分 + embedding 提取(每次运行独立 run 文件夹)
│ └── analyze_run.py # 下游分析:加载/关联 → 聚类/分类/回归 + PCA 图
├── tests/ # pytest(全 mock,91 用例)+ 可选 live test
└── output/ # mode="save" 的 .npz 输出 + run_*/ 运行结果(git 忽略)Available Tools
5 toolsevo2_batch_scoreA
Score many single-nucleotide variants against one wildtype sequence. The WT forward pass is computed exactly once and reused; identical (position, alt) mutants are forwarded once; mutant requests run with bounded concurrency (EVO2_MCP_MAX_CONCURRENCY, default 2) to respect NVIDIA rate limits, and per-variant API errors are reported per-variant. Use for saturation-mutagenesis-style analyses. This is a DNA foundation model inference tool. It does not provide clinical diagnosis. Model scores should not be interpreted as pathogenicity labels without additional validation.
| Name | Required | Description | Default |
|---|---|---|---|
| sequence | Yes | Wildtype DNA sequence (>= 2 bp). | |
| variants | Yes | List of {position, ref, alt} dicts (1-based positions). | |
| coordinate | No | 1-based |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations, the description carries the full burden of disclosure, and it excels. It reveals the caching behavior (WT pass computed once, identical mutants forwarded once), concurrency limits (EVO2_MCP_MAX_CONCURRENCY, default 2) to respect NVIDIA rate limits, and per-variant error reporting. It also adds crucial disclaimers (not clinical diagnosis, not pathogenicity labels). This is exemplary transparency.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is dense but every sentence earns its place. It leads with the core purpose, then efficiently packs performance details, error handling, and disclaimers. It is slightly longer than minimal but avoids fluff. The structure is logical: purpose → efficiency → safety/limitations. This is good, though a bit dense; a 4 feels right.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
For a batch scoring tool with no output schema, the description covers the execution semantics, concurrency, error reporting, and clinical disclaimer. However, it omits any description of the return format or how results are structured (even per-variant errors are mentioned but not the shape). Given the complexity and no annotations, the absence of output details leaves a small but notable gap, so it stops short of a 5.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema description coverage is 67% (sequence and variants have descriptions; coordinate has an enum with a default). The description does not add parameter-level meaning beyond what the schema already provides—it merely restates the variants structure and coordinate default implicitly. It does clarify the 'many' scope, but that is more behavioral than parameter-specific. Baseline 3 is appropriate since the schema covers most parameters.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description opens with a strong, specific verb-resource pair: 'Score many single-nucleotide variants against one wildtype sequence.' It clearly states the batch scope and distinguishes itself from single-variant tools by emphasizing 'many' and 'batch.' It also specifies the analysis type (saturation-mutagenesis), which orients the agent on the intended use case.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The tool provides a clear when-to-use directive: 'Use for saturation-mutagenesis-style analyses.' It also implies batching by explaining the reuse of the WT forward pass and bounded concurrency. However, it does not explicitly name alternative sibling tools for single-variant scoring, so the agent must infer those from the 'many' qualifier. This is solid but not fully explicit.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
evo2_forwardA
Run a forward pass of Evo2-7B on a DNA sequence (forward inference) and return summary statistics — or raw tensors — for the requested model layers (final logits, attention, MLP or embedding outputs). Use this when you need layer outputs for analysis, not just a scalar score. Modes: 'summary' (shape/dtype/min/max/mean/std per layer — default, context-safe), 'save' (write the .npz under the server's output dir and return the path), 'raw' (inline small tensors only; large tensors must be saved to a file instead). This is a DNA foundation model inference tool. It does not provide clinical diagnosis. Model scores should not be interpreted as pathogenicity labels without additional validation.
| Name | Required | Description | Default |
|---|---|---|---|
| mode | No | summary: per-layer shape/dtype/min/max/mean/std only. raw: inline the tensors as nested lists (small only, capped). save: always write an .npz file in the output dir and return its path. | summary |
| sequence | Yes | DNA sequence over {A,C,G,T}. Lowercase and whitespace are normalised. IUPAC ambiguity codes (N, R, Y, ...) are rejected unless the server was started with EVO2_MCP_ALLOW_AMBIGUOUS=1 (N only). | |
| save_path | No | Optional filename for the saved NPZ (implies mode='save'). Must resolve inside the server's output directory (EVO2_MCP_OUTPUT_DIR, default ./output). If omitted, a timestamped file is used. | |
| output_layers | No | Evo2 layer names. The final logits layer is 'output_layer' on self-hosted NIM 2.x containers, but the hosted health.api.nvidia.com endpoint uses model attribute names — use 'unembed' for final logits (also 'embedding_layer', 'norm', 'blocks.N.mlp'). Scoring tools auto-detect this. See https://docs.nvidia.com/nim/bionemo/evo2/latest/endpoints.html |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations exist, so the description carries full responsibility. It discloses mode behavior (summary is context-safe, raw only for small tensors, save writes to server output dir), ambiguity-code handling with an environment flag, endpoint-dependent layer naming, and the clinical limitation. This is exceptionally transparent for a complex inference tool.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is front-loaded with purpose, then organizes modes and constraints in a logical flow. Every sentence provides distinct information—no filler. Dense but efficient, appropriate for the tool's complexity.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
For a tool with four parameters, no output schema, and no annotations, this description is remarkably complete. It covers return types, mode constraints, output directory rules, ambiguity handling, endpoint differences, and disclaimers—everything an agent needs to invoke it correctly without external documentation.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema descriptions already cover all parameters (100% coverage), but the description adds significant value: it explains the endpoint-specific layer names (output_layer vs unembed), the save_mode implication of save_path, and the ambiguity environment flag. This goes beyond the schema to make parameter usage clearer.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
States a specific verb and resource ('Run a forward pass of Evo2-7B') and explicitly contrasts with scoring tools: 'Use this when you need layer outputs for analysis, not just a scalar score.' This clearly distinguishes from sibling scoring tools and conveys the tool's core purpose.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
Explicitly tells when to use this tool versus alternatives ('not just a scalar score'), and details the three modes with their intended contexts. It also adds a clinical disclaimer ('does not provide clinical diagnosis'), guiding appropriate usage boundaries.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
evo2_scoreA
Compute the model-based log-likelihood of a DNA sequence under Evo2-7B (nucleotide-level log-likelihood via the byte-level tokenizer). Returns total_log_likelihood, mean_log_likelihood, scored_positions and optionally per_position_log_likelihood (position 0 is unscored by the causal shift; value k corresponds to 0-based position k+1). Use for sequence-level probability estimates. This is a DNA foundation model inference tool. It does not provide clinical diagnosis. Model scores should not be interpreted as pathogenicity labels without additional validation.
| Name | Required | Description | Default |
|---|---|---|---|
| sequence | Yes | DNA sequence over {A,C,G,T} (>= 2 bp). | |
| include_per_position | No | Return the per-position log-likelihood list (default False to keep the response small; long lists are truncated to head+tail). |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations, the description carries full behavioral burden. It discloses output structure, the causal shift causing position 0 to be unscored, optional per-position output, and explicitly warns against clinical diagnosis and pathogenicity interpretation. This is thorough and transparent for a model-scoring tool.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is a few sentences but each adds necessary context: purpose, output details, usage, and disclaimers. It is not overly verbose and front-loads the core function. Slightly dense with parentheticals, but still efficient.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Given the absence of an output schema, the description fully explains the returned fields (total_log_likelihood, mean_log_likelihood, scored_positions, optional per_position_log_likelihood) and the positional convention. It also addresses interpretation caveats. For a single-sequence inference tool, nothing critical is missing.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema description coverage is 100%, so both parameters are well-documented in the schema. The description adds little beyond the schema; it does explain the per-position output semantics within the overall description, but that is not parameter-specific. Baseline 3 is appropriate.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly states the tool computes model-based log-likelihood of a DNA sequence under Evo2-7B, with specific output fields. It does not explicitly differentiate from siblings like evo2_batch_score or evo2_variant_score, but the single-sequence focus is implied by the parameter list and usage text.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
It provides a clear context: 'Use for sequence-level probability estimates' and notes this is a DNA foundation model inference tool. It does not explicitly state when not to use it or mention alternatives, but the use case is specified clearly enough without being misleading.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
evo2_score_fastaA
Score every record in a FASTA source under Evo2-7B. Provide EITHER fasta_text (inline FASTA) OR fasta_path (local file — only allowed when its directory is listed in EVO2_MCP_ALLOWED_DIRS; the server refuses arbitrary paths). Returns per-record total/mean log-likelihood; per-record errors are reported inline. This is a DNA foundation model inference tool. It does not provide clinical diagnosis. Model scores should not be interpreted as pathogenicity labels without additional validation.
| Name | Required | Description | Default |
|---|---|---|---|
| fasta_path | No | Local FASTA path (sandboxed by EVO2_MCP_ALLOWED_DIRS). | |
| fasta_text | No | Inline FASTA text, e.g. '>seq1\nACGT...'. |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
No annotations are present, so the description carries the full disclosure burden. It states the output type (per-record total/mean log-likelihood), error reporting behavior, and importantly warns that scores are not clinical diagnostics. It does not explicitly state read-only behavior, but for an inference tool this is implied and not a significant gap given the safety disclaimers.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is compact yet covers all essential aspects: purpose, input options, constraints, output, and limitations. The main action is front-loaded, and every sentence serves a purpose without redundancy.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Despite having no output schema, the description explains the return values clearly. It covers input constraints and error reporting, but does not specify the exact response format (e.g., whether it's a JSON object or text). For a tool with only two parameters, this is a minor gap, so a 4 is appropriate.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema coverage is 100% with descriptive parameter comments, so the baseline is 3. The description adds value by clarifying the meaning of the output (per-record scores) which is not in the schema, and reinforces the sandboxing constraint for fasta_path, going beyond the schema's own description.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description clearly states the action ('Score every record'), the specific resource (FASTA source), and the model (Evo2-7B). It also distinguishes itself from siblings by focusing on FASTA input, making it easily separable from evo2_score or evo2_variant_score without needing to infer.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
Explicitly explains when to use the tool: 'Provide EITHER fasta_text OR fasta_path', with the path restriction clearly stated. It also provides cautionary guidance on interpreting results, which helps agents avoid misuse. The description mentions no alternatives but the either/or and sandboxing rules effectively guide usage.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
evo2_variant_scoreA
Compare a single-nucleotide variant: the Evo2-7B log-likelihood of the wildtype sequence vs the mutant sequence. Returns delta_log_likelihood (mutant − wildtype); a negative value means the mutant sequence is LESS likely under the model. Positions are 1-based by default (VCF-style). Variants at position 1 are rejected because a causal LM cannot score the first base. This is a DNA foundation model inference tool. It does not provide clinical diagnosis. Model scores should not be interpreted as pathogenicity labels without additional validation.
| Name | Required | Description | Default |
|---|---|---|---|
| alt | Yes | Alternate allele (single A/C/G/T). | |
| ref | Yes | Reference allele (single A/C/G/T). | |
| position | Yes | Variant position, 1-based by default. | |
| sequence | Yes | Wildtype DNA sequence context (>= 2 bp). | |
| coordinate | No | Coordinate system of `position`. | 1-based |
| include_per_position | No |
TDQS
Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?
With no annotations, the description fully discloses behavioral traits: it explains the output meaning (negative delta indicates lower likelihood), the reasoning behind rejecting position 1 (causal LM limitation), coordinate system default, and important limitations (not clinical, not pathogenicity). This goes well beyond a basic verb+object statement and gives the agent a clear model of the tool's behavior.
Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.
Is the description appropriately sized, front-loaded, and free of redundancy?
The description is four sentences with no redundancy. It front-loads the core purpose and output interpretation, then adds constraints and domain caveats. Every sentence carries meaningful information, and the structure makes it easy for an agent to quickly grasp the tool's role.
Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.
Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?
Despite having no output schema or annotations, the description covers the essential aspects: what it computes, how to interpret the result, coordinate system, positional restriction, and domain limitations. It does not explicitly describe the effect of include_per_position (though schema notes default false), but that is a minor gap. Overall, an agent has sufficient context to call the tool correctly.
Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.
Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?
Schema coverage is high (83%), so the baseline is 3. The description adds semantic value by explaining the output delta and the coordinate system, but it does not elaborate on parameters that the schema already documents. It reinforces the 'sequence' as wildtype context, which is consistent with schema descriptions, but adds no new parameter-level nuance beyond the position-1 rejection rule.
Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.
Does the description clearly state what the tool does and how it differs from similar tools?
The description states a specific action ('Compare a single-nucleotide variant') and defines the exact output ('delta_log_likelihood (mutant − wildtype)'). It clearly distinguishes the tool from siblings by focusing on variant comparison rather than generic scoring or batch operations. The inclusion of the model name (Evo2-7B) and the caveat about clinical diagnosis further clarify its purpose.
Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.
Does the description explain when to use this tool, when not to, or what alternatives exist?
The description implies when to use the tool (for single-nucleotide variant scoring) but does not explicitly compare with siblings like evo2_score or evo2_batch_score. It does provide usage constraints (1-based positions, rejection of position 1, not for clinical diagnosis) that help an agent decide applicability, yet it lacks an explicit 'use when' versus 'use instead' statement.
Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.
Tool Schema Changelog
Recent tool additions, removals, and schema changes observed during successful MCP inspections.
5 tool updates
v0.1.0- First observed
evo2_batch_score - First observed
evo2_forward - First observed
evo2_score - First observed
evo2_score_fasta - First observed
evo2_variant_score
TDQS
Scored across 5 tools
Each tool has a clearly distinct purpose: forward pass for layer tensors, sequence log-likelihood scoring, single variant effect, batch variant scoring, and FASTA-based scoring. The descriptions clearly delineate usage scenarios, reducing misselection risk.
All tools follow the evo2_ verb-noun pattern (forward, score, variant_score, batch_score, score_fasta). While the second part varies, the consistent prefix and action-oriented naming make the set predictable and easy to navigate.
Five tools is well-scoped for a focused DNA model inference server. Each tool adds a distinct capability without redundancy, covering single sequence, variant, batch, and file-based scoring.
The surface covers the core workflows for an Evo2 model: sequence scoring, variant effect analysis (single and batch), FASTA batch processing, and forward pass tensor extraction. No obvious dead ends or missing critical operations for the stated purpose.
Maintenance
Related MCP Connectors
Protein analysis: ESM-2/ESMC embeddings, mutation scoring, landscape scans, ESMFold structure.
Hosted DNA language models: promoter, splice, enhancer, chromatin, expression, annotation
Bioinformatics MCP for genomic variant interpretation, gene-disease evidence and literature.
AI-powered bioprotocol optimization — generate, search, and manage lab protocols via MCP
Related MCP Servers
- AlicenseAqualityCmaintenanceEnables genomic sequence analysis through the Evo 2 model, supporting DNA sequence scoring, embedding, generation, and variant effect prediction with multiple model checkpoints (7B, 40B, 1B parameters).62LGPL 3.0

bio-mcp-evo2official
AlicenseNot gradedqualityDmaintenanceAn MCP server that enables AI assistants to generate, score, and analyze DNA sequences using the evo2 genomic foundation model. It supports multiple execution modes including local GPU, SLURM clusters, and the Nvidia NIM cloud API for tasks like variant effect prediction and sequence embedding.1MIT- FlicenseNot gradedqualityDmaintenanceEnables protein sequence analysis and structure prediction by extracting ESM-2 embeddings and batch processing FASTA files via Docker. It provides tools for large-scale embedding extraction, job monitoring, and model management within an MCP-compatible environment.-
- AlicenseNot gradedqualityDmaintenanceEnables AI agents to query clinical genomics databases, retrieve supporting literature, analyze population genetics, and visualize biological pathways.18MIT