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
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
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
ServerOptions
Gets the options used to construct this server.
public abstract McpServerOptions ServerOptions { get; }
Property Value
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
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
serializerOptionsJsonSerializerOptionsThe 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
taskIdstringThe unique identifier of the task to cancel.
cancellationTokenCancellationTokenThe CancellationToken to monitor for cancellation requests. The default is None.
Returns
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
taskIdis null.- ArgumentException
taskIdis 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
transportITransportThe transport to use for the server representing an already-established MCP session.
serverOptionsMcpServerOptionsConfiguration options for this server, including capabilities.
loggerFactoryILoggerFactoryLogger factory to use for logging. If null, logging will be disabled.
serviceProviderIServiceProviderOptional service provider to create new instances of tools and other dependencies.
Returns
Exceptions
- ArgumentNullException
transportorserverOptionsis 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
requestParamsElicitRequestParamsThe parameters for the elicitation request.
taskMetadataMcpTaskMetadataThe task metadata specifying TTL and other task-related options.
cancellationTokenCancellationTokenThe CancellationToken to monitor for cancellation requests.
Returns
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
requestParamsortaskMetadatais 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
requestParamsElicitRequestParamsThe parameters for the elicitation request.
cancellationTokenCancellationTokenThe 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
requestParamsis 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
messagestringThe message to present to the user.
optionsRequestOptionsOptional request options including metadata, serialization settings, and progress tracking.
cancellationTokenCancellationTokenThe CancellationToken to monitor for cancellation requests.
Returns
- ValueTask<ElicitResult<T>>
An ElicitResult<T> with the user's response, if accepted.
Type Parameters
TThe 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
messageis null.- ArgumentException
messageis 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
taskIdstringThe unique identifier of the task to retrieve.
cancellationTokenCancellationTokenThe CancellationToken to monitor for cancellation requests. The default is None.
Returns
Exceptions
- ArgumentNullException
taskIdis null.- ArgumentException
taskIdis 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
taskIdstringThe unique identifier of the task whose result to retrieve.
jsonSerializerOptionsJsonSerializerOptionsOptional serializer options for deserializing the result.
cancellationTokenCancellationTokenThe CancellationToken to monitor for cancellation requests. The default is None.
Returns
- ValueTask<TResult>
The result of the task, deserialized into type
TResult.
Type Parameters
TResultThe 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
taskIdis null.- ArgumentException
taskIdis 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
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 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
requestParamsis 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
cancellationTokenCancellationTokenThe CancellationToken to monitor for cancellation requests. The default is None.
Returns
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
taskMcpTaskThe task whose status changed.
cancellationTokenCancellationTokenThe 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
taskis 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
taskIdstringThe unique identifier of the task to poll.
cancellationTokenCancellationTokenThe CancellationToken to monitor for cancellation requests. The default is None.
Returns
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
taskIdis null.- ArgumentException
taskIdis 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
requestParamsListRootsRequestParamsThe parameters for the list roots request.
cancellationTokenCancellationTokenThe CancellationToken to monitor for cancellation requests.
Returns
- ValueTask<ListRootsResult>
A task containing the list of roots exposed by the client.
Exceptions
- ArgumentNullException
requestParamsis 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
cancellationTokenCancellationToken
Returns
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
requestParamsCreateMessageRequestParamsThe parameters for the sampling request.
taskMetadataMcpTaskMetadataThe task metadata specifying TTL and other task-related options.
cancellationTokenCancellationTokenThe CancellationToken to monitor for cancellation requests.
Returns
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
requestParamsortaskMetadatais 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
requestParamsCreateMessageRequestParamsThe parameters for the sampling request.
cancellationTokenCancellationTokenThe 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
requestParamsis 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
messagesIEnumerable<ChatMessage>The messages to send as part of the request.
chatOptionsChatOptionsThe options to use for the request, including model parameters and constraints.
serializerOptionsJsonSerializerOptionsThe JsonSerializerOptions to use for serializing user-provided objects. If null, DefaultOptions is used.
cancellationTokenCancellationTokenThe CancellationToken to monitor for cancellation requests. The default is None.
Returns
- Task<ChatResponse>
A task containing the chat response from the model.
Exceptions
- ArgumentNullException
messagesis 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
taskIdstringThe unique identifier of the task whose result to retrieve.
jsonSerializerOptionsJsonSerializerOptionsOptional serializer options for deserializing the result.
cancellationTokenCancellationTokenThe CancellationToken to monitor for cancellation requests. The default is None.
Returns
Type Parameters
TResultThe 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
taskIdis null.- ArgumentException
taskIdis empty or composed entirely of whitespace.- InvalidOperationException
The client does not support tasks.
- McpException
The task failed or was cancelled.