scorpiox-bot-plugin-memory
←plugin_memory.cc
402 lines · 14 KBHEADBlameDownload
1/*
2 * plugin_memory.c - entry point for the SCORPIOX BOT knowledge-graph memory
3 * connector.
4 *
5 * One binary, five modes, exactly as the plugin_<name> spec requires:
6 *
7 * 1. --meta / SX_PLUGIN_META=1 -> one line of discovery JSON, exit 0.
8 * Unauthenticated on purpose: /plugins on the node probes it, and the
9 * sx-connector-mcp router probes it before it will run anything else.
10 * 2. --mcp -> MCP JSON-RPC 2.0 over stdio, one request
11 * per line on stdin, one response per line on stdout. This is what makes
12 * the plugin a tool provider for SCORPIOX CODE through the single
13 * sx-connector-mcp router, with no clang change and no extra MCP server
14 * slot.
15 * 3. ?action=... | ?format=json | POST -> the JSON node API the browser UI
16 * talks to. Same nine operations as --mcp, so the UI can never drift
17 * away from what an agent sees.
18 * 4. GET (default) -> the knowledge-graph browser page.
19 * 5. --version -> id + version.
20 *
21 * Modes 3 and 4 sit behind require_node_auth(): the node's :8150 is reachable
22 * from the LAN, so a plugin that reads and writes the operator's knowledge
23 * graph must not answer a bare curl. --meta stays open so discovery works.
24 *
25 * MIT License. Copyright (c) 2026 SCORPIOX INC.
26 */
27
28#if defined(_WIN32) && !defined(_WIN32_WINNT)
29# define _WIN32_WINNT 0x0601
30#endif
31
32#if !defined(_WIN32)
33# define _POSIX_C_SOURCE 200809L
34# define _DEFAULT_SOURCE 1
35# if defined(__APPLE__)
36# define _DARWIN_C_SOURCE 1
37# endif
38#endif
39
40#include <stdio.h>
41#include <stdlib.h>
42#include <string.h>
43#include <ctype.h>
44
45#if defined(_WIN32)
46# define WIN32_LEAN_AND_MEAN
47# include <windows.h>
48# include <io.h>
49# include <fcntl.h>
50/* MinGW's CRT starts stdout in TEXT mode and rewrites every \n we emit into
51 * \r\n. A CGI header block must end with exactly CRLF CRLF; text mode turns
52 * that into \r\r\n\r\r\n, scorpiox-server cannot find the header/body
53 * separator, and the whole reply (headers included) is served as a body. Same
54 * for the MCP loop: a JSON-RPC line with a stray \r confuses line readers.
55 * Force binary stdio before main() runs. */
56__attribute__((constructor))
57static void sx_plugin_binary_stdio(void)
58{
59 _setmode(_fileno(stdout), _O_BINARY);
60 _setmode(_fileno(stdin), _O_BINARY);
61}
62#else
63# include <unistd.h>
64#endif
65
66#include "memory.h"
67
68/* In api.c */
69int api_handle(void); /* returns process exit code */
70
71/* ------------------------------------------------------------------ */
72/* --meta */
73/* ------------------------------------------------------------------ */
74
75static int mode_meta(void)
76{
77 printf("{\"name\":\"%s\",\"desc\":\"%s\",\"kind\":\"mcp\",\"mcp\":true,"
78 "\"daemon\":false,\"menus\":false,\"verified\":\"live\","
79 "\"category\":\"devtools\",\"version\":\"%s\"}\n",
80 PLUGIN_NAME, PLUGIN_DESC, PLUGIN_VER);
81 fflush(stdout);
82 return 0;
83}
84
85/* ------------------------------------------------------------------ */
86/* --mcp : MCP JSON-RPC 2.0 over stdio */
87/* */
88/* The contract sx-connector-mcp (and any other MCP host) exercises: */
89/* */
90/* initialize -> notifications/initialized -> tools/list -> */
91/* tools/call */
92/* */
93/* Rules that matter: */
94/* */
95/* - one request per line, one response per line, flushed every time. */
96/* A host reads stdout blocking, so an unflushed reply is a hang. */
97/* - a notification (no "id" member) gets NO response, not an empty */
98/* one. Answering a notification is how a router deadlocks. */
99/* - the id is echoed back exactly as it arrived (number in, number */
100/* out; string in, string out). */
101/* - a tool that fails returns a RESULT with isError:true, because */
102/* the JSON-RPC call itself succeeded and this is what hosts render */
103/* for the user. Only protocol problems are JSON-RPC errors. */
104/* ------------------------------------------------------------------ */
105
106static void put_id(buf_t *b, yyjson_val *id)
107{
108 if (!id) { buf_puts(b, "null"); return; }
109 switch (yyjson_get_type(id)) {
110 case YYJSON_TYPE_STR:
111 json_str(b, yyjson_get_str(id));
112 break;
113 case YYJSON_TYPE_NUM:
114 if (yyjson_get_subtype(id) == YYJSON_SUBTYPE_UINT) {
115 char t[32];
116 snprintf(t, sizeof t, "%llu",
117 (unsigned long long)yyjson_get_uint(id));
118 buf_puts(b, t);
119 } else if (yyjson_get_subtype(id) == YYJSON_SUBTYPE_SINT) {
120 char t[32];
121 snprintf(t, sizeof t, "%lld", (long long)yyjson_get_sint(id));
122 buf_puts(b, t);
123 } else {
124 char t[64];
125 snprintf(t, sizeof t, "%g", yyjson_get_num(id));
126 buf_puts(b, t);
127 }
128 break;
129 case YYJSON_TYPE_BOOL:
130 buf_puts(b, yyjson_get_bool(id) ? "true" : "false");
131 break;
132 default:
133 buf_puts(b, "null");
134 break;
135 }
136}
137
138static void send_result(yyjson_val *id, const char *result_json)
139{
140 buf_t b;
141 buf_init(&b);
142 buf_puts(&b, "{\"jsonrpc\":\"2.0\",\"id\":");
143 put_id(&b, id);
144 buf_puts(&b, ",\"result\":");
145 buf_puts(&b, result_json ? result_json : "{}");
146 buf_puts(&b, "}");
147 fputs(buf_str(&b), stdout);
148 fputc('\n', stdout);
149 fflush(stdout);
150 buf_free(&b);
151}
152
153static void send_error(yyjson_val *id, int code, const char *message)
154{
155 buf_t b;
156 buf_init(&b);
157 buf_puts(&b, "{\"jsonrpc\":\"2.0\",\"id\":");
158 put_id(&b, id);
159 buf_puts(&b, ",\"error\":{\"code\":");
160 { char t[16]; snprintf(t, sizeof t, "%d", code); buf_puts(&b, t); }
161 buf_puts(&b, ",\"message\":");
162 json_str(&b, message ? message : "error");
163 buf_puts(&b, "}}");
164 fputs(buf_str(&b), stdout);
165 fputc('\n', stdout);
166 fflush(stdout);
167 buf_free(&b);
168}
169
170/* resources/read serves the same graph the tools read, as one JSON text
171 * under the well-known URI. A subscription notification is not emitted: the
172 * reference server sends resources/updated to subscribers, and this connector
173 * is a single request/response process with no channel to notify on. */
174static char *resource_text(void)
175{
176 tool_out_t t;
177 char *s = NULL;
178
179 tool_out_init(&t);
180 tool_read_graph(NULL, &t);
181 if (!t.is_error && t.md && t.root)
182 s = yyjson_mut_write(t.md, 0, NULL);
183 tool_free(&t);
184 return s;
185}
186
187static void handle_request(yyjson_val *root, yyjson_val *id, const char *method)
188{
189 if (strcmp(method, "initialize") == 0) {
190 buf_t b;
191 buf_init(&b);
192 buf_puts(&b, "{\"protocolVersion\":\"" MCP_PROTOCOL
193 "\",\"capabilities\":{\"tools\":{\"listChanged\":false},"
194 "\"resources\":{\"subscribe\":false,"
195 "\"listChanged\":false}},\"serverInfo\":{\"name\":\""
196 SERVER_NAME "\",\"title\":\"Knowledge Graph Memory\","
197 "\"version\":\"" PLUGIN_VER "\"}}");
198 send_result(id, buf_str(&b));
199 buf_free(&b);
200 return;
201 }
202 if (strcmp(method, "ping") == 0) {
203 send_result(id, "{}");
204 return;
205 }
206 if (strcmp(method, "tools/list") == 0) {
207 char *tools = tools_list_json();
208 buf_t b;
209 buf_init(&b);
210 buf_puts(&b, "{\"tools\":");
211 buf_puts(&b, tools ? tools : "[]");
212 buf_puts(&b, "}");
213 send_result(id, buf_str(&b));
214 buf_free(&b);
215 free(tools);
216 return;
217 }
218 if (strcmp(method, "tools/call") == 0) {
219 yyjson_val *params = yyjson_obj_get(root, "params");
220 const char *name = NULL;
221 yyjson_val *args = NULL;
222 tool_out_t t;
223 char *res;
224
225 if (params && yyjson_is_obj(params)) {
226 yyjson_val *nv = yyjson_obj_get(params, "name");
227 if (nv && yyjson_is_str(nv)) name = yyjson_get_str(nv);
228 args = yyjson_obj_get(params, "arguments");
229 if (args && !yyjson_is_obj(args)) args = NULL;
230 }
231 if (!name) {
232 send_error(id, -32602, "tools/call needs params.name");
233 return;
234 }
235 if (tool_dispatch(name, args, &t) != 0) {
236 buf_t b;
237 buf_init(&b);
238 buf_puts(&b, "Unknown tool: ");
239 buf_puts(&b, name);
240 send_error(id, -32602, buf_str(&b));
241 buf_free(&b);
242 tool_free(&t);
243 return;
244 }
245 res = tool_mcp_result(&t);
246 send_result(id, res ? res : "{\"content\":[],\"isError\":true}");
247 free(res);
248 tool_free(&t);
249 return;
250 }
251 if (strcmp(method, "resources/list") == 0) {
252 send_result(id,
253 "{\"resources\":[{\"uri\":\"" RESOURCE_URI "\","
254 "\"name\":\"knowledge-graph\",\"title\":\"Knowledge Graph\","
255 "\"description\":\"The full knowledge graph with all entities "
256 "and relations\",\"mimeType\":\"application/json\"}]}");
257 return;
258 }
259 if (strcmp(method, "resources/templates/list") == 0) {
260 send_result(id, "{\"resourceTemplates\":[]}");
261 return;
262 }
263 if (strcmp(method, "prompts/list") == 0) {
264 send_result(id, "{\"prompts\":[]}");
265 return;
266 }
267 if (strcmp(method, "resources/read") == 0) {
268 yyjson_val *params = yyjson_obj_get(root, "params");
269 const char *uri = NULL;
270 char *text;
271 buf_t b;
272
273 if (params && yyjson_is_obj(params)) {
274 yyjson_val *u = yyjson_obj_get(params, "uri");
275 if (u && yyjson_is_str(u)) uri = yyjson_get_str(u);
276 }
277 if (!uri) { send_error(id, -32602, "resources/read needs params.uri"); return; }
278 if (strcmp(uri, RESOURCE_URI) != 0) {
279 send_error(id, -32002, "Unknown resource: this server serves "
280 RESOURCE_URI " only");
281 return;
282 }
283 text = resource_text();
284 buf_init(&b);
285 buf_puts(&b, "{\"contents\":[{\"uri\":\"" RESOURCE_URI
286 "\",\"mimeType\":\"application/json\",\"text\":");
287 json_str(&b, text ? text : "{}");
288 buf_puts(&b, "}]}");
289 send_result(id, buf_str(&b));
290 buf_free(&b);
291 free(text);
292 return;
293 }
294 if (strcmp(method, "resources/subscribe") == 0 ||
295 strcmp(method, "resources/unsubscribe") == 0) {
296 /* Accepted and ignored: there is no channel to notify on from a
297 * request/response connector, so a host that subscribes must not be
298 * left with an error. */
299 send_result(id, "{}");
300 return;
301 }
302 send_error(id, -32601, "Method not found");
303}
304
305static int mode_mcp(void)
306{
307 char *line = (char *)malloc((size_t)STDIN_LINE_MAX);
308 if (!line) return 1;
309
310 for (;;) {
311 size_t n = 0;
312 int c;
313
314 /* Read one line by hand: fgets with a fixed buffer would truncate a
315 * tools/call whose arguments carry a long observation, and a
316 * truncated line parses as valid-but-wrong JSON rather than failing. */
317 for (;;) {
318 c = fgetc(stdin);
319 if (c == EOF) { if (n == 0) { free(line); return 0; } break; }
320 if (c == '\n') break;
321 if (c == '\r') continue;
322 if (n + 1 < (size_t)STDIN_LINE_MAX) line[n++] = (char)c;
323 }
324 line[n] = '\0';
325 if (n == 0) {
326 if (c == EOF) { free(line); return 0; }
327 continue; /* blank line */
328 }
329
330 {
331 yyjson_doc *doc = yyjson_read(line, n, 0);
332 yyjson_val *root, *mv, *id;
333 const char *method;
334
335 if (!doc) {
336 send_error(NULL, -32700, "Parse error: not valid JSON");
337 continue;
338 }
339 root = yyjson_doc_get_root(doc);
340 if (!root || !yyjson_is_obj(root)) {
341 yyjson_doc_free(doc);
342 send_error(NULL, -32600, "Invalid request: expected an object");
343 continue;
344 }
345 mv = yyjson_obj_get(root, "method");
346 method = (mv && yyjson_is_str(mv)) ? yyjson_get_str(mv) : NULL;
347 id = yyjson_obj_get(root, "id");
348
349 if (!method) {
350 /* No method: either a response to something we never sent, or
351 * a malformed request. A response gets no reply. */
352 yyjson_doc_free(doc);
353 if (yyjson_obj_get(root, "result") ||
354 yyjson_obj_get(root, "error")) continue;
355 send_error(id, -32600, "Invalid request: missing method");
356 continue;
357 }
358 if (!id) { /* notification */
359 yyjson_doc_free(doc);
360 continue;
361 }
362
363 handle_request(root, id, method);
364 yyjson_doc_free(doc);
365 }
366 }
367}
368
369/* ------------------------------------------------------------------ */
370/* main */
371/* ------------------------------------------------------------------ */
372
373int main(int argc, char **argv)
374{
375 int i;
376
377 for (i = 1; i < argc; i++) {
378 if (strcmp(argv[i], "--meta") == 0) return mode_meta();
379 if (strcmp(argv[i], "--mcp") == 0) return mode_mcp();
380 if (strcmp(argv[i], "--version") == 0) {
381 printf("%s %s\n", PLUGIN_ID, PLUGIN_VER);
382 return 0;
383 }
384 if (strcmp(argv[i], "--schema") == 0) {
385 char *t = tools_list_json();
386 printf("%s\n", t ? t : "[]");
387 free(t);
388 return 0;
389 }
390 if (strcmp(argv[i], "--help") == 0) {
391 printf("usage: %s [--meta|--mcp|--schema|--version]\n"
392 "With no arguments this plugin runs as a CGI handler: the\n"
393 "browser page on GET, the JSON API on ?action=... or POST.\n",
394 PLUGIN_ID);
395 return 0;
396 }
397 }
398 if (getenv("SX_PLUGIN_META")) return mode_meta();
399 if (getenv("SX_PLUGIN_MCP")) return mode_mcp();
400
401 return api_handle();
402}