From 6fd58416e3134633539641d74755b177b0342a5a Mon Sep 17 00:00:00 2001 From: Dylan Hurd Date: Sun, 22 Nov 2026 02:09:04 +0000 Subject: [PATCH] Prevent MCP reply POSTs from resolving pending requests (#63075) ## Why Codex and an MCP server assign JSON-RPC request IDs independently. If both use the same ID, a server message returned in response to Codex's reply POST can incorrectly resolve Codex's own pending request. ## What changed In the MCP Streamable HTTP client, accept HTTP `202` and `204` as acknowledgements for outgoing JSON-RPC results and errors. After handling authentication challenges, reject other statuses for reply POSTs before decoding their bodies as JSON or server-sent events. ## Testing Add a regression test that uses the same ID for a request and a reply. It checks that the request still receives its JSON-RPC error, reply POSTs reject HTTP `409` JSON and HTTP `200` JSON or SSE, and both acknowledgement statuses are accepted. GitOrigin-RevId: 9ab1528b5c1f4af0bd281f9a6942271d7cc9812b --- .../rmcp-client/src/http_client_adapter.rs | 15 +++ .../src/http_client_adapter_tests.rs | 99 +++++++++++++++++++ 2 files changed, 114 insertions(+) diff --git a/codex-rs/rmcp-client/src/http_client_adapter.rs b/codex-rs/rmcp-client/src/http_client_adapter.rs index f350d38c7f..f32e3ab948 100644 --- a/codex-rs/rmcp-client/src/http_client_adapter.rs +++ b/codex-rs/rmcp-client/src/http_client_adapter.rs @@ -338,6 +338,21 @@ impl StreamableHttpClient for StreamableHttpClientAdapter { return Ok(StreamableHttpPostResponse::Accepted); } + // A reply answers the peer's request. A body returned to that POST + // must never resolve one of our own pending requests with the same ID. + if matches!( + message, + JsonRpcMessage::Response(_) | JsonRpcMessage::Error(_) + ) { + return Err(StreamableHttpError::UnexpectedServerResponse( + format!( + "expected acknowledgement for MCP reply, got HTTP {}", + response.status + ) + .into(), + )); + } + let content_type = response_header(&response.headers, CONTENT_TYPE); let session_id = response_header(&response.headers, HEADER_SESSION_ID); // rmcp can send a second sessionless probe after a correlated -32022. diff --git a/codex-rs/rmcp-client/src/http_client_adapter_tests.rs b/codex-rs/rmcp-client/src/http_client_adapter_tests.rs index 01b24851fb..f3e77ae27f 100644 --- a/codex-rs/rmcp-client/src/http_client_adapter_tests.rs +++ b/codex-rs/rmcp-client/src/http_client_adapter_tests.rs @@ -609,3 +609,102 @@ async fn automatic_event_stream_reconnect_refreshes_request_auth() -> anyhow::Re client.shutdown().await; Ok(()) } + +#[tokio::test] +async fn rejection_of_a_reply_cannot_answer_a_request_with_the_same_id() -> anyhow::Result<()> { + use std::sync::Arc; + + use codex_exec_server::RouteAwareHttpClient; + use codex_http_client::HttpClientFactory; + use codex_http_client::OutboundProxyPolicy; + use rmcp::model::JsonRpcMessage; + use rmcp::transport::streamable_http_client::StreamableHttpClient; + use rmcp::transport::streamable_http_client::StreamableHttpPostResponse; + use serde_json::json; + use wiremock::Mock; + use wiremock::MockServer; + use wiremock::ResponseTemplate; + use wiremock::matchers::method; + + let rejection = json!({ + "jsonrpc": "2.0", "id": 7, + "error": {"code": -32600, "message": "unknown request"}, + }); + let server = MockServer::start().await; + for (path, response) in [ + ( + "/reject", + ResponseTemplate::new(409).set_body_json(&rejection), + ), + ( + "/json", + ResponseTemplate::new(200).set_body_json(&rejection), + ), + ( + "/sse", + ResponseTemplate::new(200).set_body_raw( + format!("event: message\ndata: {rejection}\n\n"), + "text/event-stream", + ), + ), + ("/ack", ResponseTemplate::new(202)), + ("/empty", ResponseTemplate::new(204)), + ] { + Mock::given(method("POST")) + .and(wiremock::matchers::path(path)) + .respond_with(response) + .mount(&server) + .await; + } + let adapter = super::StreamableHttpClientAdapter::new( + Arc::new(RouteAwareHttpClient::new(HttpClientFactory::new( + OutboundProxyPolicy::ReqwestDefault, + ))), + HeaderMap::new(), + /*auth_provider*/ None, + /*has_configured_headers*/ false, + StreamableHttpRedirectMode::Legacy, + Default::default(), + ); + let post = |path: &str, message| { + adapter.post_message( + format!("{}{path}", server.uri()).into(), + message, + Some("same-session".into()), + /*auth_token*/ None, + Default::default(), + ) + }; + let reply: rmcp::model::ClientJsonRpcMessage = serde_json::from_value(json!({ + "jsonrpc": "2.0", "id": 7, "result": {"action": "accept"}, + }))?; + // The two peers number their requests independently. Only a POST carrying + // our request may deliver the remote error to our pending request ID 7. + let (request, rejected, json, sse) = tokio::join!( + post( + "/reject", + serde_json::from_value(json!({ + "jsonrpc": "2.0", "id": 7, "method": "ping", + }))? + ), + post("/reject", reply.clone()), + post("/json", reply.clone()), + post("/sse", reply.clone()), + ); + let StreamableHttpPostResponse::Json(error @ JsonRpcMessage::Error(_), _) = request? else { + anyhow::bail!("request lost its JSON-RPC error"); + }; + assert_eq!(serde_json::to_value(error)?, rejection); + assert_eq!( + [rejected.is_err(), json.is_err(), sse.is_err()], + [true; 3], + "409 JSON, 200 JSON, and 200 SSE must not dispatch messages for a reply" + ); + for path in ["/ack", "/empty"] { + assert!(matches!( + post(path, reply.clone()).await?, + StreamableHttpPostResponse::Accepted + )); + } + Ok(()) +}