Skip to main content
Glama
robertn702

OpenWeatherMap MCP Server

get-current-air-pollution

Retrieve real-time air quality data for any location using city name or coordinates. Access accurate pollution levels via the OpenWeatherMap MCP Server to monitor environmental conditions effectively.

Instructions

Get current air quality data

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
locationYesCity name (e.g., 'New York') or coordinates (e.g., 'lat,lon')

Implementation Reference

  • src/main.ts:519-626 (registration)
    Registers the 'get-current-air-pollution' tool with the MCP server, including the inline handler function that fetches and formats current air pollution data.
    server.addTool({
      name: "get-current-air-pollution",
      description: "Get current air quality data",
      parameters: getCurrentAirPollutionSchema,
      execute: async (args, { session, log }) => {
        try {
          log.info("Getting current air pollution", { 
            location: args.location
          });
          
          // Get OpenWeather client
          const client = getOpenWeatherClient(session as SessionData | undefined);
          
          // Configure client for this request
          configureClientForLocation(client, args.location);
          
          // Fetch current air pollution data
          const pollutionData = await client.getCurrentAirPollution();
          
          log.info("Successfully retrieved current air pollution", { 
            location: args.location,
            aqi: pollutionData.aqi
          });
          
          // Format the response
          const formattedPollution = JSON.stringify({
            location: args.location,
            coordinates: {
              latitude: pollutionData.lat,
              longitude: pollutionData.lon
            },
            air_quality: {
              index: pollutionData.aqi,
              description: pollutionData.aqiName,
              scale: "1 (Good) to 5 (Very Poor)"
            },
            pollutants: {
              carbon_monoxide: {
                value: pollutionData.components.co,
                unit: "μg/m³",
                description: "Carbon monoxide"
              },
              nitrogen_monoxide: {
                value: pollutionData.components.no,
                unit: "μg/m³",
                description: "Nitrogen monoxide"
              },
              nitrogen_dioxide: {
                value: pollutionData.components.no2,
                unit: "μg/m³",
                description: "Nitrogen dioxide"
              },
              ozone: {
                value: pollutionData.components.o3,
                unit: "μg/m³",
                description: "Ozone"
              },
              sulphur_dioxide: {
                value: pollutionData.components.so2,
                unit: "μg/m³",
                description: "Sulphur dioxide"
              },
              pm2_5: {
                value: pollutionData.components.pm2_5,
                unit: "μg/m³",
                description: "Fine particles matter"
              },
              pm10: {
                value: pollutionData.components.pm10,
                unit: "μg/m³",
                description: "Coarse particulate matter"
              },
              ammonia: {
                value: pollutionData.components.nh3,
                unit: "μg/m³",
                description: "Ammonia"
              }
            },
            timestamp: pollutionData.dt.toISOString()
          }, null, 2);
          
          return {
            content: [
              {
                type: "text",
                text: formattedPollution
              }
            ]
          };
        } catch (error) {
          log.error("Failed to get current air pollution", { 
            error: error instanceof Error ? error.message : 'Unknown error' 
          });
          
          // Provide helpful error messages
          if (error instanceof Error) {
            if (error.message.includes('city not found')) {
              throw new Error(`Location "${args.location}" not found. Please check the spelling or try using coordinates.`);
            }
            if (error.message.includes('Invalid API key')) {
              throw new Error('Invalid OpenWeatherMap API key. Please check your configuration.');
            }
          }
          
          throw new Error(`Failed to get current air pollution: ${error instanceof Error ? error.message : 'Unknown error'}`);
        }
      }
    });
  • The execute function that implements the tool logic: resolves OpenWeather client, configures location, fetches pollution data, formats it with AQI and pollutants, returns formatted JSON.
    execute: async (args, { session, log }) => {
      try {
        log.info("Getting current air pollution", { 
          location: args.location
        });
        
        // Get OpenWeather client
        const client = getOpenWeatherClient(session as SessionData | undefined);
        
        // Configure client for this request
        configureClientForLocation(client, args.location);
        
        // Fetch current air pollution data
        const pollutionData = await client.getCurrentAirPollution();
        
        log.info("Successfully retrieved current air pollution", { 
          location: args.location,
          aqi: pollutionData.aqi
        });
        
        // Format the response
        const formattedPollution = JSON.stringify({
          location: args.location,
          coordinates: {
            latitude: pollutionData.lat,
            longitude: pollutionData.lon
          },
          air_quality: {
            index: pollutionData.aqi,
            description: pollutionData.aqiName,
            scale: "1 (Good) to 5 (Very Poor)"
          },
          pollutants: {
            carbon_monoxide: {
              value: pollutionData.components.co,
              unit: "μg/m³",
              description: "Carbon monoxide"
            },
            nitrogen_monoxide: {
              value: pollutionData.components.no,
              unit: "μg/m³",
              description: "Nitrogen monoxide"
            },
            nitrogen_dioxide: {
              value: pollutionData.components.no2,
              unit: "μg/m³",
              description: "Nitrogen dioxide"
            },
            ozone: {
              value: pollutionData.components.o3,
              unit: "μg/m³",
              description: "Ozone"
            },
            sulphur_dioxide: {
              value: pollutionData.components.so2,
              unit: "μg/m³",
              description: "Sulphur dioxide"
            },
            pm2_5: {
              value: pollutionData.components.pm2_5,
              unit: "μg/m³",
              description: "Fine particles matter"
            },
            pm10: {
              value: pollutionData.components.pm10,
              unit: "μg/m³",
              description: "Coarse particulate matter"
            },
            ammonia: {
              value: pollutionData.components.nh3,
              unit: "μg/m³",
              description: "Ammonia"
            }
          },
          timestamp: pollutionData.dt.toISOString()
        }, null, 2);
        
        return {
          content: [
            {
              type: "text",
              text: formattedPollution
            }
          ]
        };
      } catch (error) {
        log.error("Failed to get current air pollution", { 
          error: error instanceof Error ? error.message : 'Unknown error' 
        });
        
        // Provide helpful error messages
        if (error instanceof Error) {
          if (error.message.includes('city not found')) {
            throw new Error(`Location "${args.location}" not found. Please check the spelling or try using coordinates.`);
          }
          if (error.message.includes('Invalid API key')) {
            throw new Error('Invalid OpenWeatherMap API key. Please check your configuration.');
          }
        }
        
        throw new Error(`Failed to get current air pollution: ${error instanceof Error ? error.message : 'Unknown error'}`);
      }
    }
  • Zod schema defining input parameters for the tool: a location string (city or coordinates).
    export const getCurrentAirPollutionSchema = z.object({
      location: z.string().describe("City name (e.g., 'New York') or coordinates (e.g., 'lat,lon')"),
    });
  • Helper function to get or create a cached OpenWeatherAPI client instance based on the session's API key.
    export function getOpenWeatherClient(session: SessionData | null | undefined): OpenWeatherAPI {
      // For stdio transport, use the global session
      const effectiveSession = session || getStdioSession();
    
      if (!effectiveSession) {
        throw new Error("No authentication session available");
      }
    
      const { apiKey } = effectiveSession;
    
      // Check cache first
      let client = clientCache.get(apiKey);
      
      if (!client) {
        // Create new client
        client = new OpenWeatherAPI({
          key: apiKey,
          // Default to metric units, can be overridden per request
          units: "metric"
        });
    
        // Cache the client
        clientCache.set(apiKey, client);
      }
    
      return client;
    }
  • Helper to parse location string and configure the API client with coordinates or city name.
    export function configureClientForLocation(
      client: OpenWeatherAPI, 
      location: string, 
      units?: Units
    ): OpenWeatherAPI {
      // Parse location
      const parsed = parseLocation(location);
      
      // Set location based on type
      if (parsed.type === 'coordinates' && parsed.latitude && parsed.longitude) {
        client.setLocationByCoordinates(parsed.latitude, parsed.longitude);
      } else if (parsed.type === 'city' && parsed.city) {
        client.setLocationByName(parsed.city);
      } else {
        throw new Error("Invalid location format");
      }
      
      // Set units if provided
      if (units) {
        client.setUnits(units);
      }
      
      return client;
    }
Behavior2/5

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

With no annotations provided, the description carries full burden for behavioral disclosure. 'Get current air quality data' implies a read-only operation but doesn't specify data freshness, rate limits, authentication requirements, error conditions, or response format. For a tool that likely makes external API calls, this leaves significant behavioral aspects undocumented.

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

Conciseness4/5

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

The description is extremely concise at just 5 words, which is appropriate for a simple data retrieval tool. It's front-loaded with the core purpose. However, given the lack of differentiation from siblings and missing behavioral context, this brevity might be under-specification rather than optimal conciseness.

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

Completeness2/5

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

Given the tool's apparent complexity (retrieving current air quality data likely involves external API calls), no annotations, no output schema, and multiple similar sibling tools, the description is incomplete. It doesn't explain what 'current' means, what data is returned, how it differs from 'get-air-pollution', or any operational constraints.

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

Parameters3/5

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

The description mentions no parameters at all, while the schema has 100% coverage with a well-documented 'location' parameter. Since schema_description_coverage is high (100%), the baseline score is 3. The description adds no parameter information beyond what the schema already provides.

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

Purpose3/5

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

The description 'Get current air quality data' clearly states the verb ('Get') and resource ('current air quality data'), making the basic purpose understandable. However, it doesn't distinguish this tool from its sibling 'get-air-pollution' - both appear to retrieve air pollution data, so the distinction isn't clear from the description alone.

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

Usage Guidelines2/5

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

The description provides no guidance about when to use this tool versus alternatives. With multiple weather/pollution-related siblings including 'get-air-pollution', 'get-current-weather', and various forecast tools, there's no indication of what makes this tool unique or when it should be preferred over other options.

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

Related 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/robertn702/mcp-openweathermap'

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