Use System.Net.ServerSentEvents for parsing SSE response (#32)

This commit is contained in:
Stephen Toub 2025-03-07 12:41:01 -05:00 • committed by GitHub
commit f15b94c244
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 13 additions and 20 deletions

View file

@ -1,4 +1,5 @@
using System.Net.Http.Headers;
using System.Net.ServerSentEvents;
using System.Text;
using System.Text.Json;
using McpDotNet.Configuration;
@ -191,30 +192,21 @@ public sealed class SseClientTransport : TransportBase, IClientTransport
response.EnsureSuccessStatusCode();
using var stream = await response.Content.ReadAsStreamAsync(cancellationToken);
using var reader = new StreamReader(stream);
// Reset reconnect attempts on successful connection
reconnectAttempts = 0;
string? currentEvent = null;
string? line;
while ((line = await reader.ReadLineAsync(cancellationToken)) != null)
await foreach (SseItem<string> sseEvent in SseParser.Create(stream).EnumerateAsync(cancellationToken))
{
if (line.StartsWith("event: "))
switch (sseEvent.EventType)
{
currentEvent = line.Substring(7);
}
else if (line.StartsWith("data: "))
{
var data = line.Substring(6);
if (currentEvent == "endpoint")
{
HandleEndpointEvent(data);
}
else
{
await ProcessSseMessage(data, cancellationToken);
}
case "endpoint":
HandleEndpointEvent(sseEvent.Data);
break;
case "message":
await ProcessSseMessage(sseEvent.Data, cancellationToken);
break;
}
}
}

View file

@ -11,7 +11,7 @@
<PackageId>mcpdotnet</PackageId>
<Version>1.0.1.3</Version>
<Authors>PederHP</Authors>
<Description>.NET client library for the Model Context Protocol (MCP)</Description>
<Description>.NET library for the Model Context Protocol (MCP)</Description>
<PackageProjectUrl>https://github.com/PederHP/mcpdotnet</PackageProjectUrl>
<RepositoryUrl>https://github.com/PederHP/mcpdotnet</RepositoryUrl>
<RepositoryType>git</RepositoryType>
@ -32,11 +32,12 @@
<ItemGroup>
<InternalsVisibleTo Include="McpDotNet.Tests" />
</ItemGroup>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="9.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="9.0.0" />
<PackageReference Include="System.Net.ServerSentEvents" Version="9.0.0" />
</ItemGroup>
</Project>