Skip to content

Commit 4765528

Browse files
committed
use event_stream_parser
1 parent 09637b6 commit 4765528

File tree

4 files changed

+10
-13
lines changed

4 files changed

+10
-13
lines changed

Gemfile

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ gem "rubocop-minitest", require: false
1010
gem "rubocop-rake", require: false
1111
gem "rubocop-shopify", ">= 2.18", require: false if RUBY_VERSION >= "3.1"
1212

13+
gem "event_stream_parser", ">= 1.0"
1314
gem "puma", ">= 5.0.0"
1415
gem "rackup", ">= 2.1.0"
1516

examples/streamable_http_client.rb

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
require "uri"
99
require "json"
1010
require "logger"
11+
require "event_stream_parser"
1112

1213
SERVER_URL = "http://localhost:9393"
1314

@@ -37,13 +38,13 @@ def connect_sse(session_id, logger)
3738
if response.code == "200"
3839
logger.info("SSE stream connected successfully")
3940

41+
parser = EventStreamParser::Parser.new
4042
response.read_body do |chunk|
41-
chunk.split("\n").each do |line|
42-
if line.start_with?("data: ")
43-
data = line[6..]
43+
parser.feed(chunk) do |type, data, _id|
44+
if type.empty?
4445
logger.info("SSE event: #{data}")
45-
elsif line.start_with?(": ")
46-
logger.debug("SSE keepalive: #{line}")
46+
else
47+
logger.info("SSE event (#{type}): #{data}")
4748
end
4849
end
4950
end

lib/mcp/client/http.rb

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -145,14 +145,8 @@ def parse_response_body(response, method, params)
145145

146146
def parse_sse_response(body, method, params)
147147
json_rpc_response = nil
148-
149-
body.to_s.each_line do |line|
150-
line = line.strip
151-
next if line.empty?
152-
next if line.start_with?(":")
153-
next unless line.start_with?("data:")
154-
155-
data = line.sub(/^data:\s*/, "")
148+
parser = EventStreamParser::Parser.new
149+
parser.feed(body.to_s) do |_type, data, _id|
156150
next if data.empty?
157151

158152
begin

test/mcp/client/http_test.rb

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
# frozen_string_literal: true
22

33
require "test_helper"
4+
require "event_stream_parser"
45
require "faraday"
56
require "webmock/minitest"
67
require "mcp/client/http"

0 commit comments

Comments
 (0)