Skip to content

Initial implementation of MCP support#13

Draft
mattt wants to merge 2 commits intomainfrom
mcp
Draft

Initial implementation of MCP support#13
mattt wants to merge 2 commits intomainfrom
mcp

Conversation

@mattt
Copy link
Owner

@mattt mattt commented Jan 16, 2025

https://modelcontextprotocol.io/

# /// script
# dependencies = [
#   "httpx",
#   "rich",
#   "hype @ git+https://github.com/mattt/hype.git@mcp",
# ]
# ///

import asyncio

import httpx

import hype
from hype.mcp import create_mcp_stdio_handler

# Weather API configuration
NWS_API_BASE: str = "https://api.weather.gov"
HEADERS = {"Accept": "application/geo+json"}

@hype.up
def get_forecast(region: str) -> list[str]:
    """Get weather forecast for the specified region.

    Args:
        region: The lat,lon coordinates (e.g. '37.7749,-122.4194' for San Francisco)

    Returns:
        A list of formatted forecast periods
    """
    with httpx.Client() as client:
        # First get the forecast grid endpoint
        points_url = f"{NWS_API_BASE}/points/{region}"
        response = client.get(points_url, headers=HEADERS)
        response.raise_for_status()
        points_data = response.json()

        # Get the detailed forecast
        forecast_url = points_data["properties"]["forecast"]
        response = client.get(forecast_url, headers=HEADERS)
        response.raise_for_status()
        data = response.json()

        periods = data["properties"]["periods"][:5]  # Next 5 forecast periods

        return [
            f"🌤️ {period['name']}\n"
            f"Temperature: {period['temperature']}°{period['temperatureUnit']}\n"
            f"Wind: {period['windSpeed']} {period['windDirection']}\n"
            f"{period['shortForecast']}\n"
            for period in periods
        ]


if __name__ == "__main__":
    try:
        # Start stdio handler
        handler = create_mcp_stdio_handler([get_forecast])
        asyncio.run(anext(handler))
    except KeyboardInterrupt:
        print("\nShutting down...")

Request

Enter JSON-RPC requests (one per line):
Example:
{
    "jsonrpc": "2.0",
    "method": "tools/call",
    "params": {
        "name": "get_forecast",
        "arguments": {
            "region": "37.7749,-122.4194"
        }
    },
    "id": 1
}

Response

{
    "jsonrpc": "2.0",
    "result": {
        "content": [
            {
                "type": "text",
                "text": "['🌤️ Today\\nTemperature: 62°F\\nWind: 3 mph NNW\\nSunny\\n', '🌤️ Tonight\\nTemperature: 45°F\\nWind: 2 mph WSW\\nPartly Cloudy\\n', '🌤️ Friday\\nTemperature: 57°F\\nWind: 2 to 7 mph SW\\nMostly Sunny\\n', '🌤️ Friday Night\\nTemperature: 45°F\\nWind: 2 to 7 mph WNW\\nPartly Cloudy then Patchy Fog\\n', '🌤️ Saturday\\nTemperature: 58°F\\nWind: 5 mph NNE\\nPatchy Fog then Sunny\\n']"
            }
        ]
    },
    "error": null,
    "id": 1
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant