forked from modelcontextprotocol/csharp-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAutoDetectingClientSessionTransport.cs
More file actions
163 lines (134 loc) · 7.01 KB
/
AutoDetectingClientSessionTransport.cs
File metadata and controls
163 lines (134 loc) · 7.01 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
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using ModelContextProtocol.Protocol;
using System.Diagnostics;
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 DelegatingChannelReader<JsonRpcMessage> _delegatingChannelReader;
private StreamableHttpClientSessionTransport? _streamableHttpTransport;
private SseClientSessionTransport? _sseTransport;
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;
_delegatingChannelReader = new DelegatingChannelReader<JsonRpcMessage>(this);
}
/// <summary>
/// Returns the active transport (either StreamableHttp or SSE)
/// </summary>
internal ITransport? ActiveTransport => _streamableHttpTransport != null ? (ITransport)_streamableHttpTransport : _sseTransport;
public ChannelReader<JsonRpcMessage> MessageReader => _delegatingChannelReader;
/// <inheritdoc/>
public async Task SendMessageAsync(JsonRpcMessage message, CancellationToken cancellationToken = default)
{
if (_streamableHttpTransport == null && _sseTransport == null)
{
var rpcRequest = message as JsonRpcRequest;
// Try StreamableHttp first
_streamableHttpTransport = new StreamableHttpClientSessionTransport(_options, _httpClient, _loggerFactory, _name);
try
{
LogAttemptingStreamableHttp(_name);
var response = await _streamableHttpTransport.SendInitialRequestAsync(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;
}
// Process the streamable HTTP response using the transport
await _streamableHttpTransport.SendMessageAsync(message, cancellationToken).ConfigureAwait(false);
// Signal that we have established a connection
LogUsingStreamableHttp(_name);
_delegatingChannelReader.SetConnected();
}
catch (Exception ex)
{
LogStreamableHttpException(_name, ex);
await _streamableHttpTransport.DisposeAsync().ConfigureAwait(false);
// Propagate the original exception
throw;
}
}
else if (_streamableHttpTransport != null)
{
await _streamableHttpTransport.SendMessageAsync(message, cancellationToken).ConfigureAwait(false);
}
else if (_sseTransport != null)
{
await _sseTransport.SendMessageAsync(message, cancellationToken).ConfigureAwait(false);
}
}
private async Task InitializeSseTransportAsync(JsonRpcMessage message, CancellationToken cancellationToken)
{
_sseTransport = new SseClientSessionTransport(_options, _httpClient, _loggerFactory, _name);
try
{
LogAttemptingSSE(_name);
await _sseTransport.ConnectAsync(cancellationToken).ConfigureAwait(false);
await _sseTransport.SendMessageAsync(message, cancellationToken).ConfigureAwait(false);
// Signal that we have established a connection
LogUsingSSE(_name);
_delegatingChannelReader.SetConnected();
}
catch (Exception ex)
{
LogSSEConnectionFailed(_name, ex);
_delegatingChannelReader.SetError(ex);
await _sseTransport.DisposeAsync().ConfigureAwait(false);
throw;
}
}
public async ValueTask DisposeAsync()
{
try
{
if (_streamableHttpTransport != null)
{
await _streamableHttpTransport.DisposeAsync().ConfigureAwait(false);
}
if (_sseTransport != null)
{
await _sseTransport.DisposeAsync().ConfigureAwait(false);
}
}
catch (Exception ex)
{
LogDisposeFailed(_name, ex);
}
}
[LoggerMessage(Level = LogLevel.Debug, Message = "{EndpointName}: Attempting to connect using Streamable HTTP transport.")]
private partial void LogAttemptingStreamableHttp(string endpointName);
[LoggerMessage(Level = LogLevel.Debug, Message = "{EndpointName}: Streamable HTTP transport failed with status code {StatusCode}, falling back to SSE transport.")]
private partial void LogStreamableHttpFailed(string endpointName, System.Net.HttpStatusCode statusCode);
[LoggerMessage(Level = LogLevel.Debug, Message = "{EndpointName}: Streamable HTTP transport failed with exception, falling back to SSE transport.")]
private partial void LogStreamableHttpException(string endpointName, Exception exception);
[LoggerMessage(Level = LogLevel.Debug, 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.Debug, Message = "{EndpointName}: Using SSE transport.")]
private partial void LogUsingSSE(string endpointName);
[LoggerMessage(Level = LogLevel.Error, Message = "{EndpointName}: Failed to connect using both Streamable HTTP and SSE transports.")]
private partial void LogSSEConnectionFailed(string endpointName, Exception exception);
[LoggerMessage(Level = LogLevel.Warning, Message = "{EndpointName}: Error disposing transport.")]
private partial void LogDisposeFailed(string endpointName, Exception exception);
}