UNPKG

@maol-1997/weatherapi-mcp

Version:

WeatherAPI MCP server - MCP tool for weather data

70 lines (69 loc) 2.35 kB
#!/usr/bin/env node import { McpServer, ResourceTemplate } from "@modelcontextprotocol/sdk/server/mcp.js"; import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"; import { z } from "zod"; import axios from 'axios'; import dotenv from 'dotenv'; dotenv.config(); const args = process.argv.slice(2); let apiKeyFromArgs; for (const arg of args) { if (!arg.startsWith('@') && !arg.startsWith('-')) { apiKeyFromArgs = arg; break; } } const API_KEY = apiKeyFromArgs || process.env.WEATHER_API_KEY; if (!API_KEY) { throw new Error('WEATHER_API_KEY environment variable not defined or API key parameter not provided!'); } const BASE_URL = 'http://api.weatherapi.com/v1'; const server = new McpServer({ name: "WeatherAPI", version: "1.1.0" }); const getWeather = async (args) => { try { const response = await axios.get(`${BASE_URL}/current.json`, { params: { key: API_KEY, q: args.location } }); const data = response.data; return { content: [{ type: "text", text: JSON.stringify({ location: data.location.name, country: data.location.country, temp_c: data.current.temp_c, condition: data.current.condition.text, humidity: data.current.humidity, wind_kph: data.current.wind_kph }, null, 2) }] }; } catch (error) { if (axios.isAxiosError(error)) { throw new Error(`Failed to fetch weather data: ${error.response?.data?.error?.message || error.message}`); } throw error; } }; server.tool("get_weather", { location: z.string().describe("City name") }, async (args) => getWeather(args)); server.resource("weather", new ResourceTemplate("weather://{city}/current", { list: undefined }), async (uri, variables) => { const city = variables.city; const result = await getWeather({ location: city }); return { contents: [{ uri: uri.href, text: result.content[0].text }] }; }); const transport = new StdioServerTransport(); await server.connect(transport);