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.System, "You are a helpful test server"),
new ChatMessage(ChatRole.User, $"Resource {uri}, context: A new subscription was started"), new ChatMessage(ChatRole.User, $"Resource {uri}, context: A new subscription was started"),
], ],
options: new ChatOptions chatOptions: new ChatOptions
{ {
MaxOutputTokens = 100, MaxOutputTokens = 100,
Temperature = 0.7f, Temperature = 0.7f,

View file

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

View file

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

View file

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

View file

@ -96,6 +96,6 @@ public sealed class McpClientPrompt
arguments as IReadOnlyDictionary<string, object?> ?? arguments as IReadOnlyDictionary<string, object?> ??
arguments?.ToDictionary(); 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> /// <returns>A <see cref="ValueTask{ReadResourceResult}"/> containing the resource's result with content and messages.</returns>
/// <remarks> /// <remarks>
/// <para> /// <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> /// </para>
/// </remarks> /// </remarks>
public ValueTask<ReadResourceResult> ReadAsync( public ValueTask<ReadResourceResult> ReadAsync(
CancellationToken cancellationToken = default) => 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( public ValueTask<ReadResourceResult> ReadAsync(
IReadOnlyDictionary<string, object?> arguments, IReadOnlyDictionary<string, object?> arguments,
CancellationToken cancellationToken = default) => 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( protected async override ValueTask<object?> InvokeCoreAsync(
AIFunctionArguments arguments, CancellationToken cancellationToken) 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 // 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 // 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 /// value will result in a progress token being included in the call, and any resulting progress notifications during the operation
/// routed to this instance. /// routed to this instance.
/// </param> /// </param>
/// <param name="serializerOptions"> /// <param name="options">
/// The JSON serialization options governing argument serialization. If <see langword="null"/>, the default serialization options are used. /// Optional request options including metadata, serialization settings, and progress tracking.
/// </param> /// </param>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param>
/// <returns> /// <returns>
@ -191,9 +195,16 @@ public sealed class McpClientTool : AIFunction
public ValueTask<CallToolResult> CallAsync( public ValueTask<CallToolResult> CallAsync(
IReadOnlyDictionary<string, object?>? arguments = null, IReadOnlyDictionary<string, object?>? arguments = null,
IProgress<ProgressNotificationValue>? progress = null, IProgress<ProgressNotificationValue>? progress = null,
JsonSerializerOptions? serializerOptions = null, RequestOptions? options = null,
CancellationToken cancellationToken = default) => CancellationToken cancellationToken = default) =>
_client.CallToolAsync(ProtocolTool.Name, arguments, progress, serializerOptions, cancellationToken); _client.CallToolAsync(
ProtocolTool.Name,
arguments,
progress,
options ?? new RequestOptions() {
JsonSerializerOptions = JsonSerializerOptions
},
cancellationToken);
/// <summary> /// <summary>
/// Creates a new instance of the tool but modified to return the specified name from its <see cref="Name"/> property. /// 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(ListRootsResult))]
[JsonSerializable(typeof(ListToolsRequestParams))] [JsonSerializable(typeof(ListToolsRequestParams))]
[JsonSerializable(typeof(ListToolsResult))] [JsonSerializable(typeof(ListToolsResult))]
[JsonSerializable(typeof(PingRequestParams))]
[JsonSerializable(typeof(PingResult))] [JsonSerializable(typeof(PingResult))]
[JsonSerializable(typeof(ReadResourceRequestParams))] [JsonSerializable(typeof(ReadResourceRequestParams))]
[JsonSerializable(typeof(ReadResourceResult))] [JsonSerializable(typeof(ReadResourceResult))]

View file

@ -150,6 +150,7 @@ public abstract partial class McpSession : IAsyncDisposable
/// </summary> /// </summary>
/// <param name="progressToken">The token that identifies the operation for which progress is being reported.</param> /// <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="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> /// <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> /// <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> /// <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( public Task NotifyProgressAsync(
ProgressToken progressToken, ProgressToken progressToken,
ProgressNotificationValue progress, ProgressNotificationValue progress,
RequestOptions? options = null,
CancellationToken cancellationToken = default) CancellationToken cancellationToken = default)
{ {
return SendNotificationAsync( return SendNotificationAsync(
@ -174,6 +176,7 @@ public abstract partial class McpSession : IAsyncDisposable
{ {
ProgressToken = progressToken, ProgressToken = progressToken,
Progress = progress, Progress = progress,
Meta = options?.Meta,
}, },
McpJsonUtilities.JsonContext.Default.ProgressNotificationParams, McpJsonUtilities.JsonContext.Default.ProgressNotificationParams,
cancellationToken); 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; } public JsonObject? Meta { get; set; }
/// <summary> /// <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> /// </summary>
[JsonIgnore] [JsonIgnore]
public ProgressToken? ProgressToken public ProgressToken? ProgressToken
@ -48,21 +48,5 @@ public abstract class RequestParams
return null; 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( var result = await client.CallToolAsync(
"echo", "echo",
new Dictionary<string, object?>() { ["message"] = "Hello MCP!" }, new Dictionary<string, object?>() { ["message"] = "Hello MCP!" },
cancellationToken:CancellationToken.None); cancellationToken: CancellationToken.None);
// echo always returns one and only one text content object // echo always returns one and only one text content object
Console.WriteLine(result.Content.First(c => c.Type == "text").Text); Console.WriteLine(result.Content.First(c => c.Type == "text").Text);
@ -83,13 +83,13 @@ using System.ComponentModel;
var serverOptions = new McpServerOptions(); var serverOptions = new McpServerOptions();
// Add tools directly // Add tools directly
serverOptions.Capabilities.Tools = new() serverOptions.Capabilities.Tools = new()
{ {
ListChanged = true, ListChanged = true,
ToolCollection = [ ToolCollection = [
McpServerTool.Create((string message) => $"hello {message}", new() McpServerTool.Create((string message) => $"hello {message}", new()
{ {
Name = "echo", Name = "echo",
Description = "Echoes the message back to the client." 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. /// Requests to sample an LLM via the client using the provided chat messages and options.
/// </summary> /// </summary>
/// <param name="messages">The messages to send as part of the request.</param> /// <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> /// <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> /// <returns>A task containing the chat response from the model.</returns>
/// <exception cref="ArgumentNullException"><paramref name="messages"/> is <see langword="null"/>.</exception> /// <exception cref="ArgumentNullException"><paramref name="messages"/> is <see langword="null"/>.</exception>
/// <exception cref="InvalidOperationException">The client does not support sampling.</exception> /// <exception cref="InvalidOperationException">The client does not support sampling.</exception>
public async Task<ChatResponse> SampleAsync( 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); Throw.IfNull(messages);
StringBuilder? systemPrompt = null; StringBuilder? systemPrompt = null;
if (options?.Instructions is { } instructions) if (chatOptions?.Instructions is { } instructions)
{ {
(systemPrompt ??= new()).Append(instructions); (systemPrompt ??= new()).Append(instructions);
} }
@ -126,15 +126,15 @@ public abstract partial class McpServer : McpSession
} }
ModelPreferences? modelPreferences = null; ModelPreferences? modelPreferences = null;
if (options?.ModelId is { } modelId) if (chatOptions?.ModelId is { } modelId)
{ {
modelPreferences = new() { Hints = [new() { Name = modelId }] }; modelPreferences = new() { Hints = [new() { Name = modelId }] };
} }
IList<Tool>? tools = null; 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) 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 }, NoneChatToolMode => new() { Mode = ToolChoice.ModeNone },
AutoChatToolMode => new() { Mode = ToolChoice.ModeAuto }, AutoChatToolMode => new() { Mode = ToolChoice.ModeAuto },
@ -159,15 +159,15 @@ public abstract partial class McpServer : McpSession
var result = await SampleAsync(new() var result = await SampleAsync(new()
{ {
MaxTokens = options?.MaxOutputTokens ?? ServerOptions.MaxSamplingOutputTokens, MaxTokens = chatOptions?.MaxOutputTokens ?? ServerOptions.MaxSamplingOutputTokens,
Messages = samplingMessages, Messages = samplingMessages,
ModelPreferences = modelPreferences, ModelPreferences = modelPreferences,
StopSequences = options?.StopSequences?.ToArray(), StopSequences = chatOptions?.StopSequences?.ToArray(),
SystemPrompt = systemPrompt?.ToString(), SystemPrompt = systemPrompt?.ToString(),
Temperature = options?.Temperature, Temperature = chatOptions?.Temperature,
ToolChoice = toolChoice, ToolChoice = toolChoice,
Tools = tools, Tools = tools,
Meta = options?.AdditionalProperties?.ToJsonObject(), Meta = chatOptions?.AdditionalProperties?.ToJsonObject(),
}, cancellationToken).ConfigureAwait(false); }, cancellationToken).ConfigureAwait(false);
List<AIContent> responseContents = []; List<AIContent> responseContents = [];
@ -472,14 +472,14 @@ public abstract partial class McpServer : McpSession
private readonly McpServer _server = server; private readonly McpServer _server = server;
/// <inheritdoc/> /// <inheritdoc/>
public Task<ChatResponse> GetResponseAsync(IEnumerable<ChatMessage> messages, ChatOptions? options = null, CancellationToken cancellationToken = default) => public Task<ChatResponse> GetResponseAsync(IEnumerable<ChatMessage> messages, ChatOptions? chatOptions = null, CancellationToken cancellationToken = default) =>
_server.SampleAsync(messages, options, cancellationToken); _server.SampleAsync(messages, chatOptions, cancellationToken);
/// <inheritdoc/> /// <inheritdoc/>
async IAsyncEnumerable<ChatResponseUpdate> IChatClient.GetStreamingResponseAsync( 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()) foreach (var update in response.ToChatResponseUpdates())
{ {
yield return update; yield return update;

View file

@ -11,6 +11,6 @@ internal sealed class TokenProgress(McpSession session, ProgressToken progressTo
/// <inheritdoc /> /// <inheritdoc />
public void Report(ProgressNotificationValue value) 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 // Act
await using var client = await GetClientAsync(); await using var client = await GetClientAsync();
await client.PingAsync(TestContext.Current.CancellationToken); await client.PingAsync(null, TestContext.Current.CancellationToken);
// Assert // Assert
Assert.NotNull(client); Assert.NotNull(client);
@ -139,7 +139,7 @@ public abstract class HttpServerIntegrationTests : LoggedTest, IClassFixture<Sse
// act // act
await using var client = await GetClientAsync(); 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 // The everything server provides 100 test resources
Assert.Equal(100, allResources.Count); 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) // 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 // 1 is index 0, which is "even" in the 0-based index
// We copied this oddity to the test server // 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.NotNull(result);
Assert.Single(result.Contents); 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) // 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 // 2 is index 1, which is "odd" in the 0-based index
// We copied this oddity to the test server // 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.NotNull(result);
Assert.Single(result.Contents); Assert.Single(result.Contents);
@ -190,7 +190,7 @@ public abstract class HttpServerIntegrationTests : LoggedTest, IClassFixture<Sse
// act // act
await using var client = await GetClientAsync(); 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
Assert.NotNull(prompts); 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.System, "You are a helpful test server"),
new ChatMessage(ChatRole.User, $"Resource {uri}, context: A new subscription was started"), new ChatMessage(ChatRole.User, $"Resource {uri}, context: A new subscription was started"),
], ],
options: new ChatOptions chatOptions: new ChatOptions
{ {
MaxOutputTokens = 100, MaxOutputTokens = 100,
Temperature = 0.7f, Temperature = 0.7f,

View file

@ -141,7 +141,7 @@ public class ConformanceTools
{ {
Progress = 0, Progress = 0,
Total = 100, Total = 100,
}, cancellationToken); }, cancellationToken: cancellationToken);
await Task.Delay(50, cancellationToken); await Task.Delay(50, cancellationToken);
@ -149,7 +149,7 @@ public class ConformanceTools
{ {
Progress = 50, Progress = 50,
Total = 100, Total = 100,
}, cancellationToken); }, cancellationToken: cancellationToken);
await Task.Delay(50, cancellationToken); await Task.Delay(50, cancellationToken);
@ -157,7 +157,7 @@ public class ConformanceTools
{ {
Progress = 100, Progress = 100,
Total = 100, Total = 100,
}, cancellationToken); }, cancellationToken: cancellationToken);
} }
return progressToken?.ToString() ?? "No progress token provided"; 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); 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())), var sampleResult = await request.Server.SampleAsync(CreateRequestSamplingParams(prompt.ToString(), "sampleLLM", Convert.ToInt32(maxTokens.GetRawText())),
cancellationToken); cancellationToken: cancellationToken);
return new CallToolResult return new CallToolResult
{ {

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