@@ -442,17 +442,22 @@ def read_response(request)
442442 # other server-to-client requests over stdio stay unsupported as documented,
443443 # and notifications carry no id.
444444 if parsed . is_a? ( Hash ) && parsed . key? ( "method" )
445- # A JSON-RPC id is a String or a Number; the reference SDKs reject other shapes at
446- # schema validation, so a ping carrying one is skipped rather than echoed back.
447- answer_ping ( parsed ) if parsed [ "method" ] == MCP :: Methods :: PING && json_rpc_id ?( parsed [ "id" ] )
445+ # A JSON-RPC id is a String or a Number, and `jsonrpc` is "2.0" ; the reference SDKs reject
446+ # other shapes at schema validation, so a ping carrying one is skipped rather than echoed back.
447+ answer_ping ( parsed ) if answerable_ping ?( parsed )
448448 next
449449 end
450450
451451 # A JSON-RPC message is an object; skip a non-object frame (array or scalar)
452452 # the same way as a frame without an id.
453453 next unless parsed . is_a? ( Hash ) && parsed . key? ( "id" )
454+ next unless parsed [ "id" ] == request_id
454455
455- return parsed if parsed [ "id" ] == request_id
456+ # Nothing else will answer the awaited request, so a response that is not JSON-RPC 2.0 fails it
457+ # instead of being skipped: without a `read_timeout`, skipping would wait forever.
458+ raise_invalid_response! ( method , params ) unless JsonRpcHandler . valid_version? ( parsed [ "jsonrpc" ] )
459+
460+ return parsed
456461 end
457462 rescue JSON ::ParserError => e
458463 raise RequestHandlerError . new (
@@ -475,6 +480,10 @@ def answer_ping(parsed)
475480 # surface as an error of the unrelated request whose response the loop is reading.
476481 end
477482
483+ def answerable_ping? ( parsed )
484+ parsed [ "method" ] == MCP ::Methods ::PING && json_rpc_id? ( parsed [ "id" ] ) && JsonRpcHandler . valid_version? ( parsed [ "jsonrpc" ] )
485+ end
486+
478487 def json_rpc_id? ( id )
479488 id . is_a? ( String ) || id . is_a? ( Numeric )
480489 end
@@ -532,6 +541,16 @@ def raise_connection_error!(method, params)
532541 error_type : :internal_error ,
533542 )
534543 end
544+
545+ # The line framing is intact, so the transport stays usable; the received value is left out of
546+ # the message because it can be any JSON value.
547+ def raise_invalid_response! ( method , params )
548+ raise RequestHandlerError . new (
549+ 'Server response is not a valid JSON-RPC 2.0 message: "jsonrpc" must be "2.0"' ,
550+ { method : method , params : params } ,
551+ error_type : :internal_error ,
552+ )
553+ end
535554 end
536555 end
537556end
0 commit comments