Skip to main content
Glama
gitPratikSingh

Weather MCP Server

search_locations

Find location names by entering a search query to identify places for weather data retrieval.

Instructions

Search for location names matching a query string

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYesSearch query for location name

Implementation Reference

  • Core implementation of the search_locations tool: searches OpenWeatherMap geo API for locations matching the query, with caching and mock fallback.
    async def search_locations(self, query: str) -> List[Dict]:
        """
        Search for locations matching the query.
        
        Args:
            query: Search query string
            
        Returns:
            List of matching locations
        """
        query = query.strip()
        
        # If no API key, return mock locations
        if not self.api_key:
            return self._get_mock_locations(query)
        
        try:
            async with httpx.AsyncClient() as client:
                url = "https://api.openweathermap.org/geo/1.0/direct"
                params = {
                    "q": query,
                    "limit": 5,
                    "appid": self.api_key
                }
                response = await client.get(url, params=params, timeout=10.0)
                response.raise_for_status()
                data = response.json()
                
                locations = []
                for item in data:
                    locations.append({
                        "name": item.get("name", ""),
                        "country": item.get("country", ""),
                        "state": item.get("state", ""),
                        "lat": item.get("lat", 0),
                        "lon": item.get("lon", 0),
                    })
                
                return locations
                
        except httpx.HTTPError:
            # Fallback to mock locations on API error
            return self._get_mock_locations(query)
  • main.py:65-78 (registration)
    Tool registration in list_tools(): defines name, description, and input schema for search_locations.
    Tool(
        name="search_locations",
        description="Search for location names matching a query string",
        inputSchema={
            "type": "object",
            "properties": {
                "query": {
                    "type": "string",
                    "description": "Search query for location name"
                }
            },
            "required": ["query"]
        }
    ),
  • main.py:115-127 (handler)
    Dispatch handler in call_tool(): extracts query argument, validates, calls weather_api.search_locations, and returns JSON response.
    elif name == "search_locations":
        query = arguments.get("query", "")
        if not query:
            return [TextContent(
                type="text",
                text="Error: query parameter is required"
            )]
        
        locations = await weather_api.search_locations(query)
        return [TextContent(
            type="text",
            text=json.dumps(locations, indent=2)
        )]
  • Helper function providing mock location data when API key is missing or on API error.
    def _get_mock_locations(self, query: str) -> List[Dict]:
        """Return mock location search results for demo purposes."""
        # Common cities that might match
        common_cities = [
            {"name": "New York", "country": "US", "state": "New York", "lat": 40.7128, "lon": -74.0060},
            {"name": "London", "country": "GB", "state": "", "lat": 51.5074, "lon": -0.1278},
            {"name": "Paris", "country": "FR", "state": "", "lat": 48.8566, "lon": 2.3522},
            {"name": "Tokyo", "country": "JP", "state": "", "lat": 35.6762, "lon": 139.6503},
            {"name": "San Francisco", "country": "US", "state": "California", "lat": 37.7749, "lon": -122.4194},
        ]
        
        # Filter by query (case-insensitive)
        query_lower = query.lower()
        matches = [city for city in common_cities if query_lower in city["name"].lower()]
        
        # If no matches, return all cities
        return matches if matches else common_cities[:3]

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/gitPratikSingh/weather_mcp_server'

If you have feedback or need assistance with the MCP directory API, please join our Discord server