Local code intelligence for developers and AI agents. Connect code, docs and infrastructure in a persistent graph, with CBM Lens, MCP tools, agent integrations and change-aware test selection.
C aiderastclaude-codecode-analysiscode-intelligencecodexcursorcypherdeveloper-toolsgemini-cligraph-visualizationkilocodeknowledge-graphmcpmcp-servermodel-context-protocolopencodesqlitetree-sitterwindsurf
feat(mcp): TOON compact output for search_graph — ~90% fewer response tokens
Martin Vogel4843a340656c
diff --git a/Makefile.cbm b/Makefile.cbmindex 43ba5ffca..44ccb7473 100644--- a/Makefile.cbm+++ b/Makefile.cbm@@ -174,7 +174,7 @@ STORE_SRCS = src/store/store.cCYPHER_SRCS = src/cypher/cypher.c# MCP server module (new)-MCP_SRCS = src/mcp/mcp.c src/mcp/index_supervisor.c+MCP_SRCS = src/mcp/mcp.c src/mcp/index_supervisor.c src/mcp/compact_out.c# Discover module (new)DISCOVER_SRCS = \diff --git a/scripts/smoke-test.sh b/scripts/smoke-test.shindex 6d9675f13..c93e1dfbe 100755--- a/scripts/smoke-test.sh+++ b/scripts/smoke-test.sh@@ -174,7 +174,9 @@ PROJECT=$(echo "$RESULT" | python3 -c "import json,sys; d=json.loads(sys.stdin.rif ! SEARCH=$(cli search_graph --project "$PROJECT" --name-pattern compute); thenecho "FAIL: search_graph (flag form) exited non-zero"; cat "$CLI_STDERR"; exit 1fi-TOTAL=$(echo "$SEARCH" | python3 -c "import json,sys; d=json.loads(sys.stdin.read()); print(d.get('total',0))" 2>/dev/null || echo "0")+# search_graph default output is TOON (key: value scalars + header/rows tables)+TOTAL=$(echo "$SEARCH" | sed -n 's/^total: //p' | head -1)+TOTAL=${TOTAL:-0}if [ "$TOTAL" -lt 1 ]; thenecho "FAIL: search_graph for 'compute' returned 0 results"exit 1@@ -207,7 +209,8 @@ echo "OK: schema has $LABELS node labels"if ! FOLDERS=$(cli search_graph --project "$PROJECT" --label Folder); thenecho "FAIL: search_graph --label Folder exited non-zero"; cat "$CLI_STDERR"; exit 1fi-FOLDER_COUNT=$(echo "$FOLDERS" | python3 -c "import json,sys; d=json.loads(sys.stdin.read()); print(d.get('total',0))" 2>/dev/null || echo "0")+FOLDER_COUNT=$(echo "$FOLDERS" | sed -n 's/^total: //p' | head -1)+FOLDER_COUNT=${FOLDER_COUNT:-0}if [ "$FOLDER_COUNT" -lt 2 ]; thenecho "FAIL: expected at least 2 Folder nodes (src, src/pkg), got $FOLDER_COUNT"exit 1@@ -396,36 +399,39 @@ echo "=== Phase 3h: CLI input-mode guards (flags / stdin / --args-file / --help# Small helper: assert its stdin is a JSON object (exit non-zero otherwise).assert_json_obj() { python3 -c "import json,sys; d=json.loads(sys.stdin.read()); sys.exit(0 if isinstance(d,dict) else 1)" 2>/dev/null; }+# search_graph emits TOON by default: a results/semantic table header proves+# the tool parsed its typed flags and produced a well-formed response.+assert_toon_table() { grep -qE '^(results|semantic)\[[0-9]+\]\{'; }-# B1: INTEGER flag — --limit is schema-typed integer; must parse to valid JSON.+# B1: INTEGER flag — --limit is schema-typed integer; must parse and answer.if ! IM_INT=$(cli search_graph --project "$PROJECT" --name-pattern compute --limit 5); thenecho "FAIL B1: search_graph --limit 5 exited non-zero"; cat "$CLI_STDERR"; exit 1fi-if echo "$IM_INT" | assert_json_obj; then- echo "OK B1: INTEGER flag (--limit 5) parsed → valid JSON"+if echo "$IM_INT" | assert_toon_table; then+ echo "OK B1: INTEGER flag (--limit 5) parsed → TOON results table"else- echo "FAIL B1: --limit 5 did not produce valid JSON"; echo "$IM_INT" | head -c 300; exit 1+ echo "FAIL B1: --limit 5 did not produce a TOON results table"; echo "$IM_INT" | head -c 300; exit 1fi# B2: BOOLEAN bare flag — --exclude-entry-points with no value → true; must succeed.if ! IM_BOOL=$(cli search_graph --project "$PROJECT" --exclude-entry-points); thenecho "FAIL B2: search_graph --exclude-entry-points exited non-zero"; cat "$CLI_STDERR"; exit 1fi-if echo "$IM_BOOL" | assert_json_obj; then+if echo "$IM_BOOL" | assert_toon_table; thenecho "OK B2: BOOLEAN bare flag (--exclude-entry-points) → success"else- echo "FAIL B2: --exclude-entry-points did not produce valid JSON"; echo "$IM_BOOL" | head -c 300; exit 1+ echo "FAIL B2: --exclude-entry-points did not produce a TOON results table"; echo "$IM_BOOL" | head -c 300; exit 1fi# B3: ARRAY flag — repeated --semantic-query accumulates into a JSON array.-# semantic_results may be empty (index-mode dependent); only assert valid JSON.+# Semantic-only calls emit ONLY the semantic table (may be empty, header stays).if ! IM_ARR=$(cli search_graph --project "$PROJECT" --semantic-query send --semantic-query publish); thenecho "FAIL B3: search_graph repeated --semantic-query exited non-zero"; cat "$CLI_STDERR"; exit 1fi-if echo "$IM_ARR" | assert_json_obj; then- echo "OK B3: ARRAY flag (repeated --semantic-query) → valid JSON"+if echo "$IM_ARR" | grep -qE '^semantic\[[0-9]+\]\{'; then+ echo "OK B3: ARRAY flag (repeated --semantic-query) → semantic TOON table"else- echo "FAIL B3: repeated --semantic-query did not produce valid JSON"; echo "$IM_ARR" | head -c 300; exit 1+ echo "FAIL B3: repeated --semantic-query did not produce a semantic table"; echo "$IM_ARR" | head -c 300; exit 1fi# B4: STDIN — piped JSON resolves; this path must NOT emit a deprecation warning.diff --git a/src/foundation/constants.h b/src/foundation/constants.hindex 977183d63..dd673e15e 100644--- a/src/foundation/constants.h+++ b/src/foundation/constants.h@@ -70,11 +70,11 @@ enum {/* ── Default pagination limits ───────────────────────────────── *//* Default page size for search_graph and the underlying store-layer search.- * Chosen so a typical broad query (e.g. file_pattern="**" on a 12k-node- * project) stays well within MCP tool-result size budgets. Callers that- * want more results paginate via offset+limit; the response always carries- * 'total' and 'has_more' so agents can detect truncation. */-enum { CBM_DEFAULT_SEARCH_LIMIT = 200 };+ * Responses land in an LLM agent's context window, so the default favors a+ * cheap first page (~50 TOON rows ≈ 1.5K tokens) over raw coverage; the+ * response always carries 'total' and 'has_more', and agents page via+ * offset+limit or narrow with label/file_pattern when has_more is true. */+enum { CBM_DEFAULT_SEARCH_LIMIT = 50 };/* ── Time conversion factors ─────────────────────────────────── */#define CBM_NSEC_PER_SEC 1000000000ULLdiff --git a/src/mcp/compact_out.c b/src/mcp/compact_out.cnew file mode 100644index 000000000..db05aa65b--- /dev/null+++ b/src/mcp/compact_out.c@@ -0,0 +1,230 @@+/* compact_out.c — TOON emission helpers. See compact_out.h for the contract. */+#include "mcp/compact_out.h"++#include <ctype.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>++enum { SB_INITIAL_CAP = 1024 };++void cbm_sb_init(cbm_sb_t *sb) {+ sb->buf = NULL;+ sb->len = 0;+ sb->cap = 0;+ sb->oom = false;+}++static bool sb_reserve(cbm_sb_t *sb, size_t extra) {+ if (sb->oom) {+ return false;+ }+ if (sb->len + extra + 1 <= sb->cap) {+ return true;+ }+ size_t ncap = sb->cap ? sb->cap : SB_INITIAL_CAP;+ while (ncap < sb->len + extra + 1) {+ ncap *= 2;+ }+ char *nbuf = (char *)realloc(sb->buf, ncap);+ if (!nbuf) {+ sb->oom = true;+ return false;+ }+ sb->buf = nbuf;+ sb->cap = ncap;+ return true;+}++void cbm_sb_append_n(cbm_sb_t *sb, const char *s, size_t n) {+ if (!s || n == 0 || !sb_reserve(sb, n)) {+ return;+ }+ memcpy(sb->buf + sb->len, s, n);+ sb->len += n;+ sb->buf[sb->len] = '\0';+}++void cbm_sb_append(cbm_sb_t *sb, const char *s) {+ if (s) {+ cbm_sb_append_n(sb, s, strlen(s));+ }+}++char *cbm_sb_finish(cbm_sb_t *sb) {+ if (sb->oom) {+ free(sb->buf);+ cbm_sb_init(sb);+ return NULL;+ }+ if (!sb->buf) {+ /* Empty but valid: return an owned empty string. */+ char *empty = (char *)calloc(1, 1);+ return empty;+ }+ char *out = sb->buf;+ cbm_sb_init(sb);+ return out;+}++void cbm_sb_free(cbm_sb_t *sb) {+ free(sb->buf);+ cbm_sb_init(sb);+}++/* ── TOON quoting ───────────────────────────────────────────────── */++/* True when `s` parses as an integer or real literal (sign, digits, one dot). */+static bool looks_numeric(const char *s) {+ if (!s || !*s) {+ return false;+ }+ const char *p = s;+ if (*p == '-' || *p == '+') {+ p++;+ }+ bool digit = false;+ bool dot = false;+ for (; *p; p++) {+ if (isdigit((unsigned char)*p)) {+ digit = true;+ } else if (*p == '.' && !dot) {+ dot = true;+ } else {+ return false;+ }+ }+ return digit;+}++static bool needs_quotes(const char *s) {+ if (!s || !*s) {+ return true; /* empty cell must be visible as "" */+ }+ if (isspace((unsigned char)s[0]) || isspace((unsigned char)s[strlen(s) - 1])) {+ return true;+ }+ for (const char *p = s; *p; p++) {+ if (*p == ',' || *p == '"' || *p == '\n' || *p == '\r') {+ return true;+ }+ }+ if (strcmp(s, "true") == 0 || strcmp(s, "false") == 0 || strcmp(s, "null") == 0) {+ return true;+ }+ return looks_numeric(s);+}++static void append_quoted(cbm_sb_t *sb, const char *s) {+ cbm_sb_append_n(sb, "\"", 1);+ for (const char *p = s ? s : ""; *p; p++) {+ switch (*p) {+ case '"':+ cbm_sb_append_n(sb, "\\\"", 2);+ break;+ case '\\':+ cbm_sb_append_n(sb, "\\\\", 2);+ break;+ case '\n':+ cbm_sb_append_n(sb, "\\n", 2);+ break;+ case '\r':+ cbm_sb_append_n(sb, "\\r", 2);+ break;+ default:+ cbm_sb_append_n(sb, p, 1);+ break;+ }+ }+ cbm_sb_append_n(sb, "\"", 1);+}++static void append_value(cbm_sb_t *sb, const char *s) {+ if (needs_quotes(s)) {+ append_quoted(sb, s);+ } else {+ cbm_sb_append(sb, s);+ }+}++/* ── Scalars ────────────────────────────────────────────────────── */++void cbm_toon_scalar_str(cbm_sb_t *sb, const char *key, const char *val) {+ cbm_sb_append(sb, key);+ cbm_sb_append_n(sb, ": ", 2);+ append_value(sb, val);+ cbm_sb_append_n(sb, "\n", 1);+}++void cbm_toon_scalar_int(cbm_sb_t *sb, const char *key, long long v) {+ char num[32];+ snprintf(num, sizeof(num), "%lld", v);+ cbm_sb_append(sb, key);+ cbm_sb_append_n(sb, ": ", 2);+ cbm_sb_append(sb, num);+ cbm_sb_append_n(sb, "\n", 1);+}++void cbm_toon_scalar_bool(cbm_sb_t *sb, const char *key, bool v) {+ cbm_sb_append(sb, key);+ cbm_sb_append_n(sb, ": ", 2);+ cbm_sb_append(sb, v ? "true" : "false");+ cbm_sb_append_n(sb, "\n", 1);+}++/* ── Tables ─────────────────────────────────────────────────────── */++void cbm_toon_table_header(cbm_sb_t *sb, const char *key, int n, const char *const *cols,+ int ncols) {+ char num[32];+ snprintf(num, sizeof(num), "[%d]{", n);+ cbm_sb_append(sb, key);+ cbm_sb_append(sb, num);+ for (int i = 0; i < ncols; i++) {+ if (i > 0) {+ cbm_sb_append_n(sb, ",", 1);+ }+ cbm_sb_append(sb, cols[i]);+ }+ cbm_sb_append_n(sb, "}:\n", 3);+}++void cbm_toon_row_begin(cbm_sb_t *sb) {+ cbm_sb_append_n(sb, " ", 2);+}++void cbm_toon_cell_str(cbm_sb_t *sb, const char *val, bool first) {+ if (!first) {+ cbm_sb_append_n(sb, ",", 1);+ }+ append_value(sb, val ? val : "");+}++void cbm_toon_cell_int(cbm_sb_t *sb, long long v, bool first) {+ char num[32];+ snprintf(num, sizeof(num), "%lld", v);+ if (!first) {+ cbm_sb_append_n(sb, ",", 1);+ }+ cbm_sb_append(sb, num);+}++void cbm_toon_cell_real(cbm_sb_t *sb, double v, bool first) {+ char num[48];+ snprintf(num, sizeof(num), "%.4g", v);+ if (!first) {+ cbm_sb_append_n(sb, ",", 1);+ }+ cbm_sb_append(sb, num);+}++void cbm_toon_cell_bool(cbm_sb_t *sb, bool v, bool first) {+ if (!first) {+ cbm_sb_append_n(sb, ",", 1);+ }+ cbm_sb_append(sb, v ? "true" : "false");+}++void cbm_toon_row_end(cbm_sb_t *sb) {+ cbm_sb_append_n(sb, "\n", 1);+}diff --git a/src/mcp/compact_out.h b/src/mcp/compact_out.hnew file mode 100644index 000000000..9d9fdedda--- /dev/null+++ b/src/mcp/compact_out.h@@ -0,0 +1,54 @@+/* compact_out.h — TOON (Token-Oriented Object Notation) emission helpers.+ *+ * Tool responses are consumed by LLM agents, where every byte is context+ * tokens. TOON encodes the same data as JSON but declares tabular fields+ * once in a header and streams rows line by line, cutting 40-60% of tokens+ * on homogeneous result sets at equal-or-better retrieval accuracy+ * (toonformat.dev/guide/benchmarks). Emitters here cover the subset we+ * emit: scalar key-value lines and flat tables with explicit [N] lengths.+ *+ * Quoting: a cell/scalar is double-quoted iff it is empty, has leading or+ * trailing whitespace, contains a comma, quote, newline, or CR, or would+ * read as a non-string literal (true/false/null/number). Quotes and+ * backslashes are escaped JSON-style; newlines become \n.+ */+#ifndef CBM_MCP_COMPACT_OUT_H+#define CBM_MCP_COMPACT_OUT_H++#include <stdbool.h>+#include <stddef.h>++/* Minimal growing string buffer (OOM-safe: sticky flag, finish returns NULL). */+typedef struct {+ char *buf;+ size_t len;+ size_t cap;+ bool oom;+} cbm_sb_t;++void cbm_sb_init(cbm_sb_t *sb);+void cbm_sb_append_n(cbm_sb_t *sb, const char *s, size_t n);+void cbm_sb_append(cbm_sb_t *sb, const char *s);+/* Returns the heap buffer (caller frees) and resets sb. NULL on OOM. */+char *cbm_sb_finish(cbm_sb_t *sb);+void cbm_sb_free(cbm_sb_t *sb);++/* `key: value` scalar lines (top-level, no indent). */+void cbm_toon_scalar_str(cbm_sb_t *sb, const char *key, const char *val);+void cbm_toon_scalar_int(cbm_sb_t *sb, const char *key, long long v);+void cbm_toon_scalar_bool(cbm_sb_t *sb, const char *key, bool v);++/* `key[n]{col1,col2,...}:` table header; rows follow at 2-space indent. */+void cbm_toon_table_header(cbm_sb_t *sb, const char *key, int n, const char *const *cols,+ int ncols);++/* Row cells: call row_begin, then cell_* per column (first=true for the+ * first cell), then row_end. Empty/NULL strings emit as empty cells. */+void cbm_toon_row_begin(cbm_sb_t *sb);+void cbm_toon_cell_str(cbm_sb_t *sb, const char *val, bool first);+void cbm_toon_cell_int(cbm_sb_t *sb, long long v, bool first);+void cbm_toon_cell_real(cbm_sb_t *sb, double v, bool first);+void cbm_toon_cell_bool(cbm_sb_t *sb, bool v, bool first);+void cbm_toon_row_end(cbm_sb_t *sb);++#endif /* CBM_MCP_COMPACT_OUT_H */diff --git a/src/mcp/mcp.c b/src/mcp/mcp.cindex a0d8e2a91..d0c6cf3bb 100644--- a/src/mcp/mcp.c+++ b/src/mcp/mcp.c@@ -55,6 +55,7 @@ enum {#include "foundation/log.h"#include "foundation/limits.h"#include "mcp/index_supervisor.h"+#include "mcp/compact_out.h"#include "foundation/str_util.h"#include "foundation/dump_verify.h"#include "foundation/compat_regex.h"@@ -352,11 +353,15 @@ static const tool_def_t TOOLS[] = {"(2) name_pattern='.*regex.*' for exact pattern matching; (3) semantic_query=[...] for ""vector cosine search that bridges vocabulary (finds 'publish' when you search 'send'). ""The three modes are independent and can be combined in a single call. "- "PAGINATION: results are capped at limit (default 200) — broader queries are silently "- "truncated. The response always includes 'total' (full match count before limit) and "- "'has_more' (true when total > offset+returned). Detect truncation with has_more, then "- "page by re-calling with offset=offset+limit until has_more is false. Narrow first via "- "label/file_pattern/min_degree before paginating large result sets.",+ "RESPONSE: compact TOON tables by default — `results[N]{qn,label,file,lines,in,out}:` "+ "header then one row per hit (in/out = edge degrees). Add per-node property columns via "+ "fields (e.g. [\"complexity\",\"signature\",\"docstring\"]); pass format=\"json\" for "+ "legacy verbose objects (include_connected always uses JSON). "+ "PAGINATION: results are capped at limit (default 50). The response always includes "+ "'total' (full match count before limit) and 'has_more' (true when total > "+ "offset+returned). Detect truncation with has_more, then page by re-calling with "+ "offset=offset+limit until has_more is false. Narrow first via label/file_pattern/"+ "min_degree before paginating large result sets.","{\"type\":\"object\",\"properties\":{\"project\":{\"type\":\"string\"},""\"query\":{\"type\":\"string\",\"description\":\"Natural-language or keyword full-text ""search using BM25 ranking. Tokens are split on whitespace; camelCase identifiers are "@@ -374,11 +379,18 @@ static const tool_def_t TOOLS[] = {"Each keyword is scored independently via per-keyword min-cosine; results reflect functions ""that score well on ALL keywords. Requires moderate/full index mode. Results appear in the ""'semantic_results' field (separate from 'results').\"},\"limit\":{\"type\":"- "\"integer\",\"description\":\"Max results per call. Default 200. Response carries "+ "\"integer\",\"description\":\"Max results per call. Default 50. Response carries ""'total' (full match count) and 'has_more' (true if truncated) so callers can ""detect the limit and paginate.\"},\"offset\":{\"type\":\"integer\",\"default\":0,""\"description\":\"Skip the first N matching nodes. Combine with 'limit' to page: "- "increment offset by limit and re-call while has_more is true.\"}},"+ "increment offset by limit and re-call while has_more is true.\"},"+ "\"format\":{\"type\":\"string\",\"enum\":[\"toon\",\"json\"],\"default\":\"toon\","+ "\"description\":\"Response encoding. toon (default): compact header+rows tables, "+ "~60% fewer tokens. json: legacy verbose per-node objects.\"},"+ "\"fields\":{\"type\":\"array\",\"items\":{\"type\":\"string\"},\"description\":"+ "\"Extra per-node property columns for toon output, e.g. complexity, cognitive, "+ "signature, docstring, return_type, is_test, lines(int). Missing values emit as "+ "empty cells.\"}},""\"required\":[\"project\"]}"},{"query_graph", "Query graph",@@ -1610,7 +1622,7 @@ enum {BM25_MIN_BUF = 2, /* minimum buffer size: at least NUL + one char */BM25_SEP_RESERVE = 1,BM25_QUERY_BUF = 1024,- BM25_DEFAULT_LIMIT = 100,+ BM25_DEFAULT_LIMIT = 50,BM25_COL_ID = 0,BM25_COL_LABEL = 1,BM25_COL_NAME = 2,@@ -1708,7 +1720,7 @@ static char *bm25_file_pattern_like(const char *file_pattern) {* Returns NULL if FTS5 is unavailable or the query produced no usable tokens,* in which case the caller falls back to the regex-based search path. */static char *bm25_search(cbm_store_t *store, const char *project, const char *query,- const char *file_pattern, int limit, int offset) {+ const char *file_pattern, int limit, int offset, bool toon) {sqlite3 *db = cbm_store_get_db(store);if (!db) {return NULL;@@ -1804,6 +1816,47 @@ static char *bm25_search(cbm_store_t *store, const char *project, const char *qu}}+ if (toon) {+ /* TOON: rows are buffered first because the table header carries the+ * row count, which sqlite only yields by stepping to completion. */+ cbm_sb_t rows;+ cbm_sb_init(&rows);+ int emitted = 0;+ while (sqlite3_step(stmt) == SQLITE_ROW) {+ char lines[CBM_SZ_32];+ int sl = sqlite3_column_int(stmt, BM25_COL_START);+ int el = sqlite3_column_int(stmt, BM25_COL_END);+ if (sl > 0) {+ snprintf(lines, sizeof(lines), "%d-%d", sl, el > sl ? el : sl);+ } else {+ lines[0] = '\0';+ }+ cbm_toon_row_begin(&rows);+ cbm_toon_cell_str(&rows, (const char *)sqlite3_column_text(stmt, BM25_COL_QN), true);+ cbm_toon_cell_str(&rows, (const char *)sqlite3_column_text(stmt, BM25_COL_LABEL),+ false);+ cbm_toon_cell_str(&rows, (const char *)sqlite3_column_text(stmt, BM25_COL_FILE), false);+ cbm_toon_cell_str(&rows, lines, false);+ cbm_toon_cell_real(&rows, sqlite3_column_double(stmt, BM25_COL_RANK), false);+ cbm_toon_row_end(&rows);+ emitted++;+ }+ sqlite3_finalize(stmt);+ free(file_like);++ cbm_sb_t sb;+ cbm_sb_init(&sb);+ cbm_toon_scalar_int(&sb, "total", total);+ cbm_toon_scalar_str(&sb, "search_mode", "bm25");+ static const char *const cols[] = {"qn", "label", "file", "lines", "rank"};+ cbm_toon_table_header(&sb, "results", emitted, cols, 5);+ char *rows_text = cbm_sb_finish(&rows);+ cbm_sb_append(&sb, rows_text ? rows_text : "");+ free(rows_text);+ cbm_toon_scalar_bool(&sb, "has_more", total > offset + emitted);+ return cbm_sb_finish(&sb);+ }+yyjson_mut_doc *doc = yyjson_mut_doc_new(NULL);yyjson_mut_val *root = yyjson_mut_obj(doc);yyjson_mut_doc_set_root(doc, root);@@ -1920,15 +1973,25 @@ static void emit_semantic_results(yyjson_mut_doc *doc, yyjson_mut_val *root,yyjson_mut_obj_add_val(doc, root, "semantic_results", sem_results);}-/* Append the semantic_query vector-search results onto the doc. Returns- * true if semantic_query was provided as a non-array (type error — caller- * should surface to the user). */-static bool run_semantic_query(yyjson_mut_doc *doc, yyjson_mut_val *root, const char *args,- cbm_store_t *store, const char *project, int limit) {+/* Run the semantic_query vector search from raw args. Sets *out_vresults /+ * *out_vcount (caller frees via cbm_store_free_vector_results when vcount>0).+ * Returns true if semantic_query was provided as a non-array (type error —+ * caller should surface to the user). */+static bool run_semantic_query_core(const char *args, cbm_store_t *store, const char *project,+ int limit, cbm_vector_result_t **out_vresults, int *out_vcount,+ bool *out_present) {enum { MAX_KW_SEARCH = 32 };+ *out_vresults = NULL;+ *out_vcount = 0;+ if (out_present) {+ *out_present = false;+ }yyjson_doc *args_doc = yyjson_read(args, strlen(args), 0);yyjson_val *args_root = args_doc ? yyjson_doc_get_root(args_doc) : NULL;yyjson_val *sq_val = args_root ? yyjson_obj_get(args_root, "semantic_query") : NULL;+ if (out_present && sq_val) {+ *out_present = true;+ }bool type_error = false;if (sq_val && !yyjson_is_arr(sq_val)) {type_error = true;@@ -1941,8 +2004,8 @@ static bool run_semantic_query(yyjson_mut_doc *doc, yyjson_mut_val *root, constif (cbm_store_vector_search(store, project, keywords, ki, sem_limit, &vresults, &vcount) ==CBM_STORE_OK &&vcount > 0) {- emit_semantic_results(doc, root, vresults, vcount);- cbm_store_free_vector_results(vresults, vcount);+ *out_vresults = vresults;+ *out_vcount = vcount;}}if (args_doc) {@@ -1951,6 +2014,145 @@ static bool run_semantic_query(yyjson_mut_doc *doc, yyjson_mut_val *root, constreturn type_error;}+/* Append the semantic_query vector-search results onto the doc. Returns+ * true if semantic_query was provided as a non-array (type error — caller+ * should surface to the user). */+static bool run_semantic_query(yyjson_mut_doc *doc, yyjson_mut_val *root, const char *args,+ cbm_store_t *store, const char *project, int limit) {+ cbm_vector_result_t *vresults = NULL;+ int vcount = 0;+ bool type_error =+ run_semantic_query_core(args, store, project, limit, &vresults, &vcount, NULL);+ if (vcount > 0) {+ emit_semantic_results(doc, root, vresults, vcount);+ cbm_store_free_vector_results(vresults, vcount);+ }+ return type_error;+}++/* ── TOON output for search_graph ───────────────────────────────────+ * Default response encoding: header+rows tables (compact_out.h). The+ * verbose per-node JSON objects remain available via format:"json" and+ * are forced for include_connected=true (nested neighbor lists). */++enum { SG_MAX_EXTRA_FIELDS = 12 };++/* Internal-only node properties never emitted to agents: similarity /+ * semantic pipeline intermediates (minhash fingerprint, structural profile,+ * body-token bag). They dominate payload size and carry zero agent value. */+static bool sg_field_blocked(const char *f) {+ return strcmp(f, "fp") == 0 || strcmp(f, "sp") == 0 || strcmp(f, "bt") == 0;+}++/* Parse the `fields` argument (array of property names) into out[] as+ * pointers owned by the returned doc (caller frees the doc after emission).+ * Blocked internal fields are silently dropped. */+static int sg_parse_fields(const char *args, const char *out[], int max_out,+ yyjson_doc **out_owner) {+ *out_owner = NULL;+ yyjson_doc *args_doc = yyjson_read(args, strlen(args), 0);+ yyjson_val *args_root = args_doc ? yyjson_doc_get_root(args_doc) : NULL;+ yyjson_val *fv = args_root ? yyjson_obj_get(args_root, "fields") : NULL;+ if (!fv || !yyjson_is_arr(fv)) {+ if (args_doc) {+ yyjson_doc_free(args_doc);+ }+ return 0;+ }+ int n = 0;+ size_t idx = 0;+ size_t max = 0;+ yyjson_val *item;+ yyjson_arr_foreach(fv, idx, max, item) {+ const char *s = yyjson_get_str(item);+ if (s && s[0] && !sg_field_blocked(s) && n < max_out) {+ out[n++] = s;+ }+ }+ if (n == 0) {+ yyjson_doc_free(args_doc);+ return 0;+ }+ *out_owner = args_doc;+ return n;+}++/* Append one row's extra-field cells, pulled from the node's properties. */+static void sg_toon_extra_cells(cbm_sb_t *sb, const char *props_json, const char *const *fields,+ int nfields) {+ yyjson_doc *pd =+ (props_json && props_json[0]) ? yyjson_read(props_json, strlen(props_json), 0) : NULL;+ yyjson_val *pr = pd ? yyjson_doc_get_root(pd) : NULL;+ for (int f = 0; f < nfields; f++) {+ yyjson_val *v = (pr && yyjson_is_obj(pr)) ? yyjson_obj_get(pr, fields[f]) : NULL;+ if (v && yyjson_is_str(v)) {+ cbm_toon_cell_str(sb, yyjson_get_str(v), false);+ } else if (v && yyjson_is_bool(v)) {+ cbm_toon_cell_bool(sb, yyjson_get_bool(v), false);+ } else if (v && yyjson_is_int(v)) {+ cbm_toon_cell_int(sb, yyjson_get_int(v), false);+ } else if (v && yyjson_is_real(v)) {+ cbm_toon_cell_real(sb, yyjson_get_real(v), false);+ } else {+ cbm_toon_cell_str(sb, "", false);+ }+ }+ if (pd) {+ yyjson_doc_free(pd);+ }+}++/* "start-end" line range, or empty when the node carries no line info. */+static void sg_lines_str(char *out, size_t sz, int start, int end) {+ if (start > 0) {+ snprintf(out, sz, "%d-%d", start, end > start ? end : start);+ } else {+ out[0] = '\0';+ }+}++/* Emit the regex-path search results as a TOON table. */+static void emit_search_results_toon(cbm_sb_t *sb, const cbm_search_output_t *out, int offset,+ const char *const *fields, int nfields) {+ cbm_toon_scalar_int(sb, "total", out->total);+ const char *cols[6 + SG_MAX_EXTRA_FIELDS] = {"qn", "label", "file", "lines", "in", "out"};+ int ncols = 6;+ for (int f = 0; f < nfields; f++) {+ cols[ncols++] = fields[f];+ }+ cbm_toon_table_header(sb, "results", out->count, cols, ncols);+ for (int i = 0; i < out->count; i++) {+ const cbm_search_result_t *sr = &out->results[i];+ char lines[CBM_SZ_32];+ sg_lines_str(lines, sizeof(lines), sr->node.start_line, sr->node.end_line);+ cbm_toon_row_begin(sb);+ cbm_toon_cell_str(sb, sr->node.qualified_name, true);+ cbm_toon_cell_str(sb, sr->node.label, false);+ cbm_toon_cell_str(sb, sr->node.file_path, false);+ cbm_toon_cell_str(sb, lines, false);+ cbm_toon_cell_int(sb, sr->in_degree, false);+ cbm_toon_cell_int(sb, sr->out_degree, false);+ sg_toon_extra_cells(sb, sr->node.properties_json, fields, nfields);+ cbm_toon_row_end(sb);+ }+ cbm_toon_scalar_bool(sb, "has_more", out->total > offset + out->count);+}++/* Emit semantic vector-search results as a TOON table. */+static void emit_semantic_results_toon(cbm_sb_t *sb, const cbm_vector_result_t *vresults,+ int vcount) {+ static const char *const cols[] = {"qn", "label", "file", "score"};+ cbm_toon_table_header(sb, "semantic", vcount, cols, 4);+ for (int v = 0; v < vcount; v++) {+ cbm_toon_row_begin(sb);+ cbm_toon_cell_str(sb, vresults[v].qualified_name, true);+ cbm_toon_cell_str(sb, vresults[v].label, false);+ cbm_toon_cell_str(sb, vresults[v].file_path, false);+ cbm_toon_cell_real(sb, vresults[v].score, false);+ cbm_toon_row_end(sb);+ }+}+static char *handle_search_graph(cbm_mcp_server_t *srv, const char *args) {char *project = get_project_arg(args);cbm_store_t *store = resolve_store(srv, project);@@ -1962,6 +2164,16 @@ static char *handle_search_graph(cbm_mcp_server_t *srv, const char *args) {return not_indexed;}+ /* Response encoding: TOON tables by default (compact, header+rows).+ * format:"json" restores the legacy verbose per-node objects; nested+ * neighbor lists (include_connected) need them, so they force JSON. */+ char *format_arg = cbm_mcp_get_string_arg(args, "format");+ bool legacy_json = format_arg && strcmp(format_arg, "json") == 0;+ free(format_arg);+ if (cbm_mcp_get_bool_arg(args, "include_connected")) {+ legacy_json = true;+ }+/* BM25 path: if `query` is set, run FTS5 full-text search with ranking* and return early. The regex/vector path below is untouched for all* other callers. If FTS5 is unavailable or the query is empty after@@ -1971,7 +2183,8 @@ static char *handle_search_graph(cbm_mcp_server_t *srv, const char *args) {int q_limit = cbm_mcp_get_int_arg(args, "limit", BM25_DEFAULT_LIMIT);int q_offset = cbm_mcp_get_int_arg(args, "offset", 0);char *q_file_pattern = cbm_mcp_get_string_arg(args, "file_pattern");- char *bm25_json = bm25_search(store, project, query, q_file_pattern, q_limit, q_offset);+ char *bm25_json =+ bm25_search(store, project, query, q_file_pattern, q_limit, q_offset, !legacy_json);free(q_file_pattern);if (bm25_json) {free(query);@@ -2020,6 +2233,93 @@ static char *handle_search_graph(cbm_mcp_server_t *srv, const char *args) {.max_degree = max_degree,};+ if (!legacy_json) {+ const char *fields[SG_MAX_EXTRA_FIELDS];+ yyjson_doc *fields_owner = NULL;+ int nfields = sg_parse_fields(args, fields, SG_MAX_EXTRA_FIELDS, &fields_owner);++ cbm_vector_result_t *vresults = NULL;+ int vcount = 0;+ bool sq_present = false;+ bool sq_type_error =+ run_semantic_query_core(args, store, project, limit, &vresults, &vcount, &sq_present);+ if (!sq_type_error) {+ /* Semantic-only calls get semantic results only: the legacy+ * behavior also ran the UNFILTERED regex search and prepended+ * up to `limit` unrelated enriched nodes to the response. */+ bool has_filters = label || name_pattern || qn_pattern || file_pattern ||+ relationship || exclude_entry_points ||+ min_degree != CBM_NOT_FOUND || max_degree != CBM_NOT_FOUND;+ bool semantic_only = sq_present && !has_filters;++ cbm_sb_t sb;+ cbm_sb_init(&sb);+ cbm_search_output_t tout = {0};+ if (!semantic_only) {+ cbm_store_search(store, ¶ms, &tout);+ emit_search_results_toon(&sb, &tout, offset, fields, nfields);+ if (tout.total == 0) {+ if (name_pattern && label) {+ cbm_toon_scalar_str(&sb, "hint",+ "No results. Try removing the label filter or "+ "broadening the name_pattern regex.");+ } else if (name_pattern) {+ cbm_toon_scalar_str(+ &sb, "hint",+ "No nodes match this pattern. Check spelling or try a broader regex.");+ } else if (label) {+ cbm_toon_scalar_str(&sb, "hint",+ "No nodes with this label. Available labels: "+ "Function, Method, Class, Interface, Route, "+ "Variable, Module, Package, File, Folder.");+ }+ }+ }+ if (vcount > 0) {+ emit_semantic_results_toon(&sb, vresults, vcount);+ } else if (semantic_only) {+ static const char *const sem_cols[] = {"qn", "label", "file", "score"};+ cbm_toon_table_header(&sb, "semantic", 0, sem_cols, 4);+ cbm_toon_scalar_str(&sb, "hint",+ "No semantic matches. semantic_query needs a moderate/full "+ "index; try broader or fewer keywords.");+ }+ if (vcount > 0) {+ cbm_store_free_vector_results(vresults, vcount);+ }+ if (fields_owner) {+ yyjson_doc_free(fields_owner);+ }+ cbm_store_search_free(&tout);+ free(project);+ free(label);+ free(name_pattern);+ free(qn_pattern);+ free(file_pattern);+ free(relationship);+ char *text = cbm_sb_finish(&sb);+ char *result = cbm_mcp_text_result(text ? text : "out of memory", text == NULL);+ free(text);+ return result;+ }+ /* semantic_query type error: fall through to the shared error text. */+ if (fields_owner) {+ yyjson_doc_free(fields_owner);+ }+ free(project);+ free(label);+ free(name_pattern);+ free(qn_pattern);+ free(file_pattern);+ free(relationship);+ return cbm_mcp_text_result(+ "semantic_query must be an array of keyword strings, e.g. "+ "[\"send\",\"pubsub\",\"publish\"] — not a single string. Split your query "+ "into individual keywords; each is scored independently via per-keyword "+ "min-cosine.",+ true);+ }+cbm_search_output_t out = {0};cbm_store_search(store, ¶ms, &out);diff --git a/tests/test_incremental.c b/tests/test_incremental.cindex 7883a9cc9..4cf9aa158 100644--- a/tests/test_incremental.c+++ b/tests/test_incremental.c@@ -127,7 +127,9 @@ static char *call_tool(const char *tool, const char *args_fmt, ...) {return cbm_mcp_handle_tool(g_srv, tool, args);}-/* Parse integer from JSON response (handles nested MCP envelope) */+/* Parse integer from a tool response (handles the nested MCP envelope).+ * Matches the JSON forms "key":N / \"key\":N and the TOON scalar `key: N`+ * (search_graph default output since the compact-output change). */static int count_in_response(const char *resp, const char *key) {if (!resp)return -1;@@ -138,6 +140,10 @@ static int count_in_response(const char *resp, const char *key) {return atoi(p + strlen(pattern));snprintf(pattern, sizeof(pattern), "\\\"%s\\\":", key);p = strstr(resp, pattern);+ if (p)+ return atoi(p + strlen(pattern));+ snprintf(pattern, sizeof(pattern), "%s: ", key);+ p = strstr(resp, pattern);if (p)return atoi(p + strlen(pattern));return -1;@@ -928,6 +934,10 @@ static int resp_has_key(const char *resp, const char *key) {if (strstr(resp, pattern) != NULL)return 1;snprintf(pattern, sizeof(pattern), "\\\"%s\\\"", key);+ if (strstr(resp, pattern) != NULL)+ return 1;+ /* TOON scalar form (`key: value`), the search_graph default output. */+ snprintf(pattern, sizeof(pattern), "%s: ", key);return strstr(resp, pattern) != NULL;}diff --git a/tests/test_mcp.c b/tests/test_mcp.cindex c072088c0..fc17548bb 100644--- a/tests/test_mcp.c+++ b/tests/test_mcp.c@@ -739,15 +739,16 @@ static void cleanup_snippet_dir(const char *tmp_dir);static char *extract_text_content(const char *mcp_result);TEST(tool_search_graph_includes_node_properties) {- /* search_graph results must surface each node's properties_json- * payload so callers don't have to round-trip through get_code_snippet- * just to read them. The setup_snippet_server inserts HandleRequest- * with a signature/return_type/is_exported property blob; this test- * pins that those keys reach the MCP response. */+ /* Node properties are OPT-IN columns in the default TOON output: the+ * default row is qn/label/file/lines/degrees only, `fields` adds the+ * requested property columns, and format:"json" restores the legacy+ * verbose objects with the full property blob. The setup_snippet_server+ * inserts HandleRequest with a signature/return_type/is_exported blob. */char tmp[256];cbm_mcp_server_t *srv = setup_snippet_server(tmp, sizeof(tmp));ASSERT_NOT_NULL(srv);+ /* Default TOON: compact table, no property spill. */char *resp = cbm_mcp_server_handle(srv, "{\"jsonrpc\":\"2.0\",\"id\":42,\"method\":\"tools/call\",""\"params\":{\"name\":\"search_graph\","@@ -756,8 +757,38 @@ TEST(tool_search_graph_includes_node_properties) {ASSERT_NOT_NULL(resp);char *inner = extract_text_content(resp);ASSERT_NOT_NULL(inner);- /* Properties from HandleRequest's properties_json must appear. */- ASSERT_NOT_NULL(strstr(inner, "signature"));+ ASSERT_NOT_NULL(strstr(inner, "results[")); /* TOON table header */+ ASSERT_NOT_NULL(strstr(inner, "{qn,label,file,lines,in,out}"));+ ASSERT_NOT_NULL(strstr(inner, "HandleRequest"));+ ASSERT_NULL(strstr(inner, "func HandleRequest")); /* signature not spilled */+ ASSERT_NULL(strstr(inner, "is_exported"));+ free(inner);+ free(resp);++ /* fields:["signature"] adds the column + values. */+ resp = cbm_mcp_server_handle(+ srv, "{\"jsonrpc\":\"2.0\",\"id\":43,\"method\":\"tools/call\","+ "\"params\":{\"name\":\"search_graph\","+ "\"arguments\":{\"project\":\"test-project\",\"label\":\"Function\","+ "\"name_pattern\":\"HandleRequest\",\"fields\":[\"signature\"],\"limit\":5}}}");+ ASSERT_NOT_NULL(resp);+ inner = extract_text_content(resp);+ ASSERT_NOT_NULL(inner);+ ASSERT_NOT_NULL(strstr(inner, "{qn,label,file,lines,in,out,signature}"));+ ASSERT_NOT_NULL(strstr(inner, "func HandleRequest"));+ free(inner);+ free(resp);++ /* format:"json" keeps the legacy verbose objects intact. */+ resp = cbm_mcp_server_handle(+ srv, "{\"jsonrpc\":\"2.0\",\"id\":44,\"method\":\"tools/call\","+ "\"params\":{\"name\":\"search_graph\","+ "\"arguments\":{\"project\":\"test-project\",\"label\":\"Function\","+ "\"name_pattern\":\"HandleRequest\",\"format\":\"json\",\"limit\":5}}}");+ ASSERT_NOT_NULL(resp);+ inner = extract_text_content(resp);+ ASSERT_NOT_NULL(inner);+ ASSERT_NOT_NULL(strstr(inner, "\"signature\""));ASSERT_NOT_NULL(strstr(inner, "func HandleRequest"));ASSERT_NOT_NULL(strstr(inner, "is_exported"));free(inner);@@ -768,6 +799,53 @@ TEST(tool_search_graph_includes_node_properties) {PASS();}+TEST(tool_search_graph_toon_never_leaks_internal_fields) {+ /* The similarity/semantic pipeline intermediates (fp minhash hex, sp+ * structural profile, bt body-token bag) dominated the legacy payload+ * (~45%) and carry zero agent value. GUARD: they never appear in TOON+ * output — not by default and not even when explicitly requested via+ * fields (blocklist). */+ char tmp[256];+ cbm_mcp_server_t *srv = setup_snippet_server(tmp, sizeof(tmp));+ ASSERT_NOT_NULL(srv);+ cbm_store_t *st = cbm_mcp_server_store(srv);+ ASSERT_NOT_NULL(st);++ /* A node whose properties carry the internal fields with sentinels. */+ cbm_node_t n = {0};+ n.project = "test-project";+ n.label = "Function";+ n.name = "fpCarrier";+ n.qualified_name = "test-project.src.fpCarrier";+ n.file_path = "src/fp.go";+ n.start_line = 1;+ n.end_line = 2;+ n.properties_json = "{\"fp\":\"FPSENTINEL00\",\"sp\":\"SPSENTINEL00\","+ "\"bt\":\"BTSENTINEL00\",\"complexity\":7}";+ ASSERT_GT(cbm_store_upsert_node(st, &n), 0);++ char *resp = cbm_mcp_server_handle(+ srv, "{\"jsonrpc\":\"2.0\",\"id\":45,\"method\":\"tools/call\","+ "\"params\":{\"name\":\"search_graph\","+ "\"arguments\":{\"project\":\"test-project\",\"name_pattern\":\"fpCarrier\","+ "\"fields\":[\"fp\",\"sp\",\"bt\",\"complexity\"],\"limit\":5}}}");+ ASSERT_NOT_NULL(resp);+ char *inner = extract_text_content(resp);+ ASSERT_NOT_NULL(inner);+ ASSERT_NOT_NULL(strstr(inner, "fpCarrier"));+ ASSERT_NULL(strstr(inner, "FPSENTINEL00"));+ ASSERT_NULL(strstr(inner, "SPSENTINEL00"));+ ASSERT_NULL(strstr(inner, "BTSENTINEL00"));+ /* Non-blocked requested field still comes through. */+ ASSERT_NOT_NULL(strstr(inner, "complexity"));+ free(inner);+ free(resp);++ cbm_mcp_server_free(srv);+ cleanup_snippet_dir(tmp);+ PASS();+}+TEST(tool_search_graph_query_honors_file_pattern_issue552) {cbm_mcp_server_t *srv = cbm_mcp_server_new(NULL);ASSERT_NOT_NULL(srv);@@ -814,8 +892,8 @@ TEST(tool_search_graph_query_honors_file_pattern_issue552) {ASSERT_NOT_NULL(resp);char *inner = extract_text_content(resp);ASSERT_NOT_NULL(inner);- ASSERT_NOT_NULL(strstr(inner, "\"search_mode\":\"bm25\""));- ASSERT_NOT_NULL(strstr(inner, "\"file_path\":\"src/lib/status.c\""));+ ASSERT_NOT_NULL(strstr(inner, "search_mode: bm25"));+ ASSERT_NOT_NULL(strstr(inner, "src/lib/status.c"));ASSERT_NULL(strstr(inner, "src/components/status.c"));free(inner);@@ -5263,6 +5341,7 @@ SUITE(mcp) {RUN_TEST(tool_unknown_tool);RUN_TEST(tool_search_graph_basic);RUN_TEST(tool_search_graph_includes_node_properties);+ RUN_TEST(tool_search_graph_toon_never_leaks_internal_fields);RUN_TEST(tool_search_graph_query_honors_file_pattern_issue552);RUN_TEST(tool_query_graph_basic);RUN_TEST(tool_index_status_no_project);