paper-fetch
Original:🇺🇸 English
Translated
1 scripts
Use whenever the user wants to obtain, download, or fetch a paper's PDF — given a DOI, an arXiv id, a paper title, a citation, or a list of DOIs. Trigger on phrases like "download this paper", "find the PDF for [DOI]", "grab me the [Nature/bioRxiv/arXiv] paper on X", "get the open-access version", "I need this article", or any bulk/batch paper download request, even when the user doesn't explicitly say "PDF" or "DOI". Resolves via Unpaywall → Semantic Scholar → arXiv → PubMed Central → bioRxiv/medRxiv → publisher direct (institutional opt-in) → Sci-Hub mirrors as last-resort fallback.
14installs
Sourceagents365-ai/365-skills
Added on
NPX Install
npx skill4agent add agents365-ai/365-skills paper-fetchTags
Translated version includes tags in frontmatterSKILL.md Content
View Translation Comparison →paper-fetch
Fetch the PDF for a paper given a DOI (or title). Tries multiple sources in priority order and stops at the first hit.
Resolution order
- Unpaywall — , read
https://api.unpaywall.org/v2/{doi}?email=$UNPAYWALL_EMAIL(skipped ifbest_oa_location.url_for_pdfnot set)UNPAYWALL_EMAIL - Semantic Scholar —
https://api.semanticscholar.org/graph/v1/paper/DOI:{doi}?fields=openAccessPdf,externalIds - arXiv — if present,
externalIds.ArXivhttps://arxiv.org/pdf/{arxiv_id}.pdf - PubMed Central OA — if PMCID present,
https://www.ncbi.nlm.nih.gov/pmc/articles/{pmcid}/pdf/ - bioRxiv / medRxiv — if DOI prefix is , query
10.1101for the latest version PDF URLhttps://api.biorxiv.org/details/{server}/{doi} - Publisher direct (institutional mode only — ) — DOI-prefix → publisher PDF template (Nature / Science / Wiley / Springer / ACS / PNAS / NEJM / Sage / T&F / Elsevier). The caller's own subscription IP / cookies / EZproxy are what authorize the fetch; unauthorized responses fail the
PAPER_FETCH_INSTITUTIONAL=1check and fall through to step 7.%PDF - Sci-Hub mirrors (on by default; disable with ) — last-resort fallback. Tries the mirror list in
PAPER_FETCH_NO_SCIHUB=1(or built-in defaultsPAPER_FETCH_SCIHUB_MIRRORS,sci-hub.ru,sci-hub.st,sci-hub.su,sci-hub.box,sci-hub.red,sci-hub.al,sci-hub.mk) in order; on full miss, scrapessci-hub.eeonce per process for fresh mirrors. CAPTCHA / missing-paper pages have no PDF iframe and fall through silently.https://www.sci-hub.pub/ - Otherwise → report failure with title/authors so the user can request via ILL
If only a title is given, pass it directly via . Resolution chain:
--title "<title>"- Crossref — primary; covers all major journal/conference DOIs
query.title - Semantic Scholar — fallback when Crossref's top match is low-confidence (
/paper/search/match) or the gap to the runner-up ismatch_score < 40. Critically, S2 covers arXiv-only preprints (no Crossref DOI). When S2 surfaces a paper that has only an arXiv id, the canonical< 3is synthesized so the download chain stays uniform.10.48550/arXiv.<id> - Crossref's best guess (low-confidence) — used only when both resolvers struggled. The result envelope sets plus a
meta.title_resolution.low_confidence: true(low_confidence_reason/score_below_threshold) so an agent can either bail or confirm viaambiguous_runner_up.--dry-run
Either way the resolved DOI, the winning resolver, the full list, and the top candidate matches are all surfaced under .
resolvers_triedmeta.title_resolutionIf is registered, the agent can alternatively resolve title → DOI through the Asta MCP first, then pass the DOI directly here. This skips paper-fetch's two-stage Crossref/S2 chain in favor of Asta's richer search surface (relevance ranking, snippet search, citation graph). Workflow: call , read (or when only is present), then . Use when Asta isn't available or when a single command is preferred.
asta-skillasta__search_paper_by_title("<title>", fields="title,year,authors,externalIds")externalIds.DOI10.48550/arXiv.<ArXiv>ArXivpaper-fetch <doi>--titleUsage
bash
python scripts/fetch.py <DOI> [options]
python scripts/fetch.py --title "<paper title>" [options]
python scripts/fetch.py --batch <FILE|-> [options]
python scripts/fetch.py schema # machine-readable self-descriptionFlags
The flags below are the ones an agent composes in normal use. For the complete contract — including , , , , , , plus parameter types and exit-code mappings — run (machine-readable, drift-checked via ).
--dry-run--pretty--stream--overwrite--timeout--versionpython scripts/fetch.py schemaschema_version| Flag | Default | Description |
|---|---|---|
| — | DOI to fetch (positional). Use |
| — | Paper title; resolved to a DOI via Crossref before download. Mutually exclusive with positional DOI / |
| — | File with one DOI per line for bulk download. Use |
| | Output directory |
| auto | |
| — | Safe-retry key. Re-running with the same key replays the original envelope from |
Agent discovery: schema
subcommand
schemabash
python scripts/fetch.py schemaEmits a complete machine-readable description of the CLI on stdout (no network). Includes , , parameter types, exit codes, error codes, envelope shapes, and environment variables. Agents should read this once, cache it against , and re-read when the cached version drifts.
cli_versionschema_versionschema_versionOutput contract
stdout emits a single JSON envelope. Every envelope carries a slot.
metaSuccess (all DOIs resolved):
json
{
"ok": true,
"data": {
"results": [
{
"doi": "10.1038/s41586-021-03819-2",
"success": true,
"source": "unpaywall",
"pdf_url": "https://www.nature.com/articles/s41586-021-03819-2.pdf",
"file": "pdfs/Jumper_2021_Highly_accurate_protein_structure_predic.pdf",
"meta": {"title": "Highly accurate protein structure prediction with AlphaFold", "year": 2021, "author": "Jumper"},
"sources_tried": ["unpaywall"]
}
],
"summary": {"total": 1, "succeeded": 1, "failed": 0},
"next": []
},
"meta": {
"request_id": "req_a908f5156fc1",
"latency_ms": 2036,
"schema_version": "1.9.0",
"cli_version": "0.13.1",
"sources_tried": ["unpaywall"]
}
}Partial (batch mode — some DOIs failed, exit code reflects the failure class):
json
{
"ok": "partial",
"data": {
"results": [
{ "doi": "10.1038/s41586-021-03819-2", "success": true, "source": "unpaywall", ... },
{
"doi": "10.1234/nonexistent",
"success": false,
"source": null,
"pdf_url": null,
"file": null,
"meta": {},
"sources_tried": ["unpaywall", "semantic_scholar"],
"error": {
"code": "not_found",
"message": "No open-access PDF found",
"retryable": true,
"retry_after_hours": 168,
"reason": "OA availability changes over time; retry after embargo lifts or preprint appears"
}
}
],
"summary": {"total": 2, "succeeded": 1, "failed": 1},
"next": ["paper-fetch 10.1234/nonexistent --out pdfs"]
},
"meta": { ... }
}The slot is an array of suggested follow-up commands: re-invoking them retries only the failed subset. Combine with to make the whole batch safely retriable without re-downloading the already-succeeded items.
next--idempotency-keyFailure (bad arguments, exit code 3):
json
{
"ok": false,
"error": {
"code": "validation_error",
"message": "Provide a DOI or --batch file",
"retryable": false
},
"meta": { ... }
}Per-item skipped (destination already exists, no ):
--overwritejson
{
"doi": "10.1038/s41586-021-03819-2",
"success": true,
"source": "unpaywall",
"pdf_url": "https://...",
"file": "pdfs/Jumper_2021_...pdf",
"skipped": true,
"skip_reason": "file_exists",
"sources_tried": ["unpaywall"]
}Idempotency replay (re-run with the same ):
--idempotency-keyThe cached envelope is returned verbatim, but and are re-stamped for the current call, and is set. No network I/O occurs.
meta.request_idmeta.latency_msmeta.replayed_from_idempotency_keyStderr progress (NDJSON)
When , stderr emits one JSON object per line for liveness:
--format json{"event": "session", "request_id": "req_...", "elapsed_ms": 0, "cli_version": "0.13.1", "schema_version": "1.9.0"}
{"event": "start", "request_id": "req_...", "elapsed_ms": 2, "doi": "10.1038/..."}
{"event": "source_try", "request_id": "req_...", "elapsed_ms": 2, "doi": "...", "source": "unpaywall"}
{"event": "source_hit", "request_id": "req_...", "elapsed_ms": 2036, "doi": "...", "source": "unpaywall", "pdf_url": "..."}
{"event": "download_ok", "request_id": "req_...", "elapsed_ms": 4120, "doi": "...", "file": "..."}Event types: , , , , , , , , , , , , . All events share and , letting an orchestrator correlate progress across stderr and the final stdout envelope. The event fires once per invocation, before any DOI work or network I/O, and carries / so agents can detect schema drift against a cached copy without waiting for the final envelope.
sessionstartsource_trysource_hitsource_misssource_skipsource_enrichsource_enrich_faileddownload_okdownload_errordownload_skipdry_runnot_foundrequest_idelapsed_mssessioncli_versionschema_versionsource_enrichauthortitlefieldssource_enrich_failedunknown_<year>_…When , stderr emits human-readable prose.
--format textExit codes
| Code | Meaning | Retryable class |
|---|---|---|
| All DOIs resolved / previewed | — |
| Unresolved — one or more DOIs had no OA copy; no transport failure | Not now (retry after |
| Reserved for auth errors (currently unused) | — |
| Validation error (bad arguments, missing input) | No |
| Transport error (network / download / IO failure) | Yes |
The taxonomy lets an orchestrator route failures deterministically: exit 4 is worth retrying immediately, exit 1 is not, exit 3 is a bug in the caller.
Error codes in JSON
Every retryable error carries a hint in the error object, so an orchestrator can schedule retries without guessing.
retry_after_hours| Code | Meaning | Retryable | |
|---|---|---|---|
| Bad arguments or empty input | No | — |
| Crossref returned no items for the given | No | — |
| No open-access PDF found | Yes | |
| Network failure during download | Yes | |
| Response was not a PDF (HTML landing page) | No | — |
| PDF URL failed SSRF safety check (private IP / non-http(s) / non-80,443 / blocked metadata host) | No | — |
| Response exceeded 50 MB limit | Yes | |
| Local filesystem write failed | Yes | |
| Unexpected error | No | — |
The canonical mapping lives in in and is surfaced in .
RETRY_AFTER_HOURSscripts/fetch.pyschema.error_codesExamples
bash
# Single DOI (JSON output when piped; text when in a terminal)
python scripts/fetch.py 10.1038/s41586-020-2649-2
# Single title (resolved to DOI via Crossref, then downloaded)
python scripts/fetch.py --title "Highly accurate protein structure prediction with AlphaFold"
# Dry-run preview (resolve without downloading)
python scripts/fetch.py 10.1038/s41586-020-2649-2 --dry-run
# Title + dry-run — preview the resolved DOI and candidate matches
python scripts/fetch.py --title "Attention Is All You Need" --dry-run
# Force JSON (for agents even inside a terminal)
python scripts/fetch.py 10.1038/s41586-020-2649-2 --format json
# Human-readable with pretty colors in a pipeline
python scripts/fetch.py 10.1038/s41586-020-2649-2 --format text
# Batch download, safely retriable
python scripts/fetch.py --batch dois.txt --out ./papers \
--idempotency-key monday-review-batch
# Pipe DOIs from another tool
zot -F ids.json query ... | jq -r '.[].doi' | python scripts/fetch.py --batch -
# Agent discovery
python scripts/fetch.py schema --pretty
# Streaming mode — one result per line as each DOI resolves
python scripts/fetch.py --batch dois.txt --stream
# Works without UNPAYWALL_EMAIL (skips Unpaywall, uses remaining 4 sources)
python scripts/fetch.py 10.1038/s41586-020-2649-2Environment
| Variable | Default | Purpose |
|---|---|---|
| unset | Contact email for Unpaywall API. Optional but recommended. Without it, Unpaywall is skipped (remaining sources still work). |
| unset | Set to any value (e.g. |
| unset | Set to any value to disable the Sci-Hub fallback (step 7). |
| unset | Comma-separated mirror hostnames to try in priority order (e.g. |
Institutional access (opt-in)
Many researchers have legitimate subscription access through their institution's IP range (on-campus or VPN). Paper-fetch can use that access by letting the publisher's own auth (your IP, your session cookies) decide whether to serve the PDF.
Host reachability does not differ between modes — public mode already trusts URLs returned by the OA APIs (Unpaywall, Semantic Scholar, bioRxiv, PMC) and fetches any HTTPS host that passes SSRF defense. Institutional mode adds two things: (1) a publisher-direct fallback (step 6 above) that constructs a publisher-side PDF URL by DOI prefix when every OA source missed, so your institutional IP/cookies can authorize the fetch, and (2) a 1 req/s rate limiter to keep batch jobs from getting your IP throttled or banned for "systematic downloading."
Opt in:
export PAPER_FETCH_INSTITUTIONAL=1What changes in institutional mode:
| Aspect | Public (default) | Institutional |
|---|---|---|
| Host reachability | Any public HTTPS host passing SSRF defense | Same |
| SSRF defense | Enforced (private IP / non-http(s) / non-80,443 / cloud metadata all blocked) | Enforced — same rules |
| Publisher-direct fallback | Off | On — DOI-prefix → publisher PDF URL, last resort after all OA sources miss |
| Rate limit | None | 1 req/s token bucket (all outbound) |
| | |
What stays the same:
- magic-byte check and 50 MB size cap (prevents HTML landing pages and oversized responses slipping through)
%PDF - No CAPTCHA solving, ever. If a publisher shows a challenge, the response won't start with and paper-fetch falls through to the next source.
%PDF - No browser automation, no Playwright, no stealth.
- Agent cannot opt in on its own — must be set by the human operator in the shell environment. This is the trust boundary.
PAPER_FETCH_INSTITUTIONAL
When paper-fetch can't find an OA copy and you're in public mode, the error envelope includes and a hint telling the user to set the env var. Agents can surface this verbatim rather than failing silently.
suggest_institutional: trueToS notice: almost every publisher subscription prohibits "systematic downloading." The 1 req/s rate limit plus the existing per-file idempotency are designed to keep individual research use within acceptable bounds. Running many parallel paper-fetch processes, or lifting the rate limit, can trigger a publisher-wide IP ban affecting your entire institution. Don't.
Notes
- Auth is delegated. The agent never runs a login subcommand. The human or the orchestrator sets in the environment; the agent inherits it. Missing email degrades gracefully to the remaining 4 sources.
UNPAYWALL_EMAIL - Trust is directional. CLI arguments are validated once at the entry point. SSRF defense, the magic-byte check, and the 50 MB size cap are enforced in the environment layer, not at the agent's request. An agent cannot loosen safety by passing a flag — opting into institutional mode (and its rate-limit risk profile) is an operator action via environment variable.
%PDF - Downloads are naturally idempotent. Re-running against the same skips files that already exist (deterministic filename:
--out; the journal segment is omitted if metadata lacks a journal/venue). Pair with{first_author}_{year}_{journal_abbrev}_{short_title}.pdfto also replay the exact envelope without any network I/O.--idempotency-key - Default output directory: .
./pdfs/