Skip to content

Commit 800476f

Browse files
committed
feat(mcp): add structured tool metadata
Signed-off-by: Martin Vogel <martin.vogel.tech@gmail.com>
1 parent b075f05 commit 800476f

3 files changed

Lines changed: 110 additions & 24 deletions

File tree

‎src/mcp/mcp.c‎

Lines changed: 70 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -249,29 +249,66 @@ char *cbm_mcp_text_result(const char *text, bool is_error) {
249249
yyjson_mut_val *content = yyjson_mut_arr(doc);
250250
yyjson_mut_val *item = yyjson_mut_obj(doc);
251251
yyjson_mut_obj_add_str(doc, item, "type", "text");
252-
yyjson_mut_obj_add_str(doc, item, "text", text);
252+
yyjson_mut_obj_add_str(doc, item, "text", text ? text : "");
253253
yyjson_mut_arr_add_val(content, item);
254254
yyjson_mut_obj_add_val(doc, root, "content", content);
255255

256-
if (is_error) {
257-
yyjson_mut_obj_add_bool(doc, root, "isError", true);
256+
if (!is_error && text) {
257+
yyjson_doc *structured_doc = yyjson_read(text, strlen(text), 0);
258+
if (structured_doc) {
259+
yyjson_val *structured_root = yyjson_doc_get_root(structured_doc);
260+
if (yyjson_is_obj(structured_root)) {
261+
yyjson_mut_val *structured = yyjson_val_mut_copy(doc, structured_root);
262+
yyjson_mut_obj_add_val(doc, root, "structuredContent", structured);
263+
}
264+
yyjson_doc_free(structured_doc);
265+
}
258266
}
267+
yyjson_mut_obj_add_bool(doc, root, "isError", is_error);
259268

260269
char *out = yy_doc_to_str(doc);
261270
yyjson_mut_doc_free(doc);
262271
return out;
263272
}
264273

274+
bool cbm_mcp_cancel_request_matches(const char *params_json, int64_t active_id,
275+
const char *active_id_str) {
276+
if (!params_json) {
277+
return false;
278+
}
279+
280+
yyjson_doc *doc = yyjson_read(params_json, strlen(params_json), 0);
281+
if (!doc) {
282+
return false;
283+
}
284+
285+
yyjson_val *root = yyjson_doc_get_root(doc);
286+
yyjson_val *request_id = yyjson_obj_get(root, "requestId");
287+
bool matches = false;
288+
if (request_id) {
289+
if (active_id_str) {
290+
matches =
291+
yyjson_is_str(request_id) && strcmp(yyjson_get_str(request_id), active_id_str) == 0;
292+
} else {
293+
matches = yyjson_is_int(request_id) && yyjson_get_int(request_id) == active_id;
294+
}
295+
}
296+
297+
yyjson_doc_free(doc);
298+
return matches;
299+
}
300+
265301
/* ── Tool definitions ─────────────────────────────────────────── */
266302

267303
typedef struct {
268304
const char *name;
305+
const char *title;
269306
const char *description;
270307
const char *input_schema; /* JSON string */
271308
} tool_def_t;
272309

273310
static const tool_def_t TOOLS[] = {
274-
{"index_repository",
311+
{"index_repository", "Index repository",
275312
"Index a repository into the knowledge graph. "
276313
"Special mode 'cross-repo-intelligence': skip extraction, only match Routes/Channels "
277314
"across projects to create CROSS_HTTP_CALLS/CROSS_ASYNC_CALLS/CROSS_CHANNEL edges. "
@@ -292,7 +329,7 @@ static const tool_def_t TOOLS[] = {
292329
"Teammates can bootstrap from the artifact instead of full re-indexing.\"}"
293330
"},\"required\":[\"repo_path\"]}"},
294331

295-
{"search_graph",
332+
{"search_graph", "Search graph",
296333
"Search the code knowledge graph for functions, classes, routes, and variables. Use INSTEAD "
297334
"OF grep/glob when finding code definitions, implementations, or relationships. Three search "
298335
"modes: (1) query='update settings' for BM25 ranked full-text search with camelCase "
@@ -329,7 +366,7 @@ static const tool_def_t TOOLS[] = {
329366
"increment offset by limit and re-call while has_more is true.\"}},"
330367
"\"required\":[\"project\"]}"},
331368

332-
{"query_graph",
369+
{"query_graph", "Query graph",
333370
"Execute a Cypher query against the knowledge graph for complex multi-hop patterns, "
334371
"aggregations, and cross-service analysis. The response includes 'total' (returned "
335372
"row count). There is a hard 100k row ceiling — for broad queries add LIMIT in the "
@@ -352,7 +389,7 @@ static const tool_def_t TOOLS[] = {
352389
"ceiling. No offset support — use search_graph for paginated browsing.\"}},"
353390
"\"required\":[\"query\",\"project\"]}"},
354391

355-
{"trace_path",
392+
{"trace_path", "Trace path",
356393
"Trace paths through the code graph. Modes: calls (callers/callees), data_flow (value "
357394
"propagation with args at each hop), cross_service (through HTTP/async Route nodes). "
358395
"Use INSTEAD OF grep for callers, dependencies, impact analysis, or data flow tracing.",
@@ -373,7 +410,7 @@ static const tool_def_t TOOLS[] = {
373410
"filtered out. When true, test nodes are included with is_test=true marker."
374411
"\"}},\"required\":[\"function_name\",\"project\"]}"},
375412

376-
{"get_code_snippet",
413+
{"get_code_snippet", "Get code snippet",
377414
"Read source code for a function/class/symbol. IMPORTANT: First call search_graph to find the "
378415
"exact qualified_name, then pass it here. This is a read tool, not a search tool. Accepts "
379416
"full qualified_name (exact match) or short function name (returns suggestions if ambiguous).",
@@ -382,11 +419,12 @@ static const tool_def_t TOOLS[] = {
382419
"\"type\":\"string\"},\"include_neighbors\":{"
383420
"\"type\":\"boolean\",\"default\":false}},\"required\":[\"qualified_name\",\"project\"]}"},
384421

385-
{"get_graph_schema", "Get the schema of the knowledge graph (node labels, edge types)",
422+
{"get_graph_schema", "Get graph schema",
423+
"Get the schema of the knowledge graph (node labels, edge types)",
386424
"{\"type\":\"object\",\"properties\":{\"project\":{\"type\":\"string\"}},\"required\":["
387425
"\"project\"]}"},
388426

389-
{"get_architecture",
427+
{"get_architecture", "Get architecture",
390428
"Get high-level architecture overview — packages, services, dependencies, and project "
391429
"structure at a glance. Includes 'clusters': Leiden community detection over the call/import "
392430
"graph, surfacing the de-facto modules (each with a label, member count, cohesion score, "
@@ -399,7 +437,7 @@ static const tool_def_t TOOLS[] = {
399437
"\"aspects\":{\"type\":\"array\",\"items\":{\"type\":\"string\"}}},\"required\":[\"project\"]"
400438
"}"},
401439

402-
{"search_code",
440+
{"search_code", "Search code",
403441
"Graph-augmented code search. Finds text patterns via grep, then enriches results with "
404442
"the knowledge graph: deduplicates matches into containing functions, ranks by structural "
405443
"importance (definitions first, popular functions next, tests last). "
@@ -423,31 +461,31 @@ static const tool_def_t TOOLS[] = {
423461
"offset parameter — raise limit or narrow with file_pattern / path_filter to see more."
424462
"\",\"default\":10}},\"required\":[\"pattern\",\"project\"]}"},
425463

426-
{"list_projects", "List all indexed projects", "{\"type\":\"object\",\"properties\":{}}"},
427-
428-
{"delete_project", "Delete a project from the index",
464+
{"list_projects", "List projects", "List all indexed projects",
465+
"{\"type\":\"object\",\"properties\":{}}"},
466+
{"delete_project", "Delete project", "Delete a project from the index",
429467
"{\"type\":\"object\",\"properties\":{\"project\":{\"type\":\"string\"}},\"required\":["
430468
"\"project\"]}"},
431469

432-
{"index_status", "Get the indexing status of a project",
470+
{"index_status", "Index status", "Get the indexing status of a project",
433471
"{\"type\":\"object\",\"properties\":{\"project\":{\"type\":\"string\"}},\"required\":["
434472
"\"project\"]}"},
435473

436-
{"detect_changes", "Detect code changes and their impact",
474+
{"detect_changes", "Detect changes", "Detect code changes and their impact",
437475
"{\"type\":\"object\",\"properties\":{\"project\":{\"type\":\"string\"},\"scope\":{\"type\":"
438476
"\"string\"},\"depth\":{\"type\":\"integer\",\"default\":2},\"base_branch\":{\"type\":"
439477
"\"string\",\"default\":\"main\"},\"since\":{\"type\":\"string\",\"description\":"
440478
"\"Git ref or tag to compare from (e.g. HEAD~5, v0.5.0). Diffs <ref>...HEAD.\"}},"
441479
"\"required\":"
442480
"[\"project\"]}"},
443481

444-
{"manage_adr", "Create or update Architecture Decision Records",
482+
{"manage_adr", "Manage ADR", "Create or update Architecture Decision Records",
445483
"{\"type\":\"object\",\"properties\":{\"project\":{\"type\":\"string\"},\"mode\":{\"type\":"
446484
"\"string\",\"enum\":[\"get\",\"update\",\"sections\"]},\"content\":{\"type\":\"string\"},"
447485
"\"sections\":{\"type\":\"array\",\"items\":{\"type\":\"string\"}}},\"required\":[\"project\"]"
448486
"}"},
449487

450-
{"ingest_traces", "Ingest runtime traces to enhance the knowledge graph",
488+
{"ingest_traces", "Ingest traces", "Ingest runtime traces to enhance the knowledge graph",
451489
"{\"type\":\"object\",\"properties\":{\"traces\":{\"type\":\"array\",\"items\":{\"type\":"
452490
"\"object\"}},\"project\":{\"type\":"
453491
"\"string\"}},\"required\":[\"traces\",\"project\"]}"},
@@ -465,6 +503,7 @@ char *cbm_mcp_tools_list(void) {
465503
for (int i = 0; i < TOOL_COUNT; i++) {
466504
yyjson_mut_val *tool = yyjson_mut_obj(doc);
467505
yyjson_mut_obj_add_str(doc, tool, "name", TOOLS[i].name);
506+
yyjson_mut_obj_add_str(doc, tool, "title", TOOLS[i].title);
468507
yyjson_mut_obj_add_str(doc, tool, "description", TOOLS[i].description);
469508

470509
/* Parse input schema JSON and embed */
@@ -531,6 +570,7 @@ char *cbm_mcp_initialize_response(const char *params_json) {
531570

532571
yyjson_mut_val *caps = yyjson_mut_obj(doc);
533572
yyjson_mut_val *tools_cap = yyjson_mut_obj(doc);
573+
yyjson_mut_obj_add_bool(doc, tools_cap, "listChanged", false);
534574
yyjson_mut_obj_add_val(doc, caps, "tools", tools_cap);
535575
yyjson_mut_obj_add_val(doc, root, "capabilities", caps);
536576

@@ -644,6 +684,7 @@ struct cbm_mcp_server {
644684
/* Active pipeline tracking for cancellation support */
645685
cbm_pipeline_t *active_pipeline; /* non-NULL while index_repository runs */
646686
int64_t active_request_id; /* JSON-RPC id of the in-progress tool call */
687+
char *active_request_id_str; /* string JSON-RPC id of the in-progress tool call */
647688
};
648689

649690
cbm_mcp_server_t *cbm_mcp_server_new(const char *store_path) {
@@ -703,6 +744,7 @@ void cbm_mcp_server_free(cbm_mcp_server_t *srv) {
703744
cbm_store_close(srv->store);
704745
}
705746
free(srv->current_project);
747+
free(srv->active_request_id_str);
706748
free(srv);
707749
}
708750

@@ -4816,11 +4858,11 @@ char *cbm_mcp_server_handle(cbm_mcp_server_t *srv, const char *line) {
48164858
/* Notifications (no id) → handle cancellation, then no response */
48174859
if (!req.has_id) {
48184860
if (req.method && strcmp(req.method, "notifications/cancelled") == 0) {
4819-
/* MCP cancellation: cancel the active pipeline if request ID matches */
4820-
if (srv->active_pipeline) {
4861+
if (srv->active_pipeline &&
4862+
cbm_mcp_cancel_request_matches(req.params_raw, srv->active_request_id,
4863+
srv->active_request_id_str)) {
48214864
cbm_pipeline_cancel(srv->active_pipeline);
4822-
cbm_log_info("mcp.cancelled", "request_id_active",
4823-
srv->active_request_id > 0 ? "yes" : "none");
4865+
cbm_log_info("mcp.cancelled", "match", "true");
48244866
}
48254867
}
48264868
cbm_jsonrpc_request_free(&req);
@@ -4842,10 +4884,16 @@ char *cbm_mcp_server_handle(cbm_mcp_server_t *srv, const char *line) {
48424884
char *tool_name = req.params_raw ? cbm_mcp_get_tool_name(req.params_raw) : NULL;
48434885
char *tool_args =
48444886
req.params_raw ? cbm_mcp_get_arguments(req.params_raw) : heap_strdup("{}");
4887+
srv->active_request_id = req.id;
4888+
free(srv->active_request_id_str);
4889+
srv->active_request_id_str = req.id_str ? heap_strdup(req.id_str) : NULL;
48454890

48464891
struct timespec t0;
48474892
cbm_clock_gettime(CLOCK_MONOTONIC, &t0);
48484893
result_json = cbm_mcp_handle_tool(srv, tool_name, tool_args);
4894+
srv->active_request_id = CBM_NOT_FOUND;
4895+
free(srv->active_request_id_str);
4896+
srv->active_request_id_str = NULL;
48494897
struct timespec t1;
48504898
cbm_clock_gettime(CLOCK_MONOTONIC, &t1);
48514899
long long dur_us = ((long long)(t1.tv_sec - t0.tv_sec) * MCP_S_TO_US) +

‎src/mcp/mcp.h‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,10 @@ char *cbm_jsonrpc_format_error(int64_t id, int code, const char *message);
5454
/* Format an MCP tool result with text content. Returns heap-allocated JSON. */
5555
char *cbm_mcp_text_result(const char *text, bool is_error);
5656

57+
/* Return true when notifications/cancelled params target the active request. */
58+
bool cbm_mcp_cancel_request_matches(const char *params_json, int64_t active_id,
59+
const char *active_id_str);
60+
5761
/* Format the tools/list response. Returns heap-allocated JSON. */
5862
char *cbm_mcp_tools_list(void);
5963

‎tests/test_mcp.c‎

Lines changed: 36 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,7 @@ TEST(mcp_initialize_response) {
144144
ASSERT_NOT_NULL(strstr(json, "codebase-memory-mcp"));
145145
ASSERT_NOT_NULL(strstr(json, "capabilities"));
146146
ASSERT_NOT_NULL(strstr(json, "tools"));
147+
ASSERT_NOT_NULL(strstr(json, "\"listChanged\":false"));
147148
ASSERT_NOT_NULL(strstr(json, "2025-11-25"));
148149
free(json);
149150

@@ -188,6 +189,15 @@ TEST(mcp_tools_list) {
188189
PASS();
189190
}
190191

192+
TEST(mcp_tools_list_latest_metadata) {
193+
char *json = cbm_mcp_tools_list();
194+
ASSERT_NOT_NULL(json);
195+
ASSERT_NOT_NULL(strstr(json, "\"title\":\"Search graph\""));
196+
ASSERT_NOT_NULL(strstr(json, "\"title\":\"Index repository\""));
197+
free(json);
198+
PASS();
199+
}
200+
191201
TEST(mcp_tools_array_schemas_have_items) {
192202
/* VS Code 1.112+ rejects array schemas without "items" (see
193203
* https://github.com/microsoft/vscode/issues/248810).
@@ -223,11 +233,32 @@ TEST(mcp_text_result) {
223233
ASSERT_NOT_NULL(strstr(json, "\"type\":\"text\""));
224234
/* The text value is JSON-escaped inside the "text" field */
225235
ASSERT_NOT_NULL(strstr(json, "total"));
236+
ASSERT_NOT_NULL(strstr(json, "\"structuredContent\":{\"total\":5}"));
237+
ASSERT_NOT_NULL(strstr(json, "\"isError\":false"));
226238
ASSERT_NULL(strstr(json, "\"isError\":true"));
227239
free(json);
228240
PASS();
229241
}
230242

243+
TEST(mcp_text_result_skips_structured_content_for_plain_text) {
244+
char *json = cbm_mcp_text_result("plain text", false);
245+
ASSERT_NOT_NULL(json);
246+
ASSERT_NULL(strstr(json, "\"structuredContent\""));
247+
ASSERT_NOT_NULL(strstr(json, "\"isError\":false"));
248+
free(json);
249+
PASS();
250+
}
251+
252+
TEST(mcp_cancel_matches_request_id) {
253+
ASSERT_TRUE(cbm_mcp_cancel_request_matches("{\"requestId\":7}", 7, NULL));
254+
ASSERT_FALSE(cbm_mcp_cancel_request_matches("{\"requestId\":8}", 7, NULL));
255+
ASSERT_TRUE(cbm_mcp_cancel_request_matches("{\"requestId\":\"call-1\"}", -1, "call-1"));
256+
ASSERT_FALSE(cbm_mcp_cancel_request_matches("{\"requestId\":\"call-2\"}", -1, "call-1"));
257+
ASSERT_FALSE(cbm_mcp_cancel_request_matches("{\"requestId\":7}", -1, "7"));
258+
ASSERT_FALSE(cbm_mcp_cancel_request_matches("{}", 7, NULL));
259+
PASS();
260+
}
261+
231262
TEST(mcp_text_result_error) {
232263
char *json = cbm_mcp_text_result("something failed", true);
233264
ASSERT_NOT_NULL(json);
@@ -1156,7 +1187,7 @@ TEST(tool_manage_adr_get_with_existing_adr) {
11561187
/* ADR content must appear in response */
11571188
ASSERT_NOT_NULL(strstr(resp, "PURPOSE"));
11581189
/* Must not be an error */
1159-
ASSERT_NULL(strstr(resp, "isError"));
1190+
ASSERT_NULL(strstr(resp, "\"isError\":true"));
11601191
free(resp);
11611192

11621193
/* Clean up */
@@ -1202,7 +1233,7 @@ TEST(tool_manage_adr_unified_backend_issue256) {
12021233
"\"mode\":\"get\"}}}");
12031234
ASSERT_NOT_NULL(resp);
12041235
ASSERT_NOT_NULL(strstr(resp, "Unified ADR backend."));
1205-
ASSERT_NULL(strstr(resp, "isError"));
1236+
ASSERT_NULL(strstr(resp, "\"isError\":true"));
12061237
free(resp);
12071238

12081239
cbm_mcp_server_free(srv);
@@ -2324,8 +2355,11 @@ SUITE(mcp) {
23242355
/* MCP protocol helpers */
23252356
RUN_TEST(mcp_initialize_response);
23262357
RUN_TEST(mcp_tools_list);
2358+
RUN_TEST(mcp_tools_list_latest_metadata);
23272359
RUN_TEST(mcp_tools_array_schemas_have_items);
23282360
RUN_TEST(mcp_text_result);
2361+
RUN_TEST(mcp_text_result_skips_structured_content_for_plain_text);
2362+
RUN_TEST(mcp_cancel_matches_request_id);
23292363
RUN_TEST(mcp_text_result_error);
23302364

23312365
/* Argument extraction */

0 commit comments

Comments
 (0)