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
Constructors
McpServer()
Initializes a new instance of the McpServer class.
[Experimental("MCPEXP002", UrlFormat = "https://github.com/modelcontextprotocol/csharp-sdk/blob/main/docs/list-of-diagnostics.md#mcpexp002")]
protected McpServer()
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.
IsMrtrSupported
Gets a value indicating whether the connected client supports Multi Round-Trip Requests (MRTR).
public virtual bool IsMrtrSupported { get; }
Property Value
Remarks
When this property returns true, tool handlers can throw InputRequiredException to return an InputRequiredResult with InputRequests and/or RequestState to the client.
When this property returns false, tool handlers should provide a fallback experience (for example, returning a text message explaining that the client does not support the required feature) instead of throwing InputRequiredException.
LoggingLevel
Gets the last logging level set by the client, or null if it's never been set.
[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 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.
[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 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.
[Obsolete("The Sampling 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 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.
Remarks
When the server is using the Streamable HTTP transport, prefer obtaining this chat client from the
McpServer instance available via RequestContext from inside a tool, prompt,
or resource handler. That routes sampling requests through the originating POST response stream via
RelatedTransport, which is always open for the duration of
the request, rather than relying on the optional standalone GET SSE stream.
Exceptions
- InvalidOperationException
The client does not support sampling.
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.
CreateMcpTaskScope(string, IMcpTaskStore)
Creates a scope that redirects server-initiated requests (elicitation, sampling, list roots) through the task store as input requests for the duration of the scope. Use this when executing tool logic in the background as a task, so that any server-to-client requests are surfaced to the client via the task's InputRequired state instead of direct JSON-RPC messages.
public IDisposable CreateMcpTaskScope(string taskId, IMcpTaskStore store)
Parameters
taskIdstringThe task ID in the store.
storeIMcpTaskStoreThe task store to write input requests to.
Returns
- IDisposable
An IDisposable that restores the previous context when disposed.
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 the server is using the Streamable HTTP transport, prefer calling this method on the
McpServer instance available via RequestContext from inside a tool, prompt,
or resource handler. That routes the request through the originating POST response stream via
RelatedTransport, which is always open for the duration of
the request, rather than relying on the optional standalone GET SSE stream.
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.
RequestRootsAsync(ListRootsRequestParams, CancellationToken)
Requests the client to list the roots it exposes.
[Obsolete("The Roots 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 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.
Remarks
When the server is using the Streamable HTTP transport, prefer calling this method on the
McpServer instance available via RequestContext from inside a tool, prompt,
or resource handler. That routes the request through the originating POST response stream via
RelatedTransport, which is always open for the duration of
the request, rather than relying on the optional standalone GET SSE stream.
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
SampleAsync(CreateMessageRequestParams, CancellationToken)
Requests to sample an LLM via the client using the specified request parameters.
[Obsolete("The Sampling 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 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 the server is using the Streamable HTTP transport, prefer calling this method on the
McpServer instance available via RequestContext from inside a tool, prompt,
or resource handler. That routes the request through the originating POST response stream via
RelatedTransport, which is always open for the duration of
the request, rather than relying on the optional standalone GET SSE stream.
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.
[Obsolete("The Sampling 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<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.
SendTaskStatusNotificationAsync(TaskStatusNotificationParams, CancellationToken)
Sends a task status notification to the connected client.
public Task SendTaskStatusNotificationAsync(TaskStatusNotificationParams notificationParams, CancellationToken cancellationToken = default)
Parameters
notificationParamsTaskStatusNotificationParamsThe task status notification parameters to send.
cancellationTokenCancellationTokenThe CancellationToken to monitor for cancellation requests. The default is None.
Returns
- Task
A task that represents the asynchronous send operation.
Exceptions
- ArgumentNullException
notificationParamsis null.