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
fix(output): preserve non-utf8 identities
Martin Vogel10ece1bb8690
diff --git a/README.md b/README.mdindex 5e306cacb..50a9bb68e 100644--- a/README.md+++ b/README.md@@ -635,6 +635,8 @@ Large compact-tree tables may start with a response-local `<section>_refs` direcLean responses truncate semantically, never by cutting arbitrary bytes from code or identifiers. Ranked graph rows are retained ahead of raw grep rows and diagnostic summaries; omitted rows/sections report totals, `has_more`, and a strictly advancing continuation offset or cursor. If even the first whole row cannot fit, CBM asks for a higher budget and emits no self-looping cursor. `max_output_tokens` is model-neutral sizing guidance: CBM enforces a deterministic ceiling of four UTF-8 bytes per requested token, so it is not a tokenizer-exact count. Detail flags such as `diagnostics`, `source_mode`, and `detail` opt into heavier fields. `search_code` additionally exposes `raw_limit`/`raw_offset`, `directory_limit`/`directory_offset`, `match_limit`, and `source_max_lines`; its default retains eight match locations per graph result and reports the exact `matches_omitted` remainder. The ranked graph answer stays intact while raw matches and directory summaries page independently. `detect_changes` pages changed files, impacted symbols, and module summaries independently.+Every response is standard UTF-8 without sacrificing POSIX byte-string identities. A value containing malformed UTF-8 is emitted reversibly as `@bytes:<lowercase hex of every original byte>`. A valid value that literally begins with the reserved `@bytes:` or `@utf8:` prefix is emitted as `@utf8:<original value>`, so decoding is unambiguous: strip one `@utf8:` prefix for literal UTF-8, or hex-decode one `@bytes:` prefix for original bytes. Ordinary valid UTF-8 is unchanged and pays no output-token overhead.+Use `cli <tool> --help` to see the flags generated from that tool's input schema:```bashdiff --git a/src/mcp/compact_out.c b/src/mcp/compact_out.cindex 29745b925..81df04fc9 100644--- a/src/mcp/compact_out.c+++ b/src/mcp/compact_out.c@@ -99,10 +99,12 @@ static bool looks_numeric(const char *s) {}/* UTF-8 sequence length starting at p, validating continuation bytes and the- * lead-byte ranges (RFC 3629: no overlongs, no surrogates, max U+10FFFF);- * 0 = not a valid sequence start. Reads stop at the first invalid byte, so a- * terminating NUL is never overrun. */-static size_t utf8_sequence_length(const unsigned char *p) {+ * lead-byte ranges (RFC 3629: no overlongs, no surrogates, max U+10FFFF).+ * `remaining` makes truncated multibyte input safe to inspect. */+static size_t utf8_sequence_length(const unsigned char *p, size_t remaining) {+ if (!p || remaining == 0) {+ return 0;+ }unsigned char c = p[0];if (c < 0x80) {return 1;@@ -111,9 +113,12 @@ static size_t utf8_sequence_length(const unsigned char *p) {return 0; /* bare continuation byte or overlong lead */}if (c < 0xE0) {- return (p[1] & 0xC0) == 0x80 ? 2 : 0;+ return remaining >= 2 && (p[1] & 0xC0) == 0x80 ? 2 : 0;}if (c < 0xF0) {+ if (remaining < 3) {+ return 0;+ }unsigned char lo = c == 0xE0 ? 0xA0 : 0x80;unsigned char hi = c == 0xED ? 0x9F : 0xBF;if (p[1] < lo || p[1] > hi || (p[2] & 0xC0) != 0x80) {@@ -122,6 +127,9 @@ static size_t utf8_sequence_length(const unsigned char *p) {return 3;}if (c < 0xF5) {+ if (remaining < 4) {+ return 0;+ }unsigned char lo = c == 0xF0 ? 0x90 : 0x80;unsigned char hi = c == 0xF4 ? 0x8F : 0xBF;if (p[1] < lo || p[1] > hi || (p[2] & 0xC0) != 0x80 || (p[3] & 0xC0) != 0x80) {@@ -132,11 +140,91 @@ static size_t utf8_sequence_length(const unsigned char *p) {return 0;}+static bool output_text_requires_encoding(const char *data, size_t len) {+ static const char bytes_prefix[] = "@bytes:";+ static const char utf8_prefix[] = "@utf8:";+ if (!data) {+ return len != 0;+ }+ if ((len >= sizeof(bytes_prefix) - 1 &&+ memcmp(data, bytes_prefix, sizeof(bytes_prefix) - 1) == 0) ||+ (len >= sizeof(utf8_prefix) - 1 &&+ memcmp(data, utf8_prefix, sizeof(utf8_prefix) - 1) == 0)) {+ return true;+ }+ size_t offset = 0;+ while (offset < len) {+ size_t sequence = utf8_sequence_length((const unsigned char *)data + offset, len - offset);+ if (!sequence) {+ return true;+ }+ offset += sequence;+ }+ return false;+}++bool cbm_output_encode_text(const char *data, size_t len, char **encoded, size_t *encoded_len) {+ static const char bytes_prefix[] = "@bytes:";+ static const char utf8_prefix[] = "@utf8:";+ static const char hex[] = "0123456789abcdef";+ if (!encoded || !encoded_len || (!data && len != 0)) {+ return false;+ }+ *encoded = NULL;+ *encoded_len = len;+ if (!output_text_requires_encoding(data, len)) {+ return true;+ }++ bool valid_utf8 = true;+ size_t offset = 0;+ while (offset < len) {+ size_t sequence = utf8_sequence_length((const unsigned char *)data + offset, len - offset);+ if (!sequence) {+ valid_utf8 = false;+ break;+ }+ offset += sequence;+ }++ size_t prefix_len = valid_utf8 ? sizeof(utf8_prefix) - 1 : sizeof(bytes_prefix) - 1;+ size_t payload_len = len;+ if (!valid_utf8) {+ if (len > ((size_t)-1 - prefix_len - 1) / 2) {+ return false;+ }+ payload_len = len * 2;+ } else if (len > (size_t)-1 - prefix_len - 1) {+ return false;+ }+ char *out = (char *)malloc(prefix_len + payload_len + 1);+ if (!out) {+ return false;+ }+ memcpy(out, valid_utf8 ? utf8_prefix : bytes_prefix, prefix_len);+ if (valid_utf8) {+ if (len > 0) {+ memcpy(out + prefix_len, data, len);+ }+ } else {+ for (size_t i = 0; i < len; i++) {+ unsigned char byte = (unsigned char)data[i];+ out[prefix_len + i * 2] = hex[byte >> 4];+ out[prefix_len + i * 2 + 1] = hex[byte & 0x0f];+ }+ }+ *encoded_len = prefix_len + payload_len;+ out[*encoded_len] = '\0';+ *encoded = out;+ return true;+}+static bool needs_quotes(const char *s) {if (!s || !*s) {return false; /* empty cells emit as the "-" placeholder, not quotes */}- for (const char *p = s; *p; p++) {+ size_t remaining = strlen(s);+ for (const char *p = s; *p; p++, remaining--) {unsigned char c = (unsigned char)*p;/* Space-delimited rows: any internal whitespace or quote forces* quoting so column positions stay parseable. Control bytes and@@ -147,11 +235,12 @@ static bool needs_quotes(const char *s) {return true;}if (c >= 0x80) {- size_t len = utf8_sequence_length((const unsigned char *)p);+ size_t len = utf8_sequence_length((const unsigned char *)p, remaining);if (!len) {return true;}p += len - 1;+ remaining -= len - 1;}}if (strcmp(s, "true") == 0 || strcmp(s, "false") == 0 || strcmp(s, "null") == 0 ||@@ -163,7 +252,8 @@ static bool needs_quotes(const char *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++) {+ size_t remaining = s ? strlen(s) : 0;+ for (const char *p = s ? s : ""; *p; p++, remaining--) {switch (*p) {case '"':cbm_sb_append_n(sb, "\\\"", 2);@@ -187,14 +277,17 @@ static void append_quoted(cbm_sb_t *sb, const char *s) {snprintf(esc, sizeof(esc), "\\u%04x", (unsigned)c);cbm_sb_append(sb, esc);} else {- size_t len = utf8_sequence_length((const unsigned char *)p);+ size_t len = utf8_sequence_length((const unsigned char *)p, remaining);if (len) {cbm_sb_append_n(sb, p, len);p += len - 1;+ remaining -= len - 1;} else {- /* Invalid byte → U+FFFD: output is valid UTF-8 by- * construction, and the corruption stays visible. */- cbm_sb_append_n(sb, "\xEF\xBF\xBD", 3);+ /* Callers normalize first; retain a defensive printable+ * escape if an internal caller ever violates that rule. */+ char esc[8];+ snprintf(esc, sizeof(esc), "\\u%04x", (unsigned)c);+ cbm_sb_append(sb, esc);}}break;@@ -209,11 +302,19 @@ static void append_value(cbm_sb_t *sb, const char *s) {cbm_sb_append_n(sb, "-", 1); /* stable column positions for empties */return;}- if (needs_quotes(s)) {- append_quoted(sb, s);+ char *encoded = NULL;+ size_t encoded_len = 0;+ if (!cbm_output_encode_text(s, strlen(s), &encoded, &encoded_len)) {+ sb->oom = true;+ return;+ }+ const char *safe = encoded ? encoded : s;+ if (needs_quotes(safe)) {+ append_quoted(sb, safe);} else {- cbm_sb_append(sb, s);+ cbm_sb_append_n(sb, safe, encoded ? encoded_len : strlen(safe));}+ free(encoded);}/* Object keys and table column names share the compact tree's structural@@ -222,17 +323,26 @@ static void append_value(cbm_sb_t *sb, const char *s) {* empty key must remain the lossless string "" rather than the missing-value* placeholder "-". */static void append_key(cbm_sb_t *sb, const char *s) {- if (!s || !*s || needs_quotes(s) || strpbrk(s, ":()\\")) {- append_quoted(sb, s ? s : "");+ const char *raw = s ? s : "";+ char *encoded = NULL;+ size_t encoded_len = 0;+ if (!cbm_output_encode_text(raw, strlen(raw), &encoded, &encoded_len)) {+ sb->oom = true;+ return;+ }+ const char *safe = encoded ? encoded : raw;+ if (!*safe || needs_quotes(safe) || strpbrk(safe, ":()\\")) {+ append_quoted(sb, safe);} else {- cbm_sb_append(sb, s);+ cbm_sb_append_n(sb, safe, encoded ? encoded_len : strlen(safe));}+ free(encoded);}/* ── Scalars ────────────────────────────────────────────────────── */void cbm_tree_scalar_str(cbm_sb_t *sb, const char *key, const char *val) {- cbm_sb_append(sb, key);+ append_key(sb, key);cbm_sb_append_n(sb, ": ", 2);append_value(sb, val);cbm_sb_append_n(sb, "\n", 1);@@ -241,14 +351,14 @@ void cbm_tree_scalar_str(cbm_sb_t *sb, const char *key, const char *val) {void cbm_tree_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);+ append_key(sb, key);cbm_sb_append_n(sb, ": ", 2);cbm_sb_append(sb, num);cbm_sb_append_n(sb, "\n", 1);}void cbm_tree_scalar_bool(cbm_sb_t *sb, const char *key, bool v) {- cbm_sb_append(sb, key);+ append_key(sb, key);cbm_sb_append_n(sb, ": ", 2);cbm_sb_append(sb, v ? "true" : "false");cbm_sb_append_n(sb, "\n", 1);@@ -262,11 +372,11 @@ void cbm_tree_table_header(cbm_sb_t *sb, const char *key, int n, const char *conint ncols) {char num[32];snprintf(num, sizeof(num), ": %d (cols:", n);- cbm_sb_append(sb, key);+ append_key(sb, key);cbm_sb_append(sb, num);for (int i = 0; i < ncols; i++) {cbm_sb_append_n(sb, " ", 1);- cbm_sb_append(sb, cols[i]);+ append_key(sb, cols[i]);}cbm_sb_append_n(sb, ")\n", 2);}@@ -420,8 +530,8 @@ static size_t tree_semantic_prefix_boundary(const char *text, size_t shared) {}static bool tree_prefix_matches(const char *value, const tree_prefix_candidate_t *candidate) {- return value && !needs_quotes(value) && strlen(value) >= candidate->len &&- memcmp(value, candidate->text, candidate->len) == 0;+ return value && !output_text_requires_encoding(value, strlen(value)) && !needs_quotes(value) &&+ strlen(value) >= candidate->len && memcmp(value, candidate->text, candidate->len) == 0;}static int tree_prefix_choice(const char *value, const tree_prefix_candidate_t *candidates,@@ -731,7 +841,7 @@ static void json_tree_block_string(cbm_sb_t *sb, const char *text, int depth) {if (c == '\t' || (c >= 0x20 && c != 0x7f && c < 0x80)) {cbm_sb_append_n(sb, p, 1);} else if (c >= 0x80) {- size_t sequence = utf8_sequence_length((const unsigned char *)p);+ size_t sequence = utf8_sequence_length((const unsigned char *)p, (size_t)(end - p));if (sequence && p + sequence <= end) {cbm_sb_append_n(sb, p, sequence);p += sequence - 1;diff --git a/src/mcp/compact_out.h b/src/mcp/compact_out.hindex 6706e2086..fa86c24e9 100644--- a/src/mcp/compact_out.h+++ b/src/mcp/compact_out.h@@ -33,6 +33,13 @@ void cbm_sb_append(cbm_sb_t *sb, const char *s);char *cbm_sb_finish(cbm_sb_t *sb);void cbm_sb_free(cbm_sb_t *sb);+/* Make an arbitrary byte string safe for both standard JSON and the compact+ * tree without losing identity. Valid UTF-8 is left untouched (`*encoded` is+ * NULL). Invalid input becomes `@bytes:<lowercase hex>`; valid strings that+ * begin with the reserved `@bytes:` or `@utf8:` prefixes become+ * `@utf8:<original>`. The caller frees a non-NULL `*encoded`. */+bool cbm_output_encode_text(const char *data, size_t len, char **encoded, size_t *encoded_len);+/* `key: value` scalar lines (top-level, no indent). */void cbm_tree_scalar_str(cbm_sb_t *sb, const char *key, const char *val);void cbm_tree_scalar_int(cbm_sb_t *sb, const char *key, long long v);diff --git a/src/mcp/mcp.c b/src/mcp/mcp.cindex 91f339956..207121735 100644--- a/src/mcp/mcp.c+++ b/src/mcp/mcp.c@@ -151,13 +151,70 @@ static char *heap_strdup(const char *s) {return d;}-/* Write yyjson_mut_doc to heap-allocated JSON string.- * ALLOW_INVALID_UNICODE: some database strings may contain non-UTF-8 bytes- * from older indexing runs — don't fail serialization over it. */+/* Replace non-UTF-8 strings inside a mutable document before standard JSON+ * serialization. Payload documents also escape literal reserved prefixes;+ * final JSON-RPC envelopes preserve already-normalized payload strings so+ * structuredContent does not acquire a second @utf8: layer. */+static bool yy_mut_normalize_output_text(yyjson_mut_doc *doc, yyjson_mut_val *value,+ bool escape_reserved) {+ if (yyjson_mut_is_str(value)) {+ char *encoded = NULL;+ size_t encoded_len = 0;+ if (!cbm_output_encode_text(yyjson_mut_get_str(value), yyjson_mut_get_len(value), &encoded,+ &encoded_len)) {+ return false;+ }+ if (!encoded) {+ return true;+ }+ if (!escape_reserved && strncmp(encoded, "@utf8:", 6) == 0) {+ free(encoded);+ return true;+ }+ yyjson_mut_val *owned = yyjson_mut_strncpy(doc, encoded, encoded_len);+ free(encoded);+ return owned && yyjson_mut_set_strn(value, yyjson_mut_get_str(owned), encoded_len);+ }+ if (yyjson_mut_is_arr(value)) {+ size_t index;+ size_t maximum;+ yyjson_mut_val *item;+ yyjson_mut_arr_foreach(value, index, maximum, item) {+ if (!yy_mut_normalize_output_text(doc, item, escape_reserved)) {+ return false;+ }+ }+ } else if (yyjson_mut_is_obj(value)) {+ size_t index;+ size_t maximum;+ yyjson_mut_val *key;+ yyjson_mut_val *item;+ yyjson_mut_obj_foreach(value, index, maximum, key, item) {+ if (!yy_mut_normalize_output_text(doc, key, escape_reserved) ||+ !yy_mut_normalize_output_text(doc, item, escape_reserved)) {+ return false;+ }+ }+ }+ return true;+}++static char *yy_doc_write_output(yyjson_mut_doc *doc, bool escape_reserved) {+ yyjson_mut_val *root = doc ? yyjson_mut_doc_get_root(doc) : NULL;+ if (!root || !yy_mut_normalize_output_text(doc, root, escape_reserved)) {+ return NULL;+ }+ return yyjson_mut_write(doc, 0, NULL);+}++/* Tool payloads are the first encoding boundary. */static char *yy_doc_to_str(yyjson_mut_doc *doc) {- size_t len = 0;- char *s = yyjson_mut_write(doc, YYJSON_WRITE_ALLOW_INVALID_UNICODE, &len);- return s;+ return yy_doc_write_output(doc, true);+}++/* Payloads embedded in a JSON-RPC envelope have already crossed that boundary. */+static char *yy_final_doc_to_str(yyjson_mut_doc *doc) {+ return yy_doc_write_output(doc, false);}/* ══════════════════════════════════════════════════════════════════@@ -260,7 +317,7 @@ char *cbm_jsonrpc_format_response(const cbm_jsonrpc_response_t *resp) {yyjson_mut_obj_add_null(doc, root, "result");}- char *out = yy_doc_to_str(doc);+ char *out = yy_final_doc_to_str(doc);yyjson_mut_doc_free(doc);return out;}@@ -273,13 +330,23 @@ char *cbm_jsonrpc_format_error(int64_t id, int code, const char *message) {yyjson_mut_obj_add_str(doc, root, "jsonrpc", "2.0");yyjson_mut_obj_add_int(doc, root, "id", id);+ char *encoded_message = NULL;+ size_t encoded_message_len = 0;+ const char *raw_message = message ? message : "";+ if (!cbm_output_encode_text(raw_message, strlen(raw_message), &encoded_message,+ &encoded_message_len)) {+ yyjson_mut_doc_free(doc);+ return NULL;+ }+yyjson_mut_val *err = yyjson_mut_obj(doc);yyjson_mut_obj_add_int(doc, err, "code", code);- yyjson_mut_obj_add_str(doc, err, "message", message);+ yyjson_mut_obj_add_str(doc, err, "message", encoded_message ? encoded_message : raw_message);yyjson_mut_obj_add_val(doc, root, "error", err);- char *out = yy_doc_to_str(doc);+ char *out = yy_final_doc_to_str(doc);yyjson_mut_doc_free(doc);+ free(encoded_message);return out;}@@ -288,6 +355,19 @@ char *cbm_jsonrpc_format_error(int64_t id, int code, const char *message) {* ══════════════════════════════════════════════════════════════════ */char *cbm_mcp_text_result(const char *text, bool is_error) {+ yyjson_doc *structured_doc = text ? yyjson_read(text, strlen(text), 0) : NULL;+ yyjson_val *structured_root = structured_doc ? yyjson_doc_get_root(structured_doc) : NULL;+ bool structured_object = structured_root && yyjson_is_obj(structured_root);+ char *encoded_text = NULL;+ size_t encoded_text_len = 0;+ const char *raw_text = text ? text : "";+ if (!structured_object &&+ !cbm_output_encode_text(raw_text, strlen(raw_text), &encoded_text, &encoded_text_len)) {+ yyjson_doc_free(structured_doc);+ return NULL;+ }+ const char *wire_text = encoded_text ? encoded_text : raw_text;+yyjson_mut_doc *doc = yyjson_mut_doc_new(NULL);yyjson_mut_val *root = yyjson_mut_obj(doc);yyjson_mut_doc_set_root(doc, root);@@ -295,23 +375,16 @@ char *cbm_mcp_text_result(const char *text, bool is_error) {yyjson_mut_val *content = yyjson_mut_arr(doc);yyjson_mut_val *item = yyjson_mut_obj(doc);yyjson_mut_obj_add_str(doc, item, "type", "text");- yyjson_mut_obj_add_str(doc, item, "text", text ? text : "");+ yyjson_mut_obj_add_str(doc, item, "text", wire_text);yyjson_mut_arr_add_val(content, item);yyjson_mut_obj_add_val(doc, root, "content", content);bool has_structured_content = false;- if (text) {- yyjson_doc *structured_doc = yyjson_read(text, strlen(text), 0);- if (structured_doc) {- yyjson_val *structured_root = yyjson_doc_get_root(structured_doc);- if (yyjson_is_obj(structured_root)) {- yyjson_mut_val *structured = yyjson_val_mut_copy(doc, structured_root);- if (structured) {- yyjson_mut_obj_add_val(doc, root, "structuredContent", structured);- has_structured_content = true;- }- }- yyjson_doc_free(structured_doc);+ if (structured_object) {+ yyjson_mut_val *structured = yyjson_val_mut_copy(doc, structured_root);+ if (structured) {+ yyjson_mut_obj_add_val(doc, root, "structuredContent", structured);+ has_structured_content = true;}}if (!has_structured_content && is_error) {@@ -339,13 +412,15 @@ char *cbm_mcp_text_result(const char *text, bool is_error) {* tests/test_mcp.c binds all three branches; scripts/smoke-test.sh* asserts the same contract on the shipped binary. */yyjson_mut_val *structured = yyjson_mut_obj(doc);- yyjson_mut_obj_add_str(doc, structured, "error", text ? text : "");+ yyjson_mut_obj_add_str(doc, structured, "error", wire_text);yyjson_mut_obj_add_val(doc, root, "structuredContent", structured);}yyjson_mut_obj_add_bool(doc, root, "isError", is_error);- char *out = yy_doc_to_str(doc);+ char *out = yy_final_doc_to_str(doc);yyjson_mut_doc_free(doc);+ yyjson_doc_free(structured_doc);+ free(encoded_text);return out;}@@ -16202,8 +16277,9 @@ bool cbm_mcp_jsonrpc_response_prepend_notice(char **response_io, const char *notyyjson_mut_doc_free(mutable_document);return false;}- char *replacement =- yyjson_mut_write(mutable_document, YYJSON_WRITE_ALLOW_INVALID_UNICODE, NULL);+ /* The response was already normalized at its JSON-RPC boundary; preserve+ * those strings while adding the valid UTF-8 notice. */+ char *replacement = yyjson_mut_write(mutable_document, 0, NULL);yyjson_mut_doc_free(mutable_document);if (!replacement) {return false;diff --git a/tests/test_mcp.c b/tests/test_mcp.cindex 1608d297f..f58d0aa9c 100644--- a/tests/test_mcp.c+++ b/tests/test_mcp.c@@ -654,12 +654,14 @@ static void mcp_replacing_mutation_guard_end(void *context, const char *project)}}-TEST(tree_cell_sanitizes_control_and_invalid_utf8) {+TEST(tree_cell_reversibly_encodes_invalid_utf8) {/* One raw control or invalid-UTF8 byte in a cell poisons LINE-ORIENTED* consumers of the ENTIRE output (BSD grep treats all of it as* unmatchable binary — the macos-15-intel release-smoke B3 class), so- * cell emission guarantees valid UTF-8: control bytes escape as \u00XX,- * invalid sequences become U+FFFD, and both force the quoted form. */+ * cell emission guarantees valid UTF-8 without losing identity: an+ * invalid string is encoded in full as @bytes:<lowercase hex>. A valid+ * string beginning with that reserved prefix is escaped as @utf8:<text>,+ * so a consumer can always distinguish data from an encoded byte string. */cbm_sb_t sb;cbm_sb_init(&sb);cbm_tree_cell_str(&sb,@@ -668,8 +670,14 @@ TEST(tree_cell_sanitizes_control_and_invalid_utf8) {true);char *out = cbm_sb_finish(&sb);ASSERT_NOT_NULL(out);- ASSERT_STR_EQ(out, "\"evil\\u0001name\xEF\xBF\xBD"- "end\"");+ ASSERT_STR_EQ(out, "@bytes:6576696c016e616d65ff656e64");+ free(out);++ cbm_sb_init(&sb);+ cbm_tree_cell_str(&sb, "@bytes:ff", true);+ out = cbm_sb_finish(&sb);+ ASSERT_NOT_NULL(out);+ ASSERT_STR_EQ(out, "@utf8:@bytes:ff");free(out);cbm_sb_init(&sb);@@ -1537,6 +1545,39 @@ TEST(mcp_text_result_omits_structured_content_for_plain_text) {PASS();}+TEST(mcp_text_result_reversibly_encodes_invalid_utf8_as_standard_json) {+ const char invalid[] = {'n', 'a', 'm', 'e', (char)0xff, '\0'};+ char *json = cbm_mcp_text_result(invalid, false);+ ASSERT_NOT_NULL(json);++ /* Strict parsing is the interoperability contract: never rely on+ * YYJSON_WRITE_ALLOW_INVALID_UNICODE's non-standard byte passthrough. */+ yyjson_doc *doc = yyjson_read(json, strlen(json), 0);+ ASSERT_NOT_NULL(doc);+ yyjson_val *root = yyjson_doc_get_root(doc);+ yyjson_val *content = yyjson_obj_get(root, "content");+ yyjson_val *item = yyjson_arr_get_first(content);+ yyjson_val *text_value = item ? yyjson_obj_get(item, "text") : NULL;+ ASSERT_TRUE(yyjson_is_str(text_value));+ ASSERT_STR_EQ(yyjson_get_str(text_value), "@bytes:6e616d65ff");+ yyjson_doc_free(doc);+ free(json);++ json = cbm_mcp_text_result("@bytes:6e616d65ff", false);+ ASSERT_NOT_NULL(json);+ doc = yyjson_read(json, strlen(json), 0);+ ASSERT_NOT_NULL(doc);+ root = yyjson_doc_get_root(doc);+ content = yyjson_obj_get(root, "content");+ item = yyjson_arr_get_first(content);+ text_value = item ? yyjson_obj_get(item, "text") : NULL;+ ASSERT_TRUE(yyjson_is_str(text_value));+ ASSERT_STR_EQ(yyjson_get_str(text_value), "@utf8:@bytes:6e616d65ff");+ yyjson_doc_free(doc);+ free(json);+ PASS();+}+TEST(mcp_cancel_matches_request_id) {ASSERT_TRUE(cbm_mcp_cancel_request_matches("{\"requestId\":7}", 7, NULL));ASSERT_FALSE(cbm_mcp_cancel_request_matches("{\"requestId\":8}", 7, NULL));@@ -17840,7 +17881,7 @@ SUITE(mcp) {RUN_TEST(jsonrpc_parse_request);RUN_TEST(jsonrpc_parse_notification);RUN_TEST(jsonrpc_parse_invalid);- RUN_TEST(tree_cell_sanitizes_control_and_invalid_utf8);+ RUN_TEST(tree_cell_reversibly_encodes_invalid_utf8);RUN_TEST(json_to_tree_uses_header_once_rows_without_losing_metadata);RUN_TEST(json_to_tree_keeps_multiline_source_readable);RUN_TEST(json_to_tree_quotes_dynamic_keys_without_line_injection);@@ -17875,6 +17916,7 @@ SUITE(mcp) {RUN_TEST(mcp_get_architecture_aspects_schema_enum_pr560);RUN_TEST(mcp_text_result);RUN_TEST(mcp_text_result_omits_structured_content_for_plain_text);+ RUN_TEST(mcp_text_result_reversibly_encodes_invalid_utf8_as_standard_json);RUN_TEST(mcp_every_tool_result_is_duplication_free);RUN_TEST(mcp_cancel_matches_request_id);RUN_TEST(mcp_text_result_error);