/*
* connector_starter.c — SCORPIOX BOT connector starter (C99, zero deps)
*
* The companion to plugin_starter.c: use that one for a tool or widget with
* no network side, use THIS one when the plugin is ALSO a connector — it
* calls an HTTPS API, exposes MCP tools, or bridges a chat network to the
* node.
*
* The smallest connector that is a real plugin: an MCP tool server, a
* node-auth-gated control API, a themed setup page and an optional
* always-on bridge, all from one file. It links against the vendored
* Connector SDK (scorpiox-bot-connector-sdk -> build/libsxconn.a), which
* carries its own HTTPS/TLS/WebSocket client and JSON, so there is nothing
* else to install and no runtime .so/.dll anywhere.
*
* Copy this file, change CONNECTOR_ID / name / desc / kind, replace the
* tools and the UI cards with your service, and build. ~200-400 lines of
* connector logic is the whole job.
*
* Modes one binary serves:
* --meta | SX_PLUGIN_META=1 one-line JSON identity
* --mcp stdio MCP JSON-RPC 2.0 tools
* --daemon long-lived bridge (tick callback below)
* ?action= | ?format=json node-auth-gated JSON control API
* GET the setup UI
*
* Build (from a sibling checkout of scorpiox-bot-connector-sdk):
* make -C ../scorpiox-bot-connector-sdk lib # once -> build/libsxconn.a
* cc -O2 -std=c99 -Wall -Wextra -Wno-overlength-strings \
* -I../scorpiox-bot-connector-sdk/src \
* -I../scorpiox-bot-connector-sdk/vendor/yyjson \
* -I../scorpiox-bot-connector-sdk/src/bearssl/inc \
* src/plugin_hello.c \
* ../scorpiox-bot-connector-sdk/build/libsxconn.a -o plugin_hello
*
* Install (the whole installation is the copy):
* cp plugin_hello ~/.scorpiox/plugins/
* cp plugin_hello /workspace/.scorpiox/plugins/ (persistent on a container)
*
* Clean-room rule for a published connector: zero LAN literals, zero
* credentials, zero hard-coded hosts. Every endpoint comes from the
* environment or the connector's own config.json in its connector dir.
*
* MIT License. Copyright (c) 2026 SCORPIOX INC.
*/
#if !defined(_WIN32)
# define _POSIX_C_SOURCE 200809L
# define _DEFAULT_SOURCE
#endif
#include "sx_connector.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#define CONNECTOR_ID "hello"
/* ------------------------------------------------------------------ tools */
/* A tool handler receives the raw arguments object and writes human-readable
* text into `out`. Return non-zero to set isError (the text is then shown as
* the failure reason — an agent can read an error, it cannot read a closed
* pipe, so never fail the transport instead of the tool). */
static int tool_echo(const char *args_json, char *out, size_t outsz,
char *err, size_t errsz)
{
yyjson_doc *d;
yyjson_val *v;
(void)err; (void)errsz;
out[0] = '\0';
d = yyjson_read(args_json && *args_json ? args_json : "{}",
strlen(args_json && *args_json ? args_json : "{}"), 0);
if (!d) { sx_copy(err, errsz, "arguments are not valid JSON"); return -1; }
v = yyjson_obj_get(yyjson_doc_get_root(d), "text");
if (v && yyjson_is_str(v)) sx_copy(out, outsz, yyjson_get_str(v));
else sx_copy(out, outsz, "(no text)");
yyjson_doc_free(d);
return 0;
}
static int tool_time(const char *args_json, char *out, size_t outsz,
char *err, size_t errsz)
{
time_t now = time(NULL);
struct tm tmv;
(void)args_json; (void)err; (void)errsz;
#if defined(_WIN32)
gmtime_s(&tmv, &now);
#else
gmtime_r(&now, &tmv);
#endif
strftime(out, outsz, "%Y-%m-%dT%H:%M:%SZ", &tmv);
return 0;
}
/* Replace this with a real call to your service. sx_http_* is the SDK's own
* HTTPS client (vendored BearSSL) — no libcurl, no OpenSSL, verified by
* default against the compiled-in root bundle plus SX_CA_BUNDLE. */
static int tool_fetch(const char *args_json, char *out, size_t outsz,
char *err, size_t errsz)
{
yyjson_doc *d;
yyjson_val *v;
sx_conn c;
sx_url u;
const char *url;
char *body = NULL;
out[0] = '\0';
d = yyjson_read(args_json && *args_json ? args_json : "{}",
strlen(args_json && *args_json ? args_json : "{}"), 0);
if (!d) { sx_copy(err, errsz, "arguments are not valid JSON"); return -1; }
v = yyjson_obj_get(yyjson_doc_get_root(d), "url");
if (!v || !yyjson_is_str(v) || !*yyjson_get_str(v)) {
yyjson_doc_free(d);
sx_copy(err, errsz, "url is required");
return -1;
}
url = yyjson_get_str(v);
if (sx_url_parse(url, &u, err, errsz) != 0) { yyjson_doc_free(d); return -1; }
yyjson_doc_free(d);
if (sx_conn_open(&c, &u, 10000, err, errsz) != 0) return -1;
if (sx_http_request(&c, "GET", u.path, NULL, NULL, NULL, 0,
15000, err, errsz) != 0) {
sx_conn_close(&c);
return -1;
}
if (sx_read_all(&c, &body, NULL, 15000) != 1 || !body) {
if (err && errsz) snprintf(err, errsz, "no response body");
free(body);
sx_conn_close(&c);
return -1;
}
sx_copy(out, outsz, body); /* truncated to outsz, always NUL-safe */
free(body);
sx_conn_close(&c);
return 0;
}
static const sx_mcp_tool TOOLS[] = {
{ "echo", "echo the text back",
"{\"type\":\"object\",\"properties\":{\"text\":{\"type\":\"string\"}}}",
tool_echo },
{ "time", "current UTC time",
"{\"type\":\"object\",\"properties\":{}}",
tool_time },
{ "fetch", "GET a URL and return the body (https verified by default)",
"{\"type\":\"object\",\"properties\":{\"url\":{\"type\":\"string\"}},"
"\"required\":[\"url\"]}",
tool_fetch },
};
#define NTOOLS (sizeof TOOLS / sizeof TOOLS[0])
/* -------------------------------------------------------------- setup UI */
static int ui(const sx_plugin_info *info, const char *query,
int embed, const char *theme)
{
sx_sender *senders = NULL;
size_t n = 0, i;
char dir[1024];
(void)query;
sx_cgi_header(200, "text/html; charset=utf-8");
sx_html_head(info->name);
printf("<h1>%s</h1><p class=\"sub\">%s · kind %s · "
"<span class=\"pill\">mcp %s</span> <span class=\"pill\">daemon %s</span> "
"<span class=\"pill\">verified %s</span> <span class=\"pill\">%s</span></p>\n",
info->name, info->desc, info->kind,
info->mcp ? "yes" : "no", info->daemon ? "yes" : "no",
info->verified, theme);
/* Under ?embed=1 the frame owns the chrome, so the page brings no toggle
* of its own. */
if (!embed)
printf("<p class=\"embed-hide\"><button class=\"ghost\" "
"onclick=\"document.documentElement.setAttribute('data-theme',"
"sxThemeNow()==='dark'?'light':'dark')\">theme</button></p>\n");
/* The sender table is the security surface of a channel connector: an
* unknown sender is refused and parked here until the owner approves it. */
if (info->daemon) {
sx_senders_load(info->id, &senders, &n);
printf("<div class=\"card\"><h2 style=\"margin:0 0 8px;font-size:15px\">"
"Allowed senders</h2>");
if (!n) {
printf("<p class=\"sub\" style=\"margin:0\">No senders yet. Unknown "
"senders are refused and held in the pairing queue "
"(default-deny).</p>");
} else {
for (i = 0; i < n; i++)
printf("<div style=\"padding:4px 0;border-top:1px solid var(--line)\">"
"<code>%s</code> <span class=\"pill\">%s</span> "
"<span class=\"%s\">%s</span></div>\n",
senders[i].key,
senders[i].approved ? "allowed" : senders[i].code,
senders[i].approved ? "ok" : "warn",
senders[i].approved ? "approved" : "pending");
}
printf("</div>\n");
sx_senders_free(senders);
}
if (sx_connector_dir(info->id, dir, sizeof dir) == 0)
printf("<div class=\"card\">state <code>%s</code></div>\n", dir);
/* A button that fetches the JSON API is the whole UI framework. The pwd
* comes from the query string because bot-web hands the iframe ?pwd=. */
printf("<div class=\"card\"><pre id=\"out\">try: ?action=status</pre>"
"<button onclick=\"fetch('?action=status&pwd='+"
"encodeURIComponent(new URLSearchParams(location.search).get('pwd')"
"||'')).then(r=>r.text()).then(t=>document.getElementById('out')"
".textContent=t)\">refresh status</button></div>\n");
sx_html_handoff_script();
fputs("</body>\n</html>\n", stdout);
return 0;
}
/* ------------------------------------------------------------ control API */
static int api(const sx_plugin_info *info, const char *query,
const char *action, const char *body)
{
yyjson_mut_doc *doc = yyjson_mut_doc_new(NULL);
yyjson_mut_val *root = yyjson_mut_obj(doc);
char dir[1024];
(void)body;
sx_require_node_auth(); /* 401 + exit unless cred ok */
yyjson_mut_doc_set_root(doc, root);
if (!action[0] || strcmp(action, "status") == 0) {
sx_connector_dir(info->id, dir, sizeof dir);
yyjson_mut_obj_add_true(doc, root, "ok");
yyjson_mut_obj_add_strcpy(doc, root, "id", info->id);
yyjson_mut_obj_add_strcpy(doc, root, "kind", info->kind);
yyjson_mut_obj_add_strcpy(doc, root, "version",
info->version ? info->version : "0.0.0");
yyjson_mut_obj_add_strcpy(doc, root, "connector_dir", dir);
yyjson_mut_obj_add_strcpy(doc, root, "node_api", sx_node_api_base());
} else if (strcmp(action, "approve") == 0) {
char key[192];
if (!sx_query_get(query, "key", key, sizeof key) || !key[0]) {
sx_json_error("key is required", 400);
yyjson_mut_doc_free(doc);
return 0;
}
yyjson_mut_obj_add_bool(doc, root, "ok",
sx_sender_approve(info->id, key) == 0);
} else if (strcmp(action, "send") == 0) {
/* the bridge's outbound half, exposed so the UI can test it */
char text[4096], sess[128], err[256];
if (!sx_query_get(query, "text", text, sizeof text) || !text[0]) {
sx_json_error("text is required", 400);
yyjson_mut_doc_free(doc);
return 0;
}
if (!sx_query_get(query, "session", sess, sizeof sess) || !sess[0])
sx_copy(sess, sizeof sess, "default");
err[0] = '\0';
if (sx_node_post_inbox(sess, text, NULL, err, sizeof err) == 0)
yyjson_mut_obj_add_true(doc, root, "ok");
else {
yyjson_mut_obj_add_false(doc, root, "ok");
yyjson_mut_obj_add_strcpy(doc, root, "error", err);
}
} else {
sx_json_error("unknown action", 400);
yyjson_mut_doc_free(doc);
return 0;
}
sx_print_json_doc(doc);
yyjson_mut_doc_free(doc);
return 0;
}
/* ---------------------------------------------------------------- daemon */
/* One tick of the bridge. Poll the platform, apply the default-deny gate
* (sx_sender_allowed), hand approved text to the node (sx_node_post_inbox),
* and watch for the reply (sx_sse_open / sx_sse_next). Return non-zero to
* stop the loop. Keep it short: sx_daemon_run() sleeps between ticks, owns
* the pidfile, and turns SIGTERM/SIGINT/SIGHUP into a clean stop. */
static int tick(const sx_daemon_cfg *cfg, void *user)
{
char *body = NULL;
char err[256];
int *ticks = (int *)user;
(*ticks)++;
if (sx_node_conversation(cfg->session ? cfg->session : "default",
-1, 5, &body, err, sizeof err) == 0) {
sx_log(cfg->id, "conversation ok (%lu bytes)",
(unsigned long)strlen(body ? body : ""));
free(body);
} else {
sx_log(cfg->id, "conversation: %s", err);
}
return 0; /* keep running */
}
/* ------------------------------------------------------------------ main */
int main(int argc, char **argv)
{
sx_plugin_info info;
memset(&info, 0, sizeof info);
info.id = CONNECTOR_ID;
info.name = "hello"; /* 1-2 words: dropdowns are small */
info.desc = "greeting"; /* <= 15 chars */
info.kind = SX_KIND_HYBRID; /* ui | mcp | channel | hybrid */
info.mcp = 1;
info.daemon = 1;
info.menus = -1; /* -1 = derive from kind */
info.verified = "mock"; /* honest: mock harness only */
info.version = "1.0.0";
sx_stdio_binary(); /* Windows: headers stay CRLF */
/* The connector modes own argv; everything else is sx_main's dispatch.
* sx_main() also handles --meta / SX_PLUGIN_META for you. */
if (sx_has_flag(argc, argv, "--mcp")) return sx_mcp_serve(&info, TOOLS, NTOOLS);
if (sx_has_flag(argc, argv, "--schema")) return sx_mcp_schema(&info, TOOLS, NTOOLS);
if (sx_has_flag(argc, argv, "--daemon")) {
sx_daemon_cfg cfg;
int ticks = 0;
const char *s;
memset(&cfg, 0, sizeof cfg);
cfg.id = CONNECTOR_ID;
s = getenv("SX_CONNECTOR_SESSION");
cfg.session = (s && *s) ? s : "default";
cfg.interval_ms = 2000;
cfg.user = &ticks;
return sx_daemon_run(&cfg, tick);
}
return sx_main(argc, argv, &info, ui, api);
}