Repository navigation
Add Wikipedia search MCP tool with tests and dependency - #1388
tamohannes wants to merge 11 commits into
Conversation
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughThis 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
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
Estimated code review effort🎯 4 (Complex) | ⏱️ ~50 minutes 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
Actionable comments posted: 5
🧹 Nitpick comments (2)
tests/test_mcp_clients.py (2)
1046-1054: Wrap stdio tool lifecycle intry/finallyto 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
📒 Files selected for processing (6)
.github/workflows/tests.ymldocs/agentic_inference/tool_calling.mdnemo_skills/mcp/servers/arxiv_tool.pynemo_skills/mcp/servers/wikipedia_tool.pytests/test_mcp_clients.pytools/requirements.txt
e69afa2 to
5f83ba7
Compare
There was a problem hiding this comment.
♻️ Duplicate comments (4)
nemo_skills/mcp/servers/wikipedia_tool.py (2)
50-52:⚠️ Potential issue | 🟡 MinorGuard
num_resultslower bound beforewikipedia.search.
min(num_results, 10)still allows0/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 | 🟠 MajorReplace broad
Exceptioncatches 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.pyAs 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 | 🟡 MinorValidate
max_resultslower bound before arXiv calls.
max_resultsis capped on the high side, but non-positive values still flow intoarxiv.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 | 🟠 MajorDon’t swallow unexpected exceptions in MCP entrypoints.
The broad catches in
arxiv_searchandarxiv_getconvert 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.pyAs 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
📒 Files selected for processing (6)
.github/workflows/tests.ymldocs/agentic_inference/tool_calling.mdnemo_skills/mcp/servers/arxiv_tool.pynemo_skills/mcp/servers/wikipedia_tool.pytests/test_mcp_clients.pytools/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
5f83ba7 to
d2fcae1
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (1)
nemo_skills/mcp/servers/arxiv_tool.py (1)
108-108:⚠️ Potential issue | 🟡 MinorReject invalid
max_resultsinstead of silently rewriting it.
max_results <= 0is currently coerced to1, 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_RESULTSAs 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
📒 Files selected for processing (5)
docs/agentic_inference/tool_calling.mdnemo_skills/mcp/servers/arxiv_tool.pynemo_skills/mcp/servers/wikipedia_tool.pytests/test_mcp_clients.pytools/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
There was a problem hiding this comment.
🧹 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
ClassVaror 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
📒 Files selected for processing (4)
nemo_skills/mcp/servers/arxiv_tool.pynemo_skills/mcp/servers/wikipedia_tool.pypyproject.tomltests/test_mcp_clients.py
✅ Files skipped from review due to trivial changes (1)
- pyproject.toml
924c9e4 to
cbb9730
Compare
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
cbb9730 to
a71f35d
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (1)
nemo_skills/mcp/servers/wikipedia_tool.py (1)
267-270:⚠️ Potential issue | 🟠 MajorReplace blind
except Exceptionhandlers 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 Exceptionhandlers 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.pyAlso 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
📒 Files selected for processing (4)
docs/agentic_inference/tool_calling.mdnemo_skills/mcp/servers/wikipedia_tool.pypyproject.tomltests/test_mcp_clients.py
✅ Files skipped from review due to trivial changes (2)
- pyproject.toml
- docs/agentic_inference/tool_calling.md
Signed-off-by: tamohannes <[email protected]>
…-tool Signed-off-by: tamohannes <[email protected]>
gwarmstrong
left a comment
There was a problem hiding this comment.
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.
Signed-off-by: tamohannes <[email protected]>
|
@coderabbitai review |
✅ Actions performedReview triggered.
|
Signed-off-by: tamohannes <[email protected]>
|
@coderabbitai review |
✅ Actions performedReview triggered.
|
Signed-off-by: tamohannes <[email protected]>
|
@coderabbitai review |
✅ Actions performedReview triggered.
|
Signed-off-by: tamohannes <[email protected]>
|
@coderabbitai review |
✅ Actions performedReview triggered.
|
Signed-off-by: tamohannes <[email protected]>
|
@coderabbitai review |
✅ Actions performedReview triggered.
|
Signed-off-by: tamohannes <[email protected]>
|
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 |
|
Tip For best results, initiate chat on the files or code changes.
[review] |
|
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 |
|
Tip For best results, initiate chat on the files or code changes.
[review] |
Signed-off-by: tamohannes <[email protected]>
|
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 |
|
Tip For best results, initiate chat on the files or code changes.
[review] |
…-tool Signed-off-by: tamohannes <[email protected]>
|
Closing in favor of #1419, reopened from an internal NVIDIA-NeMo/Skills branch so CI can access repository secrets. |
Summary
WikipediaSearchToolas a first-party MCP server for encyclopedic knowledge retrieval via the free Wikipedia API (no API key required)nemo_skills/mcp/servers/wikipedia_tool.pywithwikipedia-searchandwikipedia-pagetools, disambiguation handling, and summary truncationwikipedia>=1.4.0dependency intools/requirements.txtlist_tools,hide_argsfiltering), and@pytest.mark.liveAPI tests (search, page, disambiguation)WikipediaSearchToolto the built-in tools reference indocs/agentic_inference/tool_calling.mdUsage
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=8192Test 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)pytest tests/test_mcp_clients.py -m "not live and not gpu"— all pass)Summary by CodeRabbit
New Features
Documentation