diff --git a/Tools/XDateTools.cs b/Tools/XDateTools.cs new file mode 100644 index 0000000..0df2ce2 --- /dev/null +++ b/Tools/XDateTools.cs @@ -0,0 +1,339 @@ +using System; +using System.Text; +using TimeZoneConverter; +using xCommons.Extensions; +using System.Globalization; +using xAiModels.Attributes; +using System.Collections.Generic; +using System.Text.RegularExpressions; + +namespace xAiMcpServer.Tools +{ + [XAiMcpToolType] + public class XDateTools + { + [XAiMcpTool(Description = "Get the CURRENT date and time right now. Use this tool whenever the user asks about 'today', 'now', 'current date', 'current time', or when you need the current date/time for any relative calculation (like 'three days ago', 'next week', 'how many days until...'). Returns Gregorian, Persian (Jalali), day-of-week, and Unix timestamp.")] + public static string GetCurrentDateTime( + [XAiMcpToolParam(Description = "Optional IANA timezone (e.g. 'Asia/Tehran', 'UTC', 'Europe/London'). Defaults to 'Asia/Tehran'.", Required = false)] + string timezone = null + ) + { + try + { + var tz = ResolveTimezone(timezone ?? "Asia/Tehran"); + var nowUtc = DateTime.UtcNow; + var nowLocal = TimeZoneInfo.ConvertTimeFromUtc(nowUtc, tz); + + var pc = new PersianCalendar(); + var sb = new StringBuilder(); + sb.AppendLine($"Timezone: {tz.Id}"); + sb.AppendLine($"Local: {nowLocal:yyyy-MM-dd HH:mm:ss} {nowLocal:dddd}"); + sb.AppendLine($"UTC: {nowUtc:yyyy-MM-dd HH:mm:ss} UTC"); + sb.AppendLine($"Persian: {pc.GetYear(nowLocal):D4}/{pc.GetMonth(nowLocal):D2}/{pc.GetDayOfMonth(nowLocal):D2} {nowLocal:HH:mm:ss}"); + sb.AppendLine($"ISO 8601: {nowLocal:yyyy-MM-ddTHH:mm:ss.fffzzz}"); + sb.AppendLine($"Unix: {new DateTimeOffset(nowUtc).ToUnixTimeSeconds()}"); + sb.AppendLine($"Week: {ISOWeek.GetWeekOfYear(nowLocal)} (of {nowLocal.Year})"); + return sb.ToString().TrimEnd(); + } + catch (Exception ex) + { + return $"Error: {ex.Message}"; + } + } + + [XAiMcpTool(Description = "Detect and extract all date-like patterns from a free text. Supports Gregorian (2024-11-05), Persian (1403/08/15), Hijri (1446/05/03), ISO 8601, and month-name forms.")] + public static string DetectDates( + [XAiMcpToolParam(Description = "Free text that may contain dates.")] + string text, + [XAiMcpToolParam(Description = "Optional: hint for the primary calendar (Gregorian, Persian, Hijri). Leave empty for auto-detection.", Required = false)] + string calendarHint = null + ) + { + // + if (string.IsNullOrWhiteSpace(text)) + { + return "No text provided."; + } + + // + var patterns = new (string Name, Regex Pattern)[] + { + ("ISO8601", new Regex(@"\b\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:?\d{2})?\b")), + ("NumericYMD", new Regex(@"\b\d{4}[/\-\.]\d{1,2}[/\-\.]\d{1,2}\b")), + ("NumericDMY", new Regex(@"\b\d{1,2}[/\-\.]\d{1,2}[/\-\.]\d{2,4}\b")), + ("PersianMonth", new Regex(@"\b\d{1,2}\s+(فروردین|اردیبهشت|خرداد|تیر|مرداد|شهریور|مهر|آبان|آذر|دی|بهمن|اسفند)\s+\d{4}\b")), + ("EnglishMonth", new Regex(@"\b\d{1,2}\s+(January|February|March|April|May|June|July|August|September|October|November|December)\s+\d{4}\b", RegexOptions.IgnoreCase)), + }; + + // + var found = new List(); + var sb = new StringBuilder(); + foreach (var (name, pattern) in patterns) + { + // + foreach (Match m in pattern.Matches(text)) + { + // + if (!found.Contains(m.Value)) + { + // + found.Add(m.Value); + sb.AppendLine($"• {m.Value} [{name}]"); + } + } + } + + // + return found.Count == 0 + ? "No date pattern detected." + : $"Detected {found.Count} date(s):\n{sb.ToString().TrimEnd()}"; + } + + [XAiMcpTool(Description = "Parse a single date string. Returns the detected calendar, plus normalized Gregorian (ISO 8601), Persian, Hijri representations, and Unix timestamp.")] + public static string ParseDate( + [XAiMcpToolParam(Description = "Date string like '1403/08/15' or '2024-11-05'.")] + string date, + [XAiMcpToolParam(Description = "Optional: calendar hint (Gregorian, Persian, Hijri). Leave empty for auto-detect.", Required = false)] + string calendarHint = null + ) + { + // + try + { + // + var dt = ParseDateToGregorian(date, calendarHint); + return BuildReport(dt); + } + catch (Exception ex) + { + return $"Error: {ex.Message}"; + } + } + + [XAiMcpTool(Description = "Convert a date from one calendar to another. Supported calendars: Gregorian, Persian (Jalali/Shamsi), Hijri (Islamic).")] + public static string ConvertDate( + [XAiMcpToolParam(Description = "Date string in the source calendar.")] + string date, + [XAiMcpToolParam(Description = "Source calendar: Gregorian, Persian, or Hijri.")] + string fromCalendar, + [XAiMcpToolParam(Description = "Target calendar: Gregorian, Persian, or Hijri.")] + string toCalendar + ) + { + // + try + { + // + var greg = ParseDateToGregorian(date, fromCalendar); + var target = NormalizeCalendarName(toCalendar); + var cal = GetCalendar(target); + + // + return $"{cal.GetYear(greg):D4}/{cal.GetMonth(greg):D2}/{cal.GetDayOfMonth(greg):D2}"; + } + catch (Exception ex) + { + return $"Error: {ex.Message}"; + } + } + + [XAiMcpTool(Description = "Calculate the difference between two dates. Returns total days, and a breakdown into years/months/days.")] + public static string DateDifference( + [XAiMcpToolParam(Description = "First date string.")] + string date1, + [XAiMcpToolParam(Description = "Second date string.")] + string date2, + [XAiMcpToolParam(Description = "Optional: calendar hint for both dates.", Required = false)] + string calendarHint = null + ) + { + // + try + { + // + var d1 = ParseDateToGregorian(date1, calendarHint); + var d2 = ParseDateToGregorian(date2, calendarHint); + var span = d2 - d1; + + // + return $"Difference: {span.Days} days (= {span.Days / 365} years + {(span.Days % 365) / 30} months + {(span.Days % 365) % 30} days)"; + } + catch (Exception ex) + { + return $"Error: {ex.Message}"; + } + } + + [XAiMcpTool(Description = "Convert a date string to Unix timestamp (seconds since 1970-01-01 UTC).")] + public static string ToUnixTimestamp( + [XAiMcpToolParam(Description = "Date string.")] + string date, + [XAiMcpToolParam(Description = "Optional: calendar hint (Gregorian, Persian, Hijri).", Required = false)] + string calendarHint = null + ) + { + // + try + { + // + var dt = ParseDateToGregorian(date, calendarHint); + var ts = new DateTimeOffset(dt, TimeSpan.Zero).ToUnixTimeSeconds(); + + // + return ts.ToString(); + } + catch (Exception ex) + { + return $"Error: {ex.Message}"; + } + } + + [XAiMcpTool(Description = "Convert a Unix timestamp (seconds since 1970-01-01 UTC) back to a date string in the specified calendar.")] + public static string FromUnixTimestamp( + [XAiMcpToolParam(Description = "Unix timestamp in seconds.")] + long timestamp, + [XAiMcpToolParam(Description = "Optional: target calendar (Gregorian, Persian, Hijri). Defaults to Gregorian.", Required = false)] + string targetCalendar = null + ) + { + // + try + { + // + var dt = DateTimeOffset.FromUnixTimeSeconds(timestamp).UtcDateTime; + var calName = NormalizeCalendarName(targetCalendar) ?? "Gregorian"; + if (calName == "Gregorian") + { + return dt.ToString("yyyy-MM-dd HH:mm:ss 'UTC'"); + } + + // + var c = GetCalendar(calName); + return $"{c.GetYear(dt):D4}/{c.GetMonth(dt):D2}/{c.GetDayOfMonth(dt):D2}"; + } + catch (Exception ex) + { + return $"Error: {ex.Message}"; + } + } + + // + #region Private ... + private static string BuildReport(DateTime greg) + { + // + var pc = new PersianCalendar(); + var hc = new UmAlQuraCalendar(); + var sb = new StringBuilder(); + + // + sb.AppendLine($"Gregorian: {greg:yyyy-MM-dd}"); + sb.AppendLine($"Persian: {pc.GetYear(greg):D4}/{pc.GetMonth(greg):D2}/{pc.GetDayOfMonth(greg):D2}"); + sb.AppendLine($"Hijri: {hc.GetYear(greg):D4}/{hc.GetMonth(greg):D2}/{hc.GetDayOfMonth(greg):D2}"); + sb.AppendLine($"ISO 8601: {greg:yyyy-MM-ddTHH:mm:ss.fffZ}"); + sb.AppendLine($"Unix: {new DateTimeOffset(greg, TimeSpan.Zero).ToUnixTimeSeconds()}"); + + // + return sb.ToString().TrimEnd(); + } + + private static DateTime ParseDateToGregorian(string date, string calendarHint) + { + // + if (string.IsNullOrWhiteSpace(date)) + { + throw new ArgumentException("date is empty"); + } + + // + var m = Regex.Match(date.Trim(), @"^(?\d{4})[/\-\.](?\d{1,2})[/\-\.](?\d{1,2})$"); + if (!m.Success) + { + throw new FormatException($"Unrecognized date format: '{date}'. Expected yyyy/MM/dd."); + } + + // + var y = int.Parse(m.Groups["y"].Value); + var mo = int.Parse(m.Groups["m"].Value); + var d = int.Parse(m.Groups["d"].Value); + + // + var calName = NormalizeCalendarName(calendarHint) ?? AutoDetectCalendar(y); + return calName switch + { + // + "Gregorian" => new DateTime(y, mo, d), + "Persian" => new PersianCalendar().ToDateTime(y, mo, d, 0, 0, 0, 0), + "Hijri" => new UmAlQuraCalendar().ToDateTime(y, mo, d, 0, 0, 0, 0), + _ => throw new ArgumentException($"Unknown calendar: {calendarHint}") + }; + } + + private static string NormalizeCalendarName(string name) + { + // + if (string.IsNullOrWhiteSpace(name)) + { + return null; + } + + // + var n = name.Trim().ToLowerInvariant(); + return n switch + { + // + "gregorian" or "میلادی" or "g" => "Gregorian", + "persian" or "jalali" or "shamsi" or "شمسی" or "جلالی" or "p" => "Persian", + "hijri" or "islamic" or "قمری" or "هجری" or "h" => "Hijri", + _ => throw new ArgumentException($"Unknown calendar: {name}. Use Gregorian, Persian, or Hijri.") + }; + } + + private static string AutoDetectCalendar(int year) + { + // + if (year >= 1900 && year <= 2100) + { + return "Gregorian"; + } + + // + if (year >= 1300 && year <= 1499) + { + return "Persian"; + } + + // + return "Gregorian"; + } + + private static TimeZoneInfo ResolveTimezone(string timezoneId) + { + // + if (timezoneId.IsNullOrEmpty()) + { + timezoneId = "UTC"; + } + + // + try + { + return TZConvert.GetTimeZoneInfo(timezoneId); + } + catch + { + return TimeZoneInfo.Utc; + } + } + + private static Calendar GetCalendar(string name) => name switch + { + // + "Gregorian" => new GregorianCalendar(), + "Persian" => new PersianCalendar(), + "Hijri" => new UmAlQuraCalendar(), + _ => throw new ArgumentException($"Unknown calendar: {name}") + }; + #endregion + } +} \ No newline at end of file