Source code for arxiv_query_mcp.semantic_scholar

"""Related papers (similar, references, citations) from Semantic Scholar.

arXiv itself has no similarity or citation data, so ``arxiv_related_papers``
asks the Semantic Scholar API, which indexes arXiv papers by their arXiv ID.
"""
from __future__ import annotations

from typing import TYPE_CHECKING, Any

import httpx

from .config import Config
from .models import Relation

if TYPE_CHECKING:
    from .cache import TwoTierCache
    from .ratelimit import RateLimiter

_FIELDS = (
    "title,authors,year,publicationDate,externalIds,citationCount,abstract,url,venue"
)

# Recommendation pools, tried in order. "all-cs" covers far more papers
# (including physics and maths in practice); "recent" only knows new ones.
_RECOMMENDATION_POOLS = ("all-cs", "recent")


[docs] class PaperNotIndexedError(Exception): """Semantic Scholar has no record of the requested arXiv paper."""
def _paper_record(raw: dict[str, Any], cfg: Config) -> dict[str, Any] | None: """Convert a Semantic Scholar paper object into this server's format. Args: raw: A paper object from the Semantic Scholar API. cfg: Server configuration providing the arXiv abstract base URL. Returns: A dict with keys ``title``, ``authors``, ``year``, ``published``, ``arxiv_id``, ``doi``, ``venue``, ``citation_count``, ``url`` and ``abstract``, or ``None`` when the entry has no title (Semantic Scholar lists unresolved references that way). """ title = (raw.get("title") or "").strip() if not title: return None ids = raw.get("externalIds") or {} arxiv_id = ids.get("ArXiv") or "" return { "title": title, "authors": [a["name"] for a in raw.get("authors") or [] if a.get("name")], "year": raw.get("year"), "published": raw.get("publicationDate") or "", "arxiv_id": arxiv_id, "doi": ids.get("DOI") or "", "venue": raw.get("venue") or "", "citation_count": raw.get("citationCount"), "url": f"{cfg.arxiv_abs_base}/{arxiv_id}" if arxiv_id else raw.get("url", ""), "abstract": (raw.get("abstract") or "").strip(), } async def _get_json( url: str, params: dict[str, Any], cfg: Config, client: httpx.AsyncClient, limiter: RateLimiter | None, ) -> dict[str, Any]: """GET a Semantic Scholar endpoint and return the decoded JSON body. Raises: PaperNotIndexedError: On HTTP 404. httpx.HTTPStatusError: On other non-2xx responses (after retries). """ from .ratelimit import resilient_get headers = {"x-api-key": cfg.s2_api_key} if cfg.s2_api_key else None try: if limiter is not None: resp = await resilient_get( client, url, params=params, headers=headers, cfg=cfg, limiter=limiter ) else: resp = await client.get(url, params=params, headers=headers) resp.raise_for_status() except httpx.HTTPStatusError as exc: if exc.response.status_code == 404: raise PaperNotIndexedError(str(exc)) from exc raise data: dict[str, Any] = resp.json() return data