Initial commit
This commit is contained in:
commit
fdbd94b3f9
1 changed files with 2833 additions and 0 deletions
77
src/mcpdotnet/Protocol/Transport/TransportBase.cs
Normal file
77
src/mcpdotnet/Protocol/Transport/TransportBase.cs
Normal file
|
|
@ -0,0 +1,77 @@
|
|||
// Protocol/Transport/IMcpTransport.cs
|
||||
namespace McpDotNet.Protocol.Transport;
|
||||
|
||||
using System.Text.Json;
|
||||
using System.Threading.Channels;
|
||||
using global::McpDotNet.Protocol.Messages;
|
||||
using McpDotNet.Utils.Json;
|
||||
|
||||
// Protocol/Transport/TransportBase.cs
|
||||
|
||||
/// <summary>
|
||||
/// Base class for implementing MCP transports with common functionality.
|
||||
/// </summary>
|
||||
public abstract class TransportBase : IMcpTransport
|
||||
{
|
||||
private readonly Channel<IJsonRpcMessage> _messageChannel;
|
||||
private bool _isConnected;
|
||||
private readonly JsonSerializerOptions _jsonOptions = new JsonSerializerOptions().ConfigureForMcp();
|
||||
|
||||
protected TransportBase()
|
||||
{
|
||||
// Unbounded channel to prevent blocking on writes
|
||||
_messageChannel = Channel.CreateUnbounded<IJsonRpcMessage>(new UnboundedChannelOptions
|
||||
{
|
||||
SingleReader = true,
|
||||
SingleWriter = true,
|
||||
});
|
||||
}
|
||||
|
||||
/// <inheritdoc/>
|
||||
public bool IsConnected => _isConnected;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public ChannelReader<IJsonRpcMessage> MessageReader => _messageChannel.Reader;
|
||||
|
||||
/// <inheritdoc/>
|
||||
public abstract Task ConnectAsync(CancellationToken cancellationToken = default);
|
||||
|
||||
/// <inheritdoc/>
|
||||
public abstract Task SendMessageAsync(IJsonRpcMessage message, CancellationToken cancellationToken = default);
|
||||
|
||||
/// <inheritdoc/>
|
||||
public abstract ValueTask DisposeAsync();
|
||||
|
||||
/// <summary>
|
||||
/// Writes a message to the message channel.
|
||||
/// </summary>
|
||||
/// <param name="message">The message to write.</param>
|
||||
/// <param name="cancellationToken">Token to cancel the operation.</param>
|
||||
protected async Task WriteMessageAsync(IJsonRpcMessage message, CancellationToken cancellationToken = default)
|
||||
{
|
||||
if (!_isConnected)
|
||||
{
|
||||
throw new McpTransportException("Transport is not connected");
|
||||
}
|
||||
|
||||
await _messageChannel.Writer.WriteAsync(message, cancellationToken);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Sets the connected state of the transport.
|
||||
/// </summary>
|
||||
/// <param name="isConnected">Whether the transport is connected.</param>
|
||||
protected void SetConnected(bool isConnected)
|
||||
{
|
||||
if (_isConnected == isConnected)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_isConnected = isConnected;
|
||||
if (!isConnected)
|
||||
{
|
||||
_messageChannel.Writer.Complete();
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue