/* * plugin_time.c - entry point and HTTP front end for the SCORPIOX BOT world * time connector. * * One binary, five modes, exactly as the plugin_ spec requires: * * 1. --meta / SX_PLUGIN_META=1 -> one line of discovery JSON, exit 0. * Unauthenticated on purpose: /plugins probes it, and the * sx-connector-mcp router probes it before it will run anything else. * 2. --mcp -> MCP JSON-RPC 2.0 over stdio, one request * per line, one response per line. Through the single sx-connector-mcp * router this is what makes the plugin a tool provider for SCORPIOX CODE * with no clang change and no extra MCP server slot. * 3. --schema -> the tools/list array, for a human. * 4. ?action=... | ?format=json | POST -> the JSON API the page talks to. * Same three tools as --mcp, so the page can never drift from the agent. * 5. GET (default) -> the World Clock & Timezone Converter page. * * Modes 4 and 5 sit behind require_node_auth(): a node's :8150 is reachable * from the LAN. --meta and --mcp stay open so discovery and the router work; * neither answers a web request. * * 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 # if defined(__APPLE__) # define _DARWIN_C_SOURCE 1 # endif #endif #include #include #include #include #if defined(_WIN32) # define WIN32_LEAN_AND_MEAN # include # include # include /* MinGW's CRT starts stdout in TEXT mode and rewrites every \n into \r\n. A * CGI header block must end with exactly CRLF CRLF; text mode turns that into * \r\r\n\r\r\n, scorpiox-server never finds the separator, and the whole reply * (headers included) is served as a body. Force binary stdio before main(). */ __attribute__((constructor)) static void sx_plugin_binary_stdio(void) { _setmode(_fileno(stdout), _O_BINARY); _setmode(_fileno(stdin), _O_BINARY); } #else # include #endif #include "plugintime.h" #include "tz.h" #include "bot_theme_plugin.h" #include "ui_html.h" /* ------------------------------------------------------------------ */ /* --meta */ /* ------------------------------------------------------------------ */ static int mode_meta(void) { printf("{\"name\":\"%s\",\"desc\":\"%s\",\"kind\":\"mcp\",\"mcp\":true," "\"daemon\":false,\"menus\":false,\"verified\":\"live\"," "\"category\":\"utilities\",\"version\":\"%s\"}\n", PLUGIN_NAME, PLUGIN_DESC, PLUGIN_VER); fflush(stdout); return 0; } /* ------------------------------------------------------------------ */ /* MCP over stdio */ /* ------------------------------------------------------------------ */ static void send_raw(const char *json) { fputs(json, stdout); fputc('\n', stdout); fflush(stdout); } static void send_result_raw(const char *id_json, const char *result_json) { buf_t b; buf_init(&b); buf_puts(&b, "{\"jsonrpc\":\"2.0\",\"id\":"); buf_puts(&b, id_json ? id_json : "null"); buf_puts(&b, ",\"result\":"); buf_puts(&b, result_json ? result_json : "{}"); buf_puts(&b, "}"); send_raw(buf_str(&b)); buf_free(&b); } static void send_result(yyjson_val *id, const char *result_json) { char *js = id ? yyjson_val_write(id, 0, NULL) : NULL; send_result_raw(js ? js : "null", result_json); free(js); } static void send_error(yyjson_val *id, int code, const char *msg) { buf_t b; char *js = id ? yyjson_val_write(id, 0, NULL) : NULL; buf_init(&b); buf_puts(&b, "{\"jsonrpc\":\"2.0\",\"id\":"); /* A parse error has no id to echo; the spec says answer with null, and a * silent drop makes a broken client look like a hung server. */ buf_puts(&b, js ? js : "null"); buf_printf(&b, ",\"error\":{\"code\":%d,\"message\":", code); json_str(&b, msg); buf_puts(&b, "}}"); send_raw(buf_str(&b)); buf_free(&b); free(js); } static void handle_request(yyjson_val *root, yyjson_val *id, const char *method) { if (strcmp(method, "initialize") == 0) { buf_t b; char *local = NULL; buf_init(&b); buf_puts(&b, "{\"protocolVersion\":\"" MCP_PROTOCOL "\"," "\"capabilities\":{\"tools\":{\"listChanged\":false}}," "\"serverInfo\":{\"name\":\"" SERVER_NAME "\",\"version\":\""); buf_puts(&b, PLUGIN_VER); buf_puts(&b, "\"},\"instructions\":"); { buf_t d; buf_init(&d); buf_puts(&d, "IANA timezone queries and wall-clock conversion for " "three tools: get_current_time, convert_time and " "get_time_ago. Times are resolved from an embedded tz " "database, so every platform answers identically. The " "server's local timezone is "); buf_puts(&d, tz_local_name()); buf_puts(&d, "."); json_str(&b, buf_str(&d)); buf_free(&d); } buf_puts(&b, "}"); send_result(id, buf_str(&b)); buf_free(&b); free(local); return; } if (strcmp(method, "ping") == 0) { send_result(id, "{}"); return; } if (strcmp(method, "tools/list") == 0) { char *tools = tools_list_json(); buf_t b; buf_init(&b); buf_puts(&b, "{\"tools\":"); buf_puts(&b, tools ? tools : "[]"); buf_puts(&b, "}"); send_result(id, buf_str(&b)); buf_free(&b); free(tools); return; } if (strcmp(method, "tools/call") == 0) { yyjson_val *params = yyjson_obj_get(root, "params"); const char *name = NULL; yyjson_val *args = NULL; tool_out_t t; char *res; if (params && yyjson_is_obj(params)) { yyjson_val *nv = yyjson_obj_get(params, "name"); if (nv && yyjson_is_str(nv)) name = yyjson_get_str(nv); args = yyjson_obj_get(params, "arguments"); if (args && !yyjson_is_obj(args)) args = NULL; } if (!name) { send_error(id, -32602, "tools/call needs params.name"); return; } if (tool_dispatch(name, args, &t) != 0) { buf_t b; buf_init(&b); buf_puts(&b, "Unknown tool: "); buf_puts(&b, name); send_error(id, -32602, buf_str(&b)); buf_free(&b); tool_free(&t); return; } res = tool_mcp_result(&t); send_result(id, res ? res : "{\"content\":[],\"isError\":true}"); free(res); tool_free(&t); return; } if (strcmp(method, "resources/list") == 0) { send_result(id, "{\"resources\":[]}"); return; } if (strcmp(method, "resources/templates/list") == 0) { send_result(id, "{\"resourceTemplates\":[]}"); return; } if (strcmp(method, "prompts/list") == 0) { send_result(id, "{\"prompts\":[]}"); return; } send_error(id, -32601, "Method not found"); } static int mode_mcp(void) { char *line = (char *)malloc((size_t)STDIN_LINE_MAX); if (!line) return 1; for (;;) { size_t n = 0; int c; /* Read one line by hand: fgets with a fixed buffer would truncate a * long arguments object, and a truncated line parses as valid-but- * wrong JSON instead of failing. */ for (;;) { c = fgetc(stdin); if (c == EOF) break; if (c == '\n') break; if (n + 1 < (size_t)STDIN_LINE_MAX) line[n++] = (char)c; } line[n] = '\0'; if (n == 0) { if (c == EOF) { free(line); return 0; } continue; } { yyjson_doc *doc = yyjson_read(line, n, 0); yyjson_val *root, *mv, *id; const char *method; if (!doc) { send_error(NULL, -32700, "Parse error: not valid JSON"); continue; } root = yyjson_doc_get_root(doc); if (!root || !yyjson_is_obj(root)) { yyjson_doc_free(doc); send_error(NULL, -32600, "Invalid request: expected an object"); continue; } mv = yyjson_obj_get(root, "method"); method = (mv && yyjson_is_str(mv)) ? yyjson_get_str(mv) : NULL; id = yyjson_obj_get(root, "id"); if (!method) { yyjson_doc_free(doc); if (yyjson_obj_get(root, "result") || yyjson_obj_get(root, "error")) continue; send_error(id, -32600, "Invalid request: missing method"); continue; } if (!id) { /* notification: no reply */ yyjson_doc_free(doc); continue; } handle_request(root, id, method); yyjson_doc_free(doc); } } } /* ------------------------------------------------------------------ */ /* Query parameters */ /* ------------------------------------------------------------------ */ static int get_query_val(const char *qs, const char *key, char *out, size_t outsz) { size_t klen; if (!qs || !key || !out || outsz == 0) return 0; out[0] = '\0'; klen = strlen(key); while (*qs) { if (strncmp(qs, key, klen) == 0 && qs[klen] == '=') { size_t i = 0; qs += klen + 1; while (*qs && *qs != '&' && i + 1 < outsz) { /* %XX and + decode: a timezone name never needs it, but an * `America/Argentina/Buenos_Aires` over the wire does not, and * a page passing `time=09:30` from a form does. */ if (*qs == '%' && isxdigit((unsigned char)qs[1]) && isxdigit((unsigned char)qs[2])) { int hi = isdigit((unsigned char)qs[1]) ? qs[1] - '0' : (tolower((unsigned char)qs[1]) - 'a' + 10); int lo = isdigit((unsigned char)qs[2]) ? qs[2] - '0' : (tolower((unsigned char)qs[2]) - 'a' + 10); out[i++] = (char)((hi << 4) | lo); qs += 3; continue; } out[i++] = (*qs == '+') ? ' ' : *qs; qs++; } out[i] = '\0'; return 1; } qs = strchr(qs, '&'); if (!qs) break; qs++; } return 0; } /* ------------------------------------------------------------------ */ /* Node authentication */ /* */ /* The node's :8150 is LAN-reachable, so the page and the JSON API must */ /* not answer a bare curl. Three credential forms because three callers */ /* differ: bot-web proxies with a header, the plugin iframe appends */ /* ?pwd=, and a script may send a bearer token. --meta and --mcp return */ /* above this, so discovery and the router stay open. */ /* ------------------------------------------------------------------ */ static void require_node_auth(void) { const char *np = getenv("BOT_PASSWORD"); const char *xp, *auth, *qs; char qpwd[256]; if (!np || !*np) return; xp = getenv("HTTP_X_BOT_PASSWORD"); if (xp && strcmp(xp, np) == 0) return; auth = getenv("HTTP_AUTHORIZATION"); if (auth) { while (*auth == ' ') auth++; if (strncmp(auth, "Bearer ", 7) == 0) { auth += 7; while (*auth == ' ') auth++; if (strcmp(auth, np) == 0) return; } } qs = getenv("QUERY_STRING"); if (qs && get_query_val(qs, "pwd", qpwd, sizeof qpwd) && strcmp(qpwd, np) == 0) return; fputs("Status: 401 Unauthorized\r\n" "Content-Type: application/json; charset=utf-8\r\n" "Cache-Control: no-store\r\n" "X-Content-Type-Options: nosniff\r\n\r\n" "{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout); exit(0); } /* ------------------------------------------------------------------ */ /* Responses */ /* ------------------------------------------------------------------ */ static void json_header(void) { fputs("Content-Type: application/json; charset=utf-8\r\n" "Cache-Control: no-store\r\n" "X-Content-Type-Options: nosniff\r\n\r\n", stdout); } static void json_raw(const char *json) { json_header(); fputs(json ? json : "{\"ok\":true}", stdout); fputc('\n', stdout); fflush(stdout); } static void json_err(int code, const char *msg) { buf_t b; const char *status = "Status: 500 Internal Server Error\r\n"; if (code == 400) status = "Status: 400 Bad Request\r\n"; else if (code == 404) status = "Status: 404 Not Found\r\n"; else if (code == 413) status = "Status: 413 Payload Too Large\r\n"; buf_init(&b); buf_puts(&b, status); buf_puts(&b, "Content-Type: application/json; charset=utf-8\r\n" "Cache-Control: no-store\r\n" "X-Content-Type-Options: nosniff\r\n\r\n"); buf_puts(&b, "{\"ok\":false,\"error\":"); json_str(&b, msg ? msg : "error"); buf_puts(&b, "}\n"); fputs(buf_str(&b), stdout); fflush(stdout); buf_free(&b); } /* Reads the request body when CONTENT_LENGTH says there is one. Never blocks * on an inherited empty stdin. */ static char g_body[REQ_BODY_MAX]; static yyjson_doc *g_body_doc = NULL; static int read_body(void) { const char *cl = getenv("CONTENT_LENGTH"); long len; size_t got; g_body[0] = '\0'; if (!cl || !*cl) return 0; len = strtol(cl, NULL, 10); if (len <= 0) return 0; if ((size_t)len >= sizeof g_body) return -1; got = fread(g_body, 1, (size_t)len, stdin); g_body[got] = '\0'; return (int)got; } static yyjson_val *body_root(void) { if (!g_body_doc) { if (!g_body[0]) return NULL; g_body_doc = yyjson_read(g_body, strlen(g_body), 0); if (!g_body_doc) return NULL; } return yyjson_doc_get_root(g_body_doc); } static int param_str(const char *qs, const char *key, char *out, size_t outsz) { yyjson_val *root, *v; if (out && outsz) out[0] = '\0'; if (qs && get_query_val(qs, key, out, outsz) && out && out[0]) return 1; root = body_root(); v = root ? yyjson_obj_get(root, key) : NULL; if (v && yyjson_is_str(v)) { snprintf(out, outsz, "%s", yyjson_get_str(v)); return 1; } return 0; } /* ------------------------------------------------------------------ */ /* HTML page */ /* ------------------------------------------------------------------ */ /* Expand the two control-byte placeholders from src/ui.html into the bot * theme macros, so the page and the bot palette can never drift apart. */ static void emit_ui(void) { const char *p = UI_HTML; while (*p) { if (*p == '\001') { fputs(SX_BOT_THEME_PREPAINT "", stdout); p++; } else if (*p == '\002') { fputs(SX_BOT_THEME_HANDOFF, stdout); p++; } else { putchar(*p++); } } } static void mode_html(void) { fputs("Content-Type: text/html; charset=utf-8\r\n" "Cache-Control: no-store\r\n" "X-Content-Type-Options: nosniff\r\n" "X-Frame-Options: SAMEORIGIN\r\n" "Content-Security-Policy: default-src 'none'; script-src 'unsafe-inline'; " "style-src 'unsafe-inline'; img-src 'self' data:; connect-src 'self'; " "form-action 'none'; base-uri 'none'\r\n\r\n", stdout); emit_ui(); } /* ------------------------------------------------------------------ */ /* JSON API */ /* ------------------------------------------------------------------ */ /* Run one tool for an HTTP action. The page sends the same argument names as * the MCP schema, so one dispatch serves both surfaces. */ static void api_run(const char *tool, const char *qs) { yyjson_mut_doc *md = yyjson_mut_doc_new(NULL); yyjson_mut_val *args; yyjson_doc *adoc; yyjson_val *av; tool_out_t t; char *res; const char *keys[] = { "timezone", "time", "source_timezone", "target_timezone", "days_ago", "hours_ago", "minutes_ago", "seconds_ago" }; size_t i; if (!md) { json_err(500, "out of memory"); return; } args = yyjson_mut_obj(md); yyjson_mut_doc_set_root(md, args); for (i = 0; i < sizeof keys / sizeof keys[0]; i++) { yyjson_val *bv; char sval[512]; bv = body_root(); if (bv && yyjson_is_obj(bv)) { yyjson_val *v = yyjson_obj_get(bv, keys[i]); if (v && yyjson_is_str(v)) { yyjson_mut_obj_add_strcpy(md, args, keys[i], yyjson_get_str(v)); continue; } if (v && yyjson_is_int(v)) { yyjson_mut_obj_add_int(md, args, keys[i], (long long)yyjson_get_sint(v)); continue; } } if (qs && get_query_val(qs, keys[i], sval, sizeof sval) && sval[0]) { /* The integer fields are numeric arguments; a query string always * arrives as text, so re-type them here rather than making every * caller remember which surface wants which type. */ if (strstr(keys[i], "_ago")) { char *end = NULL; long long n = strtoll(sval, &end, 10); if (end && *end == '\0') yyjson_mut_obj_add_int(md, args, keys[i], n); else yyjson_mut_obj_add_strcpy(md, args, keys[i], sval); } else { /* strcpy, not str: `sval` is one stack buffer reused for every * key in this loop, so a borrowed pointer leaves every argument * pointing at the last value it held. Silent, and the JSON * still parses. */ yyjson_mut_obj_add_strcpy(md, args, keys[i], sval); } } } /* The tool implementations read an immutable yyjson_val; serialise the * mutable object and parse it back so both surfaces share one argument * shape (and so the HTTP path exercises the same reader as --mcp). */ { char *text = yyjson_mut_write(md, 0, NULL); yyjson_mut_doc_free(md); adoc = text ? yyjson_read(text, strlen(text), 0) : NULL; free(text); } av = adoc ? yyjson_doc_get_root(adoc) : NULL; if (strcmp(tool, "get_current_time") == 0) tool_get_current_time(av, &t); else if (strcmp(tool, "convert_time") == 0) tool_convert_time(av, &t); else if (strcmp(tool, "get_time_ago") == 0) tool_get_time_ago(av, &t); else { if (adoc) yyjson_doc_free(adoc); json_err(400, "unknown tool"); return; } res = tool_api_result(&t); json_raw(res ? res : "{\"ok\":false,\"error\":\"no result\"}"); free(res); tool_free(&t); if (adoc) yyjson_doc_free(adoc); } /* The page's zone picker: every embedded key plus the local one. */ static void api_zones(void) { buf_t b; int i; buf_init(&b); buf_puts(&b, "{\"ok\":true,\"count\":"); buf_printf(&b, "%d", tz_count()); buf_puts(&b, ",\"local\":"); json_str(&b, tz_local_name()); buf_puts(&b, ",\"zones\":["); for (i = 0; i < tz_count(); i++) { if (i) buf_putc(&b, ','); json_str(&b, tz_name_at(i)); } buf_puts(&b, "]}"); json_raw(buf_str(&b)); buf_free(&b); } static int api_handle(void) { const char *qs = getenv("QUERY_STRING"); const char *method = getenv("REQUEST_METHOD"); char action[64]; int is_get; if (!qs) qs = ""; is_get = !method || strcmp(method, "GET") == 0; require_node_auth(); if (!is_get && read_body() < 0) { json_err(413, "request body too large"); return 0; } /* Two separate buffers: parsing `format` into `action` would clobber the * action we just parsed and silently answer the default one. */ action[0] = '\0'; if (!get_query_val(qs, "action", action, sizeof action) || !action[0]) param_str(qs, "action", action, sizeof action); if (!action[0]) { if (strstr(qs, "format=json")) snprintf(action, sizeof action, "current"); else { mode_html(); return 0; } } if (strcmp(action, "current") == 0 || strcmp(action, "now") == 0) api_run("get_current_time", qs); else if (strcmp(action, "convert") == 0) api_run("convert_time", qs); else if (strcmp(action, "ago") == 0) api_run("get_time_ago", qs); else if (strcmp(action, "zones") == 0) api_zones(); else if (strcmp(action, "tools") == 0) { char *t = tools_list_json(); buf_t b; buf_init(&b); buf_puts(&b, "{\"ok\":true,\"tools\":"); buf_puts(&b, t ? t : "[]"); buf_puts(&b, "}"); json_raw(buf_str(&b)); buf_free(&b); free(t); } else if (strcmp(action, "info") == 0) { buf_t b; buf_init(&b); buf_puts(&b, "{\"ok\":true,\"id\":\"" PLUGIN_ID "\",\"version\":\"" PLUGIN_VER "\",\"kind\":\"mcp\",\"mcp\":true,\"zones\":"); buf_printf(&b, "%d", tz_count()); buf_puts(&b, ",\"local\":"); json_str(&b, tz_local_name()); buf_puts(&b, "}"); json_raw(buf_str(&b)); buf_free(&b); } else { json_err(400, "unknown action"); } if (g_body_doc) { yyjson_doc_free(g_body_doc); g_body_doc = NULL; } return 0; } /* ------------------------------------------------------------------ */ /* main */ /* ------------------------------------------------------------------ */ static void print_help(void) { int i; printf("%s %s - SCORPIOX BOT world time MCP connector\n\n" "modes:\n" " --meta print plugin discovery metadata and exit\n" " --mcp serve MCP JSON-RPC 2.0 over stdin/stdout\n" " --schema print the tools/list array\n" " --win-tz resolve a Windows timezone id to its IANA key\n" " --version print version\n" " (no args) CGI: World Clock page + ?action= API\n\n" "tools: ", PLUGIN_ID, PLUGIN_VER); for (i = 0; i < TOOL_COUNT; i++) printf("%s%s", i ? ", " : "", TOOL_NAMES[i]); printf("\nzones: %d embedded IANA zones; local is %s\n", tz_count(), tz_local_name()); } int main(int argc, char **argv) { int i; for (i = 1; i < argc; i++) { if (strcmp(argv[i], "--meta") == 0) return mode_meta(); if (strcmp(argv[i], "--mcp") == 0) return mode_mcp(); if (strcmp(argv[i], "--version") == 0) { printf("%s %s\n", PLUGIN_ID, PLUGIN_VER); return 0; } if (strcmp(argv[i], "--schema") == 0) { char *t = tools_list_json(); printf("%s\n", t ? t : "[]"); free(t); return 0; } if (strcmp(argv[i], "--win-tz") == 0) { /* Diagnostic: what does a Windows node's registry name resolve to? * The mapping is embedded on every platform, so this answers for a * Windows box from a Linux one. */ const tz_zone *z = (i + 1 < argc) ? tz_find_windows(argv[i + 1]) : NULL; if (!z) { fprintf(stderr, "%s: unknown Windows timezone id%s%s\n", PLUGIN_ID, (i + 1 < argc) ? ": " : "", (i + 1 < argc) ? argv[i + 1] : ""); return 1; } printf("%s\n", tz_zone_name(z)); return 0; } if (strcmp(argv[i], "--help") == 0) { print_help(); return 0; } } if (getenv("SX_PLUGIN_META")) return mode_meta(); if (getenv("SX_PLUGIN_MCP")) return mode_mcp(); return api_handle(); }