Repository navigation
Add Wikipedia search MCP tool with tests and dependency - #1419
Conversation
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
Signed-off-by: tamohannes <[email protected]>
…-tool Signed-off-by: tamohannes <[email protected]>
Signed-off-by: tamohannes <[email protected]>
Signed-off-by: tamohannes <[email protected]>
Signed-off-by: tamohannes <[email protected]>
Signed-off-by: tamohannes <[email protected]>
Signed-off-by: tamohannes <[email protected]>
Signed-off-by: tamohannes <[email protected]>
Signed-off-by: tamohannes <[email protected]>
…-tool Signed-off-by: tamohannes <[email protected]>
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Enterprise Run ID: 📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
📝 WalkthroughWalkthroughAdds an async MCP Wikipedia tool that queries the MediaWiki Action API with retry/backoff, cross-process rate limiting, bounded in-memory caching, HTML/text helpers, seven retrieval helpers, an MCP Tool provider for config/dispatch, tests, and a docs entry. (Documentation-only addition: tool listed in built-ins.) ChangesWikipedia Tool Integration
Sequence DiagramsequenceDiagram
participant Agent as Agent/Client
participant Tool as WikipediaSearchTool
participant Cache as In-Memory Cache
participant RateLimit as File Lock Rate Limiter
participant API as MediaWiki API
Agent->>Tool: execute(tool_name, arguments)
Tool->>Cache: check cache (SHA256 key)
alt Cache Hit
Cache-->>Tool: return cached payload
Tool-->>Agent: return result
else Cache Miss
Tool->>RateLimit: acquire lock / enforce pacing
RateLimit-->>Tool: lock acquired or fallback applied
Tool->>API: _http_get_json(...) (Action API)
API-->>Tool: JSON / HTML response
Tool->>Tool: strip HTML, truncate, format
Tool->>Cache: store formatted result
Tool-->>Agent: return result
end
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 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 docstrings
🧪 Generate unit tests (beta)
Review rate limit: 8/10 reviews remaining, refill in 6 minutes and 5 seconds. Comment |
There was a problem hiding this comment.
Actionable comments posted: 5
🤖 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 374-375: Remove the duplicate Wikipedia tool bullet so the
built-in tools list only contains one canonical entry for
nemo_skills.mcp.servers.wikipedia_tool.WikipediaSearchTool; edit the two
identical lines referencing WikipediaSearchTool and delete one of them (keep the
remaining bullet exactly as-is) to avoid the duplicated listing.
In `@nemo_skills/mcp/servers/wikipedia_tool.py`:
- Around line 698-704: The tool schema/dispatcher mismatch: update either the
tool schemas or the dispatcher calls so signatures match the implementation —
remove the invalid max_chars arg from calls to wikipedia_page(...) and
wikipedia_section(...) (or add max_chars parameter to those functions if
intended), and fix the wikipedia-query-summary tool schema to expose both
"title" and "query" (or change the dispatcher to only call
wikipedia_query_summary(title=<derived>, query=<provided>) to match the existing
wikipedia_query_summary(...) signature). Locate and fix the mismatches around
the dispatcher invocations that call wikipedia_page, wikipedia_section, and
wikipedia_query_summary and the tool definition named "wikipedia-query-summary"
so the parameters passed align with their function signatures.
- Around line 271-274: The try/except blocks around the HTTP calls (e.g., the
call to _http_get_json with client, ACTION_BASE, params) should stop catching
broad Exception; replace them with specific expected network/parse errors such
as aiohttp.ClientError, asyncio.TimeoutError, and json.JSONDecodeError (or
ValueError if _http_get_json raises that) so programming errors still surface;
update each similar block (the ones at the other listed spots that also call
_http_get_json or parse responses) to catch only those specific exceptions and
return the same Wikipedia search failed message with the caught exception info.
- Around line 643-646: The configure method currently accepts any keys in
overrides and silently stores unknown ones in self._config; modify
configure(self, overrides, context) to validate incoming override keys against
the allowed keys (e.g., set(self._config.keys()) or an explicit ALLOWED_KEYS for
this class), compute unknown = set(overrides) - allowed, and if unknown is
non-empty raise a ValueError listing the invalid keys; only call
self._config.update(overrides) after validation so typos or unsupported override
keys are rejected rather than silently accepted.
In `@tests/test_mcp_clients.py`:
- Around line 1017-1045: Add smoke tests that call WikipediaSearchTool.execute
for the non-search routes to catch signature/dispatcher mismatches: create async
pytest cases (e.g., test_wikipedia_page_execute_contract,
test_wikipedia_section_execute_contract,
test_wikipedia_query_summary_execute_contract) that instantiate
WikipediaSearchTool(), call configure(), then await
tool.execute("wikipedia-page", {appropriate minimal args}), await
tool.execute("wikipedia-section", {...}), and await
tool.execute("wikipedia-query-summary", {...}) using the input shapes listed in
list_tools(); assert the calls return a validation-style error or successful
result (i.e., do not raise a TypeError/dispatcher mismatch). Also add assertions
that list_tools() entries for "wikipedia-page", "wikipedia-section", and
"wikipedia-query-summary" include the expected input_schema properties so the
execute payload matches the declared signatures.
🪄 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: 991a8e3d-5ef7-4bd4-ba10-a364e13a1c58
📒 Files selected for processing (3)
docs/agentic_inference/tool_calling.mdnemo_skills/mcp/servers/wikipedia_tool.pytests/test_mcp_clients.py
Signed-off-by: tamohannes <[email protected]>
4fa6576 to
7f77ce3
Compare
There was a problem hiding this comment.
🧹 Nitpick comments (1)
nemo_skills/mcp/servers/wikipedia_tool.py (1)
636-636: 💤 Low valueConfig default for
max_charsexceeds the validated/clamped range.The default
max_charsin_configisEXTRACT_LIMIT = 2500(line 636), butconfigure()clamps override values to[200, 1500](line 658), and the actual tool functions (wikipedia_summary,wikipedia_query_summary) also clamp tomax(200, min(..., 1500)). This creates inconsistency—the default cannot be re-set viaconfigure().Consider aligning the default to a value within the valid range (e.g., 700 or 1500) to avoid confusion.
Suggested fix
def __init__(self) -> None: self._config: dict[str, Any] = { "num_results": 3, - "max_chars": EXTRACT_LIMIT, + "max_chars": 700, # Default within valid range [200, 1500] "max_sections": 40, "count": 5, }Also applies to: 658-658
🤖 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` at line 636, The default EXTRACT_LIMIT (used in _config "max_chars") is set to 2500 which exceeds the clamp range enforced in configure() and in wikipedia_summary / wikipedia_query_summary (they clamp to 200..1500); change the default to a value within that range (e.g., 1500 or 700) so the default aligns with the validated bounds—update the EXTRACT_LIMIT constant and any places referencing it (the _config dictionary, and ensure configure(), wikipedia_summary, and wikipedia_query_summary continue to clamp consistently).
🤖 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/wikipedia_tool.py`:
- Line 636: The default EXTRACT_LIMIT (used in _config "max_chars") is set to
2500 which exceeds the clamp range enforced in configure() and in
wikipedia_summary / wikipedia_query_summary (they clamp to 200..1500); change
the default to a value within that range (e.g., 1500 or 700) so the default
aligns with the validated bounds—update the EXTRACT_LIMIT constant and any
places referencing it (the _config dictionary, and ensure configure(),
wikipedia_summary, and wikipedia_query_summary continue to clamp consistently).
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Enterprise
Run ID: 24f83ac5-24ca-49ce-aaab-02beae965c73
📒 Files selected for processing (3)
docs/agentic_inference/tool_calling.mdnemo_skills/mcp/servers/wikipedia_tool.pytests/test_mcp_clients.py
✅ Files skipped from review due to trivial changes (1)
- docs/agentic_inference/tool_calling.md
🚧 Files skipped from review as they are similar to previous changes (1)
- tests/test_mcp_clients.py
Signed-off-by: Hovhannes Tamoyan <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 3
🤖 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 149-151: The code currently uses patterns like (data.get("query")
or {}).get("pages") or [] which silently masks malformed MediaWiki responses;
replace each occurrence (e.g., the assignments to pages at lines shown and the
similar patterns around lines 277-279, 335-337, 389-391, 433-435, 560-562) with
direct key access (e.g., data["query"]["pages"]) and either let the KeyError
propagate or raise a clear exception (ValueError) with a descriptive message
such as "Malformed MediaWiki payload: missing 'query.pages'" so failures are
loud and traceable; update the surrounding code that assumes a list to handle
the explicit exception instead of treating empty fallbacks as “not found.”
- Around line 634-658: The default_config sets "max_chars" to EXTRACT_LIMIT
(2500) but wikipedia_summary() and wikipedia_query_summary() cap at 1500, so
user defaults/overrides above 1500 are silently ignored; update default_config()
and configure() to use the same effective limit as the summary functions (set
default "max_chars" to 1500 or to the shared SUMMARY_LIMIT constant) and adjust
the configure validation in configure() to reject overrides >1500 (or clamp
consistently using the shared constant), ensuring consistency across
default_config(), configure(), wikipedia_summary(), and
wikipedia_query_summary() so user-provided values are either honored or rejected
rather than silently ignored.
- Around line 615-623: _suggest_titles() is making a raw httpx request and
bypassing the shared HTTP helper and its rate-limit/retry logic; change it to
call the shared helper (use self._http_get_json or the class's equivalent)
instead of creating AsyncClient directly, pass ACTION_BASE and params=params and
timeout if the helper accepts it, then process the returned JSON the same way
(return data[1] if it's a list with length > 1 else []), and remove the manual
try/except EXPECTED_HTTP_ERRORS block so the helper's retry/backoff and rate
limiting apply to typo/disambiguation lookups.
🪄 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: 6e9ecdc9-230a-40f4-b28f-f8c976723534
📒 Files selected for processing (3)
docs/agentic_inference/tool_calling.mdnemo_skills/mcp/servers/wikipedia_tool.pytests/test_mcp_clients.py
✅ Files skipped from review due to trivial changes (2)
- docs/agentic_inference/tool_calling.md
- tests/test_mcp_clients.py
| pages = (data.get("query") or {}).get("pages") or [] | ||
| if not pages: | ||
| return None, None, f"Wikipedia page {t!r} not found." |
There was a problem hiding this comment.
Fail loudly on malformed MediaWiki payloads.
These .get(... ) or [] fallbacks turn missing required keys like query/pages/search/parse/sections into normal "not found" or "no results" responses. That silently corrupts tool output when the upstream payload is malformed or changes shape.
As per coding guidelines, "Don't use .get() for accessing dictionary keys if the code expects them to be present; use direct access data[key_name] to fail with a clear error instead of silently corrupting data".
Also applies to: 277-279, 335-337, 389-391, 433-435, 560-562
🤖 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 149 - 151, The code
currently uses patterns like (data.get("query") or {}).get("pages") or [] which
silently masks malformed MediaWiki responses; replace each occurrence (e.g., the
assignments to pages at lines shown and the similar patterns around lines
277-279, 335-337, 389-391, 433-435, 560-562) with direct key access (e.g.,
data["query"]["pages"]) and either let the KeyError propagate or raise a clear
exception (ValueError) with a descriptive message such as "Malformed MediaWiki
payload: missing 'query.pages'" so failures are loud and traceable; update the
surrounding code that assumes a list to handle the explicit exception instead of
treating empty fallbacks as “not found.”
| headers = {"User-Agent": USER_AGENT, "Accept": "application/json"} | ||
| try: | ||
| async with httpx.AsyncClient(headers=headers) as client: | ||
| r = await client.get(ACTION_BASE, params=params, timeout=HTTP_TIMEOUT) | ||
| if r.status_code != 200: | ||
| return [] | ||
| data = r.json() | ||
| return data[1] if isinstance(data, list) and len(data) > 1 else [] | ||
| except EXPECTED_HTTP_ERRORS: |
There was a problem hiding this comment.
Route _suggest_titles() through the shared HTTP helper.
This helper currently bypasses _http_get_json(), so typo/disambiguation lookups skip the shared _rate_limit() and retry/backoff path. That leaves one extra unthrottled Wikimedia request on the missing-page path and makes suggestions disappear under 429/5xx pressure.
As per coding guidelines, "Keep code simple and elegant; reuse/extend existing functionality when possible, minimize conditional checks, use self-explanatory code over comments, avoid complicated type interfaces with unions, and keep naming consistent with existing conventions".
🤖 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 615 - 623,
_suggest_titles() is making a raw httpx request and bypassing the shared HTTP
helper and its rate-limit/retry logic; change it to call the shared helper (use
self._http_get_json or the class's equivalent) instead of creating AsyncClient
directly, pass ACTION_BASE and params=params and timeout if the helper accepts
it, then process the returned JSON the same way (return data[1] if it's a list
with length > 1 else []), and remove the manual try/except EXPECTED_HTTP_ERRORS
block so the helper's retry/backoff and rate limiting apply to
typo/disambiguation lookups.
| self._config: dict[str, Any] = { | ||
| "num_results": 3, | ||
| "max_chars": EXTRACT_LIMIT, | ||
| "max_sections": 40, | ||
| "count": 5, | ||
| } | ||
|
|
||
| def default_config(self) -> dict[str, Any]: | ||
| return dict(self._config) | ||
|
|
||
| def configure(self, overrides: dict[str, Any] | None = None, context: dict[str, Any] | None = None) -> None: | ||
| if not overrides: | ||
| return | ||
|
|
||
| unknown = set(overrides) - set(self._config) | ||
| if unknown: | ||
| raise ValueError(f"Unknown WikipediaSearchTool override(s): {sorted(unknown)}") | ||
|
|
||
| if "num_results" in overrides: | ||
| num_results = int(overrides["num_results"]) | ||
| if num_results < 1 or num_results > 5: | ||
| raise ValueError("num_results must be between 1 and 5.") | ||
| self._config["num_results"] = num_results | ||
| if "max_chars" in overrides: | ||
| self._config["max_chars"] = max(200, min(int(overrides["max_chars"]), 1500)) |
There was a problem hiding this comment.
Align max_chars config with the summary/query-summary limits.
default_config() seeds max_chars with 2500, but wikipedia_summary() and wikipedia_query_summary() cap it at 1500. Today the default path, and any higher override, is silently ignored for those tools instead of being honored or rejected.
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. Use dataclass or **kwargs syntax to handle this automatically".
🤖 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 634 - 658, The
default_config sets "max_chars" to EXTRACT_LIMIT (2500) but wikipedia_summary()
and wikipedia_query_summary() cap at 1500, so user defaults/overrides above 1500
are silently ignored; update default_config() and configure() to use the same
effective limit as the summary functions (set default "max_chars" to 1500 or to
the shared SUMMARY_LIMIT constant) and adjust the configure validation in
configure() to reject overrides >1500 (or clamp consistently using the shared
constant), ensuring consistency across default_config(), configure(),
wikipedia_summary(), and wikipedia_query_summary() so user-provided values are
either honored or rejected rather than silently ignored.
Signed-off-by: tamohannes <[email protected]>
## Summary - Add a NeMo-Gym `ns_tools` config that exposes `WikipediaSearchTool` 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#1419. Replaces fork-origin PR #1217 so CI can run with full repository secrets. ## Test plan - `PYTHONPATH=. python -m pytest resources_servers/ns_tools/tests/test_wikipedia_mcp_config.py -q --tb=short` --------- Signed-off-by: tamohannes <[email protected]> Co-authored-by: Christian Munley <[email protected]>
## Summary - Add a NeMo-Gym `ns_tools` config that exposes `WikipediaSearchTool` 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#1419. Replaces fork-origin PR #1217 so CI can run with full repository secrets. ## Test plan - `PYTHONPATH=. python -m pytest resources_servers/ns_tools/tests/test_wikipedia_mcp_config.py -q --tb=short` --------- Signed-off-by: tamohannes <[email protected]> Co-authored-by: Christian Munley <[email protected]> Signed-off-by: Rita Fernandes Neves <[email protected]>
Summary
NVIDIA-NeMo/Skillsbranch so CI can access repository secrets.WikipediaSearchToolas a first-party MCP server for encyclopedic retrieval via the free Wikipedia API.Test plan
pytest tests/test_mcp_clients.py::TestWikipediaTool -m "not live"pytest tests/test_mcp_clients.py::TestWikipediaTool -m livepytest tests/test_mcp_clients.py -m "not live and not gpu"Summary by CodeRabbit
New Features
Documentation
Tests