/* * plugin_memory.c - entry point for the SCORPIOX BOT knowledge-graph memory * 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 on the node 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 on stdin, one response per line on stdout. This is what makes * the plugin a tool provider for SCORPIOX CODE through the single * sx-connector-mcp router, with no clang change and no extra MCP server * slot. * 3. ?action=... | ?format=json | POST -> the JSON node API the browser UI * talks to. Same nine operations as --mcp, so the UI can never drift * away from what an agent sees. * 4. GET (default) -> the knowledge-graph browser page. * 5. --version -> id + version. * * Modes 3 and 4 sit behind require_node_auth(): the node's :8150 is reachable * from the LAN, so a plugin that reads and writes the operator's knowledge * graph must not answer a bare curl. --meta stays open so discovery works. * * 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 we emit 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 cannot find the header/body * separator, and the whole reply (headers included) is served as a body. Same * for the MCP loop: a JSON-RPC line with a stray \r confuses line readers. * Force binary stdio before main() runs. */ __attribute__((constructor)) static void sx_plugin_binary_stdio(void) { _setmode(_fileno(stdout), _O_BINARY); _setmode(_fileno(stdin), _O_BINARY); } #else # include #endif #include "memory.h" /* In api.c */ int api_handle(void); /* returns process exit code */ /* ------------------------------------------------------------------ */ /* --meta */ /* ------------------------------------------------------------------ */ static int mode_meta(void) { printf("{\"name\":\"%s\",\"desc\":\"%s\",\"kind\":\"mcp\",\"mcp\":true," "\"daemon\":false,\"menus\":false,\"verified\":\"live\"," "\"category\":\"devtools\",\"version\":\"%s\"}\n", PLUGIN_NAME, PLUGIN_DESC, PLUGIN_VER); fflush(stdout); return 0; } /* ------------------------------------------------------------------ */ /* --mcp : MCP JSON-RPC 2.0 over stdio */ /* */ /* The contract sx-connector-mcp (and any other MCP host) exercises: */ /* */ /* initialize -> notifications/initialized -> tools/list -> */ /* tools/call */ /* */ /* Rules that matter: */ /* */ /* - one request per line, one response per line, flushed every time. */ /* A host reads stdout blocking, so an unflushed reply is a hang. */ /* - a notification (no "id" member) gets NO response, not an empty */ /* one. Answering a notification is how a router deadlocks. */ /* - the id is echoed back exactly as it arrived (number in, number */ /* out; string in, string out). */ /* - a tool that fails returns a RESULT with isError:true, because */ /* the JSON-RPC call itself succeeded and this is what hosts render */ /* for the user. Only protocol problems are JSON-RPC errors. */ /* ------------------------------------------------------------------ */ static void put_id(buf_t *b, yyjson_val *id) { if (!id) { buf_puts(b, "null"); return; } switch (yyjson_get_type(id)) { case YYJSON_TYPE_STR: json_str(b, yyjson_get_str(id)); break; case YYJSON_TYPE_NUM: if (yyjson_get_subtype(id) == YYJSON_SUBTYPE_UINT) { char t[32]; snprintf(t, sizeof t, "%llu", (unsigned long long)yyjson_get_uint(id)); buf_puts(b, t); } else if (yyjson_get_subtype(id) == YYJSON_SUBTYPE_SINT) { char t[32]; snprintf(t, sizeof t, "%lld", (long long)yyjson_get_sint(id)); buf_puts(b, t); } else { char t[64]; snprintf(t, sizeof t, "%g", yyjson_get_num(id)); buf_puts(b, t); } break; case YYJSON_TYPE_BOOL: buf_puts(b, yyjson_get_bool(id) ? "true" : "false"); break; default: buf_puts(b, "null"); break; } } static void send_result(yyjson_val *id, const char *result_json) { buf_t b; buf_init(&b); buf_puts(&b, "{\"jsonrpc\":\"2.0\",\"id\":"); put_id(&b, id); buf_puts(&b, ",\"result\":"); buf_puts(&b, result_json ? result_json : "{}"); buf_puts(&b, "}"); fputs(buf_str(&b), stdout); fputc('\n', stdout); fflush(stdout); buf_free(&b); } static void send_error(yyjson_val *id, int code, const char *message) { buf_t b; buf_init(&b); buf_puts(&b, "{\"jsonrpc\":\"2.0\",\"id\":"); put_id(&b, id); buf_puts(&b, ",\"error\":{\"code\":"); { char t[16]; snprintf(t, sizeof t, "%d", code); buf_puts(&b, t); } buf_puts(&b, ",\"message\":"); json_str(&b, message ? message : "error"); buf_puts(&b, "}}"); fputs(buf_str(&b), stdout); fputc('\n', stdout); fflush(stdout); buf_free(&b); } /* resources/read serves the same graph the tools read, as one JSON text * under the well-known URI. A subscription notification is not emitted: the * reference server sends resources/updated to subscribers, and this connector * is a single request/response process with no channel to notify on. */ static char *resource_text(void) { tool_out_t t; char *s = NULL; tool_out_init(&t); tool_read_graph(NULL, &t); if (!t.is_error && t.md && t.root) s = yyjson_mut_write(t.md, 0, NULL); tool_free(&t); return s; } static void handle_request(yyjson_val *root, yyjson_val *id, const char *method) { if (strcmp(method, "initialize") == 0) { buf_t b; buf_init(&b); buf_puts(&b, "{\"protocolVersion\":\"" MCP_PROTOCOL "\",\"capabilities\":{\"tools\":{\"listChanged\":false}," "\"resources\":{\"subscribe\":false," "\"listChanged\":false}},\"serverInfo\":{\"name\":\"" SERVER_NAME "\",\"title\":\"Knowledge Graph Memory\"," "\"version\":\"" PLUGIN_VER "\"}}"); send_result(id, buf_str(&b)); buf_free(&b); 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\":[{\"uri\":\"" RESOURCE_URI "\"," "\"name\":\"knowledge-graph\",\"title\":\"Knowledge Graph\"," "\"description\":\"The full knowledge graph with all entities " "and relations\",\"mimeType\":\"application/json\"}]}"); return; } if (strcmp(method, "resources/templates/list") == 0) { send_result(id, "{\"resourceTemplates\":[]}"); return; } if (strcmp(method, "prompts/list") == 0) { send_result(id, "{\"prompts\":[]}"); return; } if (strcmp(method, "resources/read") == 0) { yyjson_val *params = yyjson_obj_get(root, "params"); const char *uri = NULL; char *text; buf_t b; if (params && yyjson_is_obj(params)) { yyjson_val *u = yyjson_obj_get(params, "uri"); if (u && yyjson_is_str(u)) uri = yyjson_get_str(u); } if (!uri) { send_error(id, -32602, "resources/read needs params.uri"); return; } if (strcmp(uri, RESOURCE_URI) != 0) { send_error(id, -32002, "Unknown resource: this server serves " RESOURCE_URI " only"); return; } text = resource_text(); buf_init(&b); buf_puts(&b, "{\"contents\":[{\"uri\":\"" RESOURCE_URI "\",\"mimeType\":\"application/json\",\"text\":"); json_str(&b, text ? text : "{}"); buf_puts(&b, "}]}"); send_result(id, buf_str(&b)); buf_free(&b); free(text); return; } if (strcmp(method, "resources/subscribe") == 0 || strcmp(method, "resources/unsubscribe") == 0) { /* Accepted and ignored: there is no channel to notify on from a * request/response connector, so a host that subscribes must not be * left with an error. */ send_result(id, "{}"); 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 * tools/call whose arguments carry a long observation, and a * truncated line parses as valid-but-wrong JSON rather than failing. */ for (;;) { c = fgetc(stdin); if (c == EOF) { if (n == 0) { free(line); return 0; } break; } if (c == '\n') break; if (c == '\r') continue; 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; /* blank line */ } { 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) { /* No method: either a response to something we never sent, or * a malformed request. A response gets no reply. */ 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 */ yyjson_doc_free(doc); continue; } handle_request(root, id, method); yyjson_doc_free(doc); } } } /* ------------------------------------------------------------------ */ /* main */ /* ------------------------------------------------------------------ */ 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], "--help") == 0) { printf("usage: %s [--meta|--mcp|--schema|--version]\n" "With no arguments this plugin runs as a CGI handler: the\n" "browser page on GET, the JSON API on ?action=... or POST.\n", PLUGIN_ID); return 0; } } if (getenv("SX_PLUGIN_META")) return mode_meta(); if (getenv("SX_PLUGIN_MCP")) return mode_mcp(); return api_handle(); }