cryptoPrice.ts•1.26 kB
import { z } from "zod";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
export function registerCryptoPrice(server: McpServer) {
server.tool(
"crypto-price",
"Get current cryptocurrency price from CoinGecko",
{
id: z.string().describe("Cryptocurrency id (e.g., bitcoin)"),
vs: z.string().describe("Fiat currency (e.g., usd)"),
},
async ({ id, vs }) => {
const url = `https://api.coingecko.com/api/v3/simple/price?ids=${encodeURIComponent(id)}&vs_currencies=${encodeURIComponent(vs)}`;
const ctrl = new AbortController();
const idTimeout = setTimeout(() => ctrl.abort(), 8000);
try {
const res = await fetch(url, { signal: ctrl.signal });
const data = await res.json();
const price = data[id]?.[vs] ?? null;
return {
content: [
{
type: "text",
text: JSON.stringify({ price }, null, 2),
},
],
};
} catch (err: any) {
return {
content: [
{
type: "text",
text: JSON.stringify({ error: err.message }),
},
],
};
} finally {
clearTimeout(idTimeout);
}
}
);
}