Skip to content

Commit 24b79f2

Browse files
committed
mcp: answer a refused session with the reason instead of exiting
A newer binary started in MCP mode next to a daemon from another build printed the conflict to stderr and exited. The client never got an answer to initialize, so agents saw a timeout and never the reason. The refused process now releases its cohort lease and endpoint, then serves MCP until stdin closes: initialize (the reason becomes the server instructions), tools/list (one tool, cbm_unavailable, described by the reason), every tools/call as isError with the reason, ping and prompts/list. It starts no work and touches no cache, store or lock. The exit status stays a failure. The CLI path is unchanged. Signed-off-by: chidev <[email protected]>
1 parent 274a68a commit 24b79f2

4 files changed

Lines changed: 219 additions & 3 deletions

File tree

‎src/main.c‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1814,6 +1814,21 @@ static void main_report_client_bootstrap_failure(cbm_daemon_process_role_t role,
18141814
main_report_client_failure(role, detail);
18151815
}
18161816

1817+
/* A daemon conflict in MCP mode must still answer MCP. A process that only
1818+
* wrote the reason to stderr and exited left the client waiting on
1819+
* `initialize` until it timed out, so the agent saw a timeout and never the
1820+
* reason. The refused session now answers initialize, tools/list and every
1821+
* tools/call (as a tool error carrying the reason) until stdin closes. The
1822+
* caller has already released every lease and the endpoint; this touches no
1823+
* cache, store or lock. Exit status stays a failure: the session was refused. */
1824+
static int main_serve_mcp_refusal(const char *detail) {
1825+
(void)fprintf(stderr, "codebase-memory-mcp: %s\n", detail);
1826+
(void)fprintf(stderr, "codebase-memory-mcp: this session answers MCP with that reason and "
1827+
"starts no work; it exits when the client closes stdin\n");
1828+
(void)cbm_mcp_refusal_run(stdin, stdout, detail);
1829+
return EXIT_FAILURE;
1830+
}
1831+
18171832
/* #2277: a conflict is a legitimate refusal (another build owns the account
18181833
* daemon), but it must name that daemon and the way out. known_active is a
18191834
* STATUS answer the caller already holds; without one this probes STATUS
@@ -3332,6 +3347,16 @@ int main(int argc, char **argv) {
33323347
main_conflict_remedy_probe(endpoint, &identity, NULL, remedy, sizeof(remedy));
33333348
}
33343349
}
3350+
if (role == CBM_DAEMON_PROCESS_MCP_CLIENT &&
3351+
client_cohort_status == CBM_VERSION_COHORT_CONFLICT) {
3352+
char detail[MAIN_CLIENT_FAILURE_DETAIL_CAP];
3353+
(void)snprintf(detail, sizeof(detail), "%s%s%s",
3354+
formatted ? message : "client exact-build admission failed",
3355+
remedy[0] ? " " : "", remedy);
3356+
(void)main_version_cohort_close(&client_cohort_lease, &client_cohort_manager);
3357+
cbm_daemon_ipc_endpoint_free(endpoint);
3358+
return main_serve_mcp_refusal(detail);
3359+
}
33353360
(void)fprintf(stderr, "codebase-memory-mcp: %s%s%s\n",
33363361
formatted ? message : "client exact-build admission failed",
33373362
remedy[0] ? " " : "", remedy);
@@ -3390,6 +3415,17 @@ int main(int argc, char **argv) {
33903415
cbm_daemon_bootstrap_status_t bootstrap_status =
33913416
main_client_bootstrap_with_upgrade(&bootstrap_config, &bootstrap_result, true);
33923417
cbm_daemon_ipc_endpoint_free(endpoint);
3418+
if (bootstrap_status == CBM_DAEMON_BOOTSTRAP_CONFLICT &&
3419+
role == CBM_DAEMON_PROCESS_MCP_CLIENT) {
3420+
char detail[MAIN_CLIENT_FAILURE_DETAIL_CAP];
3421+
(void)snprintf(detail, sizeof(detail), "%s%s%s",
3422+
bootstrap_result.message[0] ? bootstrap_result.message
3423+
: "CBM could not start because a conflicting "
3424+
"CBM process is active",
3425+
bootstrap_result.remedy[0] ? " " : "", bootstrap_result.remedy);
3426+
(void)main_version_cohort_close(&client_cohort_lease, &client_cohort_manager);
3427+
return main_serve_mcp_refusal(detail);
3428+
}
33933429
if (bootstrap_status != CBM_DAEMON_BOOTSTRAP_CONNECTED || !bootstrap_result.client) {
33943430
main_report_client_bootstrap_failure(role, &bootstrap_result);
33953431
(void)main_version_cohort_close(&client_cohort_lease, &client_cohort_manager);

‎src/mcp/mcp.c‎

Lines changed: 113 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1496,8 +1496,12 @@ static const char MCP_SCOUT_SERVER_INSTRUCTIONS[] =
14961496
"check_index_coverage tells whether a cited file was fully indexed. Findings are "
14971497
"provisional.";
14981498

1499+
/* instructions_override, when set, replaces the profile's instructions: the
1500+
* refusal responder uses it to put the startup refusal in front of the agent
1501+
* at connect time. */
14991502
static char *cbm_mcp_initialize_response_for_profile(const char *params_json,
1500-
cbm_mcp_tool_profile_t profile) {
1503+
cbm_mcp_tool_profile_t profile,
1504+
const char *instructions_override) {
15011505
/* Determine protocol version: if client requests a version we support,
15021506
* echo it back; otherwise respond with our latest. */
15031507
const char *version = SUPPORTED_PROTOCOL_VERSIONS[0]; /* default: latest */
@@ -1543,6 +1547,9 @@ static char *cbm_mcp_initialize_response_for_profile(const char *params_json,
15431547
} else if (profile == CBM_MCP_TOOL_PROFILE_SCOUT) {
15441548
instructions = MCP_SCOUT_SERVER_INSTRUCTIONS;
15451549
}
1550+
if (instructions_override) {
1551+
instructions = instructions_override;
1552+
}
15461553
yyjson_mut_obj_add_str(doc, root, "instructions", instructions);
15471554

15481555
char *out = yy_doc_to_str(doc);
@@ -1551,7 +1558,7 @@ static char *cbm_mcp_initialize_response_for_profile(const char *params_json,
15511558
}
15521559

15531560
char *cbm_mcp_initialize_response(const char *params_json) {
1554-
return cbm_mcp_initialize_response_for_profile(params_json, CBM_MCP_TOOL_PROFILE_ALL);
1561+
return cbm_mcp_initialize_response_for_profile(params_json, CBM_MCP_TOOL_PROFILE_ALL, NULL);
15551562
}
15561563

15571564
/* ══════════════════════════════════════════════════════════════════
@@ -21823,7 +21830,8 @@ char *cbm_mcp_server_handle(cbm_mcp_server_t *srv, const char *line) {
2182321830
bool request_timed_out = false;
2182421831

2182521832
if (strcmp(req.method, "initialize") == 0) {
21826-
result_json = cbm_mcp_initialize_response_for_profile(req.params_raw, srv->tool_profile);
21833+
result_json =
21834+
cbm_mcp_initialize_response_for_profile(req.params_raw, srv->tool_profile, NULL);
2182721835
detect_session(srv);
2182821836
if (srv->background_tasks && srv->tool_profile == CBM_MCP_TOOL_PROFILE_ALL) {
2182921837
maybe_auto_index(srv);
@@ -22272,6 +22280,108 @@ int cbm_mcp_server_run(cbm_mcp_server_t *srv, FILE *in, FILE *out) {
2227222280
return 0;
2227322281
}
2227422282

22283+
/* ── Refusal responder ────────────────────────────────────────── */
22284+
22285+
#define MCP_REFUSAL_TOOL_NAME "cbm_unavailable"
22286+
#define MCP_REFUSAL_PREFIX "codebase-memory-mcp is unavailable in this session. "
22287+
22288+
static const char MCP_REFUSAL_METHOD_NOT_FOUND[] =
22289+
"{\"code\":-32601,\"message\":\"Method not found\"}";
22290+
22291+
/* One tool, not an empty list: an empty list reads as "no tools" and the agent
22292+
* never learns why. The tool's description already carries the reason, and a
22293+
* call returns it as a tool error. */
22294+
static char *mcp_refusal_tools_list(const char *notice) {
22295+
yyjson_mut_doc *doc = yyjson_mut_doc_new(NULL);
22296+
yyjson_mut_val *root = yyjson_mut_obj(doc);
22297+
yyjson_mut_doc_set_root(doc, root);
22298+
yyjson_mut_val *tools = yyjson_mut_arr(doc);
22299+
yyjson_mut_val *tool = yyjson_mut_obj(doc);
22300+
yyjson_mut_obj_add_str(doc, tool, "name", MCP_REFUSAL_TOOL_NAME);
22301+
yyjson_mut_obj_add_str(doc, tool, "description", notice);
22302+
yyjson_mut_val *schema = yyjson_mut_obj(doc);
22303+
yyjson_mut_obj_add_str(doc, schema, "type", "object");
22304+
yyjson_mut_obj_add_val(doc, schema, "properties", yyjson_mut_obj(doc));
22305+
yyjson_mut_obj_add_val(doc, tool, "inputSchema", schema);
22306+
yyjson_mut_arr_add_val(tools, tool);
22307+
yyjson_mut_obj_add_val(doc, root, "tools", tools);
22308+
char *out = yy_doc_to_str(doc);
22309+
yyjson_mut_doc_free(doc);
22310+
return out;
22311+
}
22312+
22313+
/* The answer to one request, or NULL for a notification. */
22314+
static char *mcp_refusal_handle(const char *message, const char *reason, const char *notice) {
22315+
cbm_jsonrpc_request_t req;
22316+
if (cbm_jsonrpc_parse(message, &req) != 0) {
22317+
return NULL;
22318+
}
22319+
if (!req.has_id) {
22320+
cbm_jsonrpc_request_free(&req);
22321+
return NULL;
22322+
}
22323+
char *result_json = NULL;
22324+
const char *static_result = NULL;
22325+
if (strcmp(req.method, "initialize") == 0) {
22326+
result_json = cbm_mcp_initialize_response_for_profile(req.params_raw,
22327+
CBM_MCP_TOOL_PROFILE_ALL, notice);
22328+
} else if (strcmp(req.method, "tools/list") == 0) {
22329+
result_json = mcp_refusal_tools_list(notice);
22330+
} else if (strcmp(req.method, "tools/call") == 0) {
22331+
result_json = cbm_mcp_text_result(reason, true);
22332+
} else if (strcmp(req.method, "ping") == 0) {
22333+
static_result = "{}";
22334+
} else if (strcmp(req.method, "prompts/list") == 0) {
22335+
static_result = "{\"prompts\":[]}";
22336+
}
22337+
const char *result = result_json ? result_json : static_result;
22338+
cbm_jsonrpc_response_t resp = {
22339+
.id = req.id,
22340+
.id_str = req.id_str,
22341+
.result_json = result,
22342+
.error_json = result ? NULL : MCP_REFUSAL_METHOD_NOT_FOUND,
22343+
};
22344+
char *out = cbm_jsonrpc_format_response(&resp);
22345+
safe_free(result_json);
22346+
cbm_jsonrpc_request_free(&req);
22347+
return out;
22348+
}
22349+
22350+
int cbm_mcp_refusal_run(FILE *in, FILE *out, const char *reason) {
22351+
if (!in || !out || !reason) {
22352+
return CBM_NOT_FOUND;
22353+
}
22354+
#ifdef _WIN32
22355+
_setmode(cbm_fileno(in), _O_BINARY);
22356+
_setmode(cbm_fileno(out), _O_BINARY);
22357+
#endif
22358+
size_t notice_size = sizeof(MCP_REFUSAL_PREFIX) + strlen(reason);
22359+
char *notice = cbm_alloc(CBM_MEM_CLASS_OTHER, notice_size);
22360+
if (!notice) {
22361+
return CBM_NOT_FOUND;
22362+
}
22363+
(void)snprintf(notice, notice_size, "%s%s", MCP_REFUSAL_PREFIX, reason);
22364+
22365+
char *message = NULL;
22366+
bool content_length_framed = false;
22367+
while (cbm_mcp_read_message(in, &message, &content_length_framed) > 0) {
22368+
char *resp = mcp_refusal_handle(message, reason, notice);
22369+
safe_free(message);
22370+
if (resp) {
22371+
if (content_length_framed) {
22372+
(void)fprintf(out, "Content-Length: %zu\r\n\r\n%s", strlen(resp), resp);
22373+
} else {
22374+
(void)fprintf(out, "%s\n", resp);
22375+
}
22376+
(void)fflush(out);
22377+
safe_free(resp);
22378+
}
22379+
}
22380+
safe_free(message);
22381+
cbm_free(CBM_MEM_CLASS_OTHER, notice);
22382+
return 0;
22383+
}
22384+
2227522385
/* ── cbm_parse_file_uri ──────────────────────────────────────── */
2227622386

2227722387
bool cbm_parse_file_uri(const char *uri, char *out_path, int out_size) {

‎src/mcp/mcp.h‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -249,6 +249,15 @@ int cbm_mcp_read_message(FILE *in, char **message, bool *content_length_framed);
249249
* Blocks until EOF on input. Returns 0 on success, -1 on error. */
250250
int cbm_mcp_server_run(cbm_mcp_server_t *srv, FILE *in, FILE *out);
251251

252+
/* Serve a session that was refused at startup (another CBM build owns the
253+
* runtime). Answers initialize (the reason becomes the server instructions),
254+
* tools/list (one tool, cbm_unavailable, whose description is the reason),
255+
* every tools/call (isError with the reason), ping and prompts/list; other
256+
* requests get "Method not found" and notifications are ignored. Touches no
257+
* store, cache or lock. Blocks until EOF on input. Returns 0, or -1 on bad
258+
* arguments or allocation failure. */
259+
int cbm_mcp_refusal_run(FILE *in, FILE *out, const char *reason);
260+
252261
/* Process a single JSON-RPC request line and return the response.
253262
* Returns heap-allocated JSON response string, or NULL for notifications. */
254263
char *cbm_mcp_server_handle(cbm_mcp_server_t *srv, const char *line);

‎tests/test_mcp.c‎

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21912,6 +21912,66 @@ TEST(mcp_server_run_rapid_messages) {
2191221912
}
2191321913
#endif /* !_WIN32 */
2191421914

21915+
/* A session refused at startup (another CBM build owns the runtime) must
21916+
* still answer MCP, or the client only sees an initialize timeout. */
21917+
TEST(mcp_refusal_run_answers_with_reason) {
21918+
const char *reason = "CBM could not start because a conflicting CBM process is active "
21919+
"(build; active version 0.12.1, build abc; requested version 0.13.0, "
21920+
"build def). Active daemon: pid 4242, version 0.12.1. "
21921+
"`codebase-memory-mcp daemon stop` retires the daemon.";
21922+
const char *msgs =
21923+
"{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\","
21924+
"\"params\":{\"protocolVersion\":\"2025-06-18\",\"capabilities\":{}}}\n"
21925+
"{\"jsonrpc\":\"2.0\",\"method\":\"notifications/initialized\"}\n"
21926+
"{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"tools/list\",\"params\":{}}\n"
21927+
"{\"jsonrpc\":\"2.0\",\"id\":\"s3\",\"method\":\"tools/call\","
21928+
"\"params\":{\"name\":\"index_repository\",\"arguments\":{\"repo_path\":\"/tmp\"}}}\n"
21929+
"{\"jsonrpc\":\"2.0\",\"id\":4,\"method\":\"ping\"}\n"
21930+
"{\"jsonrpc\":\"2.0\",\"id\":5,\"method\":\"resources/list\"}\n";
21931+
FILE *in_fp = tmpfile();
21932+
FILE *out_fp = tmpfile();
21933+
ASSERT_NOT_NULL(in_fp);
21934+
ASSERT_NOT_NULL(out_fp);
21935+
ASSERT_TRUE(fputs(msgs, in_fp) >= 0);
21936+
rewind(in_fp);
21937+
21938+
ASSERT_EQ(cbm_mcp_refusal_run(in_fp, out_fp, reason), 0);
21939+
21940+
rewind(out_fp);
21941+
char lines[5][4096];
21942+
for (int i = 0; i < 5; i++) {
21943+
ASSERT_NOT_NULL(fgets(lines[i], sizeof(lines[i]), out_fp));
21944+
}
21945+
char extra[16];
21946+
ASSERT_NULL(fgets(extra, sizeof(extra), out_fp)); /* the notification got no answer */
21947+
21948+
ASSERT_NOT_NULL(strstr(lines[0], "\"id\":1"));
21949+
ASSERT_NOT_NULL(strstr(lines[0], "\"serverInfo\""));
21950+
ASSERT_NOT_NULL(strstr(lines[0], "\"tools\""));
21951+
ASSERT_NOT_NULL(strstr(lines[0], "\"protocolVersion\":\"2025-06-18\""));
21952+
ASSERT_NOT_NULL(strstr(lines[0], "unavailable in this session"));
21953+
ASSERT_NOT_NULL(strstr(lines[0], "pid 4242"));
21954+
21955+
ASSERT_NOT_NULL(strstr(lines[1], "\"id\":2"));
21956+
ASSERT_NOT_NULL(strstr(lines[1], "\"name\":\"cbm_unavailable\""));
21957+
ASSERT_NULL(strstr(lines[1], "\"search_graph\""));
21958+
21959+
ASSERT_NOT_NULL(strstr(lines[2], "\"id\":\"s3\""));
21960+
ASSERT_NOT_NULL(strstr(lines[2], "\"isError\":true"));
21961+
ASSERT_NOT_NULL(strstr(lines[2], "active version 0.12.1"));
21962+
ASSERT_NOT_NULL(strstr(lines[2], "daemon stop"));
21963+
21964+
ASSERT_NOT_NULL(strstr(lines[3], "\"id\":4"));
21965+
ASSERT_NOT_NULL(strstr(lines[3], "\"result\":{}"));
21966+
21967+
ASSERT_NOT_NULL(strstr(lines[4], "\"id\":5"));
21968+
ASSERT_NOT_NULL(strstr(lines[4], "-32601"));
21969+
21970+
fclose(in_fp);
21971+
fclose(out_fp);
21972+
PASS();
21973+
}
21974+
2191521975
/* Issue #235: passing an unrecognised project name to a tool crashed the
2191621976
* binary with a buffer overflow while building the "available_projects"
2191721977
* error list — collect_db_project_names overflowed projects[CBM_SZ_4K] via
@@ -27118,6 +27178,7 @@ SUITE(mcp) {
2711827178
#ifndef _WIN32
2711927179
RUN_TEST(mcp_server_run_rapid_messages);
2712027180
#endif
27181+
RUN_TEST(mcp_refusal_run_answers_with_reason);
2712127182

2712227183
/* Snippet resolution (port of snippet_test.go) */
2712327184
RUN_TEST(snippet_exact_qn);

0 commit comments

Comments
 (0)