Address asymmetry in McpServerHandlers/McpClientHandlers and make all filter properties settable (#1337)

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: stephentoub <2642209+stephentoub@users.noreply.github.com>
Co-authored-by: Stephen Toub <stoub@microsoft.com>
This commit is contained in:
Copilot 2026-02-23 15:51:37 -05:00 • committed by GitHub
commit a2ee0c805a
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
6 changed files with 432 additions and 293 deletions

View file

@ -22,7 +22,7 @@ namespace ModelContextProtocol.Client;
/// is done based on an ordinal, case-sensitive string comparison. /// is done based on an ordinal, case-sensitive string comparison.
/// </para> /// </para>
/// </remarks> /// </remarks>
public class McpClientHandlers public sealed class McpClientHandlers
{ {
/// <summary>Gets or sets notification handlers to register with the client.</summary> /// <summary>Gets or sets notification handlers to register with the client.</summary>
/// <remarks> /// <remarks>

View file

@ -8,7 +8,7 @@ namespace ModelContextProtocol.Server;
public sealed class McpMessageFilters public sealed class McpMessageFilters
{ {
/// <summary> /// <summary>
/// Gets the filters for all incoming JSON-RPC messages. /// Gets or sets the filters for all incoming JSON-RPC messages.
/// </summary> /// </summary>
/// <remarks> /// <remarks>
/// <para> /// <para>
@ -21,10 +21,18 @@ public sealed class McpMessageFilters
/// the next handler in the pipeline, the default handlers will not be executed. /// the next handler in the pipeline, the default handlers will not be executed.
/// </para> /// </para>
/// </remarks> /// </remarks>
public IList<McpMessageFilter> IncomingFilters { get; } = []; public IList<McpMessageFilter> IncomingFilters
{
get => field ??= [];
set
{
Throw.IfNull(value);
field = value;
}
}
/// <summary> /// <summary>
/// Gets the filters for all outgoing JSON-RPC messages. /// Gets or sets the filters for all outgoing JSON-RPC messages.
/// </summary> /// </summary>
/// <remarks> /// <remarks>
/// <para> /// <para>
@ -38,5 +46,13 @@ public sealed class McpMessageFilters
/// server-to-client messages. /// server-to-client messages.
/// </para> /// </para>
/// </remarks> /// </remarks>
public IList<McpMessageFilter> OutgoingFilters { get; } = []; public IList<McpMessageFilter> OutgoingFilters
{
get => field ??= [];
set
{
Throw.IfNull(value);
field = value;
}
}
} }

View file

@ -8,7 +8,7 @@ namespace ModelContextProtocol.Server;
public sealed class McpRequestFilters public sealed class McpRequestFilters
{ {
/// <summary> /// <summary>
/// Gets the filters for the list-tools handler pipeline. /// Gets or sets the filters for the list-tools handler pipeline.
/// </summary> /// </summary>
/// <remarks> /// <remarks>
/// <para> /// <para>
@ -22,20 +22,36 @@ public sealed class McpRequestFilters
/// Tools from both sources will be combined when returning results to clients. /// Tools from both sources will be combined when returning results to clients.
/// </para> /// </para>
/// </remarks> /// </remarks>
public IList<McpRequestFilter<ListToolsRequestParams, ListToolsResult>> ListToolsFilters { get; } = []; public IList<McpRequestFilter<ListToolsRequestParams, ListToolsResult>> ListToolsFilters
{
get => field ??= [];
set
{
Throw.IfNull(value);
field = value;
}
}
/// <summary> /// <summary>
/// Gets the filters for the call-tool handler pipeline. /// Gets or sets the filters for the call-tool handler pipeline.
/// </summary> /// </summary>
/// <remarks> /// <remarks>
/// These filters wrap handlers that are invoked when a client makes a call to a tool that isn't found in the <see cref="McpServerTool"/> collection. /// These filters wrap handlers that are invoked when a client makes a call to a tool that isn't found in the <see cref="McpServerTool"/> collection.
/// The filters can modify, log, or perform additional operations on requests and responses for /// The filters can modify, log, or perform additional operations on requests and responses for
/// <see cref="RequestMethods.ToolsCall"/> requests. The handler should implement logic to execute the requested tool and return appropriate results. /// <see cref="RequestMethods.ToolsCall"/> requests. The handler should implement logic to execute the requested tool and return appropriate results.
/// </remarks> /// </remarks>
public IList<McpRequestFilter<CallToolRequestParams, CallToolResult>> CallToolFilters { get; } = []; public IList<McpRequestFilter<CallToolRequestParams, CallToolResult>> CallToolFilters
{
get => field ??= [];
set
{
Throw.IfNull(value);
field = value;
}
}
/// <summary> /// <summary>
/// Gets the filters for the list-prompts handler pipeline. /// Gets or sets the filters for the list-prompts handler pipeline.
/// </summary> /// </summary>
/// <remarks> /// <remarks>
/// <para> /// <para>
@ -49,20 +65,36 @@ public sealed class McpRequestFilters
/// Prompts from both sources will be combined when returning results to clients. /// Prompts from both sources will be combined when returning results to clients.
/// </para> /// </para>
/// </remarks> /// </remarks>
public IList<McpRequestFilter<ListPromptsRequestParams, ListPromptsResult>> ListPromptsFilters { get; } = []; public IList<McpRequestFilter<ListPromptsRequestParams, ListPromptsResult>> ListPromptsFilters
{
get => field ??= [];
set
{
Throw.IfNull(value);
field = value;
}
}
/// <summary> /// <summary>
/// Gets the filters for the get-prompt handler pipeline. /// Gets or sets the filters for the get-prompt handler pipeline.
/// </summary> /// </summary>
/// <remarks> /// <remarks>
/// These filters wrap handlers that are invoked when a client requests details for a specific prompt that isn't found in the <see cref="McpServerPrompt"/> collection. /// These filters wrap handlers that are invoked when a client requests details for a specific prompt that isn't found in the <see cref="McpServerPrompt"/> collection.
/// The filters can modify, log, or perform additional operations on requests and responses for /// The filters can modify, log, or perform additional operations on requests and responses for
/// <see cref="RequestMethods.PromptsGet"/> requests. The handler should implement logic to fetch or generate the requested prompt and return appropriate results. /// <see cref="RequestMethods.PromptsGet"/> requests. The handler should implement logic to fetch or generate the requested prompt and return appropriate results.
/// </remarks> /// </remarks>
public IList<McpRequestFilter<GetPromptRequestParams, GetPromptResult>> GetPromptFilters { get; } = []; public IList<McpRequestFilter<GetPromptRequestParams, GetPromptResult>> GetPromptFilters
{
get => field ??= [];
set
{
Throw.IfNull(value);
field = value;
}
}
/// <summary> /// <summary>
/// Gets the filters for the list-resource-templates handler pipeline. /// Gets or sets the filters for the list-resource-templates handler pipeline.
/// </summary> /// </summary>
/// <remarks> /// <remarks>
/// These filters wrap handlers that return a list of available resource templates when requested by a client. /// These filters wrap handlers that return a list of available resource templates when requested by a client.
@ -70,10 +102,18 @@ public sealed class McpRequestFilters
/// <see cref="RequestMethods.ResourcesTemplatesList"/> requests. It supports pagination through the cursor mechanism, /// <see cref="RequestMethods.ResourcesTemplatesList"/> requests. It supports pagination through the cursor mechanism,
/// where the client can make repeated calls with the cursor returned by the previous call to retrieve more resource templates. /// where the client can make repeated calls with the cursor returned by the previous call to retrieve more resource templates.
/// </remarks> /// </remarks>
public IList<McpRequestFilter<ListResourceTemplatesRequestParams, ListResourceTemplatesResult>> ListResourceTemplatesFilters { get; } = []; public IList<McpRequestFilter<ListResourceTemplatesRequestParams, ListResourceTemplatesResult>> ListResourceTemplatesFilters
{
get => field ??= [];
set
{
Throw.IfNull(value);
field = value;
}
}
/// <summary> /// <summary>
/// Gets the filters for the list-resources handler pipeline. /// Gets or sets the filters for the list-resources handler pipeline.
/// </summary> /// </summary>
/// <remarks> /// <remarks>
/// These filters wrap handlers that return a list of available resources when requested by a client. /// These filters wrap handlers that return a list of available resources when requested by a client.
@ -81,20 +121,36 @@ public sealed class McpRequestFilters
/// <see cref="RequestMethods.ResourcesList"/> requests. It supports pagination through the cursor mechanism, /// <see cref="RequestMethods.ResourcesList"/> requests. It supports pagination through the cursor mechanism,
/// where the client can make repeated calls with the cursor returned by the previous call to retrieve more resources. /// where the client can make repeated calls with the cursor returned by the previous call to retrieve more resources.
/// </remarks> /// </remarks>
public IList<McpRequestFilter<ListResourcesRequestParams, ListResourcesResult>> ListResourcesFilters { get; } = []; public IList<McpRequestFilter<ListResourcesRequestParams, ListResourcesResult>> ListResourcesFilters
{
get => field ??= [];
set
{
Throw.IfNull(value);
field = value;
}
}
/// <summary> /// <summary>
/// Gets the filters for the read-resource handler pipeline. /// Gets or sets the filters for the read-resource handler pipeline.
/// </summary> /// </summary>
/// <remarks> /// <remarks>
/// These filters wrap handlers that are invoked when a client requests the content of a specific resource identified by its URI. /// These filters wrap handlers that are invoked when a client requests the content of a specific resource identified by its URI.
/// The filters can modify, log, or perform additional operations on requests and responses for /// The filters can modify, log, or perform additional operations on requests and responses for
/// <see cref="RequestMethods.ResourcesRead"/> requests. The handler should implement logic to locate and retrieve the requested resource. /// <see cref="RequestMethods.ResourcesRead"/> requests. The handler should implement logic to locate and retrieve the requested resource.
/// </remarks> /// </remarks>
public IList<McpRequestFilter<ReadResourceRequestParams, ReadResourceResult>> ReadResourceFilters { get; } = []; public IList<McpRequestFilter<ReadResourceRequestParams, ReadResourceResult>> ReadResourceFilters
{
get => field ??= [];
set
{
Throw.IfNull(value);
field = value;
}
}
/// <summary> /// <summary>
/// Gets the filters for the complete-handler pipeline. /// Gets or sets the filters for the complete-handler pipeline.
/// </summary> /// </summary>
/// <remarks> /// <remarks>
/// These filters wrap handlers that provide auto-completion suggestions for prompt arguments or resource references in the Model Context Protocol. /// These filters wrap handlers that provide auto-completion suggestions for prompt arguments or resource references in the Model Context Protocol.
@ -102,10 +158,18 @@ public sealed class McpRequestFilters
/// <see cref="RequestMethods.CompletionComplete"/> requests. The handler processes auto-completion requests, returning a list of suggestions based on the /// <see cref="RequestMethods.CompletionComplete"/> requests. The handler processes auto-completion requests, returning a list of suggestions based on the
/// reference type and current argument value. /// reference type and current argument value.
/// </remarks> /// </remarks>
public IList<McpRequestFilter<CompleteRequestParams, CompleteResult>> CompleteFilters { get; } = []; public IList<McpRequestFilter<CompleteRequestParams, CompleteResult>> CompleteFilters
{
get => field ??= [];
set
{
Throw.IfNull(value);
field = value;
}
}
/// <summary> /// <summary>
/// Gets the filters for the subscribe-to-resources handler pipeline. /// Gets or sets the filters for the subscribe-to-resources handler pipeline.
/// </summary> /// </summary>
/// <remarks> /// <remarks>
/// <para> /// <para>
@ -119,10 +183,18 @@ public sealed class McpRequestFilters
/// whenever a relevant resource is created, updated, or deleted. /// whenever a relevant resource is created, updated, or deleted.
/// </para> /// </para>
/// </remarks> /// </remarks>
public IList<McpRequestFilter<SubscribeRequestParams, EmptyResult>> SubscribeToResourcesFilters { get; } = []; public IList<McpRequestFilter<SubscribeRequestParams, EmptyResult>> SubscribeToResourcesFilters
{
get => field ??= [];
set
{
Throw.IfNull(value);
field = value;
}
}
/// <summary> /// <summary>
/// Gets the filters for the unsubscribe-from-resources handler pipeline. /// Gets or sets the filters for the unsubscribe-from-resources handler pipeline.
/// </summary> /// </summary>
/// <remarks> /// <remarks>
/// <para> /// <para>
@ -136,10 +208,18 @@ public sealed class McpRequestFilters
/// to the client for the specified resources. /// to the client for the specified resources.
/// </para> /// </para>
/// </remarks> /// </remarks>
public IList<McpRequestFilter<UnsubscribeRequestParams, EmptyResult>> UnsubscribeFromResourcesFilters { get; } = []; public IList<McpRequestFilter<UnsubscribeRequestParams, EmptyResult>> UnsubscribeFromResourcesFilters
{
get => field ??= [];
set
{
Throw.IfNull(value);
field = value;
}
}
/// <summary> /// <summary>
/// Gets the filters for the set-logging-level handler pipeline. /// Gets or sets the filters for the set-logging-level handler pipeline.
/// </summary> /// </summary>
/// <remarks> /// <remarks>
/// <para> /// <para>
@ -153,5 +233,13 @@ public sealed class McpRequestFilters
/// at or above the specified level to the client as notifications/message notifications. /// at or above the specified level to the client as notifications/message notifications.
/// </para> /// </para>
/// </remarks> /// </remarks>
public IList<McpRequestFilter<SetLevelRequestParams, EmptyResult>> SetLoggingLevelFilters { get; } = []; public IList<McpRequestFilter<SetLevelRequestParams, EmptyResult>> SetLoggingLevelFilters
{
get => field ??= [];
set
{
Throw.IfNull(value);
field = value;
}
}
} }

View file

@ -12,12 +12,28 @@ namespace ModelContextProtocol.Server;
public sealed class McpServerFilters public sealed class McpServerFilters
{ {
/// <summary> /// <summary>
/// Gets the filters for incoming and outgoing JSON-RPC messages. /// Gets or sets the filters for incoming and outgoing JSON-RPC messages.
/// </summary> /// </summary>
public McpMessageFilters Message { get; } = new(); public McpMessageFilters Message
{
get => field ??= new();
set
{
Throw.IfNull(value);
field = value;
}
}
/// <summary> /// <summary>
/// Gets the filters for request-specific MCP handler pipelines. /// Gets or sets the filters for request-specific MCP handler pipelines.
/// </summary> /// </summary>
public McpRequestFilters Request { get; } = new(); public McpRequestFilters Request
{
get => field ??= new();
set
{
Throw.IfNull(value);
field = value;
}
}
} }

View file

@ -97,17 +97,33 @@ public sealed class McpServerOptions
/// <summary> /// <summary>
/// Gets or sets the container of handlers used by the server for processing protocol messages. /// Gets or sets the container of handlers used by the server for processing protocol messages.
/// </summary> /// </summary>
public McpServerHandlers Handlers { get; } = new(); public McpServerHandlers Handlers
{
get => field ??= new();
set
{
Throw.IfNull(value);
field = value;
}
}
/// <summary> /// <summary>
/// Gets the filter collections for MCP server handlers. /// Gets or sets the filter collections for MCP server handlers.
/// </summary> /// </summary>
/// <remarks> /// <remarks>
/// This property provides access to filter collections that can be used to modify the behavior /// This property provides access to filter collections that can be used to modify the behavior
/// of various MCP server handlers. The first filter added is the outermost (first to execute), /// of various MCP server handlers. The first filter added is the outermost (first to execute),
/// and each subsequent filter wraps closer to the handler. /// and each subsequent filter wraps closer to the handler.
/// </remarks> /// </remarks>
public McpServerFilters Filters { get; } = new(); public McpServerFilters Filters
{
get => field ??= new();
set
{
Throw.IfNull(value);
field = value;
}
}
/// <summary> /// <summary>
/// Gets or sets a collection of tools served by the server. /// Gets or sets a collection of tools served by the server.

View file

@ -90,7 +90,9 @@ public class Program
} }
const int pageSize = 10; const int pageSize = 10;
options.Handlers.ListToolsHandler = async (request, cancellationToken) => options.Handlers = new()
{
ListToolsHandler = async (request, cancellationToken) =>
{ {
return new ListToolsResult return new ListToolsResult
{ {
@ -167,9 +169,9 @@ public class Program
} }
] ]
}; };
}; },
options.Handlers.CallToolHandler = async (request, cancellationToken) => CallToolHandler = async (request, cancellationToken) =>
{ {
if (request.Params is null) if (request.Params is null)
{ {
@ -227,9 +229,9 @@ public class Program
{ {
throw new McpProtocolException($"Unknown tool: '{request.Params.Name}'", McpErrorCode.InvalidParams); throw new McpProtocolException($"Unknown tool: '{request.Params.Name}'", McpErrorCode.InvalidParams);
} }
}; },
options.Handlers.ListResourceTemplatesHandler = async (request, cancellationToken) => ListResourceTemplatesHandler = async (request, cancellationToken) =>
{ {
return new ListResourceTemplatesResult return new ListResourceTemplatesResult
{ {
@ -241,9 +243,9 @@ public class Program
} }
] ]
}; };
}; },
options.Handlers.ListResourcesHandler = async (request, cancellationToken) => ListResourcesHandler = async (request, cancellationToken) =>
{ {
int startIndex = 0; int startIndex = 0;
var requestParams = request.Params ?? new(); var requestParams = request.Params ?? new();
@ -274,9 +276,9 @@ public class Program
NextCursor = nextCursor, NextCursor = nextCursor,
Resources = resources.GetRange(startIndex, endIndex - startIndex) Resources = resources.GetRange(startIndex, endIndex - startIndex)
}; };
}; },
options.Handlers.ReadResourceHandler = async (request, cancellationToken) => ReadResourceHandler = async (request, cancellationToken) =>
{ {
if (request.Params?.Uri is null) if (request.Params?.Uri is null)
{ {
@ -311,9 +313,9 @@ public class Program
{ {
Contents = [contents] Contents = [contents]
}; };
}; },
options.Handlers.ListPromptsHandler = async (request, cancellationToken) => ListPromptsHandler = async (request, cancellationToken) =>
{ {
return new ListPromptsResult return new ListPromptsResult
{ {
@ -345,9 +347,9 @@ public class Program
} }
] ]
}; };
}; },
options.Handlers.GetPromptHandler = async (request, cancellationToken) => GetPromptHandler = async (request, cancellationToken) =>
{ {
if (request.Params is null) if (request.Params is null)
{ {
@ -397,6 +399,7 @@ public class Program
{ {
Messages = messages Messages = messages
}; };
},
}; };
} }