-
Notifications
You must be signed in to change notification settings - Fork 670
Expand file tree
/
Copy pathStreamClientSessionTransport.cs
More file actions
212 lines (188 loc) · 7.48 KB
/
StreamClientSessionTransport.cs
File metadata and controls
212 lines (188 loc) · 7.48 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
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
using Microsoft.Extensions.Logging;
using ModelContextProtocol.Protocol;
using System.Text;
using System.Text.Json;
namespace ModelContextProtocol.Client;
/// <summary>Provides the client side of a stream-based session transport.</summary>
internal class StreamClientSessionTransport : TransportBase
{
private static readonly byte[] s_newlineBytes = "\n"u8.ToArray();
internal static UTF8Encoding NoBomUtf8Encoding { get; } = new(encoderShouldEmitUTF8Identifier: false);
private readonly TextReader _serverOutput;
private readonly Stream _serverInputStream;
private readonly SemaphoreSlim _sendLock = new(1, 1);
private readonly CancellationTokenSource _shutdownCts = new();
private Task? _readTask;
/// <summary>
/// Initializes a new instance of the <see cref="StreamClientSessionTransport"/> class.
/// </summary>
/// <param name="serverInput">
/// The server's input stream. Messages written to this stream will be sent to the server.
/// </param>
/// <param name="serverOutput">
/// The server's output stream. Messages read from this stream will be received from the server.
/// </param>
/// <param name="encoding">
/// The encoding used for reading and writing messages from the input and output streams. Defaults to UTF-8 without BOM if null.
/// </param>
/// <param name="endpointName">
/// A name that identifies this transport endpoint in logs.
/// </param>
/// <param name="loggerFactory">
/// Optional factory for creating loggers. If null, a NullLogger is used.
/// </param>
/// <remarks>
/// This constructor starts a background task to read messages from the server output stream.
/// The transport will be marked as connected once initialized.
/// </remarks>
public StreamClientSessionTransport(Stream serverInput, Stream serverOutput, Encoding? encoding, string endpointName, ILoggerFactory? loggerFactory)
: base(endpointName, loggerFactory)
{
Throw.IfNull(serverInput);
Throw.IfNull(serverOutput);
_serverInputStream = serverInput;
#if NET
_serverOutput = new StreamReader(serverOutput, encoding ?? NoBomUtf8Encoding);
#else
_serverOutput = new CancellableStreamReader(serverOutput, encoding ?? NoBomUtf8Encoding);
#endif
SetConnected();
// Start reading messages in the background. We use the rarer pattern of new Task + Start
// in order to ensure that the body of the task will always see _readTask initialized.
// It is then able to reliably null it out on completion.
var readTask = new Task<Task>(
thisRef => ((StreamClientSessionTransport)thisRef!).ReadMessagesAsync(_shutdownCts.Token),
this,
TaskCreationOptions.DenyChildAttach);
_readTask = readTask.Unwrap();
readTask.Start();
}
/// <inheritdoc/>
public override async Task SendMessageAsync(JsonRpcMessage message, CancellationToken cancellationToken = default)
{
string id = "(no id)";
if (message is JsonRpcMessageWithId messageWithId)
{
id = messageWithId.Id.ToString();
}
LogTransportSendingMessageSensitive(message);
using var _ = await _sendLock.LockAsync(cancellationToken).ConfigureAwait(false);
try
{
var json = JsonSerializer.SerializeToUtf8Bytes(message, McpJsonUtilities.JsonContext.Default.JsonRpcMessage);
await _serverInputStream.WriteAsync(json, cancellationToken).ConfigureAwait(false);
await _serverInputStream.WriteAsync(s_newlineBytes, cancellationToken).ConfigureAwait(false);
await _serverInputStream.FlushAsync(cancellationToken).ConfigureAwait(false);
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
throw;
}
catch (Exception ex)
{
LogTransportSendFailed(Name, id, ex);
throw new IOException("Failed to send message.", ex);
}
}
/// <inheritdoc/>
public override async ValueTask DisposeAsync()
{
await CleanupAsync(cancellationToken: CancellationToken.None).ConfigureAwait(false);
// Ensure the channel is always completed after disposal, even if CleanupAsync
// returned early because another caller (e.g. ReadMessagesAsync) was already
// running cleanup. SetDisconnected is idempotent—if the channel was already
// completed by the other cleanup path, this is a no-op.
SetDisconnected();
}
private async Task ReadMessagesAsync(CancellationToken cancellationToken)
{
Exception? error = null;
try
{
LogTransportEnteringReadMessagesLoop(Name);
while (true)
{
if (await _serverOutput.ReadLineAsync(cancellationToken).ConfigureAwait(false) is not string line)
{
LogTransportEndOfStream(Name);
break;
}
if (string.IsNullOrWhiteSpace(line))
{
continue;
}
LogTransportReceivedMessageSensitive(Name, line);
await ProcessMessageAsync(line, cancellationToken).ConfigureAwait(false);
}
}
catch (OperationCanceledException)
{
LogTransportReadMessagesCancelled(Name);
}
catch (Exception ex)
{
error = ex;
LogTransportReadMessagesFailed(Name, ex);
}
finally
{
_readTask = null;
await CleanupAsync(error, cancellationToken).ConfigureAwait(false);
}
}
private async Task ProcessMessageAsync(string line, CancellationToken cancellationToken)
{
try
{
var message = (JsonRpcMessage?)JsonSerializer.Deserialize(line.AsSpan().Trim(), McpJsonUtilities.DefaultOptions.GetTypeInfo(typeof(JsonRpcMessage)));
if (message != null)
{
await WriteMessageAsync(message, cancellationToken).ConfigureAwait(false);
}
else
{
LogTransportMessageParseUnexpectedTypeSensitive(Name, line);
}
}
catch (JsonException ex)
{
if (Logger.IsEnabled(LogLevel.Trace))
{
LogTransportMessageParseFailedSensitive(Name, line, ex);
}
else
{
LogTransportMessageParseFailed(Name, ex);
}
}
}
/// <summary>
/// Cancels the shutdown token to signal that the transport is shutting down,
/// without performing any other cleanup.
/// </summary>
protected void CancelShutdown()
{
_shutdownCts.Cancel();
}
protected virtual async ValueTask CleanupAsync(Exception? error = null, CancellationToken cancellationToken = default)
{
LogTransportShuttingDown(Name);
await _shutdownCts.CancelAsync().ConfigureAwait(false);
if (Interlocked.Exchange(ref _readTask, null) is Task readTask)
{
try
{
await readTask.WaitAsync(TimeSpan.FromSeconds(5), cancellationToken).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
}
catch (Exception ex)
{
LogTransportCleanupReadTaskFailed(Name, ex);
}
}
SetDisconnected(error);
LogTransportShutDown(Name);
}
}