Add request options bag to high level requests and include Meta (#970)

Co-authored-by: Stephen Toub <stoub@microsoft.com>
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
This commit is contained in:
Mike Kistler 2025-12-04 14:32:12 -08:00 • committed by GitHub
commit c447973972
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
33 changed files with 882 additions and 164 deletions

View file

@ -75,7 +75,7 @@ builder.Services
new ChatMessage(ChatRole.System, "You are a helpful test server"),
new ChatMessage(ChatRole.User, $"Resource {uri}, context: A new subscription was started"),
],
options: new ChatOptions
chatOptions: new ChatOptions
{
MaxOutputTokens = 100,
Temperature = 0.7f,

View file

@ -15,7 +15,7 @@ public class SampleLlmTool
CancellationToken cancellationToken)
{
var samplingParams = CreateRequestSamplingParams(prompt ?? string.Empty, "sampleLLM", maxTokens);
var sampleResult = await server.SampleAsync(samplingParams, cancellationToken);
var sampleResult = await server.SampleAsync(samplingParams, cancellationToken: cancellationToken);
return $"LLM sampling result: {sampleResult.Content.OfType<TextContentBlock>().FirstOrDefault()?.Text}";
}

View file

@ -18,7 +18,7 @@ public sealed class SampleLlmTool
CancellationToken cancellationToken)
{
var samplingParams = CreateRequestSamplingParams(prompt ?? string.Empty, "sampleLLM", maxTokens);
var sampleResult = await thisServer.SampleAsync(samplingParams, cancellationToken);
var sampleResult = await thisServer.SampleAsync(samplingParams, cancellationToken: cancellationToken);
return $"LLM sampling result: {sampleResult.Content.OfType<TextContentBlock>().FirstOrDefault()?.Text}";
}

View file

@ -4,6 +4,7 @@ using ModelContextProtocol.Protocol;
using ModelContextProtocol.Server;
using System.Runtime.CompilerServices;
using System.Text.Json;
using System.Text.Json.Nodes;
namespace ModelContextProtocol.Client;
@ -80,40 +81,37 @@ public abstract partial class McpClient : McpSession
/// <summary>
/// Sends a ping request to verify server connectivity.
/// </summary>
/// <param name="options">Optional request options including metadata, serialization settings, and progress tracking.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param>
/// <returns>A task that completes when the ping is successful.</returns>
/// <returns>A task containing the ping result.</returns>
/// <exception cref="McpException">The server cannot be reached or returned an error response.</exception>
public Task PingAsync(CancellationToken cancellationToken = default)
public ValueTask<PingResult> PingAsync(RequestOptions? options = null, CancellationToken cancellationToken = default)
{
var opts = McpJsonUtilities.DefaultOptions;
opts.MakeReadOnly();
return SendRequestAsync<object?, object>(
return SendRequestAsync(
RequestMethods.Ping,
parameters: null,
serializerOptions: opts,
cancellationToken: cancellationToken).AsTask();
new PingRequestParams { Meta = options?.Meta },
McpJsonUtilities.JsonContext.Default.PingRequestParams,
McpJsonUtilities.JsonContext.Default.PingResult,
cancellationToken: cancellationToken);
}
/// <summary>
/// Retrieves a list of available tools from the server.
/// </summary>
/// <param name="serializerOptions">The serializer options governing tool parameter serialization. If null, the default options are used.</param>
/// <param name="options">Optional request options including metadata, serialization settings, and progress tracking.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param>
/// <returns>A list of all available tools as <see cref="McpClientTool"/> instances.</returns>
public async ValueTask<IList<McpClientTool>> ListToolsAsync(
JsonSerializerOptions? serializerOptions = null,
RequestOptions? options = null,
CancellationToken cancellationToken = default)
{
serializerOptions ??= McpJsonUtilities.DefaultOptions;
serializerOptions.MakeReadOnly();
List<McpClientTool>? tools = null;
string? cursor = null;
do
{
var toolResults = await SendRequestAsync(
RequestMethods.ToolsList,
new() { Cursor = cursor },
new() { Cursor = cursor, Meta = options?.Meta },
McpJsonUtilities.JsonContext.Default.ListToolsRequestParams,
McpJsonUtilities.JsonContext.Default.ListToolsResult,
cancellationToken: cancellationToken).ConfigureAwait(false);
@ -121,7 +119,7 @@ public abstract partial class McpClient : McpSession
tools ??= new List<McpClientTool>(toolResults.Tools.Count);
foreach (var tool in toolResults.Tools)
{
tools.Add(new McpClientTool(this, tool, serializerOptions));
tools.Add(new McpClientTool(this, tool, options?.JsonSerializerOptions));
}
cursor = toolResults.NextCursor;
@ -134,9 +132,11 @@ public abstract partial class McpClient : McpSession
/// <summary>
/// Retrieves a list of available prompts from the server.
/// </summary>
/// <param name="options">Optional request options including metadata, serialization settings, and progress tracking.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param>
/// <returns>A list of all available prompts as <see cref="McpClientPrompt"/> instances.</returns>
public async ValueTask<IList<McpClientPrompt>> ListPromptsAsync(
RequestOptions? options = null,
CancellationToken cancellationToken = default)
{
List<McpClientPrompt>? prompts = null;
@ -145,7 +145,7 @@ public abstract partial class McpClient : McpSession
{
var promptResults = await SendRequestAsync(
RequestMethods.PromptsList,
new() { Cursor = cursor },
new() { Cursor = cursor, Meta = options?.Meta },
McpJsonUtilities.JsonContext.Default.ListPromptsRequestParams,
McpJsonUtilities.JsonContext.Default.ListPromptsResult,
cancellationToken: cancellationToken).ConfigureAwait(false);
@ -168,23 +168,23 @@ public abstract partial class McpClient : McpSession
/// </summary>
/// <param name="name">The name of the prompt to retrieve.</param>
/// <param name="arguments">Optional arguments for the prompt. The dictionary keys are parameter names, and the values are the argument values.</param>
/// <param name="serializerOptions">The serialization options governing argument serialization.</param>
/// <param name="options">Optional request options including metadata, serialization settings, and progress tracking.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param>
/// <returns>A task containing the prompt's result with content and messages.</returns>
public ValueTask<GetPromptResult> GetPromptAsync(
string name,
IReadOnlyDictionary<string, object?>? arguments = null,
JsonSerializerOptions? serializerOptions = null,
RequestOptions? options = null,
CancellationToken cancellationToken = default)
{
Throw.IfNullOrWhiteSpace(name);
serializerOptions ??= McpJsonUtilities.DefaultOptions;
var serializerOptions = options?.JsonSerializerOptions ?? McpJsonUtilities.DefaultOptions;
serializerOptions.MakeReadOnly();
return SendRequestAsync(
RequestMethods.PromptsGet,
new() { Name = name, Arguments = ToArgumentsDictionary(arguments, serializerOptions) },
new() { Name = name, Arguments = ToArgumentsDictionary(arguments, serializerOptions), Meta = options?.Meta },
McpJsonUtilities.JsonContext.Default.GetPromptRequestParams,
McpJsonUtilities.JsonContext.Default.GetPromptResult,
cancellationToken: cancellationToken);
@ -193,9 +193,11 @@ public abstract partial class McpClient : McpSession
/// <summary>
/// Retrieves a list of available resource templates from the server.
/// </summary>
/// <param name="options">Optional request options including metadata, serialization settings, and progress tracking.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param>
/// <returns>A list of all available resource templates as <see cref="ResourceTemplate"/> instances.</returns>
public async ValueTask<IList<McpClientResourceTemplate>> ListResourceTemplatesAsync(
RequestOptions? options = null,
CancellationToken cancellationToken = default)
{
List<McpClientResourceTemplate>? resourceTemplates = null;
@ -205,7 +207,7 @@ public abstract partial class McpClient : McpSession
{
var templateResults = await SendRequestAsync(
RequestMethods.ResourcesTemplatesList,
new() { Cursor = cursor },
new() { Cursor = cursor, Meta = options?.Meta },
McpJsonUtilities.JsonContext.Default.ListResourceTemplatesRequestParams,
McpJsonUtilities.JsonContext.Default.ListResourceTemplatesResult,
cancellationToken: cancellationToken).ConfigureAwait(false);
@ -226,9 +228,11 @@ public abstract partial class McpClient : McpSession
/// <summary>
/// Retrieves a list of available resources from the server.
/// </summary>
/// <param name="options">Optional request options including metadata, serialization settings, and progress tracking.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param>
/// <returns>A list of all available resources as <see cref="Resource"/> instances.</returns>
public async ValueTask<IList<McpClientResource>> ListResourcesAsync(
RequestOptions? options = null,
CancellationToken cancellationToken = default)
{
List<McpClientResource>? resources = null;
@ -238,7 +242,7 @@ public abstract partial class McpClient : McpSession
{
var resourceResults = await SendRequestAsync(
RequestMethods.ResourcesList,
new() { Cursor = cursor },
new() { Cursor = cursor, Meta = options?.Meta },
McpJsonUtilities.JsonContext.Default.ListResourcesRequestParams,
McpJsonUtilities.JsonContext.Default.ListResourcesResult,
cancellationToken: cancellationToken).ConfigureAwait(false);
@ -260,15 +264,16 @@ public abstract partial class McpClient : McpSession
/// Reads a resource from the server.
/// </summary>
/// <param name="uri">The URI of the resource.</param>
/// <param name="options">Optional request options including metadata, serialization settings, and progress tracking.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param>
public ValueTask<ReadResourceResult> ReadResourceAsync(
string uri, CancellationToken cancellationToken = default)
string uri, RequestOptions? options = null, CancellationToken cancellationToken = default)
{
Throw.IfNullOrWhiteSpace(uri);
return SendRequestAsync(
RequestMethods.ResourcesRead,
new() { Uri = uri },
new() { Uri = uri, Meta = options?.Meta },
McpJsonUtilities.JsonContext.Default.ReadResourceRequestParams,
McpJsonUtilities.JsonContext.Default.ReadResourceResult,
cancellationToken: cancellationToken);
@ -278,13 +283,14 @@ public abstract partial class McpClient : McpSession
/// Reads a resource from the server.
/// </summary>
/// <param name="uri">The URI of the resource.</param>
/// <param name="options">Optional request options including metadata, serialization settings, and progress tracking.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param>
public ValueTask<ReadResourceResult> ReadResourceAsync(
Uri uri, CancellationToken cancellationToken = default)
Uri uri, RequestOptions? options = null, CancellationToken cancellationToken = default)
{
Throw.IfNull(uri);
return ReadResourceAsync(uri.ToString(), cancellationToken);
return ReadResourceAsync(uri.ToString(), options, cancellationToken);
}
/// <summary>
@ -292,16 +298,17 @@ public abstract partial class McpClient : McpSession
/// </summary>
/// <param name="uriTemplate">The URI template of the resource.</param>
/// <param name="arguments">Arguments to use to format <paramref name="uriTemplate"/>.</param>
/// <param name="options">Optional request options including metadata, serialization settings, and progress tracking.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param>
public ValueTask<ReadResourceResult> ReadResourceAsync(
string uriTemplate, IReadOnlyDictionary<string, object?> arguments, CancellationToken cancellationToken = default)
string uriTemplate, IReadOnlyDictionary<string, object?> arguments, RequestOptions? options = null, CancellationToken cancellationToken = default)
{
Throw.IfNullOrWhiteSpace(uriTemplate);
Throw.IfNull(arguments);
return SendRequestAsync(
RequestMethods.ResourcesRead,
new() { Uri = UriTemplate.FormatUri(uriTemplate, arguments) },
new() { Uri = UriTemplate.FormatUri(uriTemplate, arguments), Meta = options?.Meta },
McpJsonUtilities.JsonContext.Default.ReadResourceRequestParams,
McpJsonUtilities.JsonContext.Default.ReadResourceResult,
cancellationToken: cancellationToken);
@ -336,15 +343,16 @@ public abstract partial class McpClient : McpSession
/// Subscribes to a resource on the server to receive notifications when it changes.
/// </summary>
/// <param name="uri">The URI of the resource to which to subscribe.</param>
/// <param name="options">Optional request options including metadata, serialization settings, and progress tracking.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
public Task SubscribeToResourceAsync(string uri, CancellationToken cancellationToken = default)
public Task SubscribeToResourceAsync(string uri, RequestOptions? options = null, CancellationToken cancellationToken = default)
{
Throw.IfNullOrWhiteSpace(uri);
return SendRequestAsync(
RequestMethods.ResourcesSubscribe,
new() { Uri = uri },
new() { Uri = uri, Meta = options?.Meta },
McpJsonUtilities.JsonContext.Default.SubscribeRequestParams,
McpJsonUtilities.JsonContext.Default.EmptyResult,
cancellationToken: cancellationToken).AsTask();
@ -354,28 +362,30 @@ public abstract partial class McpClient : McpSession
/// Subscribes to a resource on the server to receive notifications when it changes.
/// </summary>
/// <param name="uri">The URI of the resource to which to subscribe.</param>
/// <param name="options">Optional request options including metadata, serialization settings, and progress tracking.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
public Task SubscribeToResourceAsync(Uri uri, CancellationToken cancellationToken = default)
public Task SubscribeToResourceAsync(Uri uri, RequestOptions? options = null, CancellationToken cancellationToken = default)
{
Throw.IfNull(uri);
return SubscribeToResourceAsync(uri.ToString(), cancellationToken);
return SubscribeToResourceAsync(uri.ToString(), options, cancellationToken);
}
/// <summary>
/// Unsubscribes from a resource on the server to stop receiving notifications about its changes.
/// </summary>
/// <param name="uri">The URI of the resource to unsubscribe from.</param>
/// <param name="options">Optional request options including metadata, serialization settings, and progress tracking.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
public Task UnsubscribeFromResourceAsync(string uri, CancellationToken cancellationToken = default)
public Task UnsubscribeFromResourceAsync(string uri, RequestOptions? options = null, CancellationToken cancellationToken = default)
{
Throw.IfNullOrWhiteSpace(uri);
return SendRequestAsync(
RequestMethods.ResourcesUnsubscribe,
new() { Uri = uri },
new() { Uri = uri, Meta = options?.Meta },
McpJsonUtilities.JsonContext.Default.UnsubscribeRequestParams,
McpJsonUtilities.JsonContext.Default.EmptyResult,
cancellationToken: cancellationToken).AsTask();
@ -385,13 +395,14 @@ public abstract partial class McpClient : McpSession
/// Unsubscribes from a resource on the server to stop receiving notifications about its changes.
/// </summary>
/// <param name="uri">The URI of the resource to unsubscribe from.</param>
/// <param name="options">Optional request options including metadata, serialization settings, and progress tracking.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
public Task UnsubscribeFromResourceAsync(Uri uri, CancellationToken cancellationToken = default)
public Task UnsubscribeFromResourceAsync(Uri uri, RequestOptions? options = null, CancellationToken cancellationToken = default)
{
Throw.IfNull(uri);
return UnsubscribeFromResourceAsync(uri.ToString(), cancellationToken);
return UnsubscribeFromResourceAsync(uri.ToString(), options, cancellationToken);
}
/// <summary>
@ -400,23 +411,23 @@ public abstract partial class McpClient : McpSession
/// <param name="toolName">The name of the tool to call on the server.</param>
/// <param name="arguments">An optional dictionary of arguments to pass to the tool.</param>
/// <param name="progress">An optional progress reporter for server notifications.</param>
/// <param name="serializerOptions">The JSON serializer options.</param>
/// <param name="options">Optional request options including metadata, serialization settings, and progress tracking.</param>
/// <param name="cancellationToken">A cancellation token.</param>
/// <returns>The <see cref="CallToolResult"/> from the tool execution.</returns>
public ValueTask<CallToolResult> CallToolAsync(
string toolName,
IReadOnlyDictionary<string, object?>? arguments = null,
IProgress<ProgressNotificationValue>? progress = null,
JsonSerializerOptions? serializerOptions = null,
RequestOptions? options = null,
CancellationToken cancellationToken = default)
{
Throw.IfNull(toolName);
serializerOptions ??= McpJsonUtilities.DefaultOptions;
var serializerOptions = options?.JsonSerializerOptions ?? McpJsonUtilities.DefaultOptions;
serializerOptions.MakeReadOnly();
if (progress is not null)
{
return SendRequestWithProgressAsync(toolName, arguments, progress, serializerOptions, cancellationToken);
return SendRequestWithProgressAsync(toolName, arguments, progress, options?.Meta, serializerOptions, cancellationToken);
}
return SendRequestAsync(
@ -425,6 +436,7 @@ public abstract partial class McpClient : McpSession
{
Name = toolName,
Arguments = ToArgumentsDictionary(arguments, serializerOptions),
Meta = options?.Meta,
},
McpJsonUtilities.JsonContext.Default.CallToolRequestParams,
McpJsonUtilities.JsonContext.Default.CallToolResult,
@ -434,6 +446,7 @@ public abstract partial class McpClient : McpSession
string toolName,
IReadOnlyDictionary<string, object?>? arguments,
IProgress<ProgressNotificationValue> progress,
JsonObject? meta,
JsonSerializerOptions serializerOptions,
CancellationToken cancellationToken)
{
@ -451,13 +464,16 @@ public abstract partial class McpClient : McpSession
return default;
}).ConfigureAwait(false);
var metaWithProgress = meta is not null ? new JsonObject(meta) : new JsonObject();
metaWithProgress["progressToken"] = progressToken.ToString();
return await SendRequestAsync(
RequestMethods.ToolsCall,
new()
{
Name = toolName,
Arguments = ToArgumentsDictionary(arguments, serializerOptions),
ProgressToken = progressToken,
Meta = metaWithProgress,
},
McpJsonUtilities.JsonContext.Default.CallToolRequestParams,
McpJsonUtilities.JsonContext.Default.CallToolResult,
@ -469,13 +485,14 @@ public abstract partial class McpClient : McpSession
/// Sets the logging level for the server to control which log messages are sent to the client.
/// </summary>
/// <param name="level">The minimum severity level of log messages to receive from the server.</param>
/// <param name="options">Optional request options including metadata, serialization settings, and progress tracking.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param>
/// <returns>A task representing the asynchronous operation.</returns>
public Task SetLoggingLevel(LoggingLevel level, CancellationToken cancellationToken = default)
public Task SetLoggingLevel(LoggingLevel level, RequestOptions? options = null, CancellationToken cancellationToken = default)
{
return SendRequestAsync(
RequestMethods.LoggingSetLevel,
new() { Level = level },
new() { Level = level, Meta = options?.Meta },
McpJsonUtilities.JsonContext.Default.SetLevelRequestParams,
McpJsonUtilities.JsonContext.Default.EmptyResult,
cancellationToken: cancellationToken).AsTask();
@ -485,10 +502,11 @@ public abstract partial class McpClient : McpSession
/// Sets the logging level for the server to control which log messages are sent to the client.
/// </summary>
/// <param name="level">The minimum severity level of log messages to receive from the server.</param>
/// <param name="options">Optional request options including metadata, serialization settings, and progress tracking.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param>
/// <returns>A task representing the asynchronous operation.</returns>
public Task SetLoggingLevel(LogLevel level, CancellationToken cancellationToken = default) =>
SetLoggingLevel(McpServerImpl.ToLoggingLevel(level), cancellationToken);
public Task SetLoggingLevel(LogLevel level, RequestOptions? options = null, CancellationToken cancellationToken = default) =>
SetLoggingLevel(McpServerImpl.ToLoggingLevel(level), options, cancellationToken);
/// <summary>Converts a dictionary with <see cref="object"/> values to a dictionary with <see cref="JsonElement"/> values.</summary>
private static Dictionary<string, JsonElement>? ToArgumentsDictionary(

View file

@ -96,6 +96,6 @@ public sealed class McpClientPrompt
arguments as IReadOnlyDictionary<string, object?> ??
arguments?.ToDictionary();
return await _client.GetPromptAsync(ProtocolPrompt.Name, argDict, serializerOptions, cancellationToken: cancellationToken).ConfigureAwait(false);
return await _client.GetPromptAsync(ProtocolPrompt.Name, argDict, new RequestOptions() { JsonSerializerOptions = serializerOptions }, cancellationToken).ConfigureAwait(false);
}
}

View file

@ -78,10 +78,10 @@ public sealed class McpClientResource
/// <returns>A <see cref="ValueTask{ReadResourceResult}"/> containing the resource's result with content and messages.</returns>
/// <remarks>
/// <para>
/// This is a convenience method that internally calls <see cref="McpClient.ReadResourceAsync(string, CancellationToken)"/>.
/// This is a convenience method that internally calls <see cref="McpClient.ReadResourceAsync(string, RequestOptions, CancellationToken)"/>.
/// </para>
/// </remarks>
public ValueTask<ReadResourceResult> ReadAsync(
CancellationToken cancellationToken = default) =>
_client.ReadResourceAsync(Uri, cancellationToken);
_client.ReadResourceAsync(Uri, cancellationToken: cancellationToken);
}

View file

@ -83,5 +83,5 @@ public sealed class McpClientResourceTemplate
public ValueTask<ReadResourceResult> ReadAsync(
IReadOnlyDictionary<string, object?> arguments,
CancellationToken cancellationToken = default) =>
_client.ReadResourceAsync(UriTemplate, arguments, cancellationToken);
_client.ReadResourceAsync(UriTemplate, arguments, cancellationToken: cancellationToken);
}

View file

@ -128,7 +128,11 @@ public sealed class McpClientTool : AIFunction
protected async override ValueTask<object?> InvokeCoreAsync(
AIFunctionArguments arguments, CancellationToken cancellationToken)
{
CallToolResult result = await CallAsync(arguments, _progress, JsonSerializerOptions, cancellationToken).ConfigureAwait(false);
var options = JsonSerializerOptions is null ? null : new RequestOptions()
{
JsonSerializerOptions = JsonSerializerOptions,
};
CallToolResult result = await CallAsync(arguments, _progress, options, cancellationToken).ConfigureAwait(false);
// We want to translate the result content into AIContent, using AIContent as the exchange types, so
// that downstream IChatClients can specialize handling based on the content (e.g. sending image content
@ -163,8 +167,8 @@ public sealed class McpClientTool : AIFunction
/// value will result in a progress token being included in the call, and any resulting progress notifications during the operation
/// routed to this instance.
/// </param>
/// <param name="serializerOptions">
/// The JSON serialization options governing argument serialization. If <see langword="null"/>, the default serialization options are used.
/// <param name="options">
/// Optional request options including metadata, serialization settings, and progress tracking.
/// </param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param>
/// <returns>
@ -191,9 +195,16 @@ public sealed class McpClientTool : AIFunction
public ValueTask<CallToolResult> CallAsync(
IReadOnlyDictionary<string, object?>? arguments = null,
IProgress<ProgressNotificationValue>? progress = null,
JsonSerializerOptions? serializerOptions = null,
RequestOptions? options = null,
CancellationToken cancellationToken = default) =>
_client.CallToolAsync(ProtocolTool.Name, arguments, progress, serializerOptions, cancellationToken);
_client.CallToolAsync(
ProtocolTool.Name,
arguments,
progress,
options ?? new RequestOptions() {
JsonSerializerOptions = JsonSerializerOptions
},
cancellationToken);
/// <summary>
/// Creates a new instance of the tool but modified to return the specified name from its <see cref="Name"/> property.

View file

@ -132,6 +132,7 @@ public static partial class McpJsonUtilities
[JsonSerializable(typeof(ListRootsResult))]
[JsonSerializable(typeof(ListToolsRequestParams))]
[JsonSerializable(typeof(ListToolsResult))]
[JsonSerializable(typeof(PingRequestParams))]
[JsonSerializable(typeof(PingResult))]
[JsonSerializable(typeof(ReadResourceRequestParams))]
[JsonSerializable(typeof(ReadResourceResult))]

View file

@ -150,6 +150,7 @@ public abstract partial class McpSession : IAsyncDisposable
/// </summary>
/// <param name="progressToken">The token that identifies the operation for which progress is being reported.</param>
/// <param name="progress">The progress update to send, containing information such as percentage complete or status message.</param>
/// <param name="options">Optional request options including metadata, serialization settings, and progress tracking.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param>
/// <returns>A task representing the completion of the notification operation (not the operation being tracked).</returns>
/// <exception cref="ArgumentNullException">The current session instance is <see langword="null"/>.</exception>
@ -166,6 +167,7 @@ public abstract partial class McpSession : IAsyncDisposable
public Task NotifyProgressAsync(
ProgressToken progressToken,
ProgressNotificationValue progress,
RequestOptions? options = null,
CancellationToken cancellationToken = default)
{
return SendNotificationAsync(
@ -174,6 +176,7 @@ public abstract partial class McpSession : IAsyncDisposable
{
ProgressToken = progressToken,
Progress = progress,
Meta = options?.Meta,
},
McpJsonUtilities.JsonContext.Default.ProgressNotificationParams,
cancellationToken);

View file

@ -0,0 +1,11 @@
namespace ModelContextProtocol.Protocol;
/// <summary>
/// Represents the parameters used with a <see cref="RequestMethods.Ping"/> request to verify
/// server connectivity.
/// </summary>
/// <remarks>
/// The server responds with a <see cref="PingResult"/>.
/// See the <see href="https://github.com/modelcontextprotocol/specification/blob/main/schema/">schema</see> for details.
/// </remarks>
public sealed class PingRequestParams : RequestParams;

View file

@ -26,7 +26,7 @@ public abstract class RequestParams
public JsonObject? Meta { get; set; }
/// <summary>
/// Gets or sets an opaque token that will be attached to any subsequent progress notifications.
/// Gets the opaque token that will be attached to any subsequent progress notifications.
/// </summary>
[JsonIgnore]
public ProgressToken? ProgressToken
@ -48,21 +48,5 @@ public abstract class RequestParams
return null;
}
set
{
if (value is null)
{
Meta?.Remove("progressToken");
}
else
{
(Meta ??= [])["progressToken"] = value.Value.Token switch
{
string s => JsonValue.Create(s),
long l => JsonValue.Create(l),
_ => throw new InvalidOperationException("ProgressToken must be a string or a long.")
};
}
}
}
}

View file

@ -50,7 +50,7 @@ foreach (var tool in await client.ListToolsAsync())
var result = await client.CallToolAsync(
"echo",
new Dictionary<string, object?>() { ["message"] = "Hello MCP!" },
cancellationToken:CancellationToken.None);
cancellationToken: CancellationToken.None);
// echo always returns one and only one text content object
Console.WriteLine(result.Content.First(c => c.Type == "text").Text);
@ -83,13 +83,13 @@ using System.ComponentModel;
var serverOptions = new McpServerOptions();
// Add tools directly
serverOptions.Capabilities.Tools = new()
serverOptions.Capabilities.Tools = new()
{
ListChanged = true,
ToolCollection = [
McpServerTool.Create((string message) => $"hello {message}", new()
{
Name = "echo",
Name = "echo",
Description = "Echoes the message back to the client."
})
]

View file

@ -0,0 +1,96 @@
using System.Text.Json;
using System.Text.Json.Nodes;
using ModelContextProtocol.Protocol;
namespace ModelContextProtocol;
/// <summary>
/// Contains optional parameters for MCP requests.
/// </summary>
public sealed class RequestOptions
{
/// <summary>
/// Optional metadata to include in the request.
/// </summary>
private JsonObject? _meta;
/// <summary>
/// Initializes a new instance of the <see cref="RequestOptions"/> class.
/// </summary>
public RequestOptions()
{
}
/// <summary>
/// Optional metadata to include in the request.
/// When getting, automatically includes the progress token if set.
/// </summary>
public JsonObject? Meta
{
get => _meta ??= [];
set
{
// Capture the existing progressToken value if set.
var existingProgressToken = _meta?["progressToken"];
if (value is not null)
{
if (existingProgressToken is not null)
{
value["progressToken"] ??= existingProgressToken;
}
_meta = value;
}
else if (existingProgressToken is not null)
{
_meta = new()
{
["progressToken"] = existingProgressToken,
};
}
else
{
_meta = null;
}
}
}
/// <summary>
/// The serializer options governing tool parameter serialization. If null, the default options are used.
/// </summary>
public JsonSerializerOptions? JsonSerializerOptions { get; set; }
/// <summary>
/// The progress token for tracking long-running operations.
/// </summary>
public ProgressToken? ProgressToken
{
get
{
return _meta?["progressToken"] switch
{
JsonValue v when v.TryGetValue(out string? s) => new(s),
JsonValue v when v.TryGetValue(out long l) => new(l),
_ => null
};
}
set
{
if (value?.Token is { } token)
{
_meta ??= [];
_meta["progressToken"] = token switch
{
string s => s,
long l => l,
_ => throw new InvalidOperationException("ProgressToken must be a string or long"),
};
}
else
{
_meta?.Remove("progressToken");
}
}
}
}

View file

@ -68,19 +68,19 @@ public abstract partial class McpServer : McpSession
/// Requests to sample an LLM via the client using the provided chat messages and options.
/// </summary>
/// <param name="messages">The messages to send as part of the request.</param>
/// <param name="options">The options to use for the request, including model parameters and constraints.</param>
/// <param name="chatOptions">The options to use for the request, including model parameters and constraints.</param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param>
/// <returns>A task containing the chat response from the model.</returns>
/// <exception cref="ArgumentNullException"><paramref name="messages"/> is <see langword="null"/>.</exception>
/// <exception cref="InvalidOperationException">The client does not support sampling.</exception>
public async Task<ChatResponse> SampleAsync(
IEnumerable<ChatMessage> messages, ChatOptions? options = default, CancellationToken cancellationToken = default)
IEnumerable<ChatMessage> messages, ChatOptions? chatOptions = default, CancellationToken cancellationToken = default)
{
Throw.IfNull(messages);
StringBuilder? systemPrompt = null;
if (options?.Instructions is { } instructions)
if (chatOptions?.Instructions is { } instructions)
{
(systemPrompt ??= new()).Append(instructions);
}
@ -126,15 +126,15 @@ public abstract partial class McpServer : McpSession
}
ModelPreferences? modelPreferences = null;
if (options?.ModelId is { } modelId)
if (chatOptions?.ModelId is { } modelId)
{
modelPreferences = new() { Hints = [new() { Name = modelId }] };
}
IList<Tool>? tools = null;
if (options?.Tools is { Count: > 0 })
if (chatOptions?.Tools is { Count: > 0 })
{
foreach (var tool in options.Tools)
foreach (var tool in chatOptions.Tools)
{
if (tool is AIFunctionDeclaration af)
{
@ -149,7 +149,7 @@ public abstract partial class McpServer : McpSession
}
}
ToolChoice? toolChoice = options?.ToolMode switch
ToolChoice? toolChoice = chatOptions?.ToolMode switch
{
NoneChatToolMode => new() { Mode = ToolChoice.ModeNone },
AutoChatToolMode => new() { Mode = ToolChoice.ModeAuto },
@ -159,15 +159,15 @@ public abstract partial class McpServer : McpSession
var result = await SampleAsync(new()
{
MaxTokens = options?.MaxOutputTokens ?? ServerOptions.MaxSamplingOutputTokens,
MaxTokens = chatOptions?.MaxOutputTokens ?? ServerOptions.MaxSamplingOutputTokens,
Messages = samplingMessages,
ModelPreferences = modelPreferences,
StopSequences = options?.StopSequences?.ToArray(),
StopSequences = chatOptions?.StopSequences?.ToArray(),
SystemPrompt = systemPrompt?.ToString(),
Temperature = options?.Temperature,
Temperature = chatOptions?.Temperature,
ToolChoice = toolChoice,
Tools = tools,
Meta = options?.AdditionalProperties?.ToJsonObject(),
Meta = chatOptions?.AdditionalProperties?.ToJsonObject(),
}, cancellationToken).ConfigureAwait(false);
List<AIContent> responseContents = [];
@ -472,14 +472,14 @@ public abstract partial class McpServer : McpSession
private readonly McpServer _server = server;
/// <inheritdoc/>
public Task<ChatResponse> GetResponseAsync(IEnumerable<ChatMessage> messages, ChatOptions? options = null, CancellationToken cancellationToken = default) =>
_server.SampleAsync(messages, options, cancellationToken);
public Task<ChatResponse> GetResponseAsync(IEnumerable<ChatMessage> messages, ChatOptions? chatOptions = null, CancellationToken cancellationToken = default) =>
_server.SampleAsync(messages, chatOptions, cancellationToken);
/// <inheritdoc/>
async IAsyncEnumerable<ChatResponseUpdate> IChatClient.GetStreamingResponseAsync(
IEnumerable<ChatMessage> messages, ChatOptions? options, [EnumeratorCancellation] CancellationToken cancellationToken)
IEnumerable<ChatMessage> messages, ChatOptions? chatOptions, [EnumeratorCancellation] CancellationToken cancellationToken)
{
var response = await GetResponseAsync(messages, options, cancellationToken).ConfigureAwait(false);
var response = await GetResponseAsync(messages, chatOptions, cancellationToken).ConfigureAwait(false);
foreach (var update in response.ToChatResponseUpdates())
{
yield return update;

View file

@ -11,6 +11,6 @@ internal sealed class TokenProgress(McpSession session, ProgressToken progressTo
/// <inheritdoc />
public void Report(ProgressNotificationValue value)
{
_ = session.NotifyProgressAsync(progressToken, value, CancellationToken.None);
_ = session.NotifyProgressAsync(progressToken, value, cancellationToken: CancellationToken.None);
}
}

View file

@ -35,7 +35,7 @@ public abstract class HttpServerIntegrationTests : LoggedTest, IClassFixture<Sse
// Act
await using var client = await GetClientAsync();
await client.PingAsync(TestContext.Current.CancellationToken);
await client.PingAsync(null, TestContext.Current.CancellationToken);
// Assert
Assert.NotNull(client);
@ -139,7 +139,7 @@ public abstract class HttpServerIntegrationTests : LoggedTest, IClassFixture<Sse
// act
await using var client = await GetClientAsync();
IList<McpClientResource> allResources = await client.ListResourcesAsync(TestContext.Current.CancellationToken);
IList<McpClientResource> allResources = await client.ListResourcesAsync(null, TestContext.Current.CancellationToken);
// The everything server provides 100 test resources
Assert.Equal(100, allResources.Count);
@ -155,7 +155,7 @@ public abstract class HttpServerIntegrationTests : LoggedTest, IClassFixture<Sse
// Odd numbered resources are text in the everything server (despite the docs saying otherwise)
// 1 is index 0, which is "even" in the 0-based index
// We copied this oddity to the test server
var result = await client.ReadResourceAsync("test://static/resource/1", TestContext.Current.CancellationToken);
var result = await client.ReadResourceAsync("test://static/resource/1", null, TestContext.Current.CancellationToken);
Assert.NotNull(result);
Assert.Single(result.Contents);
@ -174,7 +174,7 @@ public abstract class HttpServerIntegrationTests : LoggedTest, IClassFixture<Sse
// Even numbered resources are binary in the everything server (despite the docs saying otherwise)
// 2 is index 1, which is "odd" in the 0-based index
// We copied this oddity to the test server
var result = await client.ReadResourceAsync("test://static/resource/2", TestContext.Current.CancellationToken);
var result = await client.ReadResourceAsync("test://static/resource/2", null, TestContext.Current.CancellationToken);
Assert.NotNull(result);
Assert.Single(result.Contents);
@ -190,7 +190,7 @@ public abstract class HttpServerIntegrationTests : LoggedTest, IClassFixture<Sse
// act
await using var client = await GetClientAsync();
var prompts = await client.ListPromptsAsync(TestContext.Current.CancellationToken);
var prompts = await client.ListPromptsAsync(null, TestContext.Current.CancellationToken);
// assert
Assert.NotNull(prompts);

View file

@ -47,7 +47,7 @@ public class Program
new ChatMessage(ChatRole.System, "You are a helpful test server"),
new ChatMessage(ChatRole.User, $"Resource {uri}, context: A new subscription was started"),
],
options: new ChatOptions
chatOptions: new ChatOptions
{
MaxOutputTokens = 100,
Temperature = 0.7f,

View file

@ -141,7 +141,7 @@ public class ConformanceTools
{
Progress = 0,
Total = 100,
}, cancellationToken);
}, cancellationToken: cancellationToken);
await Task.Delay(50, cancellationToken);
@ -149,7 +149,7 @@ public class ConformanceTools
{
Progress = 50,
Total = 100,
}, cancellationToken);
}, cancellationToken: cancellationToken);
await Task.Delay(50, cancellationToken);
@ -157,7 +157,7 @@ public class ConformanceTools
{
Progress = 100,
Total = 100,
}, cancellationToken);
}, cancellationToken: cancellationToken);
}
return progressToken?.ToString() ?? "No progress token provided";

View file

@ -193,7 +193,7 @@ internal static class Program
throw new McpProtocolException("Missing required arguments 'prompt' and 'maxTokens'", McpErrorCode.InvalidParams);
}
var sampleResult = await request.Server.SampleAsync(CreateRequestSamplingParams(prompt.ToString(), "sampleLLM", Convert.ToInt32(maxTokens.GetRawText())),
cancellationToken);
cancellationToken: cancellationToken);
return new CallToolResult
{

Some files were not shown because too many files have changed in this diff Show more