Skip to content

Commit a807d26

Browse files
committed
perf: Stream request body in chunks with size validation
1 parent 429f8df commit a807d26

File tree

1 file changed

+15
-9
lines changed

1 file changed

+15
-9
lines changed

src/mcp/server/streamable_http.py

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -332,15 +332,21 @@ async def _handle_post_request(self, scope: Scope, request: Request, receive: Re
332332
await response(scope, receive, send)
333333
return
334334

335-
# Parse the body - only read it once
336-
body = await request.body()
337-
if len(body) > self._maximum_message_size:
338-
response = self._create_error_response(
339-
"Payload Too Large: Message exceeds maximum size",
340-
HTTPStatus.REQUEST_ENTITY_TOO_LARGE,
341-
)
342-
await response(scope, receive, send)
343-
return
335+
# Parse the body by streaming and joining chunks
336+
chunks: list[bytes] = []
337+
total_message_size = 0
338+
async for chunk in request.stream():
339+
total_message_size += len(chunk)
340+
# Validate that body is smaller than maximum allowed message size
341+
if total_message_size > self._maximum_message_size:
342+
response = self._create_error_response(
343+
"Payload Too Large: Message exceeds maximum size",
344+
HTTPStatus.REQUEST_ENTITY_TOO_LARGE,
345+
)
346+
await response(scope, receive, send)
347+
return
348+
chunks.append(chunk)
349+
body = b"".join(chunks)
344350

345351
try:
346352
raw_message = json.loads(body)

0 commit comments

Comments
 (0)