get-current-weather
Retrieve real-time weather data for a specific location using city name or coordinates. Specify temperature units (Celsius, Fahrenheit, or Kelvin) for accurate weather conditions.
Instructions
Get current weather conditions for a location
Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| location | Yes | City name (e.g., 'New York') or coordinates (e.g., 'lat,lon') | |
| units | No | Temperature units: metric (Celsius), imperial (Fahrenheit), or standard (Kelvin) |
Input Schema (JSON Schema)
{
"$schema": "http://json-schema.org/draft-07/schema#",
"additionalProperties": false,
"properties": {
"location": {
"description": "City name (e.g., 'New York') or coordinates (e.g., 'lat,lon')",
"type": "string"
},
"units": {
"description": "Temperature units: metric (Celsius), imperial (Fahrenheit), or standard (Kelvin)",
"enum": [
"metric",
"imperial",
"standard"
],
"type": "string"
}
},
"required": [
"location"
],
"type": "object"
}
Implementation Reference
- src/main.ts:60-124 (handler)The anonymous async execute function that implements the core logic of fetching current weather data from OpenWeatherMap API via getOpenWeatherClient, configuring location, retrieving data, formatting with formatCurrentWeather, and returning formatted text response while handling specific errors.execute: async (args, { session, log }) => { try { log.info("Getting current weather", { location: args.location }); // Get OpenWeather client const client = getOpenWeatherClient(session as SessionData | undefined); // Configure client for this request configureClientForLocation(client, args.location, args.units); // Fetch current weather const weatherData = await client.getCurrent(); log.info("Successfully retrieved current weather", { lat: weatherData.lat, lon: weatherData.lon, temp: weatherData.weather.temp.cur }); // Format the response const formattedWeather = formatCurrentWeather({ name: `${weatherData.lat.toFixed(4)}, ${weatherData.lon.toFixed(4)}`, // Use coordinates as name main: { temp: weatherData.weather.temp.cur, feels_like: weatherData.weather.feelsLike.cur, humidity: weatherData.weather.humidity }, weather: [{ description: weatherData.weather.description }], wind: { speed: weatherData.weather.wind.speed, deg: weatherData.weather.wind.deg || 0 }, visibility: weatherData.weather.visibility, dt: weatherData.dtRaw, timezone: weatherData.timezoneOffset }, args.units); return { content: [ { type: "text", text: formattedWeather } ] }; } catch (error) { log.error("Failed to get current weather", { 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 weather: ${error instanceof Error ? error.message : 'Unknown error'}`); } }
- src/schemas.ts:16-19 (schema)Zod validation schema defining the input parameters for the tool: required 'location' string and optional 'units' enum (metric, imperial, standard).export const getCurrentWeatherSchema = z.object({ location: z.string().describe("City name (e.g., 'New York') or coordinates (e.g., 'lat,lon')"), units: unitsSchema, });
- src/main.ts:56-125 (registration)FastMCP server.addTool registration of the 'get-current-weather' tool, specifying name, description, input schema, and inline execute handler function.server.addTool({ name: "get-current-weather", description: "Get current weather conditions for a location", parameters: getCurrentWeatherSchema, execute: async (args, { session, log }) => { try { log.info("Getting current weather", { location: args.location }); // Get OpenWeather client const client = getOpenWeatherClient(session as SessionData | undefined); // Configure client for this request configureClientForLocation(client, args.location, args.units); // Fetch current weather const weatherData = await client.getCurrent(); log.info("Successfully retrieved current weather", { lat: weatherData.lat, lon: weatherData.lon, temp: weatherData.weather.temp.cur }); // Format the response const formattedWeather = formatCurrentWeather({ name: `${weatherData.lat.toFixed(4)}, ${weatherData.lon.toFixed(4)}`, // Use coordinates as name main: { temp: weatherData.weather.temp.cur, feels_like: weatherData.weather.feelsLike.cur, humidity: weatherData.weather.humidity }, weather: [{ description: weatherData.weather.description }], wind: { speed: weatherData.weather.wind.speed, deg: weatherData.weather.wind.deg || 0 }, visibility: weatherData.weather.visibility, dt: weatherData.dtRaw, timezone: weatherData.timezoneOffset }, args.units); return { content: [ { type: "text", text: formattedWeather } ] }; } catch (error) { log.error("Failed to get current weather", { 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 weather: ${error instanceof Error ? error.message : 'Unknown error'}`); } } });
- formatCurrentWeather helper function that transforms raw OpenWeatherMap current weather data into a structured JSON string suitable for LLM consumption.export function formatCurrentWeather(data: any, units: Units = "metric"): string { const weatherData = { location: data.name || 'Unknown', temperature: { current: Math.round(data.main.temp), feels_like: Math.round(data.main.feels_like), units: getTemperatureUnit(units) }, conditions: data.weather[0].description, humidity: data.main.humidity, wind: { speed: Number(data.wind.speed.toFixed(1)), direction: getWindDirection(data.wind.deg), units: units === "imperial" ? "mph" : "m/s" }, visibility: { value: units === "imperial" ? Number((data.visibility / 1609.34).toFixed(1)) : Number((data.visibility / 1000).toFixed(1)), units: units === "imperial" ? "mi" : "km" }, timestamp: data.dt }; return JSON.stringify(weatherData); }
- src/utils/client-resolver.ts:15-41 (helper)getOpenWeatherClient helper that retrieves or creates a cached OpenWeatherAPI client instance from 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; }