randomTrivia.ts•1.32 kB
import { z } from "zod";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
export function registerRandomTrivia(server: McpServer) {
server.tool(
"random-trivia",
"Get a random trivia question from Open Trivia DB",
z.object({}),
async () => {
const ctrl = new AbortController();
const id = setTimeout(() => ctrl.abort(), 8000);
try {
const res = await fetch("https://opentdb.com/api.php?amount=1&type=multiple", {
signal: ctrl.signal,
});
const data = await res.json();
const q = data.results?.[0];
const result = q
? {
category: q.category,
difficulty: q.difficulty,
question: q.question,
correct_answer: q.correct_answer,
incorrect_answers: q.incorrect_answers,
}
: {};
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);
}
}
);
}