Class McpClient
- Namespace
- ModelContextProtocol.Client
- Assembly
- ModelContextProtocol.Core.dll
Represents an instance of a Model Context Protocol (MCP) client session that connects to and communicates with an MCP server.
public abstract class McpClient : McpSession, IAsyncDisposable
- Inheritance
-
McpClient
- Implements
- Inherited Members
Properties
ServerCapabilities
Gets the capabilities supported by the connected server.
public abstract ServerCapabilities ServerCapabilities { get; }
Property Value
Exceptions
- InvalidOperationException
The client is not connected.
ServerInfo
Gets the implementation information of the connected server.
public abstract Implementation ServerInfo { get; }
Property Value
Remarks
This property provides identification details about the connected server, including its name and version. It is populated during the initialization handshake and is available after a successful connection.
This information can be useful for logging, debugging, compatibility checks, and displaying server information to users.
Exceptions
- InvalidOperationException
The client is not connected.
ServerInstructions
Gets any instructions describing how to use the connected server and its features.
public abstract string? ServerInstructions { get; }
Property Value
Remarks
This property contains instructions provided by the server during initialization that explain how to effectively use its capabilities. These instructions can include details about available tools, expected input formats, limitations, or any other helpful information.
This can be used by clients to improve an LLM's understanding of available tools, prompts, and resources. It can be thought of like a "hint" to the model and can be added to a system prompt.
Methods
CallToolAsTaskAsync(string, IReadOnlyDictionary<string, object?>?, McpTaskMetadata?, IProgress<ProgressNotificationValue>?, RequestOptions?, CancellationToken)
Invokes a tool on the server as a task for long-running operations.
[Experimental("MCPEXP001", UrlFormat = "https://github.com/modelcontextprotocol/csharp-sdk/blob/main/docs/list-of-diagnostics.md#mcpexp001")]
public ValueTask<McpTask> CallToolAsTaskAsync(string toolName, IReadOnlyDictionary<string, object?>? arguments = null, McpTaskMetadata? taskMetadata = null, IProgress<ProgressNotificationValue>? progress = null, RequestOptions? options = null, CancellationToken cancellationToken = default)
Parameters
toolNamestringThe name of the tool to call on the server.
argumentsIReadOnlyDictionary<string, object>An optional dictionary of arguments to pass to the tool.
taskMetadataMcpTaskMetadataMetadata for task augmentation, including optional TTL. If null, an empty metadata is used.
progressIProgress<ProgressNotificationValue>An optional progress reporter for server notifications.
optionsRequestOptionsOptional request options including metadata, serialization settings, and progress tracking.
cancellationTokenCancellationTokenThe CancellationToken to monitor for cancellation requests. The default is None.
Returns
- ValueTask<McpTask>
An McpTask representing the created task. Use GetTaskAsync(string, RequestOptions?, CancellationToken) to poll for status updates and GetTaskResultAsync(string, RequestOptions?, CancellationToken) to retrieve the final result.
Remarks
Task-augmented tool calls allow long-running operations to be executed asynchronously. Instead of blocking until the tool completes, the server immediately returns a task identifier that can be used to poll for status updates and retrieve the final result.
The server must advertise task support via capabilities.tasks.requests.tools.call and the tool
must have execution.taskSupport set to "optional" or "required".
Exceptions
- ArgumentNullException
toolNameis null.- McpException
The request failed or the server returned an error response.
CallToolAsync(CallToolRequestParams, CancellationToken)
Invokes a tool on the server.
public ValueTask<CallToolResult> CallToolAsync(CallToolRequestParams requestParams, CancellationToken cancellationToken = default)
Parameters
requestParamsCallToolRequestParamsThe request parameters to send in the request.
cancellationTokenCancellationTokenThe CancellationToken to monitor for cancellation requests. The default is None.
Returns
- ValueTask<CallToolResult>
The result of the request.
Exceptions
- ArgumentNullException
requestParamsis null.- McpException
The request failed or the server returned an error response.
CallToolAsync(string, IReadOnlyDictionary<string, object?>?, IProgress<ProgressNotificationValue>?, RequestOptions?, CancellationToken)
Invokes a tool on the server.
public ValueTask<CallToolResult> CallToolAsync(string toolName, IReadOnlyDictionary<string, object?>? arguments = null, IProgress<ProgressNotificationValue>? progress = null, RequestOptions? options = null, CancellationToken cancellationToken = default)
Parameters
toolNamestringThe name of the tool to call on the server.
argumentsIReadOnlyDictionary<string, object>An optional dictionary of arguments to pass to the tool.
progressIProgress<ProgressNotificationValue>An optional progress reporter for server notifications.
optionsRequestOptionsOptional request options including metadata, serialization settings, and progress tracking.
cancellationTokenCancellationTokenThe CancellationToken to monitor for cancellation requests. The default is None.
Returns
- ValueTask<CallToolResult>
The CallToolResult from the tool execution.
Exceptions
- ArgumentNullException
toolNameis null.- McpException
The request failed or the server returned an error response.
CancelTaskAsync(string, RequestOptions?, CancellationToken)
Cancels a running task on the server.
[Experimental("MCPEXP001", UrlFormat = "https://github.com/modelcontextprotocol/csharp-sdk/blob/main/docs/list-of-diagnostics.md#mcpexp001")]
public ValueTask<McpTask> CancelTaskAsync(string taskId, RequestOptions? options = null, CancellationToken cancellationToken = default)
Parameters
taskIdstringThe unique identifier of the task to cancel.
optionsRequestOptionsOptional request options including metadata, serialization settings, and progress tracking.
cancellationTokenCancellationTokenThe CancellationToken to monitor for cancellation requests. The default is None.
Returns
Remarks
Cancelling a task requests that the server stop execution. The server may not immediately cancel the task, and may choose to allow the task to complete if it's close to finishing.
Exceptions
- ArgumentNullException
taskIdis null.- ArgumentException
taskIdis empty or composed entirely of whitespace.
CompleteAsync(CompleteRequestParams, CancellationToken)
Requests completion suggestions for a prompt argument or resource reference.
public ValueTask<CompleteResult> CompleteAsync(CompleteRequestParams requestParams, CancellationToken cancellationToken = default)
Parameters
requestParamsCompleteRequestParamsThe request parameters to send in the request.
cancellationTokenCancellationTokenThe CancellationToken to monitor for cancellation requests. The default is None.
Returns
- ValueTask<CompleteResult>
The result of the request.
Exceptions
- ArgumentNullException
requestParamsis null.- McpException
The request failed or the server returned an error response.
CompleteAsync(Reference, string, string, RequestOptions?, CancellationToken)
Requests completion suggestions for a prompt argument or resource reference.
public ValueTask<CompleteResult> CompleteAsync(Reference reference, string argumentName, string argumentValue, RequestOptions? options = null, CancellationToken cancellationToken = default)
Parameters
referenceReferenceThe reference object specifying the type and optional URI or name.
argumentNamestringThe name of the argument for which completions are requested.
argumentValuestringThe current value of the argument, used to filter relevant completions.
optionsRequestOptionsOptional request options including metadata, serialization settings, and progress tracking.
cancellationTokenCancellationTokenThe CancellationToken to monitor for cancellation requests. The default is None.
Returns
- ValueTask<CompleteResult>
A CompleteResult containing completion suggestions.
Exceptions
- ArgumentNullException
referenceorargumentNameis null.- ArgumentException
argumentNameis empty or composed entirely of whitespace.- McpException
The request failed or the server returned an error response.
CreateAsync(IClientTransport, McpClientOptions?, ILoggerFactory?, CancellationToken)
Creates an McpClient, connecting it to the specified server.
public static Task<McpClient> CreateAsync(IClientTransport clientTransport, McpClientOptions? clientOptions = null, ILoggerFactory? loggerFactory = null, CancellationToken cancellationToken = default)
Parameters
clientTransportIClientTransportThe transport instance used to communicate with the server.
clientOptionsMcpClientOptionsA client configuration object that specifies client capabilities and protocol version. If null, details based on the current process are used.
loggerFactoryILoggerFactoryA logger factory for creating loggers for clients.
cancellationTokenCancellationTokenThe CancellationToken to monitor for cancellation requests. The default is None.
Returns
Remarks
When using an HTTP-based transport (such as HttpClientTransport), this method may throw HttpRequestException if there is a problem establishing the connection to the MCP server.
If the server requires authentication and credentials are not provided or are invalid, an HttpRequestException with an HTTP 401 Unauthorized status code will be thrown. To authenticate with a protected server, configure the OAuth property of the transport with appropriate credentials before calling this method.
Exceptions
- ArgumentNullException
clientTransportis null.- HttpRequestException
An error occurred while connecting to the server over HTTP.
- McpException
The server returned an error response during initialization.
GetPromptAsync(GetPromptRequestParams, CancellationToken)
Retrieves a list of available prompts from the server.
public ValueTask<GetPromptResult> GetPromptAsync(GetPromptRequestParams requestParams, CancellationToken cancellationToken = default)
Parameters
requestParamsGetPromptRequestParamsThe request parameters to send in the request.
cancellationTokenCancellationTokenThe CancellationToken to monitor for cancellation requests. The default is None.
Returns
- ValueTask<GetPromptResult>
The result of the request as provided by the server.
Exceptions
- ArgumentNullException
requestParamsis null.- McpException
The request failed or the server returned an error response.
GetPromptAsync(string, IReadOnlyDictionary<string, object?>?, RequestOptions?, CancellationToken)
Retrieves a specific prompt from the MCP server.
public ValueTask<GetPromptResult> GetPromptAsync(string name, IReadOnlyDictionary<string, object?>? arguments = null, RequestOptions? options = null, CancellationToken cancellationToken = default)
Parameters
namestringThe name of the prompt to retrieve.
argumentsIReadOnlyDictionary<string, object>Optional arguments for the prompt. The dictionary keys are parameter names, and the values are the argument values.
optionsRequestOptionsOptional request options including metadata, serialization settings, and progress tracking.
cancellationTokenCancellationTokenThe CancellationToken to monitor for cancellation requests. The default is None.
Returns
- ValueTask<GetPromptResult>
A task containing the prompt's result with content and messages.
Exceptions
- ArgumentNullException
nameis null.- ArgumentException
nameis empty or composed entirely of whitespace.- McpException
The request failed or the server returned an error response.
GetTaskAsync(string, RequestOptions?, CancellationToken)
Retrieves the current state of a specific task from the server.
[Experimental("MCPEXP001", UrlFormat = "https://github.com/modelcontextprotocol/csharp-sdk/blob/main/docs/list-of-diagnostics.md#mcpexp001")]
public ValueTask<McpTask> GetTaskAsync(string taskId, RequestOptions? options = null, CancellationToken cancellationToken = default)
Parameters
taskIdstringThe unique identifier of the task to retrieve.
optionsRequestOptionsOptional request options including metadata, serialization settings, and progress tracking.
cancellationTokenCancellationTokenThe CancellationToken to monitor for cancellation requests. The default is None.
Returns
Exceptions
- ArgumentNullException
taskIdis null.- ArgumentException
taskIdis empty or composed entirely of whitespace.
GetTaskResultAsync(string, RequestOptions?, CancellationToken)
Retrieves the result of a completed task, blocking until the task reaches a terminal state.
[Experimental("MCPEXP001", UrlFormat = "https://github.com/modelcontextprotocol/csharp-sdk/blob/main/docs/list-of-diagnostics.md#mcpexp001")]
public ValueTask<JsonElement> GetTaskResultAsync(string taskId, RequestOptions? options = null, CancellationToken cancellationToken = default)
Parameters
taskIdstringThe unique identifier of the task whose result to retrieve.
optionsRequestOptionsOptional request options including metadata, serialization settings, and progress tracking.
cancellationTokenCancellationTokenThe CancellationToken to monitor for cancellation requests. The default is None.
Returns
- ValueTask<JsonElement>
The raw JSON result of the task.
Remarks
This method sends a tasks/result request to the server, which will block until the task completes if it hasn't already. The server handles all polling logic internally.
Exceptions
- ArgumentNullException
taskIdis null.- ArgumentException
taskIdis empty or composed entirely of whitespace.
ListPromptsAsync(ListPromptsRequestParams, CancellationToken)
Retrieves a list of available prompts from the server.
public ValueTask<ListPromptsResult> ListPromptsAsync(ListPromptsRequestParams requestParams, CancellationToken cancellationToken = default)
Parameters
requestParamsListPromptsRequestParamsThe request parameters to send in the request.
cancellationTokenCancellationTokenThe CancellationToken to monitor for cancellation requests. The default is None.
Returns
- ValueTask<ListPromptsResult>
The result of the request as provided by the server.
Remarks
The ListPromptsAsync(RequestOptions?, CancellationToken) overload retrieves all prompts by automatically handling pagination. This overload works with the lower-level ListPromptsRequestParams and ListPromptsResult, returning the raw result from the server. Any pagination needs to be managed by the caller.
Exceptions
- ArgumentNullException
requestParamsis null.- McpException
The request failed or the server returned an error response.
ListPromptsAsync(RequestOptions?, CancellationToken)
Retrieves a list of available prompts from the server.
public ValueTask<IList<McpClientPrompt>> ListPromptsAsync(RequestOptions? options = null, CancellationToken cancellationToken = default)
Parameters
optionsRequestOptionsOptional request options including metadata, serialization settings, and progress tracking.
cancellationTokenCancellationTokenThe CancellationToken to monitor for cancellation requests. The default is None.
Returns
- ValueTask<IList<McpClientPrompt>>
A list of all available prompts as McpClientPrompt instances.
Exceptions
- McpException
The request failed or the server returned an error response.
ListResourceTemplatesAsync(ListResourceTemplatesRequestParams, CancellationToken)
Retrieves a list of available resource templates from the server.
public ValueTask<ListResourceTemplatesResult> ListResourceTemplatesAsync(ListResourceTemplatesRequestParams requestParams, CancellationToken cancellationToken = default)
Parameters
requestParamsListResourceTemplatesRequestParamsThe request parameters to send in the request.
cancellationTokenCancellationTokenThe CancellationToken to monitor for cancellation requests. The default is None.
Returns
- ValueTask<ListResourceTemplatesResult>
The result of the request as provided by the server.
Remarks
The ListResourceTemplatesAsync(RequestOptions?, CancellationToken) overload retrieves all resource templates by automatically handling pagination. This overload works with the lower-level ListResourceTemplatesRequestParams and ListResourceTemplatesResult, returning the raw result from the server. Any pagination needs to be managed by the caller.
Exceptions
- ArgumentNullException
requestParamsis null.- McpException
The request failed or the server returned an error response.
ListResourceTemplatesAsync(RequestOptions?, CancellationToken)
Retrieves a list of available resource templates from the server.
public ValueTask<IList<McpClientResourceTemplate>> ListResourceTemplatesAsync(RequestOptions? options = null, CancellationToken cancellationToken = default)
Parameters
optionsRequestOptionsOptional request options including metadata, serialization settings, and progress tracking.
cancellationTokenCancellationTokenThe CancellationToken to monitor for cancellation requests. The default is None.
Returns
- ValueTask<IList<McpClientResourceTemplate>>
A list of all available resource templates as ResourceTemplate instances.
Exceptions
- McpException
The request failed or the server returned an error response.
ListResourcesAsync(ListResourcesRequestParams, CancellationToken)
Retrieves a list of available resources from the server.
public ValueTask<ListResourcesResult> ListResourcesAsync(ListResourcesRequestParams requestParams, CancellationToken cancellationToken = default)
Parameters
requestParamsListResourcesRequestParamsThe request parameters to send in the request.
cancellationTokenCancellationTokenThe CancellationToken to monitor for cancellation requests. The default is None.
Returns
- ValueTask<ListResourcesResult>
The result of the request as provided by the server.
Remarks
The ListResourcesAsync(RequestOptions?, CancellationToken) overload retrieves all resources by automatically handling pagination. This overload works with the lower-level ListResourcesRequestParams and ListResourcesResult, returning the raw result from the server. Any pagination needs to be managed by the caller.
Exceptions
- ArgumentNullException
requestParamsis null.- McpException
The request failed or the server returned an error response.
ListResourcesAsync(RequestOptions?, CancellationToken)
Retrieves a list of available resources from the server.
public ValueTask<IList<McpClientResource>> ListResourcesAsync(RequestOptions? options = null, CancellationToken cancellationToken = default)
Parameters
optionsRequestOptionsOptional request options including metadata, serialization settings, and progress tracking.
cancellationTokenCancellationTokenThe CancellationToken to monitor for cancellation requests. The default is None.
Returns
- ValueTask<IList<McpClientResource>>
A list of all available resources as Resource instances.
Exceptions
- McpException
The request failed or the server returned an error response.
ListTasksAsync(ListTasksRequestParams, CancellationToken)
Retrieves a list of tasks from the server.
[Experimental("MCPEXP001", UrlFormat = "https://github.com/modelcontextprotocol/csharp-sdk/blob/main/docs/list-of-diagnostics.md#mcpexp001")]
public ValueTask<ListTasksResult> ListTasksAsync(ListTasksRequestParams requestParams, CancellationToken cancellationToken = default)
Parameters
requestParamsListTasksRequestParamsThe request parameters to send in the request.
cancellationTokenCancellationTokenThe CancellationToken to monitor for cancellation requests. The default is None.
Returns
- ValueTask<ListTasksResult>
The result of the request as provided by the server.
Remarks
The ListTasksAsync(RequestOptions?, CancellationToken) overload retrieves all tasks by automatically handling pagination. This overload works with the lower-level ListTasksRequestParams and ListTasksResult, returning the raw result from the server. Any pagination needs to be managed by the caller.
Exceptions
- ArgumentNullException
requestParamsis null.
ListTasksAsync(RequestOptions?, CancellationToken)
Retrieves a list of all tasks from the server.
[Experimental("MCPEXP001", UrlFormat = "https://github.com/modelcontextprotocol/csharp-sdk/blob/main/docs/list-of-diagnostics.md#mcpexp001")]
public ValueTask<IList<McpTask>> ListTasksAsync(RequestOptions? options = null, CancellationToken cancellationToken = default)
Parameters
optionsRequestOptionsOptional request options including metadata, serialization settings, and progress tracking.
cancellationTokenCancellationTokenThe CancellationToken to monitor for cancellation requests. The default is None.
Returns
ListToolsAsync(ListToolsRequestParams, CancellationToken)
Retrieves a list of available tools from the server.
public ValueTask<ListToolsResult> ListToolsAsync(ListToolsRequestParams requestParams, CancellationToken cancellationToken = default)
Parameters
requestParamsListToolsRequestParamsThe request parameters to send in the request.
cancellationTokenCancellationTokenThe CancellationToken to monitor for cancellation requests. The default is None.
Returns
- ValueTask<ListToolsResult>
The result of the request as provided by the server.
Remarks
The ListToolsAsync(RequestOptions?, CancellationToken) overload retrieves all tools by automatically handling pagination. This overload works with the lower-level ListToolsRequestParams and ListToolsResult, returning the raw result from the server. Any pagination needs to be managed by the caller.
Exceptions
- ArgumentNullException
requestParamsis null.- McpException
The request failed or the server returned an error response.
ListToolsAsync(RequestOptions?, CancellationToken)
Retrieves a list of available tools from the server.
public ValueTask<IList<McpClientTool>> ListToolsAsync(RequestOptions? options = null, CancellationToken cancellationToken = default)
Parameters
optionsRequestOptionsOptional request options including metadata, serialization settings, and progress tracking.
cancellationTokenCancellationTokenThe CancellationToken to monitor for cancellation requests. The default is None.
Returns
- ValueTask<IList<McpClientTool>>
A list of all available tools as McpClientTool instances.
Exceptions
- McpException
The request failed or the server returned an error response.
PingAsync(PingRequestParams, CancellationToken)
Sends a ping request to verify server connectivity.
public ValueTask<PingResult> PingAsync(PingRequestParams requestParams, CancellationToken cancellationToken = default)
Parameters
requestParamsPingRequestParamsThe request parameters to send in the request.
cancellationTokenCancellationTokenThe CancellationToken to monitor for cancellation requests. The default is None.
Returns
- ValueTask<PingResult>
A task containing the ping result.
Exceptions
- ArgumentNullException
requestParamsis null.- McpException
The server cannot be reached or returned an error response.
PingAsync(RequestOptions?, CancellationToken)
Sends a ping request to verify server connectivity.
public ValueTask<PingResult> PingAsync(RequestOptions? options = null, CancellationToken cancellationToken = default)
Parameters
optionsRequestOptionsOptional request options including metadata, serialization settings, and progress tracking.
cancellationTokenCancellationTokenThe CancellationToken to monitor for cancellation requests. The default is None.
Returns
- ValueTask<PingResult>
A task containing the ping result.
Exceptions
- McpException
The server cannot be reached or returned an error response.
PollTaskUntilCompleteAsync(string, RequestOptions?, CancellationToken)
Polls a task until it reaches a terminal status (completed, failed, or cancelled).
[Experimental("MCPEXP001", UrlFormat = "https://github.com/modelcontextprotocol/csharp-sdk/blob/main/docs/list-of-diagnostics.md#mcpexp001")]
public ValueTask<McpTask> PollTaskUntilCompleteAsync(string taskId, RequestOptions? options = null, CancellationToken cancellationToken = default)
Parameters
taskIdstringThe unique identifier of the task to poll.
optionsRequestOptionsOptional request options including metadata, serialization settings, and progress tracking.
cancellationTokenCancellationTokenThe CancellationToken to monitor for cancellation requests. The default is None.
Returns
Remarks
This method repeatedly calls GetTaskAsync(string, RequestOptions?, CancellationToken) until the task reaches a terminal status. It respects the PollInterval returned by the server to determine how long to wait between polling attempts.
For retrieving the actual result of a completed task, use GetTaskResultAsync(string, RequestOptions?, CancellationToken).
Exceptions
- ArgumentNullException
taskIdis null.- ArgumentException
taskIdis empty or composed entirely of whitespace.
ReadResourceAsync(ReadResourceRequestParams, CancellationToken)
Reads a resource from the server.
public ValueTask<ReadResourceResult> ReadResourceAsync(ReadResourceRequestParams requestParams, CancellationToken cancellationToken = default)
Parameters
requestParamsReadResourceRequestParamsThe request parameters to send in the request.
cancellationTokenCancellationTokenThe CancellationToken to monitor for cancellation requests. The default is None.
Returns
- ValueTask<ReadResourceResult>
The result of the request.
Exceptions
- ArgumentNullException
requestParamsis null.- McpException
The request failed or the server returned an error response.
ReadResourceAsync(string, RequestOptions?, CancellationToken)
Reads a resource from the server.
public ValueTask<ReadResourceResult> ReadResourceAsync(string uri, RequestOptions? options = null, CancellationToken cancellationToken = default)
Parameters
uristringThe URI of the resource.
optionsRequestOptionsOptional request options including metadata, serialization settings, and progress tracking.
cancellationTokenCancellationTokenThe CancellationToken to monitor for cancellation requests. The default is None.
Returns
Exceptions
- ArgumentNullException
uriis null.- ArgumentException
uriis empty or composed entirely of whitespace.- McpException
The request failed or the server returned an error response.
ReadResourceAsync(string, IReadOnlyDictionary<string, object?>, RequestOptions?, CancellationToken)
Reads a resource from the server.
public ValueTask<ReadResourceResult> ReadResourceAsync(string uriTemplate, IReadOnlyDictionary<string, object?> arguments, RequestOptions? options = null, CancellationToken cancellationToken = default)
Parameters
uriTemplatestringThe URI template of the resource.
argumentsIReadOnlyDictionary<string, object>Arguments to use to format
uriTemplate.optionsRequestOptionsOptional request options including metadata, serialization settings, and progress tracking.
cancellationTokenCancellationTokenThe CancellationToken to monitor for cancellation requests. The default is None.
Returns
Exceptions
- ArgumentNullException
uriTemplateorargumentsis null.- ArgumentException
uriTemplateis empty or composed entirely of whitespace.- McpException
The request failed or the server returned an error response.
ReadResourceAsync(Uri, RequestOptions?, CancellationToken)
Reads a resource from the server.
public ValueTask<ReadResourceResult> ReadResourceAsync(Uri uri, RequestOptions? options = null, CancellationToken cancellationToken = default)
Parameters
uriUriThe URI of the resource.
optionsRequestOptionsOptional request options including metadata, serialization settings, and progress tracking.
cancellationTokenCancellationTokenThe CancellationToken to monitor for cancellation requests. The default is None.
Returns
Exceptions
- ArgumentNullException
uriis null.- McpException
The request failed or the server returned an error response.
ResumeSessionAsync(IClientTransport, ResumeClientSessionOptions, McpClientOptions?, ILoggerFactory?, CancellationToken)
Recreates an McpClient using an existing transport session without sending a new initialize request.
public static Task<McpClient> ResumeSessionAsync(IClientTransport clientTransport, ResumeClientSessionOptions resumeOptions, McpClientOptions? clientOptions = null, ILoggerFactory? loggerFactory = null, CancellationToken cancellationToken = default)
Parameters
clientTransportIClientTransportThe transport instance already configured to connect to the target server.
resumeOptionsResumeClientSessionOptionsThe metadata captured from the original session that should be applied when resuming.
clientOptionsMcpClientOptionsOptional client settings that should mirror those used to create the original session.
loggerFactoryILoggerFactoryAn optional logger factory for diagnostics.
cancellationTokenCancellationTokenThe CancellationToken to monitor for cancellation requests. The default is None.
Returns
Exceptions
- ArgumentNullException
clientTransport,resumeOptions, ServerCapabilities, or ServerInfo is null.
SetLoggingLevelAsync(LogLevel, RequestOptions?, CancellationToken)
Sets the logging level for the server to control which log messages are sent to the client.
public Task SetLoggingLevelAsync(LogLevel level, RequestOptions? options = null, CancellationToken cancellationToken = default)
Parameters
levelLogLevelThe minimum severity level of log messages to receive from the server.
optionsRequestOptionsOptional request options including metadata, serialization settings, and progress tracking.
cancellationTokenCancellationTokenThe CancellationToken to monitor for cancellation requests. The default is None.
Returns
- Task
A task representing the asynchronous operation.
Exceptions
- McpException
The request failed or the server returned an error response.
SetLoggingLevelAsync(LoggingLevel, RequestOptions?, CancellationToken)
Sets the logging level for the server to control which log messages are sent to the client.
public Task SetLoggingLevelAsync(LoggingLevel level, RequestOptions? options = null, CancellationToken cancellationToken = default)
Parameters
levelLoggingLevelThe minimum severity level of log messages to receive from the server.
optionsRequestOptionsOptional request options including metadata, serialization settings, and progress tracking.
cancellationTokenCancellationTokenThe CancellationToken to monitor for cancellation requests. The default is None.
Returns
- Task
A task representing the asynchronous operation.
Exceptions
- McpException
The request failed or the server returned an error response.
SetLoggingLevelAsync(SetLevelRequestParams, CancellationToken)
Sets the logging level for the server to control which log messages are sent to the client.
public Task SetLoggingLevelAsync(SetLevelRequestParams requestParams, CancellationToken cancellationToken = default)
Parameters
requestParamsSetLevelRequestParamsThe request parameters to send in the request.
cancellationTokenCancellationTokenThe CancellationToken to monitor for cancellation requests. The default is None.
Returns
- Task
The result of the request.
Exceptions
- ArgumentNullException
requestParamsis null.- McpException
The request failed or the server returned an error response.
SubscribeToResourceAsync(SubscribeRequestParams, CancellationToken)
Subscribes to a resource on the server to receive notifications when it changes.
public Task SubscribeToResourceAsync(SubscribeRequestParams requestParams, CancellationToken cancellationToken = default)
Parameters
requestParamsSubscribeRequestParamsThe request parameters to send in the request.
cancellationTokenCancellationTokenThe CancellationToken to monitor for cancellation requests. The default is None.
Returns
- Task
The result of the request.
Remarks
This method subscribes to resource update notifications but does not register a handler. To receive notifications, you must separately call RegisterNotificationHandler(string, Func<JsonRpcNotification, CancellationToken, ValueTask>) with ResourceUpdatedNotification and filter for the specific resource URI. To unsubscribe, call UnsubscribeFromResourceAsync(UnsubscribeRequestParams, CancellationToken) and dispose the handler registration.
For a simpler API that handles both subscription and notification registration in a single call, use SubscribeToResourceAsync(Uri, Func<ResourceUpdatedNotificationParams, CancellationToken, ValueTask>, RequestOptions?, CancellationToken).
Exceptions
- ArgumentNullException
requestParamsis null.- McpException
The request failed or the server returned an error response.
SubscribeToResourceAsync(string, RequestOptions?, CancellationToken)
Subscribes to a resource on the server to receive notifications when it changes.
public Task SubscribeToResourceAsync(string uri, RequestOptions? options = null, CancellationToken cancellationToken = default)
Parameters
uristringThe URI of the resource to which to subscribe.
optionsRequestOptionsOptional request options including metadata, serialization settings, and progress tracking.
cancellationTokenCancellationTokenThe CancellationToken to monitor for cancellation requests. The default is None.
Returns
- Task
A task that represents the asynchronous operation.
Exceptions
- ArgumentNullException
uriis null.- ArgumentException
uriis empty or composed entirely of whitespace.- McpException
The request failed or the server returned an error response.
SubscribeToResourceAsync(string, Func<ResourceUpdatedNotificationParams, CancellationToken, ValueTask>, RequestOptions?, CancellationToken)
Subscribes to a resource on the server and registers a handler for notifications when it changes.
public Task<IAsyncDisposable> SubscribeToResourceAsync(string uri, Func<ResourceUpdatedNotificationParams, CancellationToken, ValueTask> handler, RequestOptions? options = null, CancellationToken cancellationToken = default)
Parameters
uristringThe URI of the resource to which to subscribe.
handlerFunc<ResourceUpdatedNotificationParams, CancellationToken, ValueTask>The handler to invoke when the resource is updated. It receives ResourceUpdatedNotificationParams for the subscribed resource.
optionsRequestOptionsOptional request options including metadata, serialization settings, and progress tracking.
cancellationTokenCancellationTokenThe CancellationToken to monitor for cancellation requests. The default is None.
Returns
- Task<IAsyncDisposable>
A task that completes with an IAsyncDisposable that, when disposed, unsubscribes from the resource and removes the notification handler.
Remarks
This method provides a convenient way to subscribe to resource updates and handle notifications in a single call. The returned IAsyncDisposable manages both the subscription and the notification handler registration. When disposed, it automatically unsubscribes from the resource and removes the handler.
The handler will only be invoked for notifications related to the specified resource URI. Notifications for other resources are filtered out automatically.
Exceptions
- ArgumentNullException
uriorhandleris null.- ArgumentException
uriis empty or composed entirely of whitespace.- McpException
The request failed or the server returned an error response.
SubscribeToResourceAsync(Uri, RequestOptions?, CancellationToken)
Unsubscribes from a resource on the server to stop receiving notifications about its changes.
public Task SubscribeToResourceAsync(Uri uri, RequestOptions? options = null, CancellationToken cancellationToken = default)
Parameters
uriUriThe URI of the resource to which to subscribe.
optionsRequestOptionsOptional request options including metadata, serialization settings, and progress tracking.
cancellationTokenCancellationTokenThe CancellationToken to monitor for cancellation requests. The default is None.
Returns
- Task
A task that represents the asynchronous operation.
Exceptions
- ArgumentNullException
uriis null.- McpException
The request failed or the server returned an error response.
SubscribeToResourceAsync(Uri, Func<ResourceUpdatedNotificationParams, CancellationToken, ValueTask>, RequestOptions?, CancellationToken)
Subscribes to a resource on the server and registers a handler for notifications when it changes.
public Task<IAsyncDisposable> SubscribeToResourceAsync(Uri uri, Func<ResourceUpdatedNotificationParams, CancellationToken, ValueTask> handler, RequestOptions? options = null, CancellationToken cancellationToken = default)
Parameters
uriUriThe URI of the resource to which to subscribe.
handlerFunc<ResourceUpdatedNotificationParams, CancellationToken, ValueTask>The handler to invoke when the resource is updated. It receives ResourceUpdatedNotificationParams for the subscribed resource.
optionsRequestOptionsOptional request options including metadata, serialization settings, and progress tracking.
cancellationTokenCancellationTokenThe CancellationToken to monitor for cancellation requests. The default is None.
Returns
- Task<IAsyncDisposable>
A task that completes with an IAsyncDisposable that, when disposed, unsubscribes from the resource and removes the notification handler.
Remarks
This method provides a convenient way to subscribe to resource updates and handle notifications in a single call. The returned IAsyncDisposable manages both the subscription and the notification handler registration. When disposed, it automatically unsubscribes from the resource and removes the handler.
The handler will only be invoked for notifications related to the specified resource URI. Notifications for other resources are filtered out automatically.
Exceptions
- ArgumentNullException
uriorhandleris null.- McpException
The request failed or the server returned an error response.
UnsubscribeFromResourceAsync(UnsubscribeRequestParams, CancellationToken)
Unsubscribes from a resource on the server to stop receiving notifications about its changes.
public Task UnsubscribeFromResourceAsync(UnsubscribeRequestParams requestParams, CancellationToken cancellationToken = default)
Parameters
requestParamsUnsubscribeRequestParamsThe request parameters to send in the request.
cancellationTokenCancellationTokenThe CancellationToken to monitor for cancellation requests. The default is None.
Returns
- Task
The result of the request.
Exceptions
- ArgumentNullException
requestParamsis null.- McpException
The request failed or the server returned an error response.
UnsubscribeFromResourceAsync(string, RequestOptions?, CancellationToken)
Unsubscribes from a resource on the server to stop receiving notifications about its changes.
public Task UnsubscribeFromResourceAsync(string uri, RequestOptions? options = null, CancellationToken cancellationToken = default)
Parameters
uristringThe URI of the resource to unsubscribe from.
optionsRequestOptionsOptional request options including metadata, serialization settings, and progress tracking.
cancellationTokenCancellationTokenThe CancellationToken to monitor for cancellation requests. The default is None.
Returns
- Task
A task that represents the asynchronous operation.
Exceptions
- ArgumentNullException
uriis null.- ArgumentException
uriis empty or composed entirely of whitespace.- McpException
The request failed or the server returned an error response.
UnsubscribeFromResourceAsync(Uri, RequestOptions?, CancellationToken)
Unsubscribes from a resource on the server to stop receiving notifications about its changes.
public Task UnsubscribeFromResourceAsync(Uri uri, RequestOptions? options = null, CancellationToken cancellationToken = default)
Parameters
uriUriThe URI of the resource to unsubscribe from.
optionsRequestOptionsOptional request options including metadata, serialization settings, and progress tracking.
cancellationTokenCancellationTokenThe CancellationToken to monitor for cancellation requests. The default is None.
Returns
- Task
A task that represents the asynchronous operation.
Exceptions
- ArgumentNullException
uriis null.- McpException
The request failed or the server returned an error response.