MCPcopy Create free account
hub / github.com/DeusData/codebase-memory-mcp / attach_result_source

Function attach_result_source

src/mcp/mcp.c:14364–14452  ·  view source on GitHub ↗

Attach source or context lines to a search result JSON item. */

Source from the content-addressed store, hash-verified

14362
14363/* Attach source or context lines to a search result JSON item. */
14364static void attach_result_source(yyjson_mut_doc *doc, yyjson_mut_val *item, search_result_t *r,
14365 int mode, int context_lines, int source_max_lines,
14366 const char *root_path, root_containment_t *containment) {
14367 enum { MODE_FULL = 1 };
14368 if (r->start_line <= 0 || r->end_line <= 0) {
14369 return;
14370 }
14371 size_t root_length = strlen(root_path);
14372 size_t file_length = strlen(r->file);
14373 if (root_length > SIZE_MAX - file_length - 2U) {
14374 return;
14375 }
14376 char *abs_path = malloc(root_length + file_length + 2U);
14377 if (!abs_path) {
14378 return;
14379 }
14380 memcpy(abs_path, root_path, root_length);
14381 abs_path[root_length] = '/';
14382 memcpy(abs_path + root_length + 1U, r->file, file_length + 1U);
14383
14384 /* Containment: a search result whose indexed path resolves outside the
14385 * project root (a `..` segment, or a symlink/junction that discovery
14386 * followed) must not be read back into the response. Same guard the
14387 * snippet path already uses. */
14388 if (!root_containment_check(containment, abs_path)) {
14389 free(abs_path);
14390 return;
14391 }
14392
14393 if (mode == MODE_FULL) {
14394 /* Cap each hit's source at a match-anchored window: uncapped
14395 * whole-symbol dumps ran to 5.7KB × N hits (142KB responses). The
14396 * complete symbol stays one get_code_snippet call away;
14397 * source_start/source_truncated make the cut explicit. */
14398 enum { SC_FULL_LEAD = 5 };
14399 if (source_max_lines <= 0) {
14400 yyjson_mut_obj_add_bool(doc, item, "source_omitted", true);
14401 free(abs_path);
14402 return;
14403 }
14404 int s = r->start_line;
14405 int e = r->end_line;
14406 bool truncated = false;
14407 if (e - s + 1 > source_max_lines) {
14408 if (r->match_count > 0 && r->match_lines[0] - SC_FULL_LEAD > s) {
14409 s = r->match_lines[0] - SC_FULL_LEAD;
14410 }
14411 e = s + source_max_lines - 1;
14412 if (e > r->end_line) {
14413 e = r->end_line;
14414 }
14415 truncated = true;
14416 }
14417 char *source = read_file_lines(abs_path, s, e);
14418 if (source) {
14419 char *safe_source = sanitize_utf8_lossy(source);
14420 if (safe_source) {
14421 yyjson_mut_obj_add_strcpy(doc, item, "source", safe_source);

Callers 1

assemble_search_outputFunction · 0.85

Calls 3

root_containment_checkFunction · 0.85
read_file_linesFunction · 0.85
sanitize_utf8_lossyFunction · 0.85

Tested by

no test coverage detected