Skip to content

Commit bee8724

Browse files
committed
fix: apply max_message_bytes to remaining HTTP responses
Apply the configured response limit to notification acknowledgements, replies to server-to-client requests, and session DELETE responses. Count incoming bytes without parsing or retaining these bodies. These discard reads do not load event_stream_parser. Report an over-limit body as RequestHandlerError, as send_request does. Check the size before DELETE status handling, and clear local session state even when close raises.
1 parent 5bd9b7a commit bee8724

3 files changed

Lines changed: 242 additions & 4 deletions

File tree

‎docs/_client/transports.md‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -131,7 +131,10 @@ See the [Progress](/server/progress/) page.
131131

132132
`MCP::Client::HTTP.new` accepts an optional `max_message_bytes:` keyword that caps the bytes buffered in memory for a single message from the server -
133133
an SSE event or a JSON response body. A message that reaches this limit before completing is rejected as a transport error, preventing unbounded memory growth from
134-
a server that never terminates an SSE event. It defaults to `4 * 1024 * 1024` (4 MiB); raise it if your server returns larger responses.
134+
a server that never terminates an SSE event. The same limit applies to the bodies the client reads and drops: the acknowledgement of a notification or of a response
135+
to a server-to-client request, and the answer to the session DELETE. These bodies are counted in full, regardless of content type, without parsing or loading
136+
`event_stream_parser`. An over-limit DELETE reply raises a transport error before its status is handled, including 404 or 405; replies with those statuses
137+
within the limit are still tolerated. It defaults to `4 * 1024 * 1024` (4 MiB); raise it if your server returns larger responses.
135138

136139
`MCP::Client::HTTP.new` also accepts `max_reconnection_wait:`, a budget in seconds for resuming a closed SSE stream. It gates every wait between reconnection attempts,
137140
and what is left of it becomes the read timeout of each resumed stream. The server chooses that wait through the SSE `retry:` field, and resuming happens on the calling thread,

‎lib/mcp/client/http.rb‎

Lines changed: 26 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -545,8 +545,12 @@ def send_request(request:)
545545
def send_notification(notification:)
546546
method = notification[:method] || notification["method"]
547547

548-
redacting_authorization_header { client.post("", notification, session_headers) }
548+
redacting_authorization_header do
549+
client.post("", notification, session_headers) { |req| req.options.on_data = bounded_on_data }
550+
end
549551
nil
552+
rescue MessageTooLargeError => e
553+
raise RequestHandlerError.new(e.message, { method: method }, error_type: :internal_error)
550554
rescue Faraday::Error => e
551555
raise RequestHandlerError.new(
552556
"Failed to send #{method} notification",
@@ -573,7 +577,11 @@ def close
573577
end
574578

575579
begin
576-
redacting_authorization_header { client.delete("", nil, session_headers) }
580+
redacting_authorization_header do
581+
client.delete("", nil, session_headers) { |req| req.options.on_data = bounded_on_data }
582+
end
583+
rescue MessageTooLargeError => e
584+
raise RequestHandlerError.new(e.message, {}, error_type: :internal_error)
577585
rescue Faraday::ClientError => e
578586
raise unless [404, 405].include?(e.response&.dig(:status))
579587
ensure
@@ -1234,7 +1242,22 @@ def dispatch_server_request(message)
12341242
end
12351243

12361244
def send_client_response(response)
1237-
redacting_authorization_header { client.post("", response, session_headers) }
1245+
redacting_authorization_header do
1246+
client.post("", response, session_headers) { |req| req.options.on_data = bounded_on_data }
1247+
end
1248+
end
1249+
1250+
# Counts discarded response bytes without parsing the body, whatever its content type.
1251+
def bounded_on_data
1252+
received_bytes = 0
1253+
1254+
proc do |chunk, _received_bytes, _env|
1255+
received_bytes += chunk.bytesize
1256+
1257+
if received_bytes > @max_message_bytes
1258+
raise MessageTooLargeError, "Server response body exceeds #{@max_message_bytes} bytes"
1259+
end
1260+
end
12381261
end
12391262

12401263
def parse_json_buffer(buffer, method, params)

‎test/mcp/client/http_test.rb‎

Lines changed: 212 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1338,6 +1338,210 @@ def test_send_request_accepts_sse_events_that_each_stay_within_max_message_bytes
13381338
assert_equal({ "tools" => [] }, response["result"])
13391339
end
13401340

1341+
def test_send_notification_rejects_response_body_exceeding_max_message_bytes
1342+
notification = {
1343+
jsonrpc: "2.0",
1344+
method: MCP::Methods::NOTIFICATIONS_CANCELLED,
1345+
params: { requestId: "req-1" },
1346+
}
1347+
client = HTTP.new(url: url, max_message_bytes: 64)
1348+
1349+
stub_request(:post, url).with(body: notification.to_json).to_return(status: 202, body: "a" * 128)
1350+
1351+
error = assert_raises(RequestHandlerError) do
1352+
client.send_notification(notification: notification)
1353+
end
1354+
1355+
assert_includes(error.message, "Server response body exceeds 64 bytes")
1356+
assert_equal(:internal_error, error.error_type)
1357+
end
1358+
1359+
def test_send_request_rejects_pong_acknowledgement_exceeding_max_message_bytes
1360+
request = {
1361+
jsonrpc: "2.0",
1362+
id: "test_id",
1363+
method: "tools/list",
1364+
}
1365+
client = HTTP.new(url: url, max_message_bytes: 128)
1366+
1367+
server_ping = { jsonrpc: "2.0", id: 7, method: "ping" }
1368+
tools_result = { jsonrpc: "2.0", id: "test_id", result: { tools: [] } }
1369+
stub_request(:post, url).with(
1370+
body: request.to_json,
1371+
).to_return(
1372+
status: 200,
1373+
headers: { "Content-Type" => "text/event-stream" },
1374+
body: "data: #{server_ping.to_json}\n\ndata: #{tools_result.to_json}\n\n",
1375+
)
1376+
1377+
pong = { jsonrpc: "2.0", id: 7, result: {} }
1378+
stub_request(:post, url).with(body: pong.to_json).to_return(status: 202, body: "a" * 256)
1379+
1380+
error = assert_raises(RequestHandlerError) do
1381+
client.send_request(request: request)
1382+
end
1383+
1384+
assert_includes(error.message, "Server response body exceeds 128 bytes")
1385+
assert_equal(:internal_error, error.error_type)
1386+
end
1387+
1388+
def test_close_rejects_response_body_exceeding_max_message_bytes_and_still_clears_state
1389+
client = HTTP.new(url: url, max_message_bytes: 64)
1390+
stub_initialize
1391+
client.send_request(request: { jsonrpc: "2.0", id: "1", method: "initialize" })
1392+
1393+
stub_request(:delete, url).to_return(status: 200, body: "a" * 128)
1394+
1395+
error = assert_raises(RequestHandlerError) do
1396+
client.close
1397+
end
1398+
1399+
assert_includes(error.message, "Server response body exceeds 64 bytes")
1400+
assert_nil(client.session_id)
1401+
end
1402+
1403+
def test_send_notification_bounds_sse_framed_response_without_parser
1404+
client = HTTP.new(url: url, max_message_bytes: 64)
1405+
notification = { jsonrpc: "2.0", method: MCP::Methods::NOTIFICATIONS_CANCELLED }
1406+
stub_event_stream_parser_unavailable
1407+
stub_request(:post, url).with(body: notification.to_json).to_return(
1408+
status: 202,
1409+
headers: { "Content-Type" => "text/event-stream" },
1410+
body: "data: {}\n\n" * 16,
1411+
)
1412+
1413+
error = assert_raises(RequestHandlerError) do
1414+
client.send_notification(notification: notification)
1415+
end
1416+
1417+
assert_includes(error.message, "Server response body exceeds 64 bytes")
1418+
assert_equal(:internal_error, error.error_type)
1419+
end
1420+
1421+
def test_pong_acknowledgement_bounds_sse_framed_response_without_parser
1422+
client = HTTP.new(url: url, max_message_bytes: 64)
1423+
server_ping = { "jsonrpc" => "2.0", "id" => 7, "method" => "ping" }
1424+
pong = { jsonrpc: "2.0", id: 7, result: {} }
1425+
stub_event_stream_parser_unavailable
1426+
stub_request(:post, url).with(body: pong.to_json).to_return(
1427+
status: 202,
1428+
headers: { "Content-Type" => "text/event-stream" },
1429+
body: "data: {}\n\n" * 16,
1430+
)
1431+
1432+
error = assert_raises(HTTP.const_get(:MessageTooLargeError)) do
1433+
client.send(:dispatch_server_request, server_ping)
1434+
end
1435+
1436+
assert_includes(error.message, "Server response body exceeds 64 bytes")
1437+
end
1438+
1439+
def test_close_bounds_sse_framed_response_without_parser
1440+
client = HTTP.new(url: url, max_message_bytes: 64)
1441+
stub_initialize
1442+
client.send_request(request: { jsonrpc: "2.0", id: "1", method: "initialize" })
1443+
stub_event_stream_parser_unavailable
1444+
stub_request(:delete, url).to_return(
1445+
status: 200,
1446+
headers: { "Content-Type" => "text/event-stream" },
1447+
body: "data: {}\n\n" * 16,
1448+
)
1449+
1450+
error = assert_raises(RequestHandlerError) do
1451+
client.close
1452+
end
1453+
1454+
assert_includes(error.message, "Server response body exceeds 64 bytes")
1455+
assert_nil(client.session_id)
1456+
assert_nil(client.protocol_version)
1457+
end
1458+
1459+
def test_discarded_responses_within_limit_do_not_load_parser
1460+
client = HTTP.new(url: url, max_message_bytes: 64)
1461+
stub_initialize
1462+
client.send_request(request: { jsonrpc: "2.0", id: "1", method: "initialize" })
1463+
stub_event_stream_parser_unavailable
1464+
stub_request(:post, url).to_return(
1465+
status: 202,
1466+
headers: { "Content-Type" => "text/event-stream" },
1467+
body: "data: {}\n\n" * 4,
1468+
)
1469+
stub_request(:delete, url).to_return(
1470+
status: 200,
1471+
headers: { "Content-Type" => "text/event-stream" },
1472+
body: "data: {}\n\n" * 4,
1473+
)
1474+
1475+
notification = { jsonrpc: "2.0", method: MCP::Methods::NOTIFICATIONS_CANCELLED }
1476+
assert_nil(client.send_notification(notification: notification))
1477+
client.send(:dispatch_server_request, { "jsonrpc" => "2.0", "id" => 7, "method" => "ping" })
1478+
client.close
1479+
1480+
assert_requested(:post, url, times: 3)
1481+
assert_nil(client.session_id)
1482+
assert_nil(client.protocol_version)
1483+
end
1484+
1485+
def test_discarded_response_reader_counts_bytes_across_chunks
1486+
client = HTTP.new(url: url, max_message_bytes: 64)
1487+
reader = client.send(:bounded_on_data)
1488+
reader.call("é" * 16, 0)
1489+
reader.call("é" * 16, 0)
1490+
1491+
error = assert_raises(HTTP.const_get(:MessageTooLargeError)) do
1492+
reader.call("a", 0)
1493+
end
1494+
1495+
assert_includes(error.message, "Server response body exceeds 64 bytes")
1496+
client.send(:bounded_on_data).call("a" * 64, 0)
1497+
end
1498+
1499+
def test_discarded_response_reader_bounds_the_whole_sse_framed_body
1500+
client = HTTP.new(url: url, max_message_bytes: 64)
1501+
reader = client.send(:bounded_on_data)
1502+
env = stub(response_headers: { "content-type" => "text/event-stream" })
1503+
chunk = "data: {}\n\n" * 4
1504+
reader.call(chunk, chunk.bytesize, env)
1505+
1506+
error = assert_raises(HTTP.const_get(:MessageTooLargeError)) do
1507+
reader.call(chunk, chunk.bytesize * 2, env)
1508+
end
1509+
1510+
assert_includes(error.message, "Server response body exceeds 64 bytes")
1511+
end
1512+
1513+
def test_close_applies_response_size_limit_before_status_errors
1514+
[404, 405, 500].each do |status|
1515+
client = HTTP.new(url: url, max_message_bytes: 64)
1516+
stub_initialize
1517+
client.send_request(request: { jsonrpc: "2.0", id: "1", method: "initialize" })
1518+
stub_request(:delete, url).to_return(status: status, body: "a" * 128)
1519+
1520+
error = assert_raises(RequestHandlerError) do
1521+
client.close
1522+
end
1523+
1524+
assert_includes(error.message, "Server response body exceeds 64 bytes")
1525+
assert_equal(:internal_error, error.error_type)
1526+
assert_nil(client.session_id)
1527+
assert_nil(client.protocol_version)
1528+
end
1529+
end
1530+
1531+
def test_close_tolerates_404_and_405_response_bodies_within_max_message_bytes
1532+
[404, 405].each do |status|
1533+
client = HTTP.new(url: url, max_message_bytes: 64)
1534+
stub_initialize
1535+
client.send_request(request: { jsonrpc: "2.0", id: "1", method: "initialize" })
1536+
stub_request(:delete, url).to_return(status: status, body: "a" * 64)
1537+
1538+
client.close
1539+
1540+
assert_nil(client.session_id)
1541+
assert_nil(client.protocol_version)
1542+
end
1543+
end
1544+
13411545
def test_sse_stream_rejects_unterminated_event_exceeding_max_message_bytes
13421546
stream = HTTP.const_get(:SSEStream).new(abortable: false, max_message_bytes: 64)
13431547
env = stub(response_headers: { "content-type" => "text/event-stream" })
@@ -3222,6 +3426,14 @@ def stub_notification
32223426
.to_return(status: 202, body: "")
32233427
end
32243428

3429+
def stub_event_stream_parser_unavailable
3430+
HTTP.any_instance.stubs(:require).with("faraday").returns(true)
3431+
HTTP.any_instance.stubs(:require).with("event_stream_parser").raises(LoadError, "cannot load event_stream_parser")
3432+
HTTP.const_get(:SSEStream).any_instance.stubs(:require).with("event_stream_parser")
3433+
.raises(LoadError, "cannot load event_stream_parser")
3434+
EventStreamParser::Parser.expects(:new).never
3435+
end
3436+
32253437
def stub_discover
32263438
stub_request(:post, url).with do |req|
32273439
JSON.parse(req.body)["method"] == "server/discover"

0 commit comments

Comments
 (0)