TheDocumentation Index
Fetch the complete documentation index at: https://mintlify.com/modelcontextprotocol/csharp-sdk/llms.txt
Use this file to discover all available pages before exploring further.
McpSession class represents a client or server Model Context Protocol (MCP) session, providing core communication functionality.
Namespace
Inheritance
McpSession → IAsyncDisposable
Overview
TheMcpSession class serves as the base class for both McpClient and McpServer, providing the common functionality needed for MCP protocol communication:
- Sending JSON-RPC requests and receiving responses
- Sending notifications to the connected session
- Registering handlers for receiving notifications
McpClient or McpServer classes rather than working with McpSession directly.
Properties
SessionId
Gets an identifier associated with the current MCP session.null if the session hasn’t initialized or if the transport doesn’t support multiple sessions (as is the case with STDIO).
NegotiatedProtocolVersion
Gets the negotiated protocol version for the current MCP session.null if initialization hasn’t yet occurred.
Methods
SendRequestAsync
Sends a JSON-RPC request to the connected session and waits for a response.The JSON-RPC request to send.
The cancellation token to monitor for cancellation requests.
InvalidOperationException: The transport is not connected, or another error occurred during request processing.McpException: An error occurred during request processing.
SendMessageAsync
Sends a JSON-RPC message to the connected session.The JSON-RPC message to send. This can be any type that implements JsonRpcMessage, such as JsonRpcRequest, JsonRpcResponse, JsonRpcNotification, or JsonRpcError.
The cancellation token to monitor for cancellation requests.
InvalidOperationException: The transport is not connected.ArgumentNullException:messageis null.
RegisterNotificationHandler
Registers a handler to be invoked when a notification for the specified method is received.The notification method.
The handler to be invoked.
IAsyncDisposable that will remove the registered handler when disposed.
Exceptions:
ArgumentNullException:methodorhandleris null.ArgumentException:methodis empty or composed entirely of whitespace.
Example
DisposeAsync
Disposes the session asynchronously.Example
Usage Guidelines
Proper Disposal
Always dispose of MCP sessions to ensure proper cleanup:Notification Handlers
When registering notification handlers, ensure they are properly disposed:See Also
- McpClient - Client implementation extending McpSession
- Protocol Types - MCP protocol types and messages
- Transports - Transport implementations