fetchCoordinates.ts•1.46 kB
import { z } from "zod";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
export function registerFetchCoordinates(server: McpServer) {
server.tool(
"fetch-coordinates",
"Fetch coordinates for a given city",
{
city: z.string().describe("City name"),
},
async ({ city }) => {
const ctrl = new AbortController();
const id = setTimeout(() => ctrl.abort(), 8000);
try {
const response = await fetch(
`https://geocoding-api.open-meteo.com/v1/search?name=${city}&count=10&language=en&format=json`,
{ signal: ctrl.signal }
);
const data = await response.json();
if (data.length === 0) {
return {
content: [
{
type: "text",
text: `No results found for ${city}.`,
},
],
};
}
const { latitude, longitude } = data.results[0];
const formatResult = { latitude, longitude };
return {
content: [
{
type: "text",
text: JSON.stringify(formatResult, null, 2),
},
],
};
} catch (err: any) {
return {
content: [
{
type: "text",
text: JSON.stringify({ error: err.message }),
},
],
};
} finally {
clearTimeout(id);
}
}
);
}