Skip to main content
Glama

search_wikipedia

Retrieve relevant Wikipedia articles by submitting a search query, enabling quick access to information and summaries for enhanced context.

Instructions

Search Wikipedia for articles matching a query.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
limitNo
queryYes

Implementation Reference

  • The primary handler function for the 'search_wikipedia' tool. It performs input validation on query and limit, delegates the search to WikipediaClient.search(), formats the response with status, count, and language info, and handles edge cases like empty queries or no results. Registered via the @server.tool() decorator.
    @server.tool() def search_wikipedia(query: str, limit: int = 10) -> Dict[str, Any]: """Search Wikipedia for articles matching a query.""" logger.info("Tool: Searching Wikipedia for '%s' (limit=%d)", query, limit) if not query or not query.strip(): logger.warning("Search tool called with empty query") return { "query": query, "results": [], "status": "error", "message": "Empty or invalid search query provided", } validated_limit = limit if limit <= 0: validated_limit = 10 logger.warning("Invalid limit %d; using default %d", limit, validated_limit) elif limit > 500: validated_limit = 500 logger.warning("Limit %d capped to %d", limit, validated_limit) results = wikipedia_client.search(query, limit=validated_limit) status = "success" if results else "no_results" response: Dict[str, Any] = { "query": query, "results": results, "status": status, "count": len(results), "language": wikipedia_client.base_language, } if not results: response["message"] = ( "No search results found. This could indicate connectivity issues, " "API errors, or simply no matching articles." ) return response
  • Supporting helper method in WikipediaClient class that implements the core Wikipedia search logic. Makes HTTP request to Wikipedia's query API (opensearch), handles parameters like language variant, processes JSON response into structured results with title, snippet, pageid, etc., and includes comprehensive error handling for timeouts, HTTP errors, and API issues.
    def search(self, query: str, limit: int = 10) -> List[Dict[str, Any]]: """Search Wikipedia for articles matching a query with validation and diagnostics.""" if not query or not query.strip(): logger.warning("Empty search query provided") return [] trimmed_query = query.strip() if len(trimmed_query) > 300: logger.warning( "Search query too long (%d chars), truncating to 300", len(trimmed_query), ) trimmed_query = trimmed_query[:300] if limit <= 0: logger.warning("Invalid limit %d provided, using default 10", limit) limit = 10 elif limit > 500: logger.warning("Limit %d exceeds maximum, capping at 500", limit) limit = 500 params = { "action": "query", "format": "json", "list": "search", "utf8": 1, "srsearch": trimmed_query, "srlimit": limit, } params = self._add_variant_to_params(params) try: logger.debug("Making search request to %s with params %s", self.api_url, params) response = requests.get( self.api_url, headers=self._get_request_headers(), params=params, timeout=30, ) response.raise_for_status() data = response.json() if "error" in data: error_info = data["error"] logger.error( "Wikipedia API error: %s - %s", error_info.get("code", "unknown"), error_info.get("info", "No details"), ) return [] if "warnings" in data: for warning_type, warning_body in data["warnings"].items(): logger.warning("Wikipedia API warning (%s): %s", warning_type, warning_body) query_data = data.get("query", {}) search_results = query_data.get("search", []) logger.info( "Search for '%s' returned %d results", trimmed_query, len(search_results), ) results: List[Dict[str, Any]] = [] for item in search_results: title = item.get("title") if not title: logger.warning("Search result missing title: %s", item) continue results.append( { "title": title, "snippet": item.get("snippet", ""), "pageid": item.get("pageid", 0), "wordcount": item.get("wordcount", 0), "timestamp": item.get("timestamp", ""), } ) return results except requests.exceptions.Timeout as exc: logger.error("Search request timed out for query '%s': %s", trimmed_query, exc) return [] except requests.exceptions.ConnectionError as exc: logger.error("Connection error when searching for '%s': %s", trimmed_query, exc) return [] except requests.exceptions.HTTPError as exc: logger.error("HTTP error when searching for '%s': %s", trimmed_query, exc) return [] except requests.exceptions.RequestException as exc: logger.error("Request error when searching for '%s': %s", trimmed_query, exc) return [] except ValueError as exc: logger.error("JSON decode error when searching for '%s': %s", trimmed_query, exc) return [] except Exception as exc: # pragma: no cover - unexpected safeguard logger.error("Unexpected error searching Wikipedia for '%s': %s", trimmed_query, exc) return []
  • The @server.tool() decorator registers the search_wikipedia function as an MCP tool in the FastMCP server.
    @server.tool()

Other Tools

Related Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/Rudra-ravi/wikipedia-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server