#!/usr/bin/env python3
"""
MCP Server: mcp-serper-search

Serper (Google Search API) wrapper. Returns search results only.
"""

import os
import json
from pathlib import Path
from typing import Any, Dict

import requests
from mcp.server.fastmcp import FastMCP


def _load_serper_api_key() -> str:
    api_key = os.environ.get('SERPER_API_KEY')
    if api_key:
        return api_key
    # Try local .env in CWD or project root (best-effort)
    for candidate in [Path.cwd() / '.env', Path(__file__).resolve().parents[3] / '.env']:
        try:
            if candidate.exists():
                for line in candidate.read_text().splitlines():
                    line = line.strip()
                    if line and not line.startswith('#') and line.startswith('SERPER_API_KEY='):
                        return line.split('=', 1)[1].strip()
        except Exception:
            continue
    return ""


def _configure_proxy_session() -> requests.Session:
    session = requests.Session()
    http_proxy = os.environ.get('HTTP_PROXY') or os.environ.get('http_proxy')
    https_proxy = os.environ.get('HTTPS_PROXY') or os.environ.get('https_proxy')
    no_proxy = os.environ.get('NO_PROXY') or os.environ.get('no_proxy')
    if http_proxy or https_proxy:
        proxies = {}
        if http_proxy:
            proxies['http'] = http_proxy
        if https_proxy:
            proxies['https'] = https_proxy
        session.proxies.update(proxies)
        if no_proxy:
            session.trust_env = False
            session.proxies['no'] = no_proxy
    return session


def create_server() -> FastMCP:
    mcp = FastMCP("mcp-serper-search")

    @mcp.tool()
    def serper(command: str) -> str:
        """Search the web using Serper. Input must be keywords, not URLs."""
        if not command:
            return "No search query provided"
        if command.startswith('http://') or command.startswith('https://') or '://' in command:
            return "Error: URLs are not allowed as input. Please use keywords and search terms only."

        api_key = _load_serper_api_key()
        if not api_key:
            return (
                "SERPER_API_KEY not found. Set it as an environment variable or in a .env file."
            )

        headers = {
            'X-API-KEY': api_key,
            'Content-Type': 'application/json',
        }
        payload = {"q": command}
        try:
            session = _configure_proxy_session()
            resp = session.post("https://google.serper.dev/search", headers=headers, json=payload, timeout=30)
            resp.raise_for_status()
            data: Dict[str, Any] = resp.json()
            out_lines = []
            if 'organic' in data:
                for item in data['organic'][:5]:
                    title = item.get('title', 'No title')
                    link = item.get('link', '')
                    snippet = item.get('snippet', 'No description available')
                    out_lines.append(f"Title: {title}")
                    out_lines.append(f"URL: {link}")
                    out_lines.append(f"Snippet: {snippet}")
                    out_lines.append("---")
            return "\n".join(out_lines) if out_lines else "No results found"
        except requests.exceptions.Timeout:
            return "Request timeout: The search request took too long to complete"
        except requests.exceptions.RequestException as e:
            return f"Network error during Serper search: {str(e)}"
        except json.JSONDecodeError:
            return "Invalid JSON response from Serper API"
        except Exception as e:
            return f"Error executing Serper search: {str(e)}"

    return mcp


if __name__ == "__main__":
    create_server().run()

def main():
    create_server().run()

