-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathserver.py
More file actions
293 lines (241 loc) · 10.6 KB
/
server.py
File metadata and controls
293 lines (241 loc) · 10.6 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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
"""This module defines a FastMCP server for Google Maps Platform operations."""
import os
import re
import json
import asyncio
import googlemaps
from fastmcp import FastMCP
from typing import Optional, Dict, Any
#---------------
# settings
#---------------
# these host, port, transport settings only apply if run using python
host=os.environ.get("FASTMCP_HOST", "0.0.0.0")
port=os.environ.get("FASTMCP_PORT", 8080)
transport=os.environ.get("FASTMCP_TRANSPORT", "stdio") # stdio, streamable-http, sse
google_maps_api_key=os.getenv("GOOGLE_MAPS_API_KEY")
gmaps = googlemaps.Client(key=google_maps_api_key)
#-------------
# helpers
#-------------
allowed_modes = ["driving", "walking", "bicycling", "transit"]
def assert_mode(mode: str):
assert mode in allowed_modes, f"ERROR: '{mode}' is not one of the allowed modes: {allowed_modes}"
allowed_input_types = ["textquery", "phonenumber"]
def assert_input_type(input_type: str):
assert input_type in allowed_input_types, f"ERROR: '{input_type}' is not one of the allowed inpute types: {allowed_input_types}"
#-----------------------
# initialize fastmcp
#-----------------------
# https://gofastmcp.com/servers/fastmcp#server-configuration
mcp = FastMCP(
name="FastMCP Google Maps Platform Server",
on_duplicate_tools="error",
)
#-------------------
# direction tools
#-------------------
@mcp.tool()
async def get_directions(origin: str, destination: str, mode: str="driving") -> Optional[Dict[str, Any]]:
"""Gives step-by-step instructions to get from origin to destination using a particular mode of transport
Args:
origin (str): originating address
destination (str): destination address
mode (str, optional): mode of transportation. Valid options are: driving, walking, bicycling, transit
Returns:
dictionary (JSON) of steps along with total distance and total duration
"""
try:
assert_mode(mode)
except AssertionError as e:
# print(e) # Replaced print with a return
return json.dumps({"error": str(e)}, separators=(',', ':'))
results = gmaps.directions(origin, destination, mode)
if results:
shortest_route = results[0]
output = {
"summary": shortest_route['summary'],
"total_distance": shortest_route['legs'][0]['distance']['text'],
"total_duration": shortest_route['legs'][0]['duration']['text'],
"steps": []
}
for leg in shortest_route['legs']:
for step in leg['steps']:
output["steps"].append({
"instruction": step['html_instructions'],
"distance": step['distance']['text'],
"duration": step['duration']['text']
})
return json.dumps(output, separators=(',', ':'))
else:
return "No directions found for the specified locations."
#--------------------------
# distance matrix tools
#--------------------------
@mcp.tool()
async def get_distance(origin: str, destination: str, mode: str="driving") -> Optional[Dict[str, Any]]:
"""Finds the distance and travel time between two locations for a mode of transportation
Args:
origin (str): originating address
destination (str): destination address
mode (str): mode of travel (driving, walking, bicycling, transit)
Returns:
dictionary (JSON) of total distance, total travel time duration, and mode of travel
"""
try:
assert_mode(mode)
except AssertionError as e:
# print(e) # Replaced print with a return
return json.dumps({"error": str(e)}, separators=(',', ':'))
results = gmaps.distance_matrix(origin, destination, mode)
if results:
rows = results.get('rows', [])
if not rows: # Check if rows is empty
return "No distance information found for the specified locations." # More specific message
shortest_distance_elements = rows[0].get('elements', [])
if not shortest_distance_elements or 'distance' not in shortest_distance_elements[0] or 'duration' not in shortest_distance_elements[0]:
return "No distance information found for the specified locations." # More specific message
# At this point, we expect elements[0] to have distance and duration
element = shortest_distance_elements[0]
# Additional check for status if available, e.g. "ZERO_RESULTS"
if element.get('status') == 'ZERO_RESULTS':
return "No distance information found for the specified locations (ZERO_RESULTS)."
output = {
"total_distance": element['distance']['text'],
"total_duration": element['duration']['text'],
"mode": mode,
}
return json.dumps(output, separators=(',', ':'))
else:
return "No distance information found for the specified locations." # Generic message for no results
#-------------------
# geocoding tools
#-------------------
@mcp.tool()
async def get_geocode(address: str) -> Optional[Dict[str, Any]]:
"""
Args:
address (str): can be address or the name of a place
Returns:
dictionary (JSON) with the geocode (latitude & longitude) of the address
"""
results = gmaps.geocode(address)
if results:
geocode = results[0]
output = {
"lat": geocode['geometry']['location']['lat'],
"lng": geocode['geometry']['location']['lng'],
}
return json.dumps(output, separators=(',', ':'))
else:
return "Address not found"
#-------------------
# places tools
#-------------------
@mcp.tool()
async def find_place(input: str, input_type: str="textquery", fields: list=["place_id", "formatted_address", "name", "geometry", "types", "rating"]) -> Optional[Dict[str, Any]]:
"""Find/query a place with the provided name
Args:
input (str): name of the place you're looking for. provide more details if possible (i.e. city, country, etc.) for better accuracy. can also be the establishment type (i.e. bakery, bank, etc.)
input_type (str, optional): the type of query, it can be a textquery or phonenumber query
fields (list, optional): list of fields to query for
Returns:
dictionary (JSON) of with basic information of the top result based on input query. basic information inclulde:
- name
- place_id
- address
- location (latitude, longitude)
- establishment type
- average rating
"""
try:
assert_input_type(input_type)
except AssertionError as e:
# print(e) # Replaced print with a return
return json.dumps({"error": str(e)}, separators=(',', ':'))
results = gmaps.find_place(input, input_type, fields)
if results:
try:
place = results.get('candidates', {})[0]
except IndexError:
return "No such place found"
output = {
"name": place['name'],
"place_id": place['place_id'],
"formatted_address": place['formatted_address'],
"location": place['geometry']['location'],
"types": place['types'],
"rating": place.get('rating', None),
}
return json.dumps(output, separators=(',', ':'))
@mcp.tool()
async def place_nearby(location: dict, radius: int, place_type: str) -> Optional[Dict[str, Any]]:
"""Find types of places within a radius of a location (latitude, longitude)
Args:
location (dict): dictionary with 'lat' and 'lng' as keys and values are the latitude and longitude respectively
radius (int): search area radius in meters (i.e. 2500 = 2.5km)
place_type (str): type of place you're looking for (i.e. "italian restaurant", "hotel", etc.)
Returns:
dictionary (JSON) of establishment names (key) and their place_id (value)
"""
results = gmaps.places_nearby(location, radius, place_type)
output = {}
if results:
places_nearby = results.get('results', {})
for place in range(len(places_nearby)):
place_name = places_nearby[place]['name']
place_id = places_nearby[place]['place_id']
output[place_name] = place_id
return json.dumps(output, separators=(',', ':'))
else:
return "Nothing nearby that matches the search criteria was found."
@mcp.tool()
async def place_details(place_id: str, fields: list=["name", "formatted_address", "formatted_phone_number", "website", "types", "rating", "user_ratings_total"]) -> Optional[Dict[str, Any]]:
"""
Args:
place_id (str): place_id of the place, which can be obtained via find_place() or place_nearby()
fields (list, optional): list of fields to query for
Returns:
dictionary (JSON) of with details of provided place. details inclulde:
- name
- address
- phone number
- website
- establishment type
- average rating
- total rating count
"""
results = gmaps.place(place_id, fields)
if results:
details = results.get('result', {})
if not details: # Check if details dict is empty
return "No details found for the specified place."
output = {
"name": details.get('name'), # Use .get() for all potentially missing keys
"formatted_address": details.get('formatted_address'),
"formatted_phone_number": details.get('formatted_phone_number'),
"website": details.get('website'),
"types": details.get('types'), # If types is critical and always present, direct access might be okay
"rating": details.get('rating'),
"user_ratings_total": details.get('user_ratings_total', 0), # Existing .get with default for this one
}
# Filter out None values from output to keep it clean if some fields are missing
output = {k: v for k, v in output.items() if v is not None}
if not output.get("name"): # If essential info like name is missing after .get()
return "Essential place details (e.g. name) are missing."
return json.dumps(output, separators=(',', ':'))
else:
return "No such place found." # This handles case where 'results' itself is None
#----------------
# main
#----------------
# https://gofastmcp.com/deployment/running-server
if __name__ == "__main__":
try:
asyncio.run(mcp.run(transport=transport, host=host, port=port))
except KeyboardInterrupt:
print("> FastMCP Google Maps Server stopped by user.")
except Exception as e:
print(f"> FastMCP Google Maps Server encountered error: {e}")
finally:
print("> FastMCP Google Maps Server exiting.")