File size: 2,392 Bytes
d2ff44f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f16c022
d2ff44f
 
 
 
 
 
 
e58684e
58170e1
d2ff44f
 
 
 
 
 
 
 
 
 
 
 
 
fc79518
d5f6c86
d2ff44f
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# -*- coding: utf-8 -*-
 
from mcp.server.fastmcp import FastMCP
import gradio as gr
import io
import json
import os
import re
import sys

import requests

sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8', errors='replace')
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8', errors='replace')

mcp = FastMCP("doomsweek_mcp_server")

def calc_asteroid_factor(data, weight=1.0):
    """
    Calculates the asteroid doom probability.

    Args:
        data (object): The data structure returned from NASA
        weight (float): The weight to apply to the hazard factor.
    
    Returns:
        Weighted factor for Near Earth Object impact for the next seven days.    
    """

    objects = [obj for sublist in data["near_earth_objects"].values() for obj in sublist] 

    num_objects = len(objects)

    hazardous_objects = [obj for sublist in data["near_earth_objects"].values() for obj in sublist if obj["is_potentially_hazardous_asteroid"] == True]

    num_hazardous_objects = len(hazardous_objects)

    return (num_hazardous_objects/num_objects * weight) # hazard factor 


def fetch_asteroid_data(url, api_key):
    """
    Fetches data from the NASA Near Earth Object Web Service.
    
    Returns:
        Near Earth Objects for the next seven days.    
    """

    request_data = requests.get(
        url,
        params={"api_key": api_key},  
    )

    if request_data.status_code != 200:    
        return None
    else:    
        return json.loads(request_data.content)
    
@mcp.tool()
async def calc_doom_probability():
    """
    Calculates the overall doom probability.
    
    Returns:
       The overall doom probability for the next seven days.    
    """

    nasa_url = "https://api.nasa.gov/neo/rest/v1/feed" 
    
    if not nasa_api_key:
        return "ERROR: NASA_API_KEY not set."
    else: 
        nasa_data = fetch_asteroid_data(nasa_url, nasa_api_key)
        if not nasa_data:
            return "ERROR: Unable to fetch data from NASA API."
        else:
            return calc_asteroid_factor(nasa_data, weight=1.0)
        
# demo = gr.Interface(fn=calc_doom_probability, inputs=None, outputs="text")
# demo.launch(mcp_server=True)

if __name__ == "__main__":
    # NOTE the NASA API is provided by the client via env server parameters
    nasa_api_key = os.getenv("NASA_API_KEY")
    mcp.run(transport='stdio')