Skip to content
This repository was archived by the owner on Mar 21, 2025. It is now read-only.

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

Merged
merged 1 commit into from
Mar 7, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 10 additions & 18 deletions src/mcpdotnet/Protocol/Transport/SseClientTransport.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System.Net.Http.Headers;
using System.Net.ServerSentEvents;
using System.Text;
using System.Text.Json;
using McpDotNet.Configuration;
Expand Down Expand Up @@ -191,30 +192,21 @@ private async Task ReceiveMessagesAsync(CancellationToken cancellationToken)
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;
}
}
}
Expand Down
5 changes: 3 additions & 2 deletions src/mcpdotnet/mcpdotnet.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -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>
Expand All @@ -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>
Loading