Skip to content
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
103 changes: 103 additions & 0 deletions nemo_skills/mcp/servers/tavily_search_tool.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
# Copyright (c) 2025, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import argparse
import logging
import os
from dataclasses import dataclass
from typing import Annotated

import httpx
from mcp.server.fastmcp import FastMCP
from pydantic import Field

from nemo_skills.mcp.tool_providers import MCPClientTool

logger = logging.getLogger(__name__)


@dataclass
class ExecutionResult:
error: str | None = None
result: str | None = None


mcp = FastMCP(name="tavily")

# Populated from CLI args in main()
TAVILY_API_KEY: str | None = None


## See docs https://docs.tavily.com/documentation/api-reference/endpoint/search
## There is also a hosted MCP that can be used instead of this tool: https://github.com/tavily-ai/tavily-mcp?tab=readme-ov-file#remote-mcp-server
@mcp.tool(name="tavily-search")
async def answer(
query: Annotated[str, Field(description="Search query.")],
) -> ExecutionResult:
"""Get a summary of search results from the web using Tavily."""

api_url = "https://api.tavily.com/search"

headers = {
"Authorization": f"Bearer {TAVILY_API_KEY}",
"Content-Type": "application/json",
}

payload = {
"query": query,
# "auto_parameters": False,
"search_depth": "basic",
"include_answer": "basic", ## or advanced.
}

async with httpx.AsyncClient() as client:
response = await client.post(api_url, headers=headers, json=payload)
if response.status_code != 200:
return {"error": response.json()["error"]}

result = response.json()["answer"]
Comment on lines +70 to +75

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.

⚠️ Potential issue | 🟡 Minor

Add error handling for JSON parsing and missing keys.

If the Tavily API returns a non-JSON error response or an unexpected JSON structure, the current code will raise unhandled exceptions (JSONDecodeError or KeyError).

Consider wrapping the response parsing in try-except:

     async with httpx.AsyncClient(timeout=30.0) as client:
         response = await client.post(api_url, headers=headers, json=payload)
+        try:
+            data = response.json()
+        except Exception as e:
+            return ExecutionResult(error=f"Failed to parse response: {e}")
+        
         if response.status_code != 200:
-            error_detail = response.json().get("error", response.text)
+            error_detail = data.get("error", response.text)
             return ExecutionResult(error=str(error_detail))
 
-        result = response.json()["answer"]
+        result = data.get("answer")
+        if result is None:
+            return ExecutionResult(error="No answer in response")
 
     return ExecutionResult(result=result)

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In nemo_skills/mcp/servers/tavily_search_tool.py around lines 64 to 69, the code
assumes response.json() succeeds and the "error" or "answer" keys exist; wrap
the JSON parsing and key access in a try/except block that catches
JSONDecodeError and KeyError (or use response.is_json/content-type check),
attempt to parse JSON safely for both non-200 and 200 cases, and return a clear
error dict when parsing fails or keys are missing (e.g., include response.text
and status_code), otherwise extract and return result = parsed.get("answer")
after validating it's present.


return {"result": result}

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.

⚠️ Potential issue | 🟠 Major

Return type mismatch: function returns dicts but declares ExecutionResult.

The function signature declares ExecutionResult as the return type, but lines 67 and 71 return plain dictionaries. This creates a type inconsistency.

Apply this diff to return proper ExecutionResult instances:

-    async with httpx.AsyncClient() as client:
-        response = await client.post(api_url, headers=headers, json=payload)
+    async with httpx.AsyncClient(timeout=30.0) as client:
+        response = await client.post(api_url, headers=headers, json=payload)
         if response.status_code != 200:
-            return {"error": response.json()["error"]}
+            error_detail = response.json().get("error", response.text)
+            return ExecutionResult(error=str(error_detail))
 
-    result = response.json()["answer"]
+        result = response.json()["answer"]
 
-    return {"result": result}
+    return ExecutionResult(result=result)

This also:

  • Adds a timeout to prevent indefinite hangs.
  • Uses .get() with fallback for safer error extraction.
  • Moves response.json() inside the async with block for consistency.
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
async def answer(
query: Annotated[str, Field(description="Search query.")],
) -> ExecutionResult:
"""Get a summary of search results from the web using Tavily."""
api_url = "https://api.tavily.com/search"
headers = {
"Authorization": f"Bearer {TAVILY_API_KEY}",
"Content-Type": "application/json",
}
payload = {
"query": query,
# "auto_parameters": False,
"search_depth": "basic",
"include_answer": "basic", ## or advanced.
}
async with httpx.AsyncClient() as client:
response = await client.post(api_url, headers=headers, json=payload)
if response.status_code != 200:
return {"error": response.json()["error"]}
result = response.json()["answer"]
return {"result": result}
async def answer(
query: Annotated[str, Field(description="Search query.")],
) -> ExecutionResult:
"""Get a summary of search results from the web using Tavily."""
api_url = "https://api.tavily.com/search"
headers = {
"Authorization": f"Bearer {TAVILY_API_KEY}",
"Content-Type": "application/json",
}
payload = {
"query": query,
# "auto_parameters": False,
"search_depth": "basic",
"include_answer": "basic", ## or advanced.
}
async with httpx.AsyncClient(timeout=30.0) as client:
response = await client.post(api_url, headers=headers, json=payload)
if response.status_code != 200:
error_detail = response.json().get("error", response.text)
return ExecutionResult(error=str(error_detail))
result = response.json()["answer"]
return ExecutionResult(result=result)



class TavilySearchTool(MCPClientTool):
def __init__(self) -> None:
super().__init__()
self.apply_config_updates(
{
"client": "nemo_skills.mcp.clients.MCPStdioClient",
"client_params": {
"command": "python",
"args": ["-m", "nemo_skills.mcp.servers.tavily_search_tool"],
},
}
)


def main():
parser = argparse.ArgumentParser(description="MCP server for Tavily web search tool")
parser.add_argument("--api-key", type=str, default=os.getenv("TAVILY_API_KEY"), help="Tavily API Key")
args = parser.parse_args()

if not args.api_key:
raise ValueError("Missing Tavily API key.")

global TAVILY_API_KEY
TAVILY_API_KEY = args.api_key

mcp.run(transport="stdio")


if __name__ == "__main__":
main()
Loading