forked from modelcontextprotocol/ruby-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstreamable_http_client.rb
More file actions
207 lines (174 loc) · 4.96 KB
/
streamable_http_client.rb
File metadata and controls
207 lines (174 loc) · 4.96 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
# frozen_string_literal: true
require "net/http"
require "uri"
require "json"
require "logger"
# Logger for client operations
logger = Logger.new($stdout)
logger.formatter = proc do |severity, datetime, _progname, msg|
"[CLIENT] #{severity} #{datetime.strftime("%H:%M:%S.%L")} - #{msg}\n"
end
# Server configuration
SERVER_URL = "http://localhost:9393/mcp"
PROTOCOL_VERSION = "2024-11-05"
# Helper method to make JSON-RPC requests
def make_request(session_id, method, params = {}, id = nil)
uri = URI(SERVER_URL)
http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Post.new(uri)
request["Content-Type"] = "application/json"
request["Mcp-Session-Id"] = session_id if session_id
body = {
jsonrpc: "2.0",
method: method,
params: params,
id: id || SecureRandom.uuid,
}
request.body = body.to_json
response = http.request(request)
{
status: response.code,
headers: response.to_hash,
body: JSON.parse(response.body),
}
rescue => e
{ error: e.message }
end
# Connect to SSE stream
def connect_sse(session_id, logger)
uri = URI(SERVER_URL)
logger.info("Connecting to SSE stream...")
Net::HTTP.start(uri.host, uri.port) do |http|
request = Net::HTTP::Get.new(uri)
request["Mcp-Session-Id"] = session_id
request["Accept"] = "text/event-stream"
request["Cache-Control"] = "no-cache"
http.request(request) do |response|
if response.code == "200"
logger.info("SSE stream connected successfully")
response.read_body do |chunk|
chunk.split("\n").each do |line|
if line.start_with?("data: ")
data = line[6..-1]
begin
logger.info("SSE data: #{data}")
rescue JSON::ParserError
logger.debug("Non-JSON SSE data: #{data}")
end
elsif line.start_with?(": ")
logger.debug("SSE keepalive received: #{line}")
end
end
end
else
logger.error("Failed to connect to SSE: #{response.code} #{response.message}")
end
end
end
rescue Interrupt
logger.info("SSE connection interrupted by user")
rescue => e
logger.error("SSE connection error: #{e.message}")
end
# Main client flow
def main
logger = Logger.new($stdout)
logger.formatter = proc do |severity, datetime, _progname, msg|
"[CLIENT] #{severity} #{datetime.strftime("%H:%M:%S.%L")} - #{msg}\n"
end
puts "=== MCP SSE Test Client ==="
# Step 1: Initialize session
logger.info("Initializing session...")
init_response = make_request(
nil,
"initialize",
{
protocolVersion: PROTOCOL_VERSION,
capabilities: {},
clientInfo: {
name: "sse-test-client",
version: "1.0",
},
},
"init-1",
)
if init_response[:error]
logger.error("Failed to initialize: #{init_response[:error]}")
exit(1)
end
session_id = init_response[:headers]["mcp-session-id"]&.first
if session_id.nil?
logger.error("No session ID received")
exit(1)
end
if init_response[:body].dig("result", "capabilities", "logging")
make_request(session_id, "logging/setLevel", { level: "info" })
end
logger.info("Session initialized: #{session_id}")
logger.info("Server info: #{init_response[:body]["result"]["serverInfo"]}")
# Step 2: Start SSE connection in a separate thread
sse_thread = Thread.new { connect_sse(session_id, logger) }
# Give SSE time to connect
sleep(1)
# Step 3: Interactive menu
loop do
puts <<~MESSAGE.chomp
=== Available Actions ===
1. Send custom notification
2. Test echo
3. List tools
0. Exit
Choose an action:#{" "}
MESSAGE
choice = gets.chomp
case choice
when "1"
print("Enter notification message: ")
message = gets.chomp
print("Enter delay in seconds (0 for immediate): ")
delay = gets.chomp.to_f
response = make_request(
session_id,
"tools/call",
{
name: "notification_tool",
arguments: {
message: message,
delay: delay,
},
},
)
if response[:body]["accepted"]
logger.info("Notification sent successfully")
else
logger.error("Error: #{response[:body]["error"]}")
end
when "2"
print("Enter message to echo: ")
message = gets.chomp
make_request(session_id, "tools/call", { name: "echo", arguments: { message: message } })
when "3"
make_request(session_id, "tools/list")
when "0"
logger.info("Exiting...")
break
else
puts "Invalid choice"
end
end
# Clean up
sse_thread.kill if sse_thread.alive?
# Close session
logger.info("Closing session...")
make_request(session_id, "close")
logger.info("Session closed")
rescue Interrupt
logger.info("Client interrupted by user")
rescue => e
logger.error("Client error: #{e.message}")
logger.error(e.backtrace.join("\n"))
end
# Run the client
if __FILE__ == $PROGRAM_NAME
main
end