-
Notifications
You must be signed in to change notification settings - Fork 2.5k
Expand file tree
/
Copy pathmcp.c
More file actions
4748 lines (4237 loc) · 185 KB
/
Copy pathmcp.c
File metadata and controls
4748 lines (4237 loc) · 185 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* mcp.c — MCP server: JSON-RPC 2.0 over stdio with 14 graph tools.
*
* Uses yyjson for fast JSON parsing/building.
* Single-threaded event loop: read line → parse → dispatch → respond.
*/
// operations
#include "foundation/constants.h"
enum {
MCP_FIELD_SIZE = 1040,
MCP_TIMEOUT_MS = 1000,
MCP_HALF_SEC_US = 500000,
MCP_MAX_ROWS = 100,
MCP_MAX_DEPTH = 15,
MCP_COL_2 = 2,
MCP_COL_3 = 3,
MCP_COL_4 = 4,
MCP_COL_7 = 7,
MCP_COL_10 = 10,
MCP_COL_16 = 16,
MCP_DB_EXT = 3, /* strlen(".db") */
MCP_MIN_DB_NAME = 4, /* min length for "x.db" */
MCP_SEPARATOR = 2, /* space for separator chars */
MCP_DEFAULT_DEPTH = 3,
MCP_DEFAULT_BFS_DEPTH = 2,
MCP_DEFAULT_LIMIT = 10,
MCP_BFS_LIMIT = 100,
MCP_N_DEFAULTS_2 = 2,
MCP_N_DEFAULTS_4 = 4,
MCP_URI_PREFIX = 7, /* strlen("file://") */
MCP_CONTENT_PREFIX = 15, /* strlen("Content-Length:") */
MCP_RETURN_2 = 2,
};
#define MCP_MS_TO_US 1000LL
#define MCP_S_TO_US 1000000LL
#define SLEN(s) (sizeof(s) - 1)
#include "mcp/mcp.h"
#include "store/store.h"
#include <sqlite3.h>
#include "cypher/cypher.h"
#include "pipeline/pipeline.h"
#include "pipeline/pass_cross_repo.h"
#include "cli/cli.h"
#include "watcher/watcher.h"
#include "foundation/mem.h"
#include "foundation/diagnostics.h"
#include "foundation/platform.h"
#include "foundation/compat.h"
#include "foundation/compat_fs.h"
#include "foundation/compat_thread.h"
#include "foundation/log.h"
#include "foundation/str_util.h"
#include "foundation/compat_regex.h"
#include "pipeline/artifact.h"
#ifdef _WIN32
#include <process.h>
#define getpid _getpid
#else
#include <unistd.h>
#include <poll.h>
#include <fcntl.h>
#endif
#include <yyjson/yyjson.h>
#include <stdint.h> // int64_t
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <time.h>
#include <errno.h>
/* ── Constants ────────────────────────────────────────────────── */
/* Default snippet fallback line count */
#define SNIPPET_DEFAULT_LINES 50
/* Idle store eviction: close cached project store after this many seconds
* of inactivity to free SQLite memory during idle periods. */
#define STORE_IDLE_TIMEOUT_S 60
/* Directory permissions: rwxr-xr-x */
#define ADR_DIR_PERMS 0755
/* JSON-RPC 2.0 standard error codes */
#define JSONRPC_PARSE_ERROR (-32700)
#define JSONRPC_METHOD_NOT_FOUND (-32601)
/* ── Helpers ────────────────────────────────────────────────────── */
static char *heap_strdup(const char *s) {
if (!s) {
return NULL;
}
size_t len = strlen(s);
char *d = malloc(len + SKIP_ONE);
if (d) {
memcpy(d, s, len + SKIP_ONE);
}
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. */
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;
}
/* ══════════════════════════════════════════════════════════════════
* JSON-RPC PARSING
* ══════════════════════════════════════════════════════════════════ */
int cbm_jsonrpc_parse(const char *line, cbm_jsonrpc_request_t *out) {
memset(out, 0, sizeof(*out));
out->id = CBM_NOT_FOUND;
yyjson_doc *doc = yyjson_read(line, strlen(line), 0);
if (!doc) {
return CBM_NOT_FOUND;
}
yyjson_val *root = yyjson_doc_get_root(doc);
if (!yyjson_is_obj(root)) {
yyjson_doc_free(doc);
return CBM_NOT_FOUND;
}
yyjson_val *v_jsonrpc = yyjson_obj_get(root, "jsonrpc");
yyjson_val *v_method = yyjson_obj_get(root, "method");
yyjson_val *v_id = yyjson_obj_get(root, "id");
yyjson_val *v_params = yyjson_obj_get(root, "params");
if (!v_method || !yyjson_is_str(v_method)) {
yyjson_doc_free(doc);
return CBM_NOT_FOUND;
}
out->jsonrpc =
heap_strdup(v_jsonrpc && yyjson_is_str(v_jsonrpc) ? yyjson_get_str(v_jsonrpc) : "2.0");
out->method = heap_strdup(yyjson_get_str(v_method));
if (v_id) {
out->has_id = true;
if (yyjson_is_int(v_id)) {
out->id = yyjson_get_int(v_id);
} else if (yyjson_is_str(v_id)) {
/* JSON-RPC 2.0 §4 permits string ids (Claude Desktop uses them).
* Preserve verbatim instead of coercing via strtol (issue #253). */
out->id_str = heap_strdup(yyjson_get_str(v_id));
}
}
if (v_params) {
out->params_raw = yyjson_val_write(v_params, 0, NULL);
}
yyjson_doc_free(doc);
return 0;
}
void cbm_jsonrpc_request_free(cbm_jsonrpc_request_t *r) {
if (!r) {
return;
}
safe_str_free(&r->jsonrpc);
safe_str_free(&r->method);
safe_str_free(&r->id_str);
safe_str_free(&r->params_raw);
memset(r, 0, sizeof(*r));
}
/* ══════════════════════════════════════════════════════════════════
* JSON-RPC FORMATTING
* ══════════════════════════════════════════════════════════════════ */
char *cbm_jsonrpc_format_response(const cbm_jsonrpc_response_t *resp) {
yyjson_mut_doc *doc = yyjson_mut_doc_new(NULL);
yyjson_mut_val *root = yyjson_mut_obj(doc);
yyjson_mut_doc_set_root(doc, root);
yyjson_mut_obj_add_str(doc, root, "jsonrpc", "2.0");
if (resp->id_str) {
yyjson_mut_obj_add_str(doc, root, "id", resp->id_str);
} else {
yyjson_mut_obj_add_int(doc, root, "id", resp->id);
}
if (resp->error_json) {
/* Parse the error JSON and embed */
yyjson_doc *err_doc = yyjson_read(resp->error_json, strlen(resp->error_json), 0);
if (err_doc) {
yyjson_mut_val *err_val = yyjson_val_mut_copy(doc, yyjson_doc_get_root(err_doc));
yyjson_mut_obj_add_val(doc, root, "error", err_val);
yyjson_doc_free(err_doc);
}
} else if (resp->result_json) {
/* Parse the result JSON and embed */
yyjson_doc *res_doc = yyjson_read(resp->result_json, strlen(resp->result_json), 0);
if (res_doc) {
yyjson_mut_val *res_val = yyjson_val_mut_copy(doc, yyjson_doc_get_root(res_doc));
yyjson_mut_obj_add_val(doc, root, "result", res_val);
yyjson_doc_free(res_doc);
}
} else {
/* JSON-RPC 2.0 spec: response MUST contain "result" or "error" */
yyjson_mut_obj_add_null(doc, root, "result");
}
char *out = yy_doc_to_str(doc);
yyjson_mut_doc_free(doc);
return out;
}
char *cbm_jsonrpc_format_error(int64_t id, int code, const char *message) {
yyjson_mut_doc *doc = yyjson_mut_doc_new(NULL);
yyjson_mut_val *root = yyjson_mut_obj(doc);
yyjson_mut_doc_set_root(doc, root);
yyjson_mut_obj_add_str(doc, root, "jsonrpc", "2.0");
yyjson_mut_obj_add_int(doc, root, "id", id);
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_val(doc, root, "error", err);
char *out = yy_doc_to_str(doc);
yyjson_mut_doc_free(doc);
return out;
}
/* ══════════════════════════════════════════════════════════════════
* MCP PROTOCOL HELPERS
* ══════════════════════════════════════════════════════════════════ */
char *cbm_mcp_text_result(const char *text, bool is_error) {
yyjson_mut_doc *doc = yyjson_mut_doc_new(NULL);
yyjson_mut_val *root = yyjson_mut_obj(doc);
yyjson_mut_doc_set_root(doc, root);
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);
yyjson_mut_arr_add_val(content, item);
yyjson_mut_obj_add_val(doc, root, "content", content);
if (is_error) {
yyjson_mut_obj_add_bool(doc, root, "isError", true);
}
char *out = yy_doc_to_str(doc);
yyjson_mut_doc_free(doc);
return out;
}
/* ── Tool definitions ─────────────────────────────────────────── */
typedef struct {
const char *name;
const char *description;
const char *input_schema; /* JSON string */
} tool_def_t;
static const tool_def_t TOOLS[] = {
{"index_repository",
"Index a repository into the knowledge graph. "
"Special mode 'cross-repo-intelligence': skip extraction, only match Routes/Channels "
"and Maven library dependencies across projects to create CROSS_HTTP_CALLS/"
"CROSS_ASYNC_CALLS/CROSS_CHANNEL/CROSS_LIBRARY_DEPENDS_ON/CROSS_LIBRARY_USED_BY edges. "
"Requires target_projects param. Ensure target projects have fresh indexes first.",
"{\"type\":\"object\",\"properties\":{\"repo_path\":{\"type\":\"string\",\"description\":"
"\"Path to the repository\"},"
"\"mode\":{\"type\":\"string\","
"\"enum\":[\"full\",\"moderate\",\"fast\",\"cross-repo-intelligence\"],"
"\"default\":\"full\",\"description\":\"All modes run type-aware LSP call/usage "
"resolution (per-file + cross-file). full: all files + similarity/semantic edges. "
"moderate: filtered files + similarity/semantic. fast: filtered files, no "
"similarity/semantic. cross-repo-intelligence: match Routes/Channels and Maven library "
"dependencies across projects.\"},"
"\"target_projects\":{\"type\":\"array\",\"items\":{\"type\":\"string\"},"
"\"description\":\"Projects to search for cross-repo links (cross-repo-intelligence mode). "
"Use [\\\"*\\\"] for all indexed projects. Run list_projects to see available projects.\"},"
"\"persistence\":{\"type\":\"boolean\",\"default\":false,\"description\":"
"\"Write compressed artifact to .codebase-memory/graph.db.zst for team sharing. "
"Teammates can bootstrap from the artifact instead of full re-indexing.\"}"
"},\"required\":[\"repo_path\"]}"},
{"search_graph",
"Search the code knowledge graph for functions, classes, routes, and variables. Use INSTEAD "
"OF grep/glob when finding code definitions, implementations, or relationships. Three search "
"modes: (1) query='update settings' for BM25 ranked full-text search with camelCase "
"splitting and structural label boosting — recommended for natural-language discovery; "
"(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.",
"{\"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 "
"indexed as individual words (updateCloudClient → update, cloud, client). Results are "
"ranked with structural boosting: Functions/Methods +10, Routes +8, Classes/Interfaces +5. "
"Noise labels (File/Folder/Module/Variable) are filtered out. When provided, name_pattern "
"is ignored.\"},"
"\"label\":{\"type\":\"string\"},\"name_pattern\":{\"type\":\"string\"},\"qn_pattern\":{"
"\"type\":\"string\"},\"file_pattern\":{\"type\":\"string\"},"
"\"relationship\":{\"type\":\"string\"},\"min_degree\":{\"type\":\"integer\"},"
"\"max_degree\":{\"type\":\"integer\"},\"exclude_entry_points\":{\"type\":\"boolean\"},"
"\"include_connected\":{\"type\":\"boolean\"},\"semantic_query\":{"
"\"type\":\"array\",\"items\":{\"type\":\"string\"},\"description\":\"MUST be an ARRAY of "
"keyword strings (e.g. [\\\"send\\\",\\\"pubsub\\\",\\\"publish\\\"]) — NOT a single string. "
"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 "
"'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.\"}},"
"\"required\":[\"project\"]}"},
{"query_graph",
"Execute a Cypher query against the knowledge graph for complex multi-hop patterns, "
"aggregations, and cross-service analysis. The response includes 'total' (returned "
"row count). There is a hard 100k row ceiling — for broad queries add LIMIT in the "
"Cypher itself or use search_graph + offset/limit pagination instead. "
"COMPLEXITY / BOTTLENECKS: every Function and Method node carries queryable complexity "
"properties — cyclomatic (complexity), cognitive, loop_count, loop_depth (max nested-loop "
"depth, a polynomial-degree proxy), plus interprocedural transitive_loop_depth (worst-case "
"nested-loop degree propagated along CALLS edges) and a recursive flag. Additional "
"hot-path signals: linear_scan_in_loop (count of find/contains/indexOf-style scans inside a "
"loop — the hidden O(n^2) that loop_depth misses), alloc_in_loop (allocations/appends inside "
"a loop), recursion_in_loop (a self-call inside a loop), unguarded_recursion (recursion with "
"no conditionally-guarded base case), param_count and max_access_depth (structure smells). "
"Find all hot-path candidates in one query, e.g. MATCH (f:Function) WHERE "
"f.transitive_loop_depth >= 3 OR f.linear_scan_in_loop >= 1 RETURN f.qualified_name, "
"f.transitive_loop_depth, f.linear_scan_in_loop ORDER BY f.transitive_loop_depth DESC.",
"{\"type\":\"object\",\"properties\":{\"query\":{\"type\":\"string\",\"description\":\"Cypher "
"query\"},\"project\":{\"type\":\"string\"},\"max_rows\":{\"type\":\"integer\","
"\"description\":"
"\"Optional row limit. Default: unlimited up to a 100k row "
"ceiling. No offset support — use search_graph for paginated browsing.\"}},"
"\"required\":[\"query\",\"project\"]}"},
{"trace_path",
"Trace paths through the code graph. Modes: calls (callers/callees), data_flow (value "
"propagation with args at each hop), cross_service (through HTTP/async Route nodes). "
"Use INSTEAD OF grep for callers, dependencies, impact analysis, or data flow tracing.",
"{\"type\":\"object\",\"properties\":{\"function_name\":{\"type\":\"string\"},\"project\":{"
"\"type\":\"string\"},\"direction\":{\"type\":\"string\",\"enum\":[\"inbound\",\"outbound\","
"\"both\"],\"default\":\"both\"},\"depth\":{\"type\":\"integer\",\"default\":3},\"mode\":{"
"\"type\":\"string\",\"enum\":[\"calls\",\"data_flow\",\"cross_service\"],\"default\":"
"\"calls\",\"description\":\"calls: follow CALLS edges. data_flow: follow CALLS+DATA_FLOWS "
"with arg expressions. cross_service: follow HTTP_CALLS+ASYNC_CALLS+DATA_FLOWS through "
"Routes.\"},\"parameter_name\":{\"type\":\"string\",\"description\":\"For data_flow mode: "
"scope trace to a specific parameter name\"},\"edge_types\":{\"type\":\"array\",\"items\":{"
"\"type\":\"string\"}},\"risk_labels\":{\"type\":\"boolean\",\"default\":false,"
"\"description\":\"Add risk classification (CRITICAL/HIGH/MEDIUM/LOW) based on hop distance"
"\"},\"include_tests\":{\"type\":\"boolean\",\"default\":false,"
"\"description\":\"Include test files in results. When false (default), test files are "
"filtered out. When true, test nodes are included with is_test=true marker."
"\"}},\"required\":[\"function_name\",\"project\"]}"},
{"get_code_snippet",
"Read source code for a function/class/symbol. IMPORTANT: First call search_graph to find the "
"exact qualified_name, then pass it here. This is a read tool, not a search tool. Accepts "
"full qualified_name (exact match) or short function name (returns suggestions if ambiguous).",
"{\"type\":\"object\",\"properties\":{\"qualified_name\":{\"type\":\"string\",\"description\":"
"\"Full qualified_name from search_graph, or short function name\"},\"project\":{"
"\"type\":\"string\"},\"include_neighbors\":{"
"\"type\":\"boolean\",\"default\":false}},\"required\":[\"qualified_name\",\"project\"]}"},
{"get_graph_schema", "Get the schema of the knowledge graph (node labels, edge types)",
"{\"type\":\"object\",\"properties\":{\"project\":{\"type\":\"string\"}},\"required\":["
"\"project\"]}"},
{"get_architecture",
"Get high-level architecture overview — packages, services, dependencies, and project "
"structure at a glance. Includes 'clusters': Leiden community detection over the call/import "
"graph, surfacing the de-facto modules (each with a label, member count, cohesion score, "
"representative top_nodes, and the packages/edge_types that bind it) — use these to grasp "
"the real architectural seams, which often cut across the folder layout.",
"{\"type\":\"object\",\"properties\":{\"project\":{\"type\":\"string\"},\"aspects\":{\"type\":"
"\"array\",\"items\":{\"type\":\"string\"}}},\"required\":[\"project\"]}"},
{"search_code",
"Graph-augmented code search. Finds text patterns via grep, then enriches results with "
"the knowledge graph: deduplicates matches into containing functions, ranks by structural "
"importance (definitions first, popular functions next, tests last). "
"Modes: compact (default, signatures only — token efficient), full (with source), "
"files (just file paths). Use path_filter regex to scope results. "
"TRUNCATION: enriched results are capped at limit (default 10). Response carries "
"'total_grep_matches' (raw grep hit count) and 'total_results' (deduplicated function "
"count) — compare to limit to detect truncation. There is no offset parameter; to see "
"more, raise limit or narrow the query with file_pattern / path_filter.",
"{\"type\":\"object\",\"properties\":{\"pattern\":{\"type\":\"string\"},\"project\":{\"type\":"
"\"string\"},\"file_pattern\":{\"type\":\"string\",\"description\":\"Glob for grep "
"--include (e.g. *.go)\"},\"path_filter\":{\"type\":\"string\",\"description\":\"Regex "
"filter on result file paths (e.g. ^src/ or \\\\.(go|ts)$)\"},\"mode\":{\"type\":\"string\","
"\"enum\":[\"compact\",\"full\",\"files\"],\"default\":\"compact\",\"description\":\"compact: "
"signatures+metadata (default). full: with source. files: just file list.\"},"
"\"context\":{\"type\":\"integer\",\"description\":\"Lines of context around each match "
"(like grep -C). Only used in compact mode.\"},"
"\"regex\":{\"type\":\"boolean\",\"default\":false},\"limit\":{\"type\":\"integer\","
"\"description\":\"Max enriched results per call. Default 10. Response includes "
"'total_grep_matches' and 'total_results' so callers can detect truncation. No "
"offset parameter — raise limit or narrow with file_pattern / path_filter to see more."
"\",\"default\":10}},\"required\":[\"pattern\",\"project\"]}"},
{"list_projects", "List all indexed projects", "{\"type\":\"object\",\"properties\":{}}"},
{"delete_project", "Delete a project from the index",
"{\"type\":\"object\",\"properties\":{\"project\":{\"type\":\"string\"}},\"required\":["
"\"project\"]}"},
{"index_status", "Get the indexing status of a project",
"{\"type\":\"object\",\"properties\":{\"project\":{\"type\":\"string\"}},\"required\":["
"\"project\"]}"},
{"detect_changes", "Detect code changes and their impact",
"{\"type\":\"object\",\"properties\":{\"project\":{\"type\":\"string\"},\"scope\":{\"type\":"
"\"string\"},\"depth\":{\"type\":\"integer\",\"default\":2},\"base_branch\":{\"type\":"
"\"string\",\"default\":\"main\"},\"since\":{\"type\":\"string\",\"description\":"
"\"Git ref or date to compare from (e.g. HEAD~5, v0.5.0, 2026-01-01)\"}},\"required\":"
"[\"project\"]}"},
{"manage_adr", "Create or update Architecture Decision Records",
"{\"type\":\"object\",\"properties\":{\"project\":{\"type\":\"string\"},\"mode\":{\"type\":"
"\"string\",\"enum\":[\"get\",\"update\",\"sections\"]},\"content\":{\"type\":\"string\"},"
"\"sections\":{\"type\":\"array\",\"items\":{\"type\":\"string\"}}},\"required\":[\"project\"]"
"}"},
{"ingest_traces", "Ingest runtime traces to enhance the knowledge graph",
"{\"type\":\"object\",\"properties\":{\"traces\":{\"type\":\"array\",\"items\":{\"type\":"
"\"object\"}},\"project\":{\"type\":"
"\"string\"}},\"required\":[\"traces\",\"project\"]}"},
};
static const int TOOL_COUNT = sizeof(TOOLS) / sizeof(TOOLS[0]);
char *cbm_mcp_tools_list(void) {
yyjson_mut_doc *doc = yyjson_mut_doc_new(NULL);
yyjson_mut_val *root = yyjson_mut_obj(doc);
yyjson_mut_doc_set_root(doc, root);
yyjson_mut_val *tools = yyjson_mut_arr(doc);
for (int i = 0; i < TOOL_COUNT; i++) {
yyjson_mut_val *tool = yyjson_mut_obj(doc);
yyjson_mut_obj_add_str(doc, tool, "name", TOOLS[i].name);
yyjson_mut_obj_add_str(doc, tool, "description", TOOLS[i].description);
/* Parse input schema JSON and embed */
yyjson_doc *schema_doc =
yyjson_read(TOOLS[i].input_schema, strlen(TOOLS[i].input_schema), 0);
if (schema_doc) {
yyjson_mut_val *schema = yyjson_val_mut_copy(doc, yyjson_doc_get_root(schema_doc));
yyjson_mut_obj_add_val(doc, tool, "inputSchema", schema);
yyjson_doc_free(schema_doc);
}
yyjson_mut_arr_add_val(tools, tool);
}
yyjson_mut_obj_add_val(doc, root, "tools", tools);
char *out = yy_doc_to_str(doc);
yyjson_mut_doc_free(doc);
return out;
}
/* Supported protocol versions, newest first. The server picks the newest
* version that it shares with the client (per MCP spec version negotiation). */
static const char *SUPPORTED_PROTOCOL_VERSIONS[] = {
"2025-11-25",
"2025-06-18",
"2025-03-26",
"2024-11-05",
};
static const int SUPPORTED_VERSION_COUNT =
(int)(sizeof(SUPPORTED_PROTOCOL_VERSIONS) / sizeof(SUPPORTED_PROTOCOL_VERSIONS[0]));
char *cbm_mcp_initialize_response(const char *params_json) {
/* Determine protocol version: if client requests a version we support,
* echo it back; otherwise respond with our latest. */
const char *version = SUPPORTED_PROTOCOL_VERSIONS[0]; /* default: latest */
if (params_json) {
yyjson_doc *pdoc = yyjson_read(params_json, strlen(params_json), 0);
if (pdoc) {
yyjson_val *pv = yyjson_obj_get(yyjson_doc_get_root(pdoc), "protocolVersion");
if (pv && yyjson_is_str(pv)) {
const char *requested = yyjson_get_str(pv);
for (int i = 0; i < SUPPORTED_VERSION_COUNT; i++) {
if (strcmp(requested, SUPPORTED_PROTOCOL_VERSIONS[i]) == 0) {
version = SUPPORTED_PROTOCOL_VERSIONS[i];
break;
}
}
}
yyjson_doc_free(pdoc);
}
}
yyjson_mut_doc *doc = yyjson_mut_doc_new(NULL);
yyjson_mut_val *root = yyjson_mut_obj(doc);
yyjson_mut_doc_set_root(doc, root);
yyjson_mut_obj_add_str(doc, root, "protocolVersion", version);
yyjson_mut_val *impl = yyjson_mut_obj(doc);
yyjson_mut_obj_add_str(doc, impl, "name", "codebase-memory-mcp");
yyjson_mut_obj_add_str(doc, impl, "version", "0.10.0");
yyjson_mut_obj_add_val(doc, root, "serverInfo", impl);
yyjson_mut_val *caps = yyjson_mut_obj(doc);
yyjson_mut_val *tools_cap = yyjson_mut_obj(doc);
yyjson_mut_obj_add_val(doc, caps, "tools", tools_cap);
yyjson_mut_obj_add_val(doc, root, "capabilities", caps);
char *out = yy_doc_to_str(doc);
yyjson_mut_doc_free(doc);
return out;
}
/* ══════════════════════════════════════════════════════════════════
* ARGUMENT EXTRACTION
* ══════════════════════════════════════════════════════════════════ */
char *cbm_mcp_get_tool_name(const char *params_json) {
yyjson_doc *doc = yyjson_read(params_json, strlen(params_json), 0);
if (!doc) {
return NULL;
}
yyjson_val *root = yyjson_doc_get_root(doc);
yyjson_val *name = yyjson_obj_get(root, "name");
char *result = NULL;
if (name && yyjson_is_str(name)) {
result = heap_strdup(yyjson_get_str(name));
}
yyjson_doc_free(doc);
return result;
}
char *cbm_mcp_get_arguments(const char *params_json) {
yyjson_doc *doc = yyjson_read(params_json, strlen(params_json), 0);
if (!doc) {
return NULL;
}
yyjson_val *root = yyjson_doc_get_root(doc);
yyjson_val *args = yyjson_obj_get(root, "arguments");
char *result = NULL;
if (args) {
result = yyjson_val_write(args, 0, NULL);
}
yyjson_doc_free(doc);
return result ? result : heap_strdup("{}");
}
char *cbm_mcp_get_string_arg(const char *args_json, const char *key) {
yyjson_doc *doc = yyjson_read(args_json, strlen(args_json), 0);
if (!doc) {
return NULL;
}
yyjson_val *root = yyjson_doc_get_root(doc);
yyjson_val *val = yyjson_obj_get(root, key);
char *result = NULL;
if (val && yyjson_is_str(val)) {
result = heap_strdup(yyjson_get_str(val));
}
yyjson_doc_free(doc);
return result;
}
int cbm_mcp_get_int_arg(const char *args_json, const char *key, int default_val) {
yyjson_doc *doc = yyjson_read(args_json, strlen(args_json), 0);
if (!doc) {
return default_val;
}
yyjson_val *root = yyjson_doc_get_root(doc);
yyjson_val *val = yyjson_obj_get(root, key);
int result = default_val;
if (val && yyjson_is_int(val)) {
result = yyjson_get_int(val);
}
yyjson_doc_free(doc);
return result;
}
bool cbm_mcp_get_bool_arg(const char *args_json, const char *key) {
yyjson_doc *doc = yyjson_read(args_json, strlen(args_json), 0);
if (!doc) {
return false;
}
yyjson_val *root = yyjson_doc_get_root(doc);
yyjson_val *val = yyjson_obj_get(root, key);
bool result = false;
if (val && yyjson_is_bool(val)) {
result = yyjson_get_bool(val);
}
yyjson_doc_free(doc);
return result;
}
/* ══════════════════════════════════════════════════════════════════
* MCP SERVER
* ══════════════════════════════════════════════════════════════════ */
struct cbm_mcp_server {
cbm_store_t *store; /* currently open project store (or NULL) */
bool owns_store; /* true if we opened the store */
char *current_project; /* which project store is open for (heap) */
time_t store_last_used; /* last time resolve_store was called for a named project */
char update_notice[CBM_SZ_256]; /* one-shot update notice, cleared after first injection */
bool update_checked; /* true after background check has been launched */
cbm_thread_t update_tid; /* background update check thread */
bool update_thread_active; /* true if update thread was started and needs joining */
/* Session + auto-index state */
char session_root[CBM_SZ_1K]; /* detected project root path */
char session_project[CBM_SZ_256]; /* derived project name */
bool session_detected; /* true after first detection attempt */
struct cbm_watcher *watcher; /* external watcher ref (not owned) */
struct cbm_config *config; /* external config ref (not owned) */
cbm_thread_t autoindex_tid;
bool autoindex_active; /* true if auto-index thread was started */
/* Active pipeline tracking for cancellation support */
cbm_pipeline_t *active_pipeline; /* non-NULL while index_repository runs */
int64_t active_request_id; /* JSON-RPC id of the in-progress tool call */
};
cbm_mcp_server_t *cbm_mcp_server_new(const char *store_path) {
cbm_mcp_server_t *srv = calloc(CBM_ALLOC_ONE, sizeof(*srv));
if (!srv) {
return NULL;
}
/* If a store_path is given, open that project directly.
* Otherwise, create an in-memory store for test/embedded use. */
if (store_path) {
srv->store = cbm_store_open(store_path);
srv->current_project = heap_strdup(store_path);
} else {
srv->store = cbm_store_open_memory();
}
srv->owns_store = true;
return srv;
}
cbm_store_t *cbm_mcp_server_store(cbm_mcp_server_t *srv) {
return srv ? srv->store : NULL;
}
void cbm_mcp_server_set_project(cbm_mcp_server_t *srv, const char *project) {
if (!srv) {
return;
}
free(srv->current_project);
srv->current_project = project ? heap_strdup(project) : NULL;
}
void cbm_mcp_server_set_watcher(cbm_mcp_server_t *srv, struct cbm_watcher *w) {
if (srv) {
srv->watcher = w;
}
}
void cbm_mcp_server_set_config(cbm_mcp_server_t *srv, struct cbm_config *cfg) {
if (srv) {
srv->config = cfg;
}
}
void cbm_mcp_server_free(cbm_mcp_server_t *srv) {
if (!srv) {
return;
}
if (srv->update_thread_active) {
cbm_thread_join(&srv->update_tid);
}
if (srv->autoindex_active) {
cbm_thread_join(&srv->autoindex_tid);
}
if (srv->owns_store && srv->store) {
cbm_store_close(srv->store);
}
free(srv->current_project);
free(srv);
}
/* ── Idle store eviction ──────────────────────────────────────── */
void cbm_mcp_server_evict_idle(cbm_mcp_server_t *srv, int timeout_s) {
if (!srv || !srv->store) {
return;
}
/* Protect initial in-memory stores that were never accessed via a named project.
* store_last_used stays 0 until resolve_store is called with a non-NULL project. */
if (srv->store_last_used == 0) {
return;
}
time_t now = time(NULL);
if ((now - srv->store_last_used) < timeout_s) {
return;
}
if (srv->owns_store) {
cbm_store_close(srv->store);
}
srv->store = NULL;
free(srv->current_project);
srv->current_project = NULL;
srv->store_last_used = 0;
}
bool cbm_mcp_server_has_cached_store(cbm_mcp_server_t *srv) {
return (srv && srv->store != NULL) != 0;
}
cbm_pipeline_t *cbm_mcp_server_active_pipeline(cbm_mcp_server_t *srv) {
return srv ? srv->active_pipeline : NULL;
}
/* ── Cache dir + project DB path helpers ───────────────────────── */
/* Returns the cache directory. Writes to buf, returns buf for convenience. */
static const char *cache_dir(char *buf, size_t bufsz) {
const char *dir = cbm_resolve_cache_dir();
if (!dir) {
dir = cbm_tmpdir();
}
snprintf(buf, bufsz, "%s", dir);
return buf;
}
/* Returns full .db path for a project: <cache_dir>/<project>.db */
static const char *project_db_path(const char *project, char *buf, size_t bufsz) {
if (!cbm_validate_project_name(project)) {
buf[0] = '\0';
return buf;
}
char dir[CBM_SZ_1K];
cache_dir(dir, sizeof(dir));
snprintf(buf, bufsz, "%s/%s.db", dir, project);
return buf;
}
/* ── Store resolution ──────────────────────────────────────────── */
/* Open the right project's .db file for query tools.
* Caches the connection — reopens only when project changes.
* Tracks last-access time so the event loop can evict idle stores. */
static cbm_store_t *resolve_store(cbm_mcp_server_t *srv, const char *project) {
if (!project) {
return NULL; /* project is required — no implicit fallback */
}
srv->store_last_used = time(NULL);
/* Already open for this project? */
if (srv->current_project && strcmp(srv->current_project, project) == 0 && srv->store) {
return srv->store;
}
/* Close old store */
if (srv->owns_store && srv->store) {
cbm_store_close(srv->store);
srv->store = NULL;
}
/* Open project's .db file — query-only open (no SQLITE_OPEN_CREATE) to
* prevent ghost .db file creation for unknown/unindexed projects. */
char path[CBM_SZ_1K];
project_db_path(project, path, sizeof(path));
srv->store = cbm_store_open_path_query(path);
if (srv->store) {
/* Check DB integrity — auto-clean corrupt databases */
if (!cbm_store_check_integrity(srv->store)) {
cbm_log_error("store.auto_clean", "project", project, "path", path, "action",
"deleting corrupt db — re-index required");
cbm_store_close(srv->store);
srv->store = NULL;
/* Delete the corrupt DB + WAL/SHM files */
cbm_unlink(path);
char wal_path[MCP_FIELD_SIZE];
char shm_path[MCP_FIELD_SIZE];
snprintf(wal_path, sizeof(wal_path), "%s-wal", path);
snprintf(shm_path, sizeof(shm_path), "%s-shm", path);
cbm_unlink(wal_path);
cbm_unlink(shm_path);
return NULL;
}
/* Verify the project actually exists in this database.
* A .db file may exist but be empty (e.g., after delete_project on
* Linux where unlink defers actual removal). Opening an empty/deleted
* store without closing it leaks the SQLite connection. */
cbm_project_t proj_verify = {0};
if (cbm_store_get_project(srv->store, project, &proj_verify) != CBM_STORE_OK) {
cbm_store_close(srv->store);
srv->store = NULL;
return NULL;
}
cbm_project_free_fields(&proj_verify);
srv->owns_store = true;
free(srv->current_project);
srv->current_project = heap_strdup(project);
}
return srv->store;
}
/* Forward decl — definition lives below alongside list_projects. */
static bool is_project_db_file(const char *name, size_t len);
/* Forward decl — definition lives below in handle_trace_call_path's helpers. */
static void free_node_contents(cbm_node_t *n);
/* Scan cache dir for .db files, writing comma-separated quoted names into out.
* Returns the number of projects found. */
static int collect_db_project_names(const char *dir_path, char *out, size_t out_sz) {
int count = 0;
int offset = 0;
cbm_dir_t *d = cbm_opendir(dir_path);
if (!d) {
return 0;
}
cbm_dirent_t *entry;
while ((entry = cbm_readdir(d)) != NULL) {
const char *n = entry->name;
size_t len = strlen(n);
if (!is_project_db_file(n, len)) {
continue;
}
if ((size_t)offset >= out_sz)
break; /* bounds check before write */
if (count > 0 && offset < (int)out_sz - MCP_SEPARATOR) {
out[offset++] = ',';
}
int wrote = snprintf(out + offset, out_sz - (size_t)offset, "\"%.*s\"", (int)(len - 3), n);
if (wrote > 0) {
offset += wrote;
if ((size_t)offset >= out_sz) {
offset = (int)out_sz - 1; /* clamp on truncation */
}
}
count++;
}
cbm_closedir(d);
return count;
}
/* Build a helpful error listing available projects. Caller must free() result. */
static char *build_project_list_error(const char *reason) {
char dir_path[CBM_SZ_1K];
cache_dir(dir_path, sizeof(dir_path));
char projects[CBM_SZ_4K] = "";
int count = collect_db_project_names(dir_path, projects, sizeof(projects));
enum { ERR_BUF_SZ = 5120 };
char buf[ERR_BUF_SZ];
if (count > 0) {
snprintf(buf, sizeof(buf),
"{\"error\":\"%s\",\"hint\":\"Use list_projects to see all indexed projects, "
"then pass the project name.\",\"available_projects\":[%s],\"count\":%d}",
reason, projects, count);
} else {
snprintf(buf, sizeof(buf),
"{\"error\":\"%s\",\"hint\":\"No projects indexed yet. "
"Call index_repository first.\"}",
reason);
}
return heap_strdup(buf);
}
/* Bail with project list when no store is available. */
#define REQUIRE_STORE(store, project) \
do { \
if (!(store)) { \
char *_err = build_project_list_error("project not found or not indexed"); \
char *_res = cbm_mcp_text_result(_err, true); \
free(_err); \
free(project); \
return _res; \
} \
} while (0)
/* ── Tool handler implementations ─────────────────────────────── */
/* Return true if filename is a valid project .db file (not temp/internal).
*
* Project names derived from /tmp/... source roots legitimately begin with
* "tmp-" (cbm_project_name_from_path: "/tmp/bench/..." → "tmp-bench-...";
* see tests/test_pipeline.c fixtures), so the prefix must NOT be excluded.
* The "_" prefix is reserved for internal/hidden DBs, and ":memory:" is the
* SQLite in-memory marker (defensive — never appears as a real file). */
static bool is_project_db_file(const char *name, size_t len) {
if (len < MCP_MIN_DB_NAME || strcmp(name + len - MCP_DB_EXT, ".db") != 0) {
return false;
}
if (strncmp(name, "_", SLEN("_")) == 0 || strncmp(name, ":memory:", SLEN(":memory:")) == 0) {
return false;
}
return true;
}
/* Open a .db file briefly, collect node/edge counts and root_path,
* then append a JSON entry to arr. */
static void build_project_json_entry(yyjson_mut_doc *doc, yyjson_mut_val *arr, const char *dir_path,
const char *name, size_t name_len, const struct stat *st) {
char project_name[CBM_SZ_1K];
snprintf(project_name, sizeof(project_name), "%.*s", (int)(name_len - 3), name);
char full_path[CBM_SZ_2K];
snprintf(full_path, sizeof(full_path), "%s/%s", dir_path, name);
cbm_store_t *pstore = cbm_store_open_path(full_path);
int nodes = 0;
int edges = 0;
char root_path_buf[CBM_SZ_1K] = "";
if (pstore) {
nodes = cbm_store_count_nodes(pstore, project_name);
edges = cbm_store_count_edges(pstore, project_name);
cbm_project_t proj = {0};
if (cbm_store_get_project(pstore, project_name, &proj) == CBM_STORE_OK) {
if (proj.root_path) {
snprintf(root_path_buf, sizeof(root_path_buf), "%s", proj.root_path);
}
safe_str_free(&proj.name);
safe_str_free(&proj.indexed_at);
safe_str_free(&proj.root_path);
}
cbm_store_close(pstore);
}
yyjson_mut_val *p = yyjson_mut_obj(doc);
yyjson_mut_obj_add_strcpy(doc, p, "name", project_name);
yyjson_mut_obj_add_strcpy(doc, p, "root_path", root_path_buf);
yyjson_mut_obj_add_int(doc, p, "nodes", nodes);
yyjson_mut_obj_add_int(doc, p, "edges", edges);
yyjson_mut_obj_add_int(doc, p, "size_bytes", (int64_t)st->st_size);
yyjson_mut_arr_add_val(arr, p);
}
/* list_projects: scan cache directory for .db files.
* Each project is a single .db file — no central registry needed. */
static char *handle_list_projects(cbm_mcp_server_t *srv, const char *args) {
(void)srv;
(void)args;
char dir_path[CBM_SZ_1K];
cache_dir(dir_path, sizeof(dir_path));
cbm_dir_t *d = cbm_opendir(dir_path);
yyjson_mut_doc *doc = yyjson_mut_doc_new(NULL);
yyjson_mut_val *root = yyjson_mut_obj(doc);
yyjson_mut_doc_set_root(doc, root);
yyjson_mut_val *arr = yyjson_mut_arr(doc);
if (!d) {
char msg[CBM_SZ_1K];
snprintf(msg, sizeof(msg),
"{\"error\":\"cannot read cache directory: %s\",\"hint\":"
"\"Check directory permissions or run index_repository first.\"}",
dir_path);
yyjson_mut_doc_free(doc);
return cbm_mcp_text_result(msg, true);
}
cbm_dirent_t *entry;
while ((entry = cbm_readdir(d)) != NULL) {
const char *name = entry->name;
size_t len = strlen(name);
if (!is_project_db_file(name, len)) {
continue;
}
char full_path[CBM_SZ_2K];
snprintf(full_path, sizeof(full_path), "%s/%s", dir_path, name);
struct stat st;
if (stat(full_path, &st) != 0) {
continue;
}
build_project_json_entry(doc, arr, dir_path, name, len, &st);
}
cbm_closedir(d);