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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
use super::CancellationToken;
use crate::error::{TransportError, TransportResult};
use crate::utils::SseParser;
use crate::utils::{http_get, validate_response_type, ResponseType};
use crate::{utils::http_post, MCP_SESSION_ID_HEADER};
use crate::{EventId, MCP_LAST_EVENT_ID_HEADER};
use bytes::Bytes;
use reqwest::header::{HeaderMap, HeaderValue};
use reqwest::{Client, Response, StatusCode};
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::{mpsc, RwLock};
use tokio::time;
use tokio_stream::StreamExt;
//-----------------------------------------------------------------------------------//
pub(crate) struct StreamableHttpStream {
/// HTTP client for making SSE requests
pub client: Client,
/// URL of the SSE endpoint
pub mcp_url: String,
/// Maximum number of retry attempts for failed connections
pub max_retries: usize,
/// Delay between retry attempts (overridden by SSE `retry:` field when present)
pub retry_delay: Duration,
/// Sender for transmitting received data to the readable channel
pub read_tx: mpsc::Sender<Bytes>,
/// Session id will be received from the server in the http
pub session_id: Arc<RwLock<Option<String>>>,
}
impl StreamableHttpStream {
pub(crate) async fn run(
&mut self,
payload: String,
cancellation_token: &CancellationToken,
custom_headers: &Option<HeaderMap>,
) -> TransportResult<()> {
let mut stream_parser = SseParser::new();
let mut _last_event_id: Option<EventId> = None;
let session_id = self.session_id.read().await.clone();
// Check for cancellation before attempting connection
if cancellation_token.is_cancelled() {
tracing::info!(
"StreamableHttp cancelled before connection attempt {}",
payload
);
return Err(TransportError::Cancelled(
crate::utils::CancellationError::ChannelClosed,
));
}
let response = match http_post(
&self.client,
&self.mcp_url,
payload.to_string(),
session_id.as_ref(),
custom_headers.as_ref(),
)
.await
{
Ok(response) => {
// if session_id_clone.read().await.is_none() {
let session_id = response
.headers()
.get(MCP_SESSION_ID_HEADER)
.and_then(|value| value.to_str().ok())
.map(|s| s.to_string());
let mut guard = self.session_id.write().await;
*guard = session_id;
response
}
Err(error) => {
tracing::error!("Failed to connect to MCP endpoint: {error}");
return Err(error);
}
};
// return if status code != 200 and no result is expected
if response.status() != StatusCode::OK {
return Ok(());
}
let response_type = validate_response_type(&response).await?;
// Handle non-streaming JSON response
if response_type == ResponseType::Json {
return match response.bytes().await {
Ok(bytes) => {
// Send the message
self.read_tx.send(bytes).await.map_err(|_| {
tracing::error!("Readable stream closed, shutting down MCP task");
TransportError::SendFailure(
"Failed to send message: channel closed or full".to_string(),
)
})?;
// Send the newline
self.read_tx
.send(Bytes::from_static(b"\n"))
.await
.map_err(|_| {
tracing::error!(
"Failed to send newline, channel may be closed or full"
);
TransportError::SendFailure(
"Failed to send newline: channel closed or full".to_string(),
)
})?;
Ok(())
}
Err(error) => Err(error.into()),
};
}
// Create a stream from the response bytes
let mut stream = response.bytes_stream();
// SEP-1699: track priming events. If the server closes the POST→SSE
// gracefully without sending a JSON-RPC response but did send a priming
// event (id+retry), the response will arrive on the standalone GET
// stream. Reconnect via GET with Last-Event-ID after the server-provided
// retry delay.
let mut has_priming_event = false;
let mut received_response = false;
let mut sse_retry_delay: Option<Duration> = None;
// Inner loop for processing stream chunks
loop {
let next_chunk = tokio::select! {
// Wait for the next stream chunk
chunk = stream.next() => {
match chunk {
Some(chunk) => chunk,
None => {
// Stream gracefully ended. If we got a priming event
// but no response, reconnect via GET to receive the
// pending response (SEP-1699 resumability).
if has_priming_event && !received_response {
let delay = sse_retry_delay.unwrap_or(self.retry_delay);
tracing::debug!(
"POST→SSE closed with priming only, reconnecting via GET (last_event_id={:?}, delay={:?})",
_last_event_id,
delay
);
time::sleep(delay).await;
let reconnect_response = self
.make_standalone_stream_connection(
cancellation_token,
custom_headers,
_last_event_id.clone(),
)
.await?;
stream = reconnect_response.bytes_stream();
continue;
}
return Err(TransportError::Internal("Stream has ended.".to_string()));
}
}
}
// Wait for cancellation
_ = cancellation_token.cancelled() => {
return Err(TransportError::Cancelled(
crate::utils::CancellationError::ChannelClosed,
));
}
};
match next_chunk {
Ok(bytes) => {
let events = stream_parser.process_new_chunk(bytes);
if !events.is_empty() {
for event in events {
if let Some(retry_ms) = event.retry {
sse_retry_delay = Some(Duration::from_millis(retry_ms));
}
if event.id.is_some() {
_last_event_id = event.id.clone();
has_priming_event = true;
}
if let Some(bytes) = event.data {
received_response = true;
if self.read_tx.send(bytes).await.is_err() {
tracing::error!(
"Readable stream closed, shutting down MCP task"
);
return Err(TransportError::SendFailure(
"Failed to send message: stream closed".to_string(),
));
}
}
}
// Return once we've delivered a real response
if received_response {
return Ok(());
}
}
}
Err(error) => {
tracing::error!("Error reading stream: {error}");
return Err(error.into());
}
}
}
}
pub(crate) async fn make_standalone_stream_connection(
&self,
cancellation_token: &CancellationToken,
custom_headers: &Option<HeaderMap>,
last_event_id: Option<EventId>,
) -> TransportResult<reqwest::Response> {
let mut retry_count = 0;
let session_id = self.session_id.read().await.clone();
let headers = if let Some(event_id) = last_event_id.as_ref() {
let mut headers = HeaderMap::new();
if let Some(custom) = custom_headers {
headers.extend(custom.iter().map(|(k, v)| (k.clone(), v.clone())));
}
if let Ok(event_id_value) = HeaderValue::from_str(event_id) {
headers.insert(MCP_LAST_EVENT_ID_HEADER, event_id_value);
}
&Some(headers)
} else {
custom_headers
};
loop {
// Check for cancellation before attempting connection
if cancellation_token.is_cancelled() {
tracing::info!("Standalone StreamableHttp cancelled.");
return Err(TransportError::Cancelled(
crate::utils::CancellationError::ChannelClosed,
));
}
match http_get(
&self.client,
&self.mcp_url,
session_id.as_ref(),
headers.as_ref(),
)
.await
{
Ok(response) => {
let is_event_stream = validate_response_type(&response)
.await
.is_ok_and(|response_type| response_type == ResponseType::EventStream);
if !is_event_stream {
let message =
"SSE stream response returned an unexpected Content-Type.".to_string();
tracing::warn!("{message}");
return Err(TransportError::FailedToOpenSSEStream(message));
}
return Ok(response);
}
Err(error) => {
match error {
crate::error::TransportError::HttpConnection(_) => {
// A reqwest::Error happened, we do not return ans instead retry the operation
}
crate::error::TransportError::Http(status_code) => match status_code {
StatusCode::NOT_FOUND | StatusCode::METHOD_NOT_ALLOWED => {
return Err(crate::error::TransportError::FailedToOpenSSEStream(
format!("Not supported (code: {status_code})"),
));
}
other => {
tracing::warn!(
"Failed to open SSE stream: {error} (code: {other})"
);
}
},
error => {
return Err(error); // return the error where the retry wont help
}
}
if retry_count >= self.max_retries {
tracing::warn!("Max retries ({}) reached, giving up", self.max_retries);
return Err(error);
}
retry_count += 1;
time::sleep(self.retry_delay).await;
continue;
}
};
}
}
#[allow(dead_code)]
pub(crate) async fn run_standalone(
&mut self,
cancellation_token: &CancellationToken,
custom_headers: &Option<HeaderMap>,
response: Response,
) -> TransportResult<()> {
let mut retry_count = 0;
let mut stream_parser = SseParser::new();
let mut _last_event_id: Option<EventId> = None;
// SSE `retry:` field overrides configured retry_delay (SEP-1699)
let mut sse_retry_delay: Option<Duration> = None;
let mut response = Some(response);
// Main loop for reconnection attempts
loop {
// Check for cancellation before attempting connection
if cancellation_token.is_cancelled() {
tracing::debug!("Standalone StreamableHttp cancelled.");
return Err(TransportError::Cancelled(
crate::utils::CancellationError::ChannelClosed,
));
}
// use initially passed response, otherwise try to make a new sse connection
let response = match response.take() {
Some(response) => response,
None => {
tracing::debug!(
"Reconnecting to SSE stream... (try {} of {})",
retry_count,
self.max_retries
);
self.make_standalone_stream_connection(
cancellation_token,
custom_headers,
_last_event_id.clone(),
)
.await?
}
};
// Create a stream from the response bytes
let mut stream = response.bytes_stream();
// Inner loop for processing stream chunks
loop {
let next_chunk = tokio::select! {
// Wait for the next stream chunk
chunk = stream.next() => {
match chunk {
Some(chunk) => chunk,
None => {
// Server gracefully closed the stream. SEP-1699: the
// standalone SSE channel is long-lived, so we should
// reconnect with Last-Event-ID for resumability rather
// than terminate the channel.
tracing::debug!(
"Standalone SSE stream closed by server, reconnecting (last_event_id={:?}, retry={:?})",
_last_event_id,
sse_retry_delay
);
if retry_count >= self.max_retries {
return Err(TransportError::Internal(
"Stream has ended; max reconnect retries reached".to_string()
));
}
retry_count += 1;
let delay = sse_retry_delay.unwrap_or(self.retry_delay);
time::sleep(delay).await;
break; // Break inner loop to reconnect
}
}
}
// Wait for cancellation
_ = cancellation_token.cancelled() => {
return Err(TransportError::Cancelled(
crate::utils::CancellationError::ChannelClosed,
));
}
};
match next_chunk {
Ok(bytes) => {
let events = stream_parser.process_new_chunk(bytes);
if !events.is_empty() {
for event in events {
if let Some(retry_ms) = event.retry {
sse_retry_delay = Some(Duration::from_millis(retry_ms));
}
if let Some(bytes) = event.data {
if event.id.is_some() {
_last_event_id = event.id.clone();
}
if self.read_tx.send(bytes).await.is_err() {
tracing::error!(
"Readable stream closed, shutting down MCP task"
);
return Err(TransportError::SendFailure(
"Failed to send message: stream closed".to_string(),
));
}
}
}
}
retry_count = 0; // Reset retry count on successful chunk
}
Err(error) => {
if retry_count >= self.max_retries {
tracing::error!("Error reading stream: {error}");
tracing::warn!("Max retries ({}) reached, giving up", self.max_retries);
return Err(error.into());
}
tracing::debug!(
"The standalone SSE stream encountered an error: '{}'",
error
);
retry_count += 1;
// Honor SSE `retry:` field if present (SEP-1699)
let delay = sse_retry_delay.unwrap_or(self.retry_delay);
time::sleep(delay).await;
break; // Break inner loop to reconnect
}
}
}
}
}
}