import { tool } from "@opencode-ai/plugin"; import { DateTime, Duration, Interval } from "luxon"; const DEFAULT_TIMEZONE = "Europe/Berlin"; /** * Format a DateTime for human-readable output */ function formatHuman(dt: DateTime): string { return dt.toLocaleString(DateTime.DATETIME_FULL); } /** * Get timezone abbreviation or offset string */ function getTimezoneDisplay(dt: DateTime): string { return dt.offsetNameShort || `UTC${dt.toFormat("ZZ")}`; } /** * Create a JSON response string */ function jsonResponse(data: Record): string { return JSON.stringify(data, null, 2); } /** * Parse input into a DateTime object * Accepts: ISO string, Unix milliseconds, or "now" */ function parseInput( input: string, timezone: string, ): DateTime | null { const trimmed = input.trim().toLowerCase(); // Handle "now" if (trimmed === "now") { return DateTime.now().setZone(timezone); } // Try ISO string first (most common format) const dt = DateTime.fromISO(input, { zone: timezone }); if (dt.isValid) return dt; // Try Unix timestamp (milliseconds) - only for pure numeric strings if (/^\d+$/.test(trimmed)) { const unixMs = parseInt(input, 10); if (!isNaN(unixMs) && unixMs > 0) { const dtUnix = DateTime.fromMillis(unixMs, { zone: timezone }); if (dtUnix.isValid) return dtUnix; } } // Try RFC 2822 const dt2822 = DateTime.fromRFC2822(input, { zone: timezone }); if (dt2822.isValid) return dt2822; // Try HTTP format const dtHttp = DateTime.fromHTTP(input, { zone: timezone }); if (dtHttp.isValid) return dtHttp; // Try SQL format const dtSql = DateTime.fromSQL(input, { zone: timezone }); if (dtSql.isValid) return dtSql; return null; } /** * Validate timezone and return error message if invalid */ function validateTimezone(timezone: string): string | null { const zone = DateTime.now().setZone(timezone); if (!zone.isValid) { return `Invalid timezone: "${timezone}". Examples: "America/New_York", "Europe/London", "Asia/Tokyo", "UTC"`; } return null; } /** * Build the result object for a DateTime */ function buildDateTimeResult(dt: DateTime): Record { return { iso: dt.toISO(), unix_ms: dt.toMillis(), human: formatHuman(dt), timezone: dt.zoneName, offset: dt.toFormat("ZZ"), offset_name: getTimezoneDisplay(dt), date: dt.toFormat("yyyy-MM-dd"), time: dt.toFormat("HH:mm:ss"), day_of_week: dt.weekdayLong, day_of_year: dt.ordinal, week_number: dt.weekNumber, is_dst: dt.isInDST, }; } // ============================================================================ // NOW - Get current time // ============================================================================ export const now = tool({ description: `Get the current date and time in a specified timezone. Use this tool when you need to know the current time, date, or timezone information. Returns comprehensive information including ISO format, Unix timestamp (milliseconds), human-readable format, timezone offset, DST status, and more. Examples: - Get current time in Berlin: now({ timezone: "Europe/Berlin" }) - Get current UTC time: now({ timezone: "UTC" }) - Get formatted time: now({ timezone: "America/New_York", format: "yyyy-MM-dd HH:mm" })`, args: { timezone: tool.schema .string() .default(DEFAULT_TIMEZONE) .describe( 'IANA timezone identifier (e.g., "America/New_York", "Europe/London", "Asia/Tokyo", "UTC"). Defaults to "Europe/Berlin"', ), format: tool.schema .string() .optional() .describe( 'Custom Luxon format string (e.g., "yyyy-MM-dd HH:mm", "EEEE, MMMM d"). If provided, adds a "formatted" field to the response.', ), }, async execute(args) { const timezone = args.timezone || DEFAULT_TIMEZONE; const tzError = validateTimezone(timezone); if (tzError) return tzError; const dt = DateTime.now().setZone(timezone); const result = buildDateTimeResult(dt); if (args.format) { result.formatted = dt.toFormat(args.format); } return jsonResponse(result); }, }); // ============================================================================ // CONVERT - Convert between timezones // ============================================================================ export const convert = tool({ description: `Convert a date/time from one timezone to another. Use this tool to convert timestamps between different timezones while preserving the same instant in time. Useful for scheduling across timezones, coordinating with remote teams, or understanding what time something is in another location. Examples: - Convert now from Berlin to Tokyo: convert({ time: "now", from_timezone: "Europe/Berlin", to_timezone: "Asia/Tokyo" }) - Convert specific time: convert({ time: "2024-03-15T14:30:00", from_timezone: "America/New_York", to_timezone: "Europe/London" })`, args: { time: tool.schema .string() .describe( 'The time to convert. Can be an ISO string ("2024-03-15T14:30:00"), Unix timestamp in milliseconds, or "now" for current time.', ), from_timezone: tool.schema .string() .default(DEFAULT_TIMEZONE) .describe( 'Source timezone. Defaults to "Europe/Berlin" if not specified.', ), to_timezone: tool.schema .string() .describe( 'Target timezone to convert to (e.g., "America/Los_Angeles", "Asia/Tokyo").', ), }, async execute(args) { const fromTz = args.from_timezone || DEFAULT_TIMEZONE; const toTz = args.to_timezone; const fromTzError = validateTimezone(fromTz); if (fromTzError) return fromTzError; const toTzError = validateTimezone(toTz); if (toTzError) return toTzError; const dt = parseInput(args.time, fromTz); if (!dt) { return `Invalid time format: "${args.time}". Use ISO format, Unix milliseconds, or "now".`; } const converted = dt.setZone(toTz); if (!converted.isValid) { return `Conversion failed: ${converted.invalidReason}`; } return jsonResponse({ original: { iso: dt.toISO(), human: formatHuman(dt), timezone: dt.zoneName, }, converted: { iso: converted.toISO(), human: formatHuman(converted), timezone: converted.zoneName, }, time_difference: `Same instant, different representation`, }); }, }); // ============================================================================ // PARSE - Parse date/time strings // ============================================================================ export const parse = tool({ description: `Parse a date/time string into a structured format. Use this tool to interpret various date/time formats and get a standardized representation. Handles ISO 8601, RFC 2822, HTTP dates, SQL format, and Unix timestamps. Returns comprehensive parsed information including validity checks. Examples: - Parse ISO date: parse({ input: "2024-03-15T14:30:00Z" }) - Parse Unix timestamp: parse({ input: "1710511800000" }) - Parse with timezone: parse({ input: "2024-03-15 14:30", timezone: "America/Chicago" })`, args: { input: tool.schema .string() .describe( "The date/time string to parse. Supports ISO 8601, RFC 2822, HTTP, SQL formats, and Unix milliseconds.", ), timezone: tool.schema .string() .default(DEFAULT_TIMEZONE) .describe( 'Timezone to interpret the date in if not specified in the input. Defaults to "Europe/Berlin".', ), }, async execute(args) { const timezone = args.timezone || DEFAULT_TIMEZONE; const tzError = validateTimezone(timezone); if (tzError) return tzError; const dt = parseInput(args.input, timezone); if (!dt) { return jsonResponse({ valid: false, input: args.input, error: "Could not parse input. Supported formats: ISO 8601, RFC 2822, HTTP dates, SQL format, Unix milliseconds.", examples: [ "2024-03-15T14:30:00Z", "2024-03-15T14:30:00-05:00", "Fri, 15 Mar 2024 14:30:00 GMT", "2024-03-15 14:30:00", "1710511800000", ], }); } const result = buildDateTimeResult(dt); return jsonResponse({ valid: true, input: args.input, parsed: result, }); }, }); // ============================================================================ // FORMAT - Format timestamps // ============================================================================ export const format = tool({ description: `Format a timestamp into various output formats. Use this tool to convert timestamps into human-readable or machine-readable formats. Supports ISO 8601, locale-specific formats, and custom Luxon format strings. Common format tokens: - yyyy: 4-digit year - MM: 2-digit month - dd: 2-digit day - HH: 24-hour format - mm: minutes - ss: seconds - EEEE: full weekday name - MMMM: full month name Examples: - Format as ISO: format({ time: "now", format_type: "iso" }) - Custom format: format({ time: "2024-03-15T14:30:00", custom_format: "EEEE, MMMM d, yyyy 'at' h:mm a" }) - Locale format: format({ time: "now", format_type: "locale", locale: "de-DE" })`, args: { time: tool.schema .string() .describe( 'The timestamp to format. ISO string, Unix milliseconds, or "now".', ), timezone: tool.schema .string() .default(DEFAULT_TIMEZONE) .describe('Timezone for formatting. Defaults to "Europe/Berlin".'), format_type: tool.schema .enum([ "iso", "locale", "locale_short", "locale_medium", "locale_full", "custom", ]) .default("iso") .describe( 'Preset format type: "iso" (ISO 8601), "locale" (local format), "locale_short", "locale_medium", "locale_full", or "custom".', ), custom_format: tool.schema .string() .optional() .describe( 'Custom Luxon format string (required if format_type is "custom"). E.g., "yyyy-MM-dd HH:mm:ss"', ), locale: tool.schema .string() .optional() .describe( 'Locale for formatting (e.g., "en-US", "de-DE", "fr-FR"). Affects locale-based formats.', ), }, async execute(args) { const timezone = args.timezone || DEFAULT_TIMEZONE; const tzError = validateTimezone(timezone); if (tzError) return tzError; const dt = parseInput(args.time, timezone); if (!dt) { return `Invalid time: "${args.time}". Use ISO format, Unix milliseconds, or "now".`; } const locale = args.locale || "en-US"; const dtWithLocale = dt.setLocale(locale); const formatType = args.format_type || "iso"; let formatted: string; let formatUsed: string; switch (formatType) { case "iso": formatted = dt.toISO()!; formatUsed = "ISO 8601"; break; case "locale": case "locale_medium": formatted = dtWithLocale.toLocaleString(DateTime.DATETIME_MED); formatUsed = "Locale medium"; break; case "locale_short": formatted = dtWithLocale.toLocaleString(DateTime.DATETIME_SHORT); formatUsed = "Locale short"; break; case "locale_full": formatted = dtWithLocale.toLocaleString(DateTime.DATETIME_FULL); formatUsed = "Locale full"; break; case "custom": if (!args.custom_format) { return 'Custom format requires "custom_format" argument. Example: "yyyy-MM-dd HH:mm:ss"'; } formatted = dtWithLocale.toFormat(args.custom_format); formatUsed = `Custom: ${args.custom_format}`; break; } return jsonResponse({ input: args.time, formatted, format_used: formatUsed, locale, timezone: dt.zoneName, iso: dt.toISO(), unix_ms: dt.toMillis(), }); }, }); // ============================================================================ // RELATIVE - Relative time strings // ============================================================================ export const relative = tool({ description: `Get a human-readable relative time string. Use this tool to express timestamps as relative phrases like "2 hours ago", "in 3 days", "just now", etc. Useful for displaying user-friendly time differences. Examples: - Time since an event: relative({ time: "2024-03-01T12:00:00" }) - Time until a future event: relative({ time: "2024-12-25T00:00:00" }) - Relative to specific reference: relative({ time: "2024-03-15T12:00:00", reference: "2024-03-14T12:00:00" })`, args: { time: tool.schema .string() .describe( 'The target time. ISO string, Unix milliseconds, or "now".', ), reference: tool.schema .string() .optional() .describe( "The reference point for relative calculation. Defaults to current time. Use this to calculate relative time between two specific moments.", ), timezone: tool.schema .string() .default(DEFAULT_TIMEZONE) .describe('Timezone for calculations. Defaults to "Europe/Berlin".'), locale: tool.schema .string() .optional() .describe('Locale for relative time strings (e.g., "en", "de", "fr").'), style: tool.schema .enum(["long", "short", "narrow"]) .default("long") .describe( 'Style of relative time: "long" ("2 hours ago"), "short" ("2 hr. ago"), "narrow" ("2h ago")', ), unit: tool.schema .enum([ "auto", "years", "months", "weeks", "days", "hours", "minutes", "seconds", ]) .default("auto") .describe( 'Unit to use for display. "auto" picks the most appropriate unit automatically.', ), }, async execute(args) { const timezone = args.timezone || DEFAULT_TIMEZONE; const tzError = validateTimezone(timezone); if (tzError) return tzError; const target = parseInput(args.time, timezone); if (!target) { return `Invalid target time: "${args.time}"`; } const reference = args.reference ? parseInput(args.reference, timezone) : DateTime.now().setZone(timezone); if (args.reference && !reference) { return `Invalid reference time: "${args.reference}"`; } const locale = args.locale || "en"; const targetWithLocale = target.setLocale(locale); const referenceWithLocale = reference!.setLocale(locale); const diff = targetWithLocale.diff(referenceWithLocale); const isPast = diff.milliseconds < 0; const absDiff = Duration.fromMillis(Math.abs(diff.milliseconds)); let relativeStr: string; let unitUsed: string; if (args.unit === "auto") { relativeStr = targetWithLocale.toRelative({ base: referenceWithLocale, style: args.style, }) || "unknown"; unitUsed = "auto"; } else { const unit = args.unit; relativeStr = targetWithLocale.toRelative({ base: referenceWithLocale, unit, style: args.style, }) || "unknown"; unitUsed = unit; } // Calculate detailed breakdown const breakdown = { years: Math.floor(absDiff.as("years")), months: Math.floor(absDiff.as("months") % 12), weeks: Math.floor(absDiff.as("weeks")), days: Math.floor(absDiff.as("days")), hours: Math.floor(absDiff.as("hours")), minutes: Math.floor(absDiff.as("minutes")), seconds: Math.floor(absDiff.as("seconds")), total_milliseconds: Math.abs(diff.milliseconds), }; return jsonResponse({ target: { iso: target.toISO(), human: formatHuman(target), }, reference: { iso: reference!.toISO(), human: formatHuman(reference!), }, relative: relativeStr, is_past: isPast, direction: isPast ? "past" : "future", style: args.style, unit_used: unitUsed, breakdown, }); }, }); // ============================================================================ // DURATION - Calculate duration between timestamps // ============================================================================ export const duration = tool({ description: `Calculate the exact duration between two timestamps. Use this tool to measure the time difference between two moments with precise breakdown in various units (years, months, days, hours, minutes, seconds, milliseconds). Examples: - Duration between dates: duration({ start: "2024-03-01T12:00:00", end: "2024-03-15T18:30:00" }) - Duration from now: duration({ start: "now", end: "2024-12-31T23:59:59" }) - In specific unit: duration({ start: "2024-01-01", end: "2024-02-01", unit: "days" })`, args: { start: tool.schema .string() .describe( 'Start time. ISO string, Unix milliseconds, or "now".', ), end: tool.schema .string() .describe( 'End time. ISO string, Unix milliseconds, or "now".', ), timezone: tool.schema .string() .default(DEFAULT_TIMEZONE) .describe('Timezone for calculations. Defaults to "Europe/Berlin".'), unit: tool.schema .enum([ "milliseconds", "seconds", "minutes", "hours", "days", "weeks", "months", "years", "all", ]) .default("all") .describe( 'Unit for the result. "all" returns breakdown in all units.', ), }, async execute(args) { const timezone = args.timezone || DEFAULT_TIMEZONE; const tzError = validateTimezone(timezone); if (tzError) return tzError; const start = parseInput(args.start, timezone); if (!start) { return `Invalid start time: "${args.start}"`; } const end = parseInput(args.end, timezone); if (!end) { return `Invalid end time: "${args.end}"`; } const interval = Interval.fromDateTimes(start, end); if (!interval.isValid) { return `Invalid interval: ${interval.invalidReason}`; } // Use diff with specific units to get calendar-aware duration // Luxon needs this to properly handle months/years (variable length units) const diff = end.diff(start, [ "years", "months", "days", "hours", "minutes", "seconds", "milliseconds", ]); const breakdown = { years: Math.floor(diff.years || 0), months: Math.floor(diff.months || 0), weeks: Math.floor(diff.as("weeks")), days: Math.floor(diff.days || 0), hours: Math.floor(diff.hours || 0), minutes: Math.floor(diff.minutes || 0), seconds: Math.floor(diff.seconds || 0), milliseconds: Math.floor(diff.milliseconds || 0), total_milliseconds: interval.length("milliseconds"), }; // Human readable breakdown const parts: string[] = []; if (breakdown.years > 0) { parts.push( `${breakdown.years} year${breakdown.years !== 1 ? "s" : ""}`, ); } if (breakdown.months > 0) { parts.push( `${breakdown.months} month${breakdown.months !== 1 ? "s" : ""}`, ); } if (breakdown.days > 0) { parts.push( `${breakdown.days} day${breakdown.days !== 1 ? "s" : ""}`, ); } if (breakdown.hours > 0) { parts.push( `${breakdown.hours} hour${breakdown.hours !== 1 ? "s" : ""}`, ); } if (breakdown.minutes > 0) { parts.push( `${breakdown.minutes} minute${breakdown.minutes !== 1 ? "s" : ""}`, ); } if (breakdown.seconds > 0 && parts.length === 0) { parts.push( `${breakdown.seconds} second${breakdown.seconds !== 1 ? "s" : ""}`, ); } if (parts.length === 0) { parts.push("0 seconds"); } const humanReadable = parts.join(", "); const unit = args.unit || "all"; let result: Record = { start: { iso: start.toISO(), human: formatHuman(start), }, end: { iso: end.toISO(), human: formatHuman(end), }, human: humanReadable, total_milliseconds: breakdown.total_milliseconds, breakdown, }; // Add specific unit if requested if (unit !== "all") { result[`value_in_${unit}`] = diff.as(unit); } return jsonResponse(result); }, }); // ============================================================================ // ADD - Add/subtract time from a date // ============================================================================ export const add = tool({ description: `Add or subtract time from a date to get a new timestamp. Use this tool for date arithmetic - calculating future or past dates by adding or subtracting time units. Useful for calculating deadlines, expiration dates, or scheduling. Examples: - Add 7 days: add({ time: "now", years: 0, months: 0, days: 7 }) - Subtract 2 hours: add({ time: "2024-03-15T14:00:00", hours: -2 }) - Add 1 year 3 months: add({ time: "now", years: 1, months: 3 }) - Calculate deadline: add({ time: "2024-01-15", days: 30 })`, args: { time: tool.schema .string() .describe( 'Starting timestamp. ISO string, Unix milliseconds, or "now".', ), timezone: tool.schema .string() .default(DEFAULT_TIMEZONE) .describe('Timezone for the result. Defaults to "Europe/Berlin".'), years: tool.schema .number() .default(0) .describe("Years to add (negative to subtract)."), quarters: tool.schema .number() .default(0) .describe("Quarters to add (negative to subtract)."), months: tool.schema .number() .default(0) .describe("Months to add (negative to subtract)."), weeks: tool.schema .number() .default(0) .describe("Weeks to add (negative to subtract)."), days: tool.schema .number() .default(0) .describe("Days to add (negative to subtract)."), hours: tool.schema .number() .default(0) .describe("Hours to add (negative to subtract)."), minutes: tool.schema .number() .default(0) .describe("Minutes to add (negative to subtract)."), seconds: tool.schema .number() .default(0) .describe("Seconds to add (negative to subtract)."), milliseconds: tool.schema .number() .default(0) .describe("Milliseconds to add (negative to subtract)."), }, async execute(args) { const timezone = args.timezone || DEFAULT_TIMEZONE; const tzError = validateTimezone(timezone); if (tzError) return tzError; const dt = parseInput(args.time, timezone); if (!dt) { return `Invalid time: "${args.time}"`; } const duration = Duration.fromObject({ years: args.years, quarters: args.quarters, months: args.months, weeks: args.weeks, days: args.days, hours: args.hours, minutes: args.minutes, seconds: args.seconds, milliseconds: args.milliseconds, }); const result = dt.plus(duration); if (!result.isValid) { return `Result is invalid: ${result.invalidReason}`; } // Build change description const units = [ ["years", "year"], ["quarters", "quarter"], ["months", "month"], ["weeks", "week"], ["days", "day"], ["hours", "hour"], ["minutes", "minute"], ["seconds", "second"], ["milliseconds", "millisecond"], ] as const; const changes = units .filter(([key]) => args[key]) .map(([key, label]) => `${args[key]} ${label}(s)`); const changeDesc = changes.length > 0 ? changes.join(", ") : "no change"; return jsonResponse({ original: buildDateTimeResult(dt), result: buildDateTimeResult(result), change_applied: changeDesc, difference_ms: result.toMillis() - dt.toMillis(), }); }, }); // ============================================================================ // COMPARE - Compare two timestamps // ============================================================================ export const compare = tool({ description: `Compare two timestamps to determine their chronological relationship. Use this tool to check if one time is before, after, or equal to another time. Also provides the duration difference and precise comparison results. Examples: - Check if deadline passed: compare({ time1: "now", time2: "2024-01-01T00:00:00" }) - Compare two dates: compare({ time1: "2024-03-15", time2: "2024-03-20" }) - Check meeting times: compare({ time1: "2024-03-15T09:00:00", time2: "2024-03-15T10:00:00" })`, args: { time1: tool.schema .string() .describe( 'First timestamp. ISO string, Unix milliseconds, or "now".', ), time2: tool.schema .string() .describe( 'Second timestamp. ISO string, Unix milliseconds, or "now".', ), timezone: tool.schema .string() .default(DEFAULT_TIMEZONE) .describe('Timezone for comparison. Defaults to "Europe/Berlin".'), }, async execute(args) { const timezone = args.timezone || DEFAULT_TIMEZONE; const tzError = validateTimezone(timezone); if (tzError) return tzError; const dt1 = parseInput(args.time1, timezone); if (!dt1) { return `Invalid time1: "${args.time1}"`; } const dt2 = parseInput(args.time2, timezone); if (!dt2) { return `Invalid time2: "${args.time2}"`; } const diffMs = dt2.toMillis() - dt1.toMillis(); const diff = Duration.fromMillis(Math.abs(diffMs)); let comparison: string; if (diffMs < 0) { comparison = "time1 is after time2"; } else if (diffMs > 0) { comparison = "time1 is before time2"; } else { comparison = "time1 equals time2"; } // Human-readable difference const humanDiff = dt2.toRelative({ base: dt1 }) || "unknown"; return jsonResponse({ time1: { iso: dt1.toISO(), human: formatHuman(dt1), unix_ms: dt1.toMillis(), }, time2: { iso: dt2.toISO(), human: formatHuman(dt2), unix_ms: dt2.toMillis(), }, comparison, is_before: diffMs > 0, is_after: diffMs < 0, is_equal: diffMs === 0, difference_ms: diffMs, difference_human: humanDiff, difference_breakdown: { days: Math.floor(diff.as("days")), hours: Math.floor(diff.as("hours") % 24), minutes: Math.floor(diff.as("minutes") % 60), seconds: Math.floor(diff.as("seconds") % 60), }, }); }, }); // ============================================================================ // UNIX - Unix timestamp conversion // ============================================================================ export const unix = tool({ description: `Convert between Unix timestamps (milliseconds) and formatted dates. Use this tool to convert Unix timestamps to human-readable dates or vice versa. Note: Uses MILLISECONDS (JavaScript convention), not seconds. Examples: - Current Unix timestamp: unix({ time: "now" }) - Convert Unix to date: unix({ time: "1710511800000" }) - Get Unix for specific date: unix({ time: "2024-03-15T14:30:00Z" }) - Convert to seconds: unix({ time: "now", output_unit: "seconds" })`, args: { time: tool.schema .string() .describe( 'Time to convert. ISO string, Unix milliseconds, or "now".', ), timezone: tool.schema .string() .default(DEFAULT_TIMEZONE) .describe('Timezone for the result. Defaults to "Europe/Berlin".'), output_unit: tool.schema .enum(["milliseconds", "seconds"]) .default("milliseconds") .describe( 'Output unit: "milliseconds" (JS default) or "seconds" (Unix standard).', ), }, async execute(args) { const timezone = args.timezone || DEFAULT_TIMEZONE; const tzError = validateTimezone(timezone); if (tzError) return tzError; const dt = parseInput(args.time, timezone); if (!dt) { return `Invalid time: "${args.time}"`; } const ms = dt.toMillis(); const seconds = Math.floor(ms / 1000); return jsonResponse({ input: args.time, iso: dt.toISO(), human: formatHuman(dt), timezone: dt.zoneName, unix_ms: ms, unix_seconds: seconds, output_value: args.output_unit === "seconds" ? seconds : ms, output_unit: args.output_unit, note: args.output_unit === "seconds" ? "Seconds value truncates milliseconds. Use milliseconds for full precision." : "Milliseconds is the JavaScript/JSON standard for timestamps.", }); }, }); // ============================================================================ // INFO - Timezone information // ============================================================================ export const info = tool({ description: `Get detailed information about a timezone. Use this tool to learn about a timezone's properties including its current offset, DST (Daylight Saving Time) status, abbreviation, and IANA identifier. Helpful for understanding timezone behavior and debugging timezone issues. Examples: - Info about Berlin timezone: info({ timezone: "Europe/Berlin" }) - Info about current timezone: info({}) - Check DST status: info({ timezone: "America/New_York", time: "2024-07-15" }) - List available timezones: info({ list_timezones: true })`, args: { timezone: tool.schema .string() .default(DEFAULT_TIMEZONE) .describe('IANA timezone identifier. Defaults to "Europe/Berlin".'), time: tool.schema .string() .optional() .describe( 'Specific time to check DST status. ISO string or "now". Defaults to current time.', ), list_timezones: tool.schema .boolean() .default(false) .describe( "List some common timezone identifiers instead of timezone info.", ), }, async execute(args) { // List common timezones if requested if (args.list_timezones) { const commonTimezones = [ "UTC", "America/New_York", "America/Chicago", "America/Denver", "America/Los_Angeles", "America/Anchorage", "America/Honolulu", "Europe/London", "Europe/Paris", "Europe/Berlin", "Europe/Moscow", "Asia/Dubai", "Asia/Kolkata", "Asia/Bangkok", "Asia/Singapore", "Asia/Tokyo", "Asia/Seoul", "Australia/Sydney", "Pacific/Auckland", ]; return jsonResponse({ message: "Common timezone identifiers", timezones: commonTimezones, note: "For a complete list, visit: https://en.wikipedia.org/wiki/List_of_tz_database_time_zones", }); } const timezone = args.timezone || DEFAULT_TIMEZONE; const tzError = validateTimezone(timezone); if (tzError) return tzError; const now = DateTime.now().setZone(timezone); const dt = args.time ? parseInput(args.time, timezone) : now; if (args.time && !dt) { return `Invalid time: "${args.time}"`; } const zone = dt!.zone; const offsetMinutes = dt!.offset; const offsetHours = Math.floor(Math.abs(offsetMinutes) / 60); const offsetMins = Math.abs(offsetMinutes) % 60; const offsetSign = offsetMinutes >= 0 ? "+" : "-"; // Get DST transitions if possible const isDST = dt!.isInDST; const startOfYear = DateTime.fromObject( { year: dt!.year, month: 1, day: 1 }, { zone: timezone }, ); const midYear = DateTime.fromObject( { year: dt!.year, month: 7, day: 1 }, { zone: timezone }, ); const hasDST = startOfYear.offset !== midYear.offset; return jsonResponse({ timezone: zone.name, iana_id: zone.name, current_offset: { minutes: offsetMinutes, formatted: `UTC${offsetSign}${String(offsetHours).padStart(2, "0")}:${ String(offsetMins).padStart(2, "0") }`, }, offset_name_long: dt!.offsetNameLong, offset_name_short: dt!.offsetNameShort, dst: { is_currently_observing: isDST, has_dst: hasDST, description: hasDST ? isDST ? "Currently in Daylight Saving Time" : "Currently in Standard Time" : "This timezone does not observe DST", }, checked_at: { iso: dt!.toISO(), human: formatHuman(dt!), }, zone_type: zone.type, valid: dt!.isValid, }); }, });