evo2-mcp-server
Evo2-7B 생물정보학 MCP 서버
NVIDIA가 호스팅하는 Evo2-7B Forward API를 MCP(Model Context Protocol) Tools로 캡슐화한 서버로, Claude Code, Cursor, Codex 등의 Agent가 자연어로 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 Tools를 제공합니다:
Tool | 역할 |
| DNA sequence에 대해 Evo2-7B forward inference를 실행하고, 지정된 layer의 출력 통계를 반환(또는 원본 tensor 저장) |
| Evo2 모델의 DNA sequence에 대한 model-based likelihood 계산(total / mean / per-position) |
| 단일 nucleotide variant가 Evo2 sequence likelihood에 미치는 영향 비교(Δ log-likelihood) |
| 여러 nucleotide variants 일괄 비교(WT forward 1회 재사용, 동시성 제한, 자동 중복 제거) |
| FASTA의 각 record에 대해 스코어링(로컬 경로는 |
이 프로젝트는 Bioinformatics MCP Tool Server로, 단순한 HTTP API wrapper가 아닙니다:
DNA sequence 자동 검증 / 정규화(대문자, 공백 제거, 잘못된 문자 명시적 오류)
공식 의미론 기반 likelihood 계산(byte-level tokenizer + causal shift, §17 참조)
출력 계층 설계(summary / raw / save)로 MCP context 폭발 방지
완전한 오류 분류(400/401/403/404/408/413/422/429/5xx/timeout) + retry/backoff
API Key는 환경 변수에서만 읽으며, 절대 하드코딩하지 않고 로그에도 기록하지 않음
배치 스크립트 제공:
scripts/score_fasta.py(배치 FASTA 스코어링 + embedding 추출, §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 엔드포인트:
POST https://health.api.nvidia.com/v1/biology/arc/evo2-7b/forward요청 본문(공식 OpenAPI
ForwardInputs):{ "sequence": "ACGTACGT...", "output_layers": ["output_layer"] }output_layers는 1–100개의 layer 이름을 지원합니다(예: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, shape[seq_len, batch_size, 512](512는 byte-level tokenizer의 padded vocabulary size).
⚠️ Deprecation 안내(2026-08-24 확인): build.nvidia.com에서 호스팅되는
arc/evo2-7b엔드포인트는 Deprecated로 표시되었습니다(페이지에 "This NIM Endpoint has been deprecated" 표시). 공식 NIM 문서(docs.nvidia.com/nim/bionemo/evo2/latest/)에 설명된 API는 호스팅 엔드포인트와 완전히 동일합니다. 호스팅 엔드포인트를 사용할 수 없는 경우 자체 호스팅 NIM 컨테이너로 전환하고EVO2_MCP_BASE_URL을http://localhost:8000/biology/arc/evo2로 지정할 수 있습니다.
확인된 공식 사실(구현 근거, 2026-08-24)
항목 | 결론 | 출처 |
응답 형식 | JSON | NVIDIA NIM endpoints 문서 + 호스팅 OpenAPI schema( |
|
| 동일("Final output/logits") |
vocabulary 크기 | 512(padded); byte-level tokenizer, 1 bp = 1 token | NVIDIA 문서 + Arc/vortex |
A/C/G/T → logits index | A=65, C=67, T=84, G=71(ASCII 바이트 값) | NVIDIA 문서 원문 + |
BOS/EOS/offset | 기본 BOS 없음(Arc | Arc |
likelihood 계산 |
| Arc |
특수 token | 출력에서 A/C/G/T 4개 token만 의미 있음(NIM 문서 원문) | NVIDIA 문서 |
실측과 문서의 차이(2026-08-24 live 검증, 작업 요구사항: 실제 인터페이스 기록)
실제 key로 호스팅 health.api.nvidia.com 엔드포인트를 탐색한 결과 문서의 layer 이름은 호스팅 엔드포인트에서 적용되지 않습니다:
요청한 layer 이름 | 호스팅 API 실제 동작 |
| ❌ |
| ❌ 422 |
| ✅ 최종 logits: NPZ key |
| ✅ |
| ✅ |
| ✅ |
대응 조치(구현 완료, live 통과):
EVO2_MCP_LOGITS_LAYER설정 추가(기본auto): 스코어링 도구가 먼저 문서 이름output_layer를 시도하고,422 has no attribute(호스팅 엔드포인트)를 받으면 자동으로unembed로 전환하여 캐시하고 이후 재탐색하지 않음; 자체 호스팅 NIM 2.x 컨테이너는 한 번에 성공, 추가 요청 0회.NPZ 파서는 bare key(
output_layer)와<name>.output(unembed.output) 두 가지 key 형식을 모두 지원하며, "마지막 차원 = 512" 휴리스틱으로 폴백.422오류 메시지에 이제 호스팅 엔드포인트에서 사용 가능한 속성 이름을 안내.
반환된
seq_len이 입력 시퀀스 길이와 일치하지 않는 경우(예: 서버가 padding/BOS를 추가한 경우), 이 서버는 likelihood 계산을 거부하고 raw 통계 + 명확한 설명을 반환하며, 절대 정렬을 추측하지 않습니다.
3. NVIDIA API Key 획득 방법
https://build.nvidia.com/을 열고 오른쪽 상단의 Get API Key(NVIDIA 계정 로그인 필요)를 클릭합니다.
key를 생성합니다(
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 testPython >= 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 Key, 여기서만 읽음 |
|
| 서비스 주소(자체 호스팅 NIM 시 변경) |
|
| HTTP 읽기 타임아웃(초) |
|
| 408/429/5xx 최대 재시도 횟수 |
|
| batch/FASTA 동시성 상한 |
| 비어 있음 | FASTA 읽기 허용 디렉터리( |
|
|
|
|
|
|
|
| 시퀀스 길이 하드 상한 |
|
|
|
|
| per-position 목록 반환 상한(초과 시 앞뒤만 반환) |
|
| 스코어링용 logits layer 이름: |
6. CLI 시작
# 三种方式等价
python -m evo2_mcp
evo2-mcp
uv run evo2-mcp # 用 uv 管理的项目环境
# pixi 环境:
pixi run evo2-mcp서버는 stdio를 통해 MCP 클라이언트와 통신하며, 정상 시작 후에는 출력이 없습니다(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}가 클라이언트에 의해 확장되는지는 클라이언트 구현에 따라 다릅니다. 가장 안전한 방법은 실제 key를 직접 입력하는 것입니다:
{
"mcpServers": {
"evo2": {
"command": "uv",
"args": ["run", "evo2-mcp"],
"env": {
"NVIDIA_API_KEY": "YOUR_API_KEY"
}
}
}
}하지만 실제 key가 포함된 .mcp.json을 Git에 절대 커밋하지 마세요(해당 파일을 .gitignore에 추가하거나 환경 변수/비밀 관리 도구로 주입). 또는 env를 전달하지 않고 서버 프로세스가 환경 또는 .env에서 NVIDIA_API_KEY를 직접 읽도록 할 수도 있습니다:
{
"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. Tool 목록
evo2_forward(sequence, output_layers=["output_layer"], mode="summary", save_path=None)
DNA sequence에 대해 Evo2-7B forward inference를 실행합니다. mode:
"summary"(기본값): 각 레이어에 대해shape / dtype / min / max / mean / std반환, context 안전;"save": 원본 tensor를.npz로 저장(output/evo2_forward_<타임스탬프>.npz), 경로 반환;"raw": 전체 tensor 인라인(요소 총 수가EVO2_MCP_RAW_INLINE_MAX이하인 경우에만, 기본 4096, context 폭발 방지).
layer 이름 주의: 호스팅
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를 직접 호출할 때만 실제 엔드포인트에 맞는 이름을 선택해야 합니다.
evo2_score(sequence, include_per_position=False)
Evo2의 시퀀스에 대한 likelihood 계산:
{
"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의 염기를 예측하며, 전체 512 vocab에서 log-softmax 후 대상 염기 바이트 인덱스를 취합니다. position 0은 스코어링에 참여하지 않으므로 scored_positions = length - 1, mean은 이 N-1개 값의 평균입니다. per_position_log_likelihood[k]는 시퀀스 0-based 위치 k+1(즉 1-based 위치 k+2)에 해당합니다. API가 반환한 seq_len을 시퀀스와 정렬할 수 없는 경우 결과를 위조하지 않고 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-based 위치 1(0-based 0)은 스코어링 불가(causal LM은 첫 번째 token에 확률을 부여할 수 없음) → 명시적 오류.
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는 한 번만 계산하고 모든 variant에 재사용;
동일한
(position, alt)의 mutant는 한 번만 forward(memoize);동시성은
EVO2_MCP_MAX_CONCURRENCY로 제한(기본 2, NVIDIA rate limit 준수);단일 variant 실패는 전체 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 }
}Agent가 전체 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) 스코어링 + embedding 추출은 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" }
]
}일반적인 Agent 워크플로("시퀀스의 모든 SNP를 분석하여 Evo2 score 변화가 가장 큰 상위 20개 찾기"에 해당):
读取输入 → 解析 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 과대 | 바로 오류 보고, 시퀀스 또는 layer 수 축소 안내 |
422 | 파라미터 검증 실패 | 바로 오류 보고, 상세 내용 첨부 |
429 | Rate limit | 재시도 + exponential backoff( |
5xx | NVIDIA 서버 오류 | 제한적 재시도 후 오류 보고 |
timeout | 요청 타임아웃( | 명확한 오류 보고: |
모든 오류는 MCP를 통해 구조화된 JSON으로 반환됩니다: {"error": "Evo2APIError", "message": "..."}. evo2_batch_score에서 단일 항목 실패 시 {"error": ..., "status": ...}을 반환하며, 전체 배치를 중단하지 않습니다.
14. Rate limit
NVIDIA 호스팅 NIM에는 rate limit이 있습니다. 대응 설계:
EVO2_MCP_MAX_CONCURRENCY(기본 2)로 동시성 제한;429 → exponential backoff(1s, 2s, 4s, 8s, 16s…, 상한 30s + 지터;
Retry-After가 있으면 우선 따르되 상한 60s);재시도 상한
EVO2_MCP_MAX_RETRIES(기본 4), 무한 재시도 없음;batch 내 WT는 한 번만 계산, 동일 mutant 중복 제거로 요청 수 감소.
15. 보안 설명
API Key:
NVIDIA_API_KEY환경 변수(또는.env)에서만 읽음; 코드에 하드코딩된 key 없음; 로그에는 URL, 시퀀스 길이, layer 이름만 기록하며, 시퀀스 내용과 key는 기록하지 않음; 오류 메시지에는 응답 앞 500자 요약만 포함.시퀀스 프라이버시: 모든 로그/오류에는
preview만 포함(예:ACGT...GCTA (len=12345)).경로 샌드박스:
FASTA 읽기는
EVO2_MCP_ALLOWED_DIRS로만 제한; 미설정 시 모든 로컬 경로 거부;mode="save"의save_path는 반드시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 실행도 하지 않음; Agent는 FASTA/시퀀스 입력을 통해 제한된 HTTP 요청만 트리거할 수 있음.
16. 생물학적 해석 제한
Evo2 score는 model-based sequence likelihood change이며, 실험적 증거도 임상적 병원성 진단도 아님.
delta_log_likelihood < 0은 "돌연변이체 서열이 모델 하에서 덜 가능성 있음"으로만 해석해야 하며, "병원성"으로 해석해서는 안 됨.pathogenicity를 논하려면 downstream 검증(실험, 집단 빈도, ClinVar 주석, 단백질 구조 영향 등)이 필요.
각 Tool의 description에는 다음 선언이 포함됨(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
NVIDIA 호스팅 API 참조(arc/evo2-7b-forward OpenAPI schema): https://docs.api.nvidia.com/nim/reference/arc-evo2-7b-infer
호스팅 엔드포인트 실측(2026-08-24, 실제 key):
output_layer는 422StripedHyena has no attribute 'output_layer'반환;unembed는 logits 반환(NPZ keyunembed.output, shape(1, seq, 512), float64) — 따라서 스코어링 도구는 기본적으로EVO2_MCP_LOGITS_LAYER=auto로 자동 탐지배치 실측(2026-08-25, 실제 key, 3800+개 K562 enhancer/promoter):
시퀀스 > ~100 kb일 때 호스팅 측에서 422 반환(PyTorch
canUse32BitIndexMath제한) — 배치 실행 시--skip-longer-than 100000사용;동시성 하에서 layer 이름 자동 탐지의 경쟁 조건 수정됨(
forward_logits가 로컬 변수로 시도 이름 기록) 및 회귀 테스트 추가;embedding 추출:
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 공식 tokenizer 구현): PyPIvtx1.1.0 소스vortex/model/tokenizer.pyEvo2 모델 카드: https://huggingface.co/ArcInstitute/evo2_7b
NVIDIA가 API를 조정하면 공식 최신 문서를 기준으로 하십시오; EVO2_MCP_BASE_URL은 언제든 전환 가능합니다.
18. 배치 스코어링 및 Embedding 추출(scripts/score_fasta.py)
MCP Tools는 Agent의 인터랙티브 호출에 적합; 대량 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주요 파라미터:
파라미터 | 설명 |
| 어떤 layer의 embedding을 추출할지(기본 |
| 각 시퀀스의 원본 위치별 embedding |
| 해당 길이를 초과하는 시퀀스 건너뛰기(호스팅 API 제한, §17 참조) |
| N 염기 통과 허용(N 포함 5개 시퀀스도 정상 실행되며 caveat 경고 포함) |
| 동시성 수(기본 2, rate limit 존중) |
| 기본 run 폴더 레이아웃 덮어쓰기 |
효율 설계: 각 시퀀스당 요청 1회만 전송(output_layers=["unembed","norm"], logits와 embedding 동시 획득); logits layer 이름은 전체 실행에서 한 번만 탐지; 동시성은 세마포어로 제한.
19. Embedding 연관 및 다운스트림 분석(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, layer 이름 자동 탐지(동시성 경쟁 조건 회귀 포함), variant 검증, variant/batch 스코어링 수학적 정확성(Arc 의미론과 대조하여 독립 재계산), NPZ 디코딩(JSON base64 / zip / 구버전 JSON tensor / <layer>.output key), FASTA 샌드박스, MCP session 통합, 스크립트 순수 함수(pooling/키 이름) 등.
실제 API 스모크 테스트(실제 key 필요, 기본 건너뜀). key는 .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 layer 자동 탐지(unembed), 실제 NPZ 파싱((1, seq, 512) float64), evo2_score와 원본 logits에서 수동 재계산 결과 일치, variant score.
프로젝트 구조
.
├── 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
AI-powered bioprotocol optimization — generate, search, and manage lab protocols via MCP
Free OpenAI-compatible inference with signed provenance receipts and 3 focused MCP tools.
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