diff --git a/src/mcp/mcp.c b/src/mcp/mcp.c index 2d056313..ea6cff0b 100644 --- a/src/mcp/mcp.c +++ b/src/mcp/mcp.c @@ -79,6 +79,7 @@ enum { #endif #include #include // int64_t +#include // INT_MIN, INT_MAX #include #include #include @@ -1032,7 +1033,13 @@ int cbm_mcp_get_int_arg(const char *args_json, const char *key, int default_val) yyjson_val *val = yyjson_obj_get(root, key); int result = default_val; if (val && yyjson_is_int(val)) { - result = yyjson_get_int(val); + /* Read the JSON integer as 64-bit and fall back to the default when it + * does not fit an int. Casting first wraps silently: limit 4294967297 + * became 1, and 2147483648 became negative. */ + int64_t wide = yyjson_get_sint(val); + if (wide >= (int64_t)INT_MIN && wide <= (int64_t)INT_MAX) { + result = (int)wide; + } } yyjson_doc_free(doc); return result; diff --git a/tests/test_mcp.c b/tests/test_mcp.c index 30427547..56ea2357 100644 --- a/tests/test_mcp.c +++ b/tests/test_mcp.c @@ -5679,6 +5679,23 @@ TEST(mcp_get_int_arg_bool_value) { PASS(); } +TEST(mcp_get_int_arg_out_of_range) { + /* A JSON integer wider than int must fall back to the default instead of + * wrapping: 4294967297 used to become 1 and 2147483648 became negative. */ + int val = cbm_mcp_get_int_arg("{\"limit\":4294967297}", "limit", 7); + ASSERT_EQ(val, 7); + val = cbm_mcp_get_int_arg("{\"limit\":2147483648}", "limit", 7); + ASSERT_EQ(val, 7); + val = cbm_mcp_get_int_arg("{\"limit\":-2147483649}", "limit", 7); + ASSERT_EQ(val, 7); + /* In-range boundaries are still accepted. */ + val = cbm_mcp_get_int_arg("{\"limit\":2147483647}", "limit", 7); + ASSERT_EQ(val, 2147483647); + val = cbm_mcp_get_int_arg("{\"limit\":-2147483648}", "limit", 7); + ASSERT_EQ(val, -2147483648); + PASS(); +} + TEST(mcp_get_bool_arg_empty_json) { bool val = cbm_mcp_get_bool_arg("", "key"); ASSERT_FALSE(val); @@ -7130,6 +7147,7 @@ SUITE(mcp) { RUN_TEST(mcp_get_int_arg_empty_json); RUN_TEST(mcp_get_int_arg_string_value); RUN_TEST(mcp_get_int_arg_bool_value); + RUN_TEST(mcp_get_int_arg_out_of_range); RUN_TEST(mcp_get_bool_arg_empty_json); RUN_TEST(mcp_get_bool_arg_int_value); RUN_TEST(mcp_get_tool_name_empty_json);