Table of Contents

Class McpClientExtensions

Namespace
ModelContextProtocol.Client
Assembly
ModelContextProtocol.dll

Provides extension methods for interacting with an IMcpClient.

public static class McpClientExtensions
Inheritance
McpClientExtensions
Inherited Members

Remarks

This class contains extension methods that simplify common operations with an MCP client, such as pinging a server, listing and working with tools, prompts, and resources, and managing subscriptions to resources.

Methods

CallToolAsync(IMcpClient, string, IReadOnlyDictionary<string, object?>?, JsonSerializerOptions?, CancellationToken)

Invokes a tool on the server

public static Task<CallToolResponse> CallToolAsync(this IMcpClient client, string toolName, IReadOnlyDictionary<string, object?>? arguments = null, JsonSerializerOptions? serializerOptions = null, CancellationToken cancellationToken = default)

Parameters

client IMcpClient

The client instance used to communicate with the MCP server.

toolName string

The name of the tool to call on the server..

arguments IReadOnlyDictionary<string, object>

Optional dictionary of arguments to pass to the tool. Each key represents a parameter name, and its associated value represents the argument value.

serializerOptions JsonSerializerOptions

The JSON serialization options governing argument serialization. If null, the default serialization options will be used.

cancellationToken CancellationToken

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

Returns

Task<CallToolResponse>

A task containing the CallToolResponse from the tool execution. The response includes the tool's output content, which may be structured data, text, or an error message.

Examples

// Call a simple echo tool with a string argument
var result = await client.CallToolAsync(
    "echo",
    new Dictionary<string, object?>
    {
        ["message"] = "Hello MCP!"
    });

Exceptions

ArgumentNullException

client is null.

ArgumentNullException

toolName is null.

McpException

The server could not find the requested tool, or the server encountered an error while processing the request.

CompleteAsync(IMcpClient, Reference, string, string, CancellationToken)

Requests completion suggestions for a prompt argument or resource reference.

public static Task<CompleteResult> CompleteAsync(this IMcpClient client, Reference reference, string argumentName, string argumentValue, CancellationToken cancellationToken = default)

Parameters

client IMcpClient

The client instance used to communicate with the MCP server.

reference Reference

The reference object specifying the type and optional URI or name.

argumentName string

The name of the argument for which completions are requested.

argumentValue string

The current value of the argument, used to filter relevant completions.

cancellationToken CancellationToken

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

Returns

Task<CompleteResult>

A CompleteResult containing completion suggestions.

Remarks

This method allows clients to request auto-completion suggestions for arguments in a prompt template or for resource references.

When working with prompt references, the server will return suggestions for the specified argument that match or begin with the current argument value. This is useful for implementing intelligent auto-completion in user interfaces.

When working with resource references, the server will return suggestions relevant to the specified resource URI.

Exceptions

ArgumentNullException

client is null.

ArgumentNullException

reference is null.

ArgumentNullException

argumentName is null.

ArgumentException

argumentName is empty or composed entirely of whitespace.

McpException

The server returned an error response.

CreateSamplingHandler(IChatClient)

Creates a sampling handler for use with SamplingHandler that will satisfy sampling requests using the specified Microsoft.Extensions.AI.IChatClient.

public static Func<CreateMessageRequestParams?, IProgress<ProgressNotificationValue>, CancellationToken, ValueTask<CreateMessageResult>> CreateSamplingHandler(this IChatClient chatClient)

Parameters

chatClient IChatClient

The Microsoft.Extensions.AI.IChatClient with which to satisfy sampling requests.

Returns

Func<CreateMessageRequestParams, IProgress<ProgressNotificationValue>, CancellationToken, ValueTask<CreateMessageResult>>

The created handler delegate that can be assigned to SamplingHandler.

Remarks

This method creates a function that converts MCP message requests into chat client calls, enabling an MCP client to generate text or other content using an actual AI model via the provided chat client.

The handler can process text messages, image messages, and resource messages as defined in the Model Context Protocol.

Exceptions

ArgumentNullException

chatClient is null.

EnumeratePromptsAsync(IMcpClient, CancellationToken)

Creates an enumerable for asynchronously enumerating all available prompts from the server.

public static IAsyncEnumerable<McpClientPrompt> EnumeratePromptsAsync(this IMcpClient client, CancellationToken cancellationToken = default)

Parameters

client IMcpClient

The client instance used to communicate with the MCP server.

cancellationToken CancellationToken

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

Returns

IAsyncEnumerable<McpClientPrompt>

An asynchronous sequence of all available prompts as McpClientPrompt instances.

Examples

// Enumerate all prompts available on the server
await foreach (var prompt in client.EnumeratePromptsAsync())
{
    Console.WriteLine($"Prompt: {prompt.Name}");
}

Remarks

This method uses asynchronous enumeration to retrieve prompts from the server, which allows processing prompts as they arrive rather than waiting for all prompts to be retrieved. The method automatically handles pagination with cursors if the server responds with prompts split across multiple responses.

Every iteration through the returned IAsyncEnumerable<T> will result in re-querying the server and yielding the sequence of available prompts.

Exceptions

ArgumentNullException

client is null.

EnumerateResourceTemplatesAsync(IMcpClient, CancellationToken)

Creates an enumerable for asynchronously enumerating all available resource templates from the server.

public static IAsyncEnumerable<ResourceTemplate> EnumerateResourceTemplatesAsync(this IMcpClient client, CancellationToken cancellationToken = default)

Parameters

client IMcpClient

The client instance used to communicate with the MCP server.

cancellationToken CancellationToken

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

Returns

IAsyncEnumerable<ResourceTemplate>

An asynchronous sequence of all available resource templates as ResourceTemplate instances.

Examples

// Enumerate all resource templates available on the server
await foreach (var template in client.EnumerateResourceTemplatesAsync())
{
    Console.WriteLine($"Template: {template.Name}");
}

Remarks

This method uses asynchronous enumeration to retrieve resource templates from the server, which allows processing templates as they arrive rather than waiting for all templates to be retrieved. The method automatically handles pagination with cursors if the server responds with templates split across multiple responses.

Every iteration through the returned IAsyncEnumerable<T> will result in re-querying the server and yielding the sequence of available resource templates.

Exceptions

ArgumentNullException

client is null.

EnumerateResourcesAsync(IMcpClient, CancellationToken)

Creates an enumerable for asynchronously enumerating all available resources from the server.

public static IAsyncEnumerable<Resource> EnumerateResourcesAsync(this IMcpClient client, CancellationToken cancellationToken = default)

Parameters

client IMcpClient

The client instance used to communicate with the MCP server.

cancellationToken CancellationToken

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

Returns

IAsyncEnumerable<Resource>

An asynchronous sequence of all available resources as Resource instances.

Examples

// Enumerate all resources available on the server
await foreach (var resource in client.EnumerateResourcesAsync())
{
    Console.WriteLine($"Resource URI: {resource.Uri}");
}

Remarks

This method uses asynchronous enumeration to retrieve resources from the server, which allows processing resources as they arrive rather than waiting for all resources to be retrieved. The method automatically handles pagination with cursors if the server responds with resources split across multiple responses.

Every iteration through the returned IAsyncEnumerable<T> will result in re-querying the server and yielding the sequence of available resources.

Exceptions

ArgumentNullException

client is null.

EnumerateToolsAsync(IMcpClient, JsonSerializerOptions?, CancellationToken)

Creates an enumerable for asynchronously enumerating all available tools from the server.

public static IAsyncEnumerable<McpClientTool> EnumerateToolsAsync(this IMcpClient client, JsonSerializerOptions? serializerOptions = null, CancellationToken cancellationToken = default)

Parameters

client IMcpClient

The client instance used to communicate with the MCP server.

serializerOptions JsonSerializerOptions

The serializer options governing tool parameter serialization. If null, the default options will be used.

cancellationToken CancellationToken

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

Returns

IAsyncEnumerable<McpClientTool>

An asynchronous sequence of all available tools as McpClientTool instances.

Examples

// Enumerate all tools available on the server
await foreach (var tool in client.EnumerateToolsAsync())
{
    Console.WriteLine($"Tool: {tool.Name}");
}

Remarks

This method uses asynchronous enumeration to retrieve tools from the server, which allows processing tools as they arrive rather than waiting for all tools to be retrieved. The method automatically handles pagination with cursors if the server responds with tools split across multiple responses.

The serializer options provided are flowed to each McpClientTool and will be used when invoking tools in order to serialize any parameters.

Every iteration through the returned IAsyncEnumerable<T> will result in re-querying the server and yielding the sequence of available tools.

Exceptions

ArgumentNullException

client is null.

GetPromptAsync(IMcpClient, string, IReadOnlyDictionary<string, object?>?, JsonSerializerOptions?, CancellationToken)

Retrieves a specific prompt from the MCP server.

public static Task<GetPromptResult> GetPromptAsync(this IMcpClient client, string name, IReadOnlyDictionary<string, object?>? arguments = null, JsonSerializerOptions? serializerOptions = null, CancellationToken cancellationToken = default)

Parameters

client IMcpClient

The client instance used to communicate with the MCP server.

name string

The name of the prompt to retrieve.

arguments IReadOnlyDictionary<string, object>

Optional arguments for the prompt. Keys are parameter names, and values are the argument values.

serializerOptions JsonSerializerOptions

The serialization options governing argument serialization.

cancellationToken CancellationToken

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

Returns

Task<GetPromptResult>

A task containing the prompt's result with content and messages.

Remarks

This method sends a request to the MCP server to create the specified prompt with the provided arguments. The server will process the arguments and return a prompt containing messages or other content.

Arguments are serialized into JSON and passed to the server, where they may be used to customize the prompt's behavior or content. Each prompt may have different argument requirements.

The returned GetPromptResult contains a collection of PromptMessage objects, which can be converted to Microsoft.Extensions.AI.ChatMessage objects using the ToChatMessages(GetPromptResult) method.

Exceptions

McpException

Thrown when the prompt does not exist, when required arguments are missing, or when the server encounters an error processing the prompt.

ArgumentNullException

client is null.

ListPromptsAsync(IMcpClient, CancellationToken)

Retrieves a list of available prompts from the server.

public static Task<IList<McpClientPrompt>> ListPromptsAsync(this IMcpClient client, CancellationToken cancellationToken = default)

Parameters

client IMcpClient

The client instance used to communicate with the MCP server.

cancellationToken CancellationToken

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

Returns

Task<IList<McpClientPrompt>>

A list of all available prompts as McpClientPrompt instances.

Remarks

This method fetches all available prompts from the MCP server and returns them as a complete list. It automatically handles pagination with cursors if the server responds with only a portion per request.

For servers with a large number of prompts and that responds with paginated responses, consider using EnumeratePromptsAsync(IMcpClient, CancellationToken) instead, as it streams prompts as they arrive rather than loading them all at once.

Exceptions

ArgumentNullException

client is null.

ListResourceTemplatesAsync(IMcpClient, CancellationToken)

Retrieves a list of available resource templates from the server.

public static Task<IList<ResourceTemplate>> ListResourceTemplatesAsync(this IMcpClient client, CancellationToken cancellationToken = default)

Parameters

client IMcpClient

The client instance used to communicate with the MCP server.

cancellationToken CancellationToken

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

Returns

Task<IList<ResourceTemplate>>

A list of all available resource templates as ResourceTemplate instances.

Remarks

This method fetches all available resource templates from the MCP server and returns them as a complete list. It automatically handles pagination with cursors if the server responds with only a portion per request.

For servers with a large number of resource templates and that responds with paginated responses, consider using EnumerateResourceTemplatesAsync(IMcpClient, CancellationToken) instead, as it streams templates as they arrive rather than loading them all at once.

Exceptions

ArgumentNullException

client is null.

ListResourcesAsync(IMcpClient, CancellationToken)

Retrieves a list of available resources from the server.

public static Task<IList<Resource>> ListResourcesAsync(this IMcpClient client, CancellationToken cancellationToken = default)

Parameters

client IMcpClient

The client instance used to communicate with the MCP server.

cancellationToken CancellationToken

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

Returns

Task<IList<Resource>>

A list of all available resources as Resource instances.

Examples

// Get all resources available on the server
var resources = await client.ListResourcesAsync();

// Display information about each resource
foreach (var resource in resources)
{
    Console.WriteLine($"Resource URI: {resource.Uri}");
}

Remarks

This method fetches all available resources from the MCP server and returns them as a complete list. It automatically handles pagination with cursors if the server responds with only a portion per request.

For servers with a large number of resources and that responds with paginated responses, consider using EnumerateResourcesAsync(IMcpClient, CancellationToken) instead, as it streams resources as they arrive rather than loading them all at once.

Exceptions

ArgumentNullException

client is null.

ListToolsAsync(IMcpClient, JsonSerializerOptions?, CancellationToken)

Retrieves a list of available tools from the server.

public static Task<IList<McpClientTool>> ListToolsAsync(this IMcpClient client, JsonSerializerOptions? serializerOptions = null, CancellationToken cancellationToken = default)

Parameters

client IMcpClient

The client instance used to communicate with the MCP server.

serializerOptions JsonSerializerOptions

The serializer options governing tool parameter serialization. If null, the default options will be used.

cancellationToken CancellationToken

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

Returns

Task<IList<McpClientTool>>

A list of all available tools as McpClientTool instances.

Examples

// Get all tools available on the server
var tools = await mcpClient.ListToolsAsync();

// Use tools with an AI client
ChatOptions chatOptions = new()
{
    Tools = [.. tools]
};

await foreach (var update in chatClient.GetStreamingResponseAsync(userMessage, chatOptions))
{
    Console.Write(update);
}

Remarks

This method fetches all available tools from the MCP server and returns them as a complete list. It automatically handles pagination with cursors if the server responds with only a portion per request.

For servers with a large number of tools and that responds with paginated responses, consider using EnumerateToolsAsync(IMcpClient, JsonSerializerOptions?, CancellationToken) instead, as it streams tools as they arrive rather than loading them all at once.

The serializer options provided are flowed to each McpClientTool and will be used when invoking tools in order to serialize any parameters.

Exceptions

ArgumentNullException

client is null.

PingAsync(IMcpClient, CancellationToken)

Sends a ping request to verify server connectivity.

public static Task PingAsync(this IMcpClient client, CancellationToken cancellationToken = default)

Parameters

client IMcpClient

The client instance used to communicate with the MCP server.

cancellationToken CancellationToken

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

Returns

Task

A task that completes when the ping is successful.

Remarks

This method is used to check if the MCP server is online and responding to requests. It can be useful for health checking, ensuring the connection is established, or verifying that the client has proper authorization to communicate with the server.

The ping operation is lightweight and does not require any parameters. A successful completion of the task indicates that the server is operational and accessible.

Exceptions

ArgumentNullException

client is null.

McpException

Thrown when the server cannot be reached or returns an error response.

ReadResourceAsync(IMcpClient, string, CancellationToken)

Reads a resource from the server.

public static Task<ReadResourceResult> ReadResourceAsync(this IMcpClient client, string uri, CancellationToken cancellationToken = default)

Parameters

client IMcpClient

The client instance used to communicate with the MCP server.

uri string

The uri of the resource.

cancellationToken CancellationToken

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

Returns

Task<ReadResourceResult>

Exceptions

ArgumentNullException

client is null.

ArgumentNullException

uri is null.

ArgumentException

uri is empty or composed entirely of whitespace.

ReadResourceAsync(IMcpClient, Uri, CancellationToken)

Reads a resource from the server.

public static Task<ReadResourceResult> ReadResourceAsync(this IMcpClient client, Uri uri, CancellationToken cancellationToken = default)

Parameters

client IMcpClient

The client instance used to communicate with the MCP server.

uri Uri

The uri of the resource.

cancellationToken CancellationToken

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

Returns

Task<ReadResourceResult>

Exceptions

ArgumentNullException

client is null.

ArgumentNullException

uri is null.

SetLoggingLevel(IMcpClient, LogLevel, CancellationToken)

Sets the logging level for the server to control which log messages are sent to the client.

public static Task SetLoggingLevel(this IMcpClient client, LogLevel level, CancellationToken cancellationToken = default)

Parameters

client IMcpClient

The client instance used to communicate with the MCP server.

level LogLevel

The minimum severity level of log messages to receive from the server.

cancellationToken CancellationToken

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

Returns

Task

A task representing the asynchronous operation.

Remarks

After this request is processed, the server will send log messages at or above the specified logging level as notifications to the client. For example, if Warning is set, the client will receive Warning, Error, and Critical level messages.

To receive all log messages, set the level to Trace.

Log messages are delivered as notifications to the client and can be captured by registering appropriate event handlers with the client implementation, such as with RegisterNotificationHandler(string, Func<JsonRpcNotification, CancellationToken, ValueTask>).

Exceptions

ArgumentNullException

client is null.

SetLoggingLevel(IMcpClient, LoggingLevel, CancellationToken)

Sets the logging level for the server to control which log messages are sent to the client.

public static Task SetLoggingLevel(this IMcpClient client, LoggingLevel level, CancellationToken cancellationToken = default)

Parameters

client IMcpClient

The client instance used to communicate with the MCP server.

level LoggingLevel

The minimum severity level of log messages to receive from the server.

cancellationToken CancellationToken

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

Returns

Task

A task representing the asynchronous operation.

Remarks

After this request is processed, the server will send log messages at or above the specified logging level as notifications to the client. For example, if Warning is set, the client will receive Warning, Error, Critical, Alert, and Emergency level messages.

To receive all log messages, set the level to Debug.

Log messages are delivered as notifications to the client and can be captured by registering appropriate event handlers with the client implementation, such as with RegisterNotificationHandler(string, Func<JsonRpcNotification, CancellationToken, ValueTask>).

Exceptions

ArgumentNullException

client is null.

SubscribeToResourceAsync(IMcpClient, string, CancellationToken)

Subscribes to a resource on the server to receive notifications when it changes.

public static Task SubscribeToResourceAsync(this IMcpClient client, string uri, CancellationToken cancellationToken = default)

Parameters

client IMcpClient

The client instance used to communicate with the MCP server.

uri string

The URI of the resource to which to subscribe.

cancellationToken CancellationToken

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

Returns

Task

A task that represents the asynchronous operation.

Remarks

This method allows the client to register interest in a specific resource identified by its URI. When the resource changes, the server will send notifications to the client, enabling real-time updates without polling.

The subscription remains active until explicitly unsubscribed using UnsubscribeFromResourceAsync or until the client disconnects from the server.

To handle resource change notifications, register an event handler for the appropriate notification events, such as with RegisterNotificationHandler(string, Func<JsonRpcNotification, CancellationToken, ValueTask>).

Exceptions

ArgumentNullException

client is null.

ArgumentNullException

uri is null.

ArgumentException

uri is empty or composed entirely of whitespace.

SubscribeToResourceAsync(IMcpClient, Uri, CancellationToken)

Subscribes to a resource on the server to receive notifications when it changes.

public static Task SubscribeToResourceAsync(this IMcpClient client, Uri uri, CancellationToken cancellationToken = default)

Parameters

client IMcpClient

The client instance used to communicate with the MCP server.

uri Uri

The URI of the resource to which to subscribe.

cancellationToken CancellationToken

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

Returns

Task

A task that represents the asynchronous operation.

Remarks

This method allows the client to register interest in a specific resource identified by its URI. When the resource changes, the server will send notifications to the client, enabling real-time updates without polling.

The subscription remains active until explicitly unsubscribed using UnsubscribeFromResourceAsync or until the client disconnects from the server.

To handle resource change notifications, register an event handler for the appropriate notification events, such as with RegisterNotificationHandler(string, Func<JsonRpcNotification, CancellationToken, ValueTask>).

Exceptions

ArgumentNullException

client is null.

ArgumentNullException

uri is null.

UnsubscribeFromResourceAsync(IMcpClient, string, CancellationToken)

Unsubscribes from a resource on the server to stop receiving notifications about its changes.

public static Task UnsubscribeFromResourceAsync(this IMcpClient client, string uri, CancellationToken cancellationToken = default)

Parameters

client IMcpClient

The client instance used to communicate with the MCP server.

uri string

The URI of the resource to unsubscribe from.

cancellationToken CancellationToken

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

Returns

Task

A task that represents the asynchronous operation.

Remarks

This method cancels a previous subscription to a resource, stopping the client from receiving notifications when that resource changes.

The unsubscribe operation is idempotent, meaning it can be called multiple times for the same resource without causing errors, even if there is no active subscription.

Due to the nature of the MCP protocol, it is possible the client may receive notifications after unsubscribing if those notifications were issued by the server prior to the unsubscribe request being received.

Exceptions

ArgumentNullException

client is null.

ArgumentNullException

uri is null.

ArgumentException

uri is empty or composed entirely of whitespace.

UnsubscribeFromResourceAsync(IMcpClient, Uri, CancellationToken)

Unsubscribes from a resource on the server to stop receiving notifications about its changes.

public static Task UnsubscribeFromResourceAsync(this IMcpClient client, Uri uri, CancellationToken cancellationToken = default)

Parameters

client IMcpClient

The client instance used to communicate with the MCP server.

uri Uri

The URI of the resource to unsubscribe from.

cancellationToken CancellationToken

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

Returns

Task

A task that represents the asynchronous operation.

Remarks

This method cancels a previous subscription to a resource, stopping the client from receiving notifications when that resource changes.

The unsubscribe operation is idempotent, meaning it can be called multiple times for the same resource without causing errors, even if there is no active subscription.

Due to the nature of the MCP protocol, it is possible the client may receive notifications after unsubscribing if those notifications were issued by the server prior to the unsubscribe request being received.

Exceptions

ArgumentNullException

client is null.

ArgumentNullException

uri is null.