-
Notifications
You must be signed in to change notification settings - Fork 545
Automatically fall back from Streamable HTTP to SSE on the client by default #456
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 5 commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
1051bc5
Automatically fall back from Streamable HTTP to SSE on the client by …
halter73 46a9df8
Add back spec links to SseClientTransportOptions
halter73 b548124
Revert removal of LogTransportMessageParseFailedSensitive call
halter73 e5f8bb6
Remove redundant SendMessageAsync call
halter73 b7c8684
Address PR feedback.
halter73 59de4d4
Update src/ModelContextProtocol/Client/SseClientTransportOptions.cs
halter73 7c634fe
Update src/ModelContextProtocol/Client/StreamableHttpClientSessionTra…
halter73 67caeda
whitespace fixes
halter73 4793ebf
Set StreamClientSessionTransport to the connected state before readin…
halter73 04c0877
Make StdioClientTransportTests a LoggedTest
halter73 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
142 changes: 142 additions & 0 deletions
142
src/ModelContextProtocol/Client/AutoDetectingClientSessionTransport.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,142 @@ | ||
using Microsoft.Extensions.Logging; | ||
using Microsoft.Extensions.Logging.Abstractions; | ||
using ModelContextProtocol.Protocol; | ||
using System.Net; | ||
using System.Threading.Channels; | ||
|
||
namespace ModelContextProtocol.Client; | ||
|
||
/// <summary> | ||
/// A transport that automatically detects whether to use Streamable HTTP or SSE transport | ||
/// by trying Streamable HTTP first and falling back to SSE if that fails. | ||
/// </summary> | ||
internal sealed partial class AutoDetectingClientSessionTransport : ITransport | ||
{ | ||
private readonly SseClientTransportOptions _options; | ||
private readonly HttpClient _httpClient; | ||
private readonly ILoggerFactory? _loggerFactory; | ||
private readonly ILogger _logger; | ||
private readonly string _name; | ||
private readonly Channel<JsonRpcMessage> _messageChannel; | ||
|
||
public AutoDetectingClientSessionTransport(SseClientTransportOptions transportOptions, HttpClient httpClient, ILoggerFactory? loggerFactory, string endpointName) | ||
{ | ||
Throw.IfNull(transportOptions); | ||
Throw.IfNull(httpClient); | ||
|
||
_options = transportOptions; | ||
_httpClient = httpClient; | ||
_loggerFactory = loggerFactory; | ||
_logger = (ILogger?)loggerFactory?.CreateLogger<AutoDetectingClientSessionTransport>() ?? NullLogger.Instance; | ||
_name = endpointName; | ||
|
||
// Same as TransportBase.cs. | ||
_messageChannel = Channel.CreateUnbounded<JsonRpcMessage>(new UnboundedChannelOptions | ||
{ | ||
SingleReader = true, | ||
SingleWriter = false, | ||
}); | ||
} | ||
|
||
/// <summary> | ||
/// Returns the active transport (either StreamableHttp or SSE) | ||
/// </summary> | ||
internal ITransport? ActiveTransport { get; private set; } | ||
|
||
public ChannelReader<JsonRpcMessage> MessageReader => _messageChannel.Reader; | ||
|
||
/// <inheritdoc/> | ||
public Task SendMessageAsync(JsonRpcMessage message, CancellationToken cancellationToken = default) | ||
{ | ||
if (ActiveTransport is null) | ||
{ | ||
return InitializeAsync(message, cancellationToken); | ||
} | ||
|
||
return ActiveTransport.SendMessageAsync(message, cancellationToken); | ||
} | ||
|
||
private async Task InitializeAsync(JsonRpcMessage message, CancellationToken cancellationToken) | ||
{ | ||
// Try StreamableHttp first | ||
var streamableHttpTransport = new StreamableHttpClientSessionTransport(_name, _options, _httpClient, _messageChannel, _loggerFactory); | ||
|
||
try | ||
{ | ||
LogAttemptingStreamableHttp(_name); | ||
using var response = await streamableHttpTransport.SendHttpRequestAsync(message, cancellationToken).ConfigureAwait(false); | ||
|
||
// If the status code is not success, fall back to SSE | ||
if (!response.IsSuccessStatusCode) | ||
{ | ||
LogStreamableHttpFailed(_name, response.StatusCode); | ||
|
||
await streamableHttpTransport.DisposeAsync().ConfigureAwait(false); | ||
await InitializeSseTransportAsync(message, cancellationToken).ConfigureAwait(false); | ||
return; | ||
} | ||
|
||
LogUsingStreamableHttp(_name); | ||
ActiveTransport = streamableHttpTransport; | ||
} | ||
catch | ||
{ | ||
// If nothing threw inside the try block, we've either set streamableHttpTransport as the | ||
// ActiveTransport, or else we will have disposed it in the !IsSuccessStatusCode if statement. | ||
await streamableHttpTransport.DisposeAsync().ConfigureAwait(false); | ||
throw; | ||
} | ||
} | ||
|
||
private async Task InitializeSseTransportAsync(JsonRpcMessage message, CancellationToken cancellationToken) | ||
{ | ||
var sseTransport = new SseClientSessionTransport(_name, _options, _httpClient, _messageChannel, _loggerFactory); | ||
|
||
try | ||
{ | ||
LogAttemptingSSE(_name); | ||
await sseTransport.ConnectAsync(cancellationToken).ConfigureAwait(false); | ||
await sseTransport.SendMessageAsync(message, cancellationToken).ConfigureAwait(false); | ||
|
||
LogUsingSSE(_name); | ||
ActiveTransport = sseTransport; | ||
} | ||
catch | ||
{ | ||
await sseTransport.DisposeAsync().ConfigureAwait(false); | ||
throw; | ||
} | ||
} | ||
|
||
public async ValueTask DisposeAsync() | ||
{ | ||
try | ||
{ | ||
if (ActiveTransport is not null) | ||
{ | ||
await ActiveTransport.DisposeAsync().ConfigureAwait(false); | ||
} | ||
} | ||
finally | ||
{ | ||
// In the majority of cases, either the Streamable HTTP transport or SSE transport has completed the channel by now. | ||
// However, this may not be the case if HttpClient throws during the initial request due to misconfiguration. | ||
_messageChannel.Writer.TryComplete(); | ||
} | ||
} | ||
|
||
[LoggerMessage(Level = LogLevel.Debug, Message = "{EndpointName} attempting to connect using Streamable HTTP transport.")] | ||
private partial void LogAttemptingStreamableHttp(string endpointName); | ||
|
||
[LoggerMessage(Level = LogLevel.Information, Message = "{EndpointName} streamable HTTP transport failed with status code {StatusCode}, falling back to SSE transport.")] | ||
private partial void LogStreamableHttpFailed(string endpointName, HttpStatusCode statusCode); | ||
|
||
[LoggerMessage(Level = LogLevel.Information, Message = "{EndpointName} using Streamable HTTP transport.")] | ||
private partial void LogUsingStreamableHttp(string endpointName); | ||
|
||
[LoggerMessage(Level = LogLevel.Debug, Message = "{EndpointName} attempting to connect using SSE transport.")] | ||
private partial void LogAttemptingSSE(string endpointName); | ||
|
||
[LoggerMessage(Level = LogLevel.Information, Message = "{EndpointName} using SSE transport.")] | ||
private partial void LogUsingSSE(string endpointName); | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
namespace ModelContextProtocol.Client; | ||
|
||
/// <summary> | ||
/// Specifies the transport mode for HTTP client connections. | ||
/// </summary> | ||
public enum HttpTransportMode | ||
{ | ||
/// <summary> | ||
/// Automatically detect the appropriate transport by trying Streamable HTTP first, then falling back to SSE if that fails. | ||
/// This is the recommended mode for maximum compatibility. | ||
/// </summary> | ||
AutoDetect, | ||
|
||
/// <summary> | ||
/// Use only the Streamable HTTP transport. | ||
/// </summary> | ||
StreamableHttp, | ||
|
||
/// <summary> | ||
/// Use only the HTTP with SSE transport. | ||
/// </summary> | ||
Sse | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.