wiki_search
Retrieve Wikipedia articles for answers or context by entering a search query, with options to specify the number of results. Enhances LLM responses with accurate, relevant information.
Instructions
Search Wikipedia for articles.
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| limit | No | ||
| query | Yes |
Implementation Reference
- server.py:60-60 (registration)Registers the wiki_search function as an MCP tool using the FastMCP decorator.@mcp.tool()
- server.py:61-62 (schema)Function signature with type hints defining the tool schema: inputs query (str), limit (int, default 3); output str. Docstring provides description.async def wiki_search(query: str, limit: int = 3) -> str: """Search Wikipedia for articles."""
- server.py:61-87 (handler)The core implementation of the wiki_search tool: constructs Wikipedia API params, calls helper API request, parses results, formats titles, snippets, URLs, handles errors.async def wiki_search(query: str, limit: int = 3) -> str: """Search Wikipedia for articles.""" try: params = { "action": "query", "list": "search", "srsearch": query, "format": "json", "srlimit": limit } data = await make_api_request(WIKI_API_BASE, params=params) if not data or "query" not in data or not data["query"]["search"]: return "No Wikipedia articles found for your query." results = [] for item in data["query"]["search"]: title = item["title"] snippet = item["snippet"].replace("<span class=\"searchmatch\">", "").replace("</span>", "") url = f"https://en.wikipedia.org/wiki/{urllib.parse.quote(title.replace(' ', '_'))}" results.append(f"Title: {title}\nSummary: {snippet}\nURL: {url}") return "\n\n".join(results) except Exception as e: logger.error(f"Error in wiki_search: {e}") return "Failed to search Wikipedia due to an internal error."
- server.py:34-58 (helper)Supporting utility function for making HTTP requests to APIs, used by wiki_search to query Wikipedia.async def make_api_request(url: str, params: dict = None, headers: dict = None, json: dict = None) -> dict[str, Any] | None: """Make a generic API request with proper error handling.""" default_headers = { "User-Agent": USER_AGENT, "Accept": "application/json" } if headers: default_headers.update(headers) async with httpx.AsyncClient(timeout=30.0) as client: try: if json: response = await client.post(url, json=json, headers=default_headers) else: response = await client.get(url, params=params, headers=default_headers) response.raise_for_status() return response.json() except httpx.HTTPStatusError as e: logger.error(f"HTTP error for {url}: {e}") except httpx.RequestError as e: logger.error(f"Request failed for {url}: {e}") except Exception as e: logger.error(f"Unexpected error for {url}: {e}") return None