Skip to content

Add Wikipedia search MCP tool with tests and dependency - #1388

Closed
tamohannes wants to merge 11 commits into
NVIDIA-NeMo:mainfrom
tamohannes:feat/wikipedia-mcp-tool
Closed

tamohannes wants to merge 11 commits into
NVIDIA-NeMo:mainfrom
tamohannes:feat/wikipedia-mcp-tool

Conversation

@tamohannes

@tamohannes tamohannes commented Apr 21, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

  • Add WikipediaSearchTool as a first-party MCP server for encyclopedic knowledge retrieval via the free Wikipedia API (no API key required)
  • New nemo_skills/mcp/servers/wikipedia_tool.py with wikipedia-search and wikipedia-page tools, disambiguation handling, and summary truncation
  • Declare wikipedia>=1.4.0 dependency in tools/requirements.txt
  • Tests: config validation, offline stdio subprocess integration (list_tools, hide_args filtering), and @pytest.mark.live API tests (search, page, disambiguation)
  • Docs: add WikipediaSearchTool to the built-in tools reference in docs/agentic_inference/tool_calling.md

Note: This PR is stacked on top of #1387 (ArXiv MCP tool) which adds the CI [tools] extra and the arxiv dependency. Once #1387 merges, this PR can be rebased onto main.

Usage

ns generate \
  --cluster local \
  --input_file data.jsonl \
  --output_dir outputs \
  --model Qwen/Qwen3-8B \
  --server_type vllm \
  --server_gpus 1 \
  ++tool_modules=[nemo_skills.mcp.servers.wikipedia_tool::WikipediaSearchTool] \
  ++inference.tokens_to_generate=8192

Test plan

  • pytest tests/test_mcp_clients.py::TestWikipediaTool -m "not live" — config, stdio list_tools, hide_args (all offline)
  • pytest tests/test_mcp_clients.py::TestWikipediaTool -m live — real Wikipedia API (search, page, disambiguation)
  • Existing test suite unaffected (pytest tests/test_mcp_clients.py -m "not live and not gpu" — all pass)

Summary by CodeRabbit

  • New Features

    • Added Wikipedia search and retrieval tool supporting article search, full text extraction, summaries, section listings, and targeted section retrieval—no API key required.
    • Tool includes intelligent rate-limiting, request caching, and automatic retry mechanisms for reliable operation.
  • Documentation

    • Updated documentation to include WikipediaSearchTool reference.

@coderabbitai

coderabbitai Bot commented Apr 21, 2026 •

Copy link
Copy Markdown
Contributor

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

This pull request introduces a new Wikipedia search and retrieval tool via Model Context Protocol (MCP), including a FastMCP server module exposing seven distinct tools for Wikipedia article operations, client-provider integration, integration tests, and documentation reference.

Changes

Cohort / File(s) Summary
Documentation
docs/agentic_inference/tool_calling.md
Added reference to WikipediaSearchTool in the built-in tools list with link and description.
Wikipedia Tool Implementation
nemo_skills/mcp/servers/wikipedia_tool.py
Created new FastMCP server module implementing seven Wikipedia tools: wikipedia-search, wikipedia-page, wikipedia-summary, wikipedia-sections, wikipedia-query-summary, wikipedia-key-facts, and wikipedia-section. Includes shared request throttling, in-memory caching, HTTP retry/backoff logic, and a WikipediaSearchTool client-provider class.
Test Coverage
tests/test_mcp_clients.py
Added TestWikipediaTool test class validating MCP client configuration, tool availability via list_tools(), and live Wikipedia API operations including search, page retrieval, and disambiguation handling.
Configuration
pyproject.toml
Added live pytest marker definition for tests interacting with external services.

Sequence Diagram(s)

sequenceDiagram
    participant Agent as Agent/User
    participant Client as WikipediaSearchTool<br/>(Client)
    participant Server as wikipedia_tool<br/>(FastMCP Server)
    participant API as Wikimedia<br/>REST API
    participant Cache as In-Memory<br/>Cache

    Agent->>Client: Call tool (e.g., wikipedia_search)
    Client->>Server: Start stdio subprocess<br/>(if not running)
    Client->>Server: Execute MCP tool request
    Server->>Cache: Check cache by query/title
    alt Cache Hit
        Cache-->>Server: Return cached result
    else Cache Miss
        Server->>API: HTTP GET request<br/>(with retry/backoff)
        API-->>Server: JSON response
        Server->>Cache: Store result with TTL
    end
    Server-->>Client: Return tool result
    Client-->>Agent: Tool output
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 51.56% 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 accurately summarizes the main change: adding a Wikipedia search MCP tool with associated tests and dependencies.
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

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: 5

🧹 Nitpick comments (2)
tests/test_mcp_clients.py (2)

1046-1054: Wrap stdio tool lifecycle in try/finally to guarantee shutdown.

If an assertion fails before await tool.shutdown(), the subprocess can leak and interfere with subsequent tests.

♻️ Suggested pattern
 tool = ArxivSearchTool()
 tool.configure()
-
-tools = await tool.list_tools()
-tool_names = {t["name"] for t in tools}
-assert "arxiv-search" in tool_names
-assert "arxiv-get" in tool_names
-
-await tool.shutdown()
+try:
+    tools = await tool.list_tools()
+    tool_names = {t["name"] for t in tools}
+    assert "arxiv-search" in tool_names
+    assert "arxiv-get" in tool_names
+finally:
+    await tool.shutdown()

Also applies to: 1061-1073, 1116-1124, 1131-1143

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

In `@tests/test_mcp_clients.py` around lines 1046 - 1054, Wrap the stdio tool
lifecycle in a try/finally to always call shutdown: for the ArxivSearchTool test
(use the ArxivSearchTool() constructor and its configure(), list_tools(), and
shutdown() calls) enclose the operations and assertions in a try block and call
await tool.shutdown() in the finally block so the subprocess cannot leak if an
assertion fails; apply the same try/finally pattern to the other similar tests
referenced (the blocks around lines that call
configure()/list_tools()/shutdown() at the 1061-1073, 1116-1124, and 1131-1143
ranges).

1105-1110: Disambiguation test assertion is too weak to catch regressions.

assert isinstance(result, str) will pass for both success and generic failure strings. Consider asserting disambiguation-specific content (e.g., "ambiguous" or "Did you mean").

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

In `@tests/test_mcp_clients.py` around lines 1105 - 1110, The test
test_wikipedia_disambiguation currently only checks isinstance(result, str)
which lets generic failure messages slip; update the assertion to verify
disambiguation-specific content from the wikipedia_page("Mercury") call (e.g.,
assert that result contains phrases like "ambiguous", "Did you mean", "may refer
to", or other site-specific disambiguation markers), so replace or augment the
isinstance check with a content assertion that reliably indicates a
disambiguation page was returned.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@nemo_skills/mcp/servers/arxiv_tool.py`:
- Around line 99-100: The code currently only caps max_results at MAX_RESULTS
(the branch beginning with "if max_results > MAX_RESULTS:") but doesn't validate
non-positive values; add an explicit lower-bound check before that cap: if
max_results <= 0, raise a ValueError (or a specific InputValidationError used in
this module) with a clear message like "max_results must be a positive integer",
ensuring the check occurs in the same function that processes the max_results
parameter so callers of this function (and downstream logic using max_results)
never receive non-positive values.
- Around line 77-88: The handlers in arxiv_search and arxiv_get should not catch
all Exception; instead catch only expected transient or API-related errors
(e.g., requests.exceptions.RequestException, arXiv client-specific exceptions,
XML/parse errors like xml.etree.ElementTree.ParseError, ValueError) and return
the friendly error string for those cases; for any other unexpected exceptions,
log the exception with context and re-raise so programming errors surface.
Update the except blocks in arxiv_search and arxiv_get to explicitly list the
expected exception types, use logger.exception(...) before re-raising unexpected
exceptions, and keep the existing _with_retry() retry behavior unchanged for the
lower-level call sites.

In `@nemo_skills/mcp/servers/wikipedia_tool.py`:
- Around line 45-52: Validate and clamp the num_results parameter before calling
wikipedia.search: in the function that takes num_results (the parameter name is
num_results), ensure it is at least 1 (e.g., if num_results < 1: num_results = 1
or raise ValueError) and then apply the existing cap of 10 when calling
wikipedia.search (use results=min(max(num_results, 1), 10)). This guarantees you
never pass 0 or negative values into wikipedia.search and preserves the current
upper bound behavior.
- Around line 64-65: The broad "except Exception" handlers that return
"Wikipedia search failed: {e}" should be replaced with specific external
exception catches (e.g., requests.exceptions.RequestException,
urllib3.exceptions.HTTPError, wikipedia.exceptions.HTTPTimeoutError or other
documented network/library exceptions) and re-raise any other unexpected
exceptions; locate the generic except blocks that come after the existing
DisambiguationError and PageError handlers in wikipedia_tool.py and change them
to catch only the documented network/HTTP/library errors (or remove them so
unexpected exceptions propagate), ensuring you either log/return a clear
network-error message for the expected external exceptions or re-raise for all
others.

In `@tests/test_mcp_clients.py`:
- Around line 1019-1105: Update the CI test selection to exclude live network
tests by default: change the pytest invocation used by the default CI job to use
the marker expression "not gpu and not live" (so tests like
test_arxiv_search_live, test_arxiv_get_live, test_wikipedia_search_live,
test_wikipedia_page_live and other functions annotated with `@pytest.mark.live` in
this file are skipped in default runs), or alternatively move these
`@pytest.mark.live` tests into a separate CI job that runs only when live tests
are desired; ensure the live-marked tests remain annotated with
`@pytest.mark.live` so they can still be run explicitly.

---

Nitpick comments:
In `@tests/test_mcp_clients.py`:
- Around line 1046-1054: Wrap the stdio tool lifecycle in a try/finally to
always call shutdown: for the ArxivSearchTool test (use the ArxivSearchTool()
constructor and its configure(), list_tools(), and shutdown() calls) enclose the
operations and assertions in a try block and call await tool.shutdown() in the
finally block so the subprocess cannot leak if an assertion fails; apply the
same try/finally pattern to the other similar tests referenced (the blocks
around lines that call configure()/list_tools()/shutdown() at the 1061-1073,
1116-1124, and 1131-1143 ranges).
- Around line 1105-1110: The test test_wikipedia_disambiguation currently only
checks isinstance(result, str) which lets generic failure messages slip; update
the assertion to verify disambiguation-specific content from the
wikipedia_page("Mercury") call (e.g., assert that result contains phrases like
"ambiguous", "Did you mean", "may refer to", or other site-specific
disambiguation markers), so replace or augment the isinstance check with a
content assertion that reliably indicates a disambiguation page was returned.
🪄 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: Pro Plus

Run ID: 47975a95-cad5-43c3-b468-6c2849fc730f

📥 Commits

Reviewing files that changed from the base of the PR and between 94478e5 and e69afa2.

📒 Files selected for processing (6)
  • .github/workflows/tests.yml
  • docs/agentic_inference/tool_calling.md
  • nemo_skills/mcp/servers/arxiv_tool.py
  • nemo_skills/mcp/servers/wikipedia_tool.py
  • tests/test_mcp_clients.py
  • tools/requirements.txt

Comment thread nemo_skills/mcp/servers/arxiv_tool.py Resolved
Comment thread nemo_skills/mcp/servers/arxiv_tool.py Resolved
Comment thread tests/test_mcp_clients.py Resolved
@tamohannes
tamohannes force-pushed the feat/wikipedia-mcp-tool branch from e69afa2 to 5f83ba7 Compare April 21, 2026 17:38

@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 (4)
nemo_skills/mcp/servers/wikipedia_tool.py (2)

50-52: ⚠️ Potential issue | 🟡 Minor

Guard num_results lower bound before wikipedia.search.

min(num_results, 10) still allows 0/negative values to pass through.

Suggested fix
 def wikipedia_search(
@@
 ) -> str:
@@
-    try:
-        titles = wikipedia.search(query, results=min(num_results, 10))
+    if num_results < 1:
+        raise ValueError("num_results must be a positive integer")
+
+    try:
+        titles = wikipedia.search(query, results=min(num_results, 10))
#!/bin/bash
set -euo pipefail
rg -n -C2 'num_results < 1|min\(num_results, 10\)' nemo_skills/mcp/servers/wikipedia_tool.py
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@nemo_skills/mcp/servers/wikipedia_tool.py` around lines 50 - 52, The call to
wikipedia.search uses min(num_results, 10) but doesn't prevent zero or negative
values; before calling wikipedia.search (inside the try block where titles =
wikipedia.search(query, results=min(num_results, 10)) is invoked) clamp
num_results to a valid positive range, e.g. set an effective_results = max(1,
min(num_results, 10)) and pass that to wikipedia.search so the search always
requests at least 1 result and at most 10.

64-65: ⚠️ Potential issue | 🟠 Major

Replace broad Exception catches in tool handlers.

Both handlers currently swallow all unexpected errors into user-facing strings, which can hide real regressions.

Suggested fix
-    except Exception as e:
-        return f"Wikipedia search failed: {e}"
+    # Let unexpected exceptions propagate so failures are visible.
@@
-    except Exception as e:
-        return f"Wikipedia lookup failed: {e}"
+    # Let unexpected exceptions propagate so failures are visible.
#!/bin/bash
set -euo pipefail
rg -n -C3 'except Exception as e' nemo_skills/mcp/servers/wikipedia_tool.py

As per coding guidelines: "Don't catch exceptions when they are not expected to be normally raised; let the code fail when something unexpected happens so users notice it instead of silently misbehaving."

Also applies to: 86-87

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

In `@nemo_skills/mcp/servers/wikipedia_tool.py` around lines 64 - 65, Replace the
broad except Exception handlers in the two Wikipedia tool handler try/except
blocks (the handlers that currently return strings like "Wikipedia search
failed: {e}") with targeted exception handling: catch only expected exceptions
such as network/HTTP errors (e.g., requests.exceptions.RequestException),
parsing/value errors (ValueError), or any specific library exceptions your
search/summary calls raise, return a clear user-facing message for those cases,
and for all other unexpected exceptions log the full error and re-raise them (do
not swallow). Update the two locations that currently use "except Exception as
e" so they either list explicit exception types or use "except Exception as e:
logger.exception(...); raise" for unexpected cases, ensuring unexpected errors
propagate while expected failures remain user-friendly.
nemo_skills/mcp/servers/arxiv_tool.py (2)

101-102: ⚠️ Potential issue | 🟡 Minor

Validate max_results lower bound before arXiv calls.

max_results is capped on the high side, but non-positive values still flow into arxiv.Client/arxiv.Search.

Suggested fix
 def arxiv_search(
@@
 ) -> str:
@@
-    if max_results > MAX_RESULTS:
+    if max_results < 1:
+        raise ValueError("max_results must be a positive integer")
+    if max_results > MAX_RESULTS:
         max_results = MAX_RESULTS
#!/bin/bash
set -euo pipefail
rg -n -C2 'max_results < 1|max_results > MAX_RESULTS' nemo_skills/mcp/servers/arxiv_tool.py
🤖 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 101 - 102, The code caps
max_results at MAX_RESULTS but doesn't prevent non-positive values; before
creating the arxiv.Client / arxiv.Search call (where max_results is used),
validate and handle the lower bound of max_results (the variable) by either
raising a clear ValueError when max_results < 1 or normalizing it to 1 (e.g., if
max_results < 1: max_results = 1) so that arxiv.Client/arxiv.Search never
receives a non-positive max_results; update the check near the existing
max_results > MAX_RESULTS logic to enforce this lower bound.

127-137: ⚠️ Potential issue | 🟠 Major

Don’t swallow unexpected exceptions in MCP entrypoints.

The broad catches in arxiv_search and arxiv_get convert all failures into strings, which masks programming errors and schema/API drift.

Suggested fix
-    try:
-        results = _with_retry(_fetch)
-        if not results:
-            return "No papers found for this query."
-        result_str = "\n---\n".join(results)
-        if len(_cache) < _CACHE_MAX_SIZE:
-            _cache[key] = result_str
-        return result_str
-    except Exception as e:
-        return f"ArXiv search failed: {e}"
+    results = _with_retry(_fetch)
+    if not results:
+        return "No papers found for this query."
+    result_str = "\n---\n".join(results)
+    if len(_cache) < _CACHE_MAX_SIZE:
+        _cache[key] = result_str
+    return result_str
@@
-    try:
-        paper = _with_retry(_fetch)
-        if paper is None:
-            return f"Paper {paper_id} not found on arXiv."
-        result_str = (
-            f"**{paper.title}**\n"
-            f"Authors: {', '.join(a.name for a in paper.authors)}\n"
-            f"Published: {paper.published.strftime('%Y-%m-%d')}\n"
-            f"Updated: {paper.updated.strftime('%Y-%m-%d')}\n"
-            f"Categories: {', '.join(paper.categories)}\n"
-            f"URL: {paper.entry_id}\n"
-            f"PDF: {paper.pdf_url}\n\n"
-            f"Abstract:\n{paper.summary}"
-        )
-        if len(_cache) < _CACHE_MAX_SIZE:
-            _cache[key] = result_str
-        return result_str
-    except Exception as e:
-        return f"ArXiv lookup failed: {e}"
+    paper = _with_retry(_fetch)
+    if paper is None:
+        return f"Paper {paper_id} not found on arXiv."
+    result_str = (
+        f"**{paper.title}**\n"
+        f"Authors: {', '.join(a.name for a in paper.authors)}\n"
+        f"Published: {paper.published.strftime('%Y-%m-%d')}\n"
+        f"Updated: {paper.updated.strftime('%Y-%m-%d')}\n"
+        f"Categories: {', '.join(paper.categories)}\n"
+        f"URL: {paper.entry_id}\n"
+        f"PDF: {paper.pdf_url}\n\n"
+        f"Abstract:\n{paper.summary}"
+    )
+    if len(_cache) < _CACHE_MAX_SIZE:
+        _cache[key] = result_str
+    return result_str
#!/bin/bash
set -euo pipefail
rg -n -C3 'except Exception as e' nemo_skills/mcp/servers/arxiv_tool.py

As per coding guidelines: "Don't catch exceptions when they are not expected to be normally raised; let the code fail when something unexpected happens so users notice it instead of silently misbehaving."

Also applies to: 155-173

🤖 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 127 - 137, The current
broad except in arxiv_search (and similarly in arxiv_get) swallows all
exceptions and returns a string; remove the blanket "except Exception as e" and
only handle expected, recoverable errors (e.g., network/timeout or known arXiv
API errors) or log them then re-raise; specifically update the try around
_with_retry(_fetch) / cache update (symbols: arxiv_search, arxiv_get,
_with_retry, _fetch, _cache, _CACHE_MAX_SIZE) so that unexpected exceptions
propagate (or are re-raised) instead of being converted to "ArXiv search failed:
...", and if you want to preserve user-friendly messages, catch only specific
exception types, convert those to messages, and let all other exceptions bubble
up.
🤖 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`:
- Around line 101-102: The code caps max_results at MAX_RESULTS but doesn't
prevent non-positive values; before creating the arxiv.Client / arxiv.Search
call (where max_results is used), validate and handle the lower bound of
max_results (the variable) by either raising a clear ValueError when max_results
< 1 or normalizing it to 1 (e.g., if max_results < 1: max_results = 1) so that
arxiv.Client/arxiv.Search never receives a non-positive max_results; update the
check near the existing max_results > MAX_RESULTS logic to enforce this lower
bound.
- Around line 127-137: The current broad except in arxiv_search (and similarly
in arxiv_get) swallows all exceptions and returns a string; remove the blanket
"except Exception as e" and only handle expected, recoverable errors (e.g.,
network/timeout or known arXiv API errors) or log them then re-raise;
specifically update the try around _with_retry(_fetch) / cache update (symbols:
arxiv_search, arxiv_get, _with_retry, _fetch, _cache, _CACHE_MAX_SIZE) so that
unexpected exceptions propagate (or are re-raised) instead of being converted to
"ArXiv search failed: ...", and if you want to preserve user-friendly messages,
catch only specific exception types, convert those to messages, and let all
other exceptions bubble up.

In `@nemo_skills/mcp/servers/wikipedia_tool.py`:
- Around line 50-52: The call to wikipedia.search uses min(num_results, 10) but
doesn't prevent zero or negative values; before calling wikipedia.search (inside
the try block where titles = wikipedia.search(query, results=min(num_results,
10)) is invoked) clamp num_results to a valid positive range, e.g. set an
effective_results = max(1, min(num_results, 10)) and pass that to
wikipedia.search so the search always requests at least 1 result and at most 10.
- Around line 64-65: Replace the broad except Exception handlers in the two
Wikipedia tool handler try/except blocks (the handlers that currently return
strings like "Wikipedia search failed: {e}") with targeted exception handling:
catch only expected exceptions such as network/HTTP errors (e.g.,
requests.exceptions.RequestException), parsing/value errors (ValueError), or any
specific library exceptions your search/summary calls raise, return a clear
user-facing message for those cases, and for all other unexpected exceptions log
the full error and re-raise them (do not swallow). Update the two locations that
currently use "except Exception as e" so they either list explicit exception
types or use "except Exception as e: logger.exception(...); raise" for
unexpected cases, ensuring unexpected errors propagate while expected failures
remain user-friendly.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 25275692-ee38-4d31-bb8d-60c43631c8f9

📥 Commits

Reviewing files that changed from the base of the PR and between e69afa2 and 5f83ba7.

📒 Files selected for processing (6)
  • .github/workflows/tests.yml
  • docs/agentic_inference/tool_calling.md
  • nemo_skills/mcp/servers/arxiv_tool.py
  • nemo_skills/mcp/servers/wikipedia_tool.py
  • tests/test_mcp_clients.py
  • tools/requirements.txt
✅ Files skipped from review due to trivial changes (3)
  • .github/workflows/tests.yml
  • tools/requirements.txt
  • docs/agentic_inference/tool_calling.md
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/test_mcp_clients.py

@tamohannes
tamohannes force-pushed the feat/wikipedia-mcp-tool branch from 5f83ba7 to d2fcae1 Compare April 21, 2026 17:51

@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: 1

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

108-108: ⚠️ Potential issue | 🟡 Minor

Reject invalid max_results instead of silently rewriting it.

max_results <= 0 is currently coerced to 1, which hides invalid caller input instead of failing fast.

💡 Suggested fix
-    max_results = max(1, min(max_results, MAX_RESULTS))
+    if max_results < 1:
+        raise ValueError("max_results must be >= 1")
+    if max_results > MAX_RESULTS:
+        max_results = MAX_RESULTS

As per coding guidelines: "Avoid cases where user-passed parameters are unused; code should fail if user specifies an unsupported argument or if a required argument is missing."

🤖 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 108, The current line that
coerces max_results hides invalid input; instead, validate and fail fast: in
arxiv_tool.py where max_results is handled (the variable max_results and
constant MAX_RESULTS), replace the coercion with explicit checks that raise a
ValueError if max_results <= 0 or if max_results > MAX_RESULTS, including a
clear error message like "max_results must be between 1 and {MAX_RESULTS}" so
callers get immediate feedback rather than silent rewriting.
🧹 Nitpick comments (1)
tests/test_mcp_clients.py (1)

1019-1104: Tighten live-test assertions to reduce flakiness.

Several checks are broad negatives (e.g., "Error" not in result, "failed" not in result.lower()), which are fragile. Prefer positive structural markers returned by these tools (e.g., URL:, Abstract:, heading format) so failures are more diagnostic.

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

In `@tests/test_mcp_clients.py` around lines 1019 - 1104, The live tests use weak
negative assertions that make flakes hard to diagnose; update
test_arxiv_search_live (calling arxiv_search) to assert for specific positive
markers like "URL:" or "Abstract:" or the expected arXiv item formatting instead
of just asserting "Error" not in result, change test_arxiv_get_live and
test_arxiv_get_invalid_id (calling arxiv_get) to assert presence of "Abstract"
and a valid arXiv URL or "https://arxiv.org/abs/" for success and that the
invalid id returns a clear "not found" message for failure, and replace the
broad checks in test_wikipedia_search_live and test_wikipedia_page (calling
wikipedia_search and wikipedia_page) with assertions for concrete structural
output such as a "URL:" or markdown heading pattern ("**" plus a link/title) and
expected page title text; edit only the assertions in these test functions to
check for these positive structural markers.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@nemo_skills/mcp/servers/arxiv_tool.py`:
- Around line 71-74: The _cache_put function evicts an entry whenever _cache has
reached _CACHE_MAX_SIZE even if the key being written already exists; change the
logic in _cache_put so it first checks whether key is already present in _cache
and only evicts (call _cache.popitem(last=False)) when inserting a new key and
len(_cache) >= _CACHE_MAX_SIZE; then assign/update _cache[key] = value and, if
using an ordered dict LRU, call _cache.move_to_end(key) to mark it as
most-recently-used.

---

Duplicate comments:
In `@nemo_skills/mcp/servers/arxiv_tool.py`:
- Line 108: The current line that coerces max_results hides invalid input;
instead, validate and fail fast: in arxiv_tool.py where max_results is handled
(the variable max_results and constant MAX_RESULTS), replace the coercion with
explicit checks that raise a ValueError if max_results <= 0 or if max_results >
MAX_RESULTS, including a clear error message like "max_results must be between 1
and {MAX_RESULTS}" so callers get immediate feedback rather than silent
rewriting.

---

Nitpick comments:
In `@tests/test_mcp_clients.py`:
- Around line 1019-1104: The live tests use weak negative assertions that make
flakes hard to diagnose; update test_arxiv_search_live (calling arxiv_search) to
assert for specific positive markers like "URL:" or "Abstract:" or the expected
arXiv item formatting instead of just asserting "Error" not in result, change
test_arxiv_get_live and test_arxiv_get_invalid_id (calling arxiv_get) to assert
presence of "Abstract" and a valid arXiv URL or "https://arxiv.org/abs/" for
success and that the invalid id returns a clear "not found" message for failure,
and replace the broad checks in test_wikipedia_search_live and
test_wikipedia_page (calling wikipedia_search and wikipedia_page) with
assertions for concrete structural output such as a "URL:" or markdown heading
pattern ("**" plus a link/title) and expected page title text; edit only the
assertions in these test functions to check for these positive structural
markers.
🪄 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: Pro Plus

Run ID: 11372698-7259-4153-b555-8bed11fc6eaa

📥 Commits

Reviewing files that changed from the base of the PR and between 5f83ba7 and d2fcae1.

📒 Files selected for processing (5)
  • docs/agentic_inference/tool_calling.md
  • nemo_skills/mcp/servers/arxiv_tool.py
  • nemo_skills/mcp/servers/wikipedia_tool.py
  • tests/test_mcp_clients.py
  • tools/requirements.txt
✅ Files skipped from review due to trivial changes (2)
  • docs/agentic_inference/tool_calling.md
  • tools/requirements.txt
🚧 Files skipped from review as they are similar to previous changes (1)
  • nemo_skills/mcp/servers/wikipedia_tool.py

Comment thread nemo_skills/mcp/servers/arxiv_tool.py Resolved
@tamohannes
tamohannes requested a review from jiacheng-xu April 21, 2026 17:56

@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.

🧹 Nitpick comments (1)
nemo_skills/mcp/servers/arxiv_tool.py (1)

129-134: Consider using ClassVar annotation for mutable class attributes.

Static analysis flags these as mutable default values for class attributes. While harmless here (these are internal constants for tag filtering), using ClassVar or moving to module-level constants would silence the warning.

+from typing import ClassVar
+
 class _ArxivHTMLTextParser(HTMLParser):
     """Tiny HTML-to-text extractor that preserves headings for section lookup."""

-    _SKIP_TAGS = {"script", "style", "noscript", "svg", "math"}
-    _BLOCK_TAGS = {"p", "div", "section", "article", "li", "br", "tr"}
-    _HEADING_TAGS = {"h1", "h2", "h3", "h4"}
+    _SKIP_TAGS: ClassVar[set[str]] = {"script", "style", "noscript", "svg", "math"}
+    _BLOCK_TAGS: ClassVar[set[str]] = {"p", "div", "section", "article", "li", "br", "tr"}
+    _HEADING_TAGS: ClassVar[set[str]] = {"h1", "h2", "h3", "h4"}
🤖 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 129 - 134, The
class-level sets _SKIP_TAGS, _BLOCK_TAGS, and _HEADING_TAGS on
_ArxivHTMLTextParser are flagged as mutable class attributes; annotate them as
typing.ClassVar[set[str]] (import ClassVar) or move them to module-level
constants to silence static-analysis warnings—update the declarations for
_SKIP_TAGS, _BLOCK_TAGS, and _HEADING_TAGS in class _ArxivHTMLTextParser
accordingly and ensure any type imports (ClassVar) are added to the file.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@nemo_skills/mcp/servers/arxiv_tool.py`:
- Around line 129-134: The class-level sets _SKIP_TAGS, _BLOCK_TAGS, and
_HEADING_TAGS on _ArxivHTMLTextParser are flagged as mutable class attributes;
annotate them as typing.ClassVar[set[str]] (import ClassVar) or move them to
module-level constants to silence static-analysis warnings—update the
declarations for _SKIP_TAGS, _BLOCK_TAGS, and _HEADING_TAGS in class
_ArxivHTMLTextParser accordingly and ensure any type imports (ClassVar) are
added to the file.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Enterprise

Run ID: ebb14fe7-6a72-47c7-bfff-dce2a5fdd64b

📥 Commits

Reviewing files that changed from the base of the PR and between d2fcae1 and 924c9e4.

📒 Files selected for processing (4)
  • nemo_skills/mcp/servers/arxiv_tool.py
  • nemo_skills/mcp/servers/wikipedia_tool.py
  • pyproject.toml
  • tests/test_mcp_clients.py
✅ Files skipped from review due to trivial changes (1)
  • pyproject.toml

@tamohannes
tamohannes force-pushed the feat/wikipedia-mcp-tool branch from 924c9e4 to cbb9730 Compare April 28, 2026 23:52
Use Wikimedia APIs directly with compact retrieval helpers, request throttling, and tests for the first-party MCP tool surface.

Signed-off-by: tamohannes <[email protected]>
Made-with: Cursor
@tamohannes
tamohannes force-pushed the feat/wikipedia-mcp-tool branch from cbb9730 to a71f35d Compare April 28, 2026 23:56

@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: 1

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

267-270: ⚠️ Potential issue | 🟠 Major

Replace blind except Exception handlers with expected exception types only.

These blocks swallow unexpected failures (bugs, schema drift, parse regressions) and make debugging much harder. Catch only expected transport/parsing failures (e.g., httpx/JSON/runtime retry errors from _http_get_json) and let everything else surface.

Suggested pattern
+WIKIPEDIA_EXPECTED_ERRORS = (
+    httpx.RequestError,
+    httpx.TimeoutException,
+    httpx.HTTPStatusError,
+    ValueError,   # JSON decode
+    RuntimeError, # raised in _http_get_json for retry exhaustion
+)

@@
-        except Exception as e:
+        except WIKIPEDIA_EXPECTED_ERRORS as e:
             return f"Wikipedia search failed: {e}"

Apply the same replacement to the other broad except Exception handlers in this file.

As per coding guidelines: "Don't catch exceptions when they are not expected to be normally raised; let the code fail when something unexpected happens so users notice it instead of silently misbehaving."

#!/bin/bash
set -euo pipefail
rg -n 'except Exception' nemo_skills/mcp/servers/wikipedia_tool.py

Also applies to: 326-329, 382-385, 429-430, 460-461, 502-503, 559-560, 590-591, 624-625

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

In `@nemo_skills/mcp/servers/wikipedia_tool.py` around lines 267 - 270, The blind
"except Exception" around the call to _http_get_json should be narrowed to only
the expected transport/parse errors (e.g., httpx.RequestError/HTTPError,
asyncio.TimeoutError, and json.JSONDecodeError) so unexpected bugs still
surface; update the try/except in the function that calls _http_get_json to
catch a tuple like (httpx.RequestError, asyncio.TimeoutError,
json.JSONDecodeError) and re-raise or let other exceptions propagate, import
those exception types at top of the module, and apply the same replacement to
the other broad "except Exception" blocks in wikipedia_tool.py (the handlers
around lines referenced in the review).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@nemo_skills/mcp/servers/wikipedia_tool.py`:
- Around line 241-252: The function currently advertises num_results as "1-10"
but silently clamps to 5 via n = max(1, min(int(num_results or 3), 5)); fix this
by making the API contract and runtime behavior consistent: change the Field
description for the num_results parameter to "Number of search results to return
(1-5)" and replace the silent clamp with an explicit validation that raises a
ValueError when num_results is outside 1–5 (then set n = int(num_results) after
validation); reference the num_results parameter and the local variable n (and
keep using _cache_key("search", query, n) afterwards).

---

Duplicate comments:
In `@nemo_skills/mcp/servers/wikipedia_tool.py`:
- Around line 267-270: The blind "except Exception" around the call to
_http_get_json should be narrowed to only the expected transport/parse errors
(e.g., httpx.RequestError/HTTPError, asyncio.TimeoutError, and
json.JSONDecodeError) so unexpected bugs still surface; update the try/except in
the function that calls _http_get_json to catch a tuple like
(httpx.RequestError, asyncio.TimeoutError, json.JSONDecodeError) and re-raise or
let other exceptions propagate, import those exception types at top of the
module, and apply the same replacement to the other broad "except Exception"
blocks in wikipedia_tool.py (the handlers around lines referenced in the
review).
🪄 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: 6322de12-baff-46fe-8818-905bbcf7ae68

📥 Commits

Reviewing files that changed from the base of the PR and between 924c9e4 and cbb9730.

📒 Files selected for processing (4)
  • docs/agentic_inference/tool_calling.md
  • nemo_skills/mcp/servers/wikipedia_tool.py
  • pyproject.toml
  • tests/test_mcp_clients.py
✅ Files skipped from review due to trivial changes (2)
  • pyproject.toml
  • docs/agentic_inference/tool_calling.md

@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.

Hi @tamohannes , Thank you for the contributions! I would encourage you to please switch to a tool path that avoids the MCP protocol (we have found it to cause real latency and stability issues during RL) in favor of a direct tool approach. The changes should be fairly minimal--please see the DirectPythonTool for an example.

@tamohannes

Copy link
Copy Markdown
Collaborator Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented May 1, 2026

Copy link
Copy Markdown
Contributor
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@tamohannes

Copy link
Copy Markdown
Collaborator Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented May 1, 2026

Copy link
Copy Markdown
Contributor
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@tamohannes

Copy link
Copy Markdown
Collaborator Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented May 1, 2026

Copy link
Copy Markdown
Contributor
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@tamohannes

Copy link
Copy Markdown
Collaborator Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented May 1, 2026

Copy link
Copy Markdown
Contributor
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@tamohannes

Copy link
Copy Markdown
Collaborator Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented May 1, 2026

Copy link
Copy Markdown
Contributor
✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@tamohannes

Copy link
Copy Markdown
Collaborator Author

Updated this PR to use the direct \ path instead of launching a stdio MCP server. The PR diff is now limited to the tool implementation, docs reference, and focused tests; workflow/pyproject changes were removed. @coderabbitai review

@coderabbitai

coderabbitai Bot commented May 1, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

@tamohannes Thanks for the update! I'll kick off a fresh review of the revised PR — focusing on the tool implementation, documentation reference, and tests.

[review]

@tamohannes

Copy link
Copy Markdown
Collaborator Author

Updated this PR to use the direct Tool path instead of launching a stdio MCP server. The PR diff is now limited to the tool implementation, docs reference, and focused tests; workflow/pyproject changes were removed. @coderabbitai review

@coderabbitai

coderabbitai Bot commented May 1, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

@tamohannes Thanks for the update! I'll kick off a fresh review of the revised PR — focusing on the direct Tool path implementation, documentation reference, and focused tests.

[review]

@tamohannes

Copy link
Copy Markdown
Collaborator Author

Updated to the direct Tool implementation path (no stdio MCP server/client). The final diff is scoped to the tool file, docs reference, and focused tests only. @coderabbitai review

@coderabbitai

coderabbitai Bot commented May 1, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

@tamohannes Thanks for the update! I'll kick off a fresh review of the revised PR — focusing on the direct Tool implementation, documentation reference, and focused tests only.

[review]

@tamohannes

Copy link
Copy Markdown
Collaborator Author

Closing in favor of #1419, reopened from an internal NVIDIA-NeMo/Skills branch so CI can access repository secrets.

@tamohannes tamohannes closed this May 2, 2026
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