using Microsoft.Extensions.Logging;
using ModelContextProtocol.Client;
namespace ModelContextProtocol.Protocol;
///
/// Provides an implemented around a pair of input/output streams.
///
///
/// This transport is useful for scenarios where you already have established streams for communication,
/// such as custom network protocols, pipe connections, or for testing purposes. It works with any
/// readable and writable streams.
///
public sealed class StreamClientTransport : IClientTransport
{
private readonly Stream _serverInput;
private readonly Stream _serverOutput;
private readonly ILoggerFactory? _loggerFactory;
///
/// Initializes a new instance of the class.
///
///
/// The stream representing the connected server's input.
/// Writes to this stream will be sent to the server.
///
///
/// The stream representing the connected server's output.
/// Reads from this stream will receive messages from the server.
///
/// A logger factory for creating loggers.
/// or is .
public StreamClientTransport(
Stream serverInput, Stream serverOutput, ILoggerFactory? loggerFactory = null)
{
Throw.IfNull(serverInput);
Throw.IfNull(serverOutput);
_serverInput = serverInput;
_serverOutput = serverOutput;
_loggerFactory = loggerFactory;
}
///
public string Name => "in-memory-stream";
///
public Task ConnectAsync(CancellationToken cancellationToken = default)
{
return Task.FromResult(new StreamClientSessionTransport(
_serverInput,
_serverOutput,
encoding: null,
"Client (stream)",
_loggerFactory));
}
}