/* * timeutil.c - the tools of plugin_time and the formatting they share. * * Three tools, matching the reference `mcp_server_time` server: * * get_current_time -> {timezone, datetime, day_of_week, is_dst} * convert_time -> {source, target, time_difference, later_occurrence} * get_time_ago -> {timezone, datetime, day_of_week, is_dst} * * The reference server's semantics are reproduced, not approximated: * * - an omitted timezone defaults to the node's own zone, and the tool * descriptions name it so a model can default to it; * - an unknown key is a tool error whose text starts "Invalid timezone:"; * - `time` is HH:MM in 24-hour form, and anything else is * "Invalid time format. Expected HH:MM [24-hour format]"; * - a wall time skipped by a forward clock change is an error naming the * date, not a silently shifted answer; * - a wall time repeated by a backward clock change answers the FIRST * occurrence in source/target and reports the second under * `later_occurrence`, which is the behaviour of Python's fold=0/fold=1; * - `time_difference` is "+3.0h", and a fractional zone like Nepal's +05:45 * prints "+5.75h" (two decimals, trailing zeros stripped). * * Nothing in here reads the clock directly: now_utc() honours SX_TIME_NOW * (an ISO-8601 UTC instant) so the suite can pin a date and prove a DST edge * with the same answer on every platform. * * MIT License. Copyright (c) 2026 SCORPIOX INC. */ #if defined(_WIN32) && !defined(_WIN32_WINNT) # define _WIN32_WINNT 0x0601 #endif #if !defined(_WIN32) # define _POSIX_C_SOURCE 200809L # define _DEFAULT_SOURCE 1 #endif #include #include #include #include #include #include #include "plugintime.h" #include "tz.h" const char *const TOOL_NAMES[] = { "get_current_time", "convert_time", "get_time_ago" }; const int TOOL_COUNT = (int)(sizeof TOOL_NAMES / sizeof TOOL_NAMES[0]); /* ------------------------------------------------------------------ */ /* Growable buffer */ /* ------------------------------------------------------------------ */ void buf_init(buf_t *b) { b->p = NULL; b->n = 0; b->cap = 0; } int buf_need(buf_t *b, size_t extra) { size_t want = b->n + extra + 1; char *np; size_t cap; if (want <= b->cap) return 0; cap = b->cap ? b->cap : 256; while (cap < want) { if (cap > (size_t)-1 / 2) return -1; cap *= 2; } np = (char *)realloc(b->p, cap); if (!np) return -1; b->p = np; b->cap = cap; return 0; } void buf_add(buf_t *b, const char *s, size_t n) { if (buf_need(b, n) != 0) return; if (n) memcpy(b->p + b->n, s, n); b->n += n; b->p[b->n] = '\0'; } void buf_puts(buf_t *b, const char *s) { if (s) buf_add(b, s, strlen(s)); } void buf_putc(buf_t *b, int c) { char ch = (char)c; buf_add(b, &ch, 1); } void buf_printf(buf_t *b, const char *fmt, ...) { va_list ap; int need; char tmp[512]; va_start(ap, fmt); need = vsnprintf(tmp, sizeof tmp, fmt, ap); va_end(ap); if (need < 0) return; if ((size_t)need < sizeof tmp) { buf_add(b, tmp, (size_t)need); return; } if (buf_need(b, (size_t)need) != 0) return; va_start(ap, fmt); vsnprintf(b->p + b->n, (size_t)need + 1, fmt, ap); va_end(ap); b->n += (size_t)need; } const char *buf_str(const buf_t *b) { return b->p ? b->p : ""; } void buf_free(buf_t *b) { free(b->p); buf_init(b); } void json_str(buf_t *b, const char *s) { buf_putc(b, '"'); if (s) { for (; *s; s++) { unsigned char c = (unsigned char)*s; switch (c) { case '"': buf_puts(b, "\\\""); break; case '\\': buf_puts(b, "\\\\"); break; case '\n': buf_puts(b, "\\n"); break; case '\r': buf_puts(b, "\\r"); break; case '\t': buf_puts(b, "\\t"); break; default: if (c < 0x20) buf_printf(b, "\\u%04x", c); else buf_putc(b, (char)c); } } } buf_putc(b, '"'); } /* ------------------------------------------------------------------ */ /* Formatting */ /* ------------------------------------------------------------------ */ void time_split(int64_t utc, int offset, int *year, int *month, int *day, int *hour, int *min, int *sec, int *weekday) { int64_t local = utc + offset; int64_t days = local / 86400; int64_t rem = local % 86400; int y, m, d; /* Floor division: a negative instant must round toward the past, not * toward zero, or a timestamp before 1970 gets the wrong date. */ if (rem < 0) { rem += 86400; days -= 1; } tz_civil_from_days(days, &y, &m, &d); if (year) *year = y; if (month) *month = m; if (day) *day = d; if (hour) *hour = (int)(rem / 3600); if (min) *min = (int)((rem % 3600) / 60); if (sec) *sec = (int)(rem % 60); if (weekday) *weekday = tz_weekday(days); } void time_offset_str(int offset, char *out, size_t outsz) { int a = offset < 0 ? -offset : offset; char sign = offset < 0 ? '-' : '+'; snprintf(out, outsz, "%c%02d:%02d", sign, a / 3600, (a % 3600) / 60); } void time_iso(int64_t utc, int offset, char *out, size_t outsz) { int y, m, d, hh, mm, ss; char off[16]; time_split(utc, offset, &y, &m, &d, &hh, &mm, &ss, NULL); time_offset_str(offset, off, sizeof off); snprintf(out, outsz, "%04d-%02d-%02dT%02d:%02d:%02d%s", y, m, d, hh, mm, ss, off); } static const char *const WEEKDAYS[7] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; const char *time_weekday_name(int weekday) { if (weekday < 0 || weekday > 6) return WEEKDAYS[0]; return WEEKDAYS[weekday]; } void time_diff_str(int source_off, int target_off, char *out, size_t outsz) { int diff = target_off - source_off; double hours = (double)diff / 3600.0; char tmp[32]; /* The reference prints one decimal when the difference is a whole number * of hours, otherwise two decimals with trailing zeros stripped. */ if (diff % 3600 == 0) { snprintf(out, outsz, "%+.1fh", hours); return; } snprintf(tmp, sizeof tmp, "%+.2f", hours); { size_t n = strlen(tmp); while (n > 0 && tmp[n - 1] == '0') tmp[--n] = '\0'; if (n > 0 && tmp[n - 1] == '.') tmp[--n] = '\0'; } snprintf(out, outsz, "%sh", tmp); } /* ------------------------------------------------------------------ */ /* "now" */ /* ------------------------------------------------------------------ */ static int parse_iso_utc(const char *s, int64_t *out) { int y = 0, mo = 0, d = 0, hh = 0, mm = 0, ss = 0; int n = 0; if (!s || !*s) return -1; if (sscanf(s, "%4d-%2d-%2dT%2d:%2d:%2d%n", &y, &mo, &d, &hh, &mm, &ss, &n) < 6) return -1; if (s[n] && s[n] != 'Z' && s[n] != 'z' && s[n] != '+' && s[n] != '-') return -1; if (mo < 1 || mo > 12 || d < 1 || d > 31) return -1; if (hh < 0 || hh > 23 || mm < 0 || mm > 59 || ss < 0 || ss > 60) return -1; *out = tz_days_from_civil(y, mo, d) * 86400 + hh * 3600 + mm * 60 + ss; return 0; } /* The current UTC instant. SX_TIME_NOW ("2026-03-29T01:30:00Z") pins it so a * test can assert a DST edge without waiting for one; an unparseable value is * ignored rather than fatal, because a broken env var must not take the * connector down. */ int64_t time_now_utc(void) { const char *env = getenv("SX_TIME_NOW"); int64_t pinned; if (env && *env && parse_iso_utc(env, &pinned) == 0) return pinned; return (int64_t)time(NULL); } /* ------------------------------------------------------------------ */ /* Result plumbing */ /* ------------------------------------------------------------------ */ void tool_out_init(tool_out_t *t) { memset(t, 0, sizeof *t); } void tool_err(tool_out_t *t, const char *fmt, ...) { char tmp[768]; va_list ap; va_start(ap, fmt); vsnprintf(tmp, sizeof tmp, fmt, ap); va_end(ap); if (!t->error) { size_t n = strlen(tmp); t->error = (char *)malloc(n + 1); if (t->error) memcpy(t->error, tmp, n + 1); } t->is_error = 1; } void tool_free(tool_out_t *t) { if (!t) return; if (t->md) yyjson_mut_doc_free(t->md); free(t->error); memset(t, 0, sizeof *t); } static void tool_start(tool_out_t *t) { if (t->md) return; t->md = yyjson_mut_doc_new(NULL); if (!t->md) { tool_err(t, "out of memory"); return; } t->root = yyjson_mut_obj(t->md); if (!t->root) { yyjson_mut_doc_free(t->md); t->md = NULL; tool_err(t, "out of memory"); return; } yyjson_mut_doc_set_root(t->md, t->root); } /* COPY, not reference: yyjson_mut_obj_add_str stores the caller's pointer, so a * stack buffer (every description and timezone name in this file) is reused and * the document serialises garbage. Silent, valid-looking JSON - pinned by the * "description is not the timezone text" assertion in tests/run.sh. */ static void add_str(yyjson_mut_doc *md, yyjson_mut_val *obj, const char *k, const char *v) { yyjson_mut_obj_add_strcpy(md, obj, k, v ? v : ""); } static void add_bool(yyjson_mut_doc *md, yyjson_mut_val *obj, const char *k, int v) { yyjson_mut_obj_add_bool(md, obj, k, v ? true : false); } /* Fill a TimeResult object. The two single-result tools fill the root object * directly; convert_time nests one per side, so they are the same four fields * everywhere and a caller never has to unwrap a "result" key. */ static void time_result_fill(yyjson_mut_doc *md, yyjson_mut_val *o, const tz_zone *z, int64_t utc, const char *name) { int off, dst = 0; char iso[64], abbr[24]; off = tz_offset(z, utc, &dst, abbr, sizeof abbr); time_iso(utc, off, iso, sizeof iso); add_str(md, o, "timezone", name); add_str(md, o, "datetime", iso); { int wd = 0; time_split(utc, off, NULL, NULL, NULL, NULL, NULL, NULL, &wd); add_str(md, o, "day_of_week", time_weekday_name(wd)); } add_bool(md, o, "is_dst", dst); /* Two fields the reference does not carry: a caller reading the text * block should not have to re-derive the numeric offset or the zone * abbreviation, and neither changes the meaning of the standard four. */ { char offs[16]; time_offset_str(off, offs, sizeof offs); add_str(md, o, "utc_offset", offs); add_str(md, o, "abbreviation", abbr); } } static yyjson_mut_val *time_result_obj(yyjson_mut_doc *md, const tz_zone *z, int64_t utc, const char *name) { yyjson_mut_val *o = yyjson_mut_obj(md); time_result_fill(md, o, z, utc, name); return o; } /* Resolve a timezone argument; fills `name` (the default when absent). */ static const tz_zone *zone_arg(yyjson_val *args, const char *key, char *name, size_t namesz, tool_out_t *t) { yyjson_val *v = args ? yyjson_obj_get(args, key) : NULL; if (v && yyjson_is_str(v)) { const char *s = yyjson_get_str(v); /* A string whose declared length is longer than the C string means an * embedded NUL: refuse it rather than resolving a prefix. */ if (strlen(s) != yyjson_get_len(v)) { tool_err(t, "Invalid timezone: the name contains a NUL byte"); return NULL; } if (!*s) { tool_err(t, "Invalid timezone: the name is empty"); return NULL; } snprintf(name, namesz, "%s", s); } else if (v && !yyjson_is_null(v)) { tool_err(t, "%s must be a string (an IANA timezone name)", key); return NULL; } else { snprintf(name, namesz, "%s", tz_local_name()); } { const tz_zone *z = tz_find(name); if (!z) { tool_err(t, "Invalid timezone: No time zone found with key %s", name); return NULL; } return z; } } static int int_arg(yyjson_val *args, const char *key, int dflt, int lo, int hi, tool_out_t *t) { yyjson_val *v = args ? yyjson_obj_get(args, key) : NULL; long long n; if (!v || yyjson_is_null(v)) return dflt; if (yyjson_is_int(v)) { n = (long long)yyjson_get_sint(v); } else if (yyjson_is_str(v)) { char *end = NULL; n = strtoll(yyjson_get_str(v), &end, 10); if (!end || *end) { tool_err(t, "%s must be an integer (whole number)", key); return dflt; } } else { tool_err(t, "%s must be an integer (whole number)", key); return dflt; } if (n < lo || n > hi) { tool_err(t, "%s must be between %d and %d", key, lo, hi); return dflt; } return (int)n; } /* ------------------------------------------------------------------ */ /* get_current_time */ /* ------------------------------------------------------------------ */ void tool_get_current_time(yyjson_val *args, tool_out_t *t) { char name[TZ_NAME_MAX + 1]; const tz_zone *z; int64_t now = time_now_utc(); tool_out_init(t); z = zone_arg(args, "timezone", name, sizeof name, t); if (!z) return; tool_start(t); if (t->is_error) return; time_result_fill(t->md, t->root, z, now, name); } /* ------------------------------------------------------------------ */ /* get_time_ago */ /* ------------------------------------------------------------------ */ void tool_get_time_ago(yyjson_val *args, tool_out_t *t) { char name[TZ_NAME_MAX + 1]; const tz_zone *z; int d, h, m, s; int64_t span, past; tool_out_init(t); z = zone_arg(args, "timezone", name, sizeof name, t); if (!z) return; d = int_arg(args, "days_ago", 0, 0, 365000, t); if (t->is_error) return; h = int_arg(args, "hours_ago", 0, 0, 100000000, t); if (t->is_error) return; m = int_arg(args, "minutes_ago", 0, 0, 100000000, t); if (t->is_error) return; s = int_arg(args, "seconds_ago", 0, 0, 100000000, t); if (t->is_error) return; /* The span is subtracted from the UTC instant, not the local wall clock: * "5 hours ago" across a clock change is five real hours back. */ span = (int64_t)d * 86400 + (int64_t)h * 3600 + (int64_t)m * 60 + (int64_t)s; past = time_now_utc() - span; tool_start(t); if (t->is_error) return; time_result_fill(t->md, t->root, z, past, name); } /* ------------------------------------------------------------------ */ /* convert_time */ /* ------------------------------------------------------------------ */ /* "HH:MM" -> seconds after midnight. Rejects anything else, including a * trailing colon, a 24th hour or a 60th minute. */ static int parse_hhmm(const char *s, int *out) { /* Exactly HH:MM. sscanf("%2d:%2d") would also accept "9:00" and " 9:00", * and the reference server rejects both, so the shape is checked by hand * before a number is read. */ if (!s || strlen(s) != 5) return -1; if (!isdigit((unsigned char)s[0]) || !isdigit((unsigned char)s[1])) return -1; if (s[2] != ':') return -1; if (!isdigit((unsigned char)s[3]) || !isdigit((unsigned char)s[4])) return -1; { int h = (s[0] - '0') * 10 + (s[1] - '0'); int m = (s[3] - '0') * 10 + (s[4] - '0'); if (h > 23 || m > 59) return -1; *out = h * 3600 + m * 60; } return 0; } void tool_convert_time(yyjson_val *args, tool_out_t *t) { char src_name[TZ_NAME_MAX + 1]; char dst_name[TZ_NAME_MAX + 1]; const tz_zone *zs, *zd; yyjson_val *tv; const char *time_str = NULL; int mins; int64_t now, today, wall; tz_cand_t cand[TZ_MAX_CANDIDATES]; int ncand; int i; int off_s, off_t; char diff[32]; int so, mo, dd; tool_out_init(t); tv = args ? yyjson_obj_get(args, "time") : NULL; if (!tv || !yyjson_is_str(tv)) { tool_err(t, "Missing required argument: time"); return; } time_str = yyjson_get_str(tv); if (strlen(time_str) != yyjson_get_len(tv)) { tool_err(t, "Invalid time format. Expected HH:MM [24-hour format]"); return; } if (parse_hhmm(time_str, &mins) != 0) { tool_err(t, "Invalid time format. Expected HH:MM [24-hour format]"); return; } zs = zone_arg(args, "source_timezone", src_name, sizeof src_name, t); if (!zs) return; zd = zone_arg(args, "target_timezone", dst_name, sizeof dst_name, t); if (!zd) return; /* "Today" in the source zone, at the requested wall time. */ now = time_now_utc(); off_s = tz_offset(zs, now, NULL, NULL, 0); time_split(now, off_s, NULL, NULL, NULL, NULL, NULL, NULL, NULL); { int y, m, d; time_split(now, off_s, &y, &m, &d, NULL, NULL, NULL, NULL); today = tz_days_from_civil(y, m, d); so = y; mo = m; dd = d; } wall = today * 86400 + mins; ncand = tz_resolve_wall(zs, wall, cand, TZ_MAX_CANDIDATES); if (ncand == 0) { char date[32]; time_split(wall, 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL); snprintf(date, sizeof date, "%04d-%02d-%02d", so, mo, dd); tool_err(t, "Invalid time: %s does not exist in %s on %s " "(skipped by a clock change)", time_str, src_name, date); return; } tool_start(t); if (t->is_error) return; { yyjson_mut_val *src_obj = time_result_obj(t->md, zs, cand[0].utc, src_name); yyjson_mut_val *dst_obj = time_result_obj(t->md, zd, cand[0].utc, dst_name); off_s = tz_offset(zs, cand[0].utc, NULL, NULL, 0); off_t = tz_offset(zd, cand[0].utc, NULL, NULL, 0); time_diff_str(off_s, off_t, diff, sizeof diff); yyjson_mut_obj_add_val(t->md, t->root, "source", src_obj); yyjson_mut_obj_add_val(t->md, t->root, "target", dst_obj); add_str(t->md, t->root, "time_difference", diff); /* A repeated hour has two instants. The reference reports both rather * than presenting the first as the only answer. */ if (ncand > 1) { yyjson_mut_val *later = yyjson_mut_obj(t->md); yyjson_mut_val *lsrc, *ldst; char note[512]; char src_iso[64], later_iso[64]; char d2[32]; int o_s; o_s = tz_offset(zs, cand[0].utc, NULL, NULL, 0); time_iso(cand[0].utc, o_s, src_iso, sizeof src_iso); o_s = tz_offset(zs, cand[1].utc, NULL, NULL, 0); time_iso(cand[1].utc, o_s, later_iso, sizeof later_iso); snprintf(note, sizeof note, "%s occurs twice in %s on %04d-%02d-%02d because a clock " "change repeats it: first at %s, then at %s. source and " "target are the first occurrence; this is the second.", time_str, src_name, so, mo, dd, src_iso, later_iso); add_str(t->md, later, "note", note); lsrc = time_result_obj(t->md, zs, cand[1].utc, src_name); ldst = time_result_obj(t->md, zd, cand[1].utc, dst_name); off_s = tz_offset(zs, cand[1].utc, NULL, NULL, 0); off_t = tz_offset(zd, cand[1].utc, NULL, NULL, 0); time_diff_str(off_s, off_t, d2, sizeof d2); yyjson_mut_obj_add_val(t->md, later, "source", lsrc); yyjson_mut_obj_add_val(t->md, later, "target", ldst); add_str(t->md, later, "time_difference", d2); yyjson_mut_obj_add_val(t->md, t->root, "later_occurrence", later); } else { yyjson_mut_obj_add_null(t->md, t->root, "later_occurrence"); } } (void)i; (void)off_s; (void)off_t; } /* ------------------------------------------------------------------ */ /* Schemas and dispatch */ /* ------------------------------------------------------------------ */ char *tools_list_json(void) { buf_t b; const char *local = tz_local_name(); yyjson_mut_doc *md; yyjson_mut_val *arr, *tool, *schema, *props, *req, *item; buf_init(&b); md = yyjson_mut_doc_new(NULL); if (!md) return NULL; arr = yyjson_mut_arr(md); yyjson_mut_doc_set_root(md, arr); /* get_current_time */ tool = yyjson_mut_obj(md); add_str(md, tool, "name", "get_current_time"); { char desc[512]; snprintf(desc, sizeof desc, "Get current time in a specific timezone"); add_str(md, tool, "description", desc); } schema = yyjson_mut_obj(md); add_str(md, schema, "type", "object"); props = yyjson_mut_obj(md); item = yyjson_mut_obj(md); { char td[512]; add_str(md, item, "type", "string"); snprintf(td, sizeof td, "IANA timezone name (e.g., 'America/New_York', " "'Europe/London'). Optional: defaults to the server's local " "timezone, '%s', when omitted.", local); add_str(md, item, "description", td); add_str(md, item, "default", local); } yyjson_mut_obj_add_val(md, props, "timezone", item); yyjson_mut_obj_add_val(md, schema, "properties", props); req = yyjson_mut_arr(md); yyjson_mut_obj_add_val(md, tool, "inputSchema", schema); yyjson_mut_obj_add_bool(md, tool, "readOnlyHint", true); yyjson_mut_arr_append(arr, tool); (void)req; /* convert_time */ tool = yyjson_mut_obj(md); add_str(md, tool, "name", "convert_time"); add_str(md, tool, "description", "Convert time between timezones"); schema = yyjson_mut_obj(md); add_str(md, schema, "type", "object"); props = yyjson_mut_obj(md); { char td[512]; item = yyjson_mut_obj(md); add_str(md, item, "type", "string"); snprintf(td, sizeof td, "Source IANA timezone name (e.g., " "'America/New_York', 'Europe/London'). Optional: defaults to " "the server's local timezone, '%s', when omitted.", local); add_str(md, item, "description", td); add_str(md, item, "default", local); yyjson_mut_obj_add_val(md, props, "source_timezone", item); item = yyjson_mut_obj(md); add_str(md, item, "type", "string"); add_str(md, item, "description", "Time to convert in 24-hour format (HH:MM)"); yyjson_mut_obj_add_val(md, props, "time", item); item = yyjson_mut_obj(md); add_str(md, item, "type", "string"); snprintf(td, sizeof td, "Target IANA timezone name (e.g., 'Asia/Tokyo', " "'America/Los_Angeles'). Optional: defaults to the server's " "local timezone, '%s', when omitted.", local); add_str(md, item, "description", td); add_str(md, item, "default", local); yyjson_mut_obj_add_val(md, props, "target_timezone", item); } yyjson_mut_obj_add_val(md, schema, "properties", props); req = yyjson_mut_arr(md); yyjson_mut_arr_add_str(md, req, "time"); yyjson_mut_obj_add_val(md, schema, "required", req); yyjson_mut_obj_add_val(md, tool, "inputSchema", schema); yyjson_mut_obj_add_bool(md, tool, "readOnlyHint", true); yyjson_mut_arr_append(arr, tool); /* get_time_ago */ tool = yyjson_mut_obj(md); add_str(md, tool, "name", "get_time_ago"); add_str(md, tool, "description", "Get the time a given number of days, hours, minutes and seconds " "ago in a specific timezone"); schema = yyjson_mut_obj(md); add_str(md, schema, "type", "object"); props = yyjson_mut_obj(md); { char td[512]; item = yyjson_mut_obj(md); add_str(md, item, "type", "string"); snprintf(td, sizeof td, "IANA timezone name (e.g., 'America/New_York', " "'Europe/London'). Optional: defaults to the server's local " "timezone, '%s', when omitted.", local); add_str(md, item, "description", td); add_str(md, item, "default", local); yyjson_mut_obj_add_val(md, props, "timezone", item); item = yyjson_mut_obj(md); add_str(md, item, "type", "integer"); add_str(md, item, "description", "Whole days before now"); yyjson_mut_obj_add_int(md, item, "minimum", 0); yyjson_mut_obj_add_val(md, props, "days_ago", item); item = yyjson_mut_obj(md); add_str(md, item, "type", "integer"); add_str(md, item, "description", "Whole hours before now"); yyjson_mut_obj_add_int(md, item, "minimum", 0); yyjson_mut_obj_add_val(md, props, "hours_ago", item); item = yyjson_mut_obj(md); add_str(md, item, "type", "integer"); add_str(md, item, "description", "Whole minutes before now"); yyjson_mut_obj_add_int(md, item, "minimum", 0); yyjson_mut_obj_add_val(md, props, "minutes_ago", item); item = yyjson_mut_obj(md); add_str(md, item, "type", "integer"); add_str(md, item, "description", "Whole seconds before now"); yyjson_mut_obj_add_int(md, item, "minimum", 0); yyjson_mut_obj_add_val(md, props, "seconds_ago", item); } yyjson_mut_obj_add_val(md, schema, "properties", props); yyjson_mut_obj_add_val(md, tool, "inputSchema", schema); yyjson_mut_obj_add_bool(md, tool, "readOnlyHint", true); yyjson_mut_arr_append(arr, tool); { char *text = yyjson_mut_write(md, 0, NULL); yyjson_mut_doc_free(md); return text; } } int tool_dispatch(const char *name, yyjson_val *args, tool_out_t *out) { if (!name) return -1; if (strcmp(name, "get_current_time") == 0) { tool_get_current_time(args, out); return 0; } if (strcmp(name, "convert_time") == 0) { tool_convert_time(args, out); return 0; } if (strcmp(name, "get_time_ago") == 0) { tool_get_time_ago(args, out); return 0; } return -1; } char *tool_mcp_result(tool_out_t *t) { buf_t b; buf_init(&b); if (t->is_error) { buf_puts(&b, "{\"content\":[{\"type\":\"text\",\"text\":"); json_str(&b, t->error ? t->error : "error"); buf_puts(&b, "}],\"isError\":true}"); return b.p; } { char *payload = t->md ? yyjson_mut_write(t->md, 0, NULL) : NULL; buf_puts(&b, "{\"content\":[{\"type\":\"text\",\"text\":"); json_str(&b, payload ? payload : "{}"); buf_puts(&b, "}],\"isError\":false"); if (payload) { buf_puts(&b, ",\"structuredContent\":"); buf_puts(&b, payload); } buf_puts(&b, "}"); free(payload); } return b.p; } char *tool_api_result(tool_out_t *t) { buf_t b; buf_init(&b); if (t->is_error) { buf_puts(&b, "{\"ok\":false,\"error\":"); json_str(&b, t->error ? t->error : "error"); buf_puts(&b, "}"); return b.p; } { char *payload = t->md ? yyjson_mut_write(t->md, 0, NULL) : NULL; buf_puts(&b, "{\"ok\":true"); if (payload && payload[0] == '{' && payload[1] != '}') { buf_putc(&b, ','); buf_puts(&b, payload + 1); } else { buf_putc(&b, '}'); } free(payload); } return b.p; }