import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js"; import { z } from "zod"; import http from "node:http"; function createServer() { const server = new McpServer({ name: "devcon-workshop-server", version: "1.0.0", }); server.registerTool( "get_weather", { "description": "Get the current weather for a given city.", "inputSchema": { "city": z.string().describe("The name of the city to get the weather for."), } }, async ({ city }) => { // Step 1: resolve city name to coordinates using Open-Meteo's free geocoding API const geoUrl = `https://geocoding-api.open-meteo.com/v1/search?name=${encodeURIComponent(city)}&count=1`; const geoRes = await fetch(geoUrl); const geoData = await geoRes.json(); if (!geoData.results?.length) { return { content: [{ type: "text", text: `City not found: ${city}` }] }; } const { latitude, longitude } = geoData.results[0]; // Step 2: fetch current weather for those coordinates const url = `https://api.open-meteo.com/v1/forecast` + `?latitude=${latitude}&longitude=${longitude}¤t_weather=true`; const response = await fetch(url); const data = await response.json(); const temp = data.current_weather.temperature; const wind = data.current_weather.windspeed; return { content: [ { type: "text", text: `Weather in ${city}: ${temp}°C, wind ${wind} km/h`, }, ], }; } ); return server; } const PORT = 3000; const httpServer = http.createServer(async (req, res) => { if (req.url !== "/mcp") { res.writeHead(404).end("Not found"); return; } const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined, }); res.on("close", () => transport.close()); const server = createServer(); await server.connect(transport); await transport.handleRequest(req, res); }); httpServer.listen(PORT, () => { console.log(`MCP server running at http://localhost:${PORT}/mcp`); });