| 1 | /* |
| 2 | * tools.c - the nine knowledge-graph tools for plugin_memory. |
| 3 | * |
| 4 | * These are exactly the tools of the reference MCP memory server, with the |
| 5 | * same names, the same input schemas and the same semantics, so an agent that |
| 6 | * was tuned against the reference cannot tell the difference: |
| 7 | * |
| 8 | * create_entities skip existing names, report them in `skipped` |
| 9 | * create_relations both ends must exist, dedupe the triple |
| 10 | * add_observations entity must exist, dedupe within call and store |
| 11 | * delete_entities report deleted/notFound, cascade relations |
| 12 | * delete_observations exact-text match, count across missing entities |
| 13 | * delete_relations exact triple match, count what actually went |
| 14 | * read_graph optional entityTypes + observationLimit |
| 15 | * search_nodes case-insensitive substring, limit, either-end |
| 16 | * open_nodes exact names, either-end relations |
| 17 | * |
| 18 | * The rules that are easy to lose, and are therefore pinned by tests: |
| 19 | * |
| 20 | * - create_entities SKIPS a name that already exists (or repeats earlier in |
| 21 | * the same batch) rather than adding its observations, and must say so in |
| 22 | * the result - otherwise an agent reads a skip as a store. |
| 23 | * - create_relations validates EVERY relation before adding ANY, so one bad |
| 24 | * end fails the whole call and nothing is written. |
| 25 | * - add_observations keeps the first occurrence of a string repeated within |
| 26 | * one call. |
| 27 | * - the read tools keep a relation when EITHER endpoint is in the result |
| 28 | * set; requiring both made a node's outside connections undiscoverable. |
| 29 | * - observationLimit 0 is a real value (names, types and counts only) and is |
| 30 | * not the same as omitting the option; observationCount appears only when |
| 31 | * the limit was given. |
| 32 | * - a line the loader cannot parse is preserved and written back, so a |
| 33 | * hand-edited graph survives every tool call. |
| 34 | * |
| 35 | * A tool never frees its own result: the caller serialises and then calls |
| 36 | * tool_free(). That keeps the MCP loop leak-free and stops an error path from |
| 37 | * destroying the error it is about to report. |
| 38 | * |
| 39 | * MIT License. Copyright (c) 2026 SCORPIOX INC. |
| 40 | */ |
| 41 | |
| 42 | #if defined(_WIN32) && !defined(_WIN32_WINNT) |
| 43 | # define _WIN32_WINNT 0x0601 |
| 44 | #endif |
| 45 | |
| 46 | #if !defined(_WIN32) |
| 47 | # define _POSIX_C_SOURCE 200809L |
| 48 | # define _DEFAULT_SOURCE 1 |
| 49 | #endif |
| 50 | |
| 51 | #include <stdio.h> |
| 52 | #include <stdlib.h> |
| 53 | #include <string.h> |
| 54 | #include <stdarg.h> |
| 55 | |
| 56 | #include "memory.h" |
| 57 | |
| 58 | /* ------------------------------------------------------------------ */ |
| 59 | /* Read options */ |
| 60 | /* ------------------------------------------------------------------ */ |
| 61 | |
| 62 | void read_opt_init(read_opt_t *o) |
| 63 | { |
| 64 | memset(o, 0, sizeof *o); |
| 65 | o->max_entities = 0; /* 0 = unlimited */ |
| 66 | } |
| 67 | |
| 68 | static void read_opt_free_types(read_opt_t *o) |
| 69 | { |
| 70 | size_t i; |
| 71 | for (i = 0; i < o->n_types; i++) free(o->types[i]); |
| 72 | free(o->types); |
| 73 | o->types = NULL; |
| 74 | o->n_types = 0; |
| 75 | } |
| 76 | |
| 77 | /* ------------------------------------------------------------------ */ |
| 78 | /* Result record */ |
| 79 | /* ------------------------------------------------------------------ */ |
| 80 | |
| 81 | void tool_out_init(tool_out_t *t) |
| 82 | { |
| 83 | memset(t, 0, sizeof *t); |
| 84 | } |
| 85 | |
| 86 | void tool_err(tool_out_t *t, const char *fmt, ...) |
| 87 | { |
| 88 | char tmp[768]; |
| 89 | va_list ap; |
| 90 | va_start(ap, fmt); |
| 91 | vsnprintf(tmp, sizeof tmp, fmt, ap); |
| 92 | va_end(ap); |
| 93 | if (!t->error) t->error = dup_or_null(tmp); |
| 94 | t->is_error = 1; |
| 95 | } |
| 96 | |
| 97 | void tool_free(tool_out_t *t) |
| 98 | { |
| 99 | if (!t) return; |
| 100 | if (t->md) yyjson_mut_doc_free(t->md); |
| 101 | free(t->notice); |
| 102 | free(t->error); |
| 103 | memset(t, 0, sizeof *t); |
| 104 | } |
| 105 | |
| 106 | static void tool_start(tool_out_t *t) |
| 107 | { |
| 108 | if (t->md) return; |
| 109 | t->md = yyjson_mut_doc_new(NULL); |
| 110 | if (!t->md) { tool_err(t, "out of memory"); return; } |
| 111 | t->root = yyjson_mut_obj(t->md); |
| 112 | if (!t->root) { tool_err(t, "out of memory"); return; } |
| 113 | yyjson_mut_doc_set_root(t->md, t->root); |
| 114 | } |
| 115 | |
| 116 | /* ------------------------------------------------------------------ */ |
| 117 | /* Argument helpers */ |
| 118 | /* ------------------------------------------------------------------ */ |
| 119 | |
| 120 | static yyjson_val *arg_get(yyjson_val *obj, const char *key) |
| 121 | { |
| 122 | return obj ? yyjson_obj_get(obj, key) : NULL; |
| 123 | } |
| 124 | |
| 125 | static const char *arg_str(yyjson_val *obj, const char *key) |
| 126 | { |
| 127 | yyjson_val *v = arg_get(obj, key); |
| 128 | return (v && yyjson_is_str(v)) ? yyjson_get_str(v) : NULL; |
| 129 | } |
| 130 | |
| 131 | /* Optional integer >= lo. Returns 1 when present and valid. */ |
| 132 | static int arg_opt_int(yyjson_val *obj, const char *key, int lo, int *out) |
| 133 | { |
| 134 | yyjson_val *v = arg_get(obj, key); |
| 135 | long long n; |
| 136 | if (!v || yyjson_is_null(v)) return 0; |
| 137 | if (!yyjson_is_int(v)) return -1; |
| 138 | n = (long long)yyjson_get_sint(v); |
| 139 | if (n < lo) return -1; |
| 140 | if (n > 100000000LL) n = 100000000LL; |
| 141 | *out = (int)n; |
| 142 | return 1; |
| 143 | } |
| 144 | |
| 145 | /* ------------------------------------------------------------------ */ |
| 146 | /* Mut helpers */ |
| 147 | /* ------------------------------------------------------------------ */ |
| 148 | |
| 149 | static yyjson_mut_val *ent_to_mut(yyjson_mut_doc *md, const entity_t *e, |
| 150 | const read_opt_t *o) |
| 151 | { |
| 152 | yyjson_mut_val *o_ = yyjson_mut_obj(md); |
| 153 | yyjson_mut_val *arr = yyjson_mut_arr(md); |
| 154 | size_t i, lim; |
| 155 | |
| 156 | if (!o_ || !arr) return o_; |
| 157 | yyjson_mut_obj_add_str(md, o_, "name", e->name ? e->name : ""); |
| 158 | yyjson_mut_obj_add_str(md, o_, "entityType", e->etype ? e->etype : ""); |
| 159 | lim = e->n_obs; |
| 160 | if (o && o->has_limit && (size_t)o->limit < lim) lim = (size_t)o->limit; |
| 161 | for (i = 0; i < lim; i++) |
| 162 | yyjson_mut_arr_add_str(md, arr, e->obs[i] ? e->obs[i] : ""); |
| 163 | yyjson_mut_obj_add_val(md, o_, "observations", arr); |
| 164 | if (o && o->has_limit && o->has_count) |
| 165 | yyjson_mut_obj_add_uint(md, o_, "observationCount", (uint64_t)e->n_obs); |
| 166 | return o_; |
| 167 | } |
| 168 | |
| 169 | static yyjson_mut_val *rel_to_mut(yyjson_mut_doc *md, const char *from, |
| 170 | const char *to, const char *rtype) |
| 171 | { |
| 172 | yyjson_mut_val *r = yyjson_mut_obj(md); |
| 173 | if (!r) return NULL; |
| 174 | yyjson_mut_obj_add_str(md, r, "from", from ? from : ""); |
| 175 | yyjson_mut_obj_add_str(md, r, "to", to ? to : ""); |
| 176 | yyjson_mut_obj_add_str(md, r, "relationType", rtype ? rtype : ""); |
| 177 | return r; |
| 178 | } |
| 179 | |
| 180 | static int rel_same(const relation_t *a, const char *from, const char *to, |
| 181 | const char *rtype) |
| 182 | { |
| 183 | return strcmp(a->from, from) == 0 && strcmp(a->to, to) == 0 && |
| 184 | strcmp(a->rtype, rtype) == 0; |
| 185 | } |
| 186 | /* The same triple test for two plain field triples - used when one side is a |
| 187 | * JSON object rather than a stored relation. A NULL on either side means |
| 188 | * "no match", never a strcmp on NULL. */ |
| 189 | static int rel_same_fields(const char *af, const char *at, const char *ar, |
| 190 | const char *bf, const char *bt, const char *br) |
| 191 | { |
| 192 | if (!af || !at || !ar || !bf || !bt || !br) return 0; |
| 193 | return strcmp(af, bf) == 0 && strcmp(at, bt) == 0 && strcmp(ar, br) == 0; |
| 194 | } |
| 195 | |
| 196 | |
| 197 | /* Emit {"entities":[...],"relations":[...]} for a chosen set of entities. |
| 198 | * A relation survives when EITHER endpoint is in the set, which is what makes |
| 199 | * a node's connections to nodes outside the result set discoverable. */ |
| 200 | static void emit_set(tool_out_t *t, entity_t **ents, size_t n_ents, |
| 201 | const read_opt_t *o) |
| 202 | { |
| 203 | yyjson_mut_doc *md = t->md; |
| 204 | yyjson_mut_val *ea = yyjson_mut_arr(md); |
| 205 | yyjson_mut_val *ra = yyjson_mut_arr(md); |
| 206 | size_t i, r; |
| 207 | |
| 208 | for (i = 0; i < n_ents; i++) |
| 209 | yyjson_mut_arr_add_val(ea, ent_to_mut(md, ents[i], o)); |
| 210 | |
| 211 | for (r = 0; r < G.n_rel; r++) { |
| 212 | int hit = 0; |
| 213 | for (i = 0; i < n_ents; i++) { |
| 214 | if (strcmp(G.rel[r].from, ents[i]->name) == 0 || |
| 215 | strcmp(G.rel[r].to, ents[i]->name) == 0) { hit = 1; break; } |
| 216 | } |
| 217 | if (!hit) continue; |
| 218 | yyjson_mut_arr_add_val(ra, rel_to_mut(md, G.rel[r].from, G.rel[r].to, |
| 219 | G.rel[r].rtype)); |
| 220 | } |
| 221 | yyjson_mut_obj_add_val(md, t->root, "entities", ea); |
| 222 | yyjson_mut_obj_add_val(md, t->root, "relations", ra); |
| 223 | } |
| 224 | |
| 225 | /* Emit the whole graph, honouring entityTypes + observationLimit. The kept |
| 226 | * entities are collected as pointers first so the relation filter is a |
| 227 | * pointer compare rather than a re-read of the JSON just built. */ |
| 228 | static void emit_all(tool_out_t *t, const read_opt_t *o) |
| 229 | { |
| 230 | entity_t **kept; |
| 231 | size_t i, k, w; |
| 232 | |
| 233 | kept = (entity_t **)malloc((G.n_ent ? G.n_ent : 1) * sizeof *kept); |
| 234 | if (!kept) { tool_err(t, "out of memory"); return; } |
| 235 | |
| 236 | w = 0; |
| 237 | for (i = 0; i < G.n_ent; i++) { |
| 238 | if (o->has_types) { |
| 239 | size_t q; |
| 240 | int ok = 0; |
| 241 | for (q = 0; q < o->n_types; q++) |
| 242 | if (strcmp(o->types[q], G.ent[i].etype) == 0) { ok = 1; break; } |
| 243 | if (!ok) continue; |
| 244 | } |
| 245 | if (o->max_entities > 0 && w >= (size_t)o->max_entities) break; |
| 246 | kept[w++] = &G.ent[i]; |
| 247 | } |
| 248 | k = w; |
| 249 | emit_set(t, kept, k, o); |
| 250 | free(kept); |
| 251 | } |
| 252 | |
| 253 | /* Pull observationLimit / entityTypes out of args. 0 ok, -1 malformed. */ |
| 254 | static int parse_read_opts(yyjson_val *args, read_opt_t *o) |
| 255 | { |
| 256 | yyjson_val *v; |
| 257 | if (!args) return 0; |
| 258 | |
| 259 | v = yyjson_obj_get(args, "observationLimit"); |
| 260 | if (v && !yyjson_is_null(v)) { |
| 261 | int r = arg_opt_int(args, "observationLimit", 0, &o->limit); |
| 262 | if (r != 1) return -1; |
| 263 | o->has_limit = 1; |
| 264 | o->has_count = 1; |
| 265 | } |
| 266 | v = yyjson_obj_get(args, "entityTypes"); |
| 267 | if (v && !yyjson_is_null(v)) { |
| 268 | if (!yyjson_is_arr(v) || yyjson_arr_size(v) == 0) return -1; |
| 269 | if (str_arr_from(v, &o->types, &o->n_types, 1000) != 0) return -1; |
| 270 | if (o->n_types == 0) return -1; |
| 271 | o->has_types = 1; |
| 272 | } |
| 273 | return 0; |
| 274 | } |
| 275 | |
| 276 | /* ------------------------------------------------------------------ */ |
| 277 | /* create_entities */ |
| 278 | /* ------------------------------------------------------------------ */ |
| 279 | |
| 280 | void tool_create_entities(yyjson_val *args, tool_out_t *t) |
| 281 | { |
| 282 | yyjson_val *arr = arg_get(args, "entities"); |
| 283 | yyjson_mut_val *created, *skipped; |
| 284 | size_t i, max; |
| 285 | char err[256]; |
| 286 | |
| 287 | if (!arr || !yyjson_is_arr(arr)) { |
| 288 | tool_err(t, "Missing required parameter: entities"); |
| 289 | return; |
| 290 | } |
| 291 | if (graph_load() != 0) { tool_err(t, "%s", g_data_err[0]); return; } |
| 292 | |
| 293 | tool_start(t); |
| 294 | if (t->is_error) return; |
| 295 | created = yyjson_mut_arr(t->md); |
| 296 | skipped = yyjson_mut_arr(t->md); |
| 297 | max = yyjson_arr_size(arr); |
| 298 | |
| 299 | /* Names already requested earlier in this same batch. */ |
| 300 | for (i = 0; i < max; i++) { |
| 301 | yyjson_val *e = yyjson_arr_get(arr, i); |
| 302 | const char *nm, *ty, *prior; |
| 303 | yyjson_val *ob; |
| 304 | char **obs = NULL; |
| 305 | size_t n_obs = 0, j; |
| 306 | int dup = 0; |
| 307 | |
| 308 | if (!e || !yyjson_is_obj(e)) { |
| 309 | tool_err(t, "Each entity must be an object with name, entityType " |
| 310 | "and observations."); |
| 311 | return; |
| 312 | } |
| 313 | nm = arg_str(e, "name"); |
| 314 | ty = arg_str(e, "entityType"); |
| 315 | ob = arg_get(e, "observations"); |
| 316 | if (!nm || !*nm || !ty || !*ty) { |
| 317 | tool_err(t, "Each entity needs a non-empty name and entityType."); |
| 318 | return; |
| 319 | } |
| 320 | if (ob && !yyjson_is_arr(ob)) { |
| 321 | tool_err(t, "Entity '%s': observations must be an array of " |
| 322 | "strings.", nm); |
| 323 | return; |
| 324 | } |
| 325 | /* repeat earlier in this batch? */ |
| 326 | for (j = 0; j < i && !dup; j++) { |
| 327 | prior = arg_str(yyjson_arr_get(arr, j), "name"); |
| 328 | if (prior && strcmp(prior, nm) == 0) dup = 1; |
| 329 | } |
| 330 | if (dup || ent_find(&G, nm) != NULL) { |
| 331 | yyjson_mut_arr_add_str(t->md, skipped, nm); |
| 332 | continue; |
| 333 | } |
| 334 | if (ob && str_arr_from(ob, &obs, &n_obs, |
| 335 | (size_t)MAX_OBS_PER_ENT_DEFAULT) != 0) { |
| 336 | tool_err(t, "out of memory"); |
| 337 | return; |
| 338 | } |
| 339 | if (ent_add(&G, nm, ty, obs, n_obs, err, sizeof err) != 0) { |
| 340 | for (j = 0; j < n_obs; j++) free(obs[j]); |
| 341 | free(obs); |
| 342 | tool_err(t, "%s", err[0] ? err : "cannot add the entity"); |
| 343 | return; |
| 344 | } |
| 345 | for (j = 0; j < n_obs; j++) free(obs[j]); |
| 346 | free(obs); |
| 347 | G.ent[G.n_ent - 1].keep = 1; |
| 348 | } |
| 349 | |
| 350 | if (graph_save(err, sizeof err) != 0) { |
| 351 | tool_err(t, "%s", err[0] ? err : "cannot write the graph file"); |
| 352 | return; |
| 353 | } |
| 354 | |
| 355 | { |
| 356 | read_opt_t no; |
| 357 | size_t k; |
| 358 | read_opt_init(&no); |
| 359 | for (k = 0; k < G.n_ent; k++) { |
| 360 | if (!G.ent[k].keep) continue; |
| 361 | yyjson_mut_arr_add_val(created, ent_to_mut(t->md, &G.ent[k], &no)); |
| 362 | } |
| 363 | yyjson_mut_obj_add_val(t->md, t->root, "entities", created); |
| 364 | if (yyjson_mut_arr_size(skipped) > 0) { |
| 365 | size_t ns = yyjson_mut_arr_size(skipped), q; |
| 366 | buf_t nb; |
| 367 | char head[128]; |
| 368 | yyjson_mut_obj_add_val(t->md, t->root, "skipped", skipped); |
| 369 | buf_init(&nb); |
| 370 | snprintf(head, sizeof head, "Skipped %zu %s: ", ns, |
| 371 | ns == 1 ? "entity that already exists" |
| 372 | : "entities that already exist"); |
| 373 | buf_puts(&nb, head); |
| 374 | { |
| 375 | /* Walk the array we just built with the iterator that matches |
| 376 | * it: yyjson's immutable getters on a mutable value are a |
| 377 | * type-lie, not a convenience. */ |
| 378 | yyjson_mut_arr_iter ai; |
| 379 | yyjson_mut_val *item; |
| 380 | size_t seen = 0; |
| 381 | yyjson_mut_arr_iter_init(skipped, &ai); |
| 382 | while ((item = yyjson_mut_arr_iter_next(&ai)) != NULL) { |
| 383 | if (seen++) buf_puts(&nb, ", "); |
| 384 | buf_puts(&nb, yyjson_mut_get_str(item)); |
| 385 | } |
| 386 | (void)q; |
| 387 | } |
| 388 | buf_puts(&nb, ns == 1 |
| 389 | ? ". Its observations were not added; use " |
| 390 | "add_observations for existing entities." |
| 391 | : ". Their observations were not added; use " |
| 392 | "add_observations for existing entities."); |
| 393 | t->notice = dup_or_null(buf_str(&nb)); |
| 394 | buf_free(&nb); |
| 395 | } |
| 396 | } |
| 397 | |
| 398 | for (i = 0; i < G.n_ent; i++) G.ent[i].keep = 0; |
| 399 | } |
| 400 | |
| 401 | /* ------------------------------------------------------------------ */ |
| 402 | /* create_relations */ |
| 403 | /* ------------------------------------------------------------------ */ |
| 404 | |
| 405 | void tool_create_relations(yyjson_val *args, tool_out_t *t) |
| 406 | { |
| 407 | yyjson_val *arr = arg_get(args, "relations"); |
| 408 | yyjson_mut_val *created; |
| 409 | size_t i, max; |
| 410 | char err[256]; |
| 411 | |
| 412 | if (!arr || !yyjson_is_arr(arr)) { |
| 413 | tool_err(t, "Missing required parameter: relations"); |
| 414 | return; |
| 415 | } |
| 416 | if (graph_load() != 0) { tool_err(t, "%s", g_data_err[0]); return; } |
| 417 | max = yyjson_arr_size(arr); |
| 418 | |
| 419 | /* Validate every relation before adding any: one missing end fails the |
| 420 | * whole call and nothing is written. */ |
| 421 | for (i = 0; i < max; i++) { |
| 422 | yyjson_val *r = yyjson_arr_get(arr, i); |
| 423 | const char *from = r ? arg_str(r, "from") : NULL; |
| 424 | const char *to = r ? arg_str(r, "to") : NULL; |
| 425 | const char *ty = r ? arg_str(r, "relationType") : NULL; |
| 426 | if (!r || !yyjson_is_obj(r) || !from || !*from || !to || !*to || |
| 427 | !ty || !*ty) { |
| 428 | tool_err(t, "Each relation must be an object with non-empty from, " |
| 429 | "to and relationType."); |
| 430 | return; |
| 431 | } |
| 432 | if (!ent_find(&G, from)) { |
| 433 | tool_err(t, "Entity with name %s not found", from); |
| 434 | return; |
| 435 | } |
| 436 | if (!ent_find(&G, to)) { |
| 437 | tool_err(t, "Entity with name %s not found", to); |
| 438 | return; |
| 439 | } |
| 440 | } |
| 441 | |
| 442 | tool_start(t); |
| 443 | if (t->is_error) return; |
| 444 | created = yyjson_mut_arr(t->md); |
| 445 | |
| 446 | for (i = 0; i < max; i++) { |
| 447 | yyjson_val *r = yyjson_arr_get(arr, i); |
| 448 | const char *from = arg_str(r, "from"); |
| 449 | const char *to = arg_str(r, "to"); |
| 450 | const char *ty = arg_str(r, "relationType"); |
| 451 | size_t j; |
| 452 | int dup = 0; |
| 453 | |
| 454 | for (j = 0; j < G.n_rel; j++) |
| 455 | if (rel_same(&G.rel[j], from, to, ty)) { dup = 1; break; } |
| 456 | for (j = 0; j < i && !dup; j++) { |
| 457 | yyjson_val *q = yyjson_arr_get(arr, j); |
| 458 | if (rel_same_fields(arg_str(q, "from"), arg_str(q, "to"), |
| 459 | arg_str(q, "relationType"), from, to, ty)) |
| 460 | dup = 1; |
| 461 | } |
| 462 | if (dup) continue; |
| 463 | if (rel_add(&G, from, to, ty, err, sizeof err) != 0) { |
| 464 | tool_err(t, "%s", err[0] ? err : "cannot add the relation"); |
| 465 | return; |
| 466 | } |
| 467 | yyjson_mut_arr_add_val(created, rel_to_mut(t->md, from, to, ty)); |
| 468 | } |
| 469 | |
| 470 | if (graph_save(err, sizeof err) != 0) { |
| 471 | tool_err(t, "%s", err[0] ? err : "cannot write the graph file"); |
| 472 | return; |
| 473 | } |
| 474 | yyjson_mut_obj_add_val(t->md, t->root, "relations", created); |
| 475 | } |
| 476 | |
| 477 | /* ------------------------------------------------------------------ */ |
| 478 | /* add_observations */ |
| 479 | /* ------------------------------------------------------------------ */ |
| 480 | |
| 481 | void tool_add_observations(yyjson_val *args, tool_out_t *t) |
| 482 | { |
| 483 | yyjson_val *arr = arg_get(args, "observations"); |
| 484 | yyjson_mut_val *results; |
| 485 | size_t i, max; |
| 486 | char err[256]; |
| 487 | |
| 488 | if (!arr || !yyjson_is_arr(arr)) { |
| 489 | tool_err(t, "Missing required parameter: observations"); |
| 490 | return; |
| 491 | } |
| 492 | if (graph_load() != 0) { tool_err(t, "%s", g_data_err[0]); return; } |
| 493 | |
| 494 | /* Validate first: an unknown entity fails the whole call. */ |
| 495 | max = yyjson_arr_size(arr); |
| 496 | for (i = 0; i < max; i++) { |
| 497 | yyjson_val *o_ = yyjson_arr_get(arr, i); |
| 498 | const char *nm = o_ ? arg_str(o_, "entityName") : NULL; |
| 499 | yyjson_val *contents = o_ ? arg_get(o_, "contents") : NULL; |
| 500 | if (!nm || !*nm) { |
| 501 | tool_err(t, "Each observation needs a non-empty entityName."); |
| 502 | return; |
| 503 | } |
| 504 | if (!contents || !yyjson_is_arr(contents)) { |
| 505 | tool_err(t, "Observations for %s must be an array of strings.", nm); |
| 506 | return; |
| 507 | } |
| 508 | if (!ent_find(&G, nm)) { |
| 509 | tool_err(t, "Entity with name %s not found", nm); |
| 510 | return; |
| 511 | } |
| 512 | } |
| 513 | |
| 514 | tool_start(t); |
| 515 | if (t->is_error) return; |
| 516 | results = yyjson_mut_arr(t->md); |
| 517 | |
| 518 | for (i = 0; i < max; i++) { |
| 519 | yyjson_val *o_ = yyjson_arr_get(arr, i); |
| 520 | const char *nm = arg_str(o_, "entityName"); |
| 521 | yyjson_val *contents = arg_get(o_, "contents"); |
| 522 | entity_t *e = ent_find(&G, nm); |
| 523 | yyjson_mut_val *one, *added_arr; |
| 524 | size_t j, n_c; |
| 525 | |
| 526 | if (!e) continue; |
| 527 | one = yyjson_mut_obj(t->md); |
| 528 | added_arr = yyjson_mut_arr(t->md); |
| 529 | yyjson_mut_obj_add_str(t->md, one, "entityName", nm); |
| 530 | |
| 531 | n_c = yyjson_arr_size(contents); |
| 532 | for (j = 0; j < n_c; j++) { |
| 533 | yyjson_val *cv = yyjson_arr_get(contents, j); |
| 534 | const char *c; |
| 535 | size_t k; |
| 536 | int repeat_in_call = 0, already_there = 0; |
| 537 | if (!cv || !yyjson_is_str(cv)) continue; |
| 538 | c = yyjson_get_str(cv); |
| 539 | if (!c) continue; |
| 540 | /* A string repeated within one call is stored and reported once. */ |
| 541 | for (k = 0; k < j && !repeat_in_call; k++) { |
| 542 | yyjson_val *pv = yyjson_arr_get(contents, k); |
| 543 | if (pv && yyjson_is_str(pv) && |
| 544 | strcmp(yyjson_get_str(pv), c) == 0) repeat_in_call = 1; |
| 545 | } |
| 546 | if (repeat_in_call) continue; |
| 547 | for (k = 0; k < e->n_obs; k++) |
| 548 | if (strcmp(e->obs[k], c) == 0) { already_there = 1; break; } |
| 549 | if (already_there) continue; |
| 550 | if (obs_push(e, c)) |
| 551 | yyjson_mut_arr_add_str(t->md, added_arr, c); |
| 552 | } |
| 553 | yyjson_mut_obj_add_val(t->md, one, "addedObservations", added_arr); |
| 554 | yyjson_mut_arr_add_val(results, one); |
| 555 | } |
| 556 | |
| 557 | if (graph_save(err, sizeof err) != 0) { |
| 558 | tool_err(t, "%s", err[0] ? err : "cannot write the graph file"); |
| 559 | return; |
| 560 | } |
| 561 | yyjson_mut_obj_add_val(t->md, t->root, "results", results); |
| 562 | } |
| 563 | |
| 564 | /* ------------------------------------------------------------------ */ |
| 565 | /* delete_entities */ |
| 566 | /* ------------------------------------------------------------------ */ |
| 567 | |
| 568 | void tool_delete_entities(yyjson_val *args, tool_out_t *t) |
| 569 | { |
| 570 | yyjson_val *arr = arg_get(args, "entityNames"); |
| 571 | size_t i, n_req, n_deleted = 0; |
| 572 | char err[256]; |
| 573 | const char **names = NULL; |
| 574 | int *present = NULL; |
| 575 | |
| 576 | if (!arr || !yyjson_is_arr(arr)) { |
| 577 | tool_err(t, "Missing required parameter: entityNames"); |
| 578 | return; |
| 579 | } |
| 580 | if (graph_load() != 0) { tool_err(t, "%s", g_data_err[0]); return; } |
| 581 | |
| 582 | n_req = yyjson_arr_size(arr); |
| 583 | names = (const char **)calloc(n_req ? n_req : 1, sizeof *names); |
| 584 | present = (int *)calloc(n_req ? n_req : 1, sizeof *present); |
| 585 | if (!names || !present) { |
| 586 | free((void *)names); |
| 587 | free(present); |
| 588 | tool_err(t, "out of memory"); |
| 589 | return; |
| 590 | } |
| 591 | |
| 592 | /* Record each requested name and whether the graph held it BEFORE anything |
| 593 | * is removed. Deriving "not found" after the compaction is not possible: |
| 594 | * a name that was deleted and a name that never existed both read as |
| 595 | * absent, so both facts are captured here, as plain ints - the compaction |
| 596 | * below moves G.ent entries, so no entity_t pointer may outlive this loop |
| 597 | * (lesson: a grid of records is not a set of stable addresses). */ |
| 598 | for (i = 0; i < n_req; i++) { |
| 599 | yyjson_val *v = yyjson_arr_get(arr, i); |
| 600 | const char *nm = (v && yyjson_is_str(v)) ? yyjson_get_str(v) : NULL; |
| 601 | size_t k; |
| 602 | int counted = 0; |
| 603 | names[i] = nm; |
| 604 | if (!nm) continue; |
| 605 | for (k = 0; k < G.n_ent; k++) |
| 606 | if (strcmp(G.ent[k].name, nm) == 0) { present[i] = 1; G.ent[k].keep = 1; break; } |
| 607 | for (k = 0; k < i; k++) |
| 608 | if (names[k] && strcmp(names[k], nm) == 0) { counted = 1; break; } |
| 609 | if (present[i] && !counted) n_deleted++; |
| 610 | } |
| 611 | |
| 612 | { |
| 613 | size_t w = 0, r2; |
| 614 | for (r2 = 0; r2 < G.n_rel; r2++) { |
| 615 | size_t q; |
| 616 | int hit = 0; |
| 617 | for (q = 0; q < n_req; q++) { |
| 618 | const char *nm = names[q]; |
| 619 | if (!nm) continue; |
| 620 | if (strcmp(G.rel[r2].from, nm) == 0 || |
| 621 | strcmp(G.rel[r2].to, nm) == 0) { hit = 1; break; } |
| 622 | } |
| 623 | if (hit) { |
| 624 | free(G.rel[r2].from); |
| 625 | free(G.rel[r2].to); |
| 626 | free(G.rel[r2].rtype); |
| 627 | continue; |
| 628 | } |
| 629 | G.rel[w++] = G.rel[r2]; |
| 630 | } |
| 631 | G.n_rel = w; |
| 632 | } |
| 633 | { |
| 634 | size_t w = 0, r2; |
| 635 | for (r2 = 0; r2 < G.n_ent; r2++) { |
| 636 | if (G.ent[r2].keep) { |
| 637 | size_t q; |
| 638 | for (q = 0; q < G.ent[r2].n_obs; q++) free(G.ent[r2].obs[q]); |
| 639 | free(G.ent[r2].obs); |
| 640 | free(G.ent[r2].name); |
| 641 | free(G.ent[r2].etype); |
| 642 | continue; |
| 643 | } |
| 644 | G.ent[w++] = G.ent[r2]; |
| 645 | } |
| 646 | G.n_ent = w; |
| 647 | } |
| 648 | |
| 649 | if (graph_save(err, sizeof err) != 0) { |
| 650 | free((void *)names); |
| 651 | free(present); |
| 652 | tool_err(t, "%s", err[0] ? err : "cannot write the graph file"); |
| 653 | return; |
| 654 | } |
| 655 | |
| 656 | tool_start(t); |
| 657 | if (!t->is_error) { |
| 658 | buf_t msg; |
| 659 | buf_init(&msg); |
| 660 | if (n_deleted == n_req) { |
| 661 | buf_puts(&msg, "Entities deleted successfully"); |
| 662 | } else { |
| 663 | char tmp[96]; |
| 664 | int first = 1; |
| 665 | snprintf(tmp, sizeof tmp, "Deleted %zu of %zu entities. Not found: ", |
| 666 | n_deleted, n_req); |
| 667 | buf_puts(&msg, tmp); |
| 668 | for (i = 0; i < n_req; i++) { |
| 669 | if (!names[i] || present[i]) continue; |
| 670 | if (!first) buf_puts(&msg, ", "); |
| 671 | buf_puts(&msg, names[i]); |
| 672 | first = 0; |
| 673 | } |
| 674 | } |
| 675 | yyjson_mut_obj_add_bool(t->md, t->root, "success", 1); |
| 676 | /* add_str keeps the pointer, add_strcpy copies into the doc. The message |
| 677 | * lives in a buf_t that is freed the moment this block ends, so the |
| 678 | * copy is the only way it survives into the serialised result. */ |
| 679 | yyjson_mut_obj_add_strcpy(t->md, t->root, "message", buf_str(&msg)); |
| 680 | buf_free(&msg); |
| 681 | } |
| 682 | free((void *)names); |
| 683 | free(present); |
| 684 | } |
| 685 | |
| 686 | /* ------------------------------------------------------------------ */ |
| 687 | /* delete_observations */ |
| 688 | /* ------------------------------------------------------------------ */ |
| 689 | |
| 690 | void tool_delete_observations(yyjson_val *args, tool_out_t *t) |
| 691 | { |
| 692 | yyjson_val *arr = arg_get(args, "deletions"); |
| 693 | size_t i, max, requested = 0, deleted = 0; |
| 694 | char err[256]; |
| 695 | buf_t missing; |
| 696 | |
| 697 | if (!arr || !yyjson_is_arr(arr)) { |
| 698 | tool_err(t, "Missing required parameter: deletions"); |
| 699 | return; |
| 700 | } |
| 701 | if (graph_load() != 0) { tool_err(t, "%s", g_data_err[0]); return; } |
| 702 | |
| 703 | buf_init(&missing); |
| 704 | max = yyjson_arr_size(arr); |
| 705 | for (i = 0; i < max; i++) { |
| 706 | yyjson_val *d = yyjson_arr_get(arr, i); |
| 707 | const char *nm = d ? arg_str(d, "entityName") : NULL; |
| 708 | yyjson_val *obs = d ? arg_get(d, "observations") : NULL; |
| 709 | entity_t *e; |
| 710 | size_t j, n_o; |
| 711 | |
| 712 | if (!nm || !*nm) { |
| 713 | buf_free(&missing); |
| 714 | tool_err(t, "Each deletion needs a non-empty entityName."); |
| 715 | return; |
| 716 | } |
| 717 | if (!obs || !yyjson_is_arr(obs)) { |
| 718 | buf_free(&missing); |
| 719 | tool_err(t, "Observations for %s must be an array of strings.", nm); |
| 720 | return; |
| 721 | } |
| 722 | e = ent_find(&G, nm); |
| 723 | n_o = yyjson_arr_size(obs); |
| 724 | requested += n_o; |
| 725 | if (!e) { |
| 726 | if (missing.n) buf_puts(&missing, ", "); |
| 727 | buf_puts(&missing, nm); |
| 728 | continue; |
| 729 | } |
| 730 | for (j = 0; j < n_o; j++) { |
| 731 | yyjson_val *v = yyjson_arr_get(obs, j); |
| 732 | const char *c = (v && yyjson_is_str(v)) ? yyjson_get_str(v) : NULL; |
| 733 | size_t w = 0, q; |
| 734 | if (!c) continue; |
| 735 | for (q = 0; q < e->n_obs; q++) { |
| 736 | if (strcmp(e->obs[q], c) == 0) { free(e->obs[q]); deleted++; continue; } |
| 737 | e->obs[w++] = e->obs[q]; |
| 738 | } |
| 739 | e->n_obs = w; |
| 740 | } |
| 741 | } |
| 742 | |
| 743 | if (graph_save(err, sizeof err) != 0) { |
| 744 | buf_free(&missing); |
| 745 | tool_err(t, "%s", err[0] ? err : "cannot write the graph file"); |
| 746 | return; |
| 747 | } |
| 748 | |
| 749 | tool_start(t); |
| 750 | if (!t->is_error) { |
| 751 | buf_t msg; |
| 752 | buf_init(&msg); |
| 753 | if (deleted == requested) { |
| 754 | buf_puts(&msg, "Observations deleted successfully"); |
| 755 | } else { |
| 756 | char tmp[96]; |
| 757 | snprintf(tmp, sizeof tmp, "Deleted %zu of %zu observations.", |
| 758 | deleted, requested); |
| 759 | buf_puts(&msg, tmp); |
| 760 | if (missing.n) { |
| 761 | buf_puts(&msg, " Entities not found: "); |
| 762 | buf_puts(&msg, buf_str(&missing)); |
| 763 | } |
| 764 | } |
| 765 | yyjson_mut_obj_add_bool(t->md, t->root, "success", 1); |
| 766 | /* add_str keeps the pointer, add_strcpy copies into the doc. The message |
| 767 | * lives in a buf_t that is freed the moment this block ends, so the |
| 768 | * copy is the only way it survives into the serialised result. */ |
| 769 | yyjson_mut_obj_add_strcpy(t->md, t->root, "message", buf_str(&msg)); |
| 770 | buf_free(&msg); |
| 771 | } |
| 772 | buf_free(&missing); |
| 773 | } |
| 774 | |
| 775 | /* ------------------------------------------------------------------ */ |
| 776 | /* delete_relations */ |
| 777 | /* ------------------------------------------------------------------ */ |
| 778 | |
| 779 | void tool_delete_relations(yyjson_val *args, tool_out_t *t) |
| 780 | { |
| 781 | yyjson_val *arr = arg_get(args, "relations"); |
| 782 | size_t max, before, deleted; |
| 783 | char err[256]; |
| 784 | |
| 785 | if (!arr || !yyjson_is_arr(arr)) { |
| 786 | tool_err(t, "Missing required parameter: relations"); |
| 787 | return; |
| 788 | } |
| 789 | if (graph_load() != 0) { tool_err(t, "%s", g_data_err[0]); return; } |
| 790 | max = yyjson_arr_size(arr); |
| 791 | |
| 792 | before = G.n_rel; |
| 793 | { |
| 794 | size_t w = 0, r2; |
| 795 | for (r2 = 0; r2 < G.n_rel; r2++) { |
| 796 | size_t q; |
| 797 | int hit = 0; |
| 798 | for (q = 0; q < max; q++) { |
| 799 | yyjson_val *d = yyjson_arr_get(arr, q); |
| 800 | if (!d || !yyjson_is_obj(d)) continue; |
| 801 | if (rel_same_fields(arg_str(d, "from"), arg_str(d, "to"), |
| 802 | arg_str(d, "relationType"), |
| 803 | G.rel[r2].from, G.rel[r2].to, |
| 804 | G.rel[r2].rtype)) { hit = 1; break; } |
| 805 | } |
| 806 | if (hit) { |
| 807 | free(G.rel[r2].from); |
| 808 | free(G.rel[r2].to); |
| 809 | free(G.rel[r2].rtype); |
| 810 | continue; |
| 811 | } |
| 812 | G.rel[w++] = G.rel[r2]; |
| 813 | } |
| 814 | G.n_rel = w; |
| 815 | } |
| 816 | deleted = before - G.n_rel; |
| 817 | |
| 818 | if (graph_save(err, sizeof err) != 0) { |
| 819 | tool_err(t, "%s", err[0] ? err : "cannot write the graph file"); |
| 820 | return; |
| 821 | } |
| 822 | |
| 823 | tool_start(t); |
| 824 | if (!t->is_error) { |
| 825 | buf_t msg; |
| 826 | buf_init(&msg); |
| 827 | if (deleted == max) { |
| 828 | buf_puts(&msg, "Relations deleted successfully"); |
| 829 | } else { |
| 830 | char tmp[128]; |
| 831 | snprintf(tmp, sizeof tmp, |
| 832 | "Deleted %zu of %zu relations. The rest matched nothing.", |
| 833 | deleted, max); |
| 834 | buf_puts(&msg, tmp); |
| 835 | } |
| 836 | yyjson_mut_obj_add_bool(t->md, t->root, "success", 1); |
| 837 | /* add_str keeps the pointer, add_strcpy copies into the doc. The message |
| 838 | * lives in a buf_t that is freed the moment this block ends, so the |
| 839 | * copy is the only way it survives into the serialised result. */ |
| 840 | yyjson_mut_obj_add_strcpy(t->md, t->root, "message", buf_str(&msg)); |
| 841 | buf_free(&msg); |
| 842 | } |
| 843 | } |
| 844 | |
| 845 | /* ------------------------------------------------------------------ */ |
| 846 | /* The read tools */ |
| 847 | /* ------------------------------------------------------------------ */ |
| 848 | |
| 849 | void tool_read_graph(yyjson_val *args, tool_out_t *t) |
| 850 | { |
| 851 | read_opt_t o; |
| 852 | read_opt_init(&o); |
| 853 | if (parse_read_opts(args, &o) != 0) { |
| 854 | read_opt_free_types(&o); |
| 855 | tool_err(t, "observationLimit must be an integer >= 0 and entityTypes " |
| 856 | "a non-empty array of strings."); |
| 857 | return; |
| 858 | } |
| 859 | if (graph_load() != 0) { |
| 860 | read_opt_free_types(&o); |
| 861 | tool_err(t, "%s", g_data_err[0]); |
| 862 | return; |
| 863 | } |
| 864 | tool_start(t); |
| 865 | if (!t->is_error) emit_all(t, &o); |
| 866 | read_opt_free_types(&o); |
| 867 | } |
| 868 | |
| 869 | void tool_search_nodes(yyjson_val *args, tool_out_t *t) |
| 870 | { |
| 871 | read_opt_t o; |
| 872 | const char *query; |
| 873 | entity_t **hits; |
| 874 | size_t i, n_hits = 0, cap; |
| 875 | int rc; |
| 876 | |
| 877 | read_opt_init(&o); |
| 878 | if (!args || !yyjson_is_str(yyjson_obj_get(args, "query"))) { |
| 879 | tool_err(t, "Missing required parameter: query"); |
| 880 | return; |
| 881 | } |
| 882 | query = yyjson_get_str(yyjson_obj_get(args, "query")); |
| 883 | rc = arg_opt_int(args, "limit", 1, &o.max_entities); |
| 884 | if (rc == -1) { tool_err(t, "limit must be an integer >= 1"); return; } |
| 885 | if (parse_read_opts(args, &o) != 0) { |
| 886 | read_opt_free_types(&o); |
| 887 | tool_err(t, "observationLimit must be an integer >= 0."); |
| 888 | return; |
| 889 | } |
| 890 | if (graph_load() != 0) { |
| 891 | read_opt_free_types(&o); |
| 892 | tool_err(t, "%s", g_data_err[0]); |
| 893 | return; |
| 894 | } |
| 895 | |
| 896 | cap = G.n_ent ? G.n_ent : 1; |
| 897 | hits = (entity_t **)malloc(cap * sizeof *hits); |
| 898 | if (!hits) { read_opt_free_types(&o); tool_err(t, "out of memory"); return; } |
| 899 | |
| 900 | for (i = 0; i < G.n_ent; i++) { |
| 901 | size_t q; |
| 902 | int hit = str_icontains(G.ent[i].name, query) || |
| 903 | str_icontains(G.ent[i].etype, query); |
| 904 | for (q = 0; !hit && q < G.ent[i].n_obs; q++) |
| 905 | if (str_icontains(G.ent[i].obs[q], query)) hit = 1; |
| 906 | if (hit) hits[n_hits++] = &G.ent[i]; |
| 907 | if (o.max_entities > 0 && n_hits >= (size_t)o.max_entities) break; |
| 908 | } |
| 909 | |
| 910 | tool_start(t); |
| 911 | if (!t->is_error) emit_set(t, hits, n_hits, &o); |
| 912 | free(hits); |
| 913 | read_opt_free_types(&o); |
| 914 | } |
| 915 | |
| 916 | void tool_open_nodes(yyjson_val *args, tool_out_t *t) |
| 917 | { |
| 918 | read_opt_t o; |
| 919 | yyjson_val *arr; |
| 920 | entity_t **want; |
| 921 | size_t i, max, n_want = 0; |
| 922 | |
| 923 | read_opt_init(&o); |
| 924 | if (!args) { tool_err(t, "Missing required parameter: names"); return; } |
| 925 | arr = yyjson_obj_get(args, "names"); |
| 926 | if (!arr || !yyjson_is_arr(arr)) { |
| 927 | tool_err(t, "Missing required parameter: names"); |
| 928 | return; |
| 929 | } |
| 930 | if (parse_read_opts(args, &o) != 0) { |
| 931 | read_opt_free_types(&o); |
| 932 | tool_err(t, "observationLimit must be an integer >= 0."); |
| 933 | return; |
| 934 | } |
| 935 | if (graph_load() != 0) { |
| 936 | read_opt_free_types(&o); |
| 937 | tool_err(t, "%s", g_data_err[0]); |
| 938 | return; |
| 939 | } |
| 940 | |
| 941 | max = yyjson_arr_size(arr); |
| 942 | want = (entity_t **)malloc(((max ? max : 1)) * sizeof *want); |
| 943 | if (!want) { read_opt_free_types(&o); tool_err(t, "out of memory"); return; } |
| 944 | |
| 945 | /* Stored order, one entry per matching entity; names that miss are |
| 946 | * simply skipped. */ |
| 947 | for (i = 0; i < G.n_ent && n_want < max; i++) { |
| 948 | size_t q; |
| 949 | for (q = 0; q < max; q++) { |
| 950 | yyjson_val *v = yyjson_arr_get(arr, q); |
| 951 | const char *nm = (v && yyjson_is_str(v)) ? yyjson_get_str(v) : NULL; |
| 952 | if (nm && strcmp(nm, G.ent[i].name) == 0) { want[n_want++] = &G.ent[i]; break; } |
| 953 | } |
| 954 | } |
| 955 | |
| 956 | tool_start(t); |
| 957 | if (!t->is_error) emit_set(t, want, n_want, &o); |
| 958 | free(want); |
| 959 | read_opt_free_types(&o); |
| 960 | } |
| 961 | |
| 962 | /* ------------------------------------------------------------------ */ |
| 963 | /* tools/list */ |
| 964 | /* ------------------------------------------------------------------ */ |
| 965 | |
| 966 | static const char *TOOLS_LIST_JSON = |
| 967 | "[" |
| 968 | "{\"name\":\"create_entities\"," |
| 969 | "\"description\":\"Create multiple new entities in the knowledge graph. An entity whose name already exists, or repeats an earlier entity in the same call, is skipped and its observations are not added; the result lists the skipped names in `skipped`. Use add_observations to add observations to an existing entity.\"," |
| 970 | "\"inputSchema\":{\"type\":\"object\",\"properties\":{\"entities\":{\"type\":\"array\",\"items\":{\"type\":\"object\",\"properties\":{\"name\":{\"type\":\"string\",\"description\":\"The name of the entity\"},\"entityType\":{\"type\":\"string\",\"description\":\"The type of the entity\"},\"observations\":{\"type\":\"array\",\"items\":{\"type\":\"string\"},\"description\":\"An array of observation contents associated with the entity\"}},\"required\":[\"name\",\"entityType\",\"observations\"]},\"description\":\"The entities to create, each with a name unique in the graph\"}},\"required\":[\"entities\"]}," |
| 971 | "\"annotations\":{\"readOnlyHint\":false,\"destructiveHint\":false,\"idempotentHint\":true,\"openWorldHint\":false}}," |
| 972 | |
| 973 | "{\"name\":\"create_relations\"," |
| 974 | "\"description\":\"Create multiple new relations between entities in the knowledge graph. Relations should be in active voice.\"," |
| 975 | "\"inputSchema\":{\"type\":\"object\",\"properties\":{\"relations\":{\"type\":\"array\",\"items\":{\"type\":\"object\",\"properties\":{\"from\":{\"type\":\"string\",\"description\":\"The name of the entity where the relation starts\"},\"to\":{\"type\":\"string\",\"description\":\"The name of the entity where the relation ends\"},\"relationType\":{\"type\":\"string\",\"description\":\"The type of the relation\"}},\"required\":[\"from\",\"to\",\"relationType\"]},\"description\":\"The relations to create. Both ends must name existing entities; a relation already in the graph is not added again\"}},\"required\":[\"relations\"]}," |
| 976 | "\"annotations\":{\"readOnlyHint\":false,\"destructiveHint\":false,\"idempotentHint\":true,\"openWorldHint\":false}}," |
| 977 | |
| 978 | "{\"name\":\"add_observations\"," |
| 979 | "\"description\":\"Add new observations to existing entities in the knowledge graph.\"," |
| 980 | "\"inputSchema\":{\"type\":\"object\",\"properties\":{\"observations\":{\"type\":\"array\",\"items\":{\"type\":\"object\",\"properties\":{\"entityName\":{\"type\":\"string\",\"description\":\"The name of the entity to add the observations to\"},\"contents\":{\"type\":\"array\",\"items\":{\"type\":\"string\"},\"description\":\"An array of observation contents to add\"}},\"required\":[\"entityName\",\"contents\"]},\"description\":\"The observations to add, grouped by entity. Each entity must already exist; an observation it already has is not added again\"}},\"required\":[\"observations\"]}," |
| 981 | "\"annotations\":{\"readOnlyHint\":false,\"destructiveHint\":false,\"idempotentHint\":true,\"openWorldHint\":false}}," |
| 982 | |
| 983 | "{\"name\":\"delete_entities\"," |
| 984 | "\"description\":\"Delete whole entities from the knowledge graph, together with every relation that points to or from them and all their observations. Use it only to remove an entity entirely; to remove a link between two entities and keep both, use delete_relations, and to remove facts from an entity, use delete_observations. Cannot be undone.\"," |
| 985 | "\"inputSchema\":{\"type\":\"object\",\"properties\":{\"entityNames\":{\"type\":\"array\",\"items\":{\"type\":\"string\"},\"description\":\"An array of entity names to delete\"}},\"required\":[\"entityNames\"]}," |
| 986 | "\"annotations\":{\"readOnlyHint\":false,\"destructiveHint\":true,\"idempotentHint\":true,\"openWorldHint\":false}}," |
| 987 | |
| 988 | "{\"name\":\"delete_observations\"," |
| 989 | "\"description\":\"Delete specific observations from entities in the knowledge graph.\"," |
| 990 | "\"inputSchema\":{\"type\":\"object\",\"properties\":{\"deletions\":{\"type\":\"array\",\"items\":{\"type\":\"object\",\"properties\":{\"entityName\":{\"type\":\"string\",\"description\":\"The name of the entity containing the observations\"},\"observations\":{\"type\":\"array\",\"items\":{\"type\":\"string\"},\"description\":\"An array of observations to delete\"}},\"required\":[\"entityName\",\"observations\"]},\"description\":\"The observations to delete, grouped by entity, each matched by its exact text\"}},\"required\":[\"deletions\"]}," |
| 991 | "\"annotations\":{\"readOnlyHint\":false,\"destructiveHint\":true,\"idempotentHint\":true,\"openWorldHint\":false}}," |
| 992 | |
| 993 | "{\"name\":\"delete_relations\"," |
| 994 | "\"description\":\"Delete specific relations (from, to, relationType) from the knowledge graph and keep the entities they connect. Each relation must match an existing one exactly on all three fields; if unsure, call open_nodes (or search_nodes) first to read the stored relationType. Use it to remove a link between two entities; to remove an entity itself, use delete_entities. Cannot be undone.\"," |
| 995 | "\"inputSchema\":{\"type\":\"object\",\"properties\":{\"relations\":{\"type\":\"array\",\"items\":{\"type\":\"object\",\"properties\":{\"from\":{\"type\":\"string\",\"description\":\"The name of the entity where the relation starts\"},\"to\":{\"type\":\"string\",\"description\":\"The name of the entity where the relation ends\"},\"relationType\":{\"type\":\"string\",\"description\":\"The type of the relation\"}},\"required\":[\"from\",\"to\",\"relationType\"]},\"description\":\"An array of relations to delete\"}},\"required\":[\"relations\"]}," |
| 996 | "\"annotations\":{\"readOnlyHint\":false,\"destructiveHint\":true,\"idempotentHint\":true,\"openWorldHint\":false}}," |
| 997 | |
| 998 | "{\"name\":\"read_graph\"," |
| 999 | "\"description\":\"Read the entire knowledge graph: every entity with its observations, and every relation. The result grows with the graph, so use this only when you need everything; prefer search_nodes to find entities by keyword and open_nodes to read entities whose names you know.\"," |
| 1000 | "\"inputSchema\":{\"type\":\"object\",\"properties\":{\"entityTypes\":{\"type\":\"array\",\"items\":{\"type\":\"string\"},\"description\":\"Return only entities whose entityType is one of these (exact match), and only the relations that touch one of them. Omit to return every entity.\"},\"observationLimit\":{\"type\":\"integer\",\"minimum\":0,\"description\":\"Return at most this many observations per entity (the first ones, in the order they were added) and add each entity's total as observationCount. Use 0 for names, types and counts only: a cheap overview of a large graph, after which open_nodes reads the entities you need in full. Omit to return every observation.\"}}}," |
| 1001 | "\"annotations\":{\"readOnlyHint\":true,\"destructiveHint\":false,\"idempotentHint\":true,\"openWorldHint\":false}}," |
| 1002 | |
| 1003 | "{\"name\":\"search_nodes\"," |
| 1004 | "\"description\":\"Search the knowledge graph for entities whose name, type or observations contain the query (case-insensitive). Use this when you have a keyword, a topic or part of a name but not the exact entity names. Prefer open_nodes when you already know the exact names, and use read_graph only when you need the whole graph. Returns the matching entities and every relation that touches one of them.\"," |
| 1005 | "\"inputSchema\":{\"type\":\"object\",\"properties\":{\"query\":{\"type\":\"string\",\"description\":\"The search query to match against entity names, types and observation content\"},\"limit\":{\"type\":\"integer\",\"minimum\":1,\"description\":\"Return at most this many matching entities (the first matches, in stored order), with the relations that touch them. Omit to return every match.\"},\"observationLimit\":{\"type\":\"integer\",\"minimum\":0,\"description\":\"Return at most this many observations per entity (the first ones, in the order they were added) and add each entity's total as observationCount. Use 0 for names, types and counts only: a cheap overview of a large graph, after which open_nodes reads the entities you need in full. Omit to return every observation.\"}},\"required\":[\"query\"]}," |
| 1006 | "\"annotations\":{\"readOnlyHint\":true,\"destructiveHint\":false,\"idempotentHint\":true,\"openWorldHint\":false}}," |
| 1007 | |
| 1008 | "{\"name\":\"open_nodes\"," |
| 1009 | "\"description\":\"Retrieve specific entities by their exact names, with every relation that touches one of them. Use this when you already know the names (from the conversation, or from an earlier search_nodes or read_graph result); it is the cheapest way to read entities you can name. Prefer search_nodes when you only have a keyword or part of a name. Names that do not exist are skipped.\"," |
| 1010 | "\"inputSchema\":{\"type\":\"object\",\"properties\":{\"names\":{\"type\":\"array\",\"items\":{\"type\":\"string\"},\"description\":\"An array of entity names to retrieve\"},\"observationLimit\":{\"type\":\"integer\",\"minimum\":0,\"description\":\"Return at most this many observations per entity (the first ones, in the order they were added) and add each entity's total as observationCount. Use 0 for names, types and counts only: a cheap overview of a large graph, after which open_nodes reads the entities you need in full. Omit to return every observation.\"}},\"required\":[\"names\"]}," |
| 1011 | "\"annotations\":{\"readOnlyHint\":true,\"destructiveHint\":false,\"idempotentHint\":true,\"openWorldHint\":false}}" |
| 1012 | "]"; |
| 1013 | |
| 1014 | char *tools_list_json(void) |
| 1015 | { |
| 1016 | return dup_or_null(TOOLS_LIST_JSON); |
| 1017 | } |
| 1018 | |
| 1019 | int tool_dispatch(const char *name, yyjson_val *args, tool_out_t *out) |
| 1020 | { |
| 1021 | tool_out_init(out); |
| 1022 | if (!name) return -1; |
| 1023 | if (strcmp(name, "create_entities") == 0) { tool_create_entities(args, out); return 0; } |
| 1024 | if (strcmp(name, "create_relations") == 0) { tool_create_relations(args, out); return 0; } |
| 1025 | if (strcmp(name, "add_observations") == 0) { tool_add_observations(args, out); return 0; } |
| 1026 | if (strcmp(name, "delete_entities") == 0) { tool_delete_entities(args, out); return 0; } |
| 1027 | if (strcmp(name, "delete_observations") == 0) { tool_delete_observations(args, out); return 0; } |
| 1028 | if (strcmp(name, "delete_relations") == 0) { tool_delete_relations(args, out); return 0; } |
| 1029 | if (strcmp(name, "read_graph") == 0) { tool_read_graph(args, out); return 0; } |
| 1030 | if (strcmp(name, "search_nodes") == 0) { tool_search_nodes(args, out); return 0; } |
| 1031 | if (strcmp(name, "open_nodes") == 0) { tool_open_nodes(args, out); return 0; } |
| 1032 | return -1; |
| 1033 | } |
| 1034 | |
| 1035 | /* ------------------------------------------------------------------ */ |
| 1036 | /* Serialisation */ |
| 1037 | /* ------------------------------------------------------------------ */ |
| 1038 | |
| 1039 | char *tool_mcp_result(tool_out_t *t) |
| 1040 | { |
| 1041 | buf_t b; |
| 1042 | char *out; |
| 1043 | |
| 1044 | buf_init(&b); |
| 1045 | if (t->is_error) { |
| 1046 | /* A tool-level failure is a *result* with isError, not a JSON-RPC |
| 1047 | * error: the call itself succeeded and this is what hosts render. */ |
| 1048 | buf_puts(&b, "{\"content\":[{\"type\":\"text\",\"text\":"); |
| 1049 | json_str(&b, t->error ? t->error : "the tool could not be completed"); |
| 1050 | buf_puts(&b, "}],\"isError\":true}"); |
| 1051 | out = dup_or_null(buf_str(&b)); |
| 1052 | buf_free(&b); |
| 1053 | return out; |
| 1054 | } |
| 1055 | |
| 1056 | { |
| 1057 | char *pretty = (t->md && t->root) |
| 1058 | ? yyjson_mut_write(t->md, YYJSON_WRITE_PRETTY_TWO_SPACES, NULL) |
| 1059 | : dup_or_null("{}"); |
| 1060 | buf_puts(&b, "{\"content\":[{\"type\":\"text\",\"text\":"); |
| 1061 | json_str(&b, pretty ? pretty : "{}"); |
| 1062 | buf_puts(&b, "}"); |
| 1063 | free(pretty); |
| 1064 | if (t->notice && *t->notice) { |
| 1065 | buf_puts(&b, ",{\"type\":\"text\",\"text\":"); |
| 1066 | json_str(&b, t->notice); |
| 1067 | buf_puts(&b, "}"); |
| 1068 | } |
| 1069 | buf_puts(&b, "],\"isError\":false"); |
| 1070 | } |
| 1071 | |
| 1072 | if (t->md && t->root && yyjson_mut_obj_size(t->root) > 0) { |
| 1073 | char *compact = yyjson_mut_write(t->md, 0, NULL); |
| 1074 | if (compact) { |
| 1075 | buf_puts(&b, ",\"structuredContent\":"); |
| 1076 | buf_puts(&b, compact); |
| 1077 | free(compact); |
| 1078 | } |
| 1079 | } |
| 1080 | buf_puts(&b, "}"); |
| 1081 | out = dup_or_null(buf_str(&b)); |
| 1082 | buf_free(&b); |
| 1083 | return out; |
| 1084 | } |
| 1085 | |
| 1086 | char *tool_api_result(tool_out_t *t) |
| 1087 | { |
| 1088 | buf_t b; |
| 1089 | char *out; |
| 1090 | |
| 1091 | buf_init(&b); |
| 1092 | if (t->is_error) { |
| 1093 | buf_puts(&b, "{\"ok\":false,\"error\":"); |
| 1094 | json_str(&b, t->error ? t->error : "the tool could not be completed"); |
| 1095 | buf_puts(&b, "}"); |
| 1096 | out = dup_or_null(buf_str(&b)); |
| 1097 | buf_free(&b); |
| 1098 | return out; |
| 1099 | } |
| 1100 | if (!t->md || !t->root || yyjson_mut_obj_size(t->root) == 0) { |
| 1101 | buf_free(&b); |
| 1102 | return dup_or_null("{\"ok\":true}"); |
| 1103 | } |
| 1104 | { |
| 1105 | /* The result object always begins with '{', so splicing ok in front |
| 1106 | * of it is a byte-level operation on JSON this very document |
| 1107 | * produced - one buffer, one write, no re-parsing (and no field |
| 1108 | * reordering, which a half-buffer/half-printf builder causes). */ |
| 1109 | char *compact = yyjson_mut_write(t->md, 0, NULL); |
| 1110 | if (!compact) { |
| 1111 | buf_free(&b); |
| 1112 | return dup_or_null("{\"ok\":false,\"error\":\"could not " |
| 1113 | "serialise the result\"}"); |
| 1114 | } |
| 1115 | buf_puts(&b, "{\"ok\":true"); |
| 1116 | if (compact[0] == '{' && compact[1] != '}') { |
| 1117 | buf_putc(&b, ','); |
| 1118 | buf_puts(&b, compact + 1); /* keeps the trailing '}' */ |
| 1119 | } else { |
| 1120 | buf_puts(&b, "}"); |
| 1121 | } |
| 1122 | free(compact); |
| 1123 | } |
| 1124 | out = dup_or_null(buf_str(&b)); |
| 1125 | buf_free(&b); |
| 1126 | return out; |
| 1127 | } |