Class McpSession
- Namespace
- ModelContextProtocol
- Assembly
- ModelContextProtocol.Core.dll
Represents a client or server Model Context Protocol (MCP) session.
public abstract class McpSession : IAsyncDisposable
- Inheritance
-
McpSession
- Implements
- Derived
- Inherited Members
Remarks
The MCP session provides the core communication functionality used by both clients and servers:
- Sending JSON-RPC requests and receiving responses.
- Sending notifications to the connected session.
- Registering handlers for receiving notifications.
McpSession serves as the base interface for both McpClient and McpServer interfaces, providing the common functionality needed for MCP protocol communication. Most applications will use these more specific interfaces rather than working with McpSession directly.
All MCP sessions should be properly disposed after use as they implement IAsyncDisposable.
Properties
NegotiatedProtocolVersion
Gets the negotiated protocol version for the current MCP session.
public abstract string? NegotiatedProtocolVersion { get; }
Property Value
Remarks
Returns the protocol version negotiated during session initialization, or null if initialization hasn't yet occurred.
SessionId
Gets an identifier associated with the current MCP session.
public abstract string? SessionId { get; }
Property Value
Remarks
Typically populated in transports supporting multiple sessions such as Streamable HTTP or SSE. Can return null if the session hasn't initialized or if the transport doesn't support multiple sessions (as is the case with STDIO).
Methods
DisposeAsync()
Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources asynchronously.
public abstract ValueTask DisposeAsync()
Returns
- ValueTask
A task that represents the asynchronous dispose operation.
NotifyProgressAsync(ProgressToken, ProgressNotificationValue, CancellationToken)
Notifies the connected session of progress for a long-running operation.
public Task NotifyProgressAsync(ProgressToken progressToken, ProgressNotificationValue progress, CancellationToken cancellationToken = default)
Parameters
progressToken
ProgressTokenThe ProgressToken identifying the operation for which progress is being reported.
progress
ProgressNotificationValueThe progress update to send, containing information such as percentage complete or status message.
cancellationToken
CancellationTokenThe CancellationToken to monitor for cancellation requests. The default is None.
Returns
- Task
A task representing the completion of the notification operation (not the operation being tracked).
Remarks
This method sends a progress notification to the connected session using the Model Context Protocol's standardized progress notification format. Progress updates are identified by a ProgressToken that allows the recipient to correlate multiple updates with a specific long-running operation.
Progress notifications are sent asynchronously and don't block the operation from continuing.
Exceptions
- ArgumentNullException
The current session instance is null.
RegisterNotificationHandler(string, Func<JsonRpcNotification, CancellationToken, ValueTask>)
Registers a handler to be invoked when a notification for the specified method is received.
public abstract IAsyncDisposable RegisterNotificationHandler(string method, Func<JsonRpcNotification, CancellationToken, ValueTask> handler)
Parameters
method
stringThe notification method.
handler
Func<JsonRpcNotification, CancellationToken, ValueTask>The handler to be invoked.
Returns
- IAsyncDisposable
An IDisposable that will remove the registered handler when disposed.
SendMessageAsync(JsonRpcMessage, CancellationToken)
Sends a JSON-RPC message to the connected session.
public abstract Task SendMessageAsync(JsonRpcMessage message, CancellationToken cancellationToken = default)
Parameters
message
JsonRpcMessageThe JSON-RPC message to send. This can be any type that implements JsonRpcMessage, such as JsonRpcRequest, JsonRpcResponse, JsonRpcNotification, or JsonRpcError.
cancellationToken
CancellationTokenThe CancellationToken to monitor for cancellation requests. The default is None.
Returns
- Task
A task that represents the asynchronous send operation.
Remarks
This method provides low-level access to send any JSON-RPC message. For specific message types, consider using the higher-level methods such as SendRequestAsync(JsonRpcRequest, CancellationToken) or methods on this class that provide a simpler API.
The method will serialize the message and transmit it using the underlying transport mechanism.
Exceptions
- InvalidOperationException
The transport is not connected.
- ArgumentNullException
message
is null.
SendNotificationAsync(string, CancellationToken)
Sends a parameterless notification to the connected session.
public Task SendNotificationAsync(string method, CancellationToken cancellationToken = default)
Parameters
method
stringThe notification method name.
cancellationToken
CancellationTokenThe CancellationToken to monitor for cancellation requests. The default is None.
Returns
- Task
A task that represents the asynchronous send operation.
Remarks
This method sends a notification without any parameters. Notifications are one-way messages that don't expect a response. They are commonly used for events, status updates, or to signal changes in state.
SendNotificationAsync<TParameters>(string, TParameters, JsonSerializerOptions?, CancellationToken)
Sends a notification with parameters to the connected session.
public Task SendNotificationAsync<TParameters>(string method, TParameters parameters, JsonSerializerOptions? serializerOptions = null, CancellationToken cancellationToken = default)
Parameters
method
stringThe JSON-RPC method name for the notification.
parameters
TParametersObject representing the notification parameters.
serializerOptions
JsonSerializerOptionsThe options governing parameter serialization. If null, default options are used.
cancellationToken
CancellationTokenThe CancellationToken to monitor for cancellation requests. The default is None.
Returns
- Task
A task that represents the asynchronous send operation.
Type Parameters
TParameters
The type of the notification parameters to serialize.
Remarks
This method sends a notification with parameters to the connected session. Notifications are one-way messages that don't expect a response, commonly used for events, status updates, or signaling changes.
The parameters object is serialized to JSON according to the provided serializer options or the default options if none are specified.
The Model Context Protocol defines several standard notification methods in NotificationMethods, but custom methods can also be used for application-specific notifications.
SendRequestAsync(JsonRpcRequest, CancellationToken)
Sends a JSON-RPC request to the connected session and waits for a response.
public abstract Task<JsonRpcResponse> SendRequestAsync(JsonRpcRequest request, CancellationToken cancellationToken = default)
Parameters
request
JsonRpcRequestThe JSON-RPC request to send.
cancellationToken
CancellationTokenThe CancellationToken to monitor for cancellation requests. The default is None.
Returns
- Task<JsonRpcResponse>
A task containing the session's response.
Remarks
This method provides low-level access to send raw JSON-RPC requests. For most use cases, consider using the strongly-typed methods that provide a more convenient API.
Exceptions
- InvalidOperationException
The transport is not connected, or another error occurs during request processing.
- McpException
An error occurred during request processing.
SendRequestAsync<TParameters, TResult>(string, TParameters, JsonSerializerOptions?, RequestId, CancellationToken)
Sends a JSON-RPC request and attempts to deserialize the result to TResult
.
public ValueTask<TResult> SendRequestAsync<TParameters, TResult>(string method, TParameters parameters, JsonSerializerOptions? serializerOptions = null, RequestId requestId = default, CancellationToken cancellationToken = default) where TResult : notnull
Parameters
method
stringThe JSON-RPC method name to invoke.
parameters
TParametersObject representing the request parameters.
serializerOptions
JsonSerializerOptionsThe options governing request serialization.
requestId
RequestIdThe request id for the request.
cancellationToken
CancellationTokenThe CancellationToken to monitor for cancellation requests. The default is None.
Returns
- ValueTask<TResult>
A task that represents the asynchronous operation. The task result contains the deserialized result.
Type Parameters
TParameters
The type of the request parameters to serialize from.
TResult
The type of the result to deserialize to.