| 1 | /* |
| 2 | * timeutil.c - the tools of plugin_time and the formatting they share. |
| 3 | * |
| 4 | * Three tools, matching the reference `mcp_server_time` server: |
| 5 | * |
| 6 | * get_current_time -> {timezone, datetime, day_of_week, is_dst} |
| 7 | * convert_time -> {source, target, time_difference, later_occurrence} |
| 8 | * get_time_ago -> {timezone, datetime, day_of_week, is_dst} |
| 9 | * |
| 10 | * The reference server's semantics are reproduced, not approximated: |
| 11 | * |
| 12 | * - an omitted timezone defaults to the node's own zone, and the tool |
| 13 | * descriptions name it so a model can default to it; |
| 14 | * - an unknown key is a tool error whose text starts "Invalid timezone:"; |
| 15 | * - `time` is HH:MM in 24-hour form, and anything else is |
| 16 | * "Invalid time format. Expected HH:MM [24-hour format]"; |
| 17 | * - a wall time skipped by a forward clock change is an error naming the |
| 18 | * date, not a silently shifted answer; |
| 19 | * - a wall time repeated by a backward clock change answers the FIRST |
| 20 | * occurrence in source/target and reports the second under |
| 21 | * `later_occurrence`, which is the behaviour of Python's fold=0/fold=1; |
| 22 | * - `time_difference` is "+3.0h", and a fractional zone like Nepal's +05:45 |
| 23 | * prints "+5.75h" (two decimals, trailing zeros stripped). |
| 24 | * |
| 25 | * Nothing in here reads the clock directly: now_utc() honours SX_TIME_NOW |
| 26 | * (an ISO-8601 UTC instant) so the suite can pin a date and prove a DST edge |
| 27 | * with the same answer on every platform. |
| 28 | * |
| 29 | * MIT License. Copyright (c) 2026 SCORPIOX INC. |
| 30 | */ |
| 31 | #if defined(_WIN32) && !defined(_WIN32_WINNT) |
| 32 | # define _WIN32_WINNT 0x0601 |
| 33 | #endif |
| 34 | |
| 35 | #if !defined(_WIN32) |
| 36 | # define _POSIX_C_SOURCE 200809L |
| 37 | # define _DEFAULT_SOURCE 1 |
| 38 | #endif |
| 39 | |
| 40 | #include <stdio.h> |
| 41 | #include <stdlib.h> |
| 42 | #include <string.h> |
| 43 | #include <stdarg.h> |
| 44 | #include <ctype.h> |
| 45 | #include <time.h> |
| 46 | |
| 47 | #include "plugintime.h" |
| 48 | #include "tz.h" |
| 49 | |
| 50 | const char *const TOOL_NAMES[] = { |
| 51 | "get_current_time", "convert_time", "get_time_ago" |
| 52 | }; |
| 53 | const int TOOL_COUNT = (int)(sizeof TOOL_NAMES / sizeof TOOL_NAMES[0]); |
| 54 | |
| 55 | /* ------------------------------------------------------------------ */ |
| 56 | /* Growable buffer */ |
| 57 | /* ------------------------------------------------------------------ */ |
| 58 | |
| 59 | void buf_init(buf_t *b) |
| 60 | { |
| 61 | b->p = NULL; |
| 62 | b->n = 0; |
| 63 | b->cap = 0; |
| 64 | } |
| 65 | |
| 66 | int buf_need(buf_t *b, size_t extra) |
| 67 | { |
| 68 | size_t want = b->n + extra + 1; |
| 69 | char *np; |
| 70 | size_t cap; |
| 71 | |
| 72 | if (want <= b->cap) return 0; |
| 73 | cap = b->cap ? b->cap : 256; |
| 74 | while (cap < want) { |
| 75 | if (cap > (size_t)-1 / 2) return -1; |
| 76 | cap *= 2; |
| 77 | } |
| 78 | np = (char *)realloc(b->p, cap); |
| 79 | if (!np) return -1; |
| 80 | b->p = np; |
| 81 | b->cap = cap; |
| 82 | return 0; |
| 83 | } |
| 84 | |
| 85 | void buf_add(buf_t *b, const char *s, size_t n) |
| 86 | { |
| 87 | if (buf_need(b, n) != 0) return; |
| 88 | if (n) memcpy(b->p + b->n, s, n); |
| 89 | b->n += n; |
| 90 | b->p[b->n] = '\0'; |
| 91 | } |
| 92 | |
| 93 | void buf_puts(buf_t *b, const char *s) |
| 94 | { |
| 95 | if (s) buf_add(b, s, strlen(s)); |
| 96 | } |
| 97 | |
| 98 | void buf_putc(buf_t *b, int c) |
| 99 | { |
| 100 | char ch = (char)c; |
| 101 | buf_add(b, &ch, 1); |
| 102 | } |
| 103 | |
| 104 | void buf_printf(buf_t *b, const char *fmt, ...) |
| 105 | { |
| 106 | va_list ap; |
| 107 | int need; |
| 108 | char tmp[512]; |
| 109 | |
| 110 | va_start(ap, fmt); |
| 111 | need = vsnprintf(tmp, sizeof tmp, fmt, ap); |
| 112 | va_end(ap); |
| 113 | if (need < 0) return; |
| 114 | if ((size_t)need < sizeof tmp) { |
| 115 | buf_add(b, tmp, (size_t)need); |
| 116 | return; |
| 117 | } |
| 118 | if (buf_need(b, (size_t)need) != 0) return; |
| 119 | va_start(ap, fmt); |
| 120 | vsnprintf(b->p + b->n, (size_t)need + 1, fmt, ap); |
| 121 | va_end(ap); |
| 122 | b->n += (size_t)need; |
| 123 | } |
| 124 | |
| 125 | const char *buf_str(const buf_t *b) |
| 126 | { |
| 127 | return b->p ? b->p : ""; |
| 128 | } |
| 129 | |
| 130 | void buf_free(buf_t *b) |
| 131 | { |
| 132 | free(b->p); |
| 133 | buf_init(b); |
| 134 | } |
| 135 | |
| 136 | void json_str(buf_t *b, const char *s) |
| 137 | { |
| 138 | buf_putc(b, '"'); |
| 139 | if (s) { |
| 140 | for (; *s; s++) { |
| 141 | unsigned char c = (unsigned char)*s; |
| 142 | switch (c) { |
| 143 | case '"': buf_puts(b, "\\\""); break; |
| 144 | case '\\': buf_puts(b, "\\\\"); break; |
| 145 | case '\n': buf_puts(b, "\\n"); break; |
| 146 | case '\r': buf_puts(b, "\\r"); break; |
| 147 | case '\t': buf_puts(b, "\\t"); break; |
| 148 | default: |
| 149 | if (c < 0x20) buf_printf(b, "\\u%04x", c); |
| 150 | else buf_putc(b, (char)c); |
| 151 | } |
| 152 | } |
| 153 | } |
| 154 | buf_putc(b, '"'); |
| 155 | } |
| 156 | |
| 157 | /* ------------------------------------------------------------------ */ |
| 158 | /* Formatting */ |
| 159 | /* ------------------------------------------------------------------ */ |
| 160 | |
| 161 | void time_split(int64_t utc, int offset, int *year, int *month, int *day, |
| 162 | int *hour, int *min, int *sec, int *weekday) |
| 163 | { |
| 164 | int64_t local = utc + offset; |
| 165 | int64_t days = local / 86400; |
| 166 | int64_t rem = local % 86400; |
| 167 | int y, m, d; |
| 168 | |
| 169 | /* Floor division: a negative instant must round toward the past, not |
| 170 | * toward zero, or a timestamp before 1970 gets the wrong date. */ |
| 171 | if (rem < 0) { |
| 172 | rem += 86400; |
| 173 | days -= 1; |
| 174 | } |
| 175 | tz_civil_from_days(days, &y, &m, &d); |
| 176 | if (year) *year = y; |
| 177 | if (month) *month = m; |
| 178 | if (day) *day = d; |
| 179 | if (hour) *hour = (int)(rem / 3600); |
| 180 | if (min) *min = (int)((rem % 3600) / 60); |
| 181 | if (sec) *sec = (int)(rem % 60); |
| 182 | if (weekday) *weekday = tz_weekday(days); |
| 183 | } |
| 184 | |
| 185 | void time_offset_str(int offset, char *out, size_t outsz) |
| 186 | { |
| 187 | int a = offset < 0 ? -offset : offset; |
| 188 | char sign = offset < 0 ? '-' : '+'; |
| 189 | |
| 190 | snprintf(out, outsz, "%c%02d:%02d", sign, a / 3600, (a % 3600) / 60); |
| 191 | } |
| 192 | |
| 193 | void time_iso(int64_t utc, int offset, char *out, size_t outsz) |
| 194 | { |
| 195 | int y, m, d, hh, mm, ss; |
| 196 | char off[16]; |
| 197 | |
| 198 | time_split(utc, offset, &y, &m, &d, &hh, &mm, &ss, NULL); |
| 199 | time_offset_str(offset, off, sizeof off); |
| 200 | snprintf(out, outsz, "%04d-%02d-%02dT%02d:%02d:%02d%s", y, m, d, hh, mm, ss, off); |
| 201 | } |
| 202 | |
| 203 | static const char *const WEEKDAYS[7] = { |
| 204 | "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" |
| 205 | }; |
| 206 | |
| 207 | const char *time_weekday_name(int weekday) |
| 208 | { |
| 209 | if (weekday < 0 || weekday > 6) return WEEKDAYS[0]; |
| 210 | return WEEKDAYS[weekday]; |
| 211 | } |
| 212 | |
| 213 | void time_diff_str(int source_off, int target_off, char *out, size_t outsz) |
| 214 | { |
| 215 | int diff = target_off - source_off; |
| 216 | double hours = (double)diff / 3600.0; |
| 217 | char tmp[32]; |
| 218 | |
| 219 | /* The reference prints one decimal when the difference is a whole number |
| 220 | * of hours, otherwise two decimals with trailing zeros stripped. */ |
| 221 | if (diff % 3600 == 0) { |
| 222 | snprintf(out, outsz, "%+.1fh", hours); |
| 223 | return; |
| 224 | } |
| 225 | snprintf(tmp, sizeof tmp, "%+.2f", hours); |
| 226 | { |
| 227 | size_t n = strlen(tmp); |
| 228 | while (n > 0 && tmp[n - 1] == '0') tmp[--n] = '\0'; |
| 229 | if (n > 0 && tmp[n - 1] == '.') tmp[--n] = '\0'; |
| 230 | } |
| 231 | snprintf(out, outsz, "%sh", tmp); |
| 232 | } |
| 233 | |
| 234 | /* ------------------------------------------------------------------ */ |
| 235 | /* "now" */ |
| 236 | /* ------------------------------------------------------------------ */ |
| 237 | |
| 238 | static int parse_iso_utc(const char *s, int64_t *out) |
| 239 | { |
| 240 | int y = 0, mo = 0, d = 0, hh = 0, mm = 0, ss = 0; |
| 241 | int n = 0; |
| 242 | |
| 243 | if (!s || !*s) return -1; |
| 244 | if (sscanf(s, "%4d-%2d-%2dT%2d:%2d:%2d%n", &y, &mo, &d, &hh, &mm, &ss, &n) < 6) |
| 245 | return -1; |
| 246 | if (s[n] && s[n] != 'Z' && s[n] != 'z' && s[n] != '+' && s[n] != '-') return -1; |
| 247 | if (mo < 1 || mo > 12 || d < 1 || d > 31) return -1; |
| 248 | if (hh < 0 || hh > 23 || mm < 0 || mm > 59 || ss < 0 || ss > 60) return -1; |
| 249 | *out = tz_days_from_civil(y, mo, d) * 86400 + hh * 3600 + mm * 60 + ss; |
| 250 | return 0; |
| 251 | } |
| 252 | |
| 253 | /* The current UTC instant. SX_TIME_NOW ("2026-03-29T01:30:00Z") pins it so a |
| 254 | * test can assert a DST edge without waiting for one; an unparseable value is |
| 255 | * ignored rather than fatal, because a broken env var must not take the |
| 256 | * connector down. */ |
| 257 | int64_t time_now_utc(void) |
| 258 | { |
| 259 | const char *env = getenv("SX_TIME_NOW"); |
| 260 | int64_t pinned; |
| 261 | |
| 262 | if (env && *env && parse_iso_utc(env, &pinned) == 0) return pinned; |
| 263 | return (int64_t)time(NULL); |
| 264 | } |
| 265 | |
| 266 | /* ------------------------------------------------------------------ */ |
| 267 | /* Result plumbing */ |
| 268 | /* ------------------------------------------------------------------ */ |
| 269 | |
| 270 | void tool_out_init(tool_out_t *t) |
| 271 | { |
| 272 | memset(t, 0, sizeof *t); |
| 273 | } |
| 274 | |
| 275 | void tool_err(tool_out_t *t, const char *fmt, ...) |
| 276 | { |
| 277 | char tmp[768]; |
| 278 | va_list ap; |
| 279 | |
| 280 | va_start(ap, fmt); |
| 281 | vsnprintf(tmp, sizeof tmp, fmt, ap); |
| 282 | va_end(ap); |
| 283 | if (!t->error) { |
| 284 | size_t n = strlen(tmp); |
| 285 | t->error = (char *)malloc(n + 1); |
| 286 | if (t->error) memcpy(t->error, tmp, n + 1); |
| 287 | } |
| 288 | t->is_error = 1; |
| 289 | } |
| 290 | |
| 291 | void tool_free(tool_out_t *t) |
| 292 | { |
| 293 | if (!t) return; |
| 294 | if (t->md) yyjson_mut_doc_free(t->md); |
| 295 | free(t->error); |
| 296 | memset(t, 0, sizeof *t); |
| 297 | } |
| 298 | |
| 299 | static void tool_start(tool_out_t *t) |
| 300 | { |
| 301 | if (t->md) return; |
| 302 | t->md = yyjson_mut_doc_new(NULL); |
| 303 | if (!t->md) { tool_err(t, "out of memory"); return; } |
| 304 | t->root = yyjson_mut_obj(t->md); |
| 305 | if (!t->root) { |
| 306 | yyjson_mut_doc_free(t->md); |
| 307 | t->md = NULL; |
| 308 | tool_err(t, "out of memory"); |
| 309 | return; |
| 310 | } |
| 311 | yyjson_mut_doc_set_root(t->md, t->root); |
| 312 | } |
| 313 | |
| 314 | /* COPY, not reference: yyjson_mut_obj_add_str stores the caller's pointer, so a |
| 315 | * stack buffer (every description and timezone name in this file) is reused and |
| 316 | * the document serialises garbage. Silent, valid-looking JSON - pinned by the |
| 317 | * "description is not the timezone text" assertion in tests/run.sh. */ |
| 318 | static void add_str(yyjson_mut_doc *md, yyjson_mut_val *obj, |
| 319 | const char *k, const char *v) |
| 320 | { |
| 321 | yyjson_mut_obj_add_strcpy(md, obj, k, v ? v : ""); |
| 322 | } |
| 323 | |
| 324 | static void add_bool(yyjson_mut_doc *md, yyjson_mut_val *obj, |
| 325 | const char *k, int v) |
| 326 | { |
| 327 | yyjson_mut_obj_add_bool(md, obj, k, v ? true : false); |
| 328 | } |
| 329 | |
| 330 | /* Fill a TimeResult object. The two single-result tools fill the root object |
| 331 | * directly; convert_time nests one per side, so they are the same four fields |
| 332 | * everywhere and a caller never has to unwrap a "result" key. */ |
| 333 | static void time_result_fill(yyjson_mut_doc *md, yyjson_mut_val *o, |
| 334 | const tz_zone *z, int64_t utc, const char *name) |
| 335 | { |
| 336 | int off, dst = 0; |
| 337 | char iso[64], abbr[24]; |
| 338 | |
| 339 | off = tz_offset(z, utc, &dst, abbr, sizeof abbr); |
| 340 | time_iso(utc, off, iso, sizeof iso); |
| 341 | |
| 342 | add_str(md, o, "timezone", name); |
| 343 | add_str(md, o, "datetime", iso); |
| 344 | { |
| 345 | int wd = 0; |
| 346 | time_split(utc, off, NULL, NULL, NULL, NULL, NULL, NULL, &wd); |
| 347 | add_str(md, o, "day_of_week", time_weekday_name(wd)); |
| 348 | } |
| 349 | add_bool(md, o, "is_dst", dst); |
| 350 | /* Two fields the reference does not carry: a caller reading the text |
| 351 | * block should not have to re-derive the numeric offset or the zone |
| 352 | * abbreviation, and neither changes the meaning of the standard four. */ |
| 353 | { |
| 354 | char offs[16]; |
| 355 | time_offset_str(off, offs, sizeof offs); |
| 356 | add_str(md, o, "utc_offset", offs); |
| 357 | add_str(md, o, "abbreviation", abbr); |
| 358 | } |
| 359 | } |
| 360 | |
| 361 | static yyjson_mut_val *time_result_obj(yyjson_mut_doc *md, const tz_zone *z, |
| 362 | int64_t utc, const char *name) |
| 363 | { |
| 364 | yyjson_mut_val *o = yyjson_mut_obj(md); |
| 365 | time_result_fill(md, o, z, utc, name); |
| 366 | return o; |
| 367 | } |
| 368 | |
| 369 | /* Resolve a timezone argument; fills `name` (the default when absent). */ |
| 370 | static const tz_zone *zone_arg(yyjson_val *args, const char *key, |
| 371 | char *name, size_t namesz, tool_out_t *t) |
| 372 | { |
| 373 | yyjson_val *v = args ? yyjson_obj_get(args, key) : NULL; |
| 374 | |
| 375 | if (v && yyjson_is_str(v)) { |
| 376 | const char *s = yyjson_get_str(v); |
| 377 | /* A string whose declared length is longer than the C string means an |
| 378 | * embedded NUL: refuse it rather than resolving a prefix. */ |
| 379 | if (strlen(s) != yyjson_get_len(v)) { |
| 380 | tool_err(t, "Invalid timezone: the name contains a NUL byte"); |
| 381 | return NULL; |
| 382 | } |
| 383 | if (!*s) { |
| 384 | tool_err(t, "Invalid timezone: the name is empty"); |
| 385 | return NULL; |
| 386 | } |
| 387 | snprintf(name, namesz, "%s", s); |
| 388 | } else if (v && !yyjson_is_null(v)) { |
| 389 | tool_err(t, "%s must be a string (an IANA timezone name)", key); |
| 390 | return NULL; |
| 391 | } else { |
| 392 | snprintf(name, namesz, "%s", tz_local_name()); |
| 393 | } |
| 394 | { |
| 395 | const tz_zone *z = tz_find(name); |
| 396 | if (!z) { |
| 397 | tool_err(t, "Invalid timezone: No time zone found with key %s", name); |
| 398 | return NULL; |
| 399 | } |
| 400 | return z; |
| 401 | } |
| 402 | } |
| 403 | |
| 404 | static int int_arg(yyjson_val *args, const char *key, int dflt, int lo, int hi, |
| 405 | tool_out_t *t) |
| 406 | { |
| 407 | yyjson_val *v = args ? yyjson_obj_get(args, key) : NULL; |
| 408 | long long n; |
| 409 | |
| 410 | if (!v || yyjson_is_null(v)) return dflt; |
| 411 | if (yyjson_is_int(v)) { |
| 412 | n = (long long)yyjson_get_sint(v); |
| 413 | } else if (yyjson_is_str(v)) { |
| 414 | char *end = NULL; |
| 415 | n = strtoll(yyjson_get_str(v), &end, 10); |
| 416 | if (!end || *end) { |
| 417 | tool_err(t, "%s must be an integer (whole number)", key); |
| 418 | return dflt; |
| 419 | } |
| 420 | } else { |
| 421 | tool_err(t, "%s must be an integer (whole number)", key); |
| 422 | return dflt; |
| 423 | } |
| 424 | if (n < lo || n > hi) { |
| 425 | tool_err(t, "%s must be between %d and %d", key, lo, hi); |
| 426 | return dflt; |
| 427 | } |
| 428 | return (int)n; |
| 429 | } |
| 430 | |
| 431 | /* ------------------------------------------------------------------ */ |
| 432 | /* get_current_time */ |
| 433 | /* ------------------------------------------------------------------ */ |
| 434 | |
| 435 | void tool_get_current_time(yyjson_val *args, tool_out_t *t) |
| 436 | { |
| 437 | char name[TZ_NAME_MAX + 1]; |
| 438 | const tz_zone *z; |
| 439 | int64_t now = time_now_utc(); |
| 440 | |
| 441 | tool_out_init(t); |
| 442 | z = zone_arg(args, "timezone", name, sizeof name, t); |
| 443 | if (!z) return; |
| 444 | |
| 445 | tool_start(t); |
| 446 | if (t->is_error) return; |
| 447 | time_result_fill(t->md, t->root, z, now, name); |
| 448 | } |
| 449 | |
| 450 | /* ------------------------------------------------------------------ */ |
| 451 | /* get_time_ago */ |
| 452 | /* ------------------------------------------------------------------ */ |
| 453 | |
| 454 | void tool_get_time_ago(yyjson_val *args, tool_out_t *t) |
| 455 | { |
| 456 | char name[TZ_NAME_MAX + 1]; |
| 457 | const tz_zone *z; |
| 458 | int d, h, m, s; |
| 459 | int64_t span, past; |
| 460 | |
| 461 | tool_out_init(t); |
| 462 | z = zone_arg(args, "timezone", name, sizeof name, t); |
| 463 | if (!z) return; |
| 464 | |
| 465 | d = int_arg(args, "days_ago", 0, 0, 365000, t); |
| 466 | if (t->is_error) return; |
| 467 | h = int_arg(args, "hours_ago", 0, 0, 100000000, t); |
| 468 | if (t->is_error) return; |
| 469 | m = int_arg(args, "minutes_ago", 0, 0, 100000000, t); |
| 470 | if (t->is_error) return; |
| 471 | s = int_arg(args, "seconds_ago", 0, 0, 100000000, t); |
| 472 | if (t->is_error) return; |
| 473 | |
| 474 | /* The span is subtracted from the UTC instant, not the local wall clock: |
| 475 | * "5 hours ago" across a clock change is five real hours back. */ |
| 476 | span = (int64_t)d * 86400 + (int64_t)h * 3600 + (int64_t)m * 60 + (int64_t)s; |
| 477 | past = time_now_utc() - span; |
| 478 | |
| 479 | tool_start(t); |
| 480 | if (t->is_error) return; |
| 481 | time_result_fill(t->md, t->root, z, past, name); |
| 482 | } |
| 483 | |
| 484 | /* ------------------------------------------------------------------ */ |
| 485 | /* convert_time */ |
| 486 | /* ------------------------------------------------------------------ */ |
| 487 | |
| 488 | /* "HH:MM" -> seconds after midnight. Rejects anything else, including a |
| 489 | * trailing colon, a 24th hour or a 60th minute. */ |
| 490 | static int parse_hhmm(const char *s, int *out) |
| 491 | { |
| 492 | /* Exactly HH:MM. sscanf("%2d:%2d") would also accept "9:00" and " 9:00", |
| 493 | * and the reference server rejects both, so the shape is checked by hand |
| 494 | * before a number is read. */ |
| 495 | if (!s || strlen(s) != 5) return -1; |
| 496 | if (!isdigit((unsigned char)s[0]) || !isdigit((unsigned char)s[1])) return -1; |
| 497 | if (s[2] != ':') return -1; |
| 498 | if (!isdigit((unsigned char)s[3]) || !isdigit((unsigned char)s[4])) return -1; |
| 499 | { |
| 500 | int h = (s[0] - '0') * 10 + (s[1] - '0'); |
| 501 | int m = (s[3] - '0') * 10 + (s[4] - '0'); |
| 502 | if (h > 23 || m > 59) return -1; |
| 503 | *out = h * 3600 + m * 60; |
| 504 | } |
| 505 | return 0; |
| 506 | } |
| 507 | |
| 508 | void tool_convert_time(yyjson_val *args, tool_out_t *t) |
| 509 | { |
| 510 | char src_name[TZ_NAME_MAX + 1]; |
| 511 | char dst_name[TZ_NAME_MAX + 1]; |
| 512 | const tz_zone *zs, *zd; |
| 513 | yyjson_val *tv; |
| 514 | const char *time_str = NULL; |
| 515 | int mins; |
| 516 | int64_t now, today, wall; |
| 517 | tz_cand_t cand[TZ_MAX_CANDIDATES]; |
| 518 | int ncand; |
| 519 | int i; |
| 520 | int off_s, off_t; |
| 521 | char diff[32]; |
| 522 | int so, mo, dd; |
| 523 | |
| 524 | tool_out_init(t); |
| 525 | |
| 526 | tv = args ? yyjson_obj_get(args, "time") : NULL; |
| 527 | if (!tv || !yyjson_is_str(tv)) { |
| 528 | tool_err(t, "Missing required argument: time"); |
| 529 | return; |
| 530 | } |
| 531 | time_str = yyjson_get_str(tv); |
| 532 | if (strlen(time_str) != yyjson_get_len(tv)) { |
| 533 | tool_err(t, "Invalid time format. Expected HH:MM [24-hour format]"); |
| 534 | return; |
| 535 | } |
| 536 | if (parse_hhmm(time_str, &mins) != 0) { |
| 537 | tool_err(t, "Invalid time format. Expected HH:MM [24-hour format]"); |
| 538 | return; |
| 539 | } |
| 540 | |
| 541 | zs = zone_arg(args, "source_timezone", src_name, sizeof src_name, t); |
| 542 | if (!zs) return; |
| 543 | zd = zone_arg(args, "target_timezone", dst_name, sizeof dst_name, t); |
| 544 | if (!zd) return; |
| 545 | |
| 546 | /* "Today" in the source zone, at the requested wall time. */ |
| 547 | now = time_now_utc(); |
| 548 | off_s = tz_offset(zs, now, NULL, NULL, 0); |
| 549 | time_split(now, off_s, NULL, NULL, NULL, NULL, NULL, NULL, NULL); |
| 550 | { |
| 551 | int y, m, d; |
| 552 | time_split(now, off_s, &y, &m, &d, NULL, NULL, NULL, NULL); |
| 553 | today = tz_days_from_civil(y, m, d); |
| 554 | so = y; mo = m; dd = d; |
| 555 | } |
| 556 | wall = today * 86400 + mins; |
| 557 | |
| 558 | ncand = tz_resolve_wall(zs, wall, cand, TZ_MAX_CANDIDATES); |
| 559 | if (ncand == 0) { |
| 560 | char date[32]; |
| 561 | time_split(wall, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL); |
| 562 | snprintf(date, sizeof date, "%04d-%02d-%02d", so, mo, dd); |
| 563 | tool_err(t, "Invalid time: %s does not exist in %s on %s " |
| 564 | "(skipped by a clock change)", time_str, src_name, date); |
| 565 | return; |
| 566 | } |
| 567 | |
| 568 | tool_start(t); |
| 569 | if (t->is_error) return; |
| 570 | |
| 571 | { |
| 572 | yyjson_mut_val *src_obj = time_result_obj(t->md, zs, cand[0].utc, src_name); |
| 573 | yyjson_mut_val *dst_obj = time_result_obj(t->md, zd, cand[0].utc, dst_name); |
| 574 | |
| 575 | off_s = tz_offset(zs, cand[0].utc, NULL, NULL, 0); |
| 576 | off_t = tz_offset(zd, cand[0].utc, NULL, NULL, 0); |
| 577 | time_diff_str(off_s, off_t, diff, sizeof diff); |
| 578 | |
| 579 | yyjson_mut_obj_add_val(t->md, t->root, "source", src_obj); |
| 580 | yyjson_mut_obj_add_val(t->md, t->root, "target", dst_obj); |
| 581 | add_str(t->md, t->root, "time_difference", diff); |
| 582 | |
| 583 | /* A repeated hour has two instants. The reference reports both rather |
| 584 | * than presenting the first as the only answer. */ |
| 585 | if (ncand > 1) { |
| 586 | yyjson_mut_val *later = yyjson_mut_obj(t->md); |
| 587 | yyjson_mut_val *lsrc, *ldst; |
| 588 | char note[512]; |
| 589 | char src_iso[64], later_iso[64]; |
| 590 | char d2[32]; |
| 591 | int o_s; |
| 592 | |
| 593 | o_s = tz_offset(zs, cand[0].utc, NULL, NULL, 0); |
| 594 | time_iso(cand[0].utc, o_s, src_iso, sizeof src_iso); |
| 595 | o_s = tz_offset(zs, cand[1].utc, NULL, NULL, 0); |
| 596 | time_iso(cand[1].utc, o_s, later_iso, sizeof later_iso); |
| 597 | |
| 598 | snprintf(note, sizeof note, |
| 599 | "%s occurs twice in %s on %04d-%02d-%02d because a clock " |
| 600 | "change repeats it: first at %s, then at %s. source and " |
| 601 | "target are the first occurrence; this is the second.", |
| 602 | time_str, src_name, so, mo, dd, src_iso, later_iso); |
| 603 | add_str(t->md, later, "note", note); |
| 604 | |
| 605 | lsrc = time_result_obj(t->md, zs, cand[1].utc, src_name); |
| 606 | ldst = time_result_obj(t->md, zd, cand[1].utc, dst_name); |
| 607 | off_s = tz_offset(zs, cand[1].utc, NULL, NULL, 0); |
| 608 | off_t = tz_offset(zd, cand[1].utc, NULL, NULL, 0); |
| 609 | time_diff_str(off_s, off_t, d2, sizeof d2); |
| 610 | |
| 611 | yyjson_mut_obj_add_val(t->md, later, "source", lsrc); |
| 612 | yyjson_mut_obj_add_val(t->md, later, "target", ldst); |
| 613 | add_str(t->md, later, "time_difference", d2); |
| 614 | yyjson_mut_obj_add_val(t->md, t->root, "later_occurrence", later); |
| 615 | } else { |
| 616 | yyjson_mut_obj_add_null(t->md, t->root, "later_occurrence"); |
| 617 | } |
| 618 | } |
| 619 | (void)i; |
| 620 | (void)off_s; |
| 621 | (void)off_t; |
| 622 | } |
| 623 | |
| 624 | /* ------------------------------------------------------------------ */ |
| 625 | /* Schemas and dispatch */ |
| 626 | /* ------------------------------------------------------------------ */ |
| 627 | |
| 628 | char *tools_list_json(void) |
| 629 | { |
| 630 | buf_t b; |
| 631 | const char *local = tz_local_name(); |
| 632 | yyjson_mut_doc *md; |
| 633 | yyjson_mut_val *arr, *tool, *schema, *props, *req, *item; |
| 634 | |
| 635 | buf_init(&b); |
| 636 | md = yyjson_mut_doc_new(NULL); |
| 637 | if (!md) return NULL; |
| 638 | arr = yyjson_mut_arr(md); |
| 639 | yyjson_mut_doc_set_root(md, arr); |
| 640 | |
| 641 | /* get_current_time */ |
| 642 | tool = yyjson_mut_obj(md); |
| 643 | add_str(md, tool, "name", "get_current_time"); |
| 644 | { |
| 645 | char desc[512]; |
| 646 | snprintf(desc, sizeof desc, |
| 647 | "Get current time in a specific timezone"); |
| 648 | add_str(md, tool, "description", desc); |
| 649 | } |
| 650 | schema = yyjson_mut_obj(md); |
| 651 | add_str(md, schema, "type", "object"); |
| 652 | props = yyjson_mut_obj(md); |
| 653 | item = yyjson_mut_obj(md); |
| 654 | { |
| 655 | char td[512]; |
| 656 | add_str(md, item, "type", "string"); |
| 657 | snprintf(td, sizeof td, "IANA timezone name (e.g., 'America/New_York', " |
| 658 | "'Europe/London'). Optional: defaults to the server's local " |
| 659 | "timezone, '%s', when omitted.", local); |
| 660 | add_str(md, item, "description", td); |
| 661 | add_str(md, item, "default", local); |
| 662 | } |
| 663 | yyjson_mut_obj_add_val(md, props, "timezone", item); |
| 664 | yyjson_mut_obj_add_val(md, schema, "properties", props); |
| 665 | req = yyjson_mut_arr(md); |
| 666 | yyjson_mut_obj_add_val(md, tool, "inputSchema", schema); |
| 667 | yyjson_mut_obj_add_bool(md, tool, "readOnlyHint", true); |
| 668 | yyjson_mut_arr_append(arr, tool); |
| 669 | (void)req; |
| 670 | |
| 671 | /* convert_time */ |
| 672 | tool = yyjson_mut_obj(md); |
| 673 | add_str(md, tool, "name", "convert_time"); |
| 674 | add_str(md, tool, "description", "Convert time between timezones"); |
| 675 | schema = yyjson_mut_obj(md); |
| 676 | add_str(md, schema, "type", "object"); |
| 677 | props = yyjson_mut_obj(md); |
| 678 | { |
| 679 | char td[512]; |
| 680 | item = yyjson_mut_obj(md); |
| 681 | add_str(md, item, "type", "string"); |
| 682 | snprintf(td, sizeof td, "Source IANA timezone name (e.g., " |
| 683 | "'America/New_York', 'Europe/London'). Optional: defaults to " |
| 684 | "the server's local timezone, '%s', when omitted.", local); |
| 685 | add_str(md, item, "description", td); |
| 686 | add_str(md, item, "default", local); |
| 687 | yyjson_mut_obj_add_val(md, props, "source_timezone", item); |
| 688 | |
| 689 | item = yyjson_mut_obj(md); |
| 690 | add_str(md, item, "type", "string"); |
| 691 | add_str(md, item, "description", "Time to convert in 24-hour format (HH:MM)"); |
| 692 | yyjson_mut_obj_add_val(md, props, "time", item); |
| 693 | |
| 694 | item = yyjson_mut_obj(md); |
| 695 | add_str(md, item, "type", "string"); |
| 696 | snprintf(td, sizeof td, "Target IANA timezone name (e.g., 'Asia/Tokyo', " |
| 697 | "'America/Los_Angeles'). Optional: defaults to the server's " |
| 698 | "local timezone, '%s', when omitted.", local); |
| 699 | add_str(md, item, "description", td); |
| 700 | add_str(md, item, "default", local); |
| 701 | yyjson_mut_obj_add_val(md, props, "target_timezone", item); |
| 702 | } |
| 703 | yyjson_mut_obj_add_val(md, schema, "properties", props); |
| 704 | req = yyjson_mut_arr(md); |
| 705 | yyjson_mut_arr_add_str(md, req, "time"); |
| 706 | yyjson_mut_obj_add_val(md, schema, "required", req); |
| 707 | yyjson_mut_obj_add_val(md, tool, "inputSchema", schema); |
| 708 | yyjson_mut_obj_add_bool(md, tool, "readOnlyHint", true); |
| 709 | yyjson_mut_arr_append(arr, tool); |
| 710 | |
| 711 | /* get_time_ago */ |
| 712 | tool = yyjson_mut_obj(md); |
| 713 | add_str(md, tool, "name", "get_time_ago"); |
| 714 | add_str(md, tool, "description", |
| 715 | "Get the time a given number of days, hours, minutes and seconds " |
| 716 | "ago in a specific timezone"); |
| 717 | schema = yyjson_mut_obj(md); |
| 718 | add_str(md, schema, "type", "object"); |
| 719 | props = yyjson_mut_obj(md); |
| 720 | { |
| 721 | char td[512]; |
| 722 | item = yyjson_mut_obj(md); |
| 723 | add_str(md, item, "type", "string"); |
| 724 | snprintf(td, sizeof td, "IANA timezone name (e.g., 'America/New_York', " |
| 725 | "'Europe/London'). Optional: defaults to the server's local " |
| 726 | "timezone, '%s', when omitted.", local); |
| 727 | add_str(md, item, "description", td); |
| 728 | add_str(md, item, "default", local); |
| 729 | yyjson_mut_obj_add_val(md, props, "timezone", item); |
| 730 | |
| 731 | item = yyjson_mut_obj(md); |
| 732 | add_str(md, item, "type", "integer"); |
| 733 | add_str(md, item, "description", "Whole days before now"); |
| 734 | yyjson_mut_obj_add_int(md, item, "minimum", 0); |
| 735 | yyjson_mut_obj_add_val(md, props, "days_ago", item); |
| 736 | |
| 737 | item = yyjson_mut_obj(md); |
| 738 | add_str(md, item, "type", "integer"); |
| 739 | add_str(md, item, "description", "Whole hours before now"); |
| 740 | yyjson_mut_obj_add_int(md, item, "minimum", 0); |
| 741 | yyjson_mut_obj_add_val(md, props, "hours_ago", item); |
| 742 | |
| 743 | item = yyjson_mut_obj(md); |
| 744 | add_str(md, item, "type", "integer"); |
| 745 | add_str(md, item, "description", "Whole minutes before now"); |
| 746 | yyjson_mut_obj_add_int(md, item, "minimum", 0); |
| 747 | yyjson_mut_obj_add_val(md, props, "minutes_ago", item); |
| 748 | |
| 749 | item = yyjson_mut_obj(md); |
| 750 | add_str(md, item, "type", "integer"); |
| 751 | add_str(md, item, "description", "Whole seconds before now"); |
| 752 | yyjson_mut_obj_add_int(md, item, "minimum", 0); |
| 753 | yyjson_mut_obj_add_val(md, props, "seconds_ago", item); |
| 754 | } |
| 755 | yyjson_mut_obj_add_val(md, schema, "properties", props); |
| 756 | yyjson_mut_obj_add_val(md, tool, "inputSchema", schema); |
| 757 | yyjson_mut_obj_add_bool(md, tool, "readOnlyHint", true); |
| 758 | yyjson_mut_arr_append(arr, tool); |
| 759 | |
| 760 | { |
| 761 | char *text = yyjson_mut_write(md, 0, NULL); |
| 762 | yyjson_mut_doc_free(md); |
| 763 | return text; |
| 764 | } |
| 765 | } |
| 766 | |
| 767 | int tool_dispatch(const char *name, yyjson_val *args, tool_out_t *out) |
| 768 | { |
| 769 | if (!name) return -1; |
| 770 | if (strcmp(name, "get_current_time") == 0) { tool_get_current_time(args, out); return 0; } |
| 771 | if (strcmp(name, "convert_time") == 0) { tool_convert_time(args, out); return 0; } |
| 772 | if (strcmp(name, "get_time_ago") == 0) { tool_get_time_ago(args, out); return 0; } |
| 773 | return -1; |
| 774 | } |
| 775 | |
| 776 | char *tool_mcp_result(tool_out_t *t) |
| 777 | { |
| 778 | buf_t b; |
| 779 | |
| 780 | buf_init(&b); |
| 781 | if (t->is_error) { |
| 782 | buf_puts(&b, "{\"content\":[{\"type\":\"text\",\"text\":"); |
| 783 | json_str(&b, t->error ? t->error : "error"); |
| 784 | buf_puts(&b, "}],\"isError\":true}"); |
| 785 | return b.p; |
| 786 | } |
| 787 | { |
| 788 | char *payload = t->md ? yyjson_mut_write(t->md, 0, NULL) : NULL; |
| 789 | buf_puts(&b, "{\"content\":[{\"type\":\"text\",\"text\":"); |
| 790 | json_str(&b, payload ? payload : "{}"); |
| 791 | buf_puts(&b, "}],\"isError\":false"); |
| 792 | if (payload) { |
| 793 | buf_puts(&b, ",\"structuredContent\":"); |
| 794 | buf_puts(&b, payload); |
| 795 | } |
| 796 | buf_puts(&b, "}"); |
| 797 | free(payload); |
| 798 | } |
| 799 | return b.p; |
| 800 | } |
| 801 | |
| 802 | char *tool_api_result(tool_out_t *t) |
| 803 | { |
| 804 | buf_t b; |
| 805 | |
| 806 | buf_init(&b); |
| 807 | if (t->is_error) { |
| 808 | buf_puts(&b, "{\"ok\":false,\"error\":"); |
| 809 | json_str(&b, t->error ? t->error : "error"); |
| 810 | buf_puts(&b, "}"); |
| 811 | return b.p; |
| 812 | } |
| 813 | { |
| 814 | char *payload = t->md ? yyjson_mut_write(t->md, 0, NULL) : NULL; |
| 815 | buf_puts(&b, "{\"ok\":true"); |
| 816 | if (payload && payload[0] == '{' && payload[1] != '}') { |
| 817 | buf_putc(&b, ','); |
| 818 | buf_puts(&b, payload + 1); |
| 819 | } else { |
| 820 | buf_putc(&b, '}'); |
| 821 | } |
| 822 | free(payload); |
| 823 | } |
| 824 | return b.p; |
| 825 | } |