import express from 'express';
import bodyParser from 'body-parser';
import fetch from 'node-fetch';
const app = express();
app.use(bodyParser.json());
type JsonRpcReq = { jsonrpc: string; method: string; params: any; id?: any };
app.post('/json-rpc', async (req, res) => {
const body: JsonRpcReq = req.body;
const { method, params, id } = body;
if (method === 'getWeather') {
const city = params?.city;
if (!city || typeof city !== 'string' || city.length > 100) {
return res.json({ jsonrpc: '2.0', error: { code: -32602, message: 'Invalid params' }, id });
}
try {
const apiKey = process.env.OWM_KEY;
if (!apiKey) throw new Error('OWM_KEY not set');
const r = await fetch(`https://api.openweathermap.org/data/2.5/weather?q=${encodeURIComponent(city)}&appid=${apiKey}&units=metric`);
if (!r.ok) throw new Error('External API error');
const data = await r.json();
const result = {
city: data.name,
temp_c: data.main?.temp,
description: data.weather?.[0]?.description
};
return res.json({ jsonrpc: '2.0', result, id });
} catch (err: any) {
return res.json({ jsonrpc: '2.0', error: { code: -32000, message: String(err.message) }, id });
}
} else {
res.json({ jsonrpc: '2.0', error: { code: -32601, message: 'Method not found' }, id });
}
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log(`MCP Weather server listening on ${PORT}`));