import { MCPTool } from "mcp-framework";
import { z } from "zod";
interface XkcdComic {
num: number;
img: string;
alt: string;
title: string;
}
class XkcdTool extends MCPTool {
name = "xkcd";
description = "Fetches a random xkcd comic image and its alt text.";
schema = {
message: {
type: z.string(),
description: "Message to process",
},
};
async execute() {
try {
// Get the latest comic number
const latestComicResponse = await fetch("https://xkcd.com/info.0.json");
if (!latestComicResponse.ok) {
throw new Error(
`Failed to fetch latest comic data: ${latestComicResponse.statusText}`
);
}
const latestComicData = (await latestComicResponse.json()) as XkcdComic;
const latestComicNumber = latestComicData.num;
// Generate a random comic number
const randomComicNumber = Math.floor(Math.random() * latestComicNumber) + 1;
// Fetch the random comic
const randomComicResponse = await fetch(
`https://xkcd.com/${randomComicNumber}/info.0.json`
);
if (!randomComicResponse.ok) {
throw new Error(
`Failed to fetch comic data for ${randomComicNumber}: ${randomComicResponse.statusText}`
);
}
const randomComicData = (await randomComicResponse.json()) as XkcdComic;
return `
Title: ${randomComicData.title}
Image URL: ${randomComicData.img}
Alt Text: ${randomComicData.alt}
`;
} catch (error) {
console.error("Error fetching xkcd comic:", error);
return "Error: Could not fetch xkcd comic.";
}
}
}
export default XkcdTool;