Table of Contents

Class McpServer

Namespace
ModelContextProtocol.Server
Assembly
ModelContextProtocol.Core.dll

Represents an instance of a Model Context Protocol (MCP) server that connects to and communicates with an MCP client.

public abstract class McpServer : McpSession, IAsyncDisposable
Inheritance
McpServer
Implements
Inherited Members

Properties

ClientCapabilities

Gets the capabilities supported by the client.

public abstract ClientCapabilities? ClientCapabilities { get; }

Property Value

ClientCapabilities

Remarks

These capabilities are established during the initialization handshake and indicate which features the client supports, such as sampling, roots, and other protocol-specific functionality.

Server implementations can check these capabilities to determine which features are available when interacting with the client.

ClientInfo

Gets the version and implementation information of the connected client.

public abstract Implementation? ClientInfo { get; }

Property Value

Implementation

Remarks

This property contains identification information about the client that has connected to this server, including its name and version. This information is provided by the client during initialization.

Server implementations can use this information for logging, tracking client versions, or implementing client-specific behaviors.

LoggingLevel

Gets the last logging level set by the client, or null if it's never been set.

public abstract LoggingLevel? LoggingLevel { get; }

Property Value

LoggingLevel?

ServerOptions

Gets the options used to construct this server.

public abstract McpServerOptions ServerOptions { get; }

Property Value

McpServerOptions

Remarks

These options define the server's capabilities, protocol version, and other configuration settings that were used to initialize the server.

Services

Gets the service provider for the server.

public abstract IServiceProvider? Services { get; }

Property Value

IServiceProvider

Methods

AsClientLoggerProvider()

Gets an ILogger on which logged messages will be sent as notifications to the client.

public ILoggerProvider AsClientLoggerProvider()

Returns

ILoggerProvider

An ILogger that can be used to log to the client.

AsSamplingChatClient(JsonSerializerOptions?)

Creates an Microsoft.Extensions.AI.IChatClient wrapper that can be used to send sampling requests to the client.

public IChatClient AsSamplingChatClient(JsonSerializerOptions? serializerOptions = null)

Parameters

serializerOptions JsonSerializerOptions

The JsonSerializerOptions to use for serialization. If null, DefaultOptions is used.

Returns

IChatClient

The Microsoft.Extensions.AI.IChatClient that can be used to issue sampling requests to the client.

Exceptions

InvalidOperationException

The client does not support sampling.

CancelTaskAsync(string, CancellationToken)

Cancels a running task on the client.

[Experimental("MCPEXP001", UrlFormat = "https://github.com/modelcontextprotocol/csharp-sdk/blob/main/docs/list-of-diagnostics.md#mcpexp001")]
public ValueTask<McpTask> CancelTaskAsync(string taskId, CancellationToken cancellationToken = default)

Parameters

taskId string

The unique identifier of the task to cancel.

cancellationToken CancellationToken

The CancellationToken to monitor for cancellation requests. The default is None.

Returns

ValueTask<McpTask>

The updated state of the task after cancellation.

Remarks

Cancelling a task requests that the client stop execution. The client may not immediately cancel the task, and may choose to allow the task to complete if it's close to finishing.

Exceptions

ArgumentNullException

taskId is null.

ArgumentException

taskId is empty or composed entirely of whitespace.

InvalidOperationException

The client does not support tasks or task cancellation.

McpException

The request failed or the client returned an error response.

Create(ITransport, McpServerOptions, ILoggerFactory?, IServiceProvider?)

Creates a new instance of an McpServer.

public static McpServer Create(ITransport transport, McpServerOptions serverOptions, ILoggerFactory? loggerFactory = null, IServiceProvider? serviceProvider = null)

Parameters

transport ITransport

The transport to use for the server representing an already-established MCP session.

serverOptions McpServerOptions

Configuration options for this server, including capabilities.

loggerFactory ILoggerFactory

Logger factory to use for logging. If null, logging will be disabled.

serviceProvider IServiceProvider

Optional service provider to create new instances of tools and other dependencies.

Returns

McpServer

An McpServer instance that should be disposed when no longer needed.

Exceptions

ArgumentNullException

transport or serverOptions is null.

ElicitAsTaskAsync(ElicitRequestParams, McpTaskMetadata, CancellationToken)

Requests additional information from the user via the client as a task, allowing the server to poll for completion.

[Experimental("MCPEXP001", UrlFormat = "https://github.com/modelcontextprotocol/csharp-sdk/blob/main/docs/list-of-diagnostics.md#mcpexp001")]
public ValueTask<McpTask> ElicitAsTaskAsync(ElicitRequestParams requestParams, McpTaskMetadata taskMetadata, CancellationToken cancellationToken = default)

Parameters

requestParams ElicitRequestParams

The parameters for the elicitation request.

taskMetadata McpTaskMetadata

The task metadata specifying TTL and other task-related options.

cancellationToken CancellationToken

The CancellationToken to monitor for cancellation requests.

Returns

ValueTask<McpTask>

An McpTask representing the created task on the client.

Remarks

Use GetTaskAsync(string, CancellationToken) to poll for task status and GetTaskResultAsync<TResult>(string, JsonSerializerOptions?, CancellationToken) (with ElicitResult) to retrieve the final result when the task completes.

Exceptions

ArgumentNullException

requestParams or taskMetadata is null.

InvalidOperationException

The client does not support elicitation or task-augmented elicitation.

McpException

The request failed or the client returned an error response.

ElicitAsync(ElicitRequestParams, CancellationToken)

Requests additional information from the user via the client, allowing the server to elicit structured data.

public ValueTask<ElicitResult> ElicitAsync(ElicitRequestParams requestParams, CancellationToken cancellationToken = default)

Parameters

requestParams ElicitRequestParams

The parameters for the elicitation request.

cancellationToken CancellationToken

The CancellationToken to monitor for cancellation requests.

Returns

ValueTask<ElicitResult>

A task containing the elicitation result.

Remarks

When called during task-augmented tool execution, this method automatically updates the task status to InputRequired while waiting for user input, then returns to Working when the response is received.

Exceptions

ArgumentNullException

requestParams is null.

InvalidOperationException

The client does not support elicitation.

McpException

The request failed or the client returned an error response.

ElicitAsync<T>(string, RequestOptions?, CancellationToken)

Requests additional information from the user via the client, constructing a request schema from the public serializable properties of T and deserializing the response into T.

public ValueTask<ElicitResult<T>> ElicitAsync<T>(string message, RequestOptions? options = null, CancellationToken cancellationToken = default)

Parameters

message string

The message to present to the user.

options RequestOptions

Optional request options including metadata, serialization settings, and progress tracking.

cancellationToken CancellationToken

The CancellationToken to monitor for cancellation requests.

Returns

ValueTask<ElicitResult<T>>

An ElicitResult<T> with the user's response, if accepted.

Type Parameters

T

The type describing the expected input shape. Only primitive members are supported (string, number, boolean, enum).

Remarks

Elicitation uses a constrained subset of JSON Schema and only supports strings, numbers/integers, booleans and string enums. Unsupported member types are ignored when constructing the schema.

Exceptions

ArgumentNullException

message is null.

ArgumentException

message is empty or composed entirely of whitespace.

InvalidOperationException

The client does not support elicitation.

McpException

The request failed or the client returned an error response.

GetTaskAsync(string, CancellationToken)

Retrieves the current state of a specific task from the client.

[Experimental("MCPEXP001", UrlFormat = "https://github.com/modelcontextprotocol/csharp-sdk/blob/main/docs/list-of-diagnostics.md#mcpexp001")]
public ValueTask<McpTask> GetTaskAsync(string taskId, CancellationToken cancellationToken = default)

Parameters

taskId string

The unique identifier of the task to retrieve.

cancellationToken CancellationToken

The CancellationToken to monitor for cancellation requests. The default is None.

Returns

ValueTask<McpTask>

The current state of the task.

Exceptions

ArgumentNullException

taskId is null.

ArgumentException

taskId is empty or composed entirely of whitespace.

InvalidOperationException

The client does not support tasks.

McpException

The request failed or the client returned an error response.

GetTaskResultAsync<TResult>(string, JsonSerializerOptions?, CancellationToken)

Retrieves the result of a completed task from the client, 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<TResult?> GetTaskResultAsync<TResult>(string taskId, JsonSerializerOptions? jsonSerializerOptions = null, CancellationToken cancellationToken = default)

Parameters

taskId string

The unique identifier of the task whose result to retrieve.

jsonSerializerOptions JsonSerializerOptions

Optional serializer options for deserializing the result.

cancellationToken CancellationToken

The CancellationToken to monitor for cancellation requests. The default is None.

Returns

ValueTask<TResult>

The result of the task, deserialized into type TResult.

Type Parameters

TResult

The type to deserialize the task result into.

Remarks

This method sends a tasks/result request to the client, which will block until the task completes if it hasn't already. The client handles all polling logic internally.

For sampling tasks, use CreateMessageResult as TResult. For elicitation tasks, use ElicitResult as TResult.

Exceptions

ArgumentNullException

taskId is null.

ArgumentException

taskId is empty or composed entirely of whitespace.

InvalidOperationException

The client does not support tasks.

McpException

The request failed or the client returned an error response.

ListTasksAsync(ListTasksRequestParams, CancellationToken)

Retrieves a list of tasks from the client.

[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

requestParams ListTasksRequestParams

The request parameters to send in the request.

cancellationToken CancellationToken

The CancellationToken to monitor for cancellation requests. The default is None.

Returns

ValueTask<ListTasksResult>

The result of the request as provided by the client.

Remarks

The ListTasksAsync(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 client. Any pagination needs to be managed by the caller.

Exceptions

ArgumentNullException

requestParams is null.

InvalidOperationException

The client does not support tasks or task listing.

McpException

The request failed or the client returned an error response.

ListTasksAsync(CancellationToken)

Retrieves a list of all tasks from the client.

[Experimental("MCPEXP001", UrlFormat = "https://github.com/modelcontextprotocol/csharp-sdk/blob/main/docs/list-of-diagnostics.md#mcpexp001")]
public ValueTask<IList<McpTask>> ListTasksAsync(CancellationToken cancellationToken = default)

Parameters

cancellationToken CancellationToken

The CancellationToken to monitor for cancellation requests. The default is None.

Returns

ValueTask<IList<McpTask>>

A list of all tasks.

Exceptions

InvalidOperationException

The client does not support tasks or task listing.

McpException

The request failed or the client returned an error response.

NotifyTaskStatusAsync(McpTask, CancellationToken)

Sends a task status notification to the connected client.

[Experimental("MCPEXP001", UrlFormat = "https://github.com/modelcontextprotocol/csharp-sdk/blob/main/docs/list-of-diagnostics.md#mcpexp001")]
public Task NotifyTaskStatusAsync(McpTask task, CancellationToken cancellationToken = default)

Parameters

task McpTask

The task whose status changed.

cancellationToken CancellationToken

The CancellationToken to monitor for cancellation requests.

Returns

Task

A task representing the asynchronous notification operation.

Remarks

This method sends an optional status notification to inform the client of task state changes. According to the MCP specification, receivers MAY send this notification but are not required to. Clients must not rely on receiving these notifications and should continue polling via tasks/get.

The notification is sent using the standard notifications/tasks/status method and includes the full task state information.

Exceptions

ArgumentNullException

task is null.

PollTaskUntilCompleteAsync(string, CancellationToken)

Polls a task on the client until it reaches a terminal state.

[Experimental("MCPEXP001", UrlFormat = "https://github.com/modelcontextprotocol/csharp-sdk/blob/main/docs/list-of-diagnostics.md#mcpexp001")]
public ValueTask<McpTask> PollTaskUntilCompleteAsync(string taskId, CancellationToken cancellationToken = default)

Parameters

taskId string

The unique identifier of the task to poll.

cancellationToken CancellationToken

The CancellationToken to monitor for cancellation requests. The default is None.

Returns

ValueTask<McpTask>

The task in its terminal state.

Remarks

This method repeatedly calls GetTaskAsync(string, CancellationToken) until the task reaches a terminal status. It respects the PollInterval returned by the client to determine how long to wait between polling attempts.

For retrieving the actual result of a completed task, use GetTaskResultAsync<TResult>(string, JsonSerializerOptions?, CancellationToken) or WaitForTaskResultAsync<TResult>(string, JsonSerializerOptions?, CancellationToken).

Exceptions

ArgumentNullException

taskId is null.

ArgumentException

taskId is empty or composed entirely of whitespace.

InvalidOperationException

The client does not support tasks.

McpException

The request failed or the client returned an error response.

RequestRootsAsync(ListRootsRequestParams, CancellationToken)

Requests the client to list the roots it exposes.

public ValueTask<ListRootsResult> RequestRootsAsync(ListRootsRequestParams requestParams, CancellationToken cancellationToken = default)

Parameters

requestParams ListRootsRequestParams

The parameters for the list roots request.

cancellationToken CancellationToken

The CancellationToken to monitor for cancellation requests.

Returns

ValueTask<ListRootsResult>

A task containing the list of roots exposed by the client.

Exceptions

ArgumentNullException

requestParams is null.

InvalidOperationException

The client does not support roots.

McpException

The request failed or the client returned an error response.

RunAsync(CancellationToken)

Runs the server, listening for and handling client requests.

public abstract Task RunAsync(CancellationToken cancellationToken = default)

Parameters

cancellationToken CancellationToken

Returns

Task

SampleAsTaskAsync(CreateMessageRequestParams, McpTaskMetadata, CancellationToken)

Requests to sample an LLM via the client as a task, allowing the server to poll for completion.

[Experimental("MCPEXP001", UrlFormat = "https://github.com/modelcontextprotocol/csharp-sdk/blob/main/docs/list-of-diagnostics.md#mcpexp001")]
public ValueTask<McpTask> SampleAsTaskAsync(CreateMessageRequestParams requestParams, McpTaskMetadata taskMetadata, CancellationToken cancellationToken = default)

Parameters

requestParams CreateMessageRequestParams

The parameters for the sampling request.

taskMetadata McpTaskMetadata

The task metadata specifying TTL and other task-related options.

cancellationToken CancellationToken

The CancellationToken to monitor for cancellation requests.

Returns

ValueTask<McpTask>

An McpTask representing the created task on the client.

Remarks

Use GetTaskAsync(string, CancellationToken) to poll for task status and GetTaskResultAsync<TResult>(string, JsonSerializerOptions?, CancellationToken) (with CreateMessageResult) to retrieve the final result when the task completes.

Exceptions

ArgumentNullException

requestParams or taskMetadata is null.

InvalidOperationException

The client does not support sampling or task-augmented sampling.

McpException

The request failed or the client returned an error response.

SampleAsync(CreateMessageRequestParams, CancellationToken)

Requests to sample an LLM via the client using the specified request parameters.

public ValueTask<CreateMessageResult> SampleAsync(CreateMessageRequestParams requestParams, CancellationToken cancellationToken = default)

Parameters

requestParams CreateMessageRequestParams

The parameters for the sampling request.

cancellationToken CancellationToken

The CancellationToken to monitor for cancellation requests.

Returns

ValueTask<CreateMessageResult>

A task containing the sampling result from the client.

Remarks

When called during task-augmented tool execution, this method automatically updates the task status to InputRequired while waiting for the client response, then returns to Working when the response is received.

Exceptions

ArgumentNullException

requestParams is null.

InvalidOperationException

The client does not support sampling.

McpException

The request failed or the client returned an error response.

SampleAsync(IEnumerable<ChatMessage>, ChatOptions?, JsonSerializerOptions?, CancellationToken)

Requests to sample an LLM via the client using the provided chat messages and options.

public Task<ChatResponse> SampleAsync(IEnumerable<ChatMessage> messages, ChatOptions? chatOptions = null, JsonSerializerOptions? serializerOptions = null, CancellationToken cancellationToken = default)

Parameters

messages IEnumerable<ChatMessage>

The messages to send as part of the request.

chatOptions ChatOptions

The options to use for the request, including model parameters and constraints.

serializerOptions JsonSerializerOptions

The JsonSerializerOptions to use for serializing user-provided objects. If null, DefaultOptions is used.

cancellationToken CancellationToken

The CancellationToken to monitor for cancellation requests. The default is None.

Returns

Task<ChatResponse>

A task containing the chat response from the model.

Exceptions

ArgumentNullException

messages is null.

InvalidOperationException

The client does not support sampling.

McpException

The request failed or the client returned an error response.

WaitForTaskResultAsync<TResult>(string, JsonSerializerOptions?, CancellationToken)

Waits for a task on the client to complete and retrieves its result.

[Experimental("MCPEXP001", UrlFormat = "https://github.com/modelcontextprotocol/csharp-sdk/blob/main/docs/list-of-diagnostics.md#mcpexp001")]
public ValueTask<(McpTask Task, TResult? Result)> WaitForTaskResultAsync<TResult>(string taskId, JsonSerializerOptions? jsonSerializerOptions = null, CancellationToken cancellationToken = default)

Parameters

taskId string

The unique identifier of the task whose result to retrieve.

jsonSerializerOptions JsonSerializerOptions

Optional serializer options for deserializing the result.

cancellationToken CancellationToken

The CancellationToken to monitor for cancellation requests. The default is None.

Returns

ValueTask<(McpTask Task, TResult Result)>

A tuple containing the final task state and its result.

Type Parameters

TResult

The type to deserialize the task result into.

Remarks

This method combines PollTaskUntilCompleteAsync(string, CancellationToken) and GetTaskResultAsync<TResult>(string, JsonSerializerOptions?, CancellationToken) to provide a convenient way to wait for a task to complete and retrieve its result in a single call.

If the task completes with a status of Failed or Cancelled, an McpException is thrown.

For sampling tasks, use CreateMessageResult as TResult. For elicitation tasks, use ElicitResult as TResult.

Exceptions

ArgumentNullException

taskId is null.

ArgumentException

taskId is empty or composed entirely of whitespace.

InvalidOperationException

The client does not support tasks.

McpException

The task failed or was cancelled.