Skip to main content
Glama
isdaniel

Weather MCP Server

get_air_quality

Retrieve air quality data for a city including PM2.5, PM10, ozone, and other pollutants. Get health advisories based on current levels.

Instructions

Get air quality information for a specified city including PM2.5, PM10, ozone, nitrogen dioxide, carbon monoxide, and other pollutants. Provides health advisories based on current air quality levels.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
cityYesThe name of the city to fetch air quality information for, PLEASE NOTE English name only, if the parameter city isn't English please translate to English before invoking this function.
variablesNoAir quality variables to retrieve. If not specified, defaults to pm10, pm2_5, ozone, nitrogen_dioxide, and carbon_monoxide.

Implementation Reference

  • The main handler function for the 'get_air_quality' tool. It validates inputs (city, optional variables), geocodes the city to coordinates, fetches air quality data from the service, extracts current values, and formats a comprehensive response with field descriptions for AI analysis.
    async def run_tool(self, args: dict) -> Sequence[TextContent | ImageContent | EmbeddedResource]:
        """
        Execute the air quality tool.
        """
        try:
            self.validate_required_args(args, ["city"])
    
            city = args["city"]
            variables = args.get("variables", [
                "pm10", "pm2_5", "ozone", "nitrogen_dioxide", "carbon_monoxide"
            ])
    
            logger.info(f"Getting air quality for: {city} with variables: {variables}")
    
            # Get coordinates for the city
            latitude, longitude = await self.weather_service.get_coordinates(city)
    
            # Get air quality data
            aq_data = await self.air_quality_service.get_air_quality(
                latitude, longitude, variables
            )
    
            # Get current air quality values
            current_aq = self.air_quality_service.get_current_air_quality_index(aq_data)
    
            # Build comprehensive response data for AI comprehension
            response_data = {
                "city": city,
                "latitude": latitude,
                "longitude": longitude,
                "current_air_quality": current_aq,
                "full_data": aq_data
            }
    
            # Format the response with comprehensive field descriptions
            formatted_response = self.air_quality_service.format_air_quality_comprehensive(
                response_data
            )
    
            return [
                TextContent(
                    type="text",
                    text=formatted_response
                )
            ]
    
        except ValueError as e:
            logger.error(f"Air quality service error: {str(e)}")
            return [
                TextContent(
                    type="text",
                    text=f"Error: {str(e)}"
                )
            ]
        except Exception as e:
            logger.exception(f"Unexpected error in get_air_quality: {str(e)}")
            return [
                TextContent(
                    type="text",
                    text=f"Unexpected error occurred: {str(e)}"
                )
            ]
  • Schema/input validation definition for the 'get_air_quality' tool. Defines the tool name, description, and input schema with required 'city' (string) and optional 'variables' (array of pollutant enums).
    def get_tool_description(self) -> Tool:
        """
        Return the tool description for air quality lookup.
        """
        return Tool(
            name=self.name,
            description="""Get air quality information for a specified city including PM2.5, PM10,
            ozone, nitrogen dioxide, carbon monoxide, and other pollutants. Provides health
            advisories based on current air quality levels.""",
            inputSchema={
                "type": "object",
                "properties": {
                    "city": {
                        "type": "string",
                        "description": "The name of the city to fetch air quality information for, PLEASE NOTE English name only, if the parameter city isn't English please translate to English before invoking this function."
                    },
                    "variables": {
                        "type": "array",
                        "items": {
                            "type": "string",
                            "enum": [
                                "pm10",
                                "pm2_5",
                                "carbon_monoxide",
                                "nitrogen_dioxide",
                                "ozone",
                                "sulphur_dioxide",
                                "ammonia",
                                "dust",
                                "aerosol_optical_depth"
                            ]
                        },
                        "description": "Air quality variables to retrieve. If not specified, defaults to pm10, pm2_5, ozone, nitrogen_dioxide, and carbon_monoxide."
                    }
                },
                "required": ["city"]
            }
        )
  • Registration of the GetAirQualityToolHandler in the central register_all_tools() function, binding the handler to the server's tool handler registry.
    # Air quality tools
    add_tool_handler(GetAirQualityToolHandler())
    add_tool_handler(GetAirQualityDetailsToolHandler())
  • The AirQualityService.get_air_quality() method that actually calls the Open-Meteo Air Quality API to fetch pollutant data for given coordinates.
    async def get_air_quality(
        self,
        latitude: float,
        longitude: float,
        hourly_vars: List[str] = None
    ) -> Dict[str, Any]:
        """
        Get air quality data for given coordinates.
    
        Args:
            latitude: Latitude coordinate
            longitude: Longitude coordinate
            hourly_vars: List of hourly variables to retrieve
    
        Returns:
            Air quality data dictionary
    
        Raises:
            ValueError: If air quality data cannot be retrieved
        """
        if hourly_vars is None:
            hourly_vars = ["pm10", "pm2_5", "ozone", "nitrogen_dioxide", "carbon_monoxide"]
    
        hourly_str = ",".join(hourly_vars)
    
        url = (
            f"{self.BASE_AIR_QUALITY_URL}"
            f"?latitude={latitude}&longitude={longitude}"
            f"&hourly={hourly_str}"
            f"&timezone=GMT"
        )
    
        logger.info(f"Fetching air quality data from: {url}")
    
        try:
            async with httpx.AsyncClient() as client:
                response = await client.get(url)
    
                if response.status_code != 200:
                    raise ValueError(f"Air Quality API returned status {response.status_code}")
    
                return response.json()
    
        except httpx.RequestError as e:
            raise ValueError(f"Network error while fetching air quality data: {str(e)}")
        except (KeyError, IndexError) as e:
            raise ValueError(f"Invalid response format from air quality API: {str(e)}")
Behavior3/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description bears the full burden. It lists the pollutants returned and mentions health advisories, but does not disclose any behavioral traits such as data freshness, units, potential errors, or rate limits. It is adequate but lacks depth.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is two sentences, front-loaded with the purpose, and contains no unnecessary words. Every sentence adds value and is well-structured.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the simple parameter set (2 params) and no output schema, the description is fairly complete. It explains available variables and default behavior. It could be improved by mentioning the output format or example usage, but it is sufficient for a basic retrieval tool.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The input schema has 100% coverage with descriptions for both parameters. The description adds crucial context: for the 'city' parameter, it instructs to translate non-English names to English, and for 'variables', it specifies the defaults. This goes beyond the schema definitions.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's function: getting air quality information for a specified city, including specific pollutants and health advisories. It distinguishes itself from sibling tools like 'get_air_quality_details' and weather/time tools by focusing on air quality data.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines3/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides a clear context for when to use the tool (to get air quality info) but does not explicitly state when not to use it or how it differs from the sibling 'get_air_quality_details'. No exclusions or alternatives are mentioned.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

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/isdaniel/mcp_weather_server'

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