distance.ts•1.68 kB
import { z } from "zod";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
export function registerDistance(server: McpServer) {
server.tool(
"distance",
"Calculate driving distance and duration between two coordinates using OSRM (no API key required)",
{
fromLat: z.string().describe("Starting point latitude"),
fromLon: z.string().describe("Starting point longitude"),
toLat: z.string().describe("Destination latitude"),
toLon: z.string().describe("Destination longitude"),
},
async ({ fromLat, fromLon, toLat, toLon }) => {
const url = `http://router.project-osrm.org/route/v1/driving/${fromLon},${fromLat};${toLon},${toLat}?overview=false`;
const ctrl = new AbortController();
const id = setTimeout(() => ctrl.abort(), 8000);
try {
const res = await fetch(url, { signal: ctrl.signal });
const data = await res.json();
let result: any = {
distance_km: null,
duration_min: null,
};
if (data && data.routes && data.routes[0]) {
result.distance_km = (data.routes[0].distance / 1000).toFixed(2);
result.duration_min = (data.routes[0].duration / 60).toFixed(1);
}
return {
content: [
{
type: "text",
text: JSON.stringify(result, null, 2),
},
],
};
} catch (err: any) {
return {
content: [
{
type: "text",
text: JSON.stringify({ error: err.message }),
},
],
};
} finally {
clearTimeout(id);
}
}
);
}