Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 16 additions & 1 deletion src/main/java/org/unlaxer/tinyexpression/mcp/McpServer.java
Original file line number Diff line number Diff line change
Expand Up @@ -901,14 +901,29 @@ private static String readBody(HttpExchange ex) throws IOException {
try {
long len = Long.parseLong(contentLength.trim());
if (len > MAX_REQUEST_BODY_BYTES) {
drainRequestBody(ex.getRequestBody());
throw new IOException("Request body too large: " + len + " > " + MAX_REQUEST_BODY_BYTES);
}
} catch (NumberFormatException ignored) {
// fall through to bounded read
}
}
try (InputStream is = ex.getRequestBody()) {
return new String(is.readNBytes((int) MAX_REQUEST_BODY_BYTES), StandardCharsets.UTF_8);
byte[] body = is.readNBytes((int) MAX_REQUEST_BODY_BYTES + 1);
if (body.length > MAX_REQUEST_BODY_BYTES) {
drainRequestBody(is);
throw new IOException("Request body too large: more than " + MAX_REQUEST_BODY_BYTES);
}
return new String(body, StandardCharsets.UTF_8);
}
}

private static void drainRequestBody(InputStream is) throws IOException {
try (InputStream body = is) {
byte[] buffer = new byte[8192];
while (body.read(buffer) != -1) {
// Consume the request before sending the response so the HTTP exchange can finish cleanly.
}
}
}

Expand Down
31 changes: 31 additions & 0 deletions src/test/java/org/unlaxer/tinyexpression/mcp/McpServerTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -346,6 +346,37 @@ public void oversizedBody_rejectedWith413() throws Exception {
.build();
HttpResponse<String> resp = client.send(req, HttpResponse.BodyHandlers.ofString());
assertEquals(413, resp.statusCode());
assertEquals(resp.body().getBytes(java.nio.charset.StandardCharsets.UTF_8).length,
Integer.parseInt(resp.headers().firstValue("Content-Length").orElseThrow()));
}

@Test
public void oversizedChunkedBody_rejectedWith413() throws Exception {
long max = McpServer.MAX_REQUEST_BODY_BYTES;
HttpRequest.BodyPublisher publisher = HttpRequest.BodyPublishers.fromPublisher(
subscriber -> subscriber.onSubscribe(new java.util.concurrent.Flow.Subscription() {
private boolean sent;

@Override
public void request(long n) {
if (!sent && n > 0) {
sent = true;
subscriber.onNext(java.nio.ByteBuffer.wrap(new byte[(int) max + 1]));
subscriber.onComplete();
}
}

@Override
public void cancel() {
}
}));
HttpRequest req = HttpRequest.newBuilder()
.uri(URI.create("http://127.0.0.1:" + port + "/mcp"))
.header("Content-Type", "application/json")
.POST(publisher)
.build();
HttpResponse<String> resp = client.send(req, HttpResponse.BodyHandlers.ofString());
assertEquals(413, resp.statusCode());
}

// ─── helpers ──────────────────────────────────────────────────
Expand Down
Loading