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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
//! Server-Sent Events (SSE) parser for MCP HTTP transport.
//!
//! This module provides a robust SSE parser compatible with the
//! `EventSource` specification, similar to eventsource-parser in TypeScript.
use std::collections::HashMap;
use std::fmt;
/// SSE event parsed from the stream.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SseEvent {
/// Event ID for resumption
pub id: Option<String>,
/// Event type/name
pub event: Option<String>,
/// Event data
pub data: String,
/// Retry interval in milliseconds
pub retry: Option<u64>,
}
impl SseEvent {
/// Create a new SSE event with data.
///
/// # Examples
///
/// ```rust
/// use pmcp::shared::sse_parser::SseEvent;
///
/// let event = SseEvent::new("Hello, world!");
/// assert_eq!(event.data, "Hello, world!");
/// assert!(event.id.is_none());
/// assert!(event.event.is_none());
/// ```
pub fn new(data: impl Into<String>) -> Self {
Self {
id: None,
event: None,
data: data.into(),
retry: None,
}
}
/// Set the event ID.
///
/// # Examples
///
/// ```rust
/// use pmcp::shared::sse_parser::SseEvent;
///
/// let event = SseEvent::new("data")
/// .with_id("msg-123");
/// assert_eq!(event.id, Some("msg-123".to_string()));
/// ```
pub fn with_id(mut self, id: impl Into<String>) -> Self {
self.id = Some(id.into());
self
}
/// Set the event type.
///
/// # Examples
///
/// ```rust
/// use pmcp::shared::sse_parser::SseEvent;
///
/// let event = SseEvent::new("data")
/// .with_event("custom");
/// assert_eq!(event.event, Some("custom".to_string()));
/// ```
pub fn with_event(mut self, event: impl Into<String>) -> Self {
self.event = Some(event.into());
self
}
/// Set the retry interval.
///
/// # Examples
///
/// ```rust
/// use pmcp::shared::sse_parser::SseEvent;
///
/// let event = SseEvent::new("data")
/// .with_retry(3000);
/// assert_eq!(event.retry, Some(3000));
/// ```
pub fn with_retry(mut self, retry: u64) -> Self {
self.retry = Some(retry);
self
}
}
impl fmt::Display for SseEvent {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if let Some(id) = &self.id {
writeln!(f, "id: {}", id)?;
}
if let Some(event) = &self.event {
writeln!(f, "event: {}", event)?;
}
if let Some(retry) = self.retry {
writeln!(f, "retry: {}", retry)?;
}
// Split data by newlines and write each line
for line in self.data.lines() {
writeln!(f, "data: {}", line)?;
}
writeln!(f)?; // Empty line to end event
Ok(())
}
}
/// SSE parser state machine.
#[derive(Debug)]
pub struct SseParser {
buffer: String,
current_event: EventBuilder,
last_event_id: Option<String>,
}
impl SseParser {
/// Create a new SSE parser.
///
/// # Examples
///
/// ```rust
/// use pmcp::shared::sse_parser::SseParser;
///
/// let mut parser = SseParser::new();
/// assert!(parser.last_event_id().is_none());
/// ```
pub fn new() -> Self {
Self {
buffer: String::new(),
current_event: EventBuilder::new(),
last_event_id: None,
}
}
/// Feed data to the parser and get parsed events.
///
/// # Examples
///
/// ```rust
/// use pmcp::shared::sse_parser::SseParser;
///
/// let mut parser = SseParser::new();
///
/// // Simple event
/// let events = parser.feed("data: Hello\n\n");
/// assert_eq!(events.len(), 1);
/// assert_eq!(events[0].data, "Hello");
///
/// // Event with ID
/// let events = parser.feed("id: 123\ndata: World\n\n");
/// assert_eq!(events[0].id, Some("123".to_string()));
/// assert_eq!(events[0].data, "World");
///
/// // Multi-line data
/// let events = parser.feed("data: Line 1\ndata: Line 2\n\n");
/// assert_eq!(events[0].data, "Line 1\nLine 2");
///
/// // Custom event type
/// let events = parser.feed("event: ping\ndata: pong\n\n");
/// assert_eq!(events[0].event, Some("ping".to_string()));
/// ```
pub fn feed(&mut self, data: &str) -> Vec<SseEvent> {
self.buffer.push_str(data);
let mut events = Vec::new();
while let Some(line_end) = self.buffer.find('\n') {
let line = if line_end > 0 && self.buffer.chars().nth(line_end - 1) == Some('\r') {
self.buffer[..line_end - 1].to_string()
} else {
self.buffer[..line_end].to_string()
};
if let Some(event) = self.process_line(&line) {
events.push(event);
}
self.buffer.drain(..=line_end);
}
events
}
/// Process a single line and potentially emit an event.
fn process_line(&mut self, line: &str) -> Option<SseEvent> {
// Empty line dispatches the event
if line.is_empty() {
return self.dispatch_event();
}
// Comment line (starts with :)
if line.starts_with(':') {
return None;
}
// Parse field and value
let (field, value) = if let Some(colon_pos) = line.find(':') {
let field = &line[..colon_pos];
let value = &line[colon_pos + 1..];
// Remove leading space from value if present
let value = value.strip_prefix(' ').unwrap_or(value);
(field, value)
} else {
// Field without value
(line, "")
};
// Process field
match field {
"event" => {
self.current_event.event = Some(value.to_string());
},
"data" => {
if self.current_event.data.is_empty() {
self.current_event.data = value.to_string();
} else {
self.current_event.data.push('\n');
self.current_event.data.push_str(value);
}
},
"id" if !value.contains('\0') => {
self.current_event.id = Some(value.to_string());
self.last_event_id = Some(value.to_string());
},
"retry" => {
if let Ok(retry) = value.parse::<u64>() {
self.current_event.retry = Some(retry);
}
},
_ => {
// Unknown field, ignore
},
}
None
}
/// Dispatch the current event if it has data.
fn dispatch_event(&mut self) -> Option<SseEvent> {
if self.current_event.data.is_empty() {
// No data, don't dispatch
self.current_event = EventBuilder::new();
return None;
}
let event = SseEvent {
id: self
.current_event
.id
.clone()
.or_else(|| self.last_event_id.clone()),
event: self.current_event.event.clone(),
data: self.current_event.data.clone(),
retry: self.current_event.retry,
};
self.current_event = EventBuilder::new();
Some(event)
}
/// Get the last event ID seen.
pub fn last_event_id(&self) -> Option<&str> {
self.last_event_id.as_deref()
}
/// Reset the parser state.
pub fn reset(&mut self) {
self.buffer.clear();
self.current_event = EventBuilder::new();
}
}
impl Default for SseParser {
fn default() -> Self {
Self::new()
}
}
/// Builder for SSE events during parsing.
#[derive(Debug, Clone)]
struct EventBuilder {
id: Option<String>,
event: Option<String>,
data: String,
retry: Option<u64>,
}
impl EventBuilder {
fn new() -> Self {
Self {
id: None,
event: None,
data: String::new(),
retry: None,
}
}
}
/// SSE stream builder for creating SSE responses.
#[derive(Debug)]
pub struct SseStream {
events: Vec<SseEvent>,
}
impl SseStream {
/// Create a new SSE stream builder.
pub fn new() -> Self {
Self { events: Vec::new() }
}
/// Add an event to the stream.
pub fn event(mut self, event: SseEvent) -> Self {
self.events.push(event);
self
}
/// Add a simple data event.
pub fn data(self, data: impl Into<String>) -> Self {
self.event(SseEvent::new(data))
}
/// Add a typed event with data.
pub fn typed_event(self, event_type: impl Into<String>, data: impl Into<String>) -> Self {
self.event(SseEvent::new(data).with_event(event_type))
}
/// Add a comment line.
pub fn comment(self, _comment: impl Into<String>) -> Self {
// Comments are not stored as events, they're just for keep-alive
// In a real implementation, we'd write this directly to the stream
self
}
/// Build the SSE stream as a string.
pub fn build(self) -> String {
self.events
.into_iter()
.map(|e| e.to_string())
.collect::<String>()
}
}
impl Default for SseStream {
fn default() -> Self {
Self::new()
}
}
/// Configuration for SSE connections.
#[derive(Debug, Clone)]
pub struct SseConfig {
/// Reconnection retry interval in milliseconds
pub retry: u64,
/// Maximum buffer size for incomplete lines
pub max_buffer_size: usize,
/// Enable compression
pub compression: bool,
/// Custom headers
pub headers: HashMap<String, String>,
}
impl Default for SseConfig {
fn default() -> Self {
let mut headers = HashMap::new();
headers.insert("Cache-Control".to_string(), "no-cache".to_string());
headers.insert("Connection".to_string(), "keep-alive".to_string());
Self {
retry: 3000,
max_buffer_size: 1024 * 1024, // 1MB
compression: false,
headers,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_sse_parser_simple() {
let mut parser = SseParser::new();
let input = "data: hello world\n\n";
let events = parser.feed(input);
assert_eq!(events.len(), 1);
assert_eq!(events[0].data, "hello world");
assert_eq!(events[0].event, None);
assert_eq!(events[0].id, None);
}
#[test]
fn test_sse_parser_with_event_type() {
let mut parser = SseParser::new();
let input = "event: message\ndata: hello\n\n";
let events = parser.feed(input);
assert_eq!(events.len(), 1);
assert_eq!(events[0].data, "hello");
assert_eq!(events[0].event, Some("message".to_string()));
}
#[test]
fn test_sse_parser_multiline_data() {
let mut parser = SseParser::new();
let input = "data: line 1\ndata: line 2\ndata: line 3\n\n";
let events = parser.feed(input);
assert_eq!(events.len(), 1);
assert_eq!(events[0].data, "line 1\nline 2\nline 3");
}
#[test]
fn test_sse_parser_with_id() {
let mut parser = SseParser::new();
let input = "id: 123\ndata: test\n\n";
let events = parser.feed(input);
assert_eq!(events.len(), 1);
assert_eq!(events[0].id, Some("123".to_string()));
assert_eq!(parser.last_event_id(), Some("123"));
}
#[test]
fn test_sse_parser_with_retry() {
let mut parser = SseParser::new();
let input = "retry: 5000\ndata: test\n\n";
let events = parser.feed(input);
assert_eq!(events.len(), 1);
assert_eq!(events[0].retry, Some(5000));
}
#[test]
fn test_sse_parser_comments() {
let mut parser = SseParser::new();
let input = ": this is a comment\ndata: actual data\n\n";
let events = parser.feed(input);
assert_eq!(events.len(), 1);
assert_eq!(events[0].data, "actual data");
}
#[test]
fn test_sse_parser_incremental() {
let mut parser = SseParser::new();
// Feed data incrementally
let events1 = parser.feed("data: par");
assert_eq!(events1.len(), 0);
let events2 = parser.feed("tial\ndata: more");
assert_eq!(events2.len(), 0);
let events3 = parser.feed("\n\n");
assert_eq!(events3.len(), 1);
assert_eq!(events3[0].data, "partial\nmore");
}
#[test]
fn test_sse_stream_builder() {
let stream = SseStream::new()
.data("simple message")
.typed_event("ping", "pong")
.event(SseEvent::new("complex").with_id("42").with_retry(1000))
.build();
assert!(stream.contains("data: simple message"));
assert!(stream.contains("event: ping"));
assert!(stream.contains("data: pong"));
assert!(stream.contains("id: 42"));
assert!(stream.contains("retry: 1000"));
}
#[test]
fn test_sse_event_display() {
let event = SseEvent::new("test data")
.with_id("123")
.with_event("message")
.with_retry(3000);
let output = event.to_string();
assert!(output.contains("id: 123"));
assert!(output.contains("event: message"));
assert!(output.contains("retry: 3000"));
assert!(output.contains("data: test data"));
}
}