Skip to content

Commit 99b57a3

Browse files
authored
Merge pull request #114 from dak2/handle-202
Fix to return a response code 202 if the server accepts JSON-RPC notifications and responses
2 parents 8f682c4 + cd7a54a commit 99b57a3

File tree

2 files changed

+37
-3
lines changed

2 files changed

+37
-3
lines changed

lib/mcp/server/transports/streamable_http_transport.rb

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -108,8 +108,8 @@ def handle_post(request)
108108

109109
if body["method"] == "initialize"
110110
handle_initialization(body_string, body)
111-
elsif body["method"] == MCP::Methods::NOTIFICATIONS_INITIALIZED
112-
handle_notification_initialized
111+
elsif notification?(body) || response?(body)
112+
handle_accepted
113113
else
114114
handle_regular_request(body_string, session_id)
115115
end
@@ -168,6 +168,14 @@ def parse_request_body(body_string)
168168
[400, { "Content-Type" => "application/json" }, [{ error: "Invalid JSON" }.to_json]]
169169
end
170170

171+
def notification?(body)
172+
!body["id"] && !!body["method"]
173+
end
174+
175+
def response?(body)
176+
!!body["id"] && !body["method"]
177+
end
178+
171179
def handle_initialization(body_string, body)
172180
session_id = SecureRandom.uuid
173181

@@ -187,7 +195,7 @@ def handle_initialization(body_string, body)
187195
[200, headers, [response]]
188196
end
189197

190-
def handle_notification_initialized
198+
def handle_accepted
191199
[202, {}, []]
192200
end
193201

test/mcp/server/transports/streamable_http_transport_test.rb

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -620,6 +620,32 @@ class StreamableHTTPTransportTest < ActiveSupport::TestCase
620620
assert_empty(response[2])
621621
end
622622

623+
test "handles POST request with body including JSON-RPC response object and returns with no body" do
624+
init_request = create_rack_request(
625+
"POST",
626+
"/",
627+
{ "CONTENT_TYPE" => "application/json" },
628+
{ jsonrpc: "2.0", method: "initialize", id: "init" }.to_json,
629+
)
630+
init_response = @transport.handle_request(init_request)
631+
session_id = init_response[1]["Mcp-Session-Id"]
632+
633+
request = create_rack_request(
634+
"POST",
635+
"/",
636+
{
637+
"CONTENT_TYPE" => "application/json",
638+
"HTTP_MCP_SESSION_ID" => session_id,
639+
},
640+
{ jsonrpc: "2.0", result: "success", id: "123" }.to_json,
641+
)
642+
643+
response = @transport.handle_request(request)
644+
assert_equal 202, response[0]
645+
assert_empty(response[1])
646+
assert_empty(response[2])
647+
end
648+
623649
private
624650

625651
def create_rack_request(method, path, headers, body = nil)

0 commit comments

Comments
 (0)