Skip to content

Commit 64f5e91

Browse files
authored
Merge pull request #2256 from DeusData/distill/1245-int-arg-range
fix(mcp): an integer argument outside int range takes the default
2 parents 2803d6a + 65aad0f commit 64f5e91

2 files changed

Lines changed: 30 additions & 2 deletions

File tree

‎src/mcp/mcp.c‎

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1688,8 +1688,19 @@ int cbm_mcp_get_int_arg(const char *args_json, const char *key, int default_val)
16881688
yyjson_val *root = yyjson_doc_get_root(doc);
16891689
yyjson_val *val = yyjson_obj_get(root, key);
16901690
int result = default_val;
1691-
if (val && yyjson_is_int(val)) {
1692-
result = yyjson_get_int(val);
1691+
/* yyjson_get_int truncates 64-bit integers to int (2^32 + 1 became 1);
1692+
* read the full width and treat anything outside int range like a
1693+
* non-integer, i.e. fall back to the caller's default. */
1694+
if (val && yyjson_is_sint(val)) {
1695+
int64_t parsed = yyjson_get_sint(val);
1696+
if (parsed >= INT_MIN && parsed <= INT_MAX) {
1697+
result = (int)parsed;
1698+
}
1699+
} else if (val && yyjson_is_uint(val)) {
1700+
uint64_t parsed = yyjson_get_uint(val);
1701+
if (parsed <= (uint64_t)INT_MAX) {
1702+
result = (int)parsed;
1703+
}
16931704
}
16941705
yyjson_doc_free(doc);
16951706
return result;

‎tests/test_mcp.c‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1859,6 +1859,23 @@ TEST(mcp_get_int_arg) {
18591859
ASSERT_EQ(val, 5);
18601860
val = cbm_mcp_get_int_arg(args, "missing", 42);
18611861
ASSERT_EQ(val, 42);
1862+
/* Out-of-int-range integers return the default instead of truncating:
1863+
* 2^32 + 1 used to read back as 1 through yyjson_get_int's int cast. */
1864+
val = cbm_mcp_get_int_arg("{\"limit\":4294967297}", "limit", 17);
1865+
ASSERT_EQ(val, 17);
1866+
val = cbm_mcp_get_int_arg("{\"limit\":-4294967297}", "limit", 19);
1867+
ASSERT_EQ(val, 19);
1868+
val = cbm_mcp_get_int_arg("{\"limit\":2147483648}", "limit", 23);
1869+
ASSERT_EQ(val, 23);
1870+
val = cbm_mcp_get_int_arg("{\"limit\":-9223372036854775808}", "limit", 29);
1871+
ASSERT_EQ(val, 29);
1872+
/* Boundary values and a negative in-range value still pass through. */
1873+
val = cbm_mcp_get_int_arg("{\"limit\":2147483647}", "limit", 0);
1874+
ASSERT_EQ(val, 2147483647);
1875+
val = cbm_mcp_get_int_arg("{\"limit\":-2147483648}", "limit", 0);
1876+
ASSERT_EQ(val, -2147483648);
1877+
val = cbm_mcp_get_int_arg("{\"limit\":-7}", "limit", 0);
1878+
ASSERT_EQ(val, -7);
18621879
PASS();
18631880
}
18641881

0 commit comments

Comments
 (0)