/* * plugin_webhook - SCORPIOX BOT open-source named webhook & REST trigger * MCP connector. * * One clean-room C99 binary carrying the five contracts a SCORPIOX BOT * connector plugin implements: * * --meta / SX_PLUGIN_META=1 one line of JSON discovery metadata * --mcp MCP JSON-RPC 2.0 over stdio * --schema the tool list (compatibility) * GET the bot-themed setup / test page * ?action=… (+ POST body) the node-auth-gated JSON control API * * The idea, clean-room from Hermes Agent's `gateway/platforms/webhook*.py` * and OpenClaw's `extensions/admin-http-rpc`: * * A user defines NAMED endpoints - Slack, Discord, Zapier, n8n, IFTTT, a * home-grown REST trigger - each with its own method, headers (an * Authorization token, an API key) and optional HMAC-SHA256 signature. * The agent then fires them by NAME with a JSON payload. The secret lives * in one 0600 file on the node and is never in the prompt, never in a tool * result, and never in an HTTP response: both the MCP surface and the page * see `has_secret: true` and nothing else. * * Why two tools instead of one tool per endpoint: a connector that publishes * every user-defined hook as its own MCP tool floods the agent's context with * names it will never call. webhook_list is the routing table; webhook_trigger * is the single verb. That also means adding a hook needs no restart. * * MIT License. Copyright (c) 2026 SCORPIOX INC. */ /* Before every include: MinGW defaults _WIN32_WINNT to 0x502 (hides * InetPton and friends); Apple needs _DARWIN_C_SOURCE under strict c99; * MinGW needs its own printf for %zu. */ #if defined(_WIN32) && !defined(_WIN32_WINNT) # define _WIN32_WINNT 0x0601 #endif #if defined(__APPLE__) && !defined(_DARWIN_C_SOURCE) # define _DARWIN_C_SOURCE 1 #endif #if defined(__MINGW32__) && !defined(__USE_MINGW_ANSI_STDIO) # define __USE_MINGW_ANSI_STDIO 1 #endif #ifndef _POSIX_C_SOURCE # define _POSIX_C_SOURCE 200809L #endif #include #include #include #include #include #if defined(_WIN32) # include # include # include #else # include # include # include # include #endif #include "bot_theme_plugin.h" #include "sha256.h" #include "ui_html.h" #include "wh_buf.h" #include "wh_http.h" #include "wh_store.h" #include "yyjson.h" #define PLUGIN_SLUG "webhook" #define PLUGIN_ID "plugin_webhook" #define PLUGIN_NAME "webhook" #define PLUGIN_DESC "HTTP triggers" #define PLUGIN_VER "1.0.3" #define PLUGIN_KIND "mcp" /* ===================================================================== * 1. Small shared helpers * ===================================================================== */ static void copy_trunc(char *dst, size_t capsz, const char *src) { size_t n; if (!capsz) return; if (!src) { dst[0] = '\0'; return; } n = strlen(src); if (n >= capsz) n = capsz - 1; memcpy(dst, src, n); dst[n] = '\0'; } static int ieq(const char *a, const char *b) { if (!a || !b) return 0; while (*a && *b) { if (tolower((unsigned char)*a) != tolower((unsigned char)*b)) return 0; a++; b++; } return *a == 0 && *b == 0; } static void iso_now(char *out, size_t outsz) { time_t now = time(NULL); struct tm tmv; #if defined(_WIN32) gmtime_s(&tmv, &now); #else gmtime_r(&now, &tmv); #endif strftime(out, outsz, "%Y-%m-%dT%H:%M:%SZ", &tmv); } /* Percent-decode in place (also turns '+' into a space). */ static void url_decode(char *s) { char *w = s; char *r = s; while (*r) { if (*r == '%' && isxdigit((unsigned char)r[1]) && isxdigit((unsigned char)r[2])) { int hi = isdigit((unsigned char)r[1]) ? r[1] - '0' : (tolower((unsigned char)r[1]) - 'a' + 10); int lo = isdigit((unsigned char)r[2]) ? r[2] - '0' : (tolower((unsigned char)r[2]) - 'a' + 10); *w++ = (char)((hi << 4) | lo); r += 3; } else if (*r == '+') { *w++ = ' '; r++; } else { *w++ = *r++; } } *w = '\0'; } /* Parse one QUERY_STRING value. Returns 1 when found. */ static int get_query_val(const char *qs, const char *key, char *out, size_t outsz) { size_t klen; const char *p; if (!qs || !key || !out || outsz == 0) return 0; out[0] = '\0'; klen = strlen(key); p = qs; while (*p) { if (strncmp(p, key, klen) == 0 && p[klen] == '=') { size_t i = 0; p += klen + 1; while (*p && *p != '&' && i + 1 < outsz) out[i++] = *p++; out[i] = '\0'; url_decode(out); return 1; } { const char *next = strchr(p, '&'); if (!next) break; p = next + 1; } } return 0; } static void cgi_header(long status, const char *ctype) { if (status != 200) printf("Status: %ld\r\n", status); printf("Content-Type: %s\r\n" "Cache-Control: no-store\r\n" "X-Content-Type-Options: nosniff\r\n" "Referrer-Policy: no-referrer\r\n" "Content-Security-Policy: default-src 'self' 'unsafe-inline'; " "img-src 'self' data:; connect-src 'self'\r\n\r\n", ctype); } /* ===================================================================== * 2. Node authentication * * Every route that reveals node state - the page included, because it lists * the URLs of the operator's endpoints - is gated. --meta, --mcp and --schema * return before this is called, so discovery and the tool surface keep * working on a locked node. * ===================================================================== */ static void require_node_auth(void) { const char *np = getenv("BOT_PASSWORD"); const char *xp, *auth, *qs; char qpwd[256]; if (!np || !*np) return; /* node explicitly open */ 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) { const char *t = auth + 7; while (*t == ' ') t++; if (strcmp(t, np) == 0) return; } } qs = getenv("QUERY_STRING"); if (qs && get_query_val(qs, "pwd", qpwd, sizeof qpwd) && strcmp(qpwd, np) == 0) return; cgi_header(401, "application/json; charset=utf-8"); fputs("{\"ok\":false,\"error\":\"invalid node password\"}\n", stdout); fflush(stdout); exit(0); } /* ===================================================================== * 3. Signing a body * ===================================================================== */ /* Compose the signature headers for this hook. `body` gave the payload; the * timestamp used for v2 is the same one that goes on the wire, so a verifier * can recompute exactly what we signed. */ static int sign_request(const wh_hook *h, const char *body, size_t blen, wh_header *out, int maxout, char *err, size_t errsz) { if (err && errsz) err[0] = '\0'; if (!h->sig[0]) return 0; if (maxout < 2) { if (err) snprintf(err, errsz, "no room for signature headers"); return -1; } if (strcmp(h->sig, WH_SIG_GITHUB) == 0) { char hex[65]; sx_hmac_sha256_hex(h->secret, strlen(h->secret), body, blen, hex); copy_trunc(out[0].name, sizeof out[0].name, "X-Hub-Signature-256"); snprintf(out[0].value, sizeof out[0].value, "sha256=%s", hex); return 1; } if (strcmp(h->sig, WH_SIG_GITLAB) == 0) { copy_trunc(out[0].name, sizeof out[0].name, "X-Gitlab-Token"); copy_trunc(out[0].value, sizeof out[0].value, h->secret); return 1; } if (strcmp(h->sig, WH_SIG_V2) == 0) { /* HMAC over ".": a captured request stops being * valid once the verifier's window closes, which a body-only * signature never does. */ char ts[24], hex[65], signed_buf[64 + WH_BODY_CAP]; long long now = (long long)time(NULL); int n; snprintf(ts, sizeof ts, "%lld", now); n = snprintf(signed_buf, 32, "%s.", ts); if (blen > sizeof signed_buf - (size_t)n) { if (err) snprintf(err, errsz, "payload too large to sign"); return -1; } memcpy(signed_buf + n, body, blen); sx_hmac_sha256_hex(h->secret, strlen(h->secret), signed_buf, (size_t)n + blen, hex); copy_trunc(out[0].name, sizeof out[0].name, "X-Webhook-Timestamp"); copy_trunc(out[0].value, sizeof out[0].value, ts); copy_trunc(out[1].name, sizeof out[1].name, "X-Webhook-Signature"); snprintf(out[1].value, sizeof out[1].value, "t=%s,v1=%s", ts, hex); return 2; } if (err) snprintf(err, errsz, "unknown signature scheme '%s'", h->sig); return -1; } /* Decide whether this response status counts as a success. */ static int status_is_ok(int status) { return status >= 200 && status < 300; } /* ===================================================================== * 4. Firing a hook * ===================================================================== */ typedef struct { int sent; /* 1 = a response arrived */ int status; char error[512]; char body[WH_PREVIEW_CAP + 1]; size_t body_len; int truncated; long ms; } fire_result; /* Fire a stored hook with `payload` as the JSON body and `query` appended to * the URL. Returns 0 when the request completed (whatever the status), -1 when * it could not be sent at all (refused address, TLS, timeout). */ static int fire_hook(const wh_hook *h, const char *payload, size_t plen, const char *query, fire_result *res) { wh_url u; char uerr[256]; char full_url[WH_URL_MAX + 512]; wh_header hdrs[WH_MAX_HEADERS + 4]; int n = 0, i, sig_n = 0; wh_response r; long long t0, t1; memset(res, 0, sizeof *res); snprintf(full_url, sizeof full_url, "%s", h->url); if (query && *query) { size_t l = strlen(full_url); if (l + 1 < sizeof full_url) { int has_q = strchr(full_url, '?') != NULL; snprintf(full_url + l, sizeof full_url - l, "%s%s", has_q ? "&" : "?", query); } } if (wh_url_parse(full_url, &u, uerr, sizeof uerr) != 0) { snprintf(res->error, sizeof res->error, "%s", uerr); return -1; } for (i = 0; i < h->nheaders && n < WH_MAX_HEADERS; i++) hdrs[n++] = h->headers[i]; if (plen || strcmp(h->method, "GET") != 0) { int have_ct = 0; for (i = 0; i < n; i++) if (ieq(hdrs[i].name, "Content-Type")) have_ct = 1; if (!have_ct) { copy_trunc(hdrs[n].name, sizeof hdrs[n].name, "Content-Type"); copy_trunc(hdrs[n].value, sizeof hdrs[n].value, "application/json; charset=utf-8"); n++; } } { wh_header sig[2]; char serr[160]; sig_n = sign_request(h, payload, plen, sig, 2, serr, sizeof serr); if (sig_n < 0) { snprintf(res->error, sizeof res->error, "%s", serr); return -1; } for (i = 0; i < sig_n && n < (int)(sizeof hdrs / sizeof hdrs[0]); i++) hdrs[n++] = sig[i]; } t0 = (long long)(clock() / (CLOCKS_PER_SEC / 1000)); if (wh_http_request(h->method, &u, hdrs, n, (strcmp(h->method, "GET") == 0 || strcmp(h->method, "HEAD") == 0) ? NULL : payload, (strcmp(h->method, "GET") == 0 || strcmp(h->method, "HEAD") == 0) ? 0 : plen, WH_CONNECT_MS + WH_READ_MS, &r) != 0) { t1 = (long long)(clock() / (CLOCKS_PER_SEC / 1000)); res->ms = (long)(t1 - t0); snprintf(res->error, sizeof res->error, "%s", r.error); return -1; } t1 = (long long)(clock() / (CLOCKS_PER_SEC / 1000)); res->ms = (long)(t1 - t0); res->sent = 1; res->status = r.status; res->body_len = r.body_len; res->truncated = r.truncated; memcpy(res->body, r.body, r.body_len < sizeof res->body ? r.body_len : sizeof res->body - 1); res->body[res->body_len < sizeof res->body ? res->body_len : sizeof res->body - 1] = '\0'; return 0; } /* ===================================================================== * 5. Insert / update a hook from a request body * ===================================================================== */ typedef struct { int ok; char error[320]; char name[WH_NAME_MAX]; } store_op; static int save_hook_from_json(wh_store *s, const char *json, const char *forced_name, store_op *op) { wh_hook scratch; wh_hook *existing = NULL; char err[320]; memset(op, 0, sizeof *op); memset(&scratch, 0, sizeof scratch); copy_trunc(scratch.method, sizeof scratch.method, "POST"); if (forced_name && *forced_name) { existing = wh_hook_find(s, forced_name); if (existing) scratch = *existing; /* edit in place */ } if (wh_hook_apply(&scratch, json, existing, err, sizeof err) != 0) { snprintf(op->error, sizeof op->error, "%s", err); return -1; } /* An edit may rename nothing, but a create must not silently replace a * different hook that already owns the name. */ { wh_hook *clash = wh_hook_find(s, scratch.name); if (clash && (!existing || clash != existing)) { snprintf(op->error, sizeof op->error, "a hook named '%s' already exists", scratch.name); return -1; } } if (existing) { *existing = scratch; copy_trunc(op->name, sizeof op->name, scratch.name); } else { if (s->nhooks >= WH_MAX_HOOKS) { snprintf(op->error, sizeof op->error, "the store already holds %d hooks (the maximum)", WH_MAX_HOOKS); return -1; } s->hooks[s->nhooks++] = scratch; copy_trunc(op->name, sizeof op->name, scratch.name); } if (wh_store_save(s, err, sizeof err) != 0) { snprintf(op->error, sizeof op->error, "%s", err); return -1; } op->ok = 1; return 0; } /* ===================================================================== * 6. MCP surface * ===================================================================== */ static const char TOOL_LIST_SCHEMA[] = "{\"type\":\"object\",\"properties\":{" "\"redact_url\":{\"type\":\"boolean\",\"description\":" "\"Return only the endpoint host and path without the query string " "(default true). Set false only when you must see the exact URL, and " "remember the answer may then contain a provider token.\"}}," "\"additionalProperties\":false}"; static const char TOOL_TRIGGER_SCHEMA[] = "{\"type\":\"object\",\"properties\":{" "\"name\":{\"type\":\"string\",\"description\":" "\"The name of a stored hook, exactly as webhook_list reported it.\"}," "\"payload\":{\"type\":\"string\",\"description\":" "\"The request body. A JSON object or array is sent as-is; a bare string " "is sent as a JSON string literal. Defaults to {}.\"}," "\"query\":{\"type\":\"string\",\"description\":" "\"Optional query string appended to the hook's URL, without a leading " "? (for example event=deploy&env=prod).\"}}," "\"required\":[\"name\"],\"additionalProperties\":false}"; /* webhook_list */ static int tool_list(const char *args, char *out, size_t outsz) { wh_store s; char err[320]; wh_buf b; int i, redact = 1; yyjson_doc *doc = NULL; if (args && *args) { doc = yyjson_read(args, strlen(args), 0); if (doc) { yyjson_val *v = yyjson_obj_get(yyjson_doc_get_root(doc), "redact_url"); if (v && yyjson_is_bool(v)) redact = yyjson_get_bool(v) ? 1 : 0; } } wh_store_load(&s, err, sizeof err); wh_buf_init(&b); if (s.nhooks == 0) { wh_buf_str(&b, "No webhooks are configured on this node. Ask the owner to " "add one in the webhook plugin page (Settings -> Plugins), " "then call webhook_list again."); } else { wh_buf_printf(&b, "%d configured webhook%s\n\n", s.nhooks, s.nhooks == 1 ? "" : "s"); for (i = 0; i < s.nhooks; i++) { const wh_hook *h = &s.hooks[i]; char clean[WH_URL_MAX + 32]; if (redact) { wh_url u; char uerr[160]; clean[0] = '\0'; if (wh_url_parse(h->url, &u, uerr, sizeof uerr) == 0) wh_url_redact(&u, clean, sizeof clean); else copy_trunc(clean, sizeof clean, "(invalid url)"); } else { copy_trunc(clean, sizeof clean, h->url); } wh_buf_printf(&b, "- %s %s %s", h->name, h->method, clean); if (h->sig[0]) wh_buf_printf(&b, " [signed: %s]", h->sig); if (h->nheaders) wh_buf_printf(&b, " [%d header%s]", h->nheaders, h->nheaders == 1 ? "" : "s"); wh_buf_str(&b, "\n"); if (h->desc[0]) wh_buf_printf(&b, " %s\n", h->desc); } wh_buf_str(&b, "\nUse webhook_trigger with one of these names. Secrets are " "stored on the node and never returned.\n"); } if (err[0]) wh_buf_printf(&b, "\nStore warning: %s\n", err); snprintf(out, outsz, "%s", wh_buf_cstr(&b)); wh_buf_free(&b); if (doc) yyjson_doc_free(doc); return 0; } /* webhook_trigger */ static int tool_trigger(const char *args, char *out, size_t outsz, char *err, size_t errsz) { yyjson_doc *doc; yyjson_val *root, *v; char namebuf[WH_NAME_MAX]; char payload[WH_BODY_CAP]; char query[512]; size_t plen = 0; wh_store s; wh_hook *h; char serr[320]; fire_result res; if (err && errsz) err[0] = '\0'; if (!args || !*args) { snprintf(err, errsz, "missing arguments: {\"name\":\"...\"}"); return 1; } doc = yyjson_read(args, strlen(args), 0); if (!doc) { snprintf(err, errsz, "arguments are not valid JSON"); return 1; } root = yyjson_doc_get_root(doc); /* Copy the name out of the document before it is freed: yyjson strings * point into the document's own buffer, not into a copy. */ namebuf[0] = '\0'; v = yyjson_obj_get(root, "name"); if (v && yyjson_is_str(v)) copy_trunc(namebuf, sizeof namebuf, yyjson_get_str(v)); if (!namebuf[0]) { yyjson_doc_free(doc); snprintf(err, errsz, "missing required argument: name"); return 1; } /* `payload` may arrive as a string (the schema says so, because MCP * arguments are JSON and a caller that already has a serialized body * should not have to re-encode it) or as an object/array, which is what a * model naturally sends. Both are accepted. */ v = yyjson_obj_get(root, "payload"); if (v) { if (yyjson_is_str(v)) { const char *s = yyjson_get_str(v); size_t n = strlen(s); if (n >= sizeof payload) { yyjson_doc_free(doc); snprintf(err, errsz, "payload is larger than the %u byte limit", (unsigned)sizeof payload); return 1; } memcpy(payload, s, n); plen = n; } else { char *ser = yyjson_val_write(v, 0, NULL); if (!ser) { yyjson_doc_free(doc); snprintf(err, errsz, "could not serialize payload"); return 1; } plen = strlen(ser); if (plen >= sizeof payload) { free(ser); yyjson_doc_free(doc); snprintf(err, errsz, "payload is larger than the %u byte limit", (unsigned)sizeof payload); return 1; } memcpy(payload, ser, plen); free(ser); } } query[0] = '\0'; v = yyjson_obj_get(root, "query"); if (v && yyjson_is_str(v)) copy_trunc(query, sizeof query, yyjson_get_str(v)); yyjson_doc_free(doc); if (wh_store_load(&s, serr, sizeof serr) != 0) { snprintf(err, errsz, "%s", serr); return 1; } if (!plen) { memcpy(payload, "{}", 2); plen = 2; } h = wh_hook_find(&s, namebuf); if (!h) { wh_buf b; int i; wh_buf_init(&b); wh_buf_printf(&b, "no webhook named '%s'. Configured: ", namebuf); if (s.nhooks == 0) wh_buf_str(&b, "(none)"); for (i = 0; i < s.nhooks; i++) { if (i) wh_buf_str(&b, ", "); wh_buf_str(&b, s.hooks[i].name); } snprintf(err, errsz, "%s", wh_buf_cstr(&b)); wh_buf_free(&b); return 1; } if (fire_hook(h, payload, plen, query, &res) != 0) { snprintf(err, errsz, "could not deliver to '%s': %s", namebuf, res.error); return 1; } { wh_buf b; wh_logent le; wh_buf_init(&b); wh_buf_printf(&b, "%s %s -> HTTP %d in %ld ms\n", h->method, namebuf, res.status, res.ms); wh_buf_printf(&b, "ok: %s\n", status_is_ok(res.status) ? "yes" : "no"); if (res.truncated) wh_buf_printf(&b, "body (first %u bytes of a larger response):\n", (unsigned)res.body_len); else wh_buf_printf(&b, "body:\n"); wh_buf_str(&b, res.body_len ? res.body : "(empty)"); snprintf(out, outsz, "%s", wh_buf_cstr(&b)); wh_buf_free(&b); /* Record the delivery, newest first, in the same file. */ iso_now(le.at, sizeof le.at); copy_trunc(le.name, sizeof le.name, namebuf); le.status = res.status; le.ok = status_is_ok(res.status) ? 1 : 0; le.bytes = (long)res.body_len; le.ms = res.ms; le.error[0] = '\0'; wh_store_log_add(&s, &le); wh_store_save(&s, serr, sizeof serr); } return 0; } static const struct { const char *name; const char *desc; const char *schema; int (*call)(const char *args, char *out, size_t outsz, char *err, size_t errsz); } TOOLS[] = { { "webhook_list", "List the named webhooks configured on this node: name, method, endpoint " "(query string redacted), whether it is HMAC-signed and how many secret " "headers it carries. Secrets are never returned. Call this first to learn " "which names webhook_trigger accepts.", TOOL_LIST_SCHEMA, NULL }, { "webhook_trigger", "Send one stored webhook by name with a JSON payload. The stored headers, " "bearer tokens and HMAC signature are applied on the node; the secret never " "enters this conversation. Returns the HTTP status, latency and the first " "4 KiB of the response body.", TOOL_TRIGGER_SCHEMA, tool_trigger } }; /* Minimal MCP server. Newline-delimited JSON-RPC 2.0, with Content-Length * framing accepted because some clients send LSP-style headers. Reads with * read(2), never fread(2): on a pipe fread blocks until its whole buffer fills, * which turns a client that writes the body and the newline as two separate * writes into a hang. That exact shape is what the connector router uses. */ static int read_request_line(wh_buf *line) { static char rb[16384]; static size_t rn, rp; long long want = -1; line->n = 0; for (;;) { if (rp < rn) { size_t i = rp; int nl = 0; while (i < rn && rb[i] != '\n') i++; if (i < rn) nl = 1; { size_t take = i - rp; char tmp[16385]; if (take > 0) memcpy(tmp, rb + rp, take); rp = i + (nl ? 1 : 0); tmp[take] = '\0'; while (take > 0 && (tmp[take - 1] == '\r' || tmp[take - 1] == ' ')) tmp[--take] = '\0'; if (want < 0 && strncmp(tmp, "Content-Length:", 15) == 0) { want = strtoll(tmp + 15, NULL, 10); continue; } if (want < 0 && take == 0 && !nl) continue; /* header blank */ wh_buf_add(line, tmp, take); if (want < 0) { if (nl) return 1; continue; } if ((long long)line->n >= want) { if (line->p && (size_t)want < line->cap) line->p[want] = '\0'; line->n = (size_t)want; want = -1; return 1; } wh_buf_add(line, "\n", 1); continue; } } if (rp >= rn) { rn = 0; rp = 0; } for (;;) { #if defined(_WIN32) long got = (long)_read(_fileno(stdin), rb, (unsigned)sizeof rb); #else long got = (long)read(fileno(stdin), rb, sizeof rb); #endif if (got > 0) { rn = (size_t)got; break; } if (got == 0) return line->n ? 1 : 0; #if !defined(_WIN32) if (errno == EINTR) continue; #endif return line->n ? 1 : 0; } } } static void mcp_send(wh_buf *b) { fputs(wh_buf_cstr(b), stdout); fputc('\n', stdout); fflush(stdout); } static void mcp_error(const char *id_json, long code, const char *msg) { wh_buf b; wh_buf_init(&b); wh_buf_str(&b, "{\"jsonrpc\":\"2.0\",\"id\":"); wh_buf_str(&b, id_json ? id_json : "null"); wh_buf_printf(&b, ",\"error\":{\"code\":%ld,\"message\":", code); wh_buf_json_str(&b, msg ? msg : "error"); wh_buf_str(&b, "}}"); mcp_send(&b); wh_buf_free(&b); } static void mcp_result(const char *id_json, const char *result_json) { wh_buf b; wh_buf_init(&b); wh_buf_str(&b, "{\"jsonrpc\":\"2.0\",\"id\":"); wh_buf_str(&b, id_json ? id_json : "null"); wh_buf_str(&b, ",\"result\":"); wh_buf_str(&b, result_json ? result_json : "{}"); wh_buf_str(&b, "}"); mcp_send(&b); wh_buf_free(&b); } static void mcp_tool_content(const char *id_json, const char *text, int is_error) { wh_buf b; wh_buf_init(&b); wh_buf_str(&b, "{\"content\":[{\"type\":\"text\",\"text\":"); wh_buf_json_str(&b, text ? text : ""); wh_buf_str(&b, "}]"); if (is_error) wh_buf_str(&b, ",\"isError\":true"); wh_buf_str(&b, "}"); mcp_result(id_json, wh_buf_cstr(&b)); wh_buf_free(&b); } static void mcp_tools_list(const char *id_json) { wh_buf b; size_t i; wh_buf_init(&b); wh_buf_str(&b, "{\"tools\":["); for (i = 0; i < sizeof TOOLS / sizeof TOOLS[0]; i++) { int f = 1; if (i) wh_buf_str(&b, ","); wh_buf_str(&b, "{"); wh_buf_key(&b, "name", &f); wh_buf_json_str(&b, TOOLS[i].name); wh_buf_key(&b, "description", &f); wh_buf_json_str(&b, TOOLS[i].desc); wh_buf_key(&b, "inputSchema", &f); wh_buf_str(&b, TOOLS[i].schema); wh_buf_str(&b, "}"); } wh_buf_str(&b, "]}"); mcp_result(id_json, wh_buf_cstr(&b)); wh_buf_free(&b); } static void mcp_call_tool(const char *id_json, yyjson_val *params) { yyjson_val *v; const char *name = NULL; char args[WH_BODY_CAP]; size_t i; char out[WH_BODY_CAP + WH_PREVIEW_CAP + 4096]; char err[512]; args[0] = '\0'; if (params) { v = yyjson_obj_get(params, "name"); if (v && yyjson_is_str(v)) name = yyjson_get_str(v); v = yyjson_obj_get(params, "arguments"); if (v && yyjson_is_obj(v)) { char *ser = yyjson_val_write(v, 0, NULL); if (ser) { copy_trunc(args, sizeof args, ser); free(ser); } } } if (!name || !*name) { mcp_error(id_json, -32602, "invalid params: missing tool name"); return; } for (i = 0; i < sizeof TOOLS / sizeof TOOLS[0]; i++) { if (strcmp(TOOLS[i].name, name) != 0) continue; out[0] = '\0'; err[0] = '\0'; if (i == 0) { tool_list(args[0] ? args : "{}", out, sizeof out); mcp_tool_content(id_json, out, 0); } else if (TOOLS[i].call) { int rc = TOOLS[i].call(args, out, sizeof out, err, sizeof err); if (rc != 0) mcp_tool_content(id_json, err[0] ? err : "tool failed", 1); else mcp_tool_content(id_json, out, 0); } return; } mcp_error(id_json, -32602, "unknown tool"); } static void mcp_handle_line(const char *line) { yyjson_doc *doc; yyjson_val *root, *method, *id, *params; char *id_json = NULL; const char *m; doc = yyjson_read(line, strlen(line), 0); if (!doc) { mcp_error("null", -32700, "parse error"); return; } root = yyjson_doc_get_root(doc); if (!yyjson_is_obj(root)) { yyjson_doc_free(doc); mcp_error("null", -32600, "invalid request: not an object"); return; } method = yyjson_obj_get(root, "method"); id = yyjson_obj_get(root, "id"); params = yyjson_obj_get(root, "params"); if (id) { id_json = yyjson_val_write(id, 0, NULL); if (!id_json) id_json = strdup("null"); } m = (method && yyjson_is_str(method)) ? yyjson_get_str(method) : NULL; if (!m) { if (id_json) mcp_error(id_json, -32600, "invalid request: missing method"); goto done; } if (strcmp(m, "initialize") == 0) { wh_buf b; int f = 1; wh_buf_init(&b); wh_buf_str(&b, "{"); wh_buf_key(&b, "protocolVersion", &f); wh_buf_json_str(&b, "2024-11-05"); wh_buf_key(&b, "capabilities", &f); wh_buf_str(&b, "{\"tools\":{}}"); wh_buf_key(&b, "serverInfo", &f); wh_buf_str(&b, "{"); { int g = 1; wh_buf_key(&b, "name", &g); wh_buf_json_str(&b, PLUGIN_ID); wh_buf_key(&b, "version", &g); wh_buf_json_str(&b, PLUGIN_VER); } wh_buf_str(&b, "}}"); mcp_result(id_json, wh_buf_cstr(&b)); wh_buf_free(&b); } else if (strcmp(m, "notifications/initialized") == 0 || strcmp(m, "initialized") == 0) { /* notification: no reply */ } else if (strcmp(m, "ping") == 0) { if (id_json) mcp_result(id_json, "{}"); } else if (strcmp(m, "tools/list") == 0) { mcp_tools_list(id_json); } else if (strcmp(m, "tools/call") == 0) { mcp_call_tool(id_json, params); } else if (strcmp(m, "prompts/list") == 0) { if (id_json) mcp_result(id_json, "{\"prompts\":[]}"); } else if (strcmp(m, "resources/list") == 0) { if (id_json) mcp_result(id_json, "{\"resources\":[]}"); } else if (strcmp(m, "logging/setLevel") == 0) { if (id_json) mcp_result(id_json, "{}"); } else { if (id_json) mcp_error(id_json, -32601, "method not found"); } done: free(id_json); yyjson_doc_free(doc); } static int mode_mcp(void) { wh_buf line; #if defined(_WIN32) _setmode(_fileno(stdout), _O_BINARY); _setmode(_fileno(stdin), _O_BINARY); #endif wh_buf_init(&line); while (read_request_line(&line)) { if (line.n > 4u * 1024u * 1024u) { mcp_error("null", -32600, "request too large"); continue; } if (line.n) mcp_handle_line(wh_buf_cstr(&line)); } wh_buf_free(&line); return 0; } static int mode_schema(void) { wh_buf b; size_t i; wh_buf_init(&b); wh_buf_str(&b, "{\"tools\":["); for (i = 0; i < sizeof TOOLS / sizeof TOOLS[0]; i++) { int f = 1; if (i) wh_buf_str(&b, ","); wh_buf_str(&b, "{"); wh_buf_key(&b, "name", &f); wh_buf_json_str(&b, TOOLS[i].name); wh_buf_key(&b, "description", &f); wh_buf_json_str(&b, TOOLS[i].desc); wh_buf_key(&b, "inputSchema", &f); wh_buf_str(&b, TOOLS[i].schema); wh_buf_str(&b, "}"); } wh_buf_str(&b, "]}"); fputs(wh_buf_cstr(&b), stdout); fputc('\n', stdout); wh_buf_free(&b); return 0; } /* ===================================================================== * 7. --meta * ===================================================================== */ static int mode_meta(void) { printf("{\"name\":\"%s\",\"desc\":\"%s\",\"kind\":\"%s\"," "\"mcp\":true,\"daemon\":false,\"menus\":false," "\"verified\":\"live\",\"version\":\"%s\"}\n", PLUGIN_NAME, PLUGIN_DESC, PLUGIN_KIND, PLUGIN_VER); return 0; } /* ===================================================================== * 8. JSON API (?action=…) * ===================================================================== */ static char *read_cgi_body(void) { const char *bp = getenv("POST_BODY_FILE"); const char *cl = getenv("CONTENT_LENGTH"); wh_buf b; long want = -1; char chunk[4096]; if (bp && *bp) { FILE *f = fopen(bp, "rb"); wh_buf out; size_t got; if (!f) return NULL; wh_buf_init(&out); while ((got = fread(chunk, 1, sizeof chunk, f)) > 0) wh_buf_add(&out, chunk, got); fclose(f); if (!out.p) { char *e = (char *)malloc(1); if (e) e[0] = '\0'; return e; } return out.p; } if (!cl || !*cl) return NULL; want = strtol(cl, NULL, 10); if (want <= 0) return NULL; if (want > 8 * 1024 * 1024) return NULL; wh_buf_init(&b); while ((long)b.n < want) { size_t ask = sizeof chunk; size_t got; if ((long)(b.n + ask) > want) ask = (size_t)(want - (long)b.n); got = fread(chunk, 1, ask, stdin); if (got == 0) break; wh_buf_add(&b, chunk, got); } if (!b.p) { char *e = (char *)malloc(1); if (e) e[0] = '\0'; return e; } return b.p; } static void api_ok(const char *json) { cgi_header(200, "application/json; charset=utf-8"); fputs(json, stdout); fputc('\n', stdout); fflush(stdout); } static void api_err(int status, const char *msg) { wh_buf b; int f = 1; wh_buf_init(&b); wh_buf_str(&b, "{"); wh_buf_key(&b, "ok", &f); wh_buf_str(&b, "false"); wh_buf_key(&b, "error", &f); wh_buf_json_str(&b, msg ? msg : "error"); wh_buf_str(&b, "}"); cgi_header(status, "application/json; charset=utf-8"); fputs(wh_buf_cstr(&b), stdout); fputc('\n', stdout); fflush(stdout); wh_buf_free(&b); } static int mode_api(const char *qs, const char *action) { wh_store s; char err[320]; char *body; int rc = 0; body = read_cgi_body(); memset(&s, 0, sizeof s); if (wh_store_load(&s, err, sizeof err) != 0) { api_err(500, err); free(body); return 0; } if (!action || !*action || strcmp(action, "list") == 0 || strcmp(action, "status") == 0) { char *out = (char *)malloc(256 * 1024); if (!out) { api_err(500, "out of memory"); free(body); return 0; } wh_store_list_json(&s, out, 256 * 1024); api_ok(out); free(out); } else if (strcmp(action, "save") == 0) { store_op op; char edit[WH_NAME_MAX]; edit[0] = '\0'; get_query_val(qs, "name", edit, sizeof edit); if (!body || !*body) { api_err(400, "save needs a JSON body"); } else if (save_hook_from_json(&s, body, edit, &op) != 0) { api_err(400, op.error); } else { wh_buf b; int f = 1; wh_buf_init(&b); wh_buf_str(&b, "{"); wh_buf_key(&b, "ok", &f); wh_buf_str(&b, "true"); wh_buf_key(&b, "saved", &f); wh_buf_json_str(&b, op.name); wh_buf_str(&b, "}"); api_ok(wh_buf_cstr(&b)); wh_buf_free(&b); } } else if (strcmp(action, "delete") == 0 || strcmp(action, "remove") == 0) { char name[WH_NAME_MAX]; wh_hook *h; name[0] = '\0'; get_query_val(qs, "name", name, sizeof name); if (!name[0] && body && *body) { yyjson_doc *doc = yyjson_read(body, strlen(body), 0); if (doc) { yyjson_val *v = yyjson_obj_get(yyjson_doc_get_root(doc), "name"); if (v && yyjson_is_str(v)) copy_trunc(name, sizeof name, yyjson_get_str(v)); yyjson_doc_free(doc); } } if (!name[0]) { api_err(400, "delete needs a name"); } else { int idx = -1, i; for (i = 0; i < s.nhooks; i++) if (strcmp(s.hooks[i].name, name) == 0) { idx = i; break; } if (idx < 0) { api_err(404, "no such hook"); } else { wh_hook_remove(&s, idx); if (wh_store_save(&s, err, sizeof err) != 0) api_err(500, err); else api_ok("{\"ok\":true,\"deleted\":true}"); } } (void)h; } else if (strcmp(action, "fire") == 0 || strcmp(action, "trigger") == 0 || strcmp(action, "test") == 0) { char name[WH_NAME_MAX], payload[WH_BODY_CAP], query[512]; wh_hook *h; fire_result res; name[0] = '\0'; payload[0] = '\0'; query[0] = '\0'; get_query_val(qs, "name", name, sizeof name); get_query_val(qs, "query", query, sizeof query); get_query_val(qs, "payload", payload, sizeof payload); if (!payload[0] && body && *body) { yyjson_doc *doc = yyjson_read(body, strlen(body), 0); if (doc) { yyjson_val *root = yyjson_doc_get_root(doc), *v; v = yyjson_obj_get(root, "name"); if (!name[0] && v && yyjson_is_str(v)) copy_trunc(name, sizeof name, yyjson_get_str(v)); v = yyjson_obj_get(root, "query"); if (!query[0] && v && yyjson_is_str(v)) copy_trunc(query, sizeof query, yyjson_get_str(v)); v = yyjson_obj_get(root, "payload"); if (v) { if (yyjson_is_str(v)) copy_trunc(payload, sizeof payload, yyjson_get_str(v)); else { char *ser = yyjson_val_write(v, 0, NULL); if (ser) { copy_trunc(payload, sizeof payload, ser); free(ser); } } } yyjson_doc_free(doc); } } if (!name[0]) { api_err(400, "fire needs a hook name"); } else if (!(h = wh_hook_find(&s, name))) { api_err(404, "no such hook"); } else { wh_buf b; int f = 1; wh_logent le; if (!payload[0]) copy_trunc(payload, sizeof payload, "{}"); if (fire_hook(h, payload, strlen(payload), query, &res) != 0) { wh_buf_init(&b); wh_buf_str(&b, "{"); wh_buf_key(&b, "ok", &f); wh_buf_str(&b, "false"); wh_buf_key(&b, "delivered", &f); wh_buf_str(&b, "false"); wh_buf_key(&b, "error", &f); wh_buf_json_str(&b, res.error); wh_buf_str(&b, "}"); iso_now(le.at, sizeof le.at); copy_trunc(le.name, sizeof le.name, name); le.status = 0; le.ok = 0; le.bytes = 0; le.ms = res.ms; copy_trunc(le.error, sizeof le.error, res.error); wh_store_log_add(&s, &le); wh_store_save(&s, err, sizeof err); cgi_header(502, "application/json; charset=utf-8"); fputs(wh_buf_cstr(&b), stdout); fputc('\n', stdout); wh_buf_free(&b); } else { wh_buf_init(&b); wh_buf_str(&b, "{"); wh_buf_key(&b, "ok", &f); wh_buf_str(&b, "true"); wh_buf_key(&b, "delivered", &f); wh_buf_str(&b, "true"); wh_buf_key(&b, "status", &f); wh_buf_printf(&b, "%d", res.status); wh_buf_key(&b, "ok_status", &f); wh_buf_str(&b, status_is_ok(res.status) ? "true" : "false"); wh_buf_key(&b, "ms", &f); wh_buf_printf(&b, "%ld", res.ms); wh_buf_key(&b, "bytes", &f); wh_buf_printf(&b, "%lu", (unsigned long)res.body_len); wh_buf_key(&b, "truncated", &f); wh_buf_str(&b, res.truncated ? "true" : "false"); wh_buf_key(&b, "body_preview", &f); wh_buf_json_str(&b, res.body); wh_buf_str(&b, "}"); api_ok(wh_buf_cstr(&b)); wh_buf_free(&b); iso_now(le.at, sizeof le.at); copy_trunc(le.name, sizeof le.name, name); le.status = res.status; le.ok = status_is_ok(res.status) ? 1 : 0; le.bytes = (long)res.body_len; le.ms = res.ms; le.error[0] = '\0'; wh_store_log_add(&s, &le); wh_store_save(&s, err, sizeof err); } } } else { api_err(400, "unknown action"); } free(body); return rc; } /* ===================================================================== * 9. HTML page * ===================================================================== */ static int mode_html(const char *qs, int embed, const char *theme) { const char *p = UI_HTML; cgi_header(200, "text/html; charset=utf-8"); while (*p) { /* 0x01 -> the theme block (prepaint + tokens), 0x02 -> the handoff. */ if ((unsigned char)*p == 0x01) { fputs(SX_BOT_THEME_PREPAINT, stdout); if (theme && strcmp(theme, "light") == 0) fputs("", stdout); fputs("\n", stdout); p++; continue; } if ((unsigned char)*p == 0x02) { fputs(SX_BOT_THEME_HANDOFF, stdout); fputs(SX_BOT_THEME_TOGGLE_JS, stdout); p++; continue; } fputc(*p, stdout); p++; } (void)qs; (void)embed; return 0; } /* ===================================================================== * 10. main * ===================================================================== */ int main(int argc, char **argv) { int i, meta = 0, mcp = 0, schema = 0, embed = 0; const char *qs, *theme; char qs2[4096], action[64]; char *qmark; /* MinGW: \n must stay \n. A plugin that writes its own CRLF headers in * text mode emits CR CR LF and the CGI parser splits the head in the wrong * place. Applies to every mode, not just --mcp. */ #if defined(_WIN32) _setmode(_fileno(stdout), _O_BINARY); _setmode(_fileno(stdin), _O_BINARY); #endif for (i = 1; i < argc; i++) { if (strcmp(argv[i], "--meta") == 0) meta = 1; else if (strcmp(argv[i], "--mcp") == 0) mcp = 1; else if (strcmp(argv[i], "--schema") == 0) schema = 1; else if (strcmp(argv[i], "--version") == 0) { printf("%s %s (%s)\n", PLUGIN_ID, PLUGIN_VER, PLUGIN_NAME); return 0; } } if (meta || getenv("SX_PLUGIN_META")) return mode_meta(); if (schema) return mode_schema(); if (mcp) return mode_mcp(); qs = getenv("QUERY_STRING"); if (!qs) qs = ""; copy_trunc(qs2, sizeof qs2, qs); qmark = strchr(qs2, '?'); if (qmark) memmove(qs2, qmark + 1, strlen(qmark)); action[0] = '\0'; get_query_val(qs2, "action", action, sizeof action); embed = 0; { char e[16]; if (get_query_val(qs2, "embed", e, sizeof e)) embed = strcmp(e, "1") == 0 || ieq(e, "true"); } theme = "dark"; { char t[16]; if (get_query_val(qs2, "theme", t, sizeof t)) theme = ieq(t, "light") ? "light" : "dark"; } if (action[0] || strstr(qs2, "format=json") || (getenv("REQUEST_METHOD") && ieq(getenv("REQUEST_METHOD"), "POST"))) { require_node_auth(); return mode_api(qs2, action); } require_node_auth(); return mode_html(qs2, embed, theme); }