@cablate/mcp-google-map 0.0.34 → 0.0.36
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +38 -4
- package/dist/chunk-ME57GONJ.js +1 -0
- package/dist/cli.js +2 -2
- package/dist/index.d.ts +6 -0
- package/dist/index.js +1 -1
- package/package.json +1 -1
- package/skills/google-maps/SKILL.md +2 -1
- package/skills/google-maps/references/tools-api.md +44 -0
- package/dist/chunk-LT3W7AUA.js +0 -1
package/README.md
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
|
|
7
7
|
Give your AI agent the ability to understand the physical world — geocode, route, search, and reason about locations.
|
|
8
8
|
|
|
9
|
-
- **
|
|
9
|
+
- **14 tools** — 11 atomic + 3 composite (explore-area, plan-route, compare-places)
|
|
10
10
|
- **3 modes** — stdio, StreamableHTTP, standalone exec CLI
|
|
11
11
|
- **Agent Skill** — built-in skill definition teaches AI how to chain geo tools ([`skills/google-maps/`](./skills/google-maps/))
|
|
12
12
|
|
|
@@ -14,7 +14,7 @@ Give your AI agent the ability to understand the physical world — geocode, rou
|
|
|
14
14
|
|
|
15
15
|
| | This project | [Grounding Lite](https://cloud.google.com/blog/products/ai-machine-learning/announcing-official-mcp-support-for-google-services) |
|
|
16
16
|
|---|---|---|
|
|
17
|
-
| Tools | **
|
|
17
|
+
| Tools | **14** | 3 |
|
|
18
18
|
| Geocoding | Yes | No |
|
|
19
19
|
| Step-by-step directions | Yes | No |
|
|
20
20
|
| Elevation | Yes | No |
|
|
@@ -58,6 +58,7 @@ Special thanks to [@junyinnnn](https://github.com/junyinnnn) for helping add sup
|
|
|
58
58
|
| `maps_elevation` | Get elevation (meters above sea level) for geographic coordinates. |
|
|
59
59
|
| `maps_timezone` | Get timezone ID, name, UTC/DST offsets, and local time for coordinates. |
|
|
60
60
|
| `maps_weather` | Get current weather conditions or forecast — temperature, humidity, wind, UV, precipitation. |
|
|
61
|
+
| `maps_air_quality` | Get air quality index, pollutant concentrations, and health recommendations by demographic group. |
|
|
61
62
|
| **Composite Tools** | |
|
|
62
63
|
| `maps_explore_area` | Explore what's around a location — searches multiple place types and gets details in one call. |
|
|
63
64
|
| `maps_plan_route` | Plan an optimized multi-stop route — geocodes, finds best order, returns directions. |
|
|
@@ -111,7 +112,7 @@ Then configure your MCP client:
|
|
|
111
112
|
### Server Information
|
|
112
113
|
|
|
113
114
|
- **Transport**: stdio (`--stdio`) or Streamable HTTP (default)
|
|
114
|
-
- **Tools**:
|
|
115
|
+
- **Tools**: 14 Google Maps tools (11 atomic + 3 composite)
|
|
115
116
|
|
|
116
117
|
### CLI Exec Mode (Agent Skill)
|
|
117
118
|
|
|
@@ -122,7 +123,7 @@ npx @cablate/mcp-google-map exec geocode '{"address":"Tokyo Tower"}'
|
|
|
122
123
|
npx @cablate/mcp-google-map exec search-places '{"query":"ramen in Tokyo"}'
|
|
123
124
|
```
|
|
124
125
|
|
|
125
|
-
All
|
|
126
|
+
All 14 tools available: `geocode`, `reverse-geocode`, `search-nearby`, `search-places`, `place-details`, `directions`, `distance-matrix`, `elevation`, `timezone`, `weather`, `air-quality`, `explore-area`, `plan-route`, `compare-places`. See [`skills/google-maps/`](./skills/google-maps/) for the agent skill definition and full parameter docs.
|
|
126
127
|
|
|
127
128
|
### API Key Configuration
|
|
128
129
|
|
|
@@ -215,6 +216,7 @@ src/
|
|
|
215
216
|
│ ├── elevation.ts # maps_elevation tool
|
|
216
217
|
│ ├── timezone.ts # maps_timezone tool
|
|
217
218
|
│ ├── weather.ts # maps_weather tool
|
|
219
|
+
│ ├── airQuality.ts # maps_air_quality tool
|
|
218
220
|
│ ├── exploreArea.ts # maps_explore_area (composite)
|
|
219
221
|
│ ├── planRoute.ts # maps_plan_route (composite)
|
|
220
222
|
│ └── comparePlaces.ts # maps_compare_places (composite)
|
|
@@ -249,6 +251,38 @@ skills/
|
|
|
249
251
|
|
|
250
252
|
For enterprise security reviews, see [Security Assessment Clarifications](./SECURITY_ASSESSMENT.md) — a 23-item checklist covering licensing, data protection, credential management, tool contamination, and AI agent execution environment verification.
|
|
251
253
|
|
|
254
|
+
## Roadmap
|
|
255
|
+
|
|
256
|
+
### New Tools
|
|
257
|
+
|
|
258
|
+
| Tool | What it unlocks | Status |
|
|
259
|
+
|------|----------------|--------|
|
|
260
|
+
| `maps_static_map` | Return map images with pins/routes — multimodal AI can "see" the map | Planned |
|
|
261
|
+
| `maps_air_quality` | AQI, pollutants — health-aware travel, outdoor planning, real estate | **Done** |
|
|
262
|
+
| `maps_validate_address` | Standardize and verify addresses — logistics/e-commerce | Planned |
|
|
263
|
+
| `maps_isochrone` | "Show me everything within 30 min drive" — reachability analysis | Planned |
|
|
264
|
+
| `maps_batch_geocode` | Geocode hundreds of addresses in one call — data enrichment | Planned |
|
|
265
|
+
|
|
266
|
+
### Capabilities
|
|
267
|
+
|
|
268
|
+
| Feature | What it unlocks | Status |
|
|
269
|
+
|---------|----------------|--------|
|
|
270
|
+
| Spatial Context | Agent remembers "the area we were just looking at" across turns | Research |
|
|
271
|
+
| Geo Agent Template | One command to spin up a full geo-aware AI agent | Research |
|
|
272
|
+
| Geo-Reasoning Benchmark | 10-scenario test suite measuring LLM geospatial reasoning accuracy | Research |
|
|
273
|
+
|
|
274
|
+
### Use Cases We're Building Toward
|
|
275
|
+
|
|
276
|
+
These are the real-world scenarios driving our tool decisions:
|
|
277
|
+
|
|
278
|
+
- **Travel planning** — "Plan a day trip in Tokyo" (geocode → search → directions → weather)
|
|
279
|
+
- **Real estate analysis** — "Analyze this neighborhood: schools, commute, flood risk" (search-nearby × N + elevation + distance-matrix)
|
|
280
|
+
- **Logistics optimization** — "Route these 12 deliveries efficiently from the warehouse" (plan-route)
|
|
281
|
+
- **Field sales** — "Visit 6 clients in Chicago, minimize drive time, find lunch spots" (plan-route + search-nearby)
|
|
282
|
+
- **Disaster response** — "Nearest open hospitals? Am I in a flood zone?" (search-nearby + elevation)
|
|
283
|
+
- **Content creation** — "Top 5 neighborhoods in Austin with restaurant density and airport distance" (explore-area + distance-matrix)
|
|
284
|
+
- **Accessibility** — "Wheelchair-accessible restaurants, avoid steep routes" (search-nearby + place-details + elevation)
|
|
285
|
+
|
|
252
286
|
## Changelog
|
|
253
287
|
|
|
254
288
|
See [CHANGELOG.md](./CHANGELOG.md) for version history.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Client as x,Language as A}from"@googlemaps/google-maps-services-js";import R from"dotenv";R.config();function f(p){let e=p?.response?.status,t=p?.response?.data?.error_message,r=p?.response?.data?.status;return e===403?"API key invalid or required API not enabled. Check: console.cloud.google.com \u2192 APIs & Services \u2192 Enable the relevant API (Places, Geocoding, etc.)":e===429?"API quota exceeded. Wait and retry, or check quota at console.cloud.google.com \u2192 Quotas":r==="ZERO_RESULTS"?"No results found. Try broader search terms or a larger radius.":r==="OVER_QUERY_LIMIT"?"API quota exceeded. Wait and retry, or upgrade your billing plan.":r==="REQUEST_DENIED"?`Request denied by Google Maps API. ${t||"Check your API key and enabled APIs."}`:r==="INVALID_REQUEST"?`Invalid request parameters. ${t||"Check your input values."}`:t?`${t} (HTTP ${e})`:p instanceof Error?p.message:String(p)}var E=class{constructor(e){this.defaultLanguage=A.en;if(this.client=new x({}),this.apiKey=e||process.env.GOOGLE_MAPS_API_KEY||"",!this.apiKey)throw new Error("Google Maps API Key is required")}async geocodeAddress(e){try{let t=await this.client.geocode({params:{address:e,key:this.apiKey,language:this.defaultLanguage}});if(t.data.results.length===0)throw new Error(`No location found for address: "${e}"`);let r=t.data.results[0],a=r.geometry.location;return{lat:a.lat,lng:a.lng,formatted_address:r.formatted_address,place_id:r.place_id}}catch(t){throw y.error("Error in geocodeAddress:",t),new Error(`Failed to geocode address "${e}": ${f(t)}`)}}parseCoordinates(e){let t=e.split(",").map(r=>parseFloat(r.trim()));if(t.length!==2||isNaN(t[0])||isNaN(t[1]))throw new Error(`Invalid coordinate format: "${e}". Please use "latitude,longitude" format (e.g., "25.033,121.564"`);return{lat:t[0],lng:t[1]}}async getLocation(e){return e.isCoordinates?this.parseCoordinates(e.value):this.geocodeAddress(e.value)}async geocode(e){try{let t=await this.geocodeAddress(e);return{location:{lat:t.lat,lng:t.lng},formatted_address:t.formatted_address||"",place_id:t.place_id||""}}catch(t){throw y.error("Error in geocode:",t),new Error(`Failed to geocode address "${e}": ${f(t)}`)}}async reverseGeocode(e,t){try{let r=await this.client.reverseGeocode({params:{latlng:{lat:e,lng:t},language:this.defaultLanguage,key:this.apiKey}});if(r.data.results.length===0)throw new Error(`No address found for coordinates: (${e}, ${t})`);let a=r.data.results[0];return{formatted_address:a.formatted_address,place_id:a.place_id,address_components:a.address_components}}catch(r){throw y.error("Error in reverseGeocode:",r),new Error(`Failed to reverse geocode coordinates (${e}, ${t}): ${f(r)}`)}}async calculateDistanceMatrix(e,t,r="driving"){try{let n=(await this.client.distancematrix({params:{origins:e,destinations:t,mode:r,language:this.defaultLanguage,key:this.apiKey}})).data;if(n.status!=="OK")throw new Error(`Distance matrix calculation failed with status: ${n.status}`);let s=[],l=[];return n.rows.forEach(u=>{let o=[],c=[];u.elements.forEach(d=>{d.status==="OK"?(o.push({value:d.distance.value,text:d.distance.text}),c.push({value:d.duration.value,text:d.duration.text})):(o.push(null),c.push(null))}),s.push(o),l.push(c)}),{distances:s,durations:l,origin_addresses:n.origin_addresses,destination_addresses:n.destination_addresses}}catch(a){throw y.error("Error in calculateDistanceMatrix:",a),new Error(`Failed to calculate distance matrix: ${f(a)}`)}}async getDirections(e,t,r="driving",a,n){try{let s;n&&(s=Math.floor(n.getTime()/1e3));let l;s||(a instanceof Date?l=Math.floor(a.getTime()/1e3):a?l=a:l="now");let o=(await this.client.directions({params:{origin:e,destination:t,mode:r,language:this.defaultLanguage,key:this.apiKey,arrival_time:s,departure_time:l}})).data;if(o.status!=="OK")throw new Error(`Failed to get directions with status: ${o.status} (arrival_time: ${s}, departure_time: ${l}`);if(o.routes.length===0)throw new Error(`No route found from "${e}" to "${t}" with mode: ${r}`);let c=o.routes[0],d=c.legs[0],m=i=>{if(!i||typeof i.value!="number")return"";let g=new Date(i.value*1e3),h={year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1};return i.time_zone&&typeof i.time_zone=="string"&&(h.timeZone=i.time_zone),g.toLocaleString(this.defaultLanguage.toString(),h)};return{routes:o.routes,summary:c.summary,total_distance:{value:d.distance.value,text:d.distance.text},total_duration:{value:d.duration.value,text:d.duration.text},arrival_time:m(d.arrival_time),departure_time:m(d.departure_time)}}catch(s){throw y.error("Error in getDirections:",s),new Error(`Failed to get directions from "${e}" to "${t}": ${f(s)}`)}}async getWeather(e,t,r="current",a,n){try{let s=`key=${this.apiKey}&location.latitude=${e}&location.longitude=${t}`,l;switch(r){case"forecast_daily":{let c=Math.min(Math.max(a||5,1),10);l=`https://weather.googleapis.com/v1/forecast/days:lookup?${s}&days=${c}`;break}case"forecast_hourly":{let c=Math.min(Math.max(n||24,1),240);l=`https://weather.googleapis.com/v1/forecast/hours:lookup?${s}&hours=${c}`;break}default:l=`https://weather.googleapis.com/v1/currentConditions:lookup?${s}`}let u=await fetch(l);if(!u.ok){let d=(await u.json().catch(()=>({})))?.error?.message||`HTTP ${u.status}`;throw d.includes("not supported for this location")?new Error(`Weather data is not available for this location (${e}, ${t}). The Google Weather API has limited coverage \u2014 China, Japan, South Korea, Cuba, Iran, North Korea, and Syria are unsupported. Try a location in North America, Europe, or Oceania.`):new Error(d)}let o=await u.json();return r==="current"?{temperature:o.temperature,feelsLike:o.feelsLikeTemperature,humidity:o.relativeHumidity,wind:o.wind,conditions:o.weatherCondition?.description?.text||o.weatherCondition?.type,uvIndex:o.uvIndex,precipitation:o.precipitation,visibility:o.visibility,pressure:o.airPressure,cloudCover:o.cloudCover,isDayTime:o.isDaytime}:o}catch(s){throw y.error("Error in getWeather:",s),new Error(s.message||`Failed to get weather for (${e}, ${t})`)}}async getAirQuality(e,t,r=!0,a=!1){try{let n=`https://airquality.googleapis.com/v1/currentConditions:lookup?key=${this.apiKey}`,s=[];r&&s.push("HEALTH_RECOMMENDATIONS"),a&&s.push("POLLUTANT_CONCENTRATION");let l={location:{latitude:e,longitude:t}};s.length>0&&(l.extraComputations=s);let u=await fetch(n,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(l)});if(!u.ok){let g=(await u.json().catch(()=>({})))?.error?.message||`HTTP ${u.status}`;throw new Error(g)}let o=await u.json(),c=o.indexes||[],d=c[0],m={dateTime:o.dateTime,regionCode:o.regionCode,aqi:d?.aqi,category:d?.category,dominantPollutant:d?.dominantPollutant,color:d?.color};return c.length>1&&(m.indexes=c.map(i=>({code:i.code,displayName:i.displayName,aqi:i.aqi,category:i.category,dominantPollutant:i.dominantPollutant}))),o.healthRecommendations&&(m.healthRecommendations=o.healthRecommendations),o.pollutants&&(m.pollutants=o.pollutants.map(i=>({code:i.code,displayName:i.displayName,concentration:i.concentration,additionalInfo:i.additionalInfo}))),m}catch(n){throw y.error("Error in getAirQuality:",n),new Error(n.message||`Failed to get air quality for (${e}, ${t})`)}}async getTimezone(e,t,r){try{let a=Math.floor(r?r/1e3:Date.now()/1e3),s=(await this.client.timezone({params:{location:{lat:e,lng:t},timestamp:a,key:this.apiKey}})).data;if(s.status!=="OK")throw new Error(`Timezone API returned status: ${s.status}`);let l=(s.rawOffset+s.dstOffset)*1e3,u=new Date(a*1e3+l).toISOString().replace("Z","");return{timeZoneId:s.timeZoneId,timeZoneName:s.timeZoneName,utcOffset:s.rawOffset,dstOffset:s.dstOffset,localTime:u}}catch(a){throw y.error("Error in getTimezone:",a),new Error(`Failed to get timezone for (${e}, ${t}): ${f(a)}`)}}async getElevation(e){try{let t=e.map(n=>({lat:n.latitude,lng:n.longitude})),a=(await this.client.elevation({params:{locations:t,key:this.apiKey}})).data;if(a.status!=="OK")throw new Error(`Failed to get elevation data with status: ${a.status}`);return a.results.map((n,s)=>({elevation:n.elevation,location:t[s]}))}catch(t){throw y.error("Error in getElevation:",t),new Error(`Failed to get elevation data for ${e.length} location(s): ${f(t)}`)}}};import{PlacesClient as D}from"@googlemaps/places";var _=class{constructor(e){this.defaultLanguage="en";this.placeFieldMask=["displayName","name","id","formattedAddress","location","utcOffsetMinutes","regularOpeningHours.periods","regularOpeningHours.weekdayDescriptions","currentOpeningHours.openNow","nationalPhoneNumber","websiteUri","priceLevel","rating","userRatingCount","reviews.rating","reviews.text","reviews.publishTime","reviews.authorAttribution.displayName","photos.heightPx","photos.widthPx","photos.name"].join(",");this.searchNearbyFieldMask=["places.displayName","places.name","places.id","places.formattedAddress","places.location","places.rating","places.userRatingCount","places.currentOpeningHours.openNow"].join(",");if(this.client=new D({apiKey:e||process.env.GOOGLE_MAPS_API_KEY||""}),!e&&!process.env.GOOGLE_MAPS_API_KEY)throw new Error("Google Maps API Key is required")}async searchNearby(e){try{let t={locationRestriction:{circle:{center:{latitude:e.location.lat,longitude:e.location.lng},radius:e.radius||1e3}},maxResultCount:Math.min(e.maxResultCount||20,20),languageCode:this.defaultLanguage};e.keyword&&(t.includedTypes=[e.keyword]);let[r]=await this.client.searchNearby(t,{otherArgs:{headers:{"X-Goog-FieldMask":this.searchNearbyFieldMask}}});return(r.places||[]).map(a=>this.transformSearchResult(a))}catch(t){throw y.error("Error in searchNearby (New API):",t),new Error(`Failed to search nearby places: ${this.extractErrorMessage(t)}`)}}async searchText(e){try{let t={textQuery:e.textQuery,languageCode:this.defaultLanguage,maxResultCount:Math.min(e.maxResultCount||10,20)};e.locationBias&&(t.locationBias={circle:{center:{latitude:e.locationBias.lat,longitude:e.locationBias.lng},radius:e.locationBias.radius||5e3}}),e.openNow&&(t.openNow=!0),e.minRating&&(t.minRating=e.minRating),e.includedType&&(t.includedType=e.includedType);let[r]=await this.client.searchText(t,{otherArgs:{headers:{"X-Goog-FieldMask":this.searchNearbyFieldMask}}});return(r.places||[]).map(a=>this.transformSearchResult(a))}catch(t){throw y.error("Error in searchText (New API):",t),new Error(`Failed to search places: ${this.extractErrorMessage(t)}`)}}async getPlaceDetails(e){try{let t=`places/${e}`,[r]=await this.client.getPlace({name:t,languageCode:this.defaultLanguage},{otherArgs:{headers:{"X-Goog-FieldMask":this.placeFieldMask}}});return this.transformPlaceResponse(r)}catch(t){throw y.error("Error in getPlaceDetails (New API):",t),new Error(`Failed to get place details for ${e}: ${this.extractErrorMessage(t)}`)}}transformSearchResult(e){return{name:e.displayName?.text||"",place_id:this.extractLegacyPlaceId(e),formatted_address:e.formattedAddress||"",geometry:{location:{lat:e.location?.latitude||0,lng:e.location?.longitude||0}},rating:e.rating||0,user_ratings_total:e.userRatingCount||0,opening_hours:{open_now:e.currentOpeningHours?.openNow??null}}}transformPlaceResponse(e){return{name:e.displayName?.text||e.name||"",place_id:this.extractLegacyPlaceId(e),formatted_address:e.formattedAddress||"",geometry:{location:{lat:e.location?.latitude||0,lng:e.location?.longitude||0}},rating:e.rating||0,user_ratings_total:e.userRatingCount||0,opening_hours:e.regularOpeningHours?{open_now:this.isCurrentlyOpen(e.regularOpeningHours,e.utcOffsetMinutes,e.currentOpeningHours),weekday_text:this.formatOpeningHours(e.regularOpeningHours)}:void 0,formatted_phone_number:e.nationalPhoneNumber||"",website:e.websiteUri||"",price_level:e.priceLevel||0,reviews:e.reviews?.map(t=>({rating:t.rating||0,text:t.text?.text||"",time:t.publishTime?.seconds||0,author_name:t.authorAttribution?.displayName||""}))||[],photos:e.photos?.map(t=>({photo_reference:t.name||"",height:t.heightPx||0,width:t.widthPx||0}))||[]}}extractLegacyPlaceId(e){let t=e?.name;if(typeof t=="string"&&t.startsWith("places/")){let r=t.substring(7);if(r)return r}return e?.id||""}isCurrentlyOpen(e,t,r){if(typeof r?.openNow=="boolean")return r.openNow;if(typeof e?.openNow=="boolean")return e.openNow;let a=e?.periods;if(!Array.isArray(a)||a.length===0)return!1;let n=1440,s=n*7,{day:l,minutes:u}=this.getLocalTimeComponents(t),o=l*n+u,c={SUNDAY:0,MONDAY:1,TUESDAY:2,WEDNESDAY:3,THURSDAY:4,FRIDAY:5,SATURDAY:6},d=i=>{if(typeof i=="number"&&i>=0&&i<=6)return i;if(typeof i=="string"){let g=i.toUpperCase();if(g in c)return c[g]}},m=i=>{if(!i)return;let g=typeof i.hours=="number"?i.hours:Number(i.hours??NaN),h=typeof i.minutes=="number"?i.minutes:Number(i.minutes??NaN);if(!(!Number.isFinite(g)||!Number.isFinite(h)))return g*60+h};for(let i of a){let g=d(i?.openDay),h=d(i?.closeDay??i?.openDay),w=m(i?.openTime),T=m(i?.closeTime);if(g===void 0||w===void 0)continue;let v=g*n+w,b;h===void 0||T===void 0?b=v+n:b=h*n+T,b<=v&&(b+=s);let P=o;for(;P<v;)P+=s;if(P>=v&&P<b)return!0}return!1}getLocalTimeComponents(e){let t=new Date;if(typeof e=="number"&&Number.isFinite(e)){let r=new Date(t.getTime()+e*6e4);return{day:r.getUTCDay(),minutes:r.getUTCHours()*60+r.getUTCMinutes()}}return{day:t.getDay(),minutes:t.getHours()*60+t.getMinutes()}}formatOpeningHours(e){return e?.weekdayDescriptions||[]}extractErrorMessage(e){let t=e?.code,r=e?.message||e?.details;return t===7||t===403?"API key invalid or Places API (New) not enabled. Check: console.cloud.google.com \u2192 APIs & Services \u2192 Enable 'Places API (New)'":t===8||t===429?"API quota exceeded. Wait and retry, or check quota at console.cloud.google.com \u2192 Quotas":r||(e instanceof Error?e.message:String(e))}};var N=class{constructor(e){this.mapsTools=new E(e),this.newPlacesService=new _(e)}async searchNearby(e){try{let t=await this.mapsTools.getLocation(e.center),a=await this.newPlacesService.searchNearby({location:t,keyword:e.keyword,radius:e.radius});return e.openNow&&(a=a.filter(n=>n.opening_hours?.open_now===!0)),e.minRating&&(a=a.filter(n=>(n.rating||0)>=(e.minRating||0))),{location:t,success:!0,data:a.map(n=>({name:n.name,place_id:n.place_id,address:n.formatted_address,location:n.geometry.location,rating:n.rating,total_ratings:n.user_ratings_total,open_now:n.opening_hours?.open_now}))}}catch(t){return{success:!1,error:t instanceof Error?t.message:"An error occurred during search"}}}async searchText(e){try{return{success:!0,data:(await this.newPlacesService.searchText({textQuery:e.query,locationBias:e.locationBias?{lat:e.locationBias.latitude,lng:e.locationBias.longitude,radius:e.locationBias.radius}:void 0,openNow:e.openNow,minRating:e.minRating,includedType:e.includedType})).map(r=>({name:r.name,place_id:r.place_id,address:r.formatted_address,location:r.geometry.location,rating:r.rating,total_ratings:r.user_ratings_total,open_now:r.opening_hours?.open_now}))}}catch(t){return{success:!1,error:t instanceof Error?t.message:"An error occurred during text search"}}}async getPlaceDetails(e){try{let t=await this.newPlacesService.getPlaceDetails(e);return{success:!0,data:{name:t.name,address:t.formatted_address,location:t.geometry?.location,rating:t.rating,total_ratings:t.user_ratings_total,open_now:t.opening_hours?.open_now,phone:t.formatted_phone_number,website:t.website,price_level:t.price_level,reviews:t.reviews?.map(r=>({rating:r.rating,text:r.text,time:r.time,author_name:r.author_name}))}}}catch(t){return{success:!1,error:t instanceof Error?t.message:"An error occurred while getting place details"}}}async geocode(e){try{return{success:!0,data:await this.mapsTools.geocode(e)}}catch(t){return{success:!1,error:t instanceof Error?t.message:"An error occurred while geocoding address"}}}async reverseGeocode(e,t){try{return{success:!0,data:await this.mapsTools.reverseGeocode(e,t)}}catch(r){return{success:!1,error:r instanceof Error?r.message:"An error occurred during reverse geocoding"}}}async calculateDistanceMatrix(e,t,r="driving"){try{return{success:!0,data:await this.mapsTools.calculateDistanceMatrix(e,t,r)}}catch(a){return{success:!1,error:a instanceof Error?a.message:"An error occurred while calculating distance matrix"}}}async getDirections(e,t,r="driving",a,n){try{let s=a?new Date(a):new Date,l=n?new Date(n):void 0;return{success:!0,data:await this.mapsTools.getDirections(e,t,r,s,l)}}catch(s){return{success:!1,error:s instanceof Error?s.message:"An error occurred while getting directions"}}}async getTimezone(e,t,r){try{return{success:!0,data:await this.mapsTools.getTimezone(e,t,r)}}catch(a){return{success:!1,error:a instanceof Error?a.message:"An error occurred while getting timezone"}}}async getWeather(e,t,r="current",a,n){try{return{success:!0,data:await this.mapsTools.getWeather(e,t,r,a,n)}}catch(s){return{success:!1,error:s instanceof Error?s.message:"An error occurred while getting weather"}}}async getAirQuality(e,t,r,a){try{return{success:!0,data:await this.mapsTools.getAirQuality(e,t,r,a)}}catch(n){return{success:!1,error:n instanceof Error?n.message:"An error occurred while getting air quality"}}}async exploreArea(e){let t=e.types||["restaurant","cafe","attraction"],r=e.radius||1e3,a=e.topN||3,n=await this.geocode(e.location);if(!n.success||!n.data)throw new Error(n.error||"Geocode failed");let{lat:s,lng:l}=n.data.location,u=[];for(let o of t){let c=await this.searchNearby({center:{value:`${s},${l}`,isCoordinates:!0},keyword:o,radius:r});if(!c.success||!c.data)continue;let d=c.data.slice(0,a),m=[];for(let i of d){if(!i.place_id)continue;let g=await this.getPlaceDetails(i.place_id);m.push({name:i.name,address:i.address,rating:i.rating,total_ratings:i.total_ratings,open_now:i.open_now,phone:g.data?.phone,website:g.data?.website})}u.push({type:o,count:c.data.length,top:m})}return{success:!0,data:{location:{address:n.data.formatted_address,lat:s,lng:l},radius:r,categories:u}}}async planRoute(e){let t=e.mode||"driving",r=e.stops;if(r.length<2)throw new Error("Need at least 2 stops");let a=[];for(let o of r){let c=await this.geocode(o);if(!c.success||!c.data)throw new Error(`Failed to geocode: ${o}`);a.push({originalName:o,address:c.data.formatted_address,lat:c.data.location.lat,lng:c.data.location.lng})}let n=a;if(e.optimize!==!1&&a.length>2){let o=await this.calculateDistanceMatrix(r,r,"driving");if(o.success&&o.data){let c=new Set([0]),d=[0],m=0;for(;c.size<a.length;){let i=-1,g=1/0;for(let h=0;h<a.length;h++){if(c.has(h))continue;let w=o.data.durations[m]?.[h]?.value??1/0;w<g&&(g=w,i=h)}if(i===-1)break;c.add(i),d.push(i),m=i}n=d.map(i=>a[i])}}let s=[],l=0,u=0;for(let o=0;o<n.length-1;o++){let c=await this.getDirections(n[o].originalName,n[o+1].originalName,t);c.success&&c.data?(l+=c.data.total_distance.value,u+=c.data.total_duration.value,s.push({from:n[o].originalName,to:n[o+1].originalName,distance:c.data.total_distance.text,duration:c.data.total_duration.text})):s.push({from:n[o].originalName,to:n[o+1].originalName,distance:"unknown",duration:"unknown",note:c.error||"Directions unavailable for this segment"})}return{success:!0,data:{mode:t,optimized:e.optimize!==!1&&a.length>2,stops:n.map(o=>`${o.originalName} (${o.address})`),legs:s,total_distance:`${(l/1e3).toFixed(1)} km`,total_duration:`${Math.round(u/60)} min`}}}async comparePlaces(e){let t=e.limit||5,r=await this.searchText({query:e.query});if(!r.success||!r.data)throw new Error(r.error||"Search failed");let a=r.data.slice(0,t),n=[];for(let s of a){let l=await this.getPlaceDetails(s.place_id);n.push({name:s.name,address:s.address,rating:s.rating,total_ratings:s.total_ratings,open_now:s.open_now,phone:l.data?.phone,website:l.data?.website,price_level:l.data?.price_level})}if(e.userLocation&&n.length>0){let s=`${e.userLocation.latitude},${e.userLocation.longitude}`,l=a.map(o=>`${o.location.lat},${o.location.lng}`),u=await this.calculateDistanceMatrix([s],l,"driving");if(u.success&&u.data)for(let o=0;o<n.length;o++)n[o].distance=u.data.distances[0]?.[o]?.text,n[o].drive_time=u.data.durations[0]?.[o]?.text}return{success:!0,data:n}}async getElevation(e){try{return{success:!0,data:await this.mapsTools.getElevation(e)}}catch(t){return{success:!1,error:t instanceof Error?t.message:"An error occurred while getting elevation data"}}}};var y={log:(...p)=>{console.error("[INFO]",...p)},error:(...p)=>{console.error("[ERROR]",...p)}};export{_ as a,y as b,N as c};
|
package/dist/cli.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{b as s,c as a}from"./chunk-
|
|
3
|
-
`+JSON.stringify(t.data,null,2)}],isError:!1}:{content:[{type:"text",text:t.error||"Search failed"}],isError:!0}}catch(e){return{isError:!0,content:[{type:"text",text:`Error searching nearby places: ${e instanceof Error?e.message:JSON.stringify(e)}`}]}}}var f={NAME:B,DESCRIPTION:X,SCHEMA:Q,ACTION:ee};import{z as te}from"zod";var re="maps_place_details",oe="Get comprehensive details for a specific place using its Google Maps place_id. Use after search_nearby or maps_search_places to get full information including reviews, phone number, website, opening hours, and photos. Returns everything needed to evaluate or contact a business.",se={placeId:te.string().describe("Google Maps place ID")};async function ae(r){try{let e=n(),t=await new a(e).getPlaceDetails(r.placeId);return t.success?{content:[{type:"text",text:JSON.stringify(t.data,null,2)}],isError:!1}:{content:[{type:"text",text:t.error||"Failed to get place details"}],isError:!0}}catch(e){return{isError:!0,content:[{type:"text",text:`Error getting place details: ${e instanceof Error?e.message:JSON.stringify(e)}`}]}}}var h={NAME:re,DESCRIPTION:oe,SCHEMA:se,ACTION:ae};import{z as ne}from"zod";var ie="maps_geocode",ce="Convert an address, city name, or landmark into GPS coordinates (latitude/longitude). Use when you need coordinates for a location described in text \u2014 for example, to provide a center point for search_nearby or a starting point for maps_directions.",le={address:ne.string().describe("Address or place name to convert to coordinates")};async function pe(r){try{let e=n(),t=await new a(e).geocode(r.address);return t.success?{content:[{type:"text",text:JSON.stringify(t.data,null,2)}],isError:!1}:{content:[{type:"text",text:t.error||"Failed to geocode address"}],isError:!0}}catch(e){return{isError:!0,content:[{type:"text",text:`Error geocoding address: ${e instanceof Error?e.message:JSON.stringify(e)}`}]}}}var S={NAME:ie,DESCRIPTION:ce,SCHEMA:le,ACTION:pe};import{z as j}from"zod";var de="maps_reverse_geocode",ue="Convert GPS coordinates (latitude/longitude) into a human-readable street address. Use when you have coordinates from another tool's output or a user's shared location and need the actual address.",me={latitude:j.number().describe("Latitude coordinate"),longitude:j.number().describe("Longitude coordinate")};async function ye(r){try{let e=n(),t=await new a(e).reverseGeocode(r.latitude,r.longitude);return t.success?{content:[{type:"text",text:JSON.stringify(t.data,null,2)}],isError:!1}:{content:[{type:"text",text:t.error||"Failed to reverse geocode coordinates"}],isError:!0}}catch(e){return{isError:!0,content:[{type:"text",text:`Error reverse geocoding: ${e instanceof Error?e.message:JSON.stringify(e)}`}]}}}var E={NAME:de,DESCRIPTION:ue,SCHEMA:me,ACTION:ye};import{z as b}from"zod";var ge="maps_distance_matrix",fe="Calculate travel distances and durations between multiple origins and destinations in a single request. Use for comparing travel options \u2014 e.g., 'which hotel is closest to the office?' or batch distance calculations. Supports driving, walking, bicycling, and transit modes.",he={origins:b.array(b.string()).describe("List of origin addresses or coordinates"),destinations:b.array(b.string()).describe("List of destination addresses or coordinates"),mode:b.enum(["driving","walking","bicycling","transit"]).default("driving").describe("Travel mode for calculation")};async function Se(r){try{let e=n(),t=await new a(e).calculateDistanceMatrix(r.origins,r.destinations,r.mode);return t.success?{content:[{type:"text",text:JSON.stringify(t.data,null,2)}],isError:!1}:{content:[{type:"text",text:t.error||"Failed to calculate distance matrix"}],isError:!0}}catch(e){return{isError:!0,content:[{type:"text",text:`Error calculating distance matrix: ${e instanceof Error?e.message:JSON.stringify(e)}`}]}}}var v={NAME:ge,DESCRIPTION:fe,SCHEMA:he,ACTION:Se};import{z as P}from"zod";var Ee="maps_directions",be="Get step-by-step navigation directions between two points with route details. Use when the user asks 'how do I get from A to B?' and needs the route summary, total distance, estimated travel time, or turn-by-turn instructions. Supports departure/arrival times and multiple travel modes.",ve={origin:P.string().describe("Starting point address or coordinates"),destination:P.string().describe("Destination address or coordinates"),mode:P.enum(["driving","walking","bicycling","transit"]).default("driving").describe("Travel mode for directions"),departure_time:P.string().optional().describe("Departure time (ISO string format)"),arrival_time:P.string().optional().describe("Arrival time (ISO string format)")};async function Pe(r){try{let e=n(),t=await new a(e).getDirections(r.origin,r.destination,r.mode,r.departure_time,r.arrival_time);return t.success?{content:[{type:"text",text:JSON.stringify(t.data,null,2)}],isError:!1}:{content:[{type:"text",text:t.error||"Failed to get directions"}],isError:!0}}catch(e){return{isError:!0,content:[{type:"text",text:`Error getting directions: ${e instanceof Error?e.message:JSON.stringify(e)}`}]}}}var x={NAME:Ee,DESCRIPTION:be,SCHEMA:ve,ACTION:Pe};import{z as D}from"zod";var xe="maps_elevation",Ae="Get elevation (meters above sea level) for geographic coordinates. Use when the user asks 'how high is this place', 'is this area flood-prone', or needs altitude for hiking/cycling route profiles. Also useful for real estate risk assessment \u2014 low elevation near water suggests flood risk.",Ce={locations:D.array(D.object({latitude:D.number().describe("Latitude coordinate"),longitude:D.number().describe("Longitude coordinate")})).describe("List of locations to get elevation data for")};async function Ne(r){try{let e=n(),t=await new a(e).getElevation(r.locations);return t.success?{content:[{type:"text",text:JSON.stringify(t.data,null,2)}],isError:!1}:{content:[{type:"text",text:t.error||"Failed to get elevation data"}],isError:!0}}catch(e){return{isError:!0,content:[{type:"text",text:`Error getting elevation data: ${e instanceof Error?e.message:JSON.stringify(e)}`}]}}}var A={NAME:xe,DESCRIPTION:Ae,SCHEMA:Ce,ACTION:Ne};import{z as u}from"zod";var Me="maps_search_places",Oe="Search for places using a free-text query like 'sushi restaurants in Tokyo' or 'best coffee shops near Central Park'. More flexible than search_nearby \u2014 supports natural language queries, optional location bias, rating filters, and open-now filtering. Use when the user describes what they're looking for in words rather than by type and coordinates.",Te={query:u.string().describe("Text search query (e.g., 'Italian restaurants in Manhattan', 'hotels near Taipei 101')"),locationBias:u.object({latitude:u.number().describe("Latitude to bias results toward"),longitude:u.number().describe("Longitude to bias results toward"),radius:u.number().optional().describe("Bias radius in meters (default: 5000)")}).optional().describe("Optional location to bias results toward"),openNow:u.boolean().optional().describe("Only return places that are currently open"),minRating:u.number().optional().describe("Minimum rating filter (1.0 - 5.0)"),includedType:u.string().optional().describe("Filter by place type (e.g., restaurant, cafe, hotel)")};async function Ie(r){try{let e=n(),t=await new a(e).searchText({query:r.query,locationBias:r.locationBias,openNow:r.openNow,minRating:r.minRating,includedType:r.includedType});return t.success?{content:[{type:"text",text:JSON.stringify(t.data,null,2)}],isError:!1}:{content:[{type:"text",text:t.error||"Failed to search places"}],isError:!0}}catch(e){return{isError:!0,content:[{type:"text",text:`Error searching places: ${e instanceof Error?e.message:JSON.stringify(e)}`}]}}}var C={NAME:Me,DESCRIPTION:Oe,SCHEMA:Te,ACTION:Ie};import{z as G}from"zod";var we="maps_timezone",_e="Get the timezone and current local time for a location. Use when the user asks 'what time is it in Tokyo', needs to coordinate a meeting across timezones, or is planning travel across timezone boundaries. Returns timezone ID, UTC/DST offsets, and computed local time.",Re={latitude:G.number().describe("Latitude coordinate"),longitude:G.number().describe("Longitude coordinate"),timestamp:G.number().optional().describe("Unix timestamp in ms to query timezone at a specific moment (defaults to now)")};async function ze(r){try{let e=n(),t=await new a(e).getTimezone(r.latitude,r.longitude,r.timestamp);return t.success?{content:[{type:"text",text:JSON.stringify(t.data,null,2)}],isError:!1}:{content:[{type:"text",text:t.error||"Failed to get timezone data"}],isError:!0}}catch(e){return{isError:!0,content:[{type:"text",text:`Error getting timezone: ${e instanceof Error?e.message:JSON.stringify(e)}`}]}}}var N={NAME:we,DESCRIPTION:_e,SCHEMA:Re,ACTION:ze};import{z as M}from"zod";var Ke="maps_weather",De="Get weather for a location \u2014 current conditions, daily forecast (10 days), or hourly forecast (240 hours). Use when the user asks 'what's the weather in Paris', is planning outdoor activities, or needs to pack for a trip. Coverage: most regions supported, but China, Japan, South Korea, Cuba, Iran, North Korea, Syria are unavailable.",He={latitude:M.number().describe("Latitude coordinate"),longitude:M.number().describe("Longitude coordinate"),type:M.enum(["current","forecast_daily","forecast_hourly"]).optional().describe("current = right now, forecast_daily = multi-day outlook, forecast_hourly = hour-by-hour"),forecastDays:M.number().optional().describe("Number of forecast days (1-10, only for forecast_daily, default: 5)"),forecastHours:M.number().optional().describe("Number of forecast hours (1-240, only for forecast_hourly, default: 24)")};async function ke(r){try{let e=n(),t=await new a(e).getWeather(r.latitude,r.longitude,r.type||"current",r.forecastDays,r.forecastHours);return t.success?{content:[{type:"text",text:JSON.stringify(t.data,null,2)}],isError:!1}:{content:[{type:"text",text:t.error||"Failed to get weather data"}],isError:!0}}catch(e){return{isError:!0,content:[{type:"text",text:`Error getting weather: ${e instanceof Error?e.message:JSON.stringify(e)}`}]}}}var O={NAME:Ke,DESCRIPTION:De,SCHEMA:He,ACTION:ke};import{z as T}from"zod";var $e="maps_explore_area",Ge="Explore what's around a location in one call \u2014 searches multiple place types, gets details for the top results, and returns a categorized summary. Use when the user asks 'what's around here', 'explore the area near my hotel', or needs a quick overview of a neighborhood. Replaces the manual chain of geocode \u2192 search-nearby \u2192 place-details.",Je={location:T.string().describe("Address or landmark to explore around"),types:T.array(T.string()).optional().describe("Place types to search (default: restaurant, cafe, attraction). Examples: hotel, bar, park, museum"),radius:T.number().optional().describe("Search radius in meters (default: 1000)"),topN:T.number().optional().describe("Number of top results per type to get details for (default: 3)")};async function Le(r){try{let e=n(),t=await new a(e).exploreArea(r);return{content:[{type:"text",text:JSON.stringify(t.data,null,2)}],isError:!1}}catch(e){return{isError:!0,content:[{type:"text",text:`Error exploring area: ${e.message}`}]}}}var I={NAME:$e,DESCRIPTION:Ge,SCHEMA:Je,ACTION:Le};import{z as H}from"zod";var qe="maps_plan_route",je="Plan an optimized multi-stop route in one call \u2014 geocodes all stops, finds the most efficient visit order using distance-matrix, and returns step-by-step directions between each stop. Use when the user says 'visit these 5 places efficiently', 'plan a route through A, B, C', or needs a multi-stop itinerary. Replaces the manual chain of geocode \u2192 distance-matrix \u2192 directions.",Ue={stops:H.array(H.string()).min(2).describe("List of addresses or landmarks to visit (minimum 2)"),mode:H.enum(["driving","walking","bicycling","transit"]).optional().describe("Travel mode (default: driving)"),optimize:H.boolean().optional().describe("Auto-optimize visit order by nearest-neighbor (default: true). Set false to keep original order.")};async function We(r){try{let e=n(),t=await new a(e).planRoute(r);return{content:[{type:"text",text:JSON.stringify(t.data,null,2)}],isError:!1}}catch(e){return{isError:!0,content:[{type:"text",text:`Error planning route: ${e.message}`}]}}}var w={NAME:qe,DESCRIPTION:je,SCHEMA:Ue,ACTION:We};import{z as _}from"zod";var Fe="maps_compare_places",Ze="Compare multiple places side-by-side in one call \u2014 searches by query, gets details for each result, and optionally calculates distance from your location. Use when the user asks 'which restaurant should I pick', 'compare these hotels', or needs a decision table. Replaces the manual chain of search-places \u2192 place-details \u2192 distance-matrix.",Ve={query:_.string().describe("Search query (e.g., 'ramen near Shibuya', 'hotels in Taipei')"),userLocation:_.object({latitude:_.number().describe("Your latitude"),longitude:_.number().describe("Your longitude")}).optional().describe("Your current location \u2014 if provided, adds distance and drive time to each result"),limit:_.number().optional().describe("Max places to compare (default: 5)")};async function Ye(r){try{let e=n(),t=await new a(e).comparePlaces(r);return{content:[{type:"text",text:JSON.stringify(t.data,null,2)}],isError:!1}}catch(e){return{isError:!0,content:[{type:"text",text:`Error comparing places: ${e.message}`}]}}}var R={NAME:Fe,DESCRIPTION:Ze,SCHEMA:Ve,ACTION:Ye};var p={readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!0},Be=[{name:"MCP-Server",portEnvVar:"MCP_SERVER_PORT",tools:[{name:f.NAME,description:f.DESCRIPTION,schema:f.SCHEMA,annotations:p,action:r=>f.ACTION(r)},{name:h.NAME,description:h.DESCRIPTION,schema:h.SCHEMA,annotations:p,action:r=>h.ACTION(r)},{name:S.NAME,description:S.DESCRIPTION,schema:S.SCHEMA,annotations:p,action:r=>S.ACTION(r)},{name:E.NAME,description:E.DESCRIPTION,schema:E.SCHEMA,annotations:p,action:r=>E.ACTION(r)},{name:v.NAME,description:v.DESCRIPTION,schema:v.SCHEMA,annotations:p,action:r=>v.ACTION(r)},{name:x.NAME,description:x.DESCRIPTION,schema:x.SCHEMA,annotations:p,action:r=>x.ACTION(r)},{name:A.NAME,description:A.DESCRIPTION,schema:A.SCHEMA,annotations:p,action:r=>A.ACTION(r)},{name:C.NAME,description:C.DESCRIPTION,schema:C.SCHEMA,annotations:p,action:r=>C.ACTION(r)},{name:N.NAME,description:N.DESCRIPTION,schema:N.SCHEMA,annotations:p,action:r=>N.ACTION(r)},{name:O.NAME,description:O.DESCRIPTION,schema:O.SCHEMA,annotations:p,action:r=>O.ACTION(r)},{name:I.NAME,description:I.DESCRIPTION,schema:I.SCHEMA,annotations:p,action:r=>I.ACTION(r)},{name:w.NAME,description:w.DESCRIPTION,schema:w.SCHEMA,annotations:p,action:r=>w.ACTION(r)},{name:R.NAME,description:R.DESCRIPTION,schema:R.SCHEMA,annotations:p,action:r=>R.ACTION(r)}]}],k=Be;import{McpServer as Xe}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as Qe}from"@modelcontextprotocol/sdk/server/stdio.js";import{StreamableHTTPServerTransport as et}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{isInitializeRequest as tt}from"@modelcontextprotocol/sdk/types.js";import U from"express";import{randomUUID as rt}from"crypto";import{z as ot}from"zod";var z=class r{constructor(){this.defaultApiKey=process.env.GOOGLE_MAPS_API_KEY}static getInstance(){return r.instance||(r.instance=new r),r.instance}setDefaultApiKey(e){this.defaultApiKey=e,process.env.GOOGLE_MAPS_API_KEY=e}getApiKey(e,o){if(e){let t=e.headers["x-google-maps-api-key"];if(t)return t;let i=e.headers.authorization;if(i&&i.startsWith("Bearer "))return i.substring(7)}return o||this.defaultApiKey}hasApiKey(e,o){return!!this.getApiKey(e,o)}isValidApiKeyFormat(e){return/^[A-Za-z0-9_-]{20,50}$/.test(e)}};var st="0.0.1",K=class{constructor(e,o){this.sessions={};this.httpServer=null;this.serverName=e,this.tools=o,this.server=this.createMcpServer()}createMcpServer(){let e=new Xe({name:this.serverName,version:st},{capabilities:{logging:{},tools:{}}});return this.tools.forEach(o=>{e.registerTool(o.name,{description:o.description,inputSchema:ot.object(o.schema),annotations:o.annotations},async t=>o.action(t))}),e}async connect(e){await this.server.connect(e);let o=process.stdout.write.bind(process.stdout);process.stdout.write=(t,i,c)=>typeof t=="string"&&!t.startsWith("{")?!0:o(t,i,c),s.log(`${this.serverName} connected and ready to process requests`)}async startHttpServer(e){let o=U();o.use(U.json()),o.post("/mcp",async(i,c)=>{let l=i.headers["mcp-session-id"],d,y=z.getInstance().getApiKey(i);if(s.log(`${this.serverName} API key received from request context`),l&&this.sessions[l])d=this.sessions[l],y&&(d.apiKey=y);else if(!l&&tt(i.body)){let g=new et({sessionIdGenerator:()=>rt(),onsessioninitialized:L=>{this.sessions[L]=d,s.log(`[${this.serverName}] New session initialized: ${L}`)}});d={transport:g,apiKey:y},g.onclose=()=>{g.sessionId&&(delete this.sessions[g.sessionId],s.log(`[${this.serverName}] Session closed: ${g.sessionId}`))},await this.createMcpServer().connect(g)}else{c.status(400).json({jsonrpc:"2.0",error:{code:-32e3,message:"Bad Request: No valid session ID provided"},id:null});return}await $({apiKey:d.apiKey,sessionId:l},async()=>{await d.transport.handleRequest(i,c,i.body)})});let t=async(i,c)=>{let l=i.headers["mcp-session-id"];if(!l||!this.sessions[l]){c.status(400).send("Invalid or missing session ID");return}let d=this.sessions[l],y=z.getInstance().getApiKey(i);y&&(d.apiKey=y),await $({apiKey:d.apiKey,sessionId:l},async()=>{await d.transport.handleRequest(i,c)})};o.get("/mcp",t),o.delete("/mcp",t),this.httpServer=o.listen(e,()=>{s.log(`[${this.serverName}] HTTP server listening on port ${e}`),s.log(`[${this.serverName}] MCP endpoint available at http://localhost:${e}/mcp`)})}async startStdio(){let e=new Qe;await this.connect(e)}async stopHttpServer(){if(!this.httpServer){s.error(`[${this.serverName}] HTTP server is not running or already stopped.`);return}return new Promise((e,o)=>{this.httpServer.close(t=>{if(t){s.error(`[${this.serverName}] Error stopping HTTP server:`,t),o(t);return}s.log(`[${this.serverName}] HTTP server stopped.`),this.httpServer=null;let i=Object.values(this.sessions).map(c=>(c.transport.sessionId&&delete this.sessions[c.transport.sessionId],Promise.resolve()));Promise.all(i).then(()=>{s.log(`[${this.serverName}] All transports closed.`),e()}).catch(c=>{s.error(`[${this.serverName}] Error during bulk transport closing:`,c),o(c)})})})}};import{fileURLToPath as it}from"url";import{dirname as ct}from"path";import{readFileSync as lt}from"fs";var pt=it(import.meta.url),F=ct(pt);W({path:J(process.cwd(),".env")});W({path:J(F,"../.env")});async function dt(r,e){r&&(process.env.MCP_SERVER_PORT=r.toString()),e&&(process.env.GOOGLE_MAPS_API_KEY=e),s.log("\u{1F680} Starting Google Maps MCP Server..."),s.log("\u{1F4CD} Available tools: search_nearby, get_place_details, maps_geocode, maps_reverse_geocode, maps_distance_matrix, maps_directions, maps_elevation, echo"),s.log("\u2139\uFE0F Reminder: enable Places API (New) in https://console.cloud.google.com before using the new Place features."),s.log("");let o=k.map(async t=>{let i=process.env[t.portEnvVar];if(!i){s.error(`\u26A0\uFE0F [${t.name}] Port environment variable ${t.portEnvVar} not set.`),s.log(`\u{1F4A1} Please set ${t.portEnvVar} in your .env file or use --port parameter.`),s.log(` Example: ${t.portEnvVar}=3000 or --port 3000`);return}let c=Number(i);if(isNaN(c)||c<=0){s.error(`\u274C [${t.name}] Invalid port number "${i}" defined in ${t.portEnvVar}.`);return}try{let l=new K(t.name,t.tools);s.log(`\u{1F527} [${t.name}] Initializing MCP Server in HTTP mode on port ${c}...`),await l.startHttpServer(c),s.log(`\u2705 [${t.name}] MCP Server started successfully!`),s.log(` \u{1F310} Endpoint: http://localhost:${c}/mcp`),s.log(` \u{1F4DA} Tools: ${t.tools.length} available`)}catch(l){s.error(`\u274C [${t.name}] Failed to start MCP Server on port ${c}:`,l)}});await Promise.allSettled(o),s.log(""),s.log("\u{1F389} Server initialization completed!"),s.log("\u{1F4A1} Need help? Check the README.md for configuration details.")}var Z=["geocode","reverse-geocode","search-nearby","search-places","place-details","directions","distance-matrix","elevation","timezone","weather","explore-area","plan-route","compare-places"];async function ut(r,e,o){let t=new a(o);switch(r){case"geocode":case"maps_geocode":return t.geocode(e.address);case"reverse-geocode":case"maps_reverse_geocode":return t.reverseGeocode(e.latitude,e.longitude);case"search-nearby":case"search_nearby":case"maps_search_nearby":return t.searchNearby(e);case"search-places":case"maps_search_places":return t.searchText({query:e.query,locationBias:e.locationBias,openNow:e.openNow,minRating:e.minRating,includedType:e.includedType});case"place-details":case"get_place_details":case"maps_place_details":return t.getPlaceDetails(e.placeId);case"directions":case"maps_directions":return t.getDirections(e.origin,e.destination,e.mode,e.departure_time,e.arrival_time);case"distance-matrix":case"maps_distance_matrix":return t.calculateDistanceMatrix(e.origins,e.destinations,e.mode);case"elevation":case"maps_elevation":return t.getElevation(e.locations);case"timezone":case"maps_timezone":return t.getTimezone(e.latitude,e.longitude,e.timestamp);case"weather":case"maps_weather":return t.getWeather(e.latitude,e.longitude,e.type,e.forecastDays,e.forecastHours);case"explore-area":case"maps_explore_area":return t.exploreArea(e);case"plan-route":case"maps_plan_route":return t.planRoute(e);case"compare-places":case"maps_compare_places":return t.comparePlaces(e);default:throw new Error(`Unknown tool: ${r}. Available: ${Z.join(", ")}`)}}var mt=process.argv[1]&&(process.argv[1].endsWith("cli.ts")||process.argv[1].endsWith("cli.js")||process.argv[1].endsWith("mcp-google-map")||process.argv[1].includes("mcp-google-map")),yt=import.meta.url===`file://${process.argv[1]}`;if(mt||yt){let r="0.0.0";try{let e=J(F,"../package.json");r=JSON.parse(lt(e,"utf-8")).version}catch{r="0.0.0"}at(nt(process.argv)).command("exec <tool> [params]","Execute a tool directly and output JSON",e=>e.positional("tool",{type:"string",describe:`Tool name: ${Z.join(", ")}`}).positional("params",{type:"string",describe:"JSON parameters string"}).option("apikey",{alias:"k",type:"string",description:"Google Maps API key",default:process.env.GOOGLE_MAPS_API_KEY}).example([[`$0 exec geocode '{"address":"Tokyo Tower"}'`,"Geocode an address"],[`$0 exec search-nearby '{"center":{"value":"35.68,139.74","isCoordinates":true},"keyword":"restaurant"}'`,"Search nearby"],[`$0 exec search-places '{"query":"ramen in Tokyo"}'`,"Text search"]]),async e=>{e.apikey||(console.error(JSON.stringify({error:"GOOGLE_MAPS_API_KEY not set. Use --apikey or set GOOGLE_MAPS_API_KEY environment variable."},null,2)),process.exit(1));try{let o=e.params?JSON.parse(e.params):{},t=await ut(e.tool,o,e.apikey);console.log(JSON.stringify(t,null,2)),process.exit(0)}catch(o){console.error(JSON.stringify({error:o.message},null,2)),process.exit(1)}}).command("$0","Start the MCP server (HTTP by default, --stdio for stdio mode)",e=>e.option("port",{alias:"p",type:"number",description:"Port to run the MCP server on",default:process.env.MCP_SERVER_PORT?parseInt(process.env.MCP_SERVER_PORT):3e3}).option("apikey",{alias:"k",type:"string",description:"Google Maps API key",default:process.env.GOOGLE_MAPS_API_KEY}).option("stdio",{type:"boolean",description:"Use stdio transport instead of HTTP",default:!1}).example([["$0","Start HTTP server with default settings"],['$0 --port 3000 --apikey "your_api_key"',"Start HTTP with custom port and API key"],["$0 --stdio","Start in stdio mode (for Claude Desktop, Cursor, etc.)"]]),async e=>{e.apikey&&(process.env.GOOGLE_MAPS_API_KEY=e.apikey),e.stdio?await new K(k[0].name,k[0].tools).startStdio():(s.log("\u{1F5FA}\uFE0F Google Maps MCP Server"),s.log(" A Model Context Protocol server for Google Maps services"),s.log(""),e.apikey||(s.log("\u26A0\uFE0F Google Maps API Key not found!"),s.log(" Please provide --apikey parameter or set GOOGLE_MAPS_API_KEY in your .env file"),s.log("")),dt(e.port,e.apikey).catch(o=>{s.error("\u274C Failed to start server:",o),process.exit(1)}))}).version(r).alias("version","v").help().parse()}export{dt as startServer};
|
|
2
|
+
import{b as s,c as a}from"./chunk-ME57GONJ.js";import{config as Z}from"dotenv";import{resolve as L}from"path";import dt from"yargs";import{hideBin as ut}from"yargs/helpers";import{z as m}from"zod";import{AsyncLocalStorage as Q}from"async_hooks";var U=new Q;function n(){return U.getStore()?.apiKey||process.env.GOOGLE_MAPS_API_KEY}function J(r,e){return U.run(r,e)}var X="maps_search_nearby",ee="Find places near a specific location by type (e.g., restaurants, cafes, hotels). Use when the user wants to discover what's around a given address or coordinates, such as 'find coffee shops near Times Square' or 'what hotels are near the airport'. Supports filtering by place type, search radius, minimum rating, and whether currently open.",te={center:m.object({value:m.string().describe("Address, landmark name, or coordinates (coordinate format: lat,lng)"),isCoordinates:m.boolean().default(!1).describe("Whether the value is coordinates")}).describe("Search center point (e.g. value: 49.3268778,-123.0585982, isCoordinates: true)"),keyword:m.string().optional().describe("Place type to search for (e.g., restaurant, cafe, hotel, gas_station, hospital)"),radius:m.number().default(1e3).describe("Search radius in meters"),openNow:m.boolean().default(!1).describe("Only show places that are currently open"),minRating:m.number().min(0).max(5).optional().describe("Minimum rating requirement (0-5)")};async function re(r){try{let e=n(),t=await new a(e).searchNearby(r);return t.success?{content:[{type:"text",text:`location: ${JSON.stringify(t.location,null,2)}
|
|
3
|
+
`+JSON.stringify(t.data,null,2)}],isError:!1}:{content:[{type:"text",text:t.error||"Search failed"}],isError:!0}}catch(e){return{isError:!0,content:[{type:"text",text:`Error searching nearby places: ${e instanceof Error?e.message:JSON.stringify(e)}`}]}}}var f={NAME:X,DESCRIPTION:ee,SCHEMA:te,ACTION:re};import{z as oe}from"zod";var se="maps_place_details",ae="Get comprehensive details for a specific place using its Google Maps place_id. Use after search_nearby or maps_search_places to get full information including reviews, phone number, website, opening hours, and photos. Returns everything needed to evaluate or contact a business.",ne={placeId:oe.string().describe("Google Maps place ID")};async function ie(r){try{let e=n(),t=await new a(e).getPlaceDetails(r.placeId);return t.success?{content:[{type:"text",text:JSON.stringify(t.data,null,2)}],isError:!1}:{content:[{type:"text",text:t.error||"Failed to get place details"}],isError:!0}}catch(e){return{isError:!0,content:[{type:"text",text:`Error getting place details: ${e instanceof Error?e.message:JSON.stringify(e)}`}]}}}var h={NAME:se,DESCRIPTION:ae,SCHEMA:ne,ACTION:ie};import{z as ce}from"zod";var le="maps_geocode",pe="Convert an address, city name, or landmark into GPS coordinates (latitude/longitude). Use when you need coordinates for a location described in text \u2014 for example, to provide a center point for search_nearby or a starting point for maps_directions.",de={address:ce.string().describe("Address or place name to convert to coordinates")};async function ue(r){try{let e=n(),t=await new a(e).geocode(r.address);return t.success?{content:[{type:"text",text:JSON.stringify(t.data,null,2)}],isError:!1}:{content:[{type:"text",text:t.error||"Failed to geocode address"}],isError:!0}}catch(e){return{isError:!0,content:[{type:"text",text:`Error geocoding address: ${e instanceof Error?e.message:JSON.stringify(e)}`}]}}}var S={NAME:le,DESCRIPTION:pe,SCHEMA:de,ACTION:ue};import{z as W}from"zod";var me="maps_reverse_geocode",ye="Convert GPS coordinates (latitude/longitude) into a human-readable street address. Use when you have coordinates from another tool's output or a user's shared location and need the actual address.",ge={latitude:W.number().describe("Latitude coordinate"),longitude:W.number().describe("Longitude coordinate")};async function fe(r){try{let e=n(),t=await new a(e).reverseGeocode(r.latitude,r.longitude);return t.success?{content:[{type:"text",text:JSON.stringify(t.data,null,2)}],isError:!1}:{content:[{type:"text",text:t.error||"Failed to reverse geocode coordinates"}],isError:!0}}catch(e){return{isError:!0,content:[{type:"text",text:`Error reverse geocoding: ${e instanceof Error?e.message:JSON.stringify(e)}`}]}}}var E={NAME:me,DESCRIPTION:ye,SCHEMA:ge,ACTION:fe};import{z as b}from"zod";var he="maps_distance_matrix",Se="Calculate travel distances and durations between multiple origins and destinations in a single request. Use for comparing travel options \u2014 e.g., 'which hotel is closest to the office?' or batch distance calculations. Supports driving, walking, bicycling, and transit modes.",Ee={origins:b.array(b.string()).describe("List of origin addresses or coordinates"),destinations:b.array(b.string()).describe("List of destination addresses or coordinates"),mode:b.enum(["driving","walking","bicycling","transit"]).default("driving").describe("Travel mode for calculation")};async function be(r){try{let e=n(),t=await new a(e).calculateDistanceMatrix(r.origins,r.destinations,r.mode);return t.success?{content:[{type:"text",text:JSON.stringify(t.data,null,2)}],isError:!1}:{content:[{type:"text",text:t.error||"Failed to calculate distance matrix"}],isError:!0}}catch(e){return{isError:!0,content:[{type:"text",text:`Error calculating distance matrix: ${e instanceof Error?e.message:JSON.stringify(e)}`}]}}}var P={NAME:he,DESCRIPTION:Se,SCHEMA:Ee,ACTION:be};import{z as v}from"zod";var Pe="maps_directions",ve="Get step-by-step navigation directions between two points with route details. Use when the user asks 'how do I get from A to B?' and needs the route summary, total distance, estimated travel time, or turn-by-turn instructions. Supports departure/arrival times and multiple travel modes.",Ae={origin:v.string().describe("Starting point address or coordinates"),destination:v.string().describe("Destination address or coordinates"),mode:v.enum(["driving","walking","bicycling","transit"]).default("driving").describe("Travel mode for directions"),departure_time:v.string().optional().describe("Departure time (ISO string format)"),arrival_time:v.string().optional().describe("Arrival time (ISO string format)")};async function xe(r){try{let e=n(),t=await new a(e).getDirections(r.origin,r.destination,r.mode,r.departure_time,r.arrival_time);return t.success?{content:[{type:"text",text:JSON.stringify(t.data,null,2)}],isError:!1}:{content:[{type:"text",text:t.error||"Failed to get directions"}],isError:!0}}catch(e){return{isError:!0,content:[{type:"text",text:`Error getting directions: ${e instanceof Error?e.message:JSON.stringify(e)}`}]}}}var A={NAME:Pe,DESCRIPTION:ve,SCHEMA:Ae,ACTION:xe};import{z as D}from"zod";var Ce="maps_elevation",Ne="Get elevation (meters above sea level) for geographic coordinates. Use when the user asks 'how high is this place', 'is this area flood-prone', or needs altitude for hiking/cycling route profiles. Also useful for real estate risk assessment \u2014 low elevation near water suggests flood risk.",Me={locations:D.array(D.object({latitude:D.number().describe("Latitude coordinate"),longitude:D.number().describe("Longitude coordinate")})).describe("List of locations to get elevation data for")};async function Oe(r){try{let e=n(),t=await new a(e).getElevation(r.locations);return t.success?{content:[{type:"text",text:JSON.stringify(t.data,null,2)}],isError:!1}:{content:[{type:"text",text:t.error||"Failed to get elevation data"}],isError:!0}}catch(e){return{isError:!0,content:[{type:"text",text:`Error getting elevation data: ${e instanceof Error?e.message:JSON.stringify(e)}`}]}}}var x={NAME:Ce,DESCRIPTION:Ne,SCHEMA:Me,ACTION:Oe};import{z as u}from"zod";var Ie="maps_search_places",Te="Search for places using a free-text query like 'sushi restaurants in Tokyo' or 'best coffee shops near Central Park'. More flexible than search_nearby \u2014 supports natural language queries, optional location bias, rating filters, and open-now filtering. Use when the user describes what they're looking for in words rather than by type and coordinates.",we={query:u.string().describe("Text search query (e.g., 'Italian restaurants in Manhattan', 'hotels near Taipei 101')"),locationBias:u.object({latitude:u.number().describe("Latitude to bias results toward"),longitude:u.number().describe("Longitude to bias results toward"),radius:u.number().optional().describe("Bias radius in meters (default: 5000)")}).optional().describe("Optional location to bias results toward"),openNow:u.boolean().optional().describe("Only return places that are currently open"),minRating:u.number().optional().describe("Minimum rating filter (1.0 - 5.0)"),includedType:u.string().optional().describe("Filter by place type (e.g., restaurant, cafe, hotel)")};async function _e(r){try{let e=n(),t=await new a(e).searchText({query:r.query,locationBias:r.locationBias,openNow:r.openNow,minRating:r.minRating,includedType:r.includedType});return t.success?{content:[{type:"text",text:JSON.stringify(t.data,null,2)}],isError:!1}:{content:[{type:"text",text:t.error||"Failed to search places"}],isError:!0}}catch(e){return{isError:!0,content:[{type:"text",text:`Error searching places: ${e instanceof Error?e.message:JSON.stringify(e)}`}]}}}var C={NAME:Ie,DESCRIPTION:Te,SCHEMA:we,ACTION:_e};import{z as q}from"zod";var Re="maps_timezone",ze="Get the timezone and current local time for a location. Use when the user asks 'what time is it in Tokyo', needs to coordinate a meeting across timezones, or is planning travel across timezone boundaries. Returns timezone ID, UTC/DST offsets, and computed local time.",Ke={latitude:q.number().describe("Latitude coordinate"),longitude:q.number().describe("Longitude coordinate"),timestamp:q.number().optional().describe("Unix timestamp in ms to query timezone at a specific moment (defaults to now)")};async function He(r){try{let e=n(),t=await new a(e).getTimezone(r.latitude,r.longitude,r.timestamp);return t.success?{content:[{type:"text",text:JSON.stringify(t.data,null,2)}],isError:!1}:{content:[{type:"text",text:t.error||"Failed to get timezone data"}],isError:!0}}catch(e){return{isError:!0,content:[{type:"text",text:`Error getting timezone: ${e instanceof Error?e.message:JSON.stringify(e)}`}]}}}var N={NAME:Re,DESCRIPTION:ze,SCHEMA:Ke,ACTION:He};import{z as M}from"zod";var De="maps_weather",ke="Get weather for a location \u2014 current conditions, daily forecast (10 days), or hourly forecast (240 hours). Use when the user asks 'what's the weather in Paris', is planning outdoor activities, or needs to pack for a trip. Coverage: most regions supported, but China, Japan, South Korea, Cuba, Iran, North Korea, Syria are unavailable.",$e={latitude:M.number().describe("Latitude coordinate"),longitude:M.number().describe("Longitude coordinate"),type:M.enum(["current","forecast_daily","forecast_hourly"]).optional().describe("current = right now, forecast_daily = multi-day outlook, forecast_hourly = hour-by-hour"),forecastDays:M.number().optional().describe("Number of forecast days (1-10, only for forecast_daily, default: 5)"),forecastHours:M.number().optional().describe("Number of forecast hours (1-240, only for forecast_hourly, default: 24)")};async function Ge(r){try{let e=n(),t=await new a(e).getWeather(r.latitude,r.longitude,r.type||"current",r.forecastDays,r.forecastHours);return t.success?{content:[{type:"text",text:JSON.stringify(t.data,null,2)}],isError:!1}:{content:[{type:"text",text:t.error||"Failed to get weather data"}],isError:!0}}catch(e){return{isError:!0,content:[{type:"text",text:`Error getting weather: ${e instanceof Error?e.message:JSON.stringify(e)}`}]}}}var O={NAME:De,DESCRIPTION:ke,SCHEMA:$e,ACTION:Ge};import{z as I}from"zod";var Je="maps_explore_area",qe="Explore what's around a location in one call \u2014 searches multiple place types, gets details for the top results, and returns a categorized summary. Use when the user asks 'what's around here', 'explore the area near my hotel', or needs a quick overview of a neighborhood. Replaces the manual chain of geocode \u2192 search-nearby \u2192 place-details.",Le={location:I.string().describe("Address or landmark to explore around"),types:I.array(I.string()).optional().describe("Place types to search (default: restaurant, cafe, attraction). Examples: hotel, bar, park, museum"),radius:I.number().optional().describe("Search radius in meters (default: 1000)"),topN:I.number().optional().describe("Number of top results per type to get details for (default: 3)")};async function je(r){try{let e=n(),t=await new a(e).exploreArea(r);return{content:[{type:"text",text:JSON.stringify(t.data,null,2)}],isError:!1}}catch(e){return{isError:!0,content:[{type:"text",text:`Error exploring area: ${e.message}`}]}}}var T={NAME:Je,DESCRIPTION:qe,SCHEMA:Le,ACTION:je};import{z as k}from"zod";var Ue="maps_plan_route",We="Plan an optimized multi-stop route in one call \u2014 geocodes all stops, finds the most efficient visit order using distance-matrix, and returns step-by-step directions between each stop. Use when the user says 'visit these 5 places efficiently', 'plan a route through A, B, C', or needs a multi-stop itinerary. Replaces the manual chain of geocode \u2192 distance-matrix \u2192 directions.",Fe={stops:k.array(k.string()).min(2).describe("List of addresses or landmarks to visit (minimum 2)"),mode:k.enum(["driving","walking","bicycling","transit"]).optional().describe("Travel mode (default: driving)"),optimize:k.boolean().optional().describe("Auto-optimize visit order by nearest-neighbor (default: true). Set false to keep original order.")};async function Ze(r){try{let e=n(),t=await new a(e).planRoute(r);return{content:[{type:"text",text:JSON.stringify(t.data,null,2)}],isError:!1}}catch(e){return{isError:!0,content:[{type:"text",text:`Error planning route: ${e.message}`}]}}}var w={NAME:Ue,DESCRIPTION:We,SCHEMA:Fe,ACTION:Ze};import{z as _}from"zod";var Ve="maps_compare_places",Ye="Compare multiple places side-by-side in one call \u2014 searches by query, gets details for each result, and optionally calculates distance from your location. Use when the user asks 'which restaurant should I pick', 'compare these hotels', or needs a decision table. Replaces the manual chain of search-places \u2192 place-details \u2192 distance-matrix.",Be={query:_.string().describe("Search query (e.g., 'ramen near Shibuya', 'hotels in Taipei')"),userLocation:_.object({latitude:_.number().describe("Your latitude"),longitude:_.number().describe("Your longitude")}).optional().describe("Your current location \u2014 if provided, adds distance and drive time to each result"),limit:_.number().optional().describe("Max places to compare (default: 5)")};async function Qe(r){try{let e=n(),t=await new a(e).comparePlaces(r);return{content:[{type:"text",text:JSON.stringify(t.data,null,2)}],isError:!1}}catch(e){return{isError:!0,content:[{type:"text",text:`Error comparing places: ${e.message}`}]}}}var R={NAME:Ve,DESCRIPTION:Ye,SCHEMA:Be,ACTION:Qe};import{z as $}from"zod";var Xe="maps_air_quality",et="Get air quality for a location \u2014 AQI index, pollutant concentrations, and health recommendations by demographic group (elderly, children, athletes, pregnant women, etc.). Use when the user asks 'is the air safe', 'should I wear a mask', 'good for outdoor exercise', or is planning travel for someone with respiratory/heart conditions. Coverage: global including Japan (unlike weather). Returns both universal AQI and local index (EPA for US, AEROS for Japan, etc.).",tt={latitude:$.number().describe("Latitude coordinate"),longitude:$.number().describe("Longitude coordinate"),includeHealthRecommendations:$.boolean().optional().describe("Include health advice per demographic group (default: true)"),includePollutants:$.boolean().optional().describe("Include individual pollutant concentrations \u2014 PM2.5, PM10, NO2, O3, CO, SO2 (default: false)")};async function rt(r){try{let e=n(),t=await new a(e).getAirQuality(r.latitude,r.longitude,r.includeHealthRecommendations,r.includePollutants);return t.success?{content:[{type:"text",text:JSON.stringify(t.data,null,2)}],isError:!1}:{content:[{type:"text",text:t.error||"Failed to get air quality data"}],isError:!0}}catch(e){return{isError:!0,content:[{type:"text",text:`Error getting air quality: ${e instanceof Error?e.message:JSON.stringify(e)}`}]}}}var z={NAME:Xe,DESCRIPTION:et,SCHEMA:tt,ACTION:rt};var p={readOnlyHint:!0,destructiveHint:!1,idempotentHint:!0,openWorldHint:!0},ot=[{name:"MCP-Server",portEnvVar:"MCP_SERVER_PORT",tools:[{name:f.NAME,description:f.DESCRIPTION,schema:f.SCHEMA,annotations:p,action:r=>f.ACTION(r)},{name:h.NAME,description:h.DESCRIPTION,schema:h.SCHEMA,annotations:p,action:r=>h.ACTION(r)},{name:S.NAME,description:S.DESCRIPTION,schema:S.SCHEMA,annotations:p,action:r=>S.ACTION(r)},{name:E.NAME,description:E.DESCRIPTION,schema:E.SCHEMA,annotations:p,action:r=>E.ACTION(r)},{name:P.NAME,description:P.DESCRIPTION,schema:P.SCHEMA,annotations:p,action:r=>P.ACTION(r)},{name:A.NAME,description:A.DESCRIPTION,schema:A.SCHEMA,annotations:p,action:r=>A.ACTION(r)},{name:x.NAME,description:x.DESCRIPTION,schema:x.SCHEMA,annotations:p,action:r=>x.ACTION(r)},{name:C.NAME,description:C.DESCRIPTION,schema:C.SCHEMA,annotations:p,action:r=>C.ACTION(r)},{name:N.NAME,description:N.DESCRIPTION,schema:N.SCHEMA,annotations:p,action:r=>N.ACTION(r)},{name:O.NAME,description:O.DESCRIPTION,schema:O.SCHEMA,annotations:p,action:r=>O.ACTION(r)},{name:T.NAME,description:T.DESCRIPTION,schema:T.SCHEMA,annotations:p,action:r=>T.ACTION(r)},{name:w.NAME,description:w.DESCRIPTION,schema:w.SCHEMA,annotations:p,action:r=>w.ACTION(r)},{name:R.NAME,description:R.DESCRIPTION,schema:R.SCHEMA,annotations:p,action:r=>R.ACTION(r)},{name:z.NAME,description:z.DESCRIPTION,schema:z.SCHEMA,annotations:p,action:r=>z.ACTION(r)}]}],G=ot;import{McpServer as st}from"@modelcontextprotocol/sdk/server/mcp.js";import{StdioServerTransport as at}from"@modelcontextprotocol/sdk/server/stdio.js";import{StreamableHTTPServerTransport as nt}from"@modelcontextprotocol/sdk/server/streamableHttp.js";import{isInitializeRequest as it}from"@modelcontextprotocol/sdk/types.js";import F from"express";import{randomUUID as ct}from"crypto";import{z as lt}from"zod";var K=class r{constructor(){this.defaultApiKey=process.env.GOOGLE_MAPS_API_KEY}static getInstance(){return r.instance||(r.instance=new r),r.instance}setDefaultApiKey(e){this.defaultApiKey=e,process.env.GOOGLE_MAPS_API_KEY=e}getApiKey(e,o){if(e){let t=e.headers["x-google-maps-api-key"];if(t)return t;let i=e.headers.authorization;if(i&&i.startsWith("Bearer "))return i.substring(7)}return o||this.defaultApiKey}hasApiKey(e,o){return!!this.getApiKey(e,o)}isValidApiKeyFormat(e){return/^[A-Za-z0-9_-]{20,50}$/.test(e)}};var pt="0.0.1",H=class{constructor(e,o){this.sessions={};this.httpServer=null;this.serverName=e,this.tools=o,this.server=this.createMcpServer()}createMcpServer(){let e=new st({name:this.serverName,version:pt},{capabilities:{logging:{},tools:{}}});return this.tools.forEach(o=>{e.registerTool(o.name,{description:o.description,inputSchema:lt.object(o.schema),annotations:o.annotations},async t=>o.action(t))}),e}async connect(e){await this.server.connect(e);let o=process.stdout.write.bind(process.stdout);process.stdout.write=(t,i,c)=>typeof t=="string"&&!t.startsWith("{")?!0:o(t,i,c),s.log(`${this.serverName} connected and ready to process requests`)}async startHttpServer(e){let o=F();o.use(F.json()),o.post("/mcp",async(i,c)=>{let l=i.headers["mcp-session-id"],d,y=K.getInstance().getApiKey(i);if(s.log(`${this.serverName} API key received from request context`),l&&this.sessions[l])d=this.sessions[l],y&&(d.apiKey=y);else if(!l&&it(i.body)){let g=new nt({sessionIdGenerator:()=>ct(),onsessioninitialized:j=>{this.sessions[j]=d,s.log(`[${this.serverName}] New session initialized: ${j}`)}});d={transport:g,apiKey:y},g.onclose=()=>{g.sessionId&&(delete this.sessions[g.sessionId],s.log(`[${this.serverName}] Session closed: ${g.sessionId}`))},await this.createMcpServer().connect(g)}else{c.status(400).json({jsonrpc:"2.0",error:{code:-32e3,message:"Bad Request: No valid session ID provided"},id:null});return}await J({apiKey:d.apiKey,sessionId:l},async()=>{await d.transport.handleRequest(i,c,i.body)})});let t=async(i,c)=>{let l=i.headers["mcp-session-id"];if(!l||!this.sessions[l]){c.status(400).send("Invalid or missing session ID");return}let d=this.sessions[l],y=K.getInstance().getApiKey(i);y&&(d.apiKey=y),await J({apiKey:d.apiKey,sessionId:l},async()=>{await d.transport.handleRequest(i,c)})};o.get("/mcp",t),o.delete("/mcp",t),this.httpServer=o.listen(e,()=>{s.log(`[${this.serverName}] HTTP server listening on port ${e}`),s.log(`[${this.serverName}] MCP endpoint available at http://localhost:${e}/mcp`)})}async startStdio(){let e=new at;await this.connect(e)}async stopHttpServer(){if(!this.httpServer){s.error(`[${this.serverName}] HTTP server is not running or already stopped.`);return}return new Promise((e,o)=>{this.httpServer.close(t=>{if(t){s.error(`[${this.serverName}] Error stopping HTTP server:`,t),o(t);return}s.log(`[${this.serverName}] HTTP server stopped.`),this.httpServer=null;let i=Object.values(this.sessions).map(c=>(c.transport.sessionId&&delete this.sessions[c.transport.sessionId],Promise.resolve()));Promise.all(i).then(()=>{s.log(`[${this.serverName}] All transports closed.`),e()}).catch(c=>{s.error(`[${this.serverName}] Error during bulk transport closing:`,c),o(c)})})})}};import{fileURLToPath as mt}from"url";import{dirname as yt}from"path";import{readFileSync as gt}from"fs";var ft=mt(import.meta.url),V=yt(ft);Z({path:L(process.cwd(),".env")});Z({path:L(V,"../.env")});async function ht(r,e){r&&(process.env.MCP_SERVER_PORT=r.toString()),e&&(process.env.GOOGLE_MAPS_API_KEY=e),s.log("\u{1F680} Starting Google Maps MCP Server..."),s.log("\u{1F4CD} Available tools: search_nearby, get_place_details, maps_geocode, maps_reverse_geocode, maps_distance_matrix, maps_directions, maps_elevation, echo"),s.log("\u2139\uFE0F Reminder: enable Places API (New) in https://console.cloud.google.com before using the new Place features."),s.log("");let o=G.map(async t=>{let i=process.env[t.portEnvVar];if(!i){s.error(`\u26A0\uFE0F [${t.name}] Port environment variable ${t.portEnvVar} not set.`),s.log(`\u{1F4A1} Please set ${t.portEnvVar} in your .env file or use --port parameter.`),s.log(` Example: ${t.portEnvVar}=3000 or --port 3000`);return}let c=Number(i);if(isNaN(c)||c<=0){s.error(`\u274C [${t.name}] Invalid port number "${i}" defined in ${t.portEnvVar}.`);return}try{let l=new H(t.name,t.tools);s.log(`\u{1F527} [${t.name}] Initializing MCP Server in HTTP mode on port ${c}...`),await l.startHttpServer(c),s.log(`\u2705 [${t.name}] MCP Server started successfully!`),s.log(` \u{1F310} Endpoint: http://localhost:${c}/mcp`),s.log(` \u{1F4DA} Tools: ${t.tools.length} available`)}catch(l){s.error(`\u274C [${t.name}] Failed to start MCP Server on port ${c}:`,l)}});await Promise.allSettled(o),s.log(""),s.log("\u{1F389} Server initialization completed!"),s.log("\u{1F4A1} Need help? Check the README.md for configuration details.")}var Y=["geocode","reverse-geocode","search-nearby","search-places","place-details","directions","distance-matrix","elevation","timezone","weather","explore-area","plan-route","compare-places","air-quality"];async function St(r,e,o){let t=new a(o);switch(r){case"geocode":case"maps_geocode":return t.geocode(e.address);case"reverse-geocode":case"maps_reverse_geocode":return t.reverseGeocode(e.latitude,e.longitude);case"search-nearby":case"search_nearby":case"maps_search_nearby":return t.searchNearby(e);case"search-places":case"maps_search_places":return t.searchText({query:e.query,locationBias:e.locationBias,openNow:e.openNow,minRating:e.minRating,includedType:e.includedType});case"place-details":case"get_place_details":case"maps_place_details":return t.getPlaceDetails(e.placeId);case"directions":case"maps_directions":return t.getDirections(e.origin,e.destination,e.mode,e.departure_time,e.arrival_time);case"distance-matrix":case"maps_distance_matrix":return t.calculateDistanceMatrix(e.origins,e.destinations,e.mode);case"elevation":case"maps_elevation":return t.getElevation(e.locations);case"timezone":case"maps_timezone":return t.getTimezone(e.latitude,e.longitude,e.timestamp);case"weather":case"maps_weather":return t.getWeather(e.latitude,e.longitude,e.type,e.forecastDays,e.forecastHours);case"explore-area":case"maps_explore_area":return t.exploreArea(e);case"plan-route":case"maps_plan_route":return t.planRoute(e);case"compare-places":case"maps_compare_places":return t.comparePlaces(e);case"air-quality":case"maps_air_quality":return t.getAirQuality(e.latitude,e.longitude,e.includeHealthRecommendations,e.includePollutants);default:throw new Error(`Unknown tool: ${r}. Available: ${Y.join(", ")}`)}}var Et=process.argv[1]&&(process.argv[1].endsWith("cli.ts")||process.argv[1].endsWith("cli.js")||process.argv[1].endsWith("mcp-google-map")||process.argv[1].includes("mcp-google-map")),bt=import.meta.url===`file://${process.argv[1]}`;if(Et||bt){let r="0.0.0";try{let e=L(V,"../package.json");r=JSON.parse(gt(e,"utf-8")).version}catch{r="0.0.0"}dt(ut(process.argv)).command("exec <tool> [params]","Execute a tool directly and output JSON",e=>e.positional("tool",{type:"string",describe:`Tool name: ${Y.join(", ")}`}).positional("params",{type:"string",describe:"JSON parameters string"}).option("apikey",{alias:"k",type:"string",description:"Google Maps API key",default:process.env.GOOGLE_MAPS_API_KEY}).example([[`$0 exec geocode '{"address":"Tokyo Tower"}'`,"Geocode an address"],[`$0 exec search-nearby '{"center":{"value":"35.68,139.74","isCoordinates":true},"keyword":"restaurant"}'`,"Search nearby"],[`$0 exec search-places '{"query":"ramen in Tokyo"}'`,"Text search"]]),async e=>{e.apikey||(console.error(JSON.stringify({error:"GOOGLE_MAPS_API_KEY not set. Use --apikey or set GOOGLE_MAPS_API_KEY environment variable."},null,2)),process.exit(1));try{let o=e.params?JSON.parse(e.params):{},t=await St(e.tool,o,e.apikey);console.log(JSON.stringify(t,null,2)),process.exit(0)}catch(o){console.error(JSON.stringify({error:o.message},null,2)),process.exit(1)}}).command("$0","Start the MCP server (HTTP by default, --stdio for stdio mode)",e=>e.option("port",{alias:"p",type:"number",description:"Port to run the MCP server on",default:process.env.MCP_SERVER_PORT?parseInt(process.env.MCP_SERVER_PORT):3e3}).option("apikey",{alias:"k",type:"string",description:"Google Maps API key",default:process.env.GOOGLE_MAPS_API_KEY}).option("stdio",{type:"boolean",description:"Use stdio transport instead of HTTP",default:!1}).example([["$0","Start HTTP server with default settings"],['$0 --port 3000 --apikey "your_api_key"',"Start HTTP with custom port and API key"],["$0 --stdio","Start in stdio mode (for Claude Desktop, Cursor, etc.)"]]),async e=>{e.apikey&&(process.env.GOOGLE_MAPS_API_KEY=e.apikey),e.stdio?await new H(G[0].name,G[0].tools).startStdio():(s.log("\u{1F5FA}\uFE0F Google Maps MCP Server"),s.log(" A Model Context Protocol server for Google Maps services"),s.log(""),e.apikey||(s.log("\u26A0\uFE0F Google Maps API Key not found!"),s.log(" Please provide --apikey parameter or set GOOGLE_MAPS_API_KEY in your .env file"),s.log("")),ht(e.port,e.apikey).catch(o=>{s.error("\u274C Failed to start server:",o),process.exit(1)}))}).version(r).alias("version","v").help().parse()}export{ht as startServer};
|
package/dist/index.d.ts
CHANGED
|
@@ -72,6 +72,11 @@ interface WeatherResponse {
|
|
|
72
72
|
error?: string;
|
|
73
73
|
data?: any;
|
|
74
74
|
}
|
|
75
|
+
interface AirQualityResponse {
|
|
76
|
+
success: boolean;
|
|
77
|
+
error?: string;
|
|
78
|
+
data?: any;
|
|
79
|
+
}
|
|
75
80
|
interface ElevationResponse {
|
|
76
81
|
success: boolean;
|
|
77
82
|
error?: string;
|
|
@@ -115,6 +120,7 @@ declare class PlacesSearcher {
|
|
|
115
120
|
getDirections(origin: string, destination: string, mode?: "driving" | "walking" | "bicycling" | "transit", departure_time?: string, arrival_time?: string): Promise<DirectionsResponse>;
|
|
116
121
|
getTimezone(latitude: number, longitude: number, timestamp?: number): Promise<TimezoneResponse>;
|
|
117
122
|
getWeather(latitude: number, longitude: number, type?: "current" | "forecast_daily" | "forecast_hourly", forecastDays?: number, forecastHours?: number): Promise<WeatherResponse>;
|
|
123
|
+
getAirQuality(latitude: number, longitude: number, includeHealthRecommendations?: boolean, includePollutants?: boolean): Promise<AirQualityResponse>;
|
|
118
124
|
exploreArea(params: {
|
|
119
125
|
location: string;
|
|
120
126
|
types?: string[];
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a,b,c}from"./chunk-
|
|
1
|
+
import{a,b,c}from"./chunk-ME57GONJ.js";export{b as Logger,a as NewPlacesService,c as PlacesSearcher};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cablate/mcp-google-map",
|
|
3
|
-
"version": "0.0.
|
|
3
|
+
"version": "0.0.36",
|
|
4
4
|
"mcpName": "io.github.cablate/google-map",
|
|
5
5
|
"description": "Google Maps tools for AI agents — geocode, search, directions, elevation via MCP server or standalone CLI",
|
|
6
6
|
"type": "module",
|
|
@@ -35,7 +35,7 @@ Without this Skill, the agent can only guess or refuse when asked "how do I get
|
|
|
35
35
|
|
|
36
36
|
## Tool Map
|
|
37
37
|
|
|
38
|
-
|
|
38
|
+
14 tools in four categories — pick by scenario:
|
|
39
39
|
|
|
40
40
|
### Place Discovery
|
|
41
41
|
| Tool | When to use | Example |
|
|
@@ -58,6 +58,7 @@ Without this Skill, the agent can only guess or refuse when asked "how do I get
|
|
|
58
58
|
| `elevation` | Query altitude | "Elevation profile along this hiking trail" |
|
|
59
59
|
| `timezone` | Need local time at a destination | "What time is it in Tokyo?" |
|
|
60
60
|
| `weather` | Weather at a location (current or forecast) | "What's the weather in Paris?" |
|
|
61
|
+
| `air-quality` | AQI, pollutants, health recommendations | "Is the air safe for jogging?" |
|
|
61
62
|
|
|
62
63
|
### Composite (one-call shortcuts)
|
|
63
64
|
| Tool | When to use | Example |
|
|
@@ -200,6 +200,44 @@ exec weather '{"latitude": 37.4220, "longitude": -122.0841, "type": "forecast_da
|
|
|
200
200
|
|
|
201
201
|
---
|
|
202
202
|
|
|
203
|
+
## air-quality
|
|
204
|
+
|
|
205
|
+
Get air quality index, pollutant concentrations, and health recommendations for a location.
|
|
206
|
+
|
|
207
|
+
```bash
|
|
208
|
+
exec air-quality '{"latitude": 35.6762, "longitude": 139.6503}'
|
|
209
|
+
exec air-quality '{"latitude": 35.6762, "longitude": 139.6503, "includePollutants": true}'
|
|
210
|
+
```
|
|
211
|
+
|
|
212
|
+
| Param | Type | Required | Description |
|
|
213
|
+
|-------|------|----------|-------------|
|
|
214
|
+
| latitude | number | yes | Latitude |
|
|
215
|
+
| longitude | number | yes | Longitude |
|
|
216
|
+
| includeHealthRecommendations | boolean | no | Health advice per demographic group (default: true) |
|
|
217
|
+
| includePollutants | boolean | no | Individual pollutant concentrations (default: false) |
|
|
218
|
+
|
|
219
|
+
Response:
|
|
220
|
+
```json
|
|
221
|
+
{
|
|
222
|
+
"aqi": 76,
|
|
223
|
+
"category": "Good",
|
|
224
|
+
"dominantPollutant": "pm25",
|
|
225
|
+
"healthRecommendations": {
|
|
226
|
+
"generalPopulation": "...",
|
|
227
|
+
"elderly": "...",
|
|
228
|
+
"lungDiseasePopulation": "...",
|
|
229
|
+
"heartDiseasePopulation": "...",
|
|
230
|
+
"athletes": "...",
|
|
231
|
+
"pregnantWomen": "...",
|
|
232
|
+
"children": "..."
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
```
|
|
236
|
+
|
|
237
|
+
Chaining: `geocode` → `air-quality` when the user gives an address instead of coordinates.
|
|
238
|
+
|
|
239
|
+
---
|
|
240
|
+
|
|
203
241
|
## explore-area (composite)
|
|
204
242
|
|
|
205
243
|
Explore a neighborhood in one call. Internally chains geocode → search-nearby (per type) → place-details (top N).
|
|
@@ -270,6 +308,12 @@ search-nearby {"center":{"value":"25.033,121.564","isCoordinates":true},"keyword
|
|
|
270
308
|
distance-matrix {"origins":["Taipei Main Station","Banqiao Station"],"destinations":["Taoyuan Airport","Songshan Airport"],"mode":"driving"}
|
|
271
309
|
```
|
|
272
310
|
|
|
311
|
+
**Geocode → Air Quality** — Check air quality at a named location.
|
|
312
|
+
```
|
|
313
|
+
geocode {"address":"Tokyo"}
|
|
314
|
+
air-quality {"latitude":35.6762,"longitude":139.6503}
|
|
315
|
+
```
|
|
316
|
+
|
|
273
317
|
---
|
|
274
318
|
|
|
275
319
|
## Scenario Recipes
|
package/dist/chunk-LT3W7AUA.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{Client as T,Language as A}from"@googlemaps/google-maps-services-js";import D from"dotenv";D.config();function f(h){let e=h?.response?.status,t=h?.response?.data?.error_message,r=h?.response?.data?.status;return e===403?"API key invalid or required API not enabled. Check: console.cloud.google.com \u2192 APIs & Services \u2192 Enable the relevant API (Places, Geocoding, etc.)":e===429?"API quota exceeded. Wait and retry, or check quota at console.cloud.google.com \u2192 Quotas":r==="ZERO_RESULTS"?"No results found. Try broader search terms or a larger radius.":r==="OVER_QUERY_LIMIT"?"API quota exceeded. Wait and retry, or upgrade your billing plan.":r==="REQUEST_DENIED"?`Request denied by Google Maps API. ${t||"Check your API key and enabled APIs."}`:r==="INVALID_REQUEST"?`Invalid request parameters. ${t||"Check your input values."}`:t?`${t} (HTTP ${e})`:h instanceof Error?h.message:String(h)}var E=class{constructor(e){this.defaultLanguage=A.en;if(this.client=new T({}),this.apiKey=e||process.env.GOOGLE_MAPS_API_KEY||"",!this.apiKey)throw new Error("Google Maps API Key is required")}async geocodeAddress(e){try{let t=await this.client.geocode({params:{address:e,key:this.apiKey,language:this.defaultLanguage}});if(t.data.results.length===0)throw new Error(`No location found for address: "${e}"`);let r=t.data.results[0],n=r.geometry.location;return{lat:n.lat,lng:n.lng,formatted_address:r.formatted_address,place_id:r.place_id}}catch(t){throw p.error("Error in geocodeAddress:",t),new Error(`Failed to geocode address "${e}": ${f(t)}`)}}parseCoordinates(e){let t=e.split(",").map(r=>parseFloat(r.trim()));if(t.length!==2||isNaN(t[0])||isNaN(t[1]))throw new Error(`Invalid coordinate format: "${e}". Please use "latitude,longitude" format (e.g., "25.033,121.564"`);return{lat:t[0],lng:t[1]}}async getLocation(e){return e.isCoordinates?this.parseCoordinates(e.value):this.geocodeAddress(e.value)}async geocode(e){try{let t=await this.geocodeAddress(e);return{location:{lat:t.lat,lng:t.lng},formatted_address:t.formatted_address||"",place_id:t.place_id||""}}catch(t){throw p.error("Error in geocode:",t),new Error(`Failed to geocode address "${e}": ${f(t)}`)}}async reverseGeocode(e,t){try{let r=await this.client.reverseGeocode({params:{latlng:{lat:e,lng:t},language:this.defaultLanguage,key:this.apiKey}});if(r.data.results.length===0)throw new Error(`No address found for coordinates: (${e}, ${t})`);let n=r.data.results[0];return{formatted_address:n.formatted_address,place_id:n.place_id,address_components:n.address_components}}catch(r){throw p.error("Error in reverseGeocode:",r),new Error(`Failed to reverse geocode coordinates (${e}, ${t}): ${f(r)}`)}}async calculateDistanceMatrix(e,t,r="driving"){try{let a=(await this.client.distancematrix({params:{origins:e,destinations:t,mode:r,language:this.defaultLanguage,key:this.apiKey}})).data;if(a.status!=="OK")throw new Error(`Distance matrix calculation failed with status: ${a.status}`);let o=[],u=[];return a.rows.forEach(l=>{let s=[],c=[];l.elements.forEach(d=>{d.status==="OK"?(s.push({value:d.distance.value,text:d.distance.text}),c.push({value:d.duration.value,text:d.duration.text})):(s.push(null),c.push(null))}),o.push(s),u.push(c)}),{distances:o,durations:u,origin_addresses:a.origin_addresses,destination_addresses:a.destination_addresses}}catch(n){throw p.error("Error in calculateDistanceMatrix:",n),new Error(`Failed to calculate distance matrix: ${f(n)}`)}}async getDirections(e,t,r="driving",n,a){try{let o;a&&(o=Math.floor(a.getTime()/1e3));let u;o||(n instanceof Date?u=Math.floor(n.getTime()/1e3):n?u=n:u="now");let s=(await this.client.directions({params:{origin:e,destination:t,mode:r,language:this.defaultLanguage,key:this.apiKey,arrival_time:o,departure_time:u}})).data;if(s.status!=="OK")throw new Error(`Failed to get directions with status: ${s.status} (arrival_time: ${o}, departure_time: ${u}`);if(s.routes.length===0)throw new Error(`No route found from "${e}" to "${t}" with mode: ${r}`);let c=s.routes[0],d=c.legs[0],y=i=>{if(!i||typeof i.value!="number")return"";let g=new Date(i.value*1e3),m={year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",hour12:!1};return i.time_zone&&typeof i.time_zone=="string"&&(m.timeZone=i.time_zone),g.toLocaleString(this.defaultLanguage.toString(),m)};return{routes:s.routes,summary:c.summary,total_distance:{value:d.distance.value,text:d.distance.text},total_duration:{value:d.duration.value,text:d.duration.text},arrival_time:y(d.arrival_time),departure_time:y(d.departure_time)}}catch(o){throw p.error("Error in getDirections:",o),new Error(`Failed to get directions from "${e}" to "${t}": ${f(o)}`)}}async getWeather(e,t,r="current",n,a){try{let o=`key=${this.apiKey}&location.latitude=${e}&location.longitude=${t}`,u;switch(r){case"forecast_daily":{let c=Math.min(Math.max(n||5,1),10);u=`https://weather.googleapis.com/v1/forecast/days:lookup?${o}&days=${c}`;break}case"forecast_hourly":{let c=Math.min(Math.max(a||24,1),240);u=`https://weather.googleapis.com/v1/forecast/hours:lookup?${o}&hours=${c}`;break}default:u=`https://weather.googleapis.com/v1/currentConditions:lookup?${o}`}let l=await fetch(u);if(!l.ok){let d=(await l.json().catch(()=>({})))?.error?.message||`HTTP ${l.status}`;throw d.includes("not supported for this location")?new Error(`Weather data is not available for this location (${e}, ${t}). The Google Weather API has limited coverage \u2014 China, Japan, South Korea, Cuba, Iran, North Korea, and Syria are unsupported. Try a location in North America, Europe, or Oceania.`):new Error(d)}let s=await l.json();return r==="current"?{temperature:s.temperature,feelsLike:s.feelsLikeTemperature,humidity:s.relativeHumidity,wind:s.wind,conditions:s.weatherCondition?.description?.text||s.weatherCondition?.type,uvIndex:s.uvIndex,precipitation:s.precipitation,visibility:s.visibility,pressure:s.airPressure,cloudCover:s.cloudCover,isDayTime:s.isDaytime}:s}catch(o){throw p.error("Error in getWeather:",o),new Error(o.message||`Failed to get weather for (${e}, ${t})`)}}async getTimezone(e,t,r){try{let n=Math.floor(r?r/1e3:Date.now()/1e3),o=(await this.client.timezone({params:{location:{lat:e,lng:t},timestamp:n,key:this.apiKey}})).data;if(o.status!=="OK")throw new Error(`Timezone API returned status: ${o.status}`);let u=(o.rawOffset+o.dstOffset)*1e3,l=new Date(n*1e3+u).toISOString().replace("Z","");return{timeZoneId:o.timeZoneId,timeZoneName:o.timeZoneName,utcOffset:o.rawOffset,dstOffset:o.dstOffset,localTime:l}}catch(n){throw p.error("Error in getTimezone:",n),new Error(`Failed to get timezone for (${e}, ${t}): ${f(n)}`)}}async getElevation(e){try{let t=e.map(a=>({lat:a.latitude,lng:a.longitude})),n=(await this.client.elevation({params:{locations:t,key:this.apiKey}})).data;if(n.status!=="OK")throw new Error(`Failed to get elevation data with status: ${n.status}`);return n.results.map((a,o)=>({elevation:a.elevation,location:t[o]}))}catch(t){throw p.error("Error in getElevation:",t),new Error(`Failed to get elevation data for ${e.length} location(s): ${f(t)}`)}}};import{PlacesClient as R}from"@googlemaps/places";var _=class{constructor(e){this.defaultLanguage="en";this.placeFieldMask=["displayName","name","id","formattedAddress","location","utcOffsetMinutes","regularOpeningHours.periods","regularOpeningHours.weekdayDescriptions","currentOpeningHours.openNow","nationalPhoneNumber","websiteUri","priceLevel","rating","userRatingCount","reviews.rating","reviews.text","reviews.publishTime","reviews.authorAttribution.displayName","photos.heightPx","photos.widthPx","photos.name"].join(",");this.searchNearbyFieldMask=["places.displayName","places.name","places.id","places.formattedAddress","places.location","places.rating","places.userRatingCount","places.currentOpeningHours.openNow"].join(",");if(this.client=new R({apiKey:e||process.env.GOOGLE_MAPS_API_KEY||""}),!e&&!process.env.GOOGLE_MAPS_API_KEY)throw new Error("Google Maps API Key is required")}async searchNearby(e){try{let t={locationRestriction:{circle:{center:{latitude:e.location.lat,longitude:e.location.lng},radius:e.radius||1e3}},maxResultCount:Math.min(e.maxResultCount||20,20),languageCode:this.defaultLanguage};e.keyword&&(t.includedTypes=[e.keyword]);let[r]=await this.client.searchNearby(t,{otherArgs:{headers:{"X-Goog-FieldMask":this.searchNearbyFieldMask}}});return(r.places||[]).map(n=>this.transformSearchResult(n))}catch(t){throw p.error("Error in searchNearby (New API):",t),new Error(`Failed to search nearby places: ${this.extractErrorMessage(t)}`)}}async searchText(e){try{let t={textQuery:e.textQuery,languageCode:this.defaultLanguage,maxResultCount:Math.min(e.maxResultCount||10,20)};e.locationBias&&(t.locationBias={circle:{center:{latitude:e.locationBias.lat,longitude:e.locationBias.lng},radius:e.locationBias.radius||5e3}}),e.openNow&&(t.openNow=!0),e.minRating&&(t.minRating=e.minRating),e.includedType&&(t.includedType=e.includedType);let[r]=await this.client.searchText(t,{otherArgs:{headers:{"X-Goog-FieldMask":this.searchNearbyFieldMask}}});return(r.places||[]).map(n=>this.transformSearchResult(n))}catch(t){throw p.error("Error in searchText (New API):",t),new Error(`Failed to search places: ${this.extractErrorMessage(t)}`)}}async getPlaceDetails(e){try{let t=`places/${e}`,[r]=await this.client.getPlace({name:t,languageCode:this.defaultLanguage},{otherArgs:{headers:{"X-Goog-FieldMask":this.placeFieldMask}}});return this.transformPlaceResponse(r)}catch(t){throw p.error("Error in getPlaceDetails (New API):",t),new Error(`Failed to get place details for ${e}: ${this.extractErrorMessage(t)}`)}}transformSearchResult(e){return{name:e.displayName?.text||"",place_id:this.extractLegacyPlaceId(e),formatted_address:e.formattedAddress||"",geometry:{location:{lat:e.location?.latitude||0,lng:e.location?.longitude||0}},rating:e.rating||0,user_ratings_total:e.userRatingCount||0,opening_hours:{open_now:e.currentOpeningHours?.openNow??null}}}transformPlaceResponse(e){return{name:e.displayName?.text||e.name||"",place_id:this.extractLegacyPlaceId(e),formatted_address:e.formattedAddress||"",geometry:{location:{lat:e.location?.latitude||0,lng:e.location?.longitude||0}},rating:e.rating||0,user_ratings_total:e.userRatingCount||0,opening_hours:e.regularOpeningHours?{open_now:this.isCurrentlyOpen(e.regularOpeningHours,e.utcOffsetMinutes,e.currentOpeningHours),weekday_text:this.formatOpeningHours(e.regularOpeningHours)}:void 0,formatted_phone_number:e.nationalPhoneNumber||"",website:e.websiteUri||"",price_level:e.priceLevel||0,reviews:e.reviews?.map(t=>({rating:t.rating||0,text:t.text?.text||"",time:t.publishTime?.seconds||0,author_name:t.authorAttribution?.displayName||""}))||[],photos:e.photos?.map(t=>({photo_reference:t.name||"",height:t.heightPx||0,width:t.widthPx||0}))||[]}}extractLegacyPlaceId(e){let t=e?.name;if(typeof t=="string"&&t.startsWith("places/")){let r=t.substring(7);if(r)return r}return e?.id||""}isCurrentlyOpen(e,t,r){if(typeof r?.openNow=="boolean")return r.openNow;if(typeof e?.openNow=="boolean")return e.openNow;let n=e?.periods;if(!Array.isArray(n)||n.length===0)return!1;let a=1440,o=a*7,{day:u,minutes:l}=this.getLocalTimeComponents(t),s=u*a+l,c={SUNDAY:0,MONDAY:1,TUESDAY:2,WEDNESDAY:3,THURSDAY:4,FRIDAY:5,SATURDAY:6},d=i=>{if(typeof i=="number"&&i>=0&&i<=6)return i;if(typeof i=="string"){let g=i.toUpperCase();if(g in c)return c[g]}},y=i=>{if(!i)return;let g=typeof i.hours=="number"?i.hours:Number(i.hours??NaN),m=typeof i.minutes=="number"?i.minutes:Number(i.minutes??NaN);if(!(!Number.isFinite(g)||!Number.isFinite(m)))return g*60+m};for(let i of n){let g=d(i?.openDay),m=d(i?.closeDay??i?.openDay),w=y(i?.openTime),N=y(i?.closeTime);if(g===void 0||w===void 0)continue;let v=g*a+w,b;m===void 0||N===void 0?b=v+a:b=m*a+N,b<=v&&(b+=o);let P=s;for(;P<v;)P+=o;if(P>=v&&P<b)return!0}return!1}getLocalTimeComponents(e){let t=new Date;if(typeof e=="number"&&Number.isFinite(e)){let r=new Date(t.getTime()+e*6e4);return{day:r.getUTCDay(),minutes:r.getUTCHours()*60+r.getUTCMinutes()}}return{day:t.getDay(),minutes:t.getHours()*60+t.getMinutes()}}formatOpeningHours(e){return e?.weekdayDescriptions||[]}extractErrorMessage(e){let t=e?.code,r=e?.message||e?.details;return t===7||t===403?"API key invalid or Places API (New) not enabled. Check: console.cloud.google.com \u2192 APIs & Services \u2192 Enable 'Places API (New)'":t===8||t===429?"API quota exceeded. Wait and retry, or check quota at console.cloud.google.com \u2192 Quotas":r||(e instanceof Error?e.message:String(e))}};var x=class{constructor(e){this.mapsTools=new E(e),this.newPlacesService=new _(e)}async searchNearby(e){try{let t=await this.mapsTools.getLocation(e.center),n=await this.newPlacesService.searchNearby({location:t,keyword:e.keyword,radius:e.radius});return e.openNow&&(n=n.filter(a=>a.opening_hours?.open_now===!0)),e.minRating&&(n=n.filter(a=>(a.rating||0)>=(e.minRating||0))),{location:t,success:!0,data:n.map(a=>({name:a.name,place_id:a.place_id,address:a.formatted_address,location:a.geometry.location,rating:a.rating,total_ratings:a.user_ratings_total,open_now:a.opening_hours?.open_now}))}}catch(t){return{success:!1,error:t instanceof Error?t.message:"An error occurred during search"}}}async searchText(e){try{return{success:!0,data:(await this.newPlacesService.searchText({textQuery:e.query,locationBias:e.locationBias?{lat:e.locationBias.latitude,lng:e.locationBias.longitude,radius:e.locationBias.radius}:void 0,openNow:e.openNow,minRating:e.minRating,includedType:e.includedType})).map(r=>({name:r.name,place_id:r.place_id,address:r.formatted_address,location:r.geometry.location,rating:r.rating,total_ratings:r.user_ratings_total,open_now:r.opening_hours?.open_now}))}}catch(t){return{success:!1,error:t instanceof Error?t.message:"An error occurred during text search"}}}async getPlaceDetails(e){try{let t=await this.newPlacesService.getPlaceDetails(e);return{success:!0,data:{name:t.name,address:t.formatted_address,location:t.geometry?.location,rating:t.rating,total_ratings:t.user_ratings_total,open_now:t.opening_hours?.open_now,phone:t.formatted_phone_number,website:t.website,price_level:t.price_level,reviews:t.reviews?.map(r=>({rating:r.rating,text:r.text,time:r.time,author_name:r.author_name}))}}}catch(t){return{success:!1,error:t instanceof Error?t.message:"An error occurred while getting place details"}}}async geocode(e){try{return{success:!0,data:await this.mapsTools.geocode(e)}}catch(t){return{success:!1,error:t instanceof Error?t.message:"An error occurred while geocoding address"}}}async reverseGeocode(e,t){try{return{success:!0,data:await this.mapsTools.reverseGeocode(e,t)}}catch(r){return{success:!1,error:r instanceof Error?r.message:"An error occurred during reverse geocoding"}}}async calculateDistanceMatrix(e,t,r="driving"){try{return{success:!0,data:await this.mapsTools.calculateDistanceMatrix(e,t,r)}}catch(n){return{success:!1,error:n instanceof Error?n.message:"An error occurred while calculating distance matrix"}}}async getDirections(e,t,r="driving",n,a){try{let o=n?new Date(n):new Date,u=a?new Date(a):void 0;return{success:!0,data:await this.mapsTools.getDirections(e,t,r,o,u)}}catch(o){return{success:!1,error:o instanceof Error?o.message:"An error occurred while getting directions"}}}async getTimezone(e,t,r){try{return{success:!0,data:await this.mapsTools.getTimezone(e,t,r)}}catch(n){return{success:!1,error:n instanceof Error?n.message:"An error occurred while getting timezone"}}}async getWeather(e,t,r="current",n,a){try{return{success:!0,data:await this.mapsTools.getWeather(e,t,r,n,a)}}catch(o){return{success:!1,error:o instanceof Error?o.message:"An error occurred while getting weather"}}}async exploreArea(e){let t=e.types||["restaurant","cafe","attraction"],r=e.radius||1e3,n=e.topN||3,a=await this.geocode(e.location);if(!a.success||!a.data)throw new Error(a.error||"Geocode failed");let{lat:o,lng:u}=a.data.location,l=[];for(let s of t){let c=await this.searchNearby({center:{value:`${o},${u}`,isCoordinates:!0},keyword:s,radius:r});if(!c.success||!c.data)continue;let d=c.data.slice(0,n),y=[];for(let i of d){if(!i.place_id)continue;let g=await this.getPlaceDetails(i.place_id);y.push({name:i.name,address:i.address,rating:i.rating,total_ratings:i.total_ratings,open_now:i.open_now,phone:g.data?.phone,website:g.data?.website})}l.push({type:s,count:c.data.length,top:y})}return{success:!0,data:{location:{address:a.data.formatted_address,lat:o,lng:u},radius:r,categories:l}}}async planRoute(e){let t=e.mode||"driving",r=e.stops;if(r.length<2)throw new Error("Need at least 2 stops");let n=[];for(let s of r){let c=await this.geocode(s);if(!c.success||!c.data)throw new Error(`Failed to geocode: ${s}`);n.push({originalName:s,address:c.data.formatted_address,lat:c.data.location.lat,lng:c.data.location.lng})}let a=n;if(e.optimize!==!1&&n.length>2){let s=await this.calculateDistanceMatrix(r,r,"driving");if(s.success&&s.data){let c=new Set([0]),d=[0],y=0;for(;c.size<n.length;){let i=-1,g=1/0;for(let m=0;m<n.length;m++){if(c.has(m))continue;let w=s.data.durations[y]?.[m]?.value??1/0;w<g&&(g=w,i=m)}if(i===-1)break;c.add(i),d.push(i),y=i}a=d.map(i=>n[i])}}let o=[],u=0,l=0;for(let s=0;s<a.length-1;s++){let c=await this.getDirections(a[s].originalName,a[s+1].originalName,t);c.success&&c.data?(u+=c.data.total_distance.value,l+=c.data.total_duration.value,o.push({from:a[s].originalName,to:a[s+1].originalName,distance:c.data.total_distance.text,duration:c.data.total_duration.text})):o.push({from:a[s].originalName,to:a[s+1].originalName,distance:"unknown",duration:"unknown",note:c.error||"Directions unavailable for this segment"})}return{success:!0,data:{mode:t,optimized:e.optimize!==!1&&n.length>2,stops:a.map(s=>`${s.originalName} (${s.address})`),legs:o,total_distance:`${(u/1e3).toFixed(1)} km`,total_duration:`${Math.round(l/60)} min`}}}async comparePlaces(e){let t=e.limit||5,r=await this.searchText({query:e.query});if(!r.success||!r.data)throw new Error(r.error||"Search failed");let n=r.data.slice(0,t),a=[];for(let o of n){let u=await this.getPlaceDetails(o.place_id);a.push({name:o.name,address:o.address,rating:o.rating,total_ratings:o.total_ratings,open_now:o.open_now,phone:u.data?.phone,website:u.data?.website,price_level:u.data?.price_level})}if(e.userLocation&&a.length>0){let o=`${e.userLocation.latitude},${e.userLocation.longitude}`,u=n.map(s=>`${s.location.lat},${s.location.lng}`),l=await this.calculateDistanceMatrix([o],u,"driving");if(l.success&&l.data)for(let s=0;s<a.length;s++)a[s].distance=l.data.distances[0]?.[s]?.text,a[s].drive_time=l.data.durations[0]?.[s]?.text}return{success:!0,data:a}}async getElevation(e){try{return{success:!0,data:await this.mapsTools.getElevation(e)}}catch(t){return{success:!1,error:t instanceof Error?t.message:"An error occurred while getting elevation data"}}}};var p={log:(...h)=>{console.error("[INFO]",...h)},error:(...h)=>{console.error("[ERROR]",...h)}};export{_ as a,p as b,x as c};
|