getWeather
Retrieve real-time weather data for any city by specifying its name. Integrates with Claude Code to deliver accurate current weather information for seamless application use.
Instructions
Get current weather for a city
Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| city | Yes | Name of the city |
Input Schema (JSON Schema)
{
"$schema": "http://json-schema.org/draft-07/schema#",
"additionalProperties": false,
"properties": {
"city": {
"description": "Name of the city",
"type": "string"
}
},
"required": [
"city"
],
"type": "object"
}
Implementation Reference
- index.js:12-41 (handler)The handler function in WeatherService class that fetches current weather data for a given city using the OpenWeatherMap API via axios, formats the response as MCP content, and handles errors.async getWeather(city) { if (!this.apiKey) { throw new Error('OPENWEATHER_API_KEY environment variable is not set'); } try { const response = await axios.get( `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${this.apiKey}&units=metric` ); const data = response.data; return { content: [{ type: 'text', text: JSON.stringify({ city: data.name, temperature: data.main.temp, description: data.weather[0].description, }, null, 2), }], }; } catch (error) { return { content: [{ type: 'text', text: `Error: ${error.message}`, }], isError: true, }; } }
- index.js:52-57 (registration)Registers the 'getWeather' tool with the MCP server, specifying its description, input schema using Zod, and an inline handler that delegates to the WeatherService.getWeather method.server.registerTool('getWeather', { description: 'Get current weather for a city', inputSchema: { city: z.string().describe('Name of the city'), }, }, async ({ city }) => await weatherService.getWeather(city));
- index.js:55-56 (schema)Input schema for the 'getWeather' tool defining the 'city' parameter as a string.city: z.string().describe('Name of the city'), },
- index.js:7-42 (helper)The WeatherService class providing the getWeather method and managing the OpenWeatherMap API key.class WeatherService { constructor(apiKey = process.env.OPENWEATHER_API_KEY) { this.apiKey = apiKey; } async getWeather(city) { if (!this.apiKey) { throw new Error('OPENWEATHER_API_KEY environment variable is not set'); } try { const response = await axios.get( `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${this.apiKey}&units=metric` ); const data = response.data; return { content: [{ type: 'text', text: JSON.stringify({ city: data.name, temperature: data.main.temp, description: data.weather[0].description, }, null, 2), }], }; } catch (error) { return { content: [{ type: 'text', text: `Error: ${error.message}`, }], isError: true, }; } } }