evo2-mcp-server
Evo2-7B Bioinformatics MCP Server
Un servidor que envuelve la Evo2-7B Forward API alojada por NVIDIA como herramientas MCP (Model Context Protocol), para que agentes como Claude Code, Cursor, Codex, etc. puedan controlar Evo2 mediante lenguaje natural:
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. Introducción del proyecto
Proporciona 5 herramientas MCP:
Tool | Función |
| Realiza la inferencia forward de Evo2-7B sobre una secuencia de ADN y devuelve las estadísticas de salida de la capa especificada (o guarda el tensor original) |
| Calcula la verosimilitud basada en el modelo de Evo2 para una secuencia de ADN (total / media / por posición) |
| Compara el efecto de una única variante de nucleótido sobre la verosimilitud de la secuencia de Evo2 (Δ log-verosimilitud) |
| Compara por lotes múltiples variantes de nucleótidos (reutiliza una sola forward de WT, concurrencia limitada y deduplicación automática) |
| Puntúa cada registro de un FASTA (las rutas locales están restringidas por el sandbox |
Este proyecto es un Bioinformatics MCP Tool Server, no un simple envoltorio de una API HTTP:
Valida / normaliza automáticamente la secuencia de ADN (mayúsculas, eliminación de espacios en blanco y error claro en caracteres no válidos)
Calcula la verosimilitud según la semántica oficial (tokenizador a nivel de byte + desplazamiento causal, ver §17)
Diseño de salida por niveles (summary / raw / save) para evitar la explosión del contexto de MCP
Clasificación completa de errores (400/401/403/404/408/413/422/429/5xx/timeout) + reintentos/backoff
La clave de API solo se lee de variables de entorno; nunca se codifica ni aparece en los registros
Scripts por lotes incluidos:
scripts/score_fasta.py(puntuación de FASTA por lotes + extracción de embeddings, ver §18) yscripts/analyze_run.py(análisis posteriores de clustering/clasificación/regresión, ver §19)
Related MCP server: bio-mcp-evo2
2. Introducción a la API de Evo2
Evo2 (Arc Institute / NVIDIA) es un modelo fundacional de ADN (arquitectura StripedHyena2); la versión 7B tiene 32 capas, licencia Apache-2.0 y contexto de entrenamiento de hasta 1M pb. NVIDIA ofrece un servicio NIM alojado:
Endpoint Forward:
POST https://health.api.nvidia.com/v1/biology/arc/evo2-7b/forwardCuerpo de la solicitud (OpenAPI oficial
ForwardInputs):
{ "sequence": "ACGTACGT...", "output_layers": ["output_layer"] }output_layers admite de 1 a 100 nombres de capa (por ejemplo, output_layer, decoder.layers.24.mlp.linear_fc2, decoder.layers.3.self_attention, embedding, decoder.final_norm).
Cuerpo de la respuesta (OpenAPI oficial
ForwardOutputs):{"data": "<NPZ codificado en base64>", "elapsed_ms": <int>}; las respuestas muy grandes pueden devolverse conContent-Type: application/zip(bytes NPZ sin procesar).output_layer= logits finales, con forma[seq_len, batch_size, 512](512 es el tamaño de vocabulario rellenado del tokenizador a nivel de byte).
⚠️ Aviso de obsolescencia (verificado el 2026-08-24): el endpoint
arc/evo2-7balojado en build.nvidia.com está marcado como Deprecated (la página indica "This NIM Endpoint has been deprecated"). La API descrita en la documentación oficial de NIM (docs.nvidia.com/nim/bionemo/evo2/latest/) coincide exactamente con la del endpoint alojado; si el endpoint alojado no está disponible, se puede pasar a un contenedor NIM autoalojado y apuntarEVO2_MCP_BASE_URLahttp://localhost:8000/biology/arc/evo2.
Hechos oficiales verificados (base de implementación, 2026-08-24)
Concepto | Conclusión | Fuente |
Formato de respuesta | JSON | Documentación de endpoints de NVIDIA NIM + esquema OpenAPI alojado ( |
Forma de |
| Ídem ("Final output/logits") |
Tamaño del vocabulario | 512 (rellenado); tokenizador a nivel de byte, cada pb = 1 token | Documentación de NVIDIA + Arc/vortex |
A/C/G/T → índice de logits | A=65, C=67, T=84, G=71 (valores ASCII de byte) | Texto original de la documentación de NVIDIA + |
BOS/EOS/offset | Sin BOS por defecto (Arc | Arc |
Cálculo de la verosimilitud |
| Arc |
Tokens especiales | Solo los 4 tokens A/C/G/T de la salida tienen sentido (texto original de la documentación de NIM) | Documentación de NVIDIA |
Diferencias entre lo probado y la documentación (verificación en vivo 2026-08-24; la tarea exige documentar la interfaz real)
Al probar el endpoint alojado health.api.nvidia.com con una clave real se observó que los nombres de capa de la documentación no se aplican en el endpoint alojado:
Nombre de capa solicitado | Comportamiento real de la API alojada |
| ❌ |
| ❌ 422 |
| ✅ logits finales: clave NPZ |
| ✅ |
| ✅ |
| ✅ |
Medidas adoptadas (implementadas y verificado en vivo):
Se añadió la configuración
EVO2_MCP_LOGITS_LAYER(por defectoauto): las herramientas de puntuación prueban primero el nombre de la documentaciónoutput_layer; si reciben422 has no attribute(endpoint alojado), cambian automáticamente aunembedy lo cachean, sin volver a sondear. En un contenedor NIM 2.x autoalojado funciona a la primera, sin solicitudes adicionales.El analizador NPZ admite tanto claves simples (
output_layer) como el formato<name>.output(unembed.output), con un respaldo heurístico de "última dimensión = 512".El mensaje de error
422ahora indica los nombres de atributo disponibles en el endpoint alojado.
Si el
seq_lendevuelto no coincide con la longitud de la secuencia de entrada (por ejemplo, si el servidor añade padding/BOS), este servidor se niega a calcular la verosimilitud y devuelve estadísticas sin procesar (raw) + una explicación clara; nunca especula sobre la alineación.
3. Cómo obtener la clave de API de NVIDIA
Abre https://build.nvidia.com/ y en la esquina superior derecha haz clic en Get API Key (requiere iniciar sesión con una cuenta de NVIDIA).
Crea una clave (con el formato
nvapi-xxxxxxxx...).Configúrala en una variable de entorno; no la escribas en código / configuración / Git:
export NVIDIA_API_KEY="nvapi-xxxxxxxx"También puedes copiar .env.example a .env y rellenarlo (.env ya está ignorado por .gitignore).
4. Instalación
# 推荐:pip / uv
pip install -e ".[dev]"
# 或
uv sync --extra dev
# 推荐(本项目自带):pixi 项目本地环境
pixi install
pixi run testRequiere Python >= 3.10 (se recomienda 3.11 o superior). Dependencias principales: mcp>=2.0, httpx>=0.27, numpy>=1.26, pydantic>=2.6, python-dotenv>=1.0. Los scripts de análisis (scripts/analyze_run.py) requieren además dependencias de desarrollo: scikit-learn, pandas, matplotlib.
5. Variables de entorno
Variable | Valor por defecto | Descripción |
| Sin valor (obligatorio) | Clave de API; solo se lee de aquí |
|
| Dirección del servicio (cambiar al usar NIM autoalojado) |
|
| Tiempo de espera de lectura HTTP (segundos) |
|
| Número máximo de reintentos para 408/429/5xx |
|
| Límite máximo de concurrencia para batch/FASTA |
| vacío | Directorios permitidos para leer FASTA (separados por |
|
| Directorio de salida para |
|
| Establecer a |
|
| Límite máximo estricto de longitud de secuencia |
|
| Límite máximo de elementos de tensor en línea permitidos para |
|
| Límite de la lista devuelta por posición (si se supera, toma el principio y el final) |
|
| Nombre de la capa de logits usada para puntuar: |
6. Inicio por CLI
# 三种方式等价
python -m evo2_mcp
evo2-mcp
uv run evo2-mcp # 用 uv 管理的项目环境
# pixi 环境:
pixi run evo2-mcpEl servidor se comunica con el cliente MCP mediante stdio; tras un inicio normal no produce salida (espera el apretón de manos de MCP).
7. Configuración de MCP
Claude Code (.mcp.json)
{
"mcpServers": {
"evo2": {
"command": "uv",
"args": ["run", "evo2-mcp"],
"env": {
"NVIDIA_API_KEY": "${NVIDIA_API_KEY}"
}
}
}
}Nota: si
${NVIDIA_API_KEY}se expande o no depende de la implementación del cliente. La forma más segura es escribir directamente la clave real:
{
"mcpServers": {
"evo2": {
"command": "uv",
"args": ["run", "evo2-mcp"],
"env": {
"NVIDIA_API_KEY": "YOUR_API_KEY"
}
}
}
}Pero no subas nunca a Git un .mcp.json con la clave real (añade ese archivo a .gitignore, o inyecta la clave mediante variables de entorno o un gestor de secretos). También puedes omitir env y dejar que el proceso del servidor lea NVIDIA_API_KEY desde el entorno o desde .env:
{
"mcpServers": {
"evo2": {
"command": "uv",
"args": ["run", "evo2-mcp"]
}
}
}Cursor (~/.cursor/mcp.json o .cursor/mcp.json del proyecto)
{
"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 autoalojado
{
"mcpServers": {
"evo2": {
"command": "uv",
"args": ["run", "evo2-mcp"],
"env": {
"EVO2_MCP_BASE_URL": "http://localhost:8000/biology/arc/evo2"
}
}
}
}8. Lista de herramientas
evo2_forward(sequence, output_layers=["output_layer"], mode="summary", save_path=None)
Realiza la inferencia forward de Evo2-7B sobre una secuencia de ADN. mode:
"summary"(por defecto): devuelveshape / dtype / min / max / mean / stdpara cada capa, seguro para el contexto;"save": guarda el tensor original como.npz(output/evo2_forward_<marca_de_tiempo>.npz) y devuelve la ruta;"raw": incluye el tensor completo en línea (solo si el número total de elementos ≤EVO2_MCP_RAW_INLINE_MAX, por defecto 4096, para evitar la explosión del contexto).
Atención al nombre de capa: el endpoint alojado
health.api.nvidia.comacepta nombres de atributos del modelo (para logits, usaunembed; también hayembedding_layer,norm,blocks.N.mlp). Los nombres de la documentaciónoutput_layer/decoder.layers.N.*solo se aplican a contenedores NIM 2.x autoalojados.evo2_score/evo2_variant_score/evo2_batch_score/evo2_score_fastadetectan automáticamente, sin necesidad de especificarlos manualmente; solo al llamar directamente aevo2_forwarddebes elegir el nombre según el endpoint real.
evo2_score(sequence, include_per_position=False)
Calcula la verosimilitud de Evo2 para la secuencia:
{
"sequence_length": 123,
"total_log_likelihood": -123.45,
"mean_log_likelihood": -1.2345,
"scored_positions": 122,
"per_position_log_likelihood": null,
"method_notes": "...",
"disclaimer": "..."
}Semántica (coincide con la implementación oficial de Arc): logits[i] predice la base en la posición i+1; tras hacer log-softmax sobre los 512 del vocabulario completo, se toma el índice de byte de la base objetivo; la posición 0 no participa en la puntuación, por lo que scored_positions = length - 1 y mean es el promedio de esos N-1 valores. per_position_log_likelihood[k] corresponde a la posición k+1 de la secuencia en base 0 (es decir, la posición k+2 en base 1). Si el seq_len devuelto por la API no se puede alinear con la secuencia, no se inventan resultados; se devuelven estadísticas raw y una explicación clara:
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)"
}Cadena de validación: rango de position → conversión de coordinate → ref debe coincidir con la base de la secuencia → ref≠alt → la posición 1 en base 1 (0 en base 0) no se puede puntuar (un LM causal no puede asignar probabilidad al primer token) → error claro.
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 }
]
}La forward de WT solo se calcula una vez y se reutiliza para todas las variantes;
El mutante con el mismo
(position, alt)solo hace forward una vez (memoización);La concurrencia está limitada por
EVO2_MCP_MAX_CONCURRENCY(por defecto 2, respetando el límite de tasa de NVIDIA);El fallo de una variante no afecta a todo el lote (cada una devuelve su
errorpor separado).
evo2_score_fasta(fasta_path=None, fasta_text=None)
>sequence_1
ACGTACGT...
>sequence_2
TTGGCCAA...fasta_text: FASTA en línea (disponible por defecto, con límite de tamaño/número de registros);fasta_path: solo se permite leer si el archivo está dentro deEVO2_MCP_ALLOWED_DIRS; en caso contrario, se rechaza explícitamente;Devuelve
total_log_likelihood / mean_log_likelihoodpara cada registro; un error en un registro no afecta al resto.
9. Ejemplos de uso
{
"sequence": "acgtACGT acgt", // 小写 + 空白自动处理
"output_layers": ["output_layer"],
"mode": "summary"
}Devuelve:
{
"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 }
}Cuando el agente quiera los logits completos:
{ "sequence": "ACGT...", "mode": "save" }{
"saved": true,
"path": "/abs/path/output/evo2_forward_20260824_153000.npz",
"bytes_on_disk": 24576,
"layer_stats": [...]
}10. Ejemplo de FASTA
{
"fasta_text": ">geneA\nACGTACGTACGT\n>geneB\nTTGGCCAATTGG"
}(o "fasta_path": "/data/genomes/genes.fa", con EVO2_MCP_ALLOWED_DIRS=/data/genomes configurado)
Para puntuar FASTA en grandes cantidades (por ejemplo, enhancers/promotores de un directorio completo) y extraer embeddings, usa scripts/score_fasta.py (ver §18): cada ejecución genera una carpeta de run independiente (scores.csv + embeddings.npz).
11. Ejemplo de puntuación de variantes
{
"sequence": "ACGTACGTACGTACGTACGT",
"position": 10,
"ref": "A",
"alt": "G"
}12. Ejemplo de puntuación por lotes
{
"sequence": "ACGTACGTACGTACGTACGT",
"variants": [
{ "position": 10, "ref": "A", "alt": "G" },
{ "position": 12, "ref": "T", "alt": "C" },
{ "position": 14, "ref": "A", "alt": "T" }
]
}Flujo de trabajo típico de un agente (corresponde a "analizar todos los SNP de la secuencia y encontrar los 20 con mayor cambio en la puntuación de Evo2"):
读取输入 → 解析 DNA / VCF → 生成 WT / mutant → evo2_batch_score
→ 按 |delta_log_likelihood| 排序 → 取前 20 → 保存 CSV → 解释结果13. Manejo de errores
HTTP | Significado | Comportamiento de este servidor |
400 | Bad Request (incluye secuencias ilegales, etc.) | Error directo, con resumen de la respuesta |
401 | Clave de API no válida | Error directo, indicando que se revise |
403 | Sin permisos (punto final gestionado obsoleto, etc.) | Error directo, indicando posibles causas |
404 | Ruta no existe | Error directo, indicando que se revise |
408 | Tiempo de espera del servidor | Reintentos limitados (backoff) y luego error |
413 | Payload demasiado grande | Error directo, indicando que se reduzca la secuencia o el número de capas |
422 | Fallo de validación de parámetros | Error directo, con detalles |
429 | Límite de tasa | Reintentos + exponential backoff (respetando |
5xx | Error del servidor de NVIDIA | Reintentos limitados y luego error |
timeout | Tiempo de espera de la solicitud ( | Error explícito: |
Todos los errores se devuelven como JSON estructurado a través de MCP: {"error": "Evo2APIError", "message": "..."}. En evo2_batch_score, un fallo individual devuelve {"error": ..., "status": ...}, sin interrumpir todo el lote.
14. Límite de tasa
El NIM gestionado de NVIDIA tiene límites de tasa. Estrategias de mitigación:
EVO2_MCP_MAX_CONCURRENCY(por defecto 2) limita la concurrencia;429 → exponential backoff (1s, 2s, 4s, 8s, 16s…, con tope de 30s + jitter; si hay
Retry-After, se respeta primero pero con tope de 60s);Límite de reintentos
EVO2_MCP_MAX_RETRIES(por defecto 4), no se reintenta indefinidamente;En el lote, el WT se calcula solo una vez y los mutantes idénticos se deduplican, reduciendo el número de solicitudes.
15. Notas de seguridad
Clave de API: solo se lee de la variable de entorno
NVIDIA_API_KEY(o.env); no hay claves codificadas en el código; los registros solo incluyen URL, longitud de secuencia y nombre de capa, no el contenido de la secuencia ni la clave; los mensajes de error solo contienen un resumen de los primeros 500 caracteres de la respuesta.Privacidad de secuencias: todos los registros/errores solo contienen
preview(por ejemplo,ACGT...GCTA (len=12345)).Sandbox de rutas:
La lectura de FASTA solo está permitida en
EVO2_MCP_ALLOWED_DIRS; si no está configurado, se rechazan todas las rutas locales;save_pathenmode="save"debe estar dentro deEVO2_MCP_OUTPUT_DIR;
.gitignoreya incluye.env,*.env,output/,*.npz.Bases N: se rechazan por defecto con un error explícito (el modelo Evo2 no ha sido evaluado con bases ambiguas; la documentación solo garantiza que A/C/G/T son significativos). Si realmente se necesita pasar N, se inicia con
EVO2_MCP_ALLOW_AMBIGUOUS=1— es una elección explícita, no un descarte silencioso.No ejecutar: este servidor no realiza ninguna ejecución de shell; el Agente solo puede desencadenar solicitudes HTTP restringidas a través de FASTA/entrada de secuencias.
16. Limitaciones de la interpretación biológica
La puntuación de Evo2 es un cambio de verosimilitud de secuencia basado en el modelo, no evidencia experimental, y mucho menos un diagnóstico de patogenicidad clínica.
delta_log_likelihood < 0solo puede interpretarse como "la secuencia mutante es menos probable bajo el modelo", no como "patogénica".Se necesita validación posterior (experimental, frecuencias poblacionales, anotaciones ClinVar, impacto en la estructura de la proteína, etc.) para hablar de patogenicidad.
La descripción de cada Tool incluye la siguiente declaración (visible para el cliente 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. Base de implementación y fuentes de validación (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
Referencia de la API gestionada de NVIDIA (esquema OpenAPI de arc/evo2-7b-forward): https://docs.api.nvidia.com/nim/reference/arc-evo2-7b-infer
Pruebas reales del punto final gestionado (2026-08-24, clave real):
output_layerdevuelve 422StripedHyena has no attribute 'output_layer';unembeddevuelve logits (clave NPZunembed.output, forma(1, seq, 512), float64) — por lo tanto, la herramienta de puntuación usa por defectoEVO2_MCP_LOGITS_LAYER=autopara detección automáticaPruebas por lotes (2026-08-25, clave real, más de 3800 secuencias de enhancer/promotor de K562):
Cuando la secuencia es > ~100 kb, el punto final gestionado devuelve 422 (límite de
canUse32BitIndexMathde PyTorch) — para lotes grandes usar--skip-longer-than 100000;Se ha corregido la condición de carrera en la detección automática del nombre de capa bajo concurrencia (
forward_logitsusa una variable local para registrar los nombres probados) y se ha añadido una prueba de regresión;Extracción de embeddings:
norm/embedding_layer/blocks.Nfuncionan, forma(1, seq, 4096)float64 (después de mean-pool, 4096 dimensiones).
Repositorio de Arc Institute Evo2 (
scoring.py,models.py): https://github.com/ArcInstitute/evo2CharLevelTokenizerde vortex (implementación oficial del tokenizador de Evo2): código fuente de PyPIvtx1.1.0 envortex/model/tokenizer.pyTarjeta del modelo Evo2: https://huggingface.co/ArcInstitute/evo2_7b
Si NVIDIA ajusta la API, consulte la documentación oficial más reciente; EVO2_MCP_BASE_URL se puede cambiar en cualquier momento.
18. Puntuación por lotes y extracción de embeddings (scripts/score_fasta.py)
Las herramientas MCP son adecuadas para llamadas interactivas del Agente; para puntuación FASTA a gran escala se usa el script complementario scripts/score_fasta.py (la API real se ha validado con más de 3800 secuencias de enhancer/promotor de K562).
Cada ejecución crea automáticamente una carpeta independiente con marca de tiempo:
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-embeddingsParámetros clave:
Parámetro | Descripción |
| Qué capa de embedding extraer (por defecto |
| Guarda adicionalmente los embeddings brutos por posición de cada secuencia |
| Omite secuencias más largas que ese valor (límite de la API gestionada, ver §17) |
| Permite pasar bases N (las 5 secuencias con N se ejecutan normalmente con advertencia) |
| Número de concurrencia (por defecto 2, respeta el límite de tasa) |
| Sobrescribe el diseño de carpeta de ejecución predeterminado |
Diseño de eficiencia: cada secuencia envía una sola solicitud (output_layers=["unembed","norm"], logits y embeddings se obtienen juntos); el nombre de la capa de logits se detecta solo una vez durante toda la ejecución; la concurrencia se limita con un semáforo.
19. Asociación de embeddings y análisis posterior (scripts/analyze_run.py)
embeddings.npz es la representación de secuencias con mean-pool (un vector de 4096 dimensiones por secuencia), adecuado para clustering, clasificación y regresión directos. Carga y asociación:
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]Ejecutar el análisis completo con un solo comando (clustering KMeans, clasificación enhancer-vs-promotor, regresión embedding→likelihood, gráfico PCA):
.pixi/envs/dev/bin/python scripts/analyze_run.py output/run_20260825_104403 --k 3Salida analysis_<run>.npz (X combinado + keys) y analysis_<run>.png. Puntos clave del análisis:
Antes de calcular similitud/clustering con vectores de 4096 dimensiones, normalizar a norma unitaria (el script ya lo hace);
Con muestras pequeñas, la clasificación/regresión se omite automáticamente (umbral de protección ≥6 secuencias); solo después de ejecutar las 3806 secuencias completas estos análisis tienen significado estadístico;
Clave
cis_enhancers__xxx→ categoría enhancers, región cis;trans_*de manera similar (parse_sourcepuede cambiar la dimensión de etiqueta para clasificación cis-vs-trans).
Desarrollo y pruebas
pixi install # 或 pip install -e ".[dev]"
pixi run test # 运行 pytest(全部 mock,不调用真实 API)Pruebas fuera de línea 91 passed / 4 skipped (skip = controlado por live). Cubren: validación de secuencias, normalización de mayúsculas/minúsculas y espacios, caracteres ilegales, falta de clave de API, construcción de solicitudes forward, 401/408/429/5xx/timeout, detección automática del nombre de capa (incluida la regresión de condición de carrera), validación de variantes, corrección matemática de puntuación de variantes/lotes (recalculada de forma independiente según la semántica de Arc), decodificación NPZ (JSON base64 / zip / tensor JSON antiguo / clave <layer>.output), sandbox FASTA, integración de sesión MCP, funciones puras de scripts (pooling/nombres de claves), etc.
Pruebas de humo con API real (requieren clave real, omitidas por defecto). La clave se lee automáticamente de .env (Settings.from_env() ya la carga):
EVO2_MCP_RUN_LIVE=1 .pixi/envs/dev/bin/python -m pytest tests/test_live_api.py -v -sLas pruebas live realizan solicitudes reales al punto final de NVIDIA, verificando: detección automática de la capa de logits (unembed), análisis NPZ real ((1, seq, 512) float64), evo2_score consistente con el recálculo manual a partir de los logits brutos, puntuación de variantes.
Estructura del proyecto
.
├── 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).632 PyPI2LGPL 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