UNPKG

current-time-timezone-server

Version:

MCP服务器,提供NTP校准的当前时间和时区相关功能,支持stdio和HTTP/SSE,可配置host和protocol,支持.env文件,返回指定时区的本地时间

73 lines 3.03 kB
import { z } from "zod"; import { getNtpTime, getLocalTimeInTimezone } from "./time.js"; export const registerTimeTool = (server) => { server.registerTool("get_current_time", { title: "Get Current Time", description: "Get NTP-synchronized current time, return local time for specified timezone", inputSchema: { timezone: z.string().optional().describe('Timezone, e.g. "Asia/Shanghai"') } }, async ({ timezone }) => { const ntpServer = process.env.NTP_SERVER || "pool.ntp.org"; try { const ntpTime = await getNtpTime(ntpServer); const targetTime = getLocalTimeInTimezone(ntpTime, timezone); const timestamp = Math.floor(ntpTime.getTime() / 1000); // 使用统一的UTC时间戳 const isoTime = ntpTime.toISOString(); // 使用统一的格式显示本地时间 const localTimeStr = targetTime.toLocaleString('en-US', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false }); return { content: [{ type: "text", text: JSON.stringify({ localTime: localTimeStr, isoTime: isoTime, timestamp: timestamp, timezone: timezone || 'Asia/Shanghai', ntpServer: ntpServer, status: "success" }, null, 2) }] }; } catch (error) { const now = new Date(); const targetTime = getLocalTimeInTimezone(now, timezone); const timestamp = Math.floor(now.getTime() / 1000); // 使用统一的UTC时间戳 const isoTime = now.toISOString(); // 使用统一的格式显示本地时间 const localTimeStr = targetTime.toLocaleString('en-US', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false }); return { content: [{ type: "text", text: JSON.stringify({ localTime: localTimeStr, isoTime: isoTime, timestamp: timestamp, timezone: timezone || 'Asia/Shanghai', ntpServer: ntpServer, status: "warning", message: "NTP failed, using local time" }, null, 2) }] }; } }); }; //# sourceMappingURL=toolRegistration.js.map