fetchWeather.ts•1.28 kB
import { z } from "zod";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
export function registerFetchWeather(server: McpServer) {
server.tool(
"fetch-weather",
"Fetch weather data for a given longitude and latitude",
{
lat: z.string().describe("Latitude"),
lon: z.string().describe("Longitude"),
},
async ({ lat, lon }) => {
const ctrl = new AbortController();
const id = setTimeout(() => ctrl.abort(), 8000);
try {
const weatherResponse = await fetch(
`https://api.open-meteo.com/v1/forecast?latitude=${lat}&longitude=${lon}&hourly=temperature_2m¤t=temperature_2m,precipitation,is_day,relative_humidity_2m,rain,wind_speed_10m`,
{ signal: ctrl.signal }
);
const weatherData = await weatherResponse.json();
return {
content: [
{
type: "text",
text: JSON.stringify(weatherData, null, 2),
},
],
};
} catch (err: any) {
return {
content: [
{
type: "text",
text: JSON.stringify({ error: err.message }),
},
],
};
} finally {
clearTimeout(id);
}
}
);
}