parseMcpSseEvents function
Implementation
List<McpSseEvent> parseMcpSseEvents(String body) {
final events = <McpSseEvent>[];
final dataLines = <String>[];
String? id;
String? event;
int? retryMs;
void commit() {
if (id != null ||
event != null ||
retryMs != null ||
dataLines.isNotEmpty) {
events.add(
McpSseEvent(
id: id,
event: event,
data: dataLines.join('\n'),
retryMs: retryMs,
),
);
}
id = null;
event = null;
retryMs = null;
dataLines.clear();
}
for (final rawLine in const LineSplitter().convert(body)) {
if (rawLine.isEmpty) {
commit();
continue;
}
if (rawLine.startsWith(':')) {
continue;
}
final colonIndex = rawLine.indexOf(':');
final field = colonIndex == -1 ? rawLine : rawLine.substring(0, colonIndex);
var value = colonIndex == -1 ? '' : rawLine.substring(colonIndex + 1);
if (value.startsWith(' ')) {
value = value.substring(1);
}
switch (field) {
case 'data':
dataLines.add(value);
break;
case 'id':
id = value;
break;
case 'event':
event = value;
break;
case 'retry':
retryMs = int.tryParse(value);
break;
}
}
commit();
return events;
}