Skip to content

Add ArXiv search MCP tool with tests and dependency - #1418

Merged
tamohannes merged 15 commits into
mainfrom
feat/arxiv-mcp-tool
May 2, 2026
Merged

tamohannes merged 15 commits into
mainfrom
feat/arxiv-mcp-tool

Conversation

@tamohannes

@tamohannes tamohannes commented May 2, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

  • Reopened from an internal NVIDIA-NeMo/Skills branch so CI can access repository secrets.
  • Replaces Add ArXiv search MCP tool with tests and dependency #1387.
  • Add ArxivSearchTool as a first-party MCP server for scientific paper retrieval via the free arXiv API, with search/get/sections/chunked-read support.
  • Add docs and focused tests for config, tool listing, schema exposure/hiding, invalid ID handling, and live API behavior.

Test plan

  • pytest tests/test_mcp_clients.py::TestArxivTool -m "not live"
  • pytest tests/test_mcp_clients.py::TestArxivTool -m live
  • pytest tests/test_mcp_clients.py -m "not live and not gpu"

Summary by CodeRabbit

  • New Features

    • Added ArXiv integration for searching, metadata lookup, section browsing, and chunked full-text reading.
  • Documentation

    • Reference docs updated to list the new ArXiv search tool.
  • Tests

    • Added tests covering ArXiv tool configuration, input validation, and tool listing.

Add ArxivSearchTool as a first-party MCP server for scientific paper
retrieval via the free arXiv API (no API key required). Includes:

- New nemo_skills/mcp/servers/arxiv_tool.py with arxiv-search and
  arxiv-get tools, rate limiting, retry logic, and response caching
- Declare `arxiv` dependency in tools/requirements.txt
- CI: install [tools] extra so MCP tool deps are available in tests
- Tests: config validation, offline stdio subprocess integration
  (list_tools, hide_args), invalid-id handling, and live API tests
- Docs: add ArxivSearchTool to built-in tools reference

Signed-off-by: tamohannes <[email protected]>
Made-with: Cursor
…dling

- Replace stop-at-capacity cache with LRU eviction via OrderedDict
- Clamp max_results to [1, MAX_RESULTS] instead of only capping upper bound
- Remove broad except-Exception handlers; let unexpected errors propagate
  (expected transient errors are already handled by _with_retry)
- Add @pytest.mark.live to test_arxiv_get_invalid_id (makes real API call)
- Wrap stdio integration tests in try/finally for guaranteed shutdown

Signed-off-by: tamohannes <[email protected]>
Made-with: Cursor
Use direct arXiv/OpenAlex API clients with bounded paper chunking and shared request throttling so retrieval stays robust under parallel eval workloads.

Signed-off-by: tamohannes <[email protected]>
Made-with: Cursor
@coderabbitai

coderabbitai Bot commented May 2, 2026 •

Copy link
Copy Markdown
Contributor

Warning

Rate limit exceeded

@tamohannes has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 3 minutes and 16 seconds before requesting another review.

To keep reviews running without waiting, you can enable usage-based add-on for your organization. This allows additional reviews beyond the hourly cap. Account admins can enable it under billing.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: f63184f7-62cc-4b81-bd3a-1d7dad400fc1

📥 Commits

Reviewing files that changed from the base of the PR and between 2664672 and c649093.

📒 Files selected for processing (2)
  • docs/agentic_inference/tool_calling.md
  • nemo_skills/mcp/servers/arxiv_tool.py
📝 Walkthrough

Walkthrough

A new arXiv search tool module was added to the MCP servers providing metadata search, OpenAlex-based metadata lookup with fallback to arXiv, full-paper HTML retrieval and parsing, section listing, and chunked text reads. Documentation and tests were updated to reference and validate the new ArxivSearchTool.

Changes

ArXiv Search Tool Implementation

Layer / File(s) Summary
Configuration & Caching
nemo_skills/mcp/servers/arxiv_tool.py
Module constants for OpenAlex/arXiv endpoints, user-agent, retry/backoff, and sized in-memory caches (general response cache and full-paper LRU cache); cross-process arXiv request throttling state.
Cache Helpers
nemo_skills/mcp/servers/arxiv_tool.py
Hashed JSON-argument key builder, bounded FIFO-ish eviction for response cache, and LRU refresh + size enforcement for full-paper text cache.
Text & ID Utilities
nemo_skills/mcp/servers/arxiv_tool.py
_reconstruct_abstract, _truncate, _ArxivHTMLTextParser (preserves headings), _normalize_id, and _extract_arxiv_id for identifier normalization and text extraction/section offset computation.
Full-Text Retrieval
nemo_skills/mcp/servers/arxiv_tool.py
_fetch_paper_text fetches native arXiv HTML with ar5iv fallback, parses to extract readable text, caches full text, and errors when no arXiv ID can be derived.
Atom & OpenAlex Integration
nemo_skills/mcp/servers/arxiv_tool.py
ArXiv Atom feed parser (_parse_arxiv_atom) and _arxiv_api_search for search; _http_get_json with retry/backoff and OpenAlex 429 handling (drops API key and retries politely).
Rate Limiting
nemo_skills/mcp/servers/arxiv_tool.py
_arxiv_rate_limit implements cross-process throttling using fcntl.flock with async lock fallback to enforce ARXIV_REQUEST_INTERVAL.
Public Async Functions
nemo_skills/mcp/servers/arxiv_tool.py
arxiv_search, arxiv_get, arxiv_sections, arxiv_read_chunk — each applies input validation, caching, rate-limiting, formatting, and descriptive error strings on failure.
Tool Class & Wiring
nemo_skills/mcp/servers/arxiv_tool.py
ArxivSearchTool(Tool) defines default_config, configure, list_tools (schemas for arxiv-search, arxiv-get, arxiv-sections, arxiv-read-chunk), and execute routing to async functions.
Tests & Docs
tests/test_mcp_clients.py, docs/agentic_inference/tool_calling.md
Added TestArxivTool tests validating defaults, input validation, and tool registration; docs updated to list ArxivSearchTool in built-in tools.
sequenceDiagram
    participant User
    participant ArxivTool as ArxivSearchTool
    participant Cache
    participant ArxivAPI as arXiv API
    participant OpenAlexAPI as OpenAlex API
    participant Limiter as RateLimiter

    User->>ArxivTool: arxiv_search(query, max_results)
    ArxivTool->>Cache: check_result(query, max_results)
    alt Cache Hit
        Cache-->>ArxivTool: cached_results
    else Cache Miss
        ArxivTool->>Limiter: acquire_lock()
        Limiter-->>ArxivTool: lock_granted
        ArxivTool->>ArxivAPI: GET Atom feed with query
        ArxivAPI-->>ArxivTool: Atom XML response
        ArxivTool->>ArxivTool: parse_entries()
        ArxivTool->>Cache: store_result(query, results)
    end
    ArxivTool-->>User: formatted_results

    User->>ArxivTool: arxiv_get(paper_id)
    ArxivTool->>Cache: check_metadata(paper_id)
    alt Cache Hit
        Cache-->>ArxivTool: cached_metadata
    else Cache Miss
        ArxivTool->>OpenAlexAPI: GET works endpoint
        alt OpenAlex Success
            OpenAlexAPI-->>ArxivTool: work_record
        else OpenAlex 429 or Error
            ArxivTool->>ArxivAPI: fallback single-paper query
            ArxivAPI-->>ArxivTool: fallback_abstract
        end
        ArxivTool->>Cache: store_metadata(paper_id, result)
    end
    ArxivTool-->>User: formatted_metadata

    User->>ArxivTool: arxiv_read_chunk(paper_id, offset, max_chars, query)
    ArxivTool->>Cache: check_full_text(paper_id)
    alt FullText Cached
        Cache-->>ArxivTool: extracted_text
    else FullText Not Cached
        ArxivTool->>ArxivAPI: fetch paper HTML
        ArxivTool->>ArxivTool: parse_html_to_text()
        ArxivTool->>Cache: store_full_text(paper_id, text)
    end
    ArxivTool->>ArxivTool: apply_offset_and_query()
    ArxivTool-->>User: text_chunk
Loading

🎯 4 (Complex) | ⏱️ ~60 minutes

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 58.97% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely summarizes the main changes: adding an ArXiv search MCP tool along with tests and dependency. It directly corresponds to the three modified files and their purposes.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/arxiv-mcp-tool

Review rate limit: 0/10 reviews remaining, refill in 3 minutes and 16 seconds.

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@docs/agentic_inference/tool_calling.md`:
- Around line 373-375: Remove the duplicated bullet for
nemo_skills.mcp.servers.arxiv_tool.ArxivSearchTool so it only appears once in
the list; keep the preferred description (choose either "ArXiv paper search and
retrieval (no API key required)" or "Direct arXiv paper search and retrieval (no
API key required)"), and ensure the list contains the unique entries:
nemo_skills.mcp.servers.arxiv_tool.ArxivSearchTool and
nemo_skills.mcp.servers.exa_tool.ExaTool.

In `@nemo_skills/mcp/servers/arxiv_tool.py`:
- Around line 769-771: The configure method on arxiv_tool.py currently updates
self._config with any keys, so typos or wrong types slip through; change
configure(self, overrides, context) to validate and normalize overrides before
updating: define the allowed keys (e.g. the keys used by execute()), map common
synonyms (e.g. "max_result" -> "max_results") to canonical names, check each
override key against that whitelist and raise a ValueError for unknown keys, and
validate basic types/constraints for each value (raise TypeError/ValueError for
wrong types or invalid values) before calling self._config.update(...); this
makes misconfiguration fail fast and ensures execute() receives normalized,
typed config.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: 6498bb65-e63f-4fca-ba32-d5f67116efbc

📥 Commits

Reviewing files that changed from the base of the PR and between 6877a00 and 66f45eb.

📒 Files selected for processing (3)
  • docs/agentic_inference/tool_calling.md
  • nemo_skills/mcp/servers/arxiv_tool.py
  • tests/test_mcp_clients.py

Comment thread docs/agentic_inference/tool_calling.md Resolved
Comment thread nemo_skills/mcp/servers/arxiv_tool.py Resolved

@gwarmstrong gwarmstrong left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@tamohannes
tamohannes force-pushed the feat/arxiv-mcp-tool branch from 2664672 to c649093 Compare May 2, 2026 00:14

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

♻️ Duplicate comments (1)
nemo_skills/mcp/servers/arxiv_tool.py (1)

783-783: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Inconsistent max_chars upper bound between configure() and arxiv_read_chunk().

configure() caps max_chars at PAPER_CHUNK_LIMIT (3500), but arxiv_read_chunk() at line 688 clamps to 6000, and the Field description at line 675 documents "500-6000". This means an override like {"max_chars": 5000} would be silently capped to 3500 here, even though the function itself supports up to 6000.

🔧 Suggested fix: align the upper bound
         if "max_chars" in overrides:
-            self._config["max_chars"] = max(500, min(int(overrides["max_chars"]), PAPER_CHUNK_LIMIT))
+            self._config["max_chars"] = max(500, min(int(overrides["max_chars"]), 6000))

Alternatively, define a constant MAX_CHUNK_CHARS = 6000 and use it in both places.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@nemo_skills/mcp/servers/arxiv_tool.py` at line 783, The configure() method
currently clamps self._config["max_chars"] using PAPER_CHUNK_LIMIT (3500) which
conflicts with arxiv_read_chunk()'s 6000 limit and the documented Field range;
change the shared limit so both use the same upper bound—either update
PAPER_CHUNK_LIMIT to 6000 or introduce a new constant (e.g. MAX_CHUNK_CHARS =
6000) and replace uses in configure() and arxiv_read_chunk() (and update the
Field doc if needed) so an override like {"max_chars": 5000} is not silently
reduced to 3500.
🧹 Nitpick comments (1)
nemo_skills/mcp/servers/arxiv_tool.py (1)

375-380: 💤 Low value

Nested function captures loop variable e by reference.

The text() helper defined inside the for e in ... loop captures e from the enclosing scope. This works today because text() is only called within the same iteration, but it's fragile—if someone later calls text() outside the loop or stores it, it would use the wrong entry.

♻️ Suggested fix: pass entry as parameter
     for e in root.findall("atom:entry", ns):
-
-        def text(path: str) -> str:
-            node = e.find(path, ns)
+        def text(entry: Any, path: str) -> str:
+            node = entry.find(path, ns)
             return re.sub(r"\s+", " ", node.text or "").strip() if node is not None else ""
 
         links = e.findall("atom:link", ns)
         ...
-        entry_id = text("atom:id")
+        entry_id = text(e, "atom:id")
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@nemo_skills/mcp/servers/arxiv_tool.py` around lines 375 - 380, The nested
helper text() inside the for e in root.findall("atom:entry", ns) captures loop
variable e by reference and is fragile; refactor text() to accept the entry node
as an explicit parameter (e.g., def text(entry, path: str) -> str) and update
all calls inside the loop to pass the current entry (e) instead of closing over
e; ensure the function still uses the same ns and regex logic and remains usable
outside the loop if needed.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Duplicate comments:
In `@nemo_skills/mcp/servers/arxiv_tool.py`:
- Line 783: The configure() method currently clamps self._config["max_chars"]
using PAPER_CHUNK_LIMIT (3500) which conflicts with arxiv_read_chunk()'s 6000
limit and the documented Field range; change the shared limit so both use the
same upper bound—either update PAPER_CHUNK_LIMIT to 6000 or introduce a new
constant (e.g. MAX_CHUNK_CHARS = 6000) and replace uses in configure() and
arxiv_read_chunk() (and update the Field doc if needed) so an override like
{"max_chars": 5000} is not silently reduced to 3500.

---

Nitpick comments:
In `@nemo_skills/mcp/servers/arxiv_tool.py`:
- Around line 375-380: The nested helper text() inside the for e in
root.findall("atom:entry", ns) captures loop variable e by reference and is
fragile; refactor text() to accept the entry node as an explicit parameter
(e.g., def text(entry, path: str) -> str) and update all calls inside the loop
to pass the current entry (e) instead of closing over e; ensure the function
still uses the same ns and regex logic and remains usable outside the loop if
needed.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: 1f301407-35d0-4d62-ae3b-0b67d2d3f775

📥 Commits

Reviewing files that changed from the base of the PR and between 66f45eb and 2664672.

📒 Files selected for processing (2)
  • docs/agentic_inference/tool_calling.md
  • nemo_skills/mcp/servers/arxiv_tool.py
✅ Files skipped from review due to trivial changes (1)
  • docs/agentic_inference/tool_calling.md

@tamohannes
tamohannes merged commit c616629 into main May 2, 2026
5 checks passed
@tamohannes
tamohannes deleted the feat/arxiv-mcp-tool branch May 2, 2026 01:31
cmunley1 added a commit to NVIDIA-NeMo/Gym that referenced this pull request Jun 16, 2026
## Summary

- Add a NeMo-Gym `ns_tools` config that exposes `ArxivSearchTool`
through the existing NeMo-Skills ToolManager bridge.
- Add a focused config test to keep the resource-server wiring valid.
- This is the Gym-side companion to NVIDIA-NeMo/Skills#1418.

Replaces fork-origin PR #1216 so CI can run with full repository
secrets.

## Test plan

- `PYTHONPATH=. python -m pytest
resources_servers/ns_tools/tests/test_arxiv_mcp_config.py -q --tb=short`

---------

Signed-off-by: tamohannes <[email protected]>
Co-authored-by: Christian Munley <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants