-
Notifications
You must be signed in to change notification settings - Fork 696
Expand file tree
/
Copy pathAutoDetectingClientSessionTransport.cs
More file actions
196 lines (167 loc) · 8.75 KB
/
AutoDetectingClientSessionTransport.cs
File metadata and controls
196 lines (167 loc) · 8.75 KB
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
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 HttpClientTransportOptions _options;
private readonly McpHttpClient _httpClient;
private readonly ILoggerFactory? _loggerFactory;
private readonly ILogger _logger;
private readonly string _name;
private readonly Channel<JsonRpcMessage> _messageChannel;
public AutoDetectingClientSessionTransport(string endpointName, HttpClientTransportOptions transportOptions, McpHttpClient httpClient, ILoggerFactory? loggerFactory)
{
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;
string? ITransport.SessionId => ActiveTransport?.SessionId;
/// <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 (response.IsSuccessStatusCode)
{
LogUsingStreamableHttp(_name);
ActiveTransport = streamableHttpTransport;
}
else
{
// Streamable HTTP failed. Capture the underlying error (status + body) before falling back to SSE
// so that, if SSE also fails, we can surface the real Streamable HTTP diagnostic to the caller
// instead of dropping it on the floor (see https://github.com/modelcontextprotocol/csharp-sdk/issues/1526).
LogStreamableHttpFailed(_name, response.StatusCode);
var streamableHttpError = await CreateStreamableHttpErrorAsync(response, cancellationToken).ConfigureAwait(false);
await streamableHttpTransport.DisposeAsync().ConfigureAwait(false);
await InitializeSseTransportAsync(message, streamableHttpError, cancellationToken).ConfigureAwait(false);
}
}
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 else block.
await streamableHttpTransport.DisposeAsync().ConfigureAwait(false);
throw;
}
}
private async Task InitializeSseTransportAsync(JsonRpcMessage message, HttpRequestException? streamableHttpError, CancellationToken cancellationToken)
{
if (_options.KnownSessionId is not null)
{
throw new InvalidOperationException("Streamable HTTP transport is required to resume an existing session.");
}
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 (Exception sseError) when (streamableHttpError is not null && sseError is not OperationCanceledException)
{
// SSE fallback also failed. Surface the original Streamable HTTP error as the primary failure
// so the user sees the real server diagnostic (e.g. 415 Unsupported Media Type) instead of the
// unrelated SSE-fallback error (e.g. a 405 from a Streamable-HTTP-only server that doesn't accept GET).
await sseTransport.DisposeAsync().ConfigureAwait(false);
LogSseFallbackFailedAfterStreamableHttp(_name, sseError);
throw new AggregateException(
"Streamable HTTP transport failed and the SSE fallback also failed. " +
"The first inner exception is the original Streamable HTTP error (the real server response); " +
"the second is the SSE fallback failure.",
streamableHttpError,
sseError);
}
catch
{
await sseTransport.DisposeAsync().ConfigureAwait(false);
throw;
}
}
private static async Task<HttpRequestException> CreateStreamableHttpErrorAsync(HttpResponseMessage response, CancellationToken cancellationToken)
{
// Best-effort read of the response body so the exception message includes the server's diagnostic
// (e.g. "Content-Type must be 'application/json'" on a 415). Mirrors EnsureSuccessStatusCodeWithResponseBodyAsync.
string? responseBody = null;
try
{
using var cts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
cts.CancelAfter(TimeSpan.FromSeconds(5));
responseBody = await response.Content.ReadAsStringAsync(cts.Token).ConfigureAwait(false);
const int MaxResponseBodyLength = 1024;
if (responseBody.Length > MaxResponseBodyLength)
{
responseBody = responseBody.Substring(0, MaxResponseBodyLength) + "...";
}
}
catch
{
// Ignore all errors reading the response body (e.g., stream closed, timeout, cancellation) - we'll throw without it.
}
return HttpResponseMessageExtensions.CreateHttpRequestException(response, responseBody);
}
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);
[LoggerMessage(Level = LogLevel.Warning, Message = "{EndpointName} SSE fallback failed after Streamable HTTP also failed; surfacing both errors.")]
private partial void LogSseFallbackFailedAfterStreamableHttp(string endpointName, Exception sseError);
}