|
| 1 | +# Copyright 2025 Miromind.ai |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +""" |
| 16 | +adapted from |
| 17 | +https://github.com/MiroMindAI/MiroRL/blob/5073693549ffe05a157a1886e87650ef3be6606e/mirorl/tools/serper_search.py#L1 |
| 18 | +""" |
| 19 | + |
| 20 | +import os |
| 21 | +from typing import Any, Dict |
| 22 | + |
| 23 | +import requests |
| 24 | +from mcp.server.fastmcp import FastMCP |
| 25 | +from tenacity import ( |
| 26 | + retry, |
| 27 | + retry_if_exception_type, |
| 28 | + stop_after_attempt, |
| 29 | + wait_exponential, |
| 30 | +) |
| 31 | + |
| 32 | +from .utils.url_unquote import decode_http_urls_in_dict |
| 33 | + |
| 34 | +SERPER_BASE_URL = os.getenv("SERPER_BASE_URL", "https://google.serper.dev") |
| 35 | +SERPER_API_KEY = os.getenv("SERPER_API_KEY", "") |
| 36 | + |
| 37 | + |
| 38 | +# Initialize FastMCP server |
| 39 | +mcp = FastMCP("serper-mcp-server") |
| 40 | + |
| 41 | + |
| 42 | +@retry( |
| 43 | + stop=stop_after_attempt(3), |
| 44 | + wait=wait_exponential(multiplier=1, min=4, max=10), |
| 45 | + retry=retry_if_exception_type( |
| 46 | + (requests.ConnectionError, requests.Timeout, requests.HTTPError) |
| 47 | + ), |
| 48 | +) |
| 49 | +def make_serper_request( |
| 50 | + payload: Dict[str, Any], headers: Dict[str, str] |
| 51 | +) -> requests.Response: |
| 52 | + """Make HTTP request to Serper API with retry logic.""" |
| 53 | + response = requests.post(f"{SERPER_BASE_URL}/search", json=payload, headers=headers) |
| 54 | + response.raise_for_status() |
| 55 | + return response |
| 56 | + |
| 57 | + |
| 58 | +def _is_huggingface_dataset_or_space_url(url): |
| 59 | + """ |
| 60 | + Check if the URL is a HuggingFace dataset or space URL. |
| 61 | + :param url: The URL to check |
| 62 | + :return: True if it's a HuggingFace dataset or space URL, False otherwise |
| 63 | + """ |
| 64 | + if not url: |
| 65 | + return False |
| 66 | + return "huggingface.co/datasets" in url or "huggingface.co/spaces" in url |
| 67 | + |
| 68 | + |
| 69 | +@mcp.tool() |
| 70 | +def google_search( |
| 71 | + q: str, |
| 72 | + gl: str = "us", |
| 73 | + hl: str = "en", |
| 74 | + location: str | None = None, |
| 75 | + num: int | None = None, |
| 76 | + tbs: str | None = None, |
| 77 | + page: int | None = None, |
| 78 | + autocorrect: bool | None = None, |
| 79 | +) -> Dict[str, Any]: |
| 80 | + """ |
| 81 | + Tool to perform web searches via Serper API and retrieve rich results. |
| 82 | +
|
| 83 | + It is able to retrieve organic search results, people also ask, |
| 84 | + related searches, and knowledge graph. |
| 85 | +
|
| 86 | + Args: |
| 87 | + q: Search query string |
| 88 | + gl: Optional region code for search results in ISO 3166-1 alpha-2 format (e.g., 'us') |
| 89 | + hl: Optional language code for search results in ISO 639-1 format (e.g., 'en') |
| 90 | + location: Optional location for search results (e.g., 'SoHo, New York, United States', 'California, United States') |
| 91 | + num: Number of results to return (default: 10) |
| 92 | + tbs: Time-based search filter ('qdr:h' for past hour, 'qdr:d' for past day, 'qdr:w' for past week, |
| 93 | + 'qdr:m' for past month, 'qdr:y' for past year) |
| 94 | + page: Page number of results to return (default: 1) |
| 95 | + autocorrect: Whether to autocorrect spelling in query |
| 96 | +
|
| 97 | + Returns: |
| 98 | + Dictionary containing search results and metadata. |
| 99 | + """ |
| 100 | + # Check for API key |
| 101 | + if not SERPER_API_KEY: |
| 102 | + return { |
| 103 | + "success": False, |
| 104 | + "error": "SERPER_API_KEY environment variable not set", |
| 105 | + "results": [], |
| 106 | + } |
| 107 | + |
| 108 | + # Validate required parameter |
| 109 | + if not q or not q.strip(): |
| 110 | + return { |
| 111 | + "success": False, |
| 112 | + "error": "Search query 'q' is required and cannot be empty", |
| 113 | + "results": [], |
| 114 | + } |
| 115 | + |
| 116 | + try: |
| 117 | + # Build payload with all supported parameters |
| 118 | + payload: dict[str, Any] = { |
| 119 | + "q": q.strip(), |
| 120 | + "gl": gl, |
| 121 | + "hl": hl, |
| 122 | + } |
| 123 | + |
| 124 | + # Add optional parameters if provided |
| 125 | + if location: |
| 126 | + payload["location"] = location |
| 127 | + if num is not None: |
| 128 | + payload["num"] = num |
| 129 | + else: |
| 130 | + payload["num"] = 10 # Default |
| 131 | + if tbs: |
| 132 | + payload["tbs"] = tbs |
| 133 | + if page is not None: |
| 134 | + payload["page"] = page |
| 135 | + if autocorrect is not None: |
| 136 | + payload["autocorrect"] = autocorrect |
| 137 | + |
| 138 | + # Set up headers |
| 139 | + headers = {"X-API-KEY": SERPER_API_KEY, "Content-Type": "application/json"} |
| 140 | + |
| 141 | + # Make the API request |
| 142 | + response = make_serper_request(payload, headers) |
| 143 | + data = response.json() |
| 144 | + |
| 145 | + # filter out HuggingFace dataset or space urls |
| 146 | + organic_results = [] |
| 147 | + if "organic" in data: |
| 148 | + for item in data["organic"]: |
| 149 | + if _is_huggingface_dataset_or_space_url(item.get("link", "")): |
| 150 | + continue |
| 151 | + organic_results.append(item) |
| 152 | + |
| 153 | + # Keep all original fields, but overwrite "organic" |
| 154 | + response_data = dict(data) |
| 155 | + response_data["organic"] = organic_results |
| 156 | + response_data = decode_http_urls_in_dict(response_data) |
| 157 | + |
| 158 | + return response_data |
| 159 | + |
| 160 | + except Exception as e: |
| 161 | + return {"success": False, "error": f"Unexpected error: {str(e)}", "results": []} |
| 162 | + |
| 163 | + |
| 164 | +if __name__ == "__main__": |
| 165 | + mcp.run() |
0 commit comments