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
- Extension Methods
Constructors
McpClient()
Initializes a new instance of the McpClient class.
[Experimental("MCPEXP002", UrlFormat = "https://github.com/modelcontextprotocol/csharp-sdk/blob/main/docs/list-of-diagnostics.md#mcpexp002")]
protected McpClient()
Properties
Completion
Gets a Task<TResult> that completes when the client session has completed.
public abstract Task<ClientCompletionDetails> Completion { get; }
Property Value
Remarks
The task always completes successfully. The result provides details about why the session completed. Transport implementations may return derived types with additional strongly-typed information, such as StdioClientCompletionDetails.
For graceful closure (e.g., explicit disposal), Exception will be null. For unexpected closure (e.g., process crash, network failure), it may contain an exception that caused or that represents the failure.
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 or from server/discover result metadata.
This information can be useful for logging, debugging, compatibility checks, and displaying server information to users.
Exceptions
- InvalidOperationException
The client is not connected, or the server omitted the optional server identity metadata.
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. They should focus on guidance that helps a model use the server effectively and should avoid duplicating tool, prompt, or resource descriptions.
This can be used by clients to improve an LLM's understanding of how to use the server. It can be thought of like a "hint" to the model and can be added to a system prompt.
Methods
AddKnownTools(IEnumerable<Tool>)
Registers one or more tool definitions in the client's tool cache, enabling the transport
to send Mcp-Param-* headers for those tools without requiring a prior ListToolsAsync(RequestOptions?, CancellationToken) call.
public virtual void AddKnownTools(IEnumerable<Tool> tools)
Parameters
toolsIEnumerable<Tool>The tool definitions to register.
Remarks
This method allows callers who already have tool schema information (e.g., from a previous session,
hardcoded configuration, or an out-of-band source) to provide it directly to the client. Once registered,
any CallToolAsync(string, IReadOnlyDictionary<string, object?>?, IProgress<ProgressNotificationValue>?, RequestOptions?, CancellationToken)
call for a registered tool will automatically include Mcp-Param-* HTTP headers based on
the tool's x-mcp-header schema annotations, exactly as if the tool had been discovered
via ListToolsAsync(RequestOptions?, CancellationToken).
Cache interaction behavior:
- Registered tools are added to the same internal tool cache used by ListToolsAsync(RequestOptions?, CancellationToken).
- Calling ListToolsAsync(RequestOptions?, CancellationToken) after AddKnownTools(IEnumerable<Tool>) preserves manually registered tools — only server-discovered tools are cleared and repopulated.
- If the server returns a tool with the same name as a manually registered tool, the server's definition overwrites the registered one in the cache, but the tool retains its known status and will survive subsequent cache clears. This registration is sticky for the lifetime of the McpClient; use RemoveKnownTools(IEnumerable<string>) or ClearKnownTools() to explicitly drop known tools that are no longer needed.
- Tools can be registered at any time — before or after ListToolsAsync(RequestOptions?, CancellationToken), and across multiple calls.
- Re-registering a tool with the same name overwrites the previous definition in the cache (last write wins).
Tools with invalid x-mcp-header annotations cause an ArgumentException to be thrown.
No tools are added to the cache if any tool in the batch fails validation (all-or-nothing).
Exceptions
- ArgumentNullException
toolsis null.- ArgumentException
One or more tools have invalid
x-mcp-headerannotations.
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 invoke.
argumentsIReadOnlyDictionary<string, object>An optional dictionary of arguments to pass to the tool.
progressIProgress<ProgressNotificationValue>An optional progress handler for tracking operation progress.
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 result of the tool invocation.
Exceptions
- ArgumentNullException
toolNameis null.- McpException
The request failed or the server returned an error response.
ClearKnownTools()
Removes all previously registered tool definitions from the client's tool cache.
public virtual void ClearKnownTools()
Remarks
This clears all tools that were added via AddKnownTools(IEnumerable<Tool>) from both the known-tools set and the internal tool cache. Server-discovered tools that are not also known tools are not affected and will remain in the cache until the next ListToolsAsync(RequestOptions?, CancellationToken) call.
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 specific prompt from the MCP 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.
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.
Remarks
This overload aggregates every page into a single list and does not surface the per-result caching hints (TimeToLive and CacheScope). To read those hints, use the ListPromptsAsync(ListPromptsRequestParams, CancellationToken) overload, which returns the raw ListPromptsResult for each page.
The SDK does not perform any internal caching of listing results; every call re-fetches all pages from the server. If you want to cache listing results, do so in your own code using the lower-level ListPromptsAsync(ListPromptsRequestParams, CancellationToken) overload, which exposes the per-page caching hints and lets you manage pagination so each page can be cached and expired independently.
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.
Remarks
This overload aggregates every page into a single list and does not surface the per-result caching hints (TimeToLive and CacheScope). To read those hints, use the ListResourceTemplatesAsync(ListResourceTemplatesRequestParams, CancellationToken) overload, which returns the raw ListResourceTemplatesResult for each page.
The SDK does not perform any internal caching of listing results; every call re-fetches all pages from the server. If you want to cache listing results, do so in your own code using the lower-level ListResourceTemplatesAsync(ListResourceTemplatesRequestParams, CancellationToken) overload, which exposes the per-page caching hints and lets you manage pagination so each page can be cached and expired independently.
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.
Remarks
This overload aggregates every page into a single list and does not surface the per-result caching hints (TimeToLive and CacheScope). To read those hints, use the ListResourcesAsync(ListResourcesRequestParams, CancellationToken) overload, which returns the raw ListResourcesResult for each page.
The SDK does not perform any internal caching of listing results; every call re-fetches all pages from the server. If you want to cache listing results, do so in your own code using the lower-level ListResourcesAsync(ListResourcesRequestParams, CancellationToken) overload, which exposes the per-page caching hints and lets you manage pagination so each page can be cached and expired independently.
Exceptions
- McpException
The request failed or the server returned an error response.
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.
Remarks
This overload aggregates every page into a single list and does not surface the per-result caching hints (TimeToLive and CacheScope). To read those hints, use the ListToolsAsync(ListToolsRequestParams, CancellationToken) overload, which returns the raw ListToolsResult for each page.
The SDK does not perform any internal caching of listing results; every call re-fetches all pages from the server. If you want to cache listing results, do so in your own code using the lower-level ListToolsAsync(ListToolsRequestParams, CancellationToken) overload, which exposes the per-page caching hints and lets you manage pagination so each page can be cached and expired independently.
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.
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.
RemoveKnownTools(IEnumerable<string>)
Removes one or more previously registered tool definitions from the client's tool cache by name.
public virtual void RemoveKnownTools(IEnumerable<string> toolNames)
Parameters
toolNamesIEnumerable<string>The names of the tools to remove.
Remarks
This removes the specified tools from both the known-tools set and the internal tool cache.
After removal, those tools will no longer survive ListToolsAsync(RequestOptions?, CancellationToken)
cache clears, and Mcp-Param-* headers will no longer be sent for them unless the server
re-discovers them via ListToolsAsync(RequestOptions?, CancellationToken).
Removing a tool name that was not previously added via AddKnownTools(IEnumerable<Tool>) is a no-op.
Exceptions
- ArgumentNullException
toolNamesis null.
ResolveInputRequestsAsync(IDictionary<string, InputRequest>, CancellationToken)
Resolves input requests by dispatching each request to the appropriate registered handler.
public abstract ValueTask<IDictionary<string, InputResponse>> ResolveInputRequestsAsync(IDictionary<string, InputRequest> inputRequests, CancellationToken cancellationToken)
Parameters
inputRequestsIDictionary<string, InputRequest>The input requests from the task, keyed by request identifier. Each value is an InputRequest wrapping the server-to-client request payload.
cancellationTokenCancellationTokenThe CancellationToken to monitor for cancellation requests.
Returns
- ValueTask<IDictionary<string, InputResponse>>
A dictionary of responses keyed by the same identifiers as the input requests.
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.
[Obsolete("The Logging feature is deprecated as of specification version 2026-07-28 and may be removed in a future version. See SEP-2577 for more information.", DiagnosticId = "MCP9005", UrlFormat = "https://github.com/modelcontextprotocol/csharp-sdk/blob/main/docs/list-of-diagnostics.md#obsolete-apis")]
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.
[Obsolete("The Logging feature is deprecated as of specification version 2026-07-28 and may be removed in a future version. See SEP-2577 for more information.", DiagnosticId = "MCP9005", UrlFormat = "https://github.com/modelcontextprotocol/csharp-sdk/blob/main/docs/list-of-diagnostics.md#obsolete-apis")]
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.
[Obsolete("The Logging feature is deprecated as of specification version 2026-07-28 and may be removed in a future version. See SEP-2577 for more information.", DiagnosticId = "MCP9005", UrlFormat = "https://github.com/modelcontextprotocol/csharp-sdk/blob/main/docs/list-of-diagnostics.md#obsolete-apis")]
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).
The 2026-07-28 protocol revision (SEP-2575) removed resources/subscribe in favor of
SubscriptionsListen with resourceSubscriptions. On a session that
negotiated that revision or later, this method throws an McpException with
MethodNotFound.
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)
Subscribes to a resource on the server to receive notifications when it changes.
public Task SubscribeToResourceAsync(Uri uri, RequestOptions? options = null, CancellationToken cancellationToken = default)
Parameters
uriUriThe URI of the resource to subscribe to.
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.
Remarks
The 2026-07-28 protocol revision (SEP-2575) removed resources/unsubscribe in favor of
SubscriptionsListen with resourceSubscriptions. On a session that
negotiated that revision or later, this method throws an McpException with
MethodNotFound.
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.