forked from skillrepos/ai-apps
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmcp_server.py
More file actions
237 lines (189 loc) · 10.5 KB
/
mcp_server.py
File metadata and controls
237 lines (189 loc) · 10.5 KB
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
#!/usr/bin/env python3
"""
Lab 3: FastMCP Weather Server
────────────────────────────────────────────────────────────────────────
A robust FastMCP server that provides weather and geocoding services via HTTP.
Tools Provided
--------------
1. get_weather(lat, lon) → dict with temperature °C, WMO code, conditions
2. convert_c_to_f(c) → float (temperature in °F)
3. geocode_location(name) → dict with latitude, longitude, location name
Key Features
------------
* **Robust Retry Logic**: All API calls retry up to 3 times with exponential
backoff (1.5s, 2.25s) on transient errors (429, 5xx)
* **Fresh Connections**: Each retry creates a new session to avoid connection
pool issues that can cause persistent failures
* **Graceful Error Handling**: Returns error dict instead of raising exceptions,
allowing clients to continue processing
* **HTTP Transport**: Runs on localhost:8000/mcp/ using FastAPI + Uvicorn
Architecture
------------
This server centralizes all external API calls to Open-Meteo, providing a
clean separation between agents (orchestration) and API access (this server).
"""
from __future__ import annotations
# ── stdlib ──────────────────────────────────────────────────────────
import time
from typing import Final
# ── 3rd-party ───────────────────────────────────────────────────────
import requests
from fastmcp import FastMCP
# ╔══════════════════════════════════════════════════════════════════╗
# ║ 1. Weather-code lookup table (WMO standard codes) ║
# ╚══════════════════════════════════════════════════════════════════╝
# Open-Meteo returns WMO weather codes - this maps them to descriptions.
# WMO (World Meteorological Organization) codes are used by many weather APIs.
WEATHER_CODES: Final[dict[int, str]] = {
0: "Clear sky", 1: "Mainly clear",
2: "Partly cloudy", 3: "Overcast",
45: "Fog", 48: "Depositing rime fog",
51: "Light drizzle", 53: "Moderate drizzle",
55: "Dense drizzle", 56: "Light freezing drizzle",
57: "Dense freezing drizzle", 61: "Slight rain",
63: "Moderate rain", 65: "Heavy rain",
66: "Light freezing rain", 67: "Heavy freezing rain",
71: "Slight snow fall", 73: "Moderate snow fall",
75: "Heavy snow fall", 77: "Snow grains",
80: "Slight rain showers", 81: "Moderate rain showers",
82: "Violent rain showers", 85: "Slight snow showers",
86: "Heavy snow showers", 95: "Thunderstorm",
96: "Thunderstorm with slight hail", 99: "Thunderstorm with heavy hail",
}
# ╔══════════════════════════════════════════════════════════════════╗
# ║ 2. Retry configuration for API resilience ║
# ╚══════════════════════════════════════════════════════════════════╝
# Shared retry settings for all external API calls
MAX_RETRIES = 3 # Total attempts (1 original + 2 retries)
BACKOFF_FACTOR = 1.5 # Exponential backoff: 1.5s, 2.25s, 3.375s
TRANSIENT_CODES = {429, 500, 502, 503, 504} # HTTP codes worth retrying
# ╔══════════════════════════════════════════════════════════════════╗
# ║ 3. MCP Server initialization and tool definitions ║
# ╚══════════════════════════════════════════════════════════════════╝
mcp = FastMCP("WeatherServer")
# ─── Weather Tool ────────────────────────────────────────────────────
@mcp.tool
"""
Fetch **current weather** from Open-Meteo and return a concise dict.
Retry policy
------------
* Up to MAX_RETRIES total attempts with fresh connections.
* Retries on network errors **or** HTTP 429/5xx.
* Exponential back-off (1.5 s, 2.25 s, …).
* Each retry uses a new session to avoid connection pool issues.
Parameters
----------
lat, lon : float
Geographic coordinates in decimal degrees.
Returns
-------
last_error = None
# Retry loop with fresh connections
for attempt in range(MAX_RETRIES):
try:
# Fresh session per attempt avoids connection pool reuse issues
session = requests.Session()
resp = session.get(url, timeout=15)
session.close()
# Handle rate limiting and server errors with retry
if resp.status_code in TRANSIENT_CODES:
last_error = f"HTTP {resp.status_code}"
if attempt < MAX_RETRIES - 1:
time.sleep(BACKOFF_FACTOR ** attempt)
continue
resp.raise_for_status()
except requests.HTTPError as e:
# HTTP errors (4xx, 5xx not already caught)
last_error = f"HTTP {e.response.status_code}"
if attempt < MAX_RETRIES - 1:
time.sleep(BACKOFF_FACTOR ** attempt)
continue
except requests.RequestException as e:
# Network errors (timeout, connection refused, etc.)
last_error = f"{type(e).__name__}"
if attempt < MAX_RETRIES - 1:
time.sleep(BACKOFF_FACTOR ** attempt)
continue
except (KeyError, ValueError) as e:
# Data format errors - don't retry, immediate failure
return {
"error": f"Received invalid data from weather service: {type(e).__name__}. Please try again later."
}
# All retries exhausted - return graceful error
return {
"error": f"Weather service failed after {MAX_RETRIES} attempts (last error: {last_error}). Please try again later."
}
# ─── Temperature Conversion Tool ─────────────────────────────────────
@mcp.tool
# ─── Geocoding Tool ──────────────────────────────────────────────────
@mcp.tool
def geocode_location(name: str) -> dict:
"""
Geocode a location name to latitude/longitude coordinates using Open-Meteo's geocoding API.
Retry policy
------------
* Up to MAX_RETRIES total attempts with fresh connections.
* Retries on network errors **or** HTTP 429/5xx.
* Exponential back-off (1.5 s, 2.25 s, …).
* Each retry uses a new session to avoid connection pool issues.
Parameters
----------
name : str
Location name (e.g., "San Francisco", "Paris, France", "London, UK")
Returns
-------
# Retry loop with fresh connections
for attempt in range(MAX_RETRIES):
try:
# Fresh session per attempt avoids connection pool reuse issues
session = requests.Session()
resp = session.get(url, params={"name": name, "count": 1}, timeout=15)
session.close()
# Handle rate limiting and server errors with retry
if resp.status_code in TRANSIENT_CODES:
last_error = f"HTTP {resp.status_code}"
if attempt < MAX_RETRIES - 1:
time.sleep(BACKOFF_FACTOR ** attempt)
continue
resp.raise_for_status()
# Parse and return geocoding results
data = resp.json()
if data.get("results"):
hit = data["results"][0]
return {
"latitude": hit["latitude"],
"longitude": hit["longitude"],
"name": hit.get("name", name),
}
else:
# No results found - not an error, just no match
return {
"error": f"No location found for '{name}'. Try a different search term."
}
except requests.HTTPError as e:
# HTTP errors (4xx, 5xx not already caught)
last_error = f"HTTP {e.response.status_code}"
if attempt < MAX_RETRIES - 1:
time.sleep(BACKOFF_FACTOR ** attempt)
continue
except requests.RequestException as e:
# Network errors (timeout, connection refused, etc.)
last_error = f"{type(e).__name__}"
if attempt < MAX_RETRIES - 1:
time.sleep(BACKOFF_FACTOR ** attempt)
continue
except (KeyError, ValueError) as e:
# Data format errors - don't retry, immediate failure
return {
"error": f"Received invalid data from geocoding service: {type(e).__name__}. Please try again later."
}
# All retries exhausted - return graceful error
return {
"error": f"Geocoding service failed after {MAX_RETRIES} attempts (last error: {last_error}). Please try again later."
}
# ╔══════════════════════════════════════════════════════════════════╗
# ║ 4. Server startup ║
# ╚══════════════════════════════════════════════════════════════════╝
if __name__ == "__main__":
# Start HTTP server using FastAPI + Uvicorn
# Clients connect to: http://127.0.0.1:8000/mcp/