exchangeRate.ts•1.44 kB
import { z } from "zod";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
export function registerExchangeRate(server: McpServer) {
server.tool(
"exchange-rate",
"Convert amounts between currencies using ExchangeRate.host",
{
from: z.string().describe("Base currency code"),
to: z.string().describe("Target currency code"),
amount: z.string().optional().describe("Amount to convert (default 1)"),
},
async ({ from, to, amount }) => {
const amt = Number(amount ?? "1");
const url = `https://api.exchangerate.host/convert?from=${encodeURIComponent(from)}&to=${encodeURIComponent(to)}&amount=${amt}`;
const ctrl = new AbortController();
const id = setTimeout(() => ctrl.abort(), 8000);
try {
const res = await fetch(url, { signal: ctrl.signal });
const data = await res.json();
const result = {
rate: data.info?.rate ?? null,
result: data.result ?? null,
};
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);
}
}
);
}