import { InferSchema, ToolMetadata } from "xmcp";
import { z } from "zod";
const baseUrl = "https://backend.codingthailand.com";
export const schema = {
barcode: z
.string()
.regex(/^\d{13}$/, "รหัส barcode ต้องเป็นตัวเลข 13 หลัก")
.describe("รหัส barcode ของสินค้า (13 หลัก) "),
};
export const metadata: ToolMetadata = {
name: "get_product_by_barcode",
description: "ค้นหาสินค้าด้วยรหัสบาร์โค้ด",
annotations: {
title: "Get Product By Barcode",
readOnlyHint: true,
destructiveHint: false,
idempotentHint: true,
openWorldHint: true,
},
};
interface ProductResponse {
name: string;
price: number;
stock: number;
[key: string]: any; // รองรับ field อื่นๆ ที่อาจส่งมาเพิ่ม
}
export default async function getProductByBarcode({ barcode }: InferSchema<typeof schema>) {
try {
const res = await fetch(`${baseUrl}/v2/products/barcode/${barcode}`);
if (res.status === 404) {
return {
type: "text",
text: `ไม่พบสินค้าบาร์โค้ด ${barcode} นี้ในระบบ`,
};
}
if (!res.ok) {
return {
type: "text",
text: `เกิดข้อผิดพลาดจาก API: ${res.statusText}`,
};
}
const product = (await res.json()) as ProductResponse;
return {
structuredContent: product,
type: "text",
text: `พบสินค้า: ${product.name}\n ราคา: ${product.price} stock: ${product.stock}`,
};
} catch (error) {
return {
type: "text",
text: `เกิดข้อผิดพลาด: ${error instanceof Error ? error.message : 'Unknown error'}`,
};
}
}