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
51 changes: 35 additions & 16 deletions crates/rmcp/src/transport/streamable_http_server/tower.rs
Original file line number Diff line number Diff line change
Expand Up @@ -643,17 +643,21 @@ fn validate_required_protocol_meta(
.into())
}

fn jsonrpc_http_status(message: &ServerJsonRpcMessage) -> http::StatusCode {
/// `request_meta_malformed` marks a request missing required `_meta` fields;
/// only then is `-32602` a malformed-request 400 rather than an in-band error.
fn jsonrpc_http_status(
message: &ServerJsonRpcMessage,
request_meta_malformed: bool,
) -> http::StatusCode {
let ServerJsonRpcMessage::Error(error) = message else {
return http::StatusCode::OK;
};
// Modern per-request HTTP treats invalid params as a malformed request.
// Legacy requests bypass this mapper and retain HTTP 200 JSON-RPC errors.
match error.error.code {
ErrorCode::UNSUPPORTED_PROTOCOL_VERSION
| ErrorCode::MISSING_REQUIRED_CLIENT_CAPABILITY
| ErrorCode::INVALID_PARAMS
| ErrorCode::HEADER_MISMATCH => http::StatusCode::BAD_REQUEST,
ErrorCode::INVALID_PARAMS if request_meta_malformed => http::StatusCode::BAD_REQUEST,
ErrorCode::METHOD_NOT_FOUND => http::StatusCode::NOT_FOUND,
_ => http::StatusCode::OK,
}
Expand All @@ -676,23 +680,39 @@ mod jsonrpc_http_status_tests {
#[test]
fn header_mismatch_maps_to_bad_request() {
assert_eq!(
jsonrpc_http_status(&error_message(ErrorCode::HEADER_MISMATCH)),
jsonrpc_http_status(&error_message(ErrorCode::HEADER_MISMATCH), false),
http::StatusCode::BAD_REQUEST
);
}

#[test]
fn method_not_found_maps_to_not_found() {
assert_eq!(
jsonrpc_http_status(&error_message(ErrorCode::METHOD_NOT_FOUND)),
jsonrpc_http_status(&error_message(ErrorCode::METHOD_NOT_FOUND), false),
http::StatusCode::NOT_FOUND
);
}

#[test]
fn invalid_params_for_malformed_request_meta_maps_to_bad_request() {
assert_eq!(
jsonrpc_http_status(&error_message(ErrorCode::INVALID_PARAMS), true),
http::StatusCode::BAD_REQUEST
);
}

#[test]
fn invalid_params_for_well_formed_request_meta_maps_to_ok() {
assert_eq!(
jsonrpc_http_status(&error_message(ErrorCode::INVALID_PARAMS), false),
http::StatusCode::OK
);
}

#[test]
fn unmapped_error_defaults_to_ok() {
assert_eq!(
jsonrpc_http_status(&error_message(ErrorCode::INTERNAL_ERROR)),
jsonrpc_http_status(&error_message(ErrorCode::INTERNAL_ERROR), false),
http::StatusCode::OK
);
}
Expand Down Expand Up @@ -793,13 +813,8 @@ mod standard_header_init_tests {

fn jsonrpc_message_response(
message: ServerJsonRpcMessage,
map_protocol_status: bool,
status: http::StatusCode,
) -> HttpResult<BoxResponse> {
let status = if map_protocol_status {
jsonrpc_http_status(&message)
} else {
http::StatusCode::OK
};
let body =
serde_json::to_vec(&message).map_err(internal_error_response("serialize json response"))?;
Ok(Response::builder()
Expand Down Expand Up @@ -1520,6 +1535,11 @@ where
mut request: crate::model::JsonRpcRequest<ClientRequest>,
parts: http::request::Parts,
) -> HttpResult<BoxResponse> {
let request_meta_malformed = !request
.request
.get_meta()
.missing_required_keys(&ProtocolVersion::V_2026_07_28)
.is_empty();
let peer_info = Self::peer_info_for_stateless_request(&request, &parts.headers);
request.request.extensions_mut().insert(parts);
let (transport, mut receiver) =
Expand Down Expand Up @@ -1564,17 +1584,16 @@ where
&first,
ServerJsonRpcMessage::Response(_) | ServerJsonRpcMessage::Error(_)
);
if terminal
&& (self.config.json_response || jsonrpc_http_status(&first) != http::StatusCode::OK)
{
let status = jsonrpc_http_status(&first, request_meta_malformed);
if terminal && (self.config.json_response || status != http::StatusCode::OK) {
// This message is the whole reply, so `receiver` is dropped here and
// anything the handler emits afterwards is undeliverable. Cancel it so
// a still-running handler stops instead of running on unobserved: its
// terminal `send` would otherwise fail before adding the termination
// permit, leaving the serve loop parked forever. A no-op when the
// handler already completed.
request_ct.cancel();
return jsonrpc_message_response(first, true);
return jsonrpc_message_response(first, status);
}

Ok(self.stateless_sse_response(Some(first), receiver, request_ct))
Expand Down
55 changes: 53 additions & 2 deletions crates/rmcp/tests/test_streamable_http_protocol_version.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,10 +32,18 @@ async fn spawn_server(
async fn spawn_server_with_manager(
config: StreamableHttpServerConfig,
session_manager: Arc<LocalSessionManager>,
) -> (reqwest::Client, String, CancellationToken) {
spawn_handler(Calculator::new(), config, session_manager).await
}

async fn spawn_handler<S: ServerHandler + Clone>(
handler: S,
config: StreamableHttpServerConfig,
session_manager: Arc<LocalSessionManager>,
) -> (reqwest::Client, String, CancellationToken) {
let ct = config.cancellation_token.clone();
let service: StreamableHttpService<Calculator, LocalSessionManager> =
StreamableHttpService::new(|| Ok(Calculator::new()), session_manager, config);
let service: StreamableHttpService<S, LocalSessionManager> =
StreamableHttpService::new(move || Ok(handler.clone()), session_manager, config);

let router = axum::Router::new().nest_service("/mcp", service);
let tcp_listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
Expand Down Expand Up @@ -450,6 +458,49 @@ async fn stateless_request_accepts_missing_optional_meta_client_info() {
ct.cancel();
}

#[derive(Clone)]
struct MissingResourceServer;

impl ServerHandler for MissingResourceServer {
async fn read_resource(
&self,
request: rmcp::model::ReadResourceRequestParams,
_context: rmcp::service::RequestContext<rmcp::RoleServer>,
) -> Result<rmcp::model::ReadResourceResponse, rmcp::ErrorData> {
Err(rmcp::ErrorData::resource_not_found(request.uri, None))
}
}

#[tokio::test]
async fn stateless_handler_invalid_params_stays_in_band() {
let (client, url, ct) = spawn_handler(
MissingResourceServer,
stateless_json_config(),
Arc::new(LocalSessionManager::default()),
)
.await;

let response = post_modern_request(
&client,
&url,
"resources/read",
Some("ui://widget/nope"),
json!({
"uri": "ui://widget/nope",
"_meta": {
"io.modelcontextprotocol/protocolVersion": "2026-07-28",
"io.modelcontextprotocol/clientCapabilities": {}
}
}),
)
.await;

assert_eq!(response.status(), 200);
let body: Value = response.json().await.expect("response should be JSON");
assert_eq!(body["error"]["code"], -32602);
ct.cancel();
}

// ---------------------------------------------------------------------------
// Opt-in seam: `with_stateless_protocol_metadata_required(true)`
// ---------------------------------------------------------------------------
Expand Down
Loading