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