@cablate/mcp-google-map 0.0.62 → 0.0.64
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/.codex-plugin/plugin.json +37 -0
- package/README.md +19 -8
- package/README.zh-TW.md +19 -8
- package/dist/chunk-BKUJWPKE.js +1 -0
- package/dist/cli.js +2 -2
- package/dist/index.d.ts +10 -2
- package/dist/index.js +1 -1
- package/examples/agent-skill-demo.md +39 -0
- package/package.json +5 -2
- package/plugin.json +21 -0
- package/skills/google-maps/SKILL.md +2 -2
- package/skills/google-maps/SKILL.skill +0 -0
- package/skills/google-maps/references/content-attribution.md +11 -0
- package/skills/google-maps/references/tools-api.md +7 -0
- package/dist/chunk-V2MW4XB5.js +0 -1
- package/skills/project-docs/SKILL.md +0 -66
- package/skills/project-docs/references/architecture.md +0 -137
- package/skills/project-docs/references/decisions.md +0 -149
- package/skills/project-docs/references/geo-domain-knowledge.md +0 -286
- package/skills/project-docs/references/google-maps-api-guide.md +0 -139
package/dist/chunk-V2MW4XB5.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{Client as W,Language as G}from"@googlemaps/google-maps-services-js";import z from"dotenv";var O="https://routes.googleapis.com",D={driving:"DRIVE",walking:"WALK",bicycling:"BICYCLE",transit:"TRANSIT"},L=["routes.distanceMeters","routes.duration","routes.description","routes.polyline.encodedPolyline","routes.legs.distanceMeters","routes.legs.duration","routes.legs.startLocation","routes.legs.endLocation","routes.legs.steps.navigationInstruction","routes.legs.steps.distanceMeters","routes.legs.steps.staticDuration","routes.legs.steps.startLocation","routes.legs.steps.endLocation","routes.legs.steps.transitDetails","routes.legs.polyline","routes.optimizedIntermediateWaypointIndex"].join(","),F="originIndex,destinationIndex,distanceMeters,duration,status,condition";function x(l){if(!l)return 0;let e=l.match(/^(\d+)s$/);return e?parseInt(e[1],10):0}function A(l){return l>=1e3?`${(l/1e3).toFixed(1)} km`:`${l} m`}function k(l){if(l>=3600){let t=Math.floor(l/3600),r=Math.round(l%3600/60);return r>0?`${t} hour${t>1?"s":""} ${r} min${r>1?"s":""}`:`${t} hour${t>1?"s":""}`}let e=Math.round(l/60);return`${e} min${e!==1?"s":""}`}var N=/^\s*(-?\d+\.?\d*)\s*,\s*(-?\d+\.?\d*)\s*$/;function E(l){return typeof l=="string"?l:"placeId"in l?`placeId:${l.placeId}`:`${l.latLng.latitude},${l.latLng.longitude}`}function R(l){if(typeof l!="string")return"placeId"in l?{placeId:l.placeId}:{location:{latLng:l.latLng}};let e=l.match(N);return e?{location:{latLng:{latitude:parseFloat(e[1]),longitude:parseFloat(e[2])}}}:{address:l}}function C(l,e){let t={};if(l.avoidTolls&&(t.avoidTolls=!0),l.avoidHighways&&(t.avoidHighways=!0),Object.keys(t).length!==0){if(e!=="DRIVE")throw new Error('Route modifiers "avoid_tolls" and "avoid_highways" are only supported with mode "driving".');return t}}var _=class{constructor(e){if(this.apiKey=e||process.env.GOOGLE_MAPS_API_KEY||"",!this.apiKey)throw new Error("Google Maps API Key is required")}async computeRoutes(e){let t=D[e.mode||"driving"]||"DRIVE",r={origin:R(e.origin),destination:R(e.destination),travelMode:t,computeAlternativeRoutes:!1};t==="DRIVE"&&(r.routingPreference="TRAFFIC_AWARE");let n=C(e,t);n&&(r.routeModifiers=n),e.arrivalTime?r.arrivalTime=e.arrivalTime.toISOString():e.departureTime&&(r.departureTime=e.departureTime.toISOString()),e.intermediates&&e.intermediates.length>0&&(r.intermediates=e.intermediates.map(R)),e.optimizeWaypointOrder&&e.intermediates&&e.intermediates.length>1&&t!=="TRANSIT"&&(r.optimizeWaypointOrder=!0);let o=await fetch(`${O}/directions/v2:computeRoutes`,{method:"POST",headers:{"Content-Type":"application/json","X-Goog-Api-Key":this.apiKey,"X-Goog-FieldMask":L},body:JSON.stringify(r)});if(!o.ok){let p=(await o.json().catch(()=>({})))?.error?.message||`HTTP ${o.status}`;throw new Error(p)}let s=await o.json();if(!s.routes||s.routes.length===0){let g=e.mode||"driving";throw g==="transit"?new Error(`No transit route found from "${e.originLabel??E(e.origin)}" to "${e.destinationLabel??E(e.destination)}". The Google Routes API does not support transit directions in some regions (notably Japan and India). Try using mode "driving" or "walking" instead, or use a regional transit service for public transportation details.`):new Error(`No route found from "${e.originLabel??E(e.origin)}" to "${e.destinationLabel??E(e.destination)}" with mode: ${g}`)}let i=s.routes[0],u=i.distanceMeters||0,a=x(i.duration);return{routes:s.routes,summary:i.description||"",total_distance:{value:u,text:A(u)},total_duration:{value:a,text:k(a)},arrival_time:"",departure_time:"",...i.optimizedIntermediateWaypointIndex?{optimizedIntermediateWaypointIndex:i.optimizedIntermediateWaypointIndex}:{}}}async computeRouteMatrix(e){let t=D[e.mode||"driving"]||"DRIVE",r={origins:e.origins.map(c=>({waypoint:R(c)})),destinations:e.destinations.map(c=>({waypoint:R(c)})),travelMode:t};t==="DRIVE"&&(r.routingPreference="TRAFFIC_AWARE");let n=C(e,t);n&&(r.routeModifiers=n),e.departureTime&&(r.departureTime=e.departureTime.toISOString());let o=await fetch(`${O}/distanceMatrix/v2:computeRouteMatrix`,{method:"POST",headers:{"Content-Type":"application/json","X-Goog-Api-Key":this.apiKey,"X-Goog-FieldMask":F},body:JSON.stringify(r)});if(!o.ok){let d=(await o.json().catch(()=>({})))?.error?.message||`HTTP ${o.status}`;throw new Error(d)}let s=await o.json(),i=e.origins.length,u=e.destinations.length,a=Array.from({length:i},()=>Array(u).fill(null)),g=Array.from({length:i},()=>Array(u).fill(null)),p=0;for(let c of s){let d=c.originIndex,h=c.destinationIndex;if(d===void 0||h===void 0)continue;if(c.condition==="ROUTE_NOT_FOUND"){p++;continue}let y=c.distanceMeters||0,w=x(c.duration);a[d][h]={value:y,text:A(y)},g[d][h]={value:w,text:k(w)}}let m=i*u;if(p===m&&t==="TRANSIT")throw new Error('No transit routes found for any origin/destination pair. The Google Routes API does not support transit directions in some regions (notably Japan and India). Try using mode "driving" or "walking" instead, or use a regional transit service for public transportation details.');return{distances:a,durations:g,origin_addresses:e.origins,destination_addresses:e.destinations,...p>0&&t==="TRANSIT"?{warning:`${p} of ${m} origin/destination pairs returned no transit route. The Google Routes API has limited transit coverage in some regions.`}:{}}}};z.config();function T(l){let e=l?.response?.status,t=l?.response?.data?.error_message,r=l?.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})`:l instanceof Error?l.message:String(l)}var M=class{constructor(e){this.defaultLanguage=G.en;if(this.client=new W({}),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 f.error("Error in geocodeAddress:",t),new Error(`Failed to geocode address "${e}": ${T(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 f.error("Error in geocode:",t),new Error(`Failed to geocode address "${e}": ${T(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 f.error("Error in reverseGeocode:",r),new Error(`Failed to reverse geocode coordinates (${e}, ${t}): ${T(r)}`)}}async searchAlongRoute(e){try{let r=await new _(this.apiKey).computeRoutes({origin:e.origin,destination:e.destination,mode:e.mode||"walking"}),n=r.routes[0]?.polyline?.encodedPolyline;if(!n)throw new Error("Could not get route polyline");let o=Math.min(e.maxResults||5,20),i=await fetch("https://places.googleapis.com/v1/places:searchText",{method:"POST",headers:{"Content-Type":"application/json","X-Goog-Api-Key":this.apiKey,"X-Goog-FieldMask":"places.displayName,places.id,places.formattedAddress,places.location,places.rating,places.userRatingCount,places.currentOpeningHours.openNow"},body:JSON.stringify({textQuery:e.textQuery,searchAlongRouteParameters:{polyline:{encodedPolyline:n}},maxResultCount:o})});if(!i.ok){let g=await i.json().catch(()=>({}));throw new Error(g?.error?.message||`HTTP ${i.status}`)}return{places:((await i.json()).places||[]).map(g=>({name:g.displayName?.text||"",place_id:g.id||"",formatted_address:g.formattedAddress||"",location:{lat:g.location?.latitude||0,lng:g.location?.longitude||0},rating:g.rating||0,user_ratings_total:g.userRatingCount||0,open_now:g.currentOpeningHours?.openNow??null})),route:{distance:r.total_distance.text,duration:r.total_duration.text,polyline:n}}}catch(t){throw f.error("Error in searchAlongRoute:",t),new Error(t.message||"Failed to search along route")}}async getWeather(e,t,r="current",n,o){try{let s=`key=${this.apiKey}&location.latitude=${e}&location.longitude=${t}`,i;switch(r){case"forecast_daily":{let g=Math.min(Math.max(n||5,1),10);i=`https://weather.googleapis.com/v1/forecast/days:lookup?${s}&days=${g}`;break}case"forecast_hourly":{let g=Math.min(Math.max(o||24,1),240);i=`https://weather.googleapis.com/v1/forecast/hours:lookup?${s}&hours=${g}`;break}default:i=`https://weather.googleapis.com/v1/currentConditions:lookup?${s}`}let u=await fetch(i);if(!u.ok){let p=(await u.json().catch(()=>({})))?.error?.message||`HTTP ${u.status}`;throw p.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(p)}let a=await u.json();return r==="current"?{temperature:a.temperature,feelsLike:a.feelsLikeTemperature,humidity:a.relativeHumidity,wind:a.wind,conditions:a.weatherCondition?.description?.text||a.weatherCondition?.type,uvIndex:a.uvIndex,precipitation:a.precipitation,visibility:a.visibility,pressure:a.airPressure,cloudCover:a.cloudCover,isDayTime:a.isDaytime}:a}catch(s){throw f.error("Error in getWeather:",s),new Error(s.message||`Failed to get weather for (${e}, ${t})`)}}async getAirQuality(e,t,r=!0,n=!1){try{let o=`https://airquality.googleapis.com/v1/currentConditions:lookup?key=${this.apiKey}`,s=[];r&&s.push("HEALTH_RECOMMENDATIONS"),n&&s.push("POLLUTANT_CONCENTRATION");let i={location:{latitude:e,longitude:t}};s.length>0&&(i.extraComputations=s);let u=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)});if(!u.ok){let d=(await u.json().catch(()=>({})))?.error?.message||`HTTP ${u.status}`;throw new Error(d)}let a=await u.json(),g=a.indexes||[],p=g[0],m={dateTime:a.dateTime,regionCode:a.regionCode,aqi:p?.aqi,category:p?.category,dominantPollutant:p?.dominantPollutant,color:p?.color};return g.length>1&&(m.indexes=g.map(c=>({code:c.code,displayName:c.displayName,aqi:c.aqi,category:c.category,dominantPollutant:c.dominantPollutant}))),a.healthRecommendations&&(m.healthRecommendations=a.healthRecommendations),a.pollutants&&(m.pollutants=a.pollutants.map(c=>({code:c.code,displayName:c.displayName,concentration:c.concentration,additionalInfo:c.additionalInfo}))),m}catch(o){throw f.error("Error in getAirQuality:",o),new Error(o.message||`Failed to get air quality for (${e}, ${t})`)}}async getStaticMap(e){try{let t=e.size||"600x400",r=[`key=${this.apiKey}`,`size=${t}`,`maptype=${e.maptype||"roadmap"}`];if(e.center&&r.push(`center=${encodeURIComponent(e.center)}`),e.zoom!==void 0&&r.push(`zoom=${e.zoom}`),e.markers)for(let a of e.markers)r.push(`markers=${encodeURIComponent(a)}`);if(e.path)for(let a of e.path)r.push(`path=${encodeURIComponent(a)}`);let n=`https://maps.googleapis.com/maps/api/staticmap?${r.join("&")}`;if(n.length>16384)throw new Error(`URL exceeds 16,384 character limit (${n.length}). Reduce markers or path points.`);let o=await fetch(n);if(!o.ok){let a=o.headers.get("content-type")||"";if(a.includes("application/json")||a.includes("text/")){let g=await o.text();throw new Error(`Static Maps API error: ${g}`)}throw new Error(`Static Maps API returned HTTP ${o.status}`)}let s=await o.arrayBuffer(),i=Buffer.from(s);return{base64:i.toString("base64"),size:i.length,dimensions:t}}catch(t){throw f.error("Error in getStaticMap:",t),new Error(t.message||"Failed to generate static map")}}async getTimezone(e,t,r){try{let n=Math.floor(r?r/1e3:Date.now()/1e3),s=(await this.client.timezone({params:{location:{lat:e,lng:t},timestamp:n,key:this.apiKey}})).data;if(s.status!=="OK")throw new Error(`Timezone API returned status: ${s.status}`);let i=(s.rawOffset+s.dstOffset)*1e3,u=new Date(n*1e3+i).toISOString().replace("Z","");return{timeZoneId:s.timeZoneId,timeZoneName:s.timeZoneName,utcOffset:s.rawOffset,dstOffset:s.dstOffset,localTime:u}}catch(n){throw f.error("Error in getTimezone:",n),new Error(`Failed to get timezone for (${e}, ${t}): ${T(n)}`)}}async getElevation(e){try{let t=e.map(o=>({lat:o.latitude,lng:o.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((o,s)=>({elevation:o.elevation,location:t[s]}))}catch(t){throw f.error("Error in getElevation:",t),new Error(`Failed to get elevation data for ${e.length} location(s): ${T(t)}`)}}};import{PlacesClient as K}from"@googlemaps/places";var P=class{constructor(e){this.defaultLanguage="en";this.placeFieldMask=["displayName","name","id","formattedAddress","location","utcOffsetMinutes","primaryType","types","regularOpeningHours.periods","regularOpeningHours.weekdayDescriptions","currentOpeningHours.openNow","nationalPhoneNumber","websiteUri","priceLevel","rating","userRatingCount","editorialSummary","reviews.rating","reviews.text","reviews.publishTime","reviews.authorAttribution.displayName","photos.heightPx","photos.widthPx","photos.name","parkingOptions","accessibilityOptions","servesVegetarianFood","servesBeer","servesWine","servesCocktails","servesBreakfast","servesLunch","servesDinner","servesBrunch","servesCoffee","servesDessert","dineIn","delivery","takeout","curbsidePickup","reservable","goodForGroups","goodForChildren","goodForWatchingSports","liveMusic","outdoorSeating","allowsDogs","menuForChildren","restroom","paymentOptions","reviewSummary","generativeSummary"].join(",");this.searchNearbyFieldMask=["places.displayName","places.name","places.id","places.formattedAddress","places.location","places.rating","places.userRatingCount","places.currentOpeningHours.openNow","places.primaryType","places.priceLevel"].join(",");if(this.apiKey=e||process.env.GOOGLE_MAPS_API_KEY||"",this.client=new K({apiKey:this.apiKey}),!this.apiKey)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 f.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 f.error("Error in searchText (New API):",t),new Error(`Failed to search places: ${this.extractErrorMessage(t)}`)}}async getPhotoUri(e,t=800){try{let[r]=await this.client.getPhotoMedia({name:`${e}/media`,maxWidthPx:t,skipHttpRedirect:!0});return r.photoUri||""}catch(r){throw f.error("Error in getPhotoUri:",r),new Error(`Failed to get photo URI: ${this.extractErrorMessage(r)}`)}}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}}}),n=await this.fetchNewestReviews(e),o=this.mergeReviews(r?.reviews||[],n),s={...r,reviews:o};return this.transformPlaceResponse(s)}catch(t){throw f.error("Error in getPlaceDetails (New API):",t),new Error(`Failed to get place details for ${e}: ${this.extractErrorMessage(t)}`)}}async fetchNewestReviews(e){try{let t=`https://maps.googleapis.com/maps/api/place/details/json?place_id=${e}&fields=reviews&reviews_sort=newest&language=${this.defaultLanguage}&key=${this.apiKey}`,r=await fetch(t);if(!r.ok)return[];let n=await r.json();return n.status!=="OK"?[]:(n.result?.reviews||[]).map(o=>({rating:o.rating,text:{text:o.text||"",languageCode:o.language||null},publishTime:{seconds:o.time},authorAttribution:{displayName:o.author_name||""}}))}catch{return[]}}mergeReviews(e,t){let r=new Set,n=[];for(let o of[...e,...t]){let s=o?.authorAttribution?.displayName||"",i=String(o?.publishTime?.seconds||""),u=`${s}|${i}`;if(!u||u==="|"){n.push(o);continue}r.has(u)||(r.add(u),n.push(o))}return n}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}},primary_type:e.primaryType||null,price_level:e.priceLevel||null,rating:e.rating||0,user_ratings_total:e.userRatingCount||0,opening_hours:{open_now:e.currentOpeningHours?.openNow??null}}}transformPlaceResponse(e){let t=e.parkingOptions?Object.fromEntries(Object.entries(e.parkingOptions).filter(([,i])=>i===!0)):void 0,r=e.accessibilityOptions?Object.fromEntries(Object.entries(e.accessibilityOptions).filter(([,i])=>i===!0)):void 0,n={};e.dineIn&&(n.dine_in=!0),e.delivery&&(n.delivery=!0),e.takeout&&(n.takeout=!0),e.curbsidePickup&&(n.curbside_pickup=!0),e.reservable&&(n.reservable=!0);let o={};e.servesVegetarianFood&&(o.vegetarian_food=!0),e.servesBeer&&(o.beer=!0),e.servesWine&&(o.wine=!0),e.servesCocktails&&(o.cocktails=!0),e.servesBreakfast&&(o.breakfast=!0),e.servesLunch&&(o.lunch=!0),e.servesDinner&&(o.dinner=!0),e.servesBrunch&&(o.brunch=!0),e.servesCoffee&&(o.coffee=!0),e.servesDessert&&(o.dessert=!0);let s={};return e.goodForGroups&&(s.good_for_groups=!0),e.goodForChildren&&(s.good_for_children=!0),e.goodForWatchingSports&&(s.good_for_watching_sports=!0),e.liveMusic&&(s.live_music=!0),e.outdoorSeating&&(s.outdoor_seating=!0),e.allowsDogs&&(s.allows_dogs=!0),e.menuForChildren&&(s.menu_for_children=!0),e.restroom&&(s.restroom=!0),{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}},primary_type:e.primaryType||null,types:e.types||[],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,editorial_summary:e.editorialSummary?.text||null,...Object.keys(t||{}).length>0?{parking:t}:{},...Object.keys(r||{}).length>0?{accessibility:r}:{},...Object.keys(n).length>0?{dining_options:n}:{},...Object.keys(o).length>0?{serves:o}:{},...Object.keys(s).length>0?{atmosphere:s}:{},...e.paymentOptions?{payment_options:Object.fromEntries(Object.entries(e.paymentOptions).filter(([i])=>!i.startsWith("_")))}:{},...e.reviewSummary?.text?.text?{review_summary:e.reviewSummary.text.text}:{},...e.generativeSummary?.overview?.text?{generative_summary:e.generativeSummary.overview.text}:{},reviews:e.reviews?.map(i=>({rating:i.rating||0,text:i.text?.text||"",language:i.text?.languageCode||null,time:i.publishTime?.seconds||0,author_name:i.authorAttribution?.displayName||""}))||[],photos:e.photos?.map(i=>({photo_reference:i.name||"",height:i.heightPx||0,width:i.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 o=1440,s=o*7,{day:i,minutes:u}=this.getLocalTimeComponents(t),a=i*o+u,g={SUNDAY:0,MONDAY:1,TUESDAY:2,WEDNESDAY:3,THURSDAY:4,FRIDAY:5,SATURDAY:6},p=c=>{if(typeof c=="number"&&c>=0&&c<=6)return c;if(typeof c=="string"){let d=c.toUpperCase();if(d in g)return g[d]}},m=c=>{if(!c)return;let d=typeof c.hours=="number"?c.hours:Number(c.hours??NaN),h=typeof c.minutes=="number"?c.minutes:Number(c.minutes??NaN);if(!(!Number.isFinite(d)||!Number.isFinite(h)))return d*60+h};for(let c of n){let d=p(c?.openDay),h=p(c?.closeDay??c?.openDay),y=m(c?.openTime),w=m(c?.closeTime);if(d===void 0||y===void 0)continue;let b=d*o+y,v;h===void 0||w===void 0?v=b+o:v=h*o+w,v<=b&&(v+=s);let I=a;for(;I<b;)I+=s;if(I>=b&&I<v)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))}};function j(l){let e=l.match(N);if(!e)return null;let t=parseFloat(e[1]),r=parseFloat(e[2]);return!Number.isFinite(t)||!Number.isFinite(r)||t<-90||t>90||r<-180||r>180?null:{lat:t,lng:r}}function $(l){return l.placeId?{placeId:l.placeId}:{latLng:{latitude:l.lat,longitude:l.lng}}}var S=class{constructor(e){this.mapsTools=new M(e),this.newPlacesService=new P(e),this.routesService=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(o=>o.opening_hours?.open_now===!0)),e.minRating&&(n=n.filter(o=>(o.rating||0)>=(e.minRating||0))),{location:t,success:!0,data:n.map(o=>({name:o.name,place_id:o.place_id,address:o.formatted_address,location:o.geometry.location,primary_type:o.primary_type||null,price_level:o.price_level||null,rating:o.rating,total_ratings:o.user_ratings_total,open_now:o.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,primary_type:r.primary_type||null,price_level:r.price_level||null,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,t=0){try{let r=await this.newPlacesService.getPlaceDetails(e),n;if(t>0&&r.photos?.length>0){let o=r.photos.slice(0,t);n=[];for(let s of o)try{let i=await this.newPlacesService.getPhotoUri(s.photo_reference);n.push({url:i,width:s.width,height:s.height})}catch{}}return{success:!0,data:{name:r.name,address:r.formatted_address,location:r.geometry?.location,primary_type:r.primary_type||null,types:r.types||[],rating:r.rating,total_ratings:r.user_ratings_total,opening_hours:r.opening_hours,phone:r.formatted_phone_number,website:r.website,price_level:r.price_level,editorial_summary:r.editorial_summary||null,...r.parking?{parking:r.parking}:{},...r.accessibility?{accessibility:r.accessibility}:{},...r.dining_options?{dining_options:r.dining_options}:{},...r.serves?{serves:r.serves}:{},...r.atmosphere?{atmosphere:r.atmosphere}:{},...r.payment_options?{payment_options:r.payment_options}:{},...r.review_summary?{review_summary:r.review_summary}:{},...r.generative_summary?{generative_summary:r.generative_summary}:{},photo_count:r.photos?.length||0,...n&&n.length>0?{photos:n}:{},reviews:r.reviews?.map(o=>({rating:o.rating,text:o.text,language:o.language||null,time:o.time,author_name:o.author_name}))}}}catch(r){return{success:!1,error:r instanceof Error?r.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",n,o,s){try{return{success:!0,data:await this.routesService.computeRouteMatrix({origins:e,destinations:t,mode:r,...n?{departureTime:new Date(n)}:{},...o!==void 0?{avoidTolls:o}:{},...s!==void 0?{avoidHighways:s}:{}})}}catch(i){return{success:!1,error:i instanceof Error?i.message:"An error occurred while calculating distance matrix"}}}async getDirections(e,t,r="driving",n,o,s,i){try{let u=n?new Date(n):void 0,a=o?new Date(o):void 0;return{success:!0,data:await this.routesService.computeRoutes({origin:e,destination:t,mode:r,...u?{departureTime:u}:{},...a?{arrivalTime:a}:{},...s!==void 0?{avoidTolls:s}:{},...i!==void 0?{avoidHighways:i}:{}})}}catch(u){return{success:!1,error:u instanceof Error?u.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,o){try{return{success:!0,data:await this.mapsTools.getWeather(e,t,r,n,o)}}catch(s){return{success:!1,error:s instanceof Error?s.message:"An error occurred while getting weather"}}}async getAirQuality(e,t,r,n){try{return{success:!0,data:await this.mapsTools.getAirQuality(e,t,r,n)}}catch(o){return{success:!1,error:o instanceof Error?o.message:"An error occurred while getting air quality"}}}async getStaticMap(e){try{return{success:!0,data:await this.mapsTools.getStaticMap(e)}}catch(t){return{success:!1,error:t instanceof Error?t.message:"An error occurred while generating static map"}}}async searchAlongRoute(e){try{return{success:!0,data:await this.mapsTools.searchAlongRoute(e)}}catch(t){return{success:!1,error:t instanceof Error?t.message:"An error occurred while searching along route"}}}async resolveLocation(e){if(N.test(e)){let n=j(e);if(!n)throw new Error(`Failed to resolve location: ${e} (not a valid "latitude,longitude" pair)`);let o=await this.geocode(e);return{originalName:e,address:o.success&&o.data?o.data.formatted_address:e,lat:n.lat,lng:n.lng,placeId:""}}let t=await this.geocode(e);if(t.success&&t.data)return{originalName:e,address:t.data.formatted_address,lat:t.data.location.lat,lng:t.data.location.lng,placeId:t.data.place_id};let r=await this.searchText({query:e});if(r.success&&r.data&&r.data.length>0){let n=r.data[0];return{originalName:e,address:n.address||n.name,lat:n.location.lat,lng:n.location.lng,placeId:n.place_id||""}}throw new Error(`Failed to resolve location: ${e} (geocoding: ${t.error||"no result"}; places text search: ${r.error||"no result"})`)}async exploreArea(e){let t=e.types||["restaurant","cafe","tourist_attraction"],r=e.radius||1e3,n=e.topN||3,o=await this.resolveLocation(e.location),{lat:s,lng:i}=o,u=[];for(let a of t){let g=await this.searchNearby({center:{value:`${s},${i}`,isCoordinates:!0},keyword:a,radius:r});if(!g.success||!g.data)continue;let p=g.data.slice(0,n),m=[];for(let c of p){if(!c.place_id)continue;let d=await this.getPlaceDetails(c.place_id);m.push({name:c.name,address:c.address,rating:c.rating,total_ratings:c.total_ratings,open_now:c.open_now,phone:d.data?.phone,website:d.data?.website})}u.push({type:a,count:g.data.length,top:m})}return{success:!0,data:{location:{address:o.address,lat:s,lng:i},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 n=[];for(let y of r)n.push(await this.resolveLocation(y));let o=$(n[0]),s=$(n[n.length-1]),i=r.length>2?n.slice(1,-1).map(y=>$(y)):void 0,u=e.optimize!==!1&&r.length>3&&t!=="transit",a=await this.routesService.computeRoutes({origin:o,destination:s,mode:t,intermediates:i,optimizeWaypointOrder:u,originLabel:r[0],destinationLabel:r[r.length-1],...e.departure_time?{departureTime:new Date(e.departure_time)}:{},...e.avoid_tolls!==void 0?{avoidTolls:e.avoid_tolls}:{},...e.avoid_highways!==void 0?{avoidHighways:e.avoid_highways}:{}}),p=a.routes[0]?.legs||[],m;if(u&&a.optimizedIntermediateWaypointIndex){let y=a.optimizedIntermediateWaypointIndex,w=n.slice(1,-1);m=[n[0],...y.map(b=>w[b]),n[n.length-1]]}else m=n;let c=[],d=0,h=0;for(let y=0;y<m.length-1;y++){let w=p[y];if(w){let b=w.distanceMeters||0,v=x(w.duration);d+=b,h+=v,c.push({from:m[y].originalName,to:m[y+1].originalName,distance:A(b),duration:k(v)})}else c.push({from:m[y].originalName,to:m[y+1].originalName,distance:"unknown",duration:"unknown",note:"Directions unavailable for this segment"})}return{success:!0,data:{mode:t,optimized:u,stops:m.map(y=>`${y.originalName} (${y.address})`),legs:c,total_distance:`${(d/1e3).toFixed(1)} km`,total_duration:`${Math.round(h/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),o=[];for(let s of n){let i=await this.getPlaceDetails(s.place_id);o.push({name:s.name,address:s.address,primary_type:i.data?.primary_type||s.primary_type||null,rating:s.rating,total_ratings:s.total_ratings,opening_hours:i.data?.opening_hours,phone:i.data?.phone,website:i.data?.website,price_level:i.data?.price_level,...i.data?.parking?{parking:i.data.parking}:{},...i.data?.serves?{serves:i.data.serves}:{},...i.data?.atmosphere?{atmosphere:i.data.atmosphere}:{},...i.data?.dining_options?{dining_options:i.data.dining_options}:{}})}if(e.userLocation&&o.length>0){let s=`${e.userLocation.latitude},${e.userLocation.longitude}`,i=n.map(a=>`${a.location.lat},${a.location.lng}`),u=await this.calculateDistanceMatrix([s],i,"driving");if(u.success&&u.data)for(let a=0;a<o.length;a++)o[a].distance=u.data.distances[0]?.[a]?.text,o[a].drive_time=u.data.durations[0]?.[a]?.text}return{success:!0,data:o}}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"}}}async localRankTracker(e){try{let t=e.gridSize||3,r=e.gridSpacing||1e3,{latitude:n,longitude:o}=e.center,s=Math.floor(t/2),i=111320,u=111320*Math.cos(n*Math.PI/180),a=[];for(let m=0;m<t;m++)for(let c=0;c<t;c++){let d=(m-s)*r,h=(c-s)*r;a.push({row:m,col:c,lat:n+d/i,lng:o+h/u})}let g="";try{let m=await this.getPlaceDetails(e.placeId);m.success&&m.data&&(g=m.data.name)}catch{}let p=[];for(let m of e.keywords){let c=await this.scanKeywordGrid(m,e.placeId,a,r);p.push({keyword:m,...c})}if(p.length===1){let m=p[0];return{success:!0,data:{target:{name:g,place_id:e.placeId},grid_size:`${t}x${t}`,grid_spacing_m:r,keyword:m.keyword,metrics:m.metrics,grid:m.grid}}}return{success:!0,data:{target:{name:g,place_id:e.placeId},grid_size:`${t}x${t}`,grid_spacing_m:r,keywords:p.map(m=>({keyword:m.keyword,metrics:m.metrics,grid:m.grid}))}}}catch(t){return{success:!1,error:t instanceof Error?t.message:"An error occurred during local rank tracking"}}}async scanKeywordGrid(e,t,r,n){let s=[],i=async d=>{try{let h=await this.newPlacesService.searchText({textQuery:e,locationBias:{lat:d.lat,lng:d.lng,radius:n/2},maxResultCount:20}),y=h.findIndex(b=>b.place_id===t),w=h.slice(0,3).map(b=>b.name||"");return{row:d.row,col:d.col,lat:Math.round(d.lat*1e6)/1e6,lng:Math.round(d.lng*1e6)/1e6,rank:y>=0?y+1:null,top3:w}}catch{return{row:d.row,col:d.col,lat:Math.round(d.lat*1e6)/1e6,lng:Math.round(d.lng*1e6)/1e6,rank:null,top3:[]}}};for(let d=0;d<r.length;d+=5){let h=r.slice(d,d+5),y=await Promise.all(h.map(i));s.push(...y)}let u=s.filter(d=>d.rank!==null),a=s.length,g=u.filter(d=>d.rank<=3).length,p=u.length>0?Math.round(u.reduce((d,h)=>d+h.rank,0)/u.length*10)/10:null,m=Math.round(s.reduce((d,h)=>d+(h.rank??21),0)/a*10)/10,c=Math.round(g/a*1e3)/10;return{metrics:{arp:p,atrp:m,solv:c,found_in:`${u.length}/${a}`},grid:s}}};var f={log:(...l)=>{console.error("[INFO]",...l)},error:(...l)=>{console.error("[ERROR]",...l)}};export{P as a,S as b,f as c};
|
|
@@ -1,66 +0,0 @@
|
|
|
1
|
-
---
|
|
2
|
-
name: mcp-google-map-project
|
|
3
|
-
description: Project knowledge for developing and maintaining @cablate/mcp-google-map. Architecture, Google Maps API guide, GIS domain knowledge, and design decisions. Read this skill to onboard onto the project or make informed development decisions.
|
|
4
|
-
version: 0.0.1
|
|
5
|
-
compatibility:
|
|
6
|
-
- claude-code
|
|
7
|
-
- cursor
|
|
8
|
-
- vscode-copilot
|
|
9
|
-
---
|
|
10
|
-
|
|
11
|
-
# mcp-google-map — Project Knowledge
|
|
12
|
-
|
|
13
|
-
## Overview
|
|
14
|
-
|
|
15
|
-
This skill contains everything needed to develop, maintain, and extend the `@cablate/mcp-google-map` MCP server. Reading these files gives you full context on architecture, API specifics, domain knowledge, and the reasoning behind design decisions.
|
|
16
|
-
|
|
17
|
-
For the **agent skill** (how to USE the tools), see `skills/google-maps/SKILL.md`.
|
|
18
|
-
|
|
19
|
-
---
|
|
20
|
-
|
|
21
|
-
## Quick Orientation
|
|
22
|
-
|
|
23
|
-
| Aspect | Summary |
|
|
24
|
-
|--------|---------|
|
|
25
|
-
| **What** | MCP server providing Google Maps tools for AI agents |
|
|
26
|
-
| **Stack** | TypeScript, Node.js, Express, MCP SDK, Zod |
|
|
27
|
-
| **Tools** | 18 tools (14 atomic + 4 composite) |
|
|
28
|
-
| **Transports** | stdio, Streamable HTTP, standalone exec CLI |
|
|
29
|
-
| **APIs** | Places API (New), Directions, Geocoding, Elevation, Timezone, Weather, Air Quality, Static Maps, Search Along Route |
|
|
30
|
-
|
|
31
|
-
---
|
|
32
|
-
|
|
33
|
-
## Reference Files
|
|
34
|
-
|
|
35
|
-
| File | Content | When to read |
|
|
36
|
-
|------|---------|--------------|
|
|
37
|
-
| `references/architecture.md` | System architecture, 3-layer design, transport modes, tool registration flow, 9-file checklist, code map | **Start here** when onboarding. Also read when adding new tools. |
|
|
38
|
-
| `references/google-maps-api-guide.md` | All Google Maps API endpoints used, pricing, coverage limits, rate limits, common gotchas, Places New vs Legacy | When debugging API errors, evaluating new APIs, or checking costs |
|
|
39
|
-
| `references/geo-domain-knowledge.md` | GIS fundamentals — coordinates, distance, geocoding, place types, spatial search, map projection, Japan-specific knowledge | When making tool design decisions that involve geographic concepts |
|
|
40
|
-
| `references/decisions.md` | 10 Architecture Decision Records (ADR) with context and rationale | When asking "why was X built this way?" or considering changes to existing design |
|
|
41
|
-
|
|
42
|
-
---
|
|
43
|
-
|
|
44
|
-
## How to Add a New Tool
|
|
45
|
-
|
|
46
|
-
See `references/architecture.md` § "9-File Tool Change Checklist" for the complete procedure. Summary:
|
|
47
|
-
|
|
48
|
-
1. Create `src/tools/maps/<toolName>.ts` (NAME, DESCRIPTION, SCHEMA, ACTION)
|
|
49
|
-
2. Register in `src/config.ts`
|
|
50
|
-
3. Add exec case in `src/cli.ts`
|
|
51
|
-
4. Add to `tests/smoke.test.ts` (expectedTools + API call test)
|
|
52
|
-
5. Update `README.md` (count + table + exec list + project structure)
|
|
53
|
-
6. Update `skills/google-maps/SKILL.md` (Tool Map)
|
|
54
|
-
7. Update `skills/google-maps/references/tools-api.md` (params + chaining)
|
|
55
|
-
8. Check `server.json` and `package.json` descriptions
|
|
56
|
-
|
|
57
|
-
---
|
|
58
|
-
|
|
59
|
-
## When to Update This Skill
|
|
60
|
-
|
|
61
|
-
| Trigger | What to update |
|
|
62
|
-
|---------|----------------|
|
|
63
|
-
| Architecture change | `references/architecture.md` |
|
|
64
|
-
| New Google Maps API integrated | `references/google-maps-api-guide.md` |
|
|
65
|
-
| New design decision made | `references/decisions.md` (add ADR) |
|
|
66
|
-
| New GIS concept relevant to tools | `references/geo-domain-knowledge.md` |
|
|
@@ -1,137 +0,0 @@
|
|
|
1
|
-
# Architecture Reference
|
|
2
|
-
|
|
3
|
-
## System Architecture Overview
|
|
4
|
-
|
|
5
|
-
Three-layer architecture with a shared entry point:
|
|
6
|
-
|
|
7
|
-
```
|
|
8
|
-
CLI / HTTP / stdio
|
|
9
|
-
|
|
|
10
|
-
BaseMcpServer <- MCP protocol layer (tool registration, transport)
|
|
11
|
-
|
|
|
12
|
-
Tool ACTION() <- thin dispatch, calls PlacesSearcher
|
|
13
|
-
|
|
|
14
|
-
PlacesSearcher <- service facade (composition, filtering, response shaping)
|
|
15
|
-
/|\
|
|
16
|
-
GoogleMapsTools RoutesService NewPlacesService
|
|
17
|
-
(geocode/tz/elev) (Routes API REST) (Places API New)
|
|
18
|
-
```
|
|
19
|
-
|
|
20
|
-
| Layer | Files | Responsibility |
|
|
21
|
-
|---|---|---|
|
|
22
|
-
| Entry | `src/cli.ts` | Parse CLI args, select transport mode, instantiate server |
|
|
23
|
-
| Protocol | `src/core/BaseMcpServer.ts` | Register tools, handle MCP sessions, route HTTP/stdio |
|
|
24
|
-
| Tool | `src/tools/maps/*.ts` | Declare NAME, DESCRIPTION, SCHEMA, ACTION |
|
|
25
|
-
| Config | `src/config.ts` | Assemble ToolConfig[], attach MAPS_TOOL_ANNOTATIONS |
|
|
26
|
-
| Facade | `src/services/PlacesSearcher.ts` | Orchestrate multi-step / composite tools |
|
|
27
|
-
| API client (routes) | `src/services/RoutesService.ts` | Routes API REST client (directions, distance matrix, waypoint optimization) |
|
|
28
|
-
| API client (legacy) | `src/services/toolclass.ts` | Wrap `@googlemaps/google-maps-services-js` SDK (geocode, timezone, elevation) |
|
|
29
|
-
| API client (places) | `src/services/NewPlacesService.ts` | Wrap `@googlemaps/places` gRPC client |
|
|
30
|
-
| Auth | `src/utils/apiKeyManager.ts` | API key priority resolution |
|
|
31
|
-
| Context | `src/utils/requestContext.ts` | Per-request AsyncLocalStorage propagation |
|
|
32
|
-
|
|
33
|
-
---
|
|
34
|
-
|
|
35
|
-
## Transport Modes
|
|
36
|
-
|
|
37
|
-
| Mode | Entry | How to activate | Notes |
|
|
38
|
-
|---|---|---|---|
|
|
39
|
-
| **HTTP (Streamable)** | `cli.ts` → `BaseMcpServer.startHttpServer()` | default, or `--port` | Listens on `/mcp` (POST/GET/DELETE); sessions tracked by UUID header `mcp-session-id` |
|
|
40
|
-
| **stdio** | `cli.ts` → `BaseMcpServer.startStdio()` | `--stdio` flag | Used by Claude Desktop, Cursor; stdout reserved for JSON-RPC, all logs go to stderr |
|
|
41
|
-
| **exec CLI** | `cli.ts` → `execTool()` | `mcp-google-map exec <tool> '<json>'` | No MCP protocol; directly calls `PlacesSearcher` method and prints JSON to stdout; used for scripting/piping |
|
|
42
|
-
|
|
43
|
-
### HTTP Session Lifecycle
|
|
44
|
-
|
|
45
|
-
```
|
|
46
|
-
POST /mcp (no session-id, isInitializeRequest)
|
|
47
|
-
-> create StreamableHTTPServerTransport
|
|
48
|
-
-> create new McpServer, connect transport
|
|
49
|
-
-> store in sessions[uuid]
|
|
50
|
-
|
|
51
|
-
POST /mcp (mcp-session-id header)
|
|
52
|
-
-> reuse existing session context
|
|
53
|
-
-> update apiKey if header present
|
|
54
|
-
|
|
55
|
-
DELETE /mcp (mcp-session-id header)
|
|
56
|
-
-> terminate session, clean up transport
|
|
57
|
-
```
|
|
58
|
-
|
|
59
|
-
---
|
|
60
|
-
|
|
61
|
-
## Tool Registration Flow
|
|
62
|
-
|
|
63
|
-
```
|
|
64
|
-
src/tools/maps/weather.ts exports Weather.{NAME, DESCRIPTION, SCHEMA, ACTION}
|
|
65
|
-
|
|
|
66
|
-
src/config.ts builds ToolConfig[] array, attaches MAPS_TOOL_ANNOTATIONS
|
|
67
|
-
|
|
|
68
|
-
src/cli.ts passes config.tools[] to new BaseMcpServer(name, tools)
|
|
69
|
-
|
|
|
70
|
-
BaseMcpServer.createMcpServer() calls server.registerTool(name, {description, inputSchema, annotations}, action)
|
|
71
|
-
|
|
|
72
|
-
@modelcontextprotocol/sdk exposes tool to MCP client
|
|
73
|
-
```
|
|
74
|
-
|
|
75
|
-
`MAPS_TOOL_ANNOTATIONS` applied to all tools:
|
|
76
|
-
|
|
77
|
-
```ts
|
|
78
|
-
{ readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true }
|
|
79
|
-
```
|
|
80
|
-
|
|
81
|
-
---
|
|
82
|
-
|
|
83
|
-
## API Key Management
|
|
84
|
-
|
|
85
|
-
Priority order (highest to lowest):
|
|
86
|
-
|
|
87
|
-
| Priority | Source | Header / Variable |
|
|
88
|
-
|---|---|---|
|
|
89
|
-
| 1 | HTTP request header | `X-Google-Maps-API-Key` |
|
|
90
|
-
| 2 | HTTP Authorization header | `Authorization: Bearer <key>` |
|
|
91
|
-
| 3 | Session-specific key | stored per `mcp-session-id` |
|
|
92
|
-
| 4 | CLI argument | `--apikey` / `-k` |
|
|
93
|
-
| 5 | Environment variable | `GOOGLE_MAPS_API_KEY` |
|
|
94
|
-
| 6 | `.env` file | loaded by `dotenv` at startup from `cwd` or package dir |
|
|
95
|
-
|
|
96
|
-
**Flow in HTTP mode**: `ApiKeyManager.getApiKey(req)` resolves key → stored in `SessionContext.apiKey` → propagated via `runWithContext()` (AsyncLocalStorage) → tool action reads from context or `process.env`.
|
|
97
|
-
|
|
98
|
-
**Flow in exec mode**: `--apikey` arg → directly passed to `new PlacesSearcher(apiKey)` constructor.
|
|
99
|
-
|
|
100
|
-
---
|
|
101
|
-
|
|
102
|
-
## Adding a New Tool — 9-File Checklist
|
|
103
|
-
|
|
104
|
-
From `CLAUDE.md`:
|
|
105
|
-
|
|
106
|
-
| # | File | What to update |
|
|
107
|
-
|---|---|---|
|
|
108
|
-
| 1 | `src/tools/maps/<toolName>.ts` | Define NAME, DESCRIPTION, SCHEMA, ACTION |
|
|
109
|
-
| 2 | `src/config.ts` | Add to `tools[]` array with annotations |
|
|
110
|
-
| 3 | `src/cli.ts` | Add to `EXEC_TOOLS` const + `switch` case in `execTool()` |
|
|
111
|
-
| 4 | `tests/smoke.test.ts` | Add to `expectedTools` array + update tool count assertions |
|
|
112
|
-
| 5 | `README.md` | Update tool count (header, comparison table, Server Info, exec mode) + Available Tools table + Project Structure |
|
|
113
|
-
| 6 | `skills/google-maps/SKILL.md` | Add row to Tool Map table |
|
|
114
|
-
| 7 | `skills/google-maps/references/tools-api.md` | Add parameter docs + chaining patterns |
|
|
115
|
-
| 8 | `server.json` | Update description if it mentions tool count |
|
|
116
|
-
| 9 | `package.json` | Update description if it mentions tool count |
|
|
117
|
-
|
|
118
|
-
Missing any file causes doc/behavior mismatch. Verify all before opening a PR.
|
|
119
|
-
|
|
120
|
-
---
|
|
121
|
-
|
|
122
|
-
## Code Map
|
|
123
|
-
|
|
124
|
-
| File | Purpose |
|
|
125
|
-
|---|---|
|
|
126
|
-
| `src/cli.ts` | CLI entry point — parses args, selects transport, dispatches exec mode |
|
|
127
|
-
| `src/config.ts` | Assembles ToolConfig[] array from all tool modules |
|
|
128
|
-
| `src/core/BaseMcpServer.ts` | MCP server core — tool registration, HTTP session management, stdio transport |
|
|
129
|
-
| `src/index.ts` | Package entry — exports Logger and re-exports public API |
|
|
130
|
-
| `src/services/PlacesSearcher.ts` | Service facade — orchestrates multi-step composite tools (planRoute, exploreArea, comparePlaces, searchAlongRoute) |
|
|
131
|
-
| `src/services/RoutesService.ts` | Routes API REST client — computeRoutes (directions), computeRouteMatrix (distance matrix), waypoint optimization |
|
|
132
|
-
| `src/services/toolclass.ts` | Google Maps SDK wrapper — geocode, elevation, timezone, weather, airQuality, staticMap, searchAlongRoute |
|
|
133
|
-
| `src/services/NewPlacesService.ts` | Places API (New) client — searchNearby, searchText, getPlaceDetails via gRPC |
|
|
134
|
-
| `src/tools/maps/*.ts` | Individual tool definitions (17 files) — each exports NAME, DESCRIPTION, SCHEMA, ACTION |
|
|
135
|
-
| `src/utils/apiKeyManager.ts` | Singleton — resolves API key priority from headers / session / env |
|
|
136
|
-
| `src/utils/requestContext.ts` | AsyncLocalStorage — propagates API key within a single request lifecycle |
|
|
137
|
-
| `tests/smoke.test.ts` | Integration smoke tests — validates tool list, basic API calls |
|
|
@@ -1,149 +0,0 @@
|
|
|
1
|
-
# Architecture Decision Records — mcp-google-map
|
|
2
|
-
|
|
3
|
-
> Format: Decision / Context / Rationale
|
|
4
|
-
> Sources: dev-roadmap-spec.md, CLAUDE.md, project history
|
|
5
|
-
|
|
6
|
-
---
|
|
7
|
-
|
|
8
|
-
## ADR-001: Unified `maps_` Prefix for All Tool Names
|
|
9
|
-
|
|
10
|
-
**Decision**: All tools are named with the `maps_` prefix (e.g., `maps_geocode`, `maps_search_nearby`). This was applied as a breaking change when the namespace was standardized.
|
|
11
|
-
|
|
12
|
-
**Context**: Early tool names were inconsistent — some had prefixes, some did not. As the tool count grew and the server was listed on MCP registries, namespace collisions with other MCP servers became a concern. Claude's tool selection also benefits from a clear namespace signal.
|
|
13
|
-
|
|
14
|
-
**Rationale**:
|
|
15
|
-
- Consistent namespace prevents collision when multiple MCP servers are active simultaneously.
|
|
16
|
-
- The `maps_` prefix gives Claude a strong disambiguation signal — it knows these tools are geospatial without reading descriptions.
|
|
17
|
-
- Breaking change was accepted early (pre-stable) to avoid accumulating technical debt. All 9 files in the Tool Change Checklist must be updated together on any rename.
|
|
18
|
-
|
|
19
|
-
---
|
|
20
|
-
|
|
21
|
-
## ADR-002: `compare_places` Retained as a Composite Tool
|
|
22
|
-
|
|
23
|
-
**Decision**: `maps_compare_places` is a single tool that internally fetches details for multiple places and returns a structured comparison. It is not decomposed into atomic `place_details` calls that the AI chains together.
|
|
24
|
-
|
|
25
|
-
**Context**: An alternative design would have the AI call `maps_place_details` N times and synthesize the comparison itself. During testing, this produced inconsistent output quality and required users to explicitly orchestrate the chain.
|
|
26
|
-
|
|
27
|
-
**Rationale**:
|
|
28
|
-
- Users ask "compare these restaurants" and expect a comparison table, not raw data to synthesize.
|
|
29
|
-
- Composite tools reduce chaining overhead and produce deterministic, structured output.
|
|
30
|
-
- The Geo-Reasoning Benchmark (GRB) validates this: Composite Efficiency Score (CES) rewards using 1 call instead of N calls. `compare_places` is the reference case for this metric.
|
|
31
|
-
- User preference confirmed: users do not want to manually chain atomic calls for comparison tasks.
|
|
32
|
-
|
|
33
|
-
---
|
|
34
|
-
|
|
35
|
-
## ADR-003: `maps_weather` and `maps_air_quality` as Separate Tools
|
|
36
|
-
|
|
37
|
-
**Decision**: Weather and air quality are exposed as two independent tools, not combined into a single `maps_environment` tool.
|
|
38
|
-
|
|
39
|
-
**Context**: A natural grouping might combine weather and air quality into one "environmental conditions" call. Both return ambient data about a location.
|
|
40
|
-
|
|
41
|
-
**Rationale**:
|
|
42
|
-
- **Different APIs**: Weather uses one endpoint; Air Quality uses `POST https://airquality.googleapis.com/v1/currentConditions:lookup` — a completely separate Google service requiring separate API enablement.
|
|
43
|
-
- **Different geographic coverage**: Weather API does not support Japan. Air Quality API fully supports Japan (including AEROS local index). Combining them would require complex conditional logic and mislead users about availability.
|
|
44
|
-
- **Different data structures and use cases**: Weather is for planning (will it rain?). Air quality is for health decisions (should I wear a mask? can elderly parents go outside?). The 7-demographic health recommendation field in air quality has no analogue in weather.
|
|
45
|
-
- **Independent billing**: Separate pricing makes cost attribution cleaner.
|
|
46
|
-
|
|
47
|
-
---
|
|
48
|
-
|
|
49
|
-
## ADR-004: `maps_isochrone` Not Built
|
|
50
|
-
|
|
51
|
-
**Decision**: Isochrone generation (travel-time polygons) is excluded from the roadmap, marked as "Skip for now."
|
|
52
|
-
|
|
53
|
-
**Context**: Isochrones are a commonly requested GIS feature — "show me everywhere I can reach in 30 minutes." They are valuable for real estate analysis, event planning, and accessibility research.
|
|
54
|
-
|
|
55
|
-
**Rationale**:
|
|
56
|
-
- **Google has no native isochrone API.** All alternative implementations have disqualifying problems:
|
|
57
|
-
- Mapbox Isochrone API: mature, but introduces a second vendor (Mapbox key) alongside Google — breaks the single-provider positioning.
|
|
58
|
-
- OpenRouteService: free but rate-limited and stability uncertain for production use.
|
|
59
|
-
- Distance Matrix grid approximation: 24+ API calls per isochrone at ~$0.12/request; prohibitively expensive and low-accuracy.
|
|
60
|
-
- **Core value is visual**: An isochrone polygon is only meaningful when rendered on a map. Without `maps_static_map` to display it, returning raw GeoJSON coordinates is not useful to AI or users. The feature was deprioritized until static map rendering was in place.
|
|
61
|
-
- **Revisit path**: If built later, the best approach is Distance Matrix 8-direction probing + `maps_static_map` to render an approximated polygon. Estimated effort: 8 hours.
|
|
62
|
-
|
|
63
|
-
---
|
|
64
|
-
|
|
65
|
-
## ADR-005: `maps_validate_address` Not Built
|
|
66
|
-
|
|
67
|
-
**Decision**: Address validation (checking if a postal address is deliverable) is excluded from the tool set.
|
|
68
|
-
|
|
69
|
-
**Context**: Google's Address Validation API provides USPS CASS-certified validation, deliverability flags, and address correction. It could theoretically be useful for any tool that takes address inputs.
|
|
70
|
-
|
|
71
|
-
**Rationale**:
|
|
72
|
-
- **Cost**: $17 per 1,000 requests — 3.4× the cost of standard geocoding. This is prohibitive for conversational AI use where users make casual address queries.
|
|
73
|
-
- **Wrong use case**: Address validation is designed for backend pipelines (e-commerce checkout, CRM deduplication, bulk mailing). It requires structured postal input and returns structured postal corrections — not a natural fit for natural-language AI conversations.
|
|
74
|
-
- **Coverage gap**: Only 38 countries supported; excludes most of Asia and Africa. A tool that silently fails for Tokyo or Mumbai addresses would create confusing UX.
|
|
75
|
-
- **Existing alternative**: `maps_geocode` already handles 60% of "is this address valid?" scenarios by returning whether a geocode succeeded and providing the `formatted_address` canonical form.
|
|
76
|
-
|
|
77
|
-
---
|
|
78
|
-
|
|
79
|
-
## ADR-006: Spatial Context / Session Memory Not Built
|
|
80
|
-
|
|
81
|
-
**Decision**: There is no persistent spatial context or session memory layer in the MCP server. The server does not remember previously queried locations or build a "current location" state across calls.
|
|
82
|
-
|
|
83
|
-
**Context**: A proposed feature was to maintain implicit state — if a user asks "find coffee shops" after previously mentioning "I'm in Shinjuku," the server would remember Shinjuku and use it as the implicit location for the next search.
|
|
84
|
-
|
|
85
|
-
**Rationale**:
|
|
86
|
-
- **Claude's conversation history already solves this.** Claude reads its own prior messages and can extract previously mentioned locations. A server-side memory layer would duplicate capability that already exists in the LLM.
|
|
87
|
-
- **Composite tools reduce chaining need.** Tools like `maps_explore_area` and `maps_plan_route` accept multi-intent inputs that would otherwise require chaining with location state.
|
|
88
|
-
- **Implementation risks outweigh benefits**:
|
|
89
|
-
- Implicit state leakage: state from one user's session could bleed into another in concurrent scenarios.
|
|
90
|
-
- Debugging opacity: errors become harder to trace when the server has hidden state.
|
|
91
|
-
- stdio transport has no session concept — each stdio connection is stateless by design.
|
|
92
|
-
- **User value assessed at 3/10.** In testing, users could not perceive a meaningful difference. The friction of unexpected state (wrong implicit location) outweighed the convenience.
|
|
93
|
-
|
|
94
|
-
---
|
|
95
|
-
|
|
96
|
-
## ADR-007: stdio as Primary Transport
|
|
97
|
-
|
|
98
|
-
**Decision**: The MCP server uses stdio (standard input/output) as its primary transport mechanism. HTTP/SSE is secondary.
|
|
99
|
-
|
|
100
|
-
**Context**: MCP servers can expose transport via stdio (subprocess model) or HTTP+SSE (network server model). Both are valid per the MCP specification.
|
|
101
|
-
|
|
102
|
-
**Rationale**:
|
|
103
|
-
- **MCP Registry requirement**: The official MCP registry and most client integrations (Claude Desktop, Claude Code, Cursor) prefer or require stdio-based servers for local installation.
|
|
104
|
-
- **Security model**: stdio servers run as a subprocess of the client, inheriting the client's trust context. No network port exposure, no authentication complexity.
|
|
105
|
-
- **Deployment simplicity**: `npx mcp-google-map` works out of the box without configuring ports, firewalls, or SSL.
|
|
106
|
-
- **Statelessness aligns with stdio**: Each stdio connection represents one session. This reinforces ADR-006 (no spatial context) — the transport model naturally discourages stateful designs.
|
|
107
|
-
|
|
108
|
-
---
|
|
109
|
-
|
|
110
|
-
## ADR-008: Search Along Route Uses Direct REST Calls
|
|
111
|
-
|
|
112
|
-
**Decision**: The "search along route" capability calls the Google Maps REST API directly rather than using the official `@googlemaps/google-maps-services-js` client library.
|
|
113
|
-
|
|
114
|
-
**Context**: Most tools in this project use the official client library for consistency and type safety. The route-based search requires fetching a polyline and then querying points along it — a pattern not natively supported by the client library.
|
|
115
|
-
|
|
116
|
-
**Rationale**:
|
|
117
|
-
- **Client library may not expose the required parameters or patterns** for buffered route searches. The REST API is always the source of truth; the client library is a convenience wrapper.
|
|
118
|
-
- **Direct REST calls are straightforward**: for GET requests with query parameters, `axios` or `fetch` is sufficient and keeps the implementation explicit.
|
|
119
|
-
- **Type safety can be maintained** by defining TypeScript interfaces for the REST response shapes — same outcome as using the library, without library constraints.
|
|
120
|
-
- This is an exception to the general project preference for the client library, justified by the specific technical requirement.
|
|
121
|
-
|
|
122
|
-
---
|
|
123
|
-
|
|
124
|
-
## ADR-009: MCP Prompt Templates Removed
|
|
125
|
-
|
|
126
|
-
**Decision**: MCP Prompt Templates (slash commands like `/travel-planner`) were evaluated and ultimately not shipped as a feature.
|
|
127
|
-
|
|
128
|
-
**Context**: The roadmap spec (P1-1) proposed implementing MCP's `prompts` primitive to expose slash commands in clients like Claude Desktop. The intended value was giving non-technical users a one-click entry into geo agent mode.
|
|
129
|
-
|
|
130
|
-
**Rationale**:
|
|
131
|
-
- **Client support is low and inconsistent.** As of evaluation, most MCP clients either do not render prompt templates as slash commands or render them inconsistently. The feature would benefit a small fraction of users.
|
|
132
|
-
- **SKILL.md already covers the use case** for Claude Code users — the skill system provides rich scenario guidance, chaining patterns, and example recipes that go beyond what prompt templates support.
|
|
133
|
-
- **Maintenance cost**: Prompt template content would need to stay in sync with tool capabilities, adding to the already-significant 9-file update checklist (CLAUDE.md ADR).
|
|
134
|
-
- **Revisit condition**: If MCP client support for prompts reaches broad adoption (Claude Desktop, VS Code extension, Cursor all render them consistently), this should be reconsidered. The 6-hour implementation estimate is low.
|
|
135
|
-
|
|
136
|
-
---
|
|
137
|
-
|
|
138
|
-
## ADR-010: Travel Planning Uses "Tool-Driven Diffusion," Not AI Prior Knowledge
|
|
139
|
-
|
|
140
|
-
**Decision**: Travel planning workflows are designed so the AI discovers ground truth by calling tools, not by relying on training-data knowledge of specific places, hours, or transit schedules.
|
|
141
|
-
|
|
142
|
-
**Context**: An AI could answer "what time does Kinkaku-ji open?" from training data. It could suggest a Tokyo itinerary without any tool calls based on memorized "best of Tokyo" patterns. This is faster but fragile.
|
|
143
|
-
|
|
144
|
-
**Rationale**:
|
|
145
|
-
- **Training data goes stale.** Business hours change, places close, new venues open. A tool call to `maps_place_details` returns current data; training knowledge reflects a past snapshot.
|
|
146
|
-
- **Specificity requires data.** A user asking for restaurants near their hotel requires the actual hotel coordinates, not generic neighborhood knowledge. The tool call chain (geocode hotel → search nearby → get details) produces a personalized result that training data cannot replicate.
|
|
147
|
-
- **Verifiability and trust.** When the AI cites data from a tool response (e.g., "Fushimi Inari opens at 6 AM according to Google Maps"), users can verify the source. When it speaks from training data, there is no audit trail.
|
|
148
|
-
- **The SKILL.md geo-domain knowledge** (temple hours, transit rules, energy curves) is intentionally at the *pattern* level — it tells the AI *how* to plan, not *what* specific facts are. The facts come from tools. This separation is the core design principle.
|
|
149
|
-
- Practical implementation: always geocode place names (don't assume coordinates), always fetch operating hours from `maps_place_details` (don't assume 9–5), always calculate transit time with `maps_directions` (don't estimate from distance).
|