TranslateTool.tsā¢2.09 kB
import { MCPTool } from "mcp-framework";
import { z } from "zod";
interface TestInput {
text: string;
source?: string;
target?: string;
}
class TranslateTool extends MCPTool<TestInput> {
name = "translate";
description = "Translates a given text using LibreTranslate API";
schema = {
text: {
type: z.string().min(1),
description: "Text to translate",
},
source: {
type: z.string().default("auto"),
description: "Source language code (e.g. 'ko', 'en')",
},
target: {
type: z.string().default("en"),
description: "Target language code (e.g. 'en', 'ko')",
},
};
async execute(input: TestInput) {
console.log("š” input:", input);
try {
// ķģģģ ģ¤ģ (10ģ“)
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 10000);
const response = await fetch("https://libretranslate.de/translate", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
q: input.text,
source: input.source || "auto",
target: input.target || "en",
format: "text",
}),
signal: controller.signal,
});
clearTimeout(timeoutId);
if (!response.ok) {
throw new Error(`Translation API failed with status ${response.status}: ${response.statusText}`);
}
const data = await response.json();
if (!data.translatedText) {
throw new Error("Translation API returned invalid response format");
}
return data.translatedText;
} catch (error) {
console.error("Translation error:", error);
if (error instanceof Error) {
if (error.name === 'AbortError') {
throw new Error("Translation request timed out. Please try again.");
}
throw new Error(`Translation failed: ${error.message}`);
}
throw new Error("Translation failed due to an unknown error");
}
}
}
export default TranslateTool;