/* * plugin_filesystem - SCORPIOX BOT open-source allowlisted filesystem MCP * connector for your node * * A clean-room rewrite (pure C99, zero dependencies) of the tool surface of * modelcontextprotocol/servers `src/filesystem`, reshaped as a SCORPIOX BOT * connector plugin: ONE binary, FOUR modes. * * 1. --meta / SX_PLUGIN_META=1 -> JSON discovery metadata (unauthenticated) * 2. --mcp -> MCP JSON-RPC 2.0 over stdio * (initialize / tools/list / tools/call) * 3. ?action=... / ?format=json -> JSON control API (require_node_auth) * 4. GET (default) -> Allowed Roots & Permissions page * * Repo: https://plugingit.scorpiox.net/scorpiox-bot-plugin-filesystem.git * * SANDBOX BY CONSTRUCTION. There is no popen, no system, no socket anywhere * in this file: the plugin touches the filesystem and nothing else. Every * path that arrives in a tool call or an HTTP request is canonicalised on the * real filesystem (realpath() on POSIX, GetFullPathNameA + * GetFinalPathNameByHandleA on Windows) and prefix-checked against the * allowlisted roots AFTER symlink resolution. `..`, embedded NUL bytes and * symlinks that point outside the roots are refused with an explicit error. * /proc, /sys and /dev are refused even when they sit under an allowed root. * * Two forms of every root are kept (the configured path AND its realpath), * which is what lets a user configure /tmp on macOS and still reach the * files that realpath resolves under /private/tmp. * * Roots come from * ~/.scorpiox/connectors/plugin_filesystem/roots.json (or the node's * /workspace/.scorpiox/connectors/... equivalent), overridable with the * FS_ALLOWED_ROOTS environment variable for tests, and defaulting to * /workspace or $HOME when nothing is configured. * * MIT License. Copyright (c) 2026 SCORPIOX INC. */ /* Must come before every include on Windows: MinGW defaults to 0x502 * (Server 2003), which hides GetFinalPathNameByHandleA and friends. */ #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 #include #include #include #if defined(_WIN32) # define WIN32_LEAN_AND_MEAN # include # include # include # include /* WIN32_LEAN_AND_MEAN trims the transitive that mingw's * used to drag in, so include it by name - the stat/lstat * helpers below are shared by both platforms. */ # include # include # define SEP '\\' # define PATH_SPLITCH '\\' #else # include # include # include # include # define SEP '/' # define PATH_SPLITCH '/' #endif #include "yyjson.h" #include "bot_theme_plugin.h" #include "ui_html.h" #define PLUGIN_SLUG "filesystem" #define PLUGIN_ID "plugin_filesystem" #define PLUGIN_VER "1.0.1" #define PLUGIN_NAME "filesystem" #define PLUGIN_DESC "Allowlist FS" #define MCP_PROTO "2024-11-05" #define PATH_SZ 4096 #define NAME_SZ 512 #define MAX_ROOTS 16 #define MAX_ENTRIES 5000 /* entries listed per directory */ #define WALK_BUDGET 20000 /* entries visited per tree/search */ #define MAX_RESULTS 1000 /* search_files matches */ #define MAX_DEPTH 24 /* recursive walk guard */ #define READ_CAP ((size_t)10 * 1024 * 1024) /* 10 MiB per file */ #define WRITE_CAP ((size_t)8 * 1024 * 1024) /* 8 MiB body per write */ #define BIN_PROBE 8192 #define IO_CHUNK 65536 #define MCP_LINE_CAP ((size_t)64 * 1024 * 1024) /* one request line */ #define TOOLS_N 11 /* ------------------------------------------------------------------ */ /* Growable byte buffer */ /* ------------------------------------------------------------------ */ typedef struct { char *p; size_t n; size_t cap; } buf_t; static void buf_init(buf_t *b) { b->p = NULL; b->n = 0; b->cap = 0; } static int buf_need(buf_t *b, size_t extra) { size_t want = b->n + extra + 1; char *np; if (want <= b->cap) return 1; if (b->cap == 0) b->cap = 1024; while (b->cap < want) { if (b->cap > (size_t)256 * 1024 * 1024) return 0; b->cap *= 2; } np = (char *)realloc(b->p, b->cap); if (!np) return 0; b->p = np; return 1; } static void buf_add(buf_t *b, const char *s, size_t n) { if (n == 0) return; if (!buf_need(b, n)) return; memcpy(b->p + b->n, s, n); b->n += n; b->p[b->n] = '\0'; } static void buf_puts(buf_t *b, const char *s) { if (s) buf_add(b, s, strlen(s)); } static void buf_putc(buf_t *b, char c) { if (!buf_need(b, 1)) return; b->p[b->n++] = c; b->p[b->n] = '\0'; } static const char *buf_str(buf_t *b) { return b->p ? b->p : ""; } static void buf_printf(buf_t *b, const char *fmt, ...) { char tmp[1024]; va_list ap; int n; va_start(ap, fmt); n = vsnprintf(tmp, sizeof tmp, fmt, ap); va_end(ap); if (n < 0) return; if ((size_t)n < sizeof tmp) { buf_add(b, tmp, (size_t)n); return; } { char *big = (char *)malloc((size_t)n + 1); if (!big) return; va_start(ap, fmt); vsnprintf(big, (size_t)n + 1, fmt, ap); va_end(ap); buf_add(b, big, (size_t)n); free(big); } } static void buf_free(buf_t *b) { free(b->p); b->p = NULL; b->n = 0; b->cap = 0; } /* ------------------------------------------------------------------ */ /* Small utilities */ /* ------------------------------------------------------------------ */ static void str_copy(char *dst, size_t sz, const char *src) { size_t n; if (!dst || sz == 0) return; if (!src) { dst[0] = '\0'; return; } n = strlen(src); if (n >= sz) n = sz - 1; memcpy(dst, src, n); dst[n] = '\0'; } static int str_ieq(const char *a, const char *b) { for (; *a && *b; a++, b++) { if (tolower((unsigned char)*a) != tolower((unsigned char)*b)) return 0; } return *a == *b; } #if defined(_WIN32) static void rstrip_sep(char *s) { size_t n = strlen(s); while (n > 3 && (s[n - 1] == '\\' || s[n - 1] == '/')) s[--n] = '\0'; } #endif static void path_join(char *out, size_t sz, const char *a, const char *b) { size_t n; if (!out || sz == 0) return; out[0] = '\0'; if (!a) a = ""; if (!b) b = ""; str_copy(out, sz, a); n = strlen(out); if (n && out[n - 1] != '/' && out[n - 1] != '\\' && n + 1 < sz) { out[n++] = SEP; out[n] = '\0'; } if (n + strlen(b) < sz) str_copy(out + n, sz - n, b); } static void url_decode(char *s) { char *o = s; if (!s) return; while (*s) { if (*s == '%' && isxdigit((unsigned char)s[1]) && isxdigit((unsigned char)s[2])) { int hi = s[1] <= '9' ? s[1] - '0' : (tolower((unsigned char)s[1]) - 'a' + 10); int lo = s[2] <= '9' ? s[2] - '0' : (tolower((unsigned char)s[2]) - 'a' + 10); *o++ = (char)((hi << 4) | lo); s += 3; } else if (*s == '+') { *o++ = ' '; s++; } else { *o++ = *s++; } } *o = '\0'; } static int get_query_val(const char *qs, const char *key, char *out, size_t outsz) { size_t klen; const char *p; if (!out || outsz == 0) return 0; out[0] = '\0'; if (!qs || !key) return 0; klen = strlen(key); for (p = qs; *p; ) { if (strncmp(p, key, klen) == 0 && p[klen] == '=') { const char *v = p + klen + 1; size_t i = 0; while (*v && *v != '&' && i + 1 < outsz) out[i++] = *v++; out[i] = '\0'; url_decode(out); return 1; } p = strchr(p, '&'); if (!p) break; p++; } return 0; } /* JSON-escape s into b (quotes included). Bytes are passed through so * UTF-8 file content survives; control characters are escaped. */ static void json_str(buf_t *b, const char *s) { buf_putc(b, '"'); for (; s && *s; s++) { unsigned char c = (unsigned char)*s; switch (c) { case '"': buf_puts(b, "\\\""); break; case '\\': buf_puts(b, "\\\\"); break; case '\n': buf_puts(b, "\\n"); break; case '\r': buf_puts(b, "\\r"); break; case '\t': buf_puts(b, "\\t"); break; default: if (c < 0x20) { char tmp[8]; sprintf(tmp, "\\u%04x", c); buf_puts(b, tmp); } else { buf_putc(b, (char)c); } } } buf_putc(b, '"'); } static void fmt_iso(long long t, char *out, size_t sz) { time_t tt = (time_t)t; struct tm tmv; #if defined(_WIN32) gmtime_s(&tmv, &tt); #else gmtime_r(&tt, &tmv); #endif strftime(out, sz, "%Y-%m-%dT%H:%M:%SZ", &tmv); } /* ------------------------------------------------------------------ */ /* yyjson helpers */ /* */ /* yyjson (vendored, MIT, upstream yyjson/yyjson) is the only thing */ /* that touches JSON structure. Requests are read with yyjson_read() */ /* (no insitu, so the request buffer is never mutated and never needs */ /* a terminator), and every response is written through the buf_t */ /* helpers below so a 10 MiB file body is escaped exactly once. */ /* ------------------------------------------------------------------ */ /* JSON strings may carry \u0000. yyjson keeps the whole length but the C * pointer truncates at the NUL, so "a.txt\0secret" would silently become * "a.txt" - a path the caller never asked for. Any string we treat as a path, * pattern or text must therefore be NUL-free; ju_cstr is the gate. */ static const char *ju_cstr(yyjson_val *v) { const char *s; if (!v || !yyjson_is_str(v)) return NULL; s = yyjson_get_str(v); if (!s) return NULL; if (strlen(s) != yyjson_get_len(v)) return NULL; /* embedded NUL */ return s; } static const char *ju_str(yyjson_val *o, const char *key) { if (!o) return NULL; return ju_cstr(yyjson_obj_get(o, key)); } static long long ju_int(yyjson_val *o, const char *key, long long dflt, int *present) { yyjson_val *v; if (present) *present = 0; if (!o) return dflt; v = yyjson_obj_get(o, key); if (!v) return dflt; if (yyjson_is_num(v)) { if (present) *present = 1; return (long long)yyjson_get_num(v); } if (yyjson_is_str(v)) { /* {"head":"20"} is what a * chatty model often sends */ char *endp = NULL; long long n = strtoll(yyjson_get_str(v), &endp, 10); if (endp && *endp == '\0' && endp != yyjson_get_str(v)) { if (present) *present = 1; return n; } } return dflt; } static int ju_bool(yyjson_val *o, const char *key, int dflt) { yyjson_val *v; if (!o) return dflt; v = yyjson_obj_get(o, key); if (!v) return dflt; if (yyjson_is_bool(v)) return yyjson_get_bool(v) ? 1 : 0; if (yyjson_is_str(v)) return str_ieq(yyjson_get_str(v), "true"); if (yyjson_is_int(v)) return yyjson_get_sint(v) != 0; return dflt; } /* Coerce a string field that may arrive as a number (an agent that sends * {"head":20}) instead of "20". Returns 1 when the key exists at all. */ static int ju_field_str(yyjson_val *o, const char *key, char *out, size_t outsz) { yyjson_val *v; if (!o) return 0; v = yyjson_obj_get(o, key); if (!v) return 0; if (yyjson_is_str(v)) { const char *s = ju_cstr(v); if (!s) return 0; /* embedded NUL: refuse, never truncate */ str_copy(out, outsz, s); return 1; } if (yyjson_is_int(v)) { snprintf(out, outsz, "%lld", (long long)yyjson_get_sint(v)); return 1; } if (yyjson_is_uint(v)) { snprintf(out, outsz, "%llu", (unsigned long long)yyjson_get_uint(v)); return 1; } if (yyjson_is_real(v)) { snprintf(out, outsz, "%g", yyjson_get_real(v)); return 1; } if (yyjson_is_bool(v)) { str_copy(out, outsz, yyjson_get_bool(v) ? "true" : "false"); return 1; } return 0; } /* ------------------------------------------------------------------ */ /* Node auth (CGI modes only; --meta and --mcp are exempt) */ /* ------------------------------------------------------------------ */ static void require_node_auth(void) { const char *np = getenv("BOT_PASSWORD"); const char *xp; const char *auth; const char *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); } /* ------------------------------------------------------------------ */ /* Allowed roots */ /* */ /* Each root is stored TWICE where the two forms differ: the path the */ /* operator configured and its canonical realpath. That is what makes */ /* a configured /tmp work on macOS, where realpath answers /private/ */ /* tmp, and it is also what lets the UI show an operator whose root */ /* has drifted (a symlinked home, a mounted volume) before they file */ /* a bug about a tool that "cannot see my files". */ /* ------------------------------------------------------------------ */ typedef struct { char configured[PATH_SZ]; char canonical[PATH_SZ]; int exists; int is_dir; } root_t; static root_t g_roots[MAX_ROOTS]; static int g_root_count; static int g_tool_off[TOOLS_N]; /* permissions: 1 = disabled */ static char g_roots_file[PATH_SZ]; static int deny_count; static char g_deny[MAX_ROOTS][PATH_SZ]; /* Tool names in registration order - the same order tools/list reports. */ static const char *TOOL_NAMES[TOOLS_N] = { "read_text_file", "read_multiple_files", "write_file", "edit_file", "create_directory", "list_directory", "directory_tree", "move_file", "search_files", "get_file_info", "list_allowed_directories" }; static int tool_index(const char *name) { int i; if (!name) return -1; for (i = 0; i < TOOLS_N; i++) if (strcmp(TOOL_NAMES[i], name) == 0) return i; return -1; } /* ------------------------------------------------------------------ */ /* Path canonicalisation */ /* ------------------------------------------------------------------ */ #if defined(_WIN32) static void win_norm(char *s) { for (; *s; s++) { if (*s == '/') *s = '\\'; *s = (char)tolower((unsigned char)*s); } } static int path_under_p(const char *p, const char *root) { char a[PATH_SZ], b[PATH_SZ]; size_t n; str_copy(a, sizeof a, p); str_copy(b, sizeof b, root); win_norm(a); win_norm(b); n = strlen(b); while (n > 3 && b[n - 1] == '\\') b[--n] = '\0'; if (strcmp(a, b) == 0) return 1; if (strncmp(a, b, n) == 0 && a[n] == '\\') return 1; return 0; } #else /* POSIX */ static int path_under_p(const char *p, const char *root) { size_t n; if (!p || !root) return 0; n = strlen(root); if (strcmp(p, root) == 0) return 1; if (n && root[n - 1] == '/') return strncmp(p, root, n) == 0; if (n && strncmp(p, root, n) == 0 && p[n] == '/') return 1; return 0; } #endif /* platform prefix check */ /* Lexical normalisation only: no filesystem access, so it works for a path * that does not exist yet (write_file, create_directory). Because * path_shape_ok() has already rejected every ".." segment, collapsing * separators here cannot be used to walk out of anything. */ static int lexical_abs(const char *raw, char *out, size_t outsz) { size_t i, o = 0; int last_sep = 1; /* the head counts as a sep */ if (!raw || !*raw) return 0; #if defined(_WIN32) { char full[PATH_SZ]; DWORD n = GetFullPathNameA(raw, (DWORD)sizeof full, full, NULL); if (n == 0 || n >= (DWORD)sizeof full) return 0; str_copy(out, outsz, full); rstrip_sep(out); return out[0] ? 1 : 0; } #else if (raw[0] != '/') return 0; if (outsz < 2) return 0; out[o++] = '/'; /* absolute, always */ for (i = 1; raw[i]; i++) { char c = raw[i]; if (c == '\\') c = '/'; if (c == '/') { if (last_sep) continue; if (o + 1 >= outsz) return 0; out[o++] = '/'; last_sep = 1; /* collapse a "." segment: /a/./b behaves as /a/b */ if (raw[i + 1] == '.' && (raw[i + 2] == '/' || raw[i + 2] == '\\' || raw[i + 2] == '\0')) i++; continue; } if (o + 1 >= outsz) return 0; out[o++] = c; last_sep = 0; } if (o == 0) { out[0] = '/'; out[1] = '\0'; return 1; } while (o > 1 && out[o - 1] == '/') o--; out[o] = '\0'; return 1; #endif } /* Lexical form, used when the target does not exist yet. */ static int norm_lex(const char *raw, char *out, size_t outsz) { return lexical_abs(raw, out, outsz); } /* Full canonicalisation: resolves every symlink that exists on disk. */ static int canon_path(const char *raw, char *out, size_t outsz) { #if defined(_WIN32) char full[PATH_SZ]; HANDLE h; char final[PATH_SZ]; if (!lexical_abs(raw, full, sizeof full)) return 0; if (GetFileAttributesA(full) == INVALID_FILE_ATTRIBUTES) return 0; h = CreateFileA(full, 0, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL); if (h != INVALID_HANDLE_VALUE) { DWORD fn = GetFinalPathNameByHandleA(h, final, (DWORD)sizeof final, 0); CloseHandle(h); if (fn > 0 && fn < (DWORD)sizeof final) { char *src = final; if (strncmp(src, "\\\\?\\", 4) == 0) src += 4; str_copy(out, outsz, src); return 1; } } str_copy(out, outsz, full); return 1; #else char *r; char lex[PATH_SZ]; struct stat lst; if (!lexical_abs(raw, lex, sizeof lex)) return 0; if (lstat(lex, &lst) != 0) return 0; /* nothing there to canonicalise */ r = realpath(lex, NULL); if (!r) return 0; str_copy(out, outsz, r); free(r); return 1; #endif } /* Absolute-path shape check. Rejects NUL smuggling attempts, `..` anywhere, * and on POSIX anything not rooted at '/'. */ static int path_shape_ok(const char *raw) { size_t i; if (!raw || !*raw) return 0; if (strlen(raw) >= PATH_SZ) return 0; #if !defined(_WIN32) if (raw[0] != '/') return 0; #else if (!(isalpha((unsigned char)raw[0]) && raw[1] == ':' && (raw[2] == '\\' || raw[2] == '/'))) { if (raw[0] != '/' && raw[0] != '\\') return 0; /* UNC-ish: allowed */ } #endif for (i = 0; raw[i]; i++) { if ((unsigned char)raw[i] < 0x20) return 0; /* control bytes */ } /* `..` is never a legitimate segment: a caller that means the parent * sends the parent's absolute path. Rejecting it outright also kills * %2e%2e and every other encoded variant after url_decode(). */ for (i = 0; raw[i]; i++) { if (raw[i] != '.') continue; if (i > 0 && raw[i - 1] != '/' && raw[i - 1] != '\\') continue; if (raw[i + 1] == '.' && (raw[i + 2] == '/' || raw[i + 2] == '\\' || raw[i + 2] == '\0')) return 0; } return 1; } static int denied_path(const char *p) { int i; for (i = 0; i < deny_count; i++) if (path_under_p(p, g_deny[i])) return 1; #if !defined(_WIN32) { static const char *deny[] = { "/proc", "/sys", "/dev" }; size_t k; for (k = 0; k < sizeof deny / sizeof deny[0]; k++) if (path_under_p(p, deny[k])) return 1; } #else { /* Windows equivalents of "never go here": the registry hives and the * system volume shadow copies live under C:\Windows and C:\System * Volume Information, and a node's own plugin directory is where the * binaries the bot executes sit. */ static const char *deny[] = { "C:\\Windows\\System32\\config", "C:\\System Volume Information" }; size_t k; for (k = 0; k < sizeof deny / sizeof deny[0]; k++) if (path_under_p(p, deny[k])) return 1; } #endif return 0; } static int root_contains(const char *canon) { int i; for (i = 0; i < g_root_count; i++) { if (path_under_p(canon, g_roots[i].canonical)) return i; if (g_roots[i].configured[0] && path_under_p(canon, g_roots[i].configured)) return i; } return -1; } static void parent_of(const char *canon, char *out, size_t outsz) { size_t n; str_copy(out, outsz, canon); n = strlen(out); while (n > 1 && (out[n - 1] == '/' || out[n - 1] == '\\')) out[--n] = '\0'; #if defined(_WIN32) while (n > 3 && out[n - 1] != '\\' && out[n - 1] != '/') out[--n] = '\0'; if (n > 3) out[--n] = '\0'; else str_copy(out, outsz, canon); #else while (n > 1 && out[n - 1] != '/') out[--n] = '\0'; if (n > 1) out[--n] = '\0'; if (!out[0]) str_copy(out, outsz, "/"); #endif } /* Authorise one path for one mode. * mode 'r' - the entry must exist and be inside a root. * mode 'w' - the ENTRY may not exist yet, so its PARENT is the thing that * must exist and stay inside a root; a symlinked leaf that * points out of the sandbox is refused by re-checking the * canonical form of what is already on disk. * On failure returns 0 with a one-line reason in err (never a stack trace: * these strings are what the model reads to decide what to do next). */ static int resolve_allowed(const char *raw, char *out, size_t outsz, char mode, const char **err) { char canon[PATH_SZ], parent[PATH_SZ]; if (!raw || !*raw) { *err = "path is empty"; return 0; } if (!path_shape_ok(raw)) { *err = "path must be absolute and must not contain '..'"; return 0; } if (!canon_path(raw, canon, sizeof canon)) { if (mode == 'r') { *err = "path does not exist"; return 0; } /* The entry does not exist yet (write_file, create_directory): the * lexical form is what we can check, and the parent is what has to * really exist and stay inside a root. */ if (!norm_lex(raw, canon, sizeof canon)) { *err = "path could not be normalised"; return 0; } } if (denied_path(canon)) { *err = "path is on the deny list"; return 0; } if (root_contains(canon) < 0) { *err = "path is outside the allowed directories"; return 0; } if (mode == 'w') { parent_of(canon, parent, sizeof parent); if (strcmp(parent, canon) != 0) { char pc[PATH_SZ]; if (canon_path(parent, pc, sizeof pc)) { if (denied_path(pc)) { *err = "parent directory is denied"; return 0; } if (root_contains(pc) < 0) { *err = "parent directory is outside the allowed directories"; return 0; } } } } str_copy(out, outsz, canon); return 1; } /* ------------------------------------------------------------------ */ /* Config directory + roots.json */ /* ------------------------------------------------------------------ */ /* State lives OUTSIDE the plugin binary path (connector spec §C.1) so it * survives reinstall and container restarts: * $FS_CONNECTORS_DIR// (tests) * /workspace/.scorpiox/connectors// (BotCloud containers) * ~/.scorpiox/connectors// (POSIX) * %LOCALAPPDATA%\\scorpiox\\connectors\\/ (Windows) */ #if defined(_WIN32) static int is_dir_path(const char *p) { DWORD att; if (!p || !*p) return 0; att = GetFileAttributesA(p); return (att != INVALID_FILE_ATTRIBUTES) && (att & FILE_ATTRIBUTE_DIRECTORY); } #else static int is_dir_path(const char *p) { struct stat st; if (!p || !*p) return 0; return (stat(p, &st) == 0) && S_ISDIR(st.st_mode); } #endif static void connectors_dir(char *out, size_t outsz) { const char *env = getenv("FS_CONNECTORS_DIR"); const char *home; if (env && *env) { snprintf(out, outsz, "%s/%s", env, PLUGIN_ID); return; } #if defined(_WIN32) home = getenv("LOCALAPPDATA"); if (!home || !*home) home = getenv("USERPROFILE"); if (home && *home) { snprintf(out, outsz, "%s\\scorpiox\\connectors\\%s", home, PLUGIN_ID); return; } snprintf(out, outsz, ".\\scorpiox-connectors\\%s", PLUGIN_ID); #else if (is_dir_path("/workspace/.scorpiox")) { snprintf(out, outsz, "/workspace/.scorpiox/connectors/%s", PLUGIN_ID); return; } home = getenv("HOME"); if (home && *home) { snprintf(out, outsz, "%s/.scorpiox/connectors/%s", home, PLUGIN_ID); return; } snprintf(out, outsz, "./.scorpiox-connectors/%s", PLUGIN_ID); #endif } /* mkdir -p, portable, mode 0700 (this directory holds operator config). */ static int mkpath(const char *path) { char tmp[PATH_SZ]; char *p; size_t n; str_copy(tmp, sizeof tmp, path); n = strlen(tmp); while (n > 1 && (tmp[n - 1] == '/' || tmp[n - 1] == '\\')) tmp[--n] = '\0'; for (p = tmp + 1; *p; p++) { if (*p != '/' && *p != '\\') continue; *p = '\0'; #if defined(_WIN32) _mkdir(tmp); #else mkdir(tmp, 0700); #endif *p = SEP; } #if defined(_WIN32) if (_mkdir(tmp) == 0 || errno == EEXIST) return 0; return -1; #else if (mkdir(tmp, 0700) == 0 || errno == EEXIST) return 0; return -1; #endif } static void add_root_raw(const char *configured) { char canon[PATH_SZ]; struct stat st; int i; if (g_root_count >= MAX_ROOTS) return; if (!configured || !*configured) return; /* Trim surrounding whitespace and any leftover shell quotes: an operator * who pastes "/data/reports " or '/data/reports' into roots.json means * the directory, not a name with a trailing space. */ { char clean[PATH_SZ]; size_t a = 0, b2 = strlen(configured); while (a < b2 && isspace((unsigned char)configured[a])) a++; while (b2 > a && isspace((unsigned char)configured[b2 - 1])) b2--; if (b2 - a >= 2 && ((configured[a] == '"' && configured[b2 - 1] == '"') || (configured[a] == '\'' && configured[b2 - 1] == '\''))) { a++; b2--; } if (b2 <= a) return; if (b2 - a >= PATH_SZ) return; memcpy(clean, configured + a, b2 - a); clean[b2 - a] = '\0'; if (!path_shape_ok(clean)) return; if (!canon_path(clean, canon, sizeof canon)) return; if (denied_path(canon)) return; } for (i = 0; i < g_root_count; i++) if (strcmp(g_roots[i].canonical, canon) == 0) return; str_copy(g_roots[g_root_count].configured, PATH_SZ, configured); str_copy(g_roots[g_root_count].canonical, PATH_SZ, canon); #if defined(_WIN32) { DWORD att = GetFileAttributesA(canon); g_roots[g_root_count].exists = (att != INVALID_FILE_ATTRIBUTES); g_roots[g_root_count].is_dir = (att != INVALID_FILE_ATTRIBUTES) && (att & FILE_ATTRIBUTE_DIRECTORY); } #else st.st_mode = 0; g_roots[g_root_count].exists = (stat(canon, &st) == 0); g_roots[g_root_count].is_dir = S_ISDIR(st.st_mode); #endif g_root_count++; } static void add_deny(const char *p) { char canon[PATH_SZ]; int i; if (deny_count >= MAX_ROOTS) return; if (!p || !*p) return; if (!path_shape_ok(p)) return; if (!canon_path(p, canon, sizeof canon)) str_copy(canon, sizeof canon, p); for (i = 0; i < deny_count; i++) if (strcmp(g_deny[i], canon) == 0) return; str_copy(g_deny[deny_count++], PATH_SZ, canon); } /* roots.json: {"roots":["/data","/srv"],"denied":["/data/secret"], * "permissions":{"write_file":false,...}} * A missing or unreadable file is not an error - the defaults below apply. */ static int load_roots_file(void) { FILE *f; long sz; char *txt; yyjson_doc *doc; yyjson_val *root, *arr, *perm, *it; size_t i, max; int loaded = 0; if (!g_roots_file[0]) { char dir[PATH_SZ]; connectors_dir(dir, sizeof dir); snprintf(g_roots_file, sizeof g_roots_file, "%s", dir); if (g_roots_file[0]) { size_t dl = strlen(g_roots_file); if (dl + 12 < sizeof g_roots_file) { g_roots_file[dl] = SEP; g_roots_file[dl + 1] = '\0'; str_copy(g_roots_file + dl + 1, sizeof g_roots_file - dl - 1, "roots.json"); } } } f = fopen(g_roots_file, "rb"); if (!f) return 0; if (fseek(f, 0, SEEK_END) != 0) { fclose(f); return 0; } sz = ftell(f); if (sz < 0 || (size_t)sz > 256 * 1024) { fclose(f); return 0; } rewind(f); txt = (char *)malloc((size_t)sz + 1); if (!txt) { fclose(f); return 0; } if (fread(txt, 1, (size_t)sz, f) != (size_t)sz) { free(txt); fclose(f); return 0; } txt[sz] = '\0'; fclose(f); doc = yyjson_read(txt, (size_t)sz, 0); free(txt); if (!doc) return 0; root = yyjson_doc_get_root(doc); if (!yyjson_is_obj(root)) { yyjson_doc_free(doc); return 0; } arr = yyjson_obj_get(root, "roots"); if (yyjson_is_arr(arr)) { max = yyjson_arr_size(arr); for (i = 0; i < max; i++) { it = yyjson_arr_get(arr, i); if (yyjson_is_str(it)) { add_root_raw(yyjson_get_str(it)); loaded = 1; } } } arr = yyjson_obj_get(root, "denied"); if (yyjson_is_arr(arr)) { max = yyjson_arr_size(arr); for (i = 0; i < max; i++) { it = yyjson_arr_get(arr, i); if (yyjson_is_str(it)) add_deny(yyjson_get_str(it)); } } perm = yyjson_obj_get(root, "permissions"); if (yyjson_is_obj(perm)) { for (i = 0; i < (size_t)TOOLS_N; i++) { yyjson_val *v = yyjson_obj_get(perm, TOOL_NAMES[i]); if (v && yyjson_is_bool(v) && !yyjson_get_bool(v)) g_tool_off[i] = 1; } loaded = 1; } yyjson_doc_free(doc); return loaded; } static void init_roots(void) { const char *extra; const char *home; if (g_root_count) return; /* 1. $FS_ALLOWED_ROOTS always wins - tests and one-shot operator overrides * must not need a file, and a connector that cannot be pointed at a * fixture tree cannot be tested at all. */ extra = getenv("FS_ALLOWED_ROOTS"); if (extra && *extra) { char copy[PATH_SZ]; char *tok; char delim; #if defined(_WIN32) delim = ';'; /* ':' is drive syntax on NT */ #else delim = ':'; #endif str_copy(copy, sizeof copy, extra); tok = copy; while (tok && *tok) { char *nx = strchr(tok, delim); if (nx) *nx++ = '\0'; add_root_raw(tok); tok = nx; } if (g_root_count) return; } /* 2. operator config */ if (load_roots_file() && g_root_count) return; /* 3. defaults: the two places a node actually keeps user files. */ #if defined(_WIN32) home = getenv("USERPROFILE"); if (home && *home) add_root_raw(home); { const char *d = getenv("DRIVE"); char buf[PATH_SZ]; if (d && *d) { snprintf(buf, sizeof buf, "%s:\\codebases", d); add_root_raw(buf); } add_root_raw("D:\\codebases"); } #else if (is_dir_path("/workspace")) add_root_raw("/workspace"); home = getenv("HOME"); if (home && *home) add_root_raw(home); if (g_root_count == 0) add_root_raw("/tmp"); /* last resort, still scoped */ #endif } /* ------------------------------------------------------------------ */ /* Filesystem primitives */ /* ------------------------------------------------------------------ */ static int is_regular(const char *p) { #if defined(_WIN32) DWORD att = GetFileAttributesA(p); if (att == INVALID_FILE_ATTRIBUTES) return 0; return !(att & FILE_ATTRIBUTE_DIRECTORY); #else struct stat st; if (lstat(p, &st) != 0) return 0; return S_ISREG(st.st_mode); #endif } static int is_link_path(const char *p) { #if defined(_WIN32) DWORD att = GetFileAttributesA(p); return (att != INVALID_FILE_ATTRIBUTES) && (att & FILE_ATTRIBUTE_REPARSE_POINT); #else struct stat st; return (lstat(p, &st) == 0) && S_ISLNK(st.st_mode); #endif } static long long file_size(const char *p) { #if defined(_WIN32) WIN32_FILE_ATTRIBUTE_DATA d; LARGE_INTEGER li; if (!GetFileAttributesExA(p, GetFileExInfoStandard, &d)) return -1; li.HighPart = d.nFileSizeHigh; li.LowPart = d.nFileSizeLow; return (long long)li.QuadPart; #else struct stat st; if (stat(p, &st) != 0) return -1; return (long long)st.st_size; #endif } static long long file_mtime(const char *p) { #if defined(_WIN32) WIN32_FILE_ATTRIBUTE_DATA d; FILETIME ft; ULARGE_INTEGER u; if (!GetFileAttributesExA(p, GetFileExInfoStandard, &d)) return 0; ft = d.ftLastWriteTime; u.LowPart = ft.dwLowDateTime; u.HighPart = ft.dwHighDateTime; return (long long)(u.QuadPart / 10000000ULL - 11644473600ULL); #else struct stat st; if (stat(p, &st) != 0) return 0; return (long long)st.st_mtime; #endif } static unsigned file_mode(const char *p) { #if defined(_WIN32) DWORD att = GetFileAttributesA(p); unsigned m = 0; if (att == INVALID_FILE_ATTRIBUTES) return 0; m |= 0700; if (!(att & FILE_ATTRIBUTE_READONLY)) m |= 0222; if (att & FILE_ATTRIBUTE_DIRECTORY) m |= 0111; return m; #else struct stat st; if (stat(p, &st) != 0) return 0; return (unsigned)(st.st_mode & 07777); #endif } /* Read the whole file (capped) into b. Sets *binary when a NUL shows up in * the first BIN_PROBE bytes - the same probe the read-only browser uses, so * both plugins agree on what "binary" means on this node. */ static int read_whole(const char *path, buf_t *b, size_t cap, int *binary, const char **err) { FILE *f; long long sz; char chunk[IO_CHUNK]; size_t total = 0; int probed = 0; if (binary) *binary = 0; sz = file_size(path); if (sz < 0) { *err = "cannot stat file"; return 0; } if ((size_t)sz > cap) { *err = "file is larger than the read limit"; return 0; } f = fopen(path, "rb"); if (!f) { *err = (errno == EACCES) ? "permission denied" : "cannot open file"; return 0; } for (;;) { size_t n = fread(chunk, 1, sizeof chunk, f); if (n == 0) break; if (!binary) { /* fall through */ } else if (!probed) { size_t i, stop = n < BIN_PROBE ? n : BIN_PROBE; for (i = 0; i < stop; i++) if (chunk[i] == '\0') { *binary = 1; break; } if (total + n >= BIN_PROBE) probed = 1; } buf_add(b, chunk, n); total += n; if (total > cap) { fclose(f); *err = "file is larger than the read limit"; return 0; } } fclose(f); if (binary && !probed) { /* small file: probe what we have */ size_t i, stop = b->n < BIN_PROBE ? b->n : BIN_PROBE; for (i = 0; i < stop; i++) if (b->p && b->p[i] == '\0') { *binary = 1; break; } } *err = NULL; return 1; } /* First n lines, joined with a single \n and with no trailing newline - * the same shape upstream headFile returns, so a caller that counts * newlines counts lines and not an extra blank one. */ static void text_head(const char *s, size_t len, long n, buf_t *out) { size_t i = 0; long lines = 0; if (n < 0) { buf_add(out, s, len); return; } if (n == 0) return; while (i < len && lines < n) { size_t start = i, e = i; while (e < len && s[e] != '\n') e++; if (lines) buf_putc(out, '\n'); if (e > start && s[e - 1] == '\r') e--; /* CRLF normalised */ buf_add(out, s + start, e - start); lines++; i = (e < len) ? e + 1 : len; } } /* Last n lines. A trailing newline ends the last line rather than starting an * empty one, so "a\nb\n" with tail=1 is "b\n" - the same reading the upstream * tailFile takes, and the one that stops an off-by-one from appearing as * "tail 1 gave me a blank line". */ static void text_tail(const char *s, size_t len, long n, buf_t *out) { size_t end = len; long lines = 0; size_t i; if (n < 0) { buf_add(out, s, len); return; } if (n == 0 || len == 0) return; while (end > 0 && (s[end - 1] == '\n' || s[end - 1] == '\r')) end--; if (end == 0) return; for (i = end; i > 0; ) { i--; if (s[i] == '\n') { lines++; if (lines >= n) { i++; break; } } } buf_add(out, s + i, end - i); } /* Write content atomically: write to .tmp-, flush to disk, then * rename over the target. A crash mid-write therefore leaves either the old * file or the new one, never a half-written file - which matters because the * whole point of this connector is that an agent edits files unattended. */ static int write_atomic(const char *path, const char *content, size_t len, const char **err) { char tmp[PATH_SZ]; FILE *f; int rc = 0; snprintf(tmp, sizeof tmp, "%s.tmp-%ld", path, (long) #if defined(_WIN32) GetCurrentProcessId() #else (long)getpid() #endif ); f = fopen(tmp, "wb"); if (!f) { *err = "cannot create temporary file"; return 0; } if (len && fwrite(content, 1, len, f) != len) { fclose(f); #if !defined(_WIN32) remove(tmp); #else DeleteFileA(tmp); #endif *err = "write failed (disk full?)"; return 0; } if (fflush(f) != 0) { fclose(f); rc = 0; *err = "flush failed"; } else { #if !defined(_WIN32) fflush(f); fsync(fileno(f)); #endif fclose(f); rc = 1; } if (!rc) return 0; #if defined(_WIN32) /* Windows rename() refuses to replace an existing file. */ { char bak[PATH_SZ]; snprintf(bak, sizeof bak, "%s.bak-%ld", path, (long)GetCurrentProcessId()); MoveFileExA(tmp, path, MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH); if (GetFileAttributesA(tmp) != INVALID_FILE_ATTRIBUTES) { /* fallback: copy over then delete the temp */ CopyFileA(tmp, path, FALSE); DeleteFileA(tmp); (void)bak; } if (GetFileAttributesA(path) == INVALID_FILE_ATTRIBUTES) { *err = "rename failed"; return 0; } } #else if (rename(tmp, path) != 0) { remove(tmp); *err = "rename failed"; return 0; } #endif *err = NULL; return 1; } static int ensure_parent(const char *path) { char parent[PATH_SZ]; parent_of(path, parent, sizeof parent); if (strcmp(parent, path) == 0) return 0; return mkpath(parent); } static int mkdir_p(const char *path) { return mkpath(path); } static int copy_file(const char *src, const char *dst, const char **err) { FILE *in, *out; char chunk[IO_CHUNK]; size_t n; in = fopen(src, "rb"); if (!in) { *err = "cannot open source"; return 0; } if (ensure_parent(dst) != 0) { fclose(in); *err = "cannot create destination directory"; return 0; } out = fopen(dst, "wb"); if (!out) { fclose(in); *err = "cannot create destination"; return 0; } while ((n = fread(chunk, 1, sizeof chunk, in)) > 0) { if (fwrite(chunk, 1, n, out) != n) { fclose(in); fclose(out); *err = "copy failed (disk full?)"; return 0; } } if (ferror(in)) { fclose(in); fclose(out); *err = "read error"; return 0; } fclose(in); if (fflush(out) != 0) { fclose(out); *err = "flush failed"; return 0; } fclose(out); *err = NULL; return 1; } /* ------------------------------------------------------------------ */ /* Glob matching */ /* */ /* search_files and excludePatterns need minimatch's useful subset with */ /* no dependency: '*' and '?' within one path segment, '**' across */ /* segments, and brace-free patterns. A pattern with no separator is */ /* matched against the file NAME as well as the relative path, which is */ /* what makes "*.log" behave like a person expects. */ /* ------------------------------------------------------------------ */ static int glob_here(const char *pat, const char *s, int slash_means_end) { while (*pat) { if (pat[0] == '*' && pat[1] == '*') { const char *p2 = pat + 2; if (*p2 == '/') p2++; if (!*p2) return 1; /* ** matches rest */ for (;;) { if (glob_here(p2, s, 0)) return 1; while (*s && *s != '/') s++; if (*s == '/') s++; else break; } return 0; } if (*pat == '*') { const char *p2 = pat + 1; if (slash_means_end) { for (;;) { if (glob_here(p2, s, slash_means_end)) return 1; if (*s == '/' || *s == '\\') return 0; if (!*s) return 0; s++; } } for (;;) { if (glob_here(p2, s, slash_means_end)) return 1; if (!*s) return 0; s++; } } if (*pat == '?') { if (!*s || *s == '/') return 0; pat++; s++; continue; } if (*pat != *s) return 0; pat++; s++; } return *s == '\0'; } static int glob_match(const char *pat, const char *s) { if (!pat || !s) return 0; return glob_here(pat, s, 1); } /* Excludes follow upstream isExcludedPath: a pattern with a star is matched * on the relative path (and a trailing double-star-slash also matches the * directory itself); a plain name matches at any depth. */ static int is_excluded(const char *relpath, int is_dir, yyjson_val *excludes) { size_t i, max; if (!excludes || !yyjson_is_arr(excludes)) return 0; max = yyjson_arr_size(excludes); for (i = 0; i < max; i++) { yyjson_val *v = yyjson_arr_get(excludes, i); const char *pat; char buf[NAME_SZ * 4]; if (!yyjson_is_str(v)) continue; pat = yyjson_get_str(v); if (!pat || !*pat) continue; if (strchr(pat, '*')) { if (glob_match(pat, relpath)) return 1; { size_t pl = strlen(pat); if (pl > 3 && !strcmp(pat + pl - 3, "/**")) { char cut[NAME_SZ * 4]; str_copy(cut, sizeof cut, pat); cut[pl - 3] = '\0'; if (is_dir && glob_match(cut, relpath)) return 1; } } continue; } if (glob_match(pat, relpath)) return 1; snprintf(buf, sizeof buf, "**/%s", pat); if (glob_match(buf, relpath)) return 1; if (is_dir) { snprintf(buf, sizeof buf, "**/%s/**", pat); if (glob_match(buf, relpath)) return 1; } } return 0; } /* ------------------------------------------------------------------ */ /* Unified diff (enough of it to read like git's) */ /* ------------------------------------------------------------------ */ typedef struct { char **line; size_t n; } lines_t; static void lines_split(const char *s, size_t len, lines_t *out) { size_t cap = 64, n = 0, start = 0, i; char **v = (char **)malloc(cap * sizeof *v); out->line = NULL; out->n = 0; if (!v) return; for (i = 0; i <= len; i++) { if (i == len || s[i] == '\n') { size_t sl = i - start; char *ln; if (sl && s[start + sl - 1] == '\r') sl--; /* compare LF-only */ ln = (char *)malloc(sl + 1); if (!ln) break; memcpy(ln, s + start, sl); ln[sl] = '\0'; if (n == cap) { char **nv; cap *= 2; nv = (char **)realloc(v, cap * sizeof *v); if (!nv) { free(ln); break; } v = nv; } v[n++] = ln; start = i + 1; if (i == len) break; } } out->line = v; out->n = n; } static void lines_free(lines_t *l) { size_t i; for (i = 0; i < l->n; i++) free(l->line[i]); free(l->line); l->line = NULL; l->n = 0; } /* Append one @@ hunk with its context. */ static void diff_hunk(buf_t *out, lines_t *a, lines_t *b, size_t a0, size_t a1, size_t b0, size_t b1) { size_t i; if (a1 > a0 || b1 > b0) { buf_printf(out, "@@ -%u,%u +%u,%u @@\n", (unsigned)(a0 + 1), (unsigned)(a1 - a0), (unsigned)(b0 + 1), (unsigned)(b1 - b0)); for (i = a0; i < a1; i++) { buf_putc(out, '-'); buf_puts(out, a->line[i]); buf_putc(out, '\n'); } for (i = b0; i < b1; i++) { buf_putc(out, '+'); buf_puts(out, b->line[i]); buf_putc(out, '\n'); } } } /* A deliberately simple LCS-free diff: match the common prefix and suffix, * then report the middle as one remove/add pair. Real git diffs of agent * edits are almost always local, and a wrong-but-labelled diff is worse than * a coarse honest one, so nothing here pretends to be Myers. */ static void make_diff(buf_t *out, const char *an, size_t alen, const char *bn, size_t blen, const char *name) { lines_t a, b; size_t pre = 0, suf = 0; lines_split(an, alen, &a); lines_split(bn, blen, &b); while (pre < a.n && pre < b.n && !strcmp(a.line[pre], b.line[pre])) pre++; while (suf + pre < a.n && suf + pre < b.n && !strcmp(a.line[a.n - 1 - suf], b.line[b.n - 1 - suf])) suf++; buf_printf(out, "--- %s\n+++ %s\n", name, name); if (a.n == b.n && pre == a.n) { buf_puts(out, "(no changes)\n"); } else { diff_hunk(out, &a, &b, pre, a.n - suf, pre, b.n - suf); } lines_free(&a); lines_free(&b); } /* ------------------------------------------------------------------ */ /* Directory helpers */ /* ------------------------------------------------------------------ */ typedef struct { char name[NAME_SZ]; int is_dir; int is_link; long long size; long long mtime; } dent_t; static int cmp_dent(const void *x, const void *y) { const dent_t *a = (const dent_t *)x, *b = (const dent_t *)y; if (a->is_dir != b->is_dir) return a->is_dir ? -1 : 1; /* dirs first */ return strcmp(a->name, b->name); } /* Read one directory, sorted, capped. Returns count or -1. */ static long list_dir(const char *path, dent_t **out, const char **err) { dent_t *v = NULL; long n = 0, cap = 0; #if !defined(_WIN32) DIR *d; struct dirent *de; d = opendir(path); if (!d) { *err = (errno == EACCES) ? "permission denied" : (errno == ENOENT) ? "path does not exist" : "cannot read directory"; return -1; } while ((de = readdir(d)) != NULL) { char full[PATH_SZ]; dent_t e; if (!strcmp(de->d_name, ".") || !strcmp(de->d_name, "..")) continue; if (n == cap) { dent_t *nv; cap = cap ? cap * 2 : 128; if (cap > MAX_ENTRIES) cap = MAX_ENTRIES; nv = (dent_t *)realloc(v, (size_t)cap * sizeof *v); if (!nv) break; v = nv; } if (n >= MAX_ENTRIES) break; memset(&e, 0, sizeof e); str_copy(e.name, sizeof e.name, de->d_name); path_join(full, sizeof full, path, de->d_name); e.is_link = is_link_path(full); e.is_dir = is_dir_path(full); e.size = e.is_dir ? 0 : file_size(full); e.mtime = file_mtime(full); v[n++] = e; } closedir(d); #else WIN32_FIND_DATAA fd; HANDLE h; char pat[PATH_SZ]; snprintf(pat, sizeof pat, "%s\\*", path); h = FindFirstFileA(pat, &fd); if (h == INVALID_HANDLE_VALUE) { *err = "cannot read directory"; return -1; } do { char full[PATH_SZ]; dent_t e; if (!strcmp(fd.cFileName, ".") || !strcmp(fd.cFileName, "..")) continue; if (n == cap) { dent_t *nv; cap = cap ? cap * 2 : 128; if (cap > MAX_ENTRIES) cap = MAX_ENTRIES; nv = (dent_t *)realloc(v, (size_t)cap * sizeof *v); if (!nv) break; v = nv; } if (n >= MAX_ENTRIES) break; memset(&e, 0, sizeof e); str_copy(e.name, sizeof e.name, fd.cFileName); path_join(full, sizeof full, path, fd.cFileName); e.is_link = (fd.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT) != 0; e.is_dir = (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0; { ULARGE_INTEGER u; u.LowPart = fd.nFileSizeLow; u.HighPart = fd.nFileSizeHigh; e.size = e.is_dir ? 0 : (long long)u.QuadPart; } { ULARGE_INTEGER u; u.LowPart = fd.ftLastWriteTime.dwLowDateTime; u.HighPart = fd.ftLastWriteTime.dwHighDateTime; e.mtime = (long long)(u.QuadPart / 10000000ULL - 11644473600ULL); } v[n++] = e; } while (FindNextFileA(h, &fd)); FindClose(h); #endif if (n > 1) qsort(v, (size_t)n, sizeof *v, cmp_dent); *out = v; *err = NULL; return n; } /* ------------------------------------------------------------------ */ /* MCP tools */ /* */ /* Each handler appends either the result text or a one-line reason to */ /* *text and returns 0 (result) or 1 (isError). The dispatcher wraps */ /* the text into {"content":[{"type":"text","text":...}],"isError":b}, */ /* which is exactly what scorpiox-connector-mcp relays upstream. */ /* */ /* Error text is written for the MODEL, not for a log: it names the */ /* path, says which rule refused it, and (where there is one) what to */ /* do instead. "permission denied" alone sends an agent in circles. */ /* ------------------------------------------------------------------ */ typedef int (*tool_fn)(yyjson_val *args, buf_t *text); /* Refuse the "binary" case in a way that tells the caller what to use. */ #define BINARY_HINT "file contains binary bytes; read_text_file returns text only - use get_file_info for metadata, or the files plugin to view it" static int tool_read_text_file(yyjson_val *args, buf_t *text) { char raw[PATH_SZ], canon[PATH_SZ]; const char *err = NULL; buf_t b; int have_head = 0, have_tail = 0; long head = -1, tail = -1; int binary = 0; if (!ju_field_str(args, "path", raw, sizeof raw)) return (buf_puts(text, "missing required parameter \"path\""), 1); if (!resolve_allowed(raw, canon, sizeof canon, 'r', &err)) return (buf_printf(text, "%s: %s", raw, err ? err : "refused"), 1); if (!is_regular(canon)) return (buf_printf(text, "%s: not a regular file", raw), 1); head = ju_int(args, "head", -1, &have_head); tail = ju_int(args, "tail", -1, &have_tail); if (head < -1 || tail < -1) return (buf_puts(text, "head and tail must be non-negative integers"), 1); buf_init(&b); if (!read_whole(canon, &b, READ_CAP, &binary, &err)) { buf_printf(text, "%s: %s", raw, err ? err : "read failed"); buf_free(&b); return 1; } if (binary) { buf_printf(text, "%s: " BINARY_HINT, raw); buf_free(&b); return 1; } if (have_head && have_tail) { buf_puts(text, "head and tail are mutually exclusive - send one or the other"); buf_free(&b); return 1; } if (have_head) text_head(b.p ? b.p : "", b.n, head, text); else if (have_tail) text_tail(b.p ? b.p : "", b.n, tail, text); else buf_add(text, b.p ? b.p : "", b.n); buf_free(&b); return 0; } /* One element of read_multiple_files. Kept as a function so the loop that * drives it stays readable. */ static void read_one_path(const char *path, buf_t *out, int *first) { char canon[PATH_SZ]; const char *err = NULL; buf_t b; int binary = 0; /* each item below terminates with its own newline, so the separator is * "--- " and not " --- " - that is what makes the output byte-split * on a line of three dashes, exactly like upstream */ if (!*first) buf_puts(out, "---\n"); *first = 0; if (!resolve_allowed(path, canon, sizeof canon, 'r', &err)) { buf_printf(out, "%s: Error - %s\n", path, err ? err : "refused"); return; } if (!is_regular(canon)) { buf_printf(out, "%s: Error - not a regular file\n", path); return; } buf_init(&b); if (!read_whole(canon, &b, READ_CAP, &binary, &err)) { buf_printf(out, "%s: Error - %s\n", path, err ? err : "read failed"); buf_free(&b); return; } if (binary) { buf_printf(out, "%s: Error - binary file\n", path); buf_free(&b); return; } buf_printf(out, "%s:\n", path); buf_add(out, b.p ? b.p : "", b.n); buf_putc(out, '\n'); buf_free(&b); } static int tool_read_multiple_files(yyjson_val *args, buf_t *text) { yyjson_val *arr = args ? yyjson_obj_get(args, "paths") : NULL; size_t i, max; int first = 1; if (!arr || !yyjson_is_arr(arr) || yyjson_arr_size(arr) == 0) return (buf_puts(text, "missing required parameter \"paths\" (a non-empty array of strings)"), 1); max = yyjson_arr_size(arr); if (max > 200) max = 200; /* one call must not swallow a node */ for (i = 0; i < max; i++) { yyjson_val *v = yyjson_arr_get(arr, i); const char *pv = ju_cstr(v); /* NUL-safe: never a truncated path */ if (pv && pv[0]) read_one_path(pv, text, &first); } return 0; } static int tool_write_file(yyjson_val *args, buf_t *text) { char raw[PATH_SZ], canon[PATH_SZ]; const char *err = NULL; const char *content; size_t clen; if (!ju_field_str(args, "path", raw, sizeof raw)) return (buf_puts(text, "missing required parameter \"path\""), 1); if (!resolve_allowed(raw, canon, sizeof canon, 'w', &err)) return (buf_printf(text, "%s: %s", raw, err ? err : "refused"), 1); if (is_dir_path(canon)) return (buf_printf(text, "%s: that is a directory", raw), 1); if (is_link_path(canon)) return (buf_printf(text, "%s: refusing to write through a symlink", raw), 1); { yyjson_val *cv = args ? yyjson_obj_get(args, "content") : NULL; if (!cv) return (buf_puts(text, "missing required parameter \"content\""), 1); if (!yyjson_is_str(cv)) return (buf_puts(text, "\"content\" must be a string"), 1); content = yyjson_get_str(cv); clen = yyjson_get_len(cv); } if (clen > WRITE_CAP) return (buf_printf(text, "content is %llu bytes (limit %llu)", (unsigned long long)clen, (unsigned long long)WRITE_CAP), 1); if (ensure_parent(canon) != 0) return (buf_printf(text, "%s: cannot create the parent directory", raw), 1); if (!write_atomic(canon, content, clen, &err)) return (buf_printf(text, "%s: %s", raw, err ? err : "write failed"), 1); buf_printf(text, "Successfully wrote %llu bytes to %s", (unsigned long long)clen, raw); return 0; } /* ------------------------------------------------------------------ */ /* edit_file */ /* */ /* Upstream semantics, kept: edits apply in order, each to the result */ /* of the ones before it; each replaces the FIRST match of oldText; */ /* an exact match wins, and when there is none a run of whole lines */ /* matches if each line is equal once leading and trailing whitespace */ /* is ignored (newText then takes the file's indentation is NOT */ /* re-derived - we keep the caller's text and say so in the diff); if */ /* ANY edit has no match NOTHING is written and the error shows where */ /* the file diverges; dryRun computes and returns the diff without */ /* touching the disk. The file's own line ending is detected and */ /* restored. */ /* ------------------------------------------------------------------ */ /* Find `needle` in `hay` (exact). Returns offset or (size_t)-1. */ static size_t find_sub(const char *hay, size_t hlen, const char *needle, size_t nlen) { size_t i; if (nlen == 0 || nlen > hlen) return (size_t)-1; for (i = 0; i + nlen <= hlen; i++) if (!memcmp(hay + i, needle, nlen)) return i; return (size_t)-1; } /* Whitespace-insensitive whole-line match. Returns start offset of the * matching region and sets *endlen, or (size_t)-1. The match must start at * a line boundary and the compared run must be followed by a newline when * oldText ends with one. */ static size_t find_lines(const char *hay, size_t hlen, const char *needle, size_t nlen, size_t *matchlen) { /* Split needle into lines (LF-only, trailing \n dropped). */ char *ndup; char *nl[64]; size_t nlines = 0, i, start = 0; char *hl[4096]; size_t hlines = 0, pos[4097]; size_t cand; *matchlen = 0; if (nlen == 0) return (size_t)-1; ndup = (char *)malloc(nlen + 1); if (!ndup) return (size_t)-1; memcpy(ndup, needle, nlen); ndup[nlen] = '\0'; if (nlen && ndup[nlen - 1] == '\n') ndup[nlen - 1] = '\0'; for (i = 0; ndup[i]; i++) { if (ndup[i] == '\r') ndup[i] = '\0'; if (ndup[i] == '\n') { ndup[i] = '\0'; if (nlines < 64) nl[nlines++] = ndup + start; start = i + 1; } } if (nlines < 64) nl[nlines++] = ndup + start; /* oldText ended with a newline: that trailing "" is not a line to match, * and the boundary is enforced separately below. */ if (nlen && needle[nlen - 1] == '\n' && nlines > 1 && nl[nlines - 1][0] == '\0') nlines--; if (nlines == 0 || nlines > 64) { free(ndup); return (size_t)-1; } /* Split haystack into lines, remembering offsets. */ start = 0; for (i = 0; i <= hlen; i++) { if (i == hlen || hay[i] == '\n') { if (hlines < 4096) { size_t lstart = start, lend = i; /* strip a trailing \r for comparison, keep the byte in place */ pos[hlines] = lstart; { size_t sl = lstart, el = lend; char *dup; if (el > sl && hay[el - 1] == '\r') el--; dup = (char *)malloc(el - sl + 1); if (!dup) { size_t k; for (k = 0; k < hlines; k++) free(hl[k]); free(ndup); return (size_t)-1; } memcpy(dup, hay + sl, el - sl); dup[el - sl] = '\0'; hl[hlines] = dup; } hlines++; } start = i + 1; if (i == hlen) break; } } if (hlines + 1 > 4096) { hlines = 4096; } for (cand = 0; cand + nlines <= hlines && cand + nlines <= 4096; cand++) { size_t j, ok = 1; for (j = 0; j < nlines; j++) { const char *a = nl[j], *b = hl[cand + j]; while (*a == ' ' || *a == '\t') a++; while (*b == ' ' || *b == '\t') b++; { size_t la = strlen(a), lb = strlen(b); while (la && (a[la - 1] == ' ' || a[la - 1] == '\t')) la--; while (lb && (b[lb - 1] == ' ' || b[lb - 1] == '\t')) lb--; if (la != lb || memcmp(a, b, la)) { ok = 0; break; } } } if (ok) { size_t s = pos[cand]; size_t e = pos[cand + nlines - 1]; /* The run must land on line boundaries. The last matched line * ends at its newline (or at EOF); when oldText itself asked for * the newline it is part of the match, when it did not the * file's own newline is left alone - which is what keeps an edit * from silently deleting the file's trailing newline. */ while (e < hlen && hay[e] != '\n') e++; if (needle[nlen - 1] == '\n') { if (e == hlen) { /* no newline to consume */ size_t k; for (k = 0; k < hlines; k++) free(hl[k]); free(ndup); return (size_t)-1; } e++; } *matchlen = e - s; { size_t k; for (k = 0; k < hlines; k++) free(hl[k]); } free(ndup); return s; } } { size_t k; for (k = 0; k < hlines; k++) free(hl[k]); } free(ndup); return (size_t)-1; } /* Report the first diverging non-blank line of `cur` vs `old`, numbered. */ static void describe_mismatch(buf_t *text, const char *cur, size_t curlen, const char *old, size_t oldlen, size_t index) { char probe[NAME_SZ]; size_t i, o = 0, shown = 0; size_t plen = 0; /* first non-empty line of oldText, trimmed */ while (o < oldlen && (old[o] == '\n' || old[o] == '\r' || old[o] == ' ' || old[o] == '\t')) o++; while (o + plen < oldlen && plen < sizeof probe - 1 && old[o + plen] != '\n' && old[o + plen] != '\r') { probe[plen] = old[o + plen]; plen++; } probe[plen] = '\0'; /* trim trailing spaces */ while (plen && (probe[plen - 1] == ' ' || probe[plen - 1] == '\t')) probe[--plen] = '\0'; buf_printf(text, "edit #%u did not match. ", (unsigned)(index + 1)); if (plen) { long long best = -1; double bestscore = -1; /* Find the line of the file most similar to probe's first token. */ size_t ls = 0, ln = 1; for (i = 0; i <= curlen; i++) { if (i == curlen || cur[i] == '\n') { size_t s = ls, e = i, m, hits = 0; while (s < e && (cur[s] == ' ' || cur[s] == '\t')) s++; while (e > s && (cur[e - 1] == ' ' || cur[e - 1] == '\t' || cur[e - 1] == '\r')) e--; if (e > s && plen) { for (m = s; m < e; m++) { size_t k; for (k = 0; k < plen; k++) if (cur[m] == probe[k]) { hits++; break; } } { double sc = (double)hits / (double)(e - s); if (sc > bestscore) { bestscore = sc; best = (long long)ln; } } } ls = i + 1; ln++; } } if (best > 0) { buf_printf(text, "The closest line is %lld. ", best); /* print up to 3 numbered lines around it */ { size_t ls2 = 0, ln2 = 1; for (i = 0; i <= curlen; i++) { if (i == curlen || cur[i] == '\n') { int phantom = (i == curlen && ls2 == curlen); if (!phantom && ln2 >= (size_t)best - 1 && shown < 3) { size_t s = ls2, e = (i < curlen) ? i : curlen; buf_printf(text, "%lld| ", (long long)ln2); for (; s < e && s < ls2 + 200; s++) if (cur[s] != '\r') buf_putc(text, cur[s]); buf_putc(text, '\n'); shown++; } ls2 = i + 1; ln2++; } } } } else { buf_puts(text, "Nothing in the file resembles oldText. "); } } else { buf_puts(text, "oldText was blank. "); } buf_puts(text, "Copy oldText from a read_text_file of the current content and retry."); } static int tool_edit_file(yyjson_val *args, buf_t *text) { char raw[PATH_SZ], canon[PATH_SZ]; const char *err = NULL; yyjson_val *edits; buf_t cur, work; size_t i, max; int dry_run; char *orig = NULL; size_t origlen = 0; int eol_crlf = 0; if (!ju_field_str(args, "path", raw, sizeof raw)) return (buf_puts(text, "missing required parameter \"path\""), 1); if (!resolve_allowed(raw, canon, sizeof canon, 'w', &err)) return (buf_printf(text, "%s: %s", raw, err ? err : "refused"), 1); if (!is_regular(canon)) return (buf_printf(text, "%s: not a regular file", raw), 1); edits = args ? yyjson_obj_get(args, "edits") : NULL; if (!edits || !yyjson_is_arr(edits) || yyjson_arr_size(edits) == 0) return (buf_puts(text, "missing required parameter \"edits\" (a non-empty array of {oldText,newText})"), 1); dry_run = ju_bool(args, "dryRun", 0); buf_init(&cur); if (!read_whole(canon, &cur, READ_CAP, NULL, &err)) { buf_printf(text, "%s: %s", raw, err ? err : "read failed"); buf_free(&cur); return 1; } /* detect the file's dominant line ending so the write restores it */ for (i = 0; i + 1 < cur.n; i++) if (cur.p[i] == '\r' && cur.p[i + 1] == '\n') { eol_crlf = 1; break; } /* normalise to LF for matching */ { size_t o = 0; for (i = 0; i < cur.n; i++) if (!(cur.p[i] == '\r' && i + 1 < cur.n && cur.p[i + 1] == '\n')) cur.p[o++] = cur.p[i]; cur.n = o; if (cur.p) cur.p[o] = '\0'; } orig = (char *)malloc(cur.n + 1); if (!orig) { buf_free(&cur); return (buf_puts(text, "out of memory"), 1); } memcpy(orig, cur.p ? cur.p : "", cur.n); orig[cur.n] = '\0'; origlen = cur.n; buf_init(&work); buf_add(&work, orig, origlen); max = yyjson_arr_size(edits); if (max > 100) max = 100; for (i = 0; i < max; i++) { yyjson_val *e = yyjson_arr_get(edits, i); const char *ot, *nt; size_t otlen, ntlen, at, ml; buf_t next; if (!yyjson_is_obj(e)) { buf_free(&work); free(orig); buf_free(&cur); buf_puts(text, "each edit must be an object with oldText and newText"); return 1; } ot = ju_str(e, "oldText"); nt = ju_str(e, "newText"); if (!ot) { buf_free(&work); free(orig); buf_free(&cur); buf_printf(text, "edit #%u is missing \"oldText\"", (unsigned)(i + 1)); return 1; } if (!nt) nt = ""; otlen = strlen(ot); ntlen = strlen(nt); if (otlen == 0) { buf_free(&work); free(orig); buf_free(&cur); buf_printf(text, "edit #%u has empty oldText - that would insert at position 0; send a real anchor", (unsigned)(i + 1)); return 1; } at = find_sub(work.p, work.n, ot, otlen); ml = otlen; if (at == (size_t)-1) at = find_lines(work.p, work.n, ot, otlen, &ml); if (at == (size_t)-1) { describe_mismatch(text, work.p, work.n, ot, otlen, i); buf_puts(text, " Nothing was written."); buf_free(&work); free(orig); buf_free(&cur); return 1; } buf_init(&next); buf_add(&next, work.p, at); buf_add(&next, nt, ntlen); buf_add(&next, work.p + at + ml, work.n - at - ml); buf_free(&work); work = next; } if (!dry_run) { buf_t outb; const char *werr = NULL; buf_init(&outb); if (eol_crlf) { for (i = 0; i < work.n; i++) { if (work.p[i] == '\n') buf_putc(&outb, '\r'); buf_putc(&outb, work.p[i]); } } else { buf_add(&outb, work.p, work.n); } if (!write_atomic(canon, outb.p ? outb.p : "", outb.n, &werr)) { buf_free(&outb); buf_free(&work); free(orig); buf_free(&cur); buf_printf(text, "%s: %s", raw, werr ? werr : "write failed"); return 1; } buf_free(&outb); } make_diff(text, orig, origlen, work.p ? work.p : "", work.n, raw); if (dry_run) buf_puts(text, "\n(dry run - nothing was written)\n"); buf_free(&work); free(orig); buf_free(&cur); return 0; } /* ------------------------------------------------------------------ */ /* The remaining tools */ /* ------------------------------------------------------------------ */ static int tool_create_directory(yyjson_val *args, buf_t *text) { char raw[PATH_SZ], canon[PATH_SZ]; const char *err = NULL; if (!ju_field_str(args, "path", raw, sizeof raw)) return (buf_puts(text, "missing required parameter \"path\""), 1); if (!resolve_allowed(raw, canon, sizeof canon, 'w', &err)) return (buf_printf(text, "%s: %s", raw, err ? err : "refused"), 1); if (is_dir_path(canon)) { buf_printf(text, "Directory already exists: %s", raw); return 0; } if (is_regular(canon)) return (buf_printf(text, "%s: a file already exists at that path", raw), 1); if (mkdir_p(canon) != 0) return (buf_printf(text, "%s: cannot create directory (%s)", raw, strerror(errno)), 1); buf_printf(text, "Successfully created directory %s", raw); return 0; } static void emit_listing(buf_t *text, const char *path, const char *raw, long n, dent_t *v, int with_sizes) { long i; long long tot_files = 0, tot_dirs = 0; for (i = 0; i < n; i++) { if (v[i].is_dir) tot_dirs++; else tot_files++; buf_puts(text, v[i].is_dir ? "[DIR] " : "[FILE] "); buf_puts(text, v[i].name); if (with_sizes && !v[i].is_dir) buf_printf(text, " %lld bytes", v[i].size); buf_putc(text, '\n'); } if (n >= MAX_ENTRIES) buf_printf(text, "(listing truncated at %d entries)\n", MAX_ENTRIES); if (with_sizes) buf_printf(text, "\n%d directories, %lld files\n", (int)tot_dirs, tot_files); (void)path; (void)raw; } static int tool_list_directory(yyjson_val *args, buf_t *text) { char raw[PATH_SZ], canon[PATH_SZ]; const char *err = NULL; dent_t *v = NULL; long n; if (!ju_field_str(args, "path", raw, sizeof raw)) return (buf_puts(text, "missing required parameter \"path\""), 1); if (!resolve_allowed(raw, canon, sizeof canon, 'r', &err)) return (buf_printf(text, "%s: %s", raw, err ? err : "refused"), 1); if (!is_dir_path(canon)) return (buf_printf(text, "%s: not a directory", raw), 1); n = list_dir(canon, &v, &err); if (n < 0) { buf_printf(text, "%s: %s", raw, err ? err : "cannot read directory"); return 1; } emit_listing(text, canon, raw, n, v, 0); free(v); return 0; } /* Upstream says the tree is "formatted with 2-space indentation for * readability", and an agent pastes this straight into a reply, so the * indentation is part of the tool's output contract - not decoration. */ static void indent(buf_t *b, int depth) { int i; for (i = 0; i < depth * 2; i++) buf_putc(b, ' '); } /* Whether the buffer ends with an entry (so a closing bracket needs its own * line). An empty children array stays on one line: []. */ static int body_has_entries(const buf_t *b) { size_t i; if (!b->p || b->n == 0) return 0; i = b->n - 1; while (i > 0 && (b->p[i] == ' ' || b->p[i] == '\n')) i--; return b->p[i] != '['; } static int tree_walk(buf_t *b, const char *dir, const char *rel, int depth, int max_depth, long *budget, yyjson_val *excludes, int *truncated) { dent_t *v = NULL; const char *err = NULL; long n, i; int first = 1; if (*budget <= 0) { *truncated = 1; return 0; } n = list_dir(dir, &v, &err); if (n < 0) return -1; for (i = 0; i < n; i++) { char child[PATH_SZ], crel[PATH_SZ]; if (*budget <= 0) { *truncated = 1; break; } if (v[i].name[0] == '.') continue; /* dotfiles stay out of a tree */ (*budget)--; path_join(child, sizeof child, dir, v[i].name); if (rel[0]) snprintf(crel, sizeof crel, "%s/%s", rel, v[i].name); else str_copy(crel, sizeof crel, v[i].name); if (is_excluded(crel, v[i].is_dir, excludes)) continue; if (!first) buf_putc(b, ','); first = 0; buf_putc(b, '\n'); indent(b, depth); buf_puts(b, "{\"name\":"); json_str(b, v[i].name); buf_puts(b, ", \"type\":"); buf_puts(b, v[i].is_dir ? "\"directory\"" : "\"file\""); if (v[i].is_dir && depth < max_depth) { int sub_trunc = 0; buf_puts(b, ", \"children\":["); tree_walk(b, child, crel, depth + 1, max_depth, budget, excludes, &sub_trunc); if (sub_trunc) *truncated = 1; if (body_has_entries(b)) { buf_putc(b, '\n'); indent(b, depth); } buf_putc(b, ']'); } buf_putc(b, '}'); } free(v); return 0; } static int tool_directory_tree(yyjson_val *args, buf_t *text) { char raw[PATH_SZ], canon[PATH_SZ]; const char *err = NULL; int have = 0; long long md = ju_int(args, "maxDepth", 4, &have); long budget = WALK_BUDGET; int truncated = 0; yyjson_val *excludes = args ? yyjson_obj_get(args, "excludePatterns") : NULL; buf_t body; if (!ju_field_str(args, "path", raw, sizeof raw)) return (buf_puts(text, "missing required parameter \"path\""), 1); if (!resolve_allowed(raw, canon, sizeof canon, 'r', &err)) return (buf_printf(text, "%s: %s", raw, err ? err : "refused"), 1); if (!is_dir_path(canon)) return (buf_printf(text, "%s: not a directory", raw), 1); if (md < 0) md = 0; if (md > MAX_DEPTH) md = MAX_DEPTH; buf_init(&body); buf_putc(&body, '['); tree_walk(&body, canon, "", 1, (int)md, &budget, excludes, &truncated); if (body_has_entries(&body)) { buf_putc(&body, '\n'); indent(&body, 0); } buf_putc(&body, ']'); buf_add(text, body.p ? body.p : "[]", body.n); buf_free(&body); if (truncated) buf_printf(text, "\n(truncated after %d entries; narrow the path or lower maxDepth)", WALK_BUDGET); return 0; } static int tool_move_file(yyjson_val *args, buf_t *text) { char sraw[PATH_SZ], draw[PATH_SZ], src[PATH_SZ], dst[PATH_SZ]; const char *err = NULL; if (!ju_field_str(args, "source", sraw, sizeof sraw)) return (buf_puts(text, "missing required parameter \"source\""), 1); if (!ju_field_str(args, "destination", draw, sizeof draw)) return (buf_puts(text, "missing required parameter \"destination\""), 1); if (!resolve_allowed(sraw, src, sizeof src, 'r', &err)) return (buf_printf(text, "source %s: %s", sraw, err ? err : "refused"), 1); if (is_link_path(src)) return (buf_printf(text, "source %s: refusing to move a symlink", sraw), 1); if (resolve_allowed(draw, dst, sizeof dst, 'r', &err)) { if (is_dir_path(dst)) return (buf_printf(text, "%s: a directory already exists at the destination", draw), 1); if (strcmp(src, dst) == 0) { buf_printf(text, "Source and destination are the same file: %s", sraw); return 0; } /* Upstream refuses to overwrite; so do we, silently-overwriting an * operator's file is the one thing an agent should never get. */ return (buf_printf(text, "%s already exists - move nothing. Move to a new name instead.", draw), 1); } if (!resolve_allowed(draw, dst, sizeof dst, 'w', &err)) return (buf_printf(text, "destination %s: %s", draw, err ? err : "refused"), 1); if (ensure_parent(dst) != 0) return (buf_printf(text, "%s: cannot create the destination directory", draw), 1); #if defined(_WIN32) if (!MoveFileExA(src, dst, MOVEFILE_WRITE_THROUGH)) { DWORD e = GetLastError(); if (e == ERROR_NOT_SAME_DEVICE) { if (!copy_file(src, dst, &err)) { buf_printf(text, "%s: %s", sraw, err ? err : "copy failed"); return 1; } DeleteFileA(src); } else { buf_printf(text, "%s -> %s: Win32 error %lu", sraw, draw, (unsigned long)e); return 1; } } #else if (rename(src, dst) != 0) { if (errno == EXDEV) { /* Cross-device: copy then remove. Same visible result, one more * window, so the removal only happens once the copy is on disk. */ if (!copy_file(src, dst, &err)) { buf_printf(text, "%s -> %s: %s", sraw, draw, err ? err : "copy failed"); return 1; } if (remove(src) != 0) { buf_printf(text, "copied %s to %s but could not remove the source (%s)", sraw, draw, strerror(errno)); return 1; } } else { buf_printf(text, "%s -> %s: %s", sraw, draw, strerror(errno)); return 1; } } #endif buf_printf(text, "Successfully moved %s to %s", sraw, draw); return 0; } /* A walk may only descend into paths still inside a root; re-checking each * child also catches a symlink that a directory scan handed us. */ static int is_allowed_for_walk(const char *canon_child) { char pc[PATH_SZ]; if (denied_path(canon_child)) return 0; if (root_contains(canon_child) >= 0) return 1; if (canon_path(canon_child, pc, sizeof pc)) return root_contains(pc) >= 0 && !denied_path(pc); return 0; } typedef struct { buf_t *out; long count; int truncated; } search_ctx; static void search_walk(const char *dir, const char *rel, const char *pattern, yyjson_val *excludes, long *budget, search_ctx *sc) { dent_t *v = NULL; const char *err = NULL; long n, i; if (*budget <= 0) { sc->truncated = 1; return; } n = list_dir(dir, &v, &err); if (n < 0) return; /* unreadable subtree: skip */ for (i = 0; i < n; i++) { char child[PATH_SZ], crel[PATH_SZ]; if (*budget <= 0) { sc->truncated = 1; break; } (*budget)--; path_join(child, sizeof child, dir, v[i].name); if (rel[0]) snprintf(crel, sizeof crel, "%s/%s", rel, v[i].name); else str_copy(crel, sizeof crel, v[i].name); /* excludes are checked before anything else, so an excluded subtree * is never even opened (upstream #4162) */ if (is_excluded(crel, v[i].is_dir, excludes)) continue; if (!is_allowed_for_walk(child)) { continue; } if (sc->count < MAX_RESULTS) { int hit = glob_match(pattern, crel) || glob_match(pattern, v[i].name); if (hit) { if (sc->count) buf_putc(sc->out, '\n'); buf_puts(sc->out, child); sc->count++; } } else { sc->truncated = 1; } if (v[i].is_dir) search_walk(child, crel, pattern, excludes, budget, sc); } free(v); } static int tool_search_files(yyjson_val *args, buf_t *text) { char raw[PATH_SZ], canon[PATH_SZ], rel[PATH_SZ] = ""; const char *err = NULL; char pattern[NAME_SZ]; yyjson_val *excludes; search_ctx sc; long budget = WALK_BUDGET; if (!ju_field_str(args, "path", raw, sizeof raw)) return (buf_puts(text, "missing required parameter \"path\""), 1); if (!ju_field_str(args, "pattern", pattern, sizeof pattern)) return (buf_puts(text, "missing required parameter \"pattern\""), 1); if (!resolve_allowed(raw, canon, sizeof canon, 'r', &err)) return (buf_printf(text, "%s: %s", raw, err ? err : "refused"), 1); if (!is_dir_path(canon)) return (buf_printf(text, "%s: not a directory (search walks directories)", raw), 1); excludes = args ? yyjson_obj_get(args, "excludePatterns") : NULL; sc.out = text; sc.count = 0; sc.truncated = 0; search_walk(canon, rel, pattern, excludes, &budget, &sc); if (sc.count == 0) { buf_puts(text, "(no matches)"); return 0; } if (sc.truncated) buf_printf(text, "\n(truncated: %d matches shown, walk budget %d entries; narrow the path or add excludePatterns)", (int)sc.count, WALK_BUDGET); return 0; } /* One timestamp as a JSON string (or null). */ static void json_time(buf_t *b, long long t) { char iso[40]; if (t <= 0) { buf_puts(b, "null"); return; } fmt_iso(t, iso, sizeof iso); json_str(b, iso); } static long long file_atime(const char *p) { #if defined(_WIN32) WIN32_FILE_ATTRIBUTE_DATA d; ULARGE_INTEGER u; if (!GetFileAttributesExA(p, GetFileExInfoStandard, &d)) return 0; u.LowPart = d.ftLastAccessTime.dwLowDateTime; u.HighPart = d.ftLastAccessTime.dwHighDateTime; return (long long)(u.QuadPart / 10000000ULL - 11644473600ULL); #else struct stat st; if (stat(p, &st) != 0) return 0; return (long long)st.st_atime; #endif } static int tool_get_file_info(yyjson_val *args, buf_t *text) { char raw[PATH_SZ], canon[PATH_SZ]; const char *err = NULL; if (!ju_field_str(args, "path", raw, sizeof raw)) return (buf_puts(text, "missing required parameter \"path\""), 1); if (!resolve_allowed(raw, canon, sizeof canon, 'r', &err)) return (buf_printf(text, "%s: %s", raw, err ? err : "refused"), 1); buf_puts(text, "{\n \"path\":"); json_str(text, canon); buf_puts(text, is_dir_path(canon) ? ",\n \"type\":\"directory\"" : ",\n \"type\":\"file\""); buf_printf(text, ",\n \"size\":%lld", file_size(canon)); buf_puts(text, ",\n \"created\":"); json_time(text, 0); /* birth time is not portable */ buf_puts(text, ",\n \"modified\":"); json_time(text, file_mtime(canon)); buf_puts(text, ",\n \"accessed\":"); json_time(text, file_atime(canon)); buf_printf(text, ",\n \"isFile\":%s", is_regular(canon) ? "true" : "false"); buf_printf(text, ",\n \"isDirectory\":%s", is_dir_path(canon) ? "true" : "false"); buf_printf(text, ",\n \"isSymlink\":%s", is_link_path(canon) ? "true" : "false"); buf_printf(text, ",\n \"mode\":\"%04o\"\n}\n", file_mode(canon)); return 0; } static int tool_list_allowed_directories(yyjson_val *args, buf_t *text) { int i; (void)args; buf_printf(text, "Allowed directories (%d):\n", g_root_count); if (g_root_count == 0) buf_puts(text, "(none configured - the plugin has nothing it may touch)"); for (i = 0; i < g_root_count; i++) { buf_puts(text, g_roots[i].canonical); if (strcmp(g_roots[i].configured, g_roots[i].canonical) != 0) buf_printf(text, " (configured as %s)", g_roots[i].configured); if (!g_roots[i].exists) buf_puts(text, " [does not exist]"); else if (!g_roots[i].is_dir) buf_puts(text, " [not a directory]"); buf_putc(text, '\n'); } return 0; } /* ------------------------------------------------------------------ */ /* Tool registry */ /* */ /* Descriptions are written to be read by a model choosing a tool, so */ /* they say when to use this one and what the parameters mean, and every */ /* one ends with the same reminder: it only works inside the allowed */ /* directories. The inputSchema is what the router hands to clang's */ /* MAX_TOOLS 512 budget, so it stays compact. */ /* ------------------------------------------------------------------ */ typedef struct { const char *name; const char *title; const char *desc; const char *schema; int read_only; int destructive; tool_fn fn; } tool_def; #define S_PROPS(p) "{\"type\":\"object\",\"properties\":{" p "},\"required\"" static const tool_def TOOLS[TOOLS_N] = { {"read_text_file", "Read Text File", "Read the complete contents of a file as text. Use head for the first N lines " "or tail for the last N (send at most one). Fails on binary files; use " "get_file_info for metadata. Only works within allowed directories.", "{\"type\":\"object\",\"properties\":{\"path\":{\"type\":\"string\",\"description\":\"Absolute file path\"}," "\"head\":{\"type\":\"integer\",\"description\":\"Return only the first N lines\"}," "\"tail\":{\"type\":\"integer\",\"description\":\"Return only the last N lines\"}}," "\"required\":[\"path\"]}", 1, 0, tool_read_text_file}, {"read_multiple_files", "Read Multiple Files", "Read several files in one call - cheaper than one read per file when " "comparing or diffing. Each result is prefixed with its path and separated by " "a line of three dashes; a file that fails reports its error without stopping " "the rest. Only works within allowed directories.", "{\"type\":\"object\",\"properties\":{\"paths\":{\"type\":\"array\",\"items\":{\"type\":\"string\"}," "\"description\":\"Absolute file paths (up to 200)\"}},\"required\":[\"paths\"]}", 1, 0, tool_read_multiple_files}, {"write_file", "Write File", "Create or completely overwrite a file. Content is written to a temporary " "file and renamed into place, so a crash cannot leave a half-written file. " "Missing parent directories are created. Only works within allowed directories.", "{\"type\":\"object\",\"properties\":{\"path\":{\"type\":\"string\",\"description\":\"Absolute file path\"}," "\"content\":{\"type\":\"string\",\"description\":\"Exact bytes to write\"}},\"required\":[\"path\",\"content\"]}", 0, 1, tool_write_file}, {"edit_file", "Edit File", "Apply targeted replacements to a text file. Edits apply in order and each " "replaces the first match of its oldText; oldText must match exactly, except " "that LF/CRLF never matters and a run of whole lines matches when each line " "is equal ignoring leading and trailing whitespace. If any edit fails to " "match, NOTHING is written and the reply shows the closest numbered lines. " "Set dryRun to see the diff without touching the disk. Only works within " "allowed directories.", "{\"type\":\"object\",\"properties\":{\"path\":{\"type\":\"string\",\"description\":\"Absolute file path\"}," "\"edits\":{\"type\":\"array\",\"items\":{\"type\":\"object\",\"properties\":{\"oldText\":{\"type\":\"string\"}," "\"newText\":{\"type\":\"string\"}},\"required\":[\"oldText\",\"newText\"]}},\"dryRun\":{\"type\":\"boolean\"," "\"description\":\"Compute and return the diff without writing\"}},\"required\":[\"path\",\"edits\"]}", 0, 1, tool_edit_file}, {"create_directory", "Create Directory", "Create a directory and any missing parents. Succeeds if it already exists. " "Only works within allowed directories.", "{\"type\":\"object\",\"properties\":{\"path\":{\"type\":\"string\",\"description\":\"Absolute directory path\"}}," "\"required\":[\"path\"]}", 0, 0, tool_create_directory}, {"list_directory", "List Directory", "List entries directly inside a directory, each marked [DIR] or [FILE], " "directories first then alphabetical. For a recursive view use directory_tree. " "Only works within allowed directories.", "{\"type\":\"object\",\"properties\":{\"path\":{\"type\":\"string\",\"description\":\"Absolute directory path\"}}," "\"required\":[\"path\"]}", 1, 0, tool_list_directory}, {"directory_tree", "Directory Tree", "Recursive tree of a directory as JSON: name, type (file/directory) and " "children for directories. maxDepth bounds the depth (default 4); " "excludePatterns are glob patterns matched against the relative path. Dot " "entries are omitted. Only works within allowed directories.", "{\"type\":\"object\",\"properties\":{\"path\":{\"type\":\"string\",\"description\":\"Absolute directory path\"}," "\"maxDepth\":{\"type\":\"integer\",\"description\":\"Levels to descend (0-24, default 4)\"}," "\"excludePatterns\":{\"type\":\"array\",\"items\":{\"type\":\"string\"}," "\"description\":\"Globs such as node_modules or *.tmp matched on the relative path\"}}," "\"required\":[\"path\"]}", 1, 0, tool_directory_tree}, {"move_file", "Move File", "Move or rename a file or directory. Will NOT overwrite an existing " "destination - move to a new name instead. A cross-device move falls back to " "copy-then-delete. Only works within allowed directories.", "{\"type\":\"object\",\"properties\":{\"source\":{\"type\":\"string\",\"description\":\"Absolute current path\"}," "\"destination\":{\"type\":\"string\",\"description\":\"Absolute new path (must not exist)\"}}," "\"required\":[\"source\",\"destination\"]}", 0, 1, tool_move_file}, {"search_files", "Search Files", "Recursively find files and directories whose name or relative path matches a " "glob pattern such as *.c or test_*.py. excludePatterns prunes subtrees " "(node_modules, .git) before they are ever opened. Returns absolute paths. " "Only works within allowed directories.", "{\"type\":\"object\",\"properties\":{\"path\":{\"type\":\"string\",\"description\":\"Absolute directory to search\"}," "\"pattern\":{\"type\":\"string\",\"description\":\"Glob, e.g. *.log or **/README*\"}," "\"excludePatterns\":{\"type\":\"array\",\"items\":{\"type\":\"string\"}," "\"description\":\"Globs pruned from the walk\"}},\"required\":[\"path\",\"pattern\"]}", 1, 0, tool_search_files}, {"get_file_info", "Get File Info", "Size, timestamps, type, symlink-ness and permission bits of one path. Use " "this before reading anything large. Only works within allowed directories.", "{\"type\":\"object\",\"properties\":{\"path\":{\"type\":\"string\",\"description\":\"Absolute path\"}}," "\"required\":[\"path\"]}", 1, 0, tool_get_file_info}, {"list_allowed_directories", "List Allowed Directories", "Report the directories this server may read and write, with the canonical " "path each one really resolves to. Call this first when a path is refused so " "you can pick a path inside a root.", "{\"type\":\"object\",\"properties\":{}}", 1, 0, tool_list_allowed_directories} }; /* ------------------------------------------------------------------ */ /* --mcp : MCP JSON-RPC 2.0 over stdio */ /* */ /* Contract as the router drives it (scorpiox-connector-mcp): one JSON */ /* object per line, responses on stdout terminated by \n, and nothing */ /* else ever printed to stdout. Logs therefore go to stderr, a malformed */ /* line is answered with -32700 (the router skips unparseable lines, but */ /* an id-less parse error is what a client needs to see it is talking to */ /* a real server), and a notification gets no reply at all. */ /* */ /* Content-Length framing is tolerated on input because a few clients */ /* speak LSP-style headers; output is always newline-delimited. */ /* ------------------------------------------------------------------ */ static void log_err(const char *fmt, ...) { va_list ap; fputs(PLUGIN_ID ": ", stderr); va_start(ap, fmt); vfprintf(stderr, fmt, ap); va_end(ap); fputc('\n', stderr); } static void send_msg(const char *json) { fputs(json, stdout); fputc('\n', stdout); fflush(stdout); } static void send_result(const char *id_raw, const char *result_json) { buf_t b; if (!id_raw) return; /* notification */ buf_init(&b); buf_printf(&b, "{\"jsonrpc\":\"2.0\",\"id\":%s,\"result\":%s}", id_raw, result_json ? result_json : "{}"); send_msg(b.p ? b.p : "{}"); buf_free(&b); } static void send_error(const char *id_raw, int code, const char *msg) { buf_t b; /* A parse error has no id to echo, but JSON-RPC still wants the * client to see it: answer with id:null. Only a request we know is a * notification (an id-less, method-bearing line) stays silent. */ buf_init(&b); buf_printf(&b, "{\"jsonrpc\":\"2.0\",\"id\":%s,\"error\":{\"code\":%d,\"message\":", id_raw ? id_raw : "null", code); json_str(&b, msg ? msg : "error"); buf_puts(&b, "}}"); send_msg(b.p ? b.p : "{}"); buf_free(&b); } /* The id verbatim (number or string) so it round-trips byte-exact. */ static char *id_raw_of(yyjson_val *root) { yyjson_val *id = yyjson_obj_get(root, "id"); char *s; if (!id) return NULL; /* a notification */ s = yyjson_val_write(id, 0, NULL); return s ? s : strdup("null"); } static void emit_tools_list(const char *id_raw) { buf_t b; int i; buf_init(&b); buf_puts(&b, "{\"tools\":["); for (i = 0; i < TOOLS_N; i++) { if (i) buf_putc(&b, ','); buf_puts(&b, "{\"name\":"); json_str(&b, TOOLS[i].name); buf_puts(&b, ",\"title\":"); json_str(&b, TOOLS[i].title); buf_puts(&b, ",\"description\":"); json_str(&b, TOOLS[i].desc); buf_puts(&b, ",\"inputSchema\":"); buf_puts(&b, TOOLS[i].schema); buf_puts(&b, ",\"annotations\":{\"readOnlyHint\":"); buf_puts(&b, TOOLS[i].read_only ? "true" : "false"); buf_puts(&b, ",\"destructiveHint\":"); buf_puts(&b, TOOLS[i].destructive ? "true" : "false"); buf_puts(&b, ",\"idempotentHint\":true,\"openWorldHint\":false}"); buf_putc(&b, '}'); } buf_puts(&b, "]}"); send_result(id_raw, b.p); buf_free(&b); } static void handle_tools_call(const char *id_raw, yyjson_val *params) { const char *name = ju_str(params, "name"); yyjson_val *arguments = params ? yyjson_obj_get(params, "arguments") : NULL; buf_t text; int is_err; int idx; buf_t out; if (!name || !*name) { send_error(id_raw, -32602, "missing tool name"); return; } idx = tool_index(name); if (idx < 0) { send_error(id_raw, -32602, "unknown tool"); return; } if (g_tool_off[idx]) { buf_t why; buf_init(&why); buf_printf(&why, "tool \"%s\" is disabled in this connector's permissions - " "enable it in the filesystem plugin page (Allowed Roots & Permissions)", TOOLS[idx].name); buf_init(&out); buf_puts(&out, "{\"isError\":true,\"content\":[{\"type\":\"text\",\"text\":"); json_str(&out, why.p ? why.p : ""); buf_puts(&out, "}]}"); send_result(id_raw, out.p); buf_free(&out); buf_free(&why); return; } if (arguments && !yyjson_is_obj(arguments)) arguments = NULL; buf_init(&text); is_err = TOOLS[idx].fn(arguments, &text); buf_init(&out); buf_puts(&out, "{\"isError\":"); buf_puts(&out, is_err ? "true" : "false"); buf_puts(&out, ",\"content\":[{\"type\":\"text\",\"text\":"); json_str(&out, text.p ? text.p : ""); buf_puts(&out, "}]}"); send_result(id_raw, out.p); buf_free(&out); buf_free(&text); } static void handle_line(const char *line) { yyjson_doc *doc; yyjson_val *root, *params; const char *method; char *id_raw; if (!line) return; while (*line == ' ' || *line == '\t') line++; if (!*line) return; doc = yyjson_read(line, strlen(line), 0); if (!doc) { send_error(NULL, -32700, "parse error"); return; } root = yyjson_doc_get_root(doc); if (!yyjson_is_obj(root)) { yyjson_doc_free(doc); send_error(NULL, -32700, "parse error"); return; } method = ju_str(root, "method"); id_raw = id_raw_of(root); params = yyjson_obj_get(root, "params"); if (!method) { if (id_raw) send_error(id_raw, -32600, "missing method"); free(id_raw); yyjson_doc_free(doc); return; } if (!strcmp(method, "initialize")) { buf_t b; const char *want = ju_str(params, "protocolVersion"); buf_init(&b); buf_puts(&b, "{\"protocolVersion\":"); /* Answer the client's version when it is one we speak, else ours: * 2024-11-05 is what scorpiox-connector-mcp asks for. */ json_str(&b, (want && (!strcmp(want, "2024-11-05") || !strcmp(want, "2025-03-26") || !strcmp(want, "2025-06-18"))) ? want : MCP_PROTO); buf_puts(&b, ",\"capabilities\":{\"tools\":{\"listChanged\":false}},\"serverInfo\":{"); buf_puts(&b, "\"name\":\""); buf_puts(&b, PLUGIN_ID); buf_puts(&b, "\",\"version\":\""); buf_puts(&b, PLUGIN_VER); buf_puts(&b, "\"},\"instructions\":"); json_str(&b, "Sandboxed filesystem tools. Every path is canonicalised and " "must resolve inside the allowed roots; traversal and symlink " "escapes are refused. Call list_allowed_directories first if " "a path is refused."); buf_putc(&b, '}'); send_result(id_raw, b.p); buf_free(&b); } else if (!strncmp(method, "notifications/", 14) || !strcmp(method, "ping")) { if (id_raw && !strcmp(method, "ping")) send_result(id_raw, "{}"); } else if (!strcmp(method, "tools/list")) { if (id_raw) { init_roots(); emit_tools_list(id_raw); } } else if (!strcmp(method, "tools/call")) { init_roots(); handle_tools_call(id_raw, params); } else if (!strcmp(method, "resources/list")) { if (id_raw) send_result(id_raw, "{\"resources\":[]}"); } else if (!strcmp(method, "resources/templates/list")) { if (id_raw) send_result(id_raw, "{\"resourceTemplates\":[]}"); } else if (!strcmp(method, "prompts/list")) { if (id_raw) send_result(id_raw, "{\"prompts\":[]}"); } else if (!strcmp(method, "logging/setLevel")) { if (id_raw) send_result(id_raw, "{}"); } else { if (id_raw) send_error(id_raw, -32601, "method not found"); } free(id_raw); yyjson_doc_free(doc); } /* Read one request. Newline-delimited, with Content-Length framing accepted * because a handful of clients emit LSP headers instead of newlines. */ static int read_request_line(buf_t *line) { static char rb[IO_CHUNK]; 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[IO_CHUNK + 1]; /* +1: the terminator below */ 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)) { want = strtoll(tmp + 15, NULL, 10); continue; } if (want < 0 && take == 0 && !nl) continue; /* header blank */ buf_add(line, tmp, take); if (want < 0) { /* Newline-delimited: a chunk without '\n' is not a line, * it is the front half of one. Only return when the * terminator was actually seen (or at EOF below). * take==0 && nl is the terminator that completes a frame * written as two separate writes - the router's * proc_send() writes the body and the '\n' apart, and an * earlier cut of this function dropped that blank line * into the header path, hanging every router call. */ if (nl) return 1; continue; } if ((long long)line->n >= want) { /* framed body */ if (line->p && (size_t)want < line->cap) line->p[want] = '\0'; line->n = (size_t)want; want = -1; return 1; } buf_putc(line, '\n'); continue; } } if (rp >= rn) { rn = 0; rp = 0; } /* NOT fread: on a pipe fread blocks until the whole 64 KiB buffer * fills or EOF, so a client that sends "frame" and flushes, then * sends "\n" later (the router's proc_send writes body and newline * as separate writes), would hang. read() returns what is there. */ 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; /* EOF */ #if !defined(_WIN32) if (errno == EINTR) continue; /* signal, retry */ #endif return line->n ? 1 : 0; /* error = close */ } } } static int mode_mcp(void) { buf_t line; #if defined(_WIN32) _setmode(_fileno(stdout), O_BINARY); /* \n stays \n, no CRLF */ _setmode(_fileno(stdin), O_BINARY); #endif buf_init(&line); while (read_request_line(&line)) { if (line.n > MCP_LINE_CAP) { log_err("request line exceeds %d bytes; dropping", (int)MCP_LINE_CAP); send_error(NULL, -32600, "request too large"); continue; } if (line.n) handle_line(line.p); } buf_free(&line); return 0; } /* ------------------------------------------------------------------ */ /* Config persistence (the Setup UI writes what --mcp reads) */ /* ------------------------------------------------------------------ */ /* Atomic like write_file: same tmp+rename discipline, because a half-written * roots.json would silently widen or narrow the sandbox. */ static int save_roots_file(void) { char dir[PATH_SZ], tmp[PATH_SZ]; buf_t b; FILE *f; int i; connectors_dir(dir, sizeof dir); if (mkpath(dir) != 0) return -1; snprintf(tmp, sizeof tmp, "%s", g_roots_file); if (strlen(tmp) + 12 >= sizeof tmp) return -1; str_copy(tmp + strlen(tmp), sizeof tmp - strlen(tmp), ".tmp"); buf_init(&b); buf_puts(&b, "{\n \"roots\": ["); for (i = 0; i < g_root_count; i++) { if (i) buf_putc(&b, ','); buf_puts(&b, "\n "); json_str(&b, g_roots[i].configured[0] ? g_roots[i].configured : g_roots[i].canonical); } buf_puts(&b, g_root_count ? "\n ],\n" : "],\n"); buf_puts(&b, " \"denied\": ["); for (i = 0; i < deny_count; i++) { if (i) buf_putc(&b, ','); buf_puts(&b, "\n "); json_str(&b, g_deny[i]); } buf_puts(&b, deny_count ? "\n ],\n" : "],\n"); buf_puts(&b, " \"permissions\": {\n"); for (i = 0; i < TOOLS_N; i++) { buf_printf(&b, " \"%s\": %s%s\n", TOOL_NAMES[i], g_tool_off[i] ? "false" : "true", i + 1 < TOOLS_N ? "," : ""); } buf_puts(&b, " }\n}\n"); f = fopen(tmp, "wb"); if (!f) { buf_free(&b); return -1; } if (b.n && fwrite(b.p, 1, b.n, f) != b.n) { fclose(f); #if defined(_WIN32) DeleteFileA(tmp); #else remove(tmp); #endif buf_free(&b); return -1; } fclose(f); #if defined(_WIN32) MoveFileExA(g_roots_file, tmp, 0); /* keep a copy for rollback */ if (!MoveFileExA(tmp, g_roots_file, MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH)) { buf_free(&b); return -1; } #else if (rename(tmp, g_roots_file) != 0) { remove(tmp); buf_free(&b); return -1; } #endif buf_free(&b); return 0; } static void ensure_roots_file_path(void) { if (g_roots_file[0]) return; init_roots(); if (g_roots_file[0]) return; { char dir[PATH_SZ]; connectors_dir(dir, sizeof dir); snprintf(g_roots_file, sizeof g_roots_file, "%s", dir); { size_t dl = strlen(g_roots_file); if (dl + 12 < sizeof g_roots_file) { g_roots_file[dl] = SEP; g_roots_file[dl + 1] = '\0'; str_copy(g_roots_file + dl + 1, sizeof g_roots_file - dl - 1, "roots.json"); } } } } 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_err(int code, const char *msg) { if (code == 400) fputs("Status: 400 Bad Request\r\n", stdout); else if (code == 403) fputs("Status: 403 Forbidden\r\n", stdout); else if (code == 404) fputs("Status: 404 Not Found\r\n", stdout); else if (code == 409) fputs("Status: 409 Conflict\r\n", stdout); else fputs("Status: 500 Internal Server Error\r\n", stdout); json_header(); printf("{\"ok\":false,\"error\":"); { buf_t b; buf_init(&b); json_str(&b, msg ? msg : "error"); fputs(buf_str(&b), stdout); buf_free(&b); } fputs("}\n", stdout); } /* ------------------------------------------------------------------ */ /* CGI actions */ /* ------------------------------------------------------------------ */ static void do_status(void) { int i; json_header(); printf("{\"ok\":true,\"plugin\":\"%s\",\"version\":\"%s\",\"kind\":\"mcp\"," "\"mcp\":true,\"verified\":\"live\",\"protocol\":\"%s\",\"tools\":%d," "\"roots_file\":", PLUGIN_ID, PLUGIN_VER, MCP_PROTO, TOOLS_N); { buf_t b; buf_init(&b); ensure_roots_file_path(); json_str(&b, g_roots_file); printf("%s", buf_str(&b)); buf_free(&b); } printf(",\"config_source\":%s", getenv("FS_ALLOWED_ROOTS") ? "\"env:FS_ALLOWED_ROOTS\"" : (g_root_count ? "\"roots.json-or-defaults\"" : "\"none\"")); printf(",\"writable\":%s", (g_roots_file[0] && access(g_roots_file, 2) == 0) || (!g_roots_file[0]) ? "true" : "false"); printf(",\"roots\":["); for (i = 0; i < g_root_count; i++) { printf("%s{\"configured\":", i ? "," : ""); { buf_t b; buf_init(&b); json_str(&b, g_roots[i].configured); printf("%s", buf_str(&b)); buf_free(&b); } printf(",\"canonical\":"); { buf_t b; buf_init(&b); json_str(&b, g_roots[i].canonical); printf("%s", buf_str(&b)); buf_free(&b); } printf(",\"exists\":%s,\"is_dir\":%s,\"drift\":%s}", g_roots[i].exists ? "true" : "false", g_roots[i].is_dir ? "true" : "false", strcmp(g_roots[i].configured, g_roots[i].canonical) ? "true" : "false"); } printf("],\"denied\":["); for (i = 0; i < deny_count; i++) { buf_t b; buf_init(&b); json_str(&b, g_deny[i]); printf("%s%s", i ? "," : "", buf_str(&b)); buf_free(&b); } printf("],\"permissions\":{"); for (i = 0; i < TOOLS_N; i++) printf("%s\"%s\":%s", i ? "," : "", TOOL_NAMES[i], g_tool_off[i] ? "false" : "true"); printf("}}\n"); } static void do_roots(void) { int i; json_header(); printf("{\"ok\":true,\"count\":%d,\"roots\":[", g_root_count); for (i = 0; i < g_root_count; i++) { const char *base = strrchr(g_roots[i].canonical, '/'); char label[NAME_SZ]; buf_t b; buf_init(&b); if (i) buf_putc(&b, ','); /* after init - was UB before it */ buf_puts(&b, "\n {\"path\":"); json_str(&b, g_roots[i].canonical); buf_puts(&b, ",\"canonical\":"); json_str(&b, g_roots[i].canonical); buf_puts(&b, ",\"configured\":"); json_str(&b, g_roots[i].configured); buf_puts(&b, ",\"name\":"); if (base && base[1]) str_copy(label, sizeof label, base + 1); else str_copy(label, sizeof label, g_roots[i].canonical); json_str(&b, label); buf_printf(&b, ",\"exists\":%s,\"is_dir\":%s}", g_roots[i].exists ? "true" : "false", g_roots[i].is_dir ? "true" : "false"); fputs(buf_str(&b), stdout); buf_free(&b); } printf("\n]}\n"); } static void do_roots_add(const char *path) { int before = g_root_count; char canon[PATH_SZ]; if (!path || !*path) { json_err(400, "path is required"); return; } if (!path_shape_ok(path)) { json_err(400, "path must be absolute and must not contain '..'"); return; } if (!canon_path(path, canon, sizeof canon)) { json_err(404, "that directory does not exist yet"); return; } if (denied_path(canon)) { json_err(403, "that path is on the deny list"); return; } add_root_raw(path); if (g_root_count == before) { json_err(409, "that directory is already allowed"); return; } ensure_roots_file_path(); if (save_roots_file() != 0) { json_err(500, "could not write roots.json"); return; } json_header(); printf("{\"ok\":true,\"added\":"); { buf_t b; buf_init(&b); json_str(&b, canon); printf("%s", buf_str(&b)); buf_free(&b); } printf(",\"count\":%d}\n", g_root_count); } static void do_roots_remove(const char *path) { char canon[PATH_SZ]; int i, j, found = 0; if (!path || !*path) { json_err(400, "path is required"); return; } if (canon_path(path, canon, sizeof canon)) { /* matched below */ } else { str_copy(canon, sizeof canon, path); } for (i = 0; i < g_root_count; i++) { if (!strcmp(g_roots[i].canonical, canon) || !strcmp(g_roots[i].configured, path) || path_under_p(canon, g_roots[i].canonical)) { for (j = i; j + 1 < g_root_count; j++) g_roots[j] = g_roots[j + 1]; g_root_count--; found = 1; break; } } if (!found) { json_err(404, "that directory is not in the allowlist"); return; } ensure_roots_file_path(); if (save_roots_file() != 0) { json_err(500, "could not write roots.json"); return; } json_header(); printf("{\"ok\":true,\"removed\":true,\"count\":%d}\n", g_root_count); } static void do_permissions(void) { int i; json_header(); printf("{\"ok\":true,\"permissions\":{"); for (i = 0; i < TOOLS_N; i++) printf("%s\"%s\":%s", i ? "," : "", TOOL_NAMES[i], g_tool_off[i] ? "false" : "true"); printf("}}\n"); } static void do_permissions_set(const char *qs) { char tool[64], val[16]; int idx; if (!get_query_val(qs, "tool", tool, sizeof tool)) { json_err(400, "tool is required"); return; } idx = tool_index(tool); if (idx < 0) { json_err(404, "unknown tool"); return; } if (!get_query_val(qs, "enabled", val, sizeof val)) { json_err(400, "enabled is required (true/false)"); return; } g_tool_off[idx] = (strcmp(val, "true") == 0 || strcmp(val, "1") == 0) ? 0 : 1; /* list_allowed_directories is the diagnostic an operator needs when a * path is refused, so it can never be switched off. */ if (idx == TOOLS_N - 1) g_tool_off[idx] = 0; ensure_roots_file_path(); if (save_roots_file() != 0) { json_err(500, "could not write roots.json"); return; } json_header(); printf("{\"ok\":true,\"tool\":"); { buf_t b; buf_init(&b); json_str(&b, TOOL_NAMES[idx]); printf("%s", buf_str(&b)); buf_free(&b); } printf(",\"enabled\":%s}\n", g_tool_off[idx] ? "false" : "true"); } /* The sandbox boundary tester: what an operator types in, the tool sees. * Reports both forms and the exact reason a path is refused. */ static void do_sandbox_test(const char *path) { char canon[PATH_SZ]; const char *err = NULL; int allowed = 0; if (!path || !*path) { json_err(400, "path is required"); return; } allowed = resolve_allowed(path, canon, sizeof canon, 'r', &err); if (!allowed) { /* a write-mode answer is more useful for a path that does not exist */ char wc[PATH_SZ]; const char *werr = NULL; if (resolve_allowed(path, wc, sizeof wc, 'w', &werr)) { buf_t b; json_header(); printf("{\"ok\":true,\"path\":"); buf_init(&b); json_str(&b, path); printf("%s,\"allowed\":true,\"mode\":\"write\",\"canonical\":", buf_str(&b)); buf_free(&b); buf_init(&b); json_str(&b, wc); printf("%s}\n", buf_str(&b)); buf_free(&b); return; } } { buf_t b; json_header(); buf_init(&b); json_str(&b, path); printf("{\"ok\":true,\"path\":%s,\"allowed\":%s,\"canonical\":", buf_str(&b), allowed ? "true" : "false"); buf_free(&b); if (allowed) { buf_init(&b); json_str(&b, canon); printf("%s,\"reason\":\"inside an allowed root\"}\n", buf_str(&b)); buf_free(&b); } else { buf_init(&b); json_str(&b, canon); printf("%s,\"reason\":", buf_str(&b)); buf_free(&b); buf_init(&b); json_str(&b, err ? err : "refused"); printf("%s}\n", buf_str(&b)); buf_free(&b); } } } static void do_tools(void) { int i; json_header(); printf("{\"ok\":true,\"tools\":["); for (i = 0; i < TOOLS_N; i++) { buf_t b; buf_init(&b); if (i) buf_putc(&b, ','); buf_puts(&b, "{\"name\":"); json_str(&b, TOOLS[i].name); buf_puts(&b, ",\"title\":"); json_str(&b, TOOLS[i].title); buf_puts(&b, ",\"description\":"); json_str(&b, TOOLS[i].desc); buf_printf(&b, ",\"read_only\":%s,\"destructive\":%s,\"enabled\":%s}", TOOLS[i].read_only ? "true" : "false", TOOLS[i].destructive ? "true" : "false", g_tool_off[i] ? "false" : "true"); fputs(buf_str(&b), stdout); buf_free(&b); } printf("]}\n"); } /* ------------------------------------------------------------------ */ /* HTML UI */ /* ------------------------------------------------------------------ */ /* 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. */ static void emit_ui(int embed) { 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++); } } (void)embed; } static void mode_html(int embed) { 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(embed); } /* ------------------------------------------------------------------ */ /* main */ /* ------------------------------------------------------------------ */ static void print_help(void) { printf("%s %s - SCORPIOX BOT allowlisted filesystem 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" " (no args) CGI: Allowed Roots & Permissions page + ?action= API\n" " --version print version\n\n" "config: %s/roots.json (or FS_ALLOWED_ROOTS, colon-separated)\n" "tools: ", PLUGIN_ID, PLUGIN_VER, " ~/.scorpiox/connectors/" PLUGIN_ID); { int i; for (i = 0; i < TOOLS_N; i++) printf("%s%s", i ? ", " : "", TOOLS[i].name); } printf("\n"); } int main(int argc, char **argv) { const char *qs; char action[64]; char path[PATH_SZ]; int i; /* 1. Discovery metadata - unauthenticated: /plugins and the connector * router probe every installed binary, and a probe that needs the * node password is a probe that fails. */ if ((argc > 1 && strcmp(argv[1], "--meta") == 0) || getenv("SX_PLUGIN_META")) { fputs("{\"name\":\"" PLUGIN_NAME "\",\"desc\":\"" PLUGIN_DESC "\"," "\"kind\":\"mcp\",\"mcp\":true,\"daemon\":false,\"menus\":false," "\"verified\":\"live\",\"version\":\"" PLUGIN_VER "\"}\n", stdout); return 0; } for (i = 1; i < argc; i++) { if (!strcmp(argv[i], "--version")) { printf("%s %s\n", PLUGIN_ID, PLUGIN_VER); return 0; } if (!strcmp(argv[i], "--help") || !strcmp(argv[i], "-h")) { print_help(); return 0; } } /* 2. MCP stdio server - the connector mode. No CGI headers, no auth: * the caller is the node's own MCP router, already trusted. */ if (argc > 1 && !strcmp(argv[1], "--mcp")) { init_roots(); return mode_mcp(); } /* 3. CGI modes below are all behind node auth. */ require_node_auth(); init_roots(); qs = getenv("QUERY_STRING"); if (!qs) qs = ""; action[0] = '\0'; path[0] = '\0'; get_query_val(qs, "action", action, sizeof action); get_query_val(qs, "path", path, sizeof path); if (action[0] || strstr(qs, "format=json")) { if (!action[0]) str_copy(action, sizeof action, "status"); if (!strcmp(action, "status")) do_status(); else if (!strcmp(action, "roots")) do_roots(); else if (!strcmp(action, "roots_add")) do_roots_add(path); else if (!strcmp(action, "roots_remove")) do_roots_remove(path); else if (!strcmp(action, "permissions")) do_permissions(); else if (!strcmp(action, "permissions_set")) do_permissions_set(qs); else if (!strcmp(action, "sandbox_test")) do_sandbox_test(path); else if (!strcmp(action, "tools")) do_tools(); else json_err(400, "unknown action"); return 0; } /* 4. Everything else is the page. */ { int embed = strstr(qs, "embed=1") != NULL || strstr(qs, "embed=true") != NULL; mode_html(embed); } return 0; }