|
import json |
|
import sys |
|
import os |
|
import logging |
|
from dotenv import load_dotenv |
|
import requests |
|
from urllib.parse import quote |
|
import urllib.request |
|
import urllib.parse |
|
|
|
# Configure logging |
|
logging.basicConfig(level=logging.DEBUG) |
|
logger = logging.getLogger(__name__) |
|
|
|
|
|
def brave_search(query, api_key): |
|
"""Queries the Brave Search API and returns the results.""" |
|
logger.debug("ENTERING BRAVE_SEARCH FUNCTION") |
|
logger.debug(f"QUERY: {query}") |
|
logger.debug(f"API KEY STARTS WITH: {api_key[:4]}") |
|
|
|
url = f"https://api.search.brave.com/res/v1/web/search?q={urllib.parse.quote(query)}" |
|
logger.debug(f"URL: {url}") |
|
|
|
headers = { |
|
"Accept": "application/json", |
|
"Accept-Encoding": "gzip", |
|
"X-Subscription-Token": api_key, |
|
} |
|
logger.debug(f"HEADERS: {headers}") |
|
|
|
try: |
|
logger.debug("ABOUT TO MAKE REQUEST") |
|
req = urllib.request.Request(url, headers=headers) |
|
with urllib.request.urlopen(req) as response: |
|
logger.debug(f"GOT RESPONSE STATUS: {response.status}") |
|
logger.debug(f"RESPONSE HEADERS: {response.headers}") |
|
logger.debug(f"RESPONSE CONTENT: {response.read()[:500]}") # First 500 bytes |
|
return json.loads(response.read()) |
|
except Exception as e: |
|
logger.error(f"API REQUEST FAILED WITH ERROR: {str(e)}") |
|
return {"error": str(e)} |
|
|
|
|
|
# Main execution |
|
query = input_data.get("query") |
|
|
|
try: |
|
from dotenv import load_dotenv |
|
load_dotenv() |
|
api_key = "123456" |
|
# can't seem to use env variable here |
|
# api_key = os.getenv("BRAVE_SEARCH_API_KEY") |
|
|
|
logger.debug(f"API key: {api_key}") |
|
logger.info("MCP script starting") |
|
|
|
if not api_key: |
|
print(json.dumps({"error": "BRAVE_SEARCH_API_KEY not found in environment"})) |
|
else: |
|
results = brave_search(query, api_key) |
|
print(json.dumps(results)) |
|
|
|
except Exception as e: |
|
print(json.dumps({"error": str(e)})) |