diff --git a/docs/concepts/filters.md b/docs/concepts/filters.md index 4a1516302..611326d32 100644 --- a/docs/concepts/filters.md +++ b/docs/concepts/filters.md @@ -1,18 +1,18 @@ --- title: Filters author: halter73 -description: MCP Server Filters +description: MCP Server and Client Filters uid: filters --- -# MCP Server Filters +# MCP Filters -The MCP Server provides two levels of filters for intercepting and modifying request processing: +The MCP SDK provides filters for intercepting and modifying JSON-RPC message and request processing on both servers and clients: -1. **Message Filters** - Low-level filters (`AddIncomingFilter`, `AddOutgoingFilter`) configured via `WithMessageFilters(...)` that intercept all JSON-RPC messages before routing. -2. **Request-Specific Filters** - Handler-level filters (for example, `AddListToolsFilter`, `AddCallToolFilter`) configured via `WithRequestFilters(...)` that target specific MCP operations. - -The filters are stored in `McpServerOptions.Filters`. +- **Server Filters** (`McpServerOptions.Filters`) + 1. **Message Filters** - Low-level filters (`AddIncomingFilter`, `AddOutgoingFilter`) configured via `WithMessageFilters(...)` that intercept all JSON-RPC messages before routing. + 2. **Request-Specific Filters** - Handler-level filters (for example, `AddListToolsFilter`, `AddCallToolFilter`) configured via `WithRequestFilters(...)` that target specific MCP operations. +- **Client Message Filters** (`McpClientOptions.Filters.Message`) - Low-level filters (`IncomingFilters`, `OutgoingFilters`) that intercept all incoming and outgoing JSON-RPC messages on an `McpClient`. ## Available request-specific filter methods @@ -615,3 +615,54 @@ Within filters, you have access to: - `context.User` - The current user's `ClaimsPrincipal`. - `context.Services` - The request's service provider for resolving authorization services. - `context.MatchedPrimitive` - The matched tool/prompt/resource with its metadata including authorization attributes via `context.MatchedPrimitive.Metadata`. + +## Client message filters + +`McpClient` supports incoming and outgoing JSON-RPC message filters through `McpClientOptions.Filters.Message`: + +- `IncomingFilters` (`IList`) - Intercepts all incoming JSON-RPC messages from the server (responses, errors, server-initiated requests, and notifications) after parsing and before pending-request correlation or handler dispatch. +- `OutgoingFilters` (`IList`) - Intercepts all outgoing JSON-RPC messages from the client (requests, notifications, responses, and errors) after protocol metadata injection and before transport serialization. + +Each filter receives an `McpClientMessageContext` exposing: + +- `context.Client` - The `McpClient` instance (including `NegotiatedProtocolVersion`, and once connected, `ServerCapabilities` and `ServerInfo`). Note that filters also run on handshake messages (`server/discover` and `initialize`), during which `ServerCapabilities` and `ServerInfo` throw `InvalidOperationException` until connection completes. +- `context.JsonRpcMessage` - The JSON-RPC message being processed (can be inspected, mutated, or replaced). Replacing `JsonRpcMessage` with a new message whose `Context` is `null` preserves the previous message's `JsonRpcMessageContext` (including `Items` and transport metadata). +- `context.Items` - A per-message dictionary shared across all filters processing the message and with custom client request handlers. + +### Configuring client message filters + +```csharp +var clientOptions = new McpClientOptions(); + +// Attach custom metadata to outgoing requests +clientOptions.Filters.Message.OutgoingFilters.Add(next => async (context, cancellationToken) => +{ + if (context.JsonRpcMessage is JsonRpcRequest request) + { + var paramsObj = request.Params as JsonObject ?? new JsonObject(); + request.Params = paramsObj; + + var meta = paramsObj["_meta"] as JsonObject ?? new JsonObject(); + paramsObj["_meta"] = meta; + meta["com.example/trace-id"] = Guid.NewGuid().ToString("N"); + } + + await next(context, cancellationToken); +}); + +// Observe or validate incoming responses, errors, notifications, and server requests +clientOptions.Filters.Message.IncomingFilters.Add(next => async (context, cancellationToken) => +{ + await next(context, cancellationToken); +}); + +await using var client = await McpClient.CreateAsync(transport, clientOptions); +``` + +### Ordering and lifecycle + +- Filters execute in deterministic registration order, with the first registered filter running outermost (before inner filters on entry, and after inner filters on return or error). +- `IncomingFilters` and `OutgoingFilters` are validated and snapshotted before the transport connects (`McpClient.CreateAsync` / `McpClient.ResumeSessionAsync`), and filter factories are composed once when the client is constructed. Mutating `McpClientOptions.Filters` after client creation does not reorder or remove active filters, and any state captured in a filter factory closure persists across messages for that client. +- A filter can return early without calling `next` to suppress a notification or short-circuit processing of a server-initiated request (for example, after sending its own response). Returning early without sending an outgoing request, or suppressing an incoming response or error for a pending request, fails the pending request immediately with `InvalidOperationException` rather than hanging. +- A filter can throw an exception to reject a message: for outgoing messages, the exception propagates to the caller; for incoming responses and errors, the exception fails the awaiting request; for incoming server-initiated requests, the error is sent back as a JSON-RPC error response unless a response has already been sent. + diff --git a/docs/list-of-diagnostics.md b/docs/list-of-diagnostics.md index 07cd14b8a..bed0ae0d9 100644 --- a/docs/list-of-diagnostics.md +++ b/docs/list-of-diagnostics.md @@ -28,7 +28,7 @@ If you use experimental APIs, you will get one of the diagnostics shown below. T | Diagnostic ID | Description | | :------------ | :---------- | | `MCPEXP001` | Experimental APIs tied to MCP specification features. Reuse this ID for newly introduced experimental spec features, and add feature-specific messages/URLs in `Experimentals`. | -| `MCPEXP002` | Experimental SDK extensibility APIs used to implement features in standalone packages without requiring Core to understand those features. For example, the Tasks package uses these APIs to extend the SDK while keeping the Tasks concept out of Core. This includes `McpClient`/`McpServer` subclassing, custom request handlers, alternate handlers and filters, outgoing request interception, and `RunSessionHandler`. These APIs remain experimental until additional extensibility scenarios validate the design. | +| `MCPEXP002` | Experimental SDK extensibility APIs used to implement features in standalone packages without requiring Core to understand those features. For example, the Tasks package uses these APIs to extend the SDK while keeping the Tasks concept out of Core. This includes `McpClient`/`McpServer` subclassing, server and client custom request handlers (`McpServerOptions.RequestHandlers`, `McpClientOptions.RequestHandlers`), alternate handlers and filters, outgoing request interception, and `RunSessionHandler`. These APIs remain experimental until additional extensibility scenarios validate the design. | | `MCPEXP003` | Experimental MCP Apps extension APIs. MCP Apps is the first official MCP extension (`io.modelcontextprotocol/ui`), enabling servers to deliver interactive UIs inside AI clients (see [MCP Apps specification](https://github.com/modelcontextprotocol/ext-apps/blob/main/specification/2026-01-26/apps.mdx)). | | `MCPEXP005` | Experimental MCP Skills extension APIs (`io.modelcontextprotocol/skills`). The extension and its C# APIs are subject to change. | diff --git a/src/ModelContextProtocol.Core/Client/McpClient.Methods.cs b/src/ModelContextProtocol.Core/Client/McpClient.Methods.cs index bccdd7a2e..846a4ade5 100644 --- a/src/ModelContextProtocol.Core/Client/McpClient.Methods.cs +++ b/src/ModelContextProtocol.Core/Client/McpClient.Methods.cs @@ -44,11 +44,21 @@ public static async Task CreateAsync( CancellationToken cancellationToken = default) { Throw.IfNull(clientTransport); + var validatedOptions = McpClientImpl.ValidateAndSnapshotOptions(clientOptions); var transport = await clientTransport.ConnectAsync(cancellationToken).ConfigureAwait(false); var endpointName = clientTransport.Name; - var clientSession = new McpClientImpl(transport, endpointName, clientOptions, loggerFactory); + McpClientImpl clientSession; + try + { + clientSession = new McpClientImpl(transport, endpointName, clientOptions, loggerFactory, validatedOptions); + } + catch + { + await transport.DisposeAsync().ConfigureAwait(false); + throw; + } try { await clientSession.ConnectAsync(cancellationToken).ConfigureAwait(false); @@ -117,10 +127,20 @@ public static async Task ResumeSessionAsync( Throw.IfNull(resumeOptions); Throw.IfNull(resumeOptions.ServerCapabilities); Throw.IfNull(resumeOptions.ServerInfo); + var validatedOptions = McpClientImpl.ValidateAndSnapshotOptions(clientOptions); var transport = await clientTransport.ConnectAsync(cancellationToken).ConfigureAwait(false); - McpClientImpl clientSession = new(transport, clientTransport.Name, clientOptions, loggerFactory); + McpClientImpl clientSession; + try + { + clientSession = new(transport, clientTransport.Name, clientOptions, loggerFactory, validatedOptions); + } + catch + { + await transport.DisposeAsync().ConfigureAwait(false); + throw; + } clientSession.ResumeSession(resumeOptions); return clientSession; diff --git a/src/ModelContextProtocol.Core/Client/McpClientFilters.cs b/src/ModelContextProtocol.Core/Client/McpClientFilters.cs new file mode 100644 index 000000000..36d1d07fe --- /dev/null +++ b/src/ModelContextProtocol.Core/Client/McpClientFilters.cs @@ -0,0 +1,25 @@ +namespace ModelContextProtocol.Client; + +/// +/// Provides filter collections for MCP client pipelines. +/// +/// +/// This class contains collections of filters that can be applied to MCP client message processing. +/// This allows for middleware-style composition where filters can perform actions before and after the inner handler. +/// +public sealed class McpClientFilters +{ + /// + /// Gets or sets the filters for incoming and outgoing JSON-RPC messages. + /// + /// The value is . + public McpClientMessageFilters Message + { + get => field ??= new(); + set + { + Throw.IfNull(value); + field = value; + } + } +} diff --git a/src/ModelContextProtocol.Core/Client/McpClientImpl.cs b/src/ModelContextProtocol.Core/Client/McpClientImpl.cs index 51aa4b6a1..e1b588fce 100644 --- a/src/ModelContextProtocol.Core/Client/McpClientImpl.cs +++ b/src/ModelContextProtocol.Core/Client/McpClientImpl.cs @@ -12,6 +12,28 @@ namespace ModelContextProtocol.Client; #pragma warning disable MCPEXP002 internal sealed partial class McpClientImpl : McpClient { + private static readonly HashSet s_reservedCoreRequestMethods = new(StringComparer.Ordinal) + { + RequestMethods.Ping, + RequestMethods.SamplingCreateMessage, + RequestMethods.RootsList, + RequestMethods.ElicitationCreate, + RequestMethods.Initialize, + RequestMethods.ServerDiscover, + RequestMethods.ToolsList, + RequestMethods.ToolsCall, + RequestMethods.PromptsList, + RequestMethods.PromptsGet, + RequestMethods.ResourcesList, + RequestMethods.ResourcesRead, + RequestMethods.ResourcesTemplatesList, + RequestMethods.ResourcesSubscribe, + RequestMethods.ResourcesUnsubscribe, + RequestMethods.LoggingSetLevel, + RequestMethods.CompletionComplete, + RequestMethods.SubscriptionsListen, + }; + private static Implementation DefaultImplementation { get; } = new() { Name = AssemblyNameHelper.DefaultAssemblyName.Name ?? nameof(McpClient), @@ -42,10 +64,17 @@ internal sealed partial class McpClientImpl : McpClient /// The name of the endpoint for logging and debug purposes. /// Options for the client, defining protocol version and capabilities. /// The logger factory. - internal McpClientImpl(ITransport transport, string endpointName, McpClientOptions? options, ILoggerFactory? loggerFactory) + /// Optional pre-validated and snapshotted client options. + internal McpClientImpl( + ITransport transport, + string endpointName, + McpClientOptions? options, + ILoggerFactory? loggerFactory, + ValidatedOptionsSnapshot? validatedOptions = null) #pragma warning restore MCPEXP002 { - options ??= new(); + var snapshot = validatedOptions ?? ValidateAndSnapshotOptions(options); + options = snapshot.Options; _transport = transport; _endpointName = $"Client ({options.ClientInfo?.Name ?? DefaultImplementation.Name} {options.ClientInfo?.Version ?? DefaultImplementation.Version})"; @@ -55,7 +84,14 @@ internal McpClientImpl(ITransport transport, string endpointName, McpClientOptio var notificationHandlers = new NotificationHandlers(); var requestHandlers = new RequestHandlers(); - RegisterHandlers(options, notificationHandlers, requestHandlers); + RegisterHandlers(options, snapshot.CustomRequestHandlers, notificationHandlers, requestHandlers); + + var incomingMessageFilter = BuildMessageFilterPipeline( + snapshot.IncomingFilters, + nameof(McpClientMessageFilters.IncomingFilters)); + var outgoingMessageFilter = BuildMessageFilterPipeline( + snapshot.OutgoingFilters, + nameof(McpClientMessageFilters.OutgoingFilters)); _sessionHandler = new McpSessionHandler( isServer: false, @@ -63,8 +99,8 @@ internal McpClientImpl(ITransport transport, string endpointName, McpClientOptio endpointName, requestHandlers, notificationHandlers, - incomingMessageFilter: null, - outgoingMessageFilter: null, + incomingMessageFilter, + outgoingMessageFilter, _logger); ToolDiscovered = tool => _toolCache[tool.Name] = tool; @@ -88,7 +124,13 @@ internal McpClientImpl(ITransport transport, string endpointName, McpClientOptio }; } - private void RegisterHandlers(McpClientOptions options, NotificationHandlers notificationHandlers, RequestHandlers requestHandlers) + private void RegisterHandlers( + McpClientOptions options, +#pragma warning disable MCPEXP002 + McpClientRequestHandler[] customRequestHandlers, +#pragma warning restore MCPEXP002 + NotificationHandlers notificationHandlers, + RequestHandlers requestHandlers) { McpClientHandlers handlers = options.Handlers; @@ -159,6 +201,156 @@ private void RegisterHandlers(McpClientOptions options, NotificationHandlers not _options.Capabilities.Elicitation.Form = new(); } } + + ConfigureCustomRequestHandlers(customRequestHandlers, requestHandlers); + } + + internal readonly struct ValidatedOptionsSnapshot( + McpClientOptions options, + McpClientMessageFilter[] incomingFilters, + McpClientMessageFilter[] outgoingFilters, +#pragma warning disable MCPEXP002 + McpClientRequestHandler[] customRequestHandlers) +#pragma warning restore MCPEXP002 + { + public McpClientOptions Options { get; } = options; + public McpClientMessageFilter[] IncomingFilters { get; } = incomingFilters; + public McpClientMessageFilter[] OutgoingFilters { get; } = outgoingFilters; +#pragma warning disable MCPEXP002 + public McpClientRequestHandler[] CustomRequestHandlers { get; } = customRequestHandlers; +#pragma warning restore MCPEXP002 + } + + internal static ValidatedOptionsSnapshot ValidateAndSnapshotOptions(McpClientOptions? options) + { + options ??= new McpClientOptions(); + + var incomingFilters = SnapshotAndValidateFilters(options.Filters.Message.IncomingFilters, nameof(McpClientMessageFilters.IncomingFilters)); + var outgoingFilters = SnapshotAndValidateFilters(options.Filters.Message.OutgoingFilters, nameof(McpClientMessageFilters.OutgoingFilters)); + +#pragma warning disable MCPEXP002 + McpClientRequestHandler[] customHandlersSnapshot; + if (options.RequestHandlers is { Count: > 0 } customHandlers) + { + customHandlersSnapshot = new McpClientRequestHandler[customHandlers.Count]; + HashSet? seenMethods = null; + for (int i = 0; i < customHandlers.Count; i++) + { + var entry = customHandlers[i]; + if (entry is null) + { + throw new InvalidOperationException( + $"A custom request handler registered through {nameof(McpClientOptions)}.{nameof(McpClientOptions.RequestHandlers)} is null."); + } + + if (string.IsNullOrWhiteSpace(entry.Method)) + { + throw new InvalidOperationException( + $"A custom request handler registered through {nameof(McpClientOptions)}.{nameof(McpClientOptions.RequestHandlers)} has a null or empty {nameof(McpClientRequestHandler.Method)}."); + } + + if (entry.Handler is null) + { + throw new InvalidOperationException( + $"The custom request handler for '{entry.Method}' has a null {nameof(McpClientRequestHandler.Handler)}."); + } + + if (s_reservedCoreRequestMethods.Contains(entry.Method)) + { + throw new InvalidOperationException( + $"A custom request handler registered through {nameof(McpClientOptions)}.{nameof(McpClientOptions.RequestHandlers)} " + + $"uses the built-in MCP method '{entry.Method}'. Custom handlers cannot replace built-in methods."); + } + + seenMethods ??= new HashSet(StringComparer.Ordinal); + if (!seenMethods.Add(entry.Method)) + { + throw new InvalidOperationException( + $"A custom request handler registered through {nameof(McpClientOptions)}.{nameof(McpClientOptions.RequestHandlers)} " + + $"uses the method '{entry.Method}', which is already registered. Custom handlers cannot replace other custom handlers."); + } + + customHandlersSnapshot[i] = entry; + } + } + else + { + customHandlersSnapshot = []; + } +#pragma warning restore MCPEXP002 + + return new ValidatedOptionsSnapshot(options, incomingFilters, outgoingFilters, customHandlersSnapshot); + } + + private static McpClientMessageFilter[] SnapshotAndValidateFilters(IList filters, string filterCollectionName) + { + if (filters.Count == 0) + { + return []; + } + + var snapshot = new McpClientMessageFilter[filters.Count]; + for (int i = 0; i < filters.Count; i++) + { + snapshot[i] = filters[i] ?? throw new InvalidOperationException( + $"A filter registered in {nameof(McpClientOptions)}.{nameof(McpClientOptions.Filters)}.{nameof(McpClientFilters.Message)}.{filterCollectionName} is null."); + } + + return snapshot; + } + + private void ConfigureCustomRequestHandlers( +#pragma warning disable MCPEXP002 + McpClientRequestHandler[] customHandlers, +#pragma warning restore MCPEXP002 + RequestHandlers requestHandlers) + { +#pragma warning disable MCPEXP002 + foreach (var entry in customHandlers) + { + if (requestHandlers.ContainsKey(entry.Method)) + { + throw new InvalidOperationException( + $"A custom request handler registered through {nameof(McpClientOptions)}.{nameof(McpClientOptions.RequestHandlers)} " + + $"uses the method '{entry.Method}', which is already registered. Custom handlers cannot replace built-in or other custom handlers."); + } + + var handler = entry.Handler; + requestHandlers[entry.Method] = (request, cancellationToken) => + { + var context = new McpClientRequestContext(this, request, request.Params); + return handler(context, cancellationToken).AsTask(); + }; + } +#pragma warning restore MCPEXP002 + } + + private JsonRpcMessageFilter BuildMessageFilterPipeline(McpClientMessageFilter[] snapshot, string filterCollectionName) + { + if (snapshot.Length == 0) + { + return next => next; + } + + return next => + { + McpClientMessageHandler current = (context, cancellationToken) => + next(context.JsonRpcMessage, cancellationToken); + + for (int i = snapshot.Length - 1; i >= 0; i--) + { + current = snapshot[i](current) ?? throw new InvalidOperationException( + $"A filter registered in {nameof(McpClientOptions)}.{nameof(McpClientOptions.Filters)}.{nameof(McpClientFilters.Message)}.{filterCollectionName} returned null."); + } + + return (message, cancellationToken) => + { + // Ensure message has a Context so Items can be shared through the pipeline. + message.Context ??= new(); + var context = new McpClientMessageContext(this, message); + return current(context, cancellationToken); + }; + }; } /// @@ -701,6 +893,12 @@ request.Params is System.Text.Json.Nodes.JsonObject paramsObjForHeaders && } } + // Snapshot pre-filter Items so MRTR retries start with fresh per-message Items while + // preserving internal entries (such as ToolContextKey) and any caller-supplied Items. + KeyValuePair[]? initialItems = request.Context?.Items is { Count: > 0 } existingItems + ? [.. existingItems] + : null; + const int maxRetries = 10; InjectRequestMetaIfNeeded(request); @@ -741,7 +939,12 @@ request.Params is System.Text.Json.Nodes.JsonObject paramsObjForHeaders && paramsObj.Remove("requestState"); } - request = new JsonRpcRequest { Method = request.Method, Params = paramsObj, Context = request.Context }; + request = new JsonRpcRequest + { + Method = request.Method, + Params = paramsObj, + Context = CloneContextForRetry(request.Context, initialItems), + }; InjectRequestMetaIfNeeded(request); } else if (inputRequiredResult.RequestState is not null) @@ -751,7 +954,12 @@ request.Params is System.Text.Json.Nodes.JsonObject paramsObjForHeaders && paramsObj["requestState"] = inputRequiredResult.RequestState; paramsObj.Remove("inputResponses"); - request = new JsonRpcRequest { Method = request.Method, Params = paramsObj, Context = request.Context }; + request = new JsonRpcRequest + { + Method = request.Method, + Params = paramsObj, + Context = CloneContextForRetry(request.Context, initialItems), + }; InjectRequestMetaIfNeeded(request); } else @@ -771,6 +979,42 @@ request.Params is System.Text.Json.Nodes.JsonObject paramsObjForHeaders && throw new McpException($"Server returned InputRequiredResult more than {maxRetries} times."); } + private static JsonRpcMessageContext? CloneContextForRetry( + JsonRpcMessageContext? source, + KeyValuePair[]? initialItems) + { + if (source is null && initialItems is null) + { + return null; + } + + Dictionary? clonedItems = null; + if (initialItems is { Length: > 0 }) + { + clonedItems = new Dictionary(initialItems.Length); + foreach (var kvp in initialItems) + { + clonedItems[kvp.Key] = kvp.Value; + } + } + + return new JsonRpcMessageContext + { + RelatedTransport = source?.RelatedTransport, + ExecutionContext = source?.ExecutionContext, + User = source?.User, + Items = clonedItems, +#pragma warning disable MCPEXP002 + RoutingName = source?.RoutingName, +#pragma warning restore MCPEXP002 + ProtocolVersion = source?.ProtocolVersion, + ClientInfo = source?.ClientInfo, + ClientCapabilities = source?.ClientCapabilities, + LogLevel = source?.LogLevel, + RequestTimeout = source?.RequestTimeout, + }; + } + /// /// Injects the 2026-07-28 protocol's per-request _meta fields (protocol version, client info, /// client capabilities) into the request when this client negotiated the 2026-07-28 or later revision diff --git a/src/ModelContextProtocol.Core/Client/McpClientMessageContext.cs b/src/ModelContextProtocol.Core/Client/McpClientMessageContext.cs new file mode 100644 index 000000000..53df4fddc --- /dev/null +++ b/src/ModelContextProtocol.Core/Client/McpClientMessageContext.cs @@ -0,0 +1,104 @@ +using ModelContextProtocol.Protocol; + +namespace ModelContextProtocol.Client; + +/// +/// Provides a context container that provides access to the client and resources for processing a JSON-RPC message. +/// +/// +/// +/// The encapsulates contextual information for handling any JSON-RPC message, +/// including requests, responses, notifications, and errors. +/// +/// +/// This type is typically received as a parameter in message filter delegates registered via +/// 's or +/// collections. +/// +/// +public class McpClientMessageContext +{ + private JsonRpcMessage _jsonRpcMessage; + + /// + /// Initializes a new instance of the class with the specified client and JSON-RPC message. + /// + /// The client with which this instance is associated. + /// The JSON-RPC message associated with this context. + /// or is . + public McpClientMessageContext(McpClient client, JsonRpcMessage jsonRpcMessage) + { + Throw.IfNull(client); + Throw.IfNull(jsonRpcMessage); + + Client = client; + _jsonRpcMessage = jsonRpcMessage; + } + + /// Gets or sets the client with which this instance is associated. + /// + /// Message filters also run during connection establishment (server/discover and initialize). + /// During those handshake messages, and + /// are not yet populated and will throw + /// until connection completes. + /// + /// The value is . + public McpClient Client + { + get => field; + set + { + Throw.IfNull(value); + field = value; + } + } + + /// + /// Gets or sets a key/value collection that can be used to share data within the scope of this message. + /// + /// + /// This dictionary is shared with the property + /// on the underlying , ensuring that data set in message filters + /// flows through to downstream filters and handlers. + /// + public IDictionary Items + { + get + { + JsonRpcMessage.Context ??= new(); + return JsonRpcMessage.Context.Items ??= new Dictionary(); + } + set + { + JsonRpcMessage.Context ??= new(); + JsonRpcMessage.Context.Items = value; + } + } + + /// + /// Gets or sets the JSON-RPC message associated with this context. + /// + /// + /// This property provides access to the complete JSON-RPC message, + /// including the method name (for requests and notifications), request ID (for requests and responses), + /// and associated transport metadata. Replacing this property substitutes the message passed to + /// downstream filters and handlers or sent over the transport. If the replacement message has a + /// , the previous message's + /// (including and transport metadata) is preserved. + /// + /// The value is . + public virtual JsonRpcMessage JsonRpcMessage + { + get => _jsonRpcMessage; + set + { + Throw.IfNull(value); + if (!ReferenceEquals(value, _jsonRpcMessage) && _jsonRpcMessage.Context is { } previousContext && value.Context is null) + { + value.Context = previousContext; + } + + _jsonRpcMessage = value; + } + } +} diff --git a/src/ModelContextProtocol.Core/Client/McpClientMessageFilter.cs b/src/ModelContextProtocol.Core/Client/McpClientMessageFilter.cs new file mode 100644 index 000000000..c9861d88c --- /dev/null +++ b/src/ModelContextProtocol.Core/Client/McpClientMessageFilter.cs @@ -0,0 +1,28 @@ +namespace ModelContextProtocol.Client; + +/// +/// Delegate type for applying filters to client JSON-RPC messages. +/// +/// The next message handler in the pipeline. +/// The next message handler wrapped with the filter. +/// +/// +/// Message filters allow you to intercept and process JSON-RPC messages before they are dispatched to +/// client handlers or pending requests (incoming), or before they are sent to the server (outgoing). +/// This is useful for implementing cross-cutting concerns that need to apply to all message types, +/// such as logging, metadata propagation, redaction, or request tracing. +/// +/// +/// Filters are applied in the order they are registered, with the first registered filter being the outermost. +/// Each filter receives the next handler in the pipeline and can choose to: +/// +/// Call the next handler to continue processing (await next(context, cancellationToken)). +/// Modify or replace before calling . +/// Skip downstream handlers or suppress a notification by not calling . +/// Perform operations before and/or after calling . +/// Catch and handle exceptions from inner handlers. +/// +/// +/// +public delegate McpClientMessageHandler McpClientMessageFilter( + McpClientMessageHandler next); diff --git a/src/ModelContextProtocol.Core/Client/McpClientMessageFilters.cs b/src/ModelContextProtocol.Core/Client/McpClientMessageFilters.cs new file mode 100644 index 000000000..87b6b25b2 --- /dev/null +++ b/src/ModelContextProtocol.Core/Client/McpClientMessageFilters.cs @@ -0,0 +1,58 @@ +namespace ModelContextProtocol.Client; + +/// +/// Provides grouped message filter collections for an MCP client. +/// +public sealed class McpClientMessageFilters +{ + /// + /// Gets or sets the filters for all incoming JSON-RPC messages received from the server. + /// + /// + /// + /// These filters intercept all incoming JSON-RPC messages before they are processed by the client, + /// including responses, errors, server-initiated requests, and notifications. + /// + /// + /// Filters are applied in registration order, with the first registered filter being the outermost. + /// If a message filter does not call the next handler in the pipeline, downstream processing for that + /// message is skipped. + /// + /// + /// The value is . + public IList IncomingFilters + { + get => field ??= []; + set + { + Throw.IfNull(value); + field = value; + } + } + + /// + /// Gets or sets the filters for all outgoing JSON-RPC messages sent to the server. + /// + /// + /// + /// These filters intercept all outgoing JSON-RPC messages before they are sent over the transport, + /// including requests, notifications, responses to server-initiated requests, and errors. + /// + /// + /// Filters are applied in registration order, with the first registered filter being the outermost. + /// If a message filter does not call the next handler in the pipeline, the message will not be sent. + /// Filters may also call the next handler multiple times with different messages to emit additional + /// client-to-server messages. + /// + /// + /// The value is . + public IList OutgoingFilters + { + get => field ??= []; + set + { + Throw.IfNull(value); + field = value; + } + } +} diff --git a/src/ModelContextProtocol.Core/Client/McpClientMessageHandler.cs b/src/ModelContextProtocol.Core/Client/McpClientMessageHandler.cs new file mode 100644 index 000000000..1cc388589 --- /dev/null +++ b/src/ModelContextProtocol.Core/Client/McpClientMessageHandler.cs @@ -0,0 +1,16 @@ +namespace ModelContextProtocol.Client; + +/// +/// Delegate type for handling JSON-RPC messages in a client message filter pipeline. +/// +/// The message context containing the JSON-RPC message and associated client metadata. +/// A cancellation token to cancel the operation. +/// A task representing the asynchronous operation. +/// +/// This delegate can handle any type of JSON-RPC message, including requests, notifications, responses, and errors. +/// Use this with to implement cross-cutting concerns that apply to all +/// client JSON-RPC traffic, such as logging, metadata propagation, redaction, or request tracing. +/// +public delegate Task McpClientMessageHandler( + McpClientMessageContext context, + CancellationToken cancellationToken); diff --git a/src/ModelContextProtocol.Core/Client/McpClientOptions.cs b/src/ModelContextProtocol.Core/Client/McpClientOptions.cs index 7d9c701cc..04fb64f95 100644 --- a/src/ModelContextProtocol.Core/Client/McpClientOptions.cs +++ b/src/ModelContextProtocol.Core/Client/McpClientOptions.cs @@ -185,4 +185,35 @@ public McpClientHandlers Handlers } } + /// + /// Gets or sets the container of filters used by the client for intercepting protocol messages. + /// + /// The value is . + public McpClientFilters Filters + { + get => field ??= new(); + set + { + Throw.IfNull(value); + field = value; + } + } + + /// + /// Gets or sets custom request handlers to register with the client. + /// + /// + /// + /// Each registers a handler for a server-initiated JSON-RPC method + /// not built into the core client. Handlers receive the client and request payload through + /// and control their own serialization, or can be created + /// with strongly-typed parameters and results via + /// . + /// + /// + /// Each method must be unique. Custom handlers cannot replace built-in MCP methods or other custom handlers. + /// + /// + [Experimental(Experimentals.Extensibility_DiagnosticId, UrlFormat = Experimentals.Extensibility_Url)] + public IList? RequestHandlers { get; set; } } diff --git a/src/ModelContextProtocol.Core/Client/McpClientRequestContext.cs b/src/ModelContextProtocol.Core/Client/McpClientRequestContext.cs new file mode 100644 index 000000000..d6aa99542 --- /dev/null +++ b/src/ModelContextProtocol.Core/Client/McpClientRequestContext.cs @@ -0,0 +1,64 @@ +using ModelContextProtocol.Protocol; +using System.Diagnostics.CodeAnalysis; + +namespace ModelContextProtocol.Client; + +/// +/// Provides a context container that provides access to the server request parameters and resources for processing an incoming client request. +/// +/// Type of the request parameters specific to the MCP operation. +/// +/// The encapsulates contextual information for handling an +/// incoming server-to-client MCP request, including the deserialized parameters, raw , +/// associated , and shared dictionary. +/// +[Experimental(Experimentals.Extensibility_DiagnosticId, UrlFormat = Experimentals.Extensibility_Url)] +public sealed class McpClientRequestContext : McpClientMessageContext +{ + /// + /// Initializes a new instance of the class with the specified client, JSON-RPC request, and request parameters. + /// + /// The client with which this instance is associated. + /// The JSON-RPC request associated with this context. + /// The parameters associated with this request. + /// or is . + public McpClientRequestContext(McpClient client, JsonRpcRequest jsonRpcRequest, TParams parameters) + : base(client, jsonRpcRequest) + { + Params = parameters; + } + + /// Gets or sets the parameters associated with this request. + public TParams Params { get; set; } + + /// + /// The value is not a . + public override JsonRpcMessage JsonRpcMessage + { + get => base.JsonRpcMessage; + set + { + Throw.IfNull(value); + if (value is not Protocol.JsonRpcRequest) + { + throw new ArgumentException($"The message must be a {nameof(Protocol.JsonRpcRequest)}.", nameof(value)); + } + + base.JsonRpcMessage = value; + } + } + + /// + /// Gets or sets the JSON-RPC request associated with this context. + /// + /// + /// This property provides access to the complete JSON-RPC request that initiated this handler invocation, + /// including the method name, parameters, request ID, and associated transport metadata. + /// + /// The value is . + public JsonRpcRequest JsonRpcRequest + { + get => (JsonRpcRequest)base.JsonRpcMessage; + set => base.JsonRpcMessage = value; + } +} diff --git a/src/ModelContextProtocol.Core/Client/McpClientRequestHandler.cs b/src/ModelContextProtocol.Core/Client/McpClientRequestHandler.cs new file mode 100644 index 000000000..ff7b903f3 --- /dev/null +++ b/src/ModelContextProtocol.Core/Client/McpClientRequestHandler.cs @@ -0,0 +1,142 @@ +using ModelContextProtocol.Protocol; +using System.Diagnostics.CodeAnalysis; +using System.Text.Json; +using System.Text.Json.Nodes; +using System.Text.Json.Serialization.Metadata; + +namespace ModelContextProtocol.Client; + +/// +/// Represents a custom request handler that can be registered with the MCP client to handle +/// arbitrary server-initiated JSON-RPC methods. +/// +/// +/// +/// Custom request handlers are registered via and +/// are invoked when a JSON-RPC request with the matching is received from the server. +/// The handler receives a with raw JSON parameters and returns a +/// serialized response, giving extensions full control over request and response serialization. +/// +/// +/// Use +/// or +/// to register a strongly-typed handler that automatically deserializes parameters and serializes results. +/// +/// +[Experimental(Experimentals.Extensibility_DiagnosticId, UrlFormat = Experimentals.Extensibility_Url)] +public sealed class McpClientRequestHandler +{ + /// + /// Gets the JSON-RPC method name this handler responds to. + /// + public required string Method { get; init; } + + /// + /// Gets the handler function that processes incoming requests for the specified method. + /// + /// + /// The handler receives the raw JSON parameters in and the + /// full in . + /// It returns a serialized response, or for void methods. + /// + public required Func, CancellationToken, ValueTask> Handler { get; init; } + + /// + /// Creates a strongly-typed custom request handler for the specified method. + /// + /// The type of the request parameters to deserialize from JSON. + /// The type of the response result to serialize to JSON. + /// The JSON-RPC method name this handler responds to. + /// The handler function that processes incoming requests for . + /// + /// The used to deserialize parameters and serialize results. + /// If , is used. + /// + /// A configured instance. + /// or is . + /// is empty or composed entirely of whitespace. + /// + /// If incoming request parameters cannot be deserialized to , an + /// with is thrown and + /// returned to the server as a JSON-RPC invalid-params error. + /// + public static McpClientRequestHandler Create( + string method, + Func, CancellationToken, ValueTask> handler, + JsonSerializerOptions? serializerOptions = null) + { + Throw.IfNullOrWhiteSpace(method); + Throw.IfNull(handler); + + serializerOptions ??= McpJsonUtilities.DefaultOptions; + serializerOptions.MakeReadOnly(); + + return Create( + method, + handler, + serializerOptions.GetTypeInfo(), + serializerOptions.GetTypeInfo()); + } + + /// + /// Creates a strongly-typed custom request handler for the specified method using explicit JSON type metadata. + /// + /// The type of the request parameters to deserialize from JSON. + /// The type of the response result to serialize to JSON. + /// The JSON-RPC method name this handler responds to. + /// The handler function that processes incoming requests for . + /// The JSON type metadata used to deserialize incoming request parameters. + /// The JSON type metadata used to serialize the handler result. + /// A configured instance. + /// + /// , , , or is . + /// + /// is empty or composed entirely of whitespace. + /// + /// If incoming request parameters cannot be deserialized to , an + /// with is thrown and + /// returned to the server as a JSON-RPC invalid-params error. + /// + public static McpClientRequestHandler Create( + string method, + Func, CancellationToken, ValueTask> handler, + JsonTypeInfo paramsTypeInfo, + JsonTypeInfo resultTypeInfo) + { + Throw.IfNullOrWhiteSpace(method); + Throw.IfNull(handler); + Throw.IfNull(paramsTypeInfo); + Throw.IfNull(resultTypeInfo); + + return new McpClientRequestHandler + { + Method = method, + Handler = async (context, cancellationToken) => + { + TParams? typedParams; + if (context.Params is null) + { + typedParams = default; + } + else + { + try + { + typedParams = JsonSerializer.Deserialize(context.Params, paramsTypeInfo); + } + catch (JsonException ex) + { + throw new McpProtocolException( + $"Invalid parameters for method '{method}'.", + ex, + McpErrorCode.InvalidParams); + } + } + + var typedContext = new McpClientRequestContext(context.Client, context.JsonRpcRequest, typedParams); + TResult result = await handler(typedContext, cancellationToken).ConfigureAwait(false); + return JsonSerializer.SerializeToNode(result, resultTypeInfo); + }, + }; + } +} diff --git a/src/ModelContextProtocol.Core/McpSessionHandler.cs b/src/ModelContextProtocol.Core/McpSessionHandler.cs index 5a51c9cc5..3cb1496e0 100644 --- a/src/ModelContextProtocol.Core/McpSessionHandler.cs +++ b/src/ModelContextProtocol.Core/McpSessionHandler.cs @@ -81,8 +81,10 @@ internal static bool SupportsNaturalOutputSchemas(string? protocolVersion) private readonly ITransport _transport; private readonly RequestHandlers _requestHandlers; private readonly NotificationHandlers _notificationHandlers; - private readonly JsonRpcMessageFilter _incomingMessageFilter; - private readonly JsonRpcMessageFilter _outgoingMessageFilter; + private readonly Func _incomingMessageHandler; + private readonly Func _outgoingMessageHandler; + private readonly AsyncLocal _currentIncomingState = new(); + private readonly AsyncLocal _currentOutgoingRequestState = new(); private readonly long _sessionStartingTimestamp = Stopwatch.GetTimestamp(); private readonly DistributedContextPropagator _propagator = DistributedContextPropagator.Current; @@ -141,9 +143,9 @@ public McpSessionHandler( EndpointName = endpointName; _requestHandlers = requestHandlers; _notificationHandlers = notificationHandlers; - _incomingMessageFilter = incomingMessageFilter ?? (next => next); - _outgoingMessageFilter = outgoingMessageFilter ?? (next => next); _logger = logger; + _incomingMessageHandler = (incomingMessageFilter ?? (next => next))(HandleIncomingMessageTerminalAsync); + _outgoingMessageHandler = (outgoingMessageFilter ?? (next => next))(SendToTransportCoreAsync); // ping was removed in the 2026-07-28 protocol revision (SEP-2575). On the 2026-07-28 or later version, // return MethodNotFound; on an older version, the per-spec behavior is to always answer @@ -240,6 +242,9 @@ private async Task ProcessMessagesCoreAsync(CancellationToken cancellationToken) async Task ProcessMessageAsync() { JsonRpcMessageWithId? messageWithId = message as JsonRpcMessageWithId; + IncomingMessageState? incomingState = message is JsonRpcRequest incomingRequest + ? new IncomingMessageState(incomingRequest.Id) + : null; CancellationTokenSource? combinedCts = null; try { @@ -271,17 +276,26 @@ async Task ProcessMessageAsync() #endif // Handle the message. - await HandleMessageAsync(message, combinedCts?.Token ?? cancellationToken).ConfigureAwait(false); + await HandleMessageAsync(message, incomingState, combinedCts?.Token ?? cancellationToken).ConfigureAwait(false); + + if (message is JsonRpcResponse or JsonRpcError && + messageWithId is not null && + _pendingRequests.TryRemove(messageWithId.Id, out var suppressedPendingTcs)) + { + suppressedPendingTcs.TrySetException(new InvalidOperationException( + $"An incoming message filter suppressed the response for request '{messageWithId.Id}'.")); + } } catch (Exception ex) { - // Only send responses for request errors that aren't user-initiated cancellation. + // Only send responses for request errors that aren't user-initiated cancellation + // and haven't already had a response sent for this request. bool isUserCancellation = ex is OperationCanceledException && !cancellationToken.IsCancellationRequested && combinedCts?.IsCancellationRequested is true; - if (!isUserCancellation && message is JsonRpcRequest request) + if (!isUserCancellation && message is JsonRpcRequest request && incomingState?.ResponseSent != true) { JsonRpcErrorDetail detail = ex switch { @@ -331,6 +345,12 @@ ex is OperationCanceledException && await SendMessageAsync(errorMessage, cancellationToken).ConfigureAwait(false); } + else if (message is JsonRpcResponse or JsonRpcError && + messageWithId is not null && + _pendingRequests.TryRemove(messageWithId.Id, out var pendingTcs)) + { + pendingTcs.TrySetException(ex); + } else if (ex is not OperationCanceledException) { if (_logger.IsEnabled(LogLevel.Trace)) @@ -411,7 +431,7 @@ private static async Task GetCompletionDetailsAsync(Tas } } - private async Task HandleMessageAsync(JsonRpcMessage message, CancellationToken cancellationToken) + private async Task HandleMessageAsync(JsonRpcMessage message, IncomingMessageState? incomingState, CancellationToken cancellationToken) { Histogram durationMetric = _isServer ? s_serverOperationDuration : s_clientOperationDuration; string method = GetMethodName(message); @@ -432,6 +452,13 @@ private async Task HandleMessageAsync(JsonRpcMessage message, CancellationToken TagList tags = default; bool addTags = activity is { IsAllDataRequested: true } || startingTimestamp is not null; + if (incomingState is null && addTags) + { + incomingState = new IncomingMessageState(default); + } + + IncomingMessageState? previousIncomingState = _currentIncomingState.Value; + _currentIncomingState.Value = incomingState; try { if (addTags) @@ -439,14 +466,12 @@ private async Task HandleMessageAsync(JsonRpcMessage message, CancellationToken AddTags(ref tags, activity, message, method, target); } - await _incomingMessageFilter(async (msg, ct) => + await _incomingMessageHandler(message, cancellationToken).ConfigureAwait(false); + + if (addTags && incomingState?.Result is { } result) { - var result = await HandleMessageCoreAsync(msg, ct).ConfigureAwait(false); - if (addTags && result is not null) - { - AddResponseTags(ref tags, activity, result, method); - } - })(message, cancellationToken).ConfigureAwait(false); + AddResponseTags(ref tags, activity, result, method); + } } catch (Exception e) when (addTags) { @@ -455,10 +480,20 @@ await _incomingMessageFilter(async (msg, ct) => } finally { + _currentIncomingState.Value = previousIncomingState; FinalizeDiagnostics(activity, startingTimestamp, durationMetric, ref tags); } } + private async Task HandleIncomingMessageTerminalAsync(JsonRpcMessage message, CancellationToken cancellationToken) + { + var result = await HandleMessageCoreAsync(message, cancellationToken).ConfigureAwait(false); + if (result is not null && _currentIncomingState.Value is { } state) + { + state.Result = result; + } + } + private async Task HandleMessageCoreAsync(JsonRpcMessage message, CancellationToken cancellationToken) { switch (message) @@ -695,7 +730,23 @@ public async Task SendRequestAsync(JsonRpcRequest request, Canc AddTags(ref tags, activity, request, method, target); } - await SendToRelatedTransportAsync(request, cancellationToken).ConfigureAwait(false); + var outgoingState = new OutgoingRequestState(request.Id); + OutgoingRequestState? previousOutgoingState = _currentOutgoingRequestState.Value; + _currentOutgoingRequestState.Value = outgoingState; + try + { + await SendToRelatedTransportAsync(request, cancellationToken).ConfigureAwait(false); + } + finally + { + _currentOutgoingRequestState.Value = previousOutgoingState; + } + + if (!outgoingState.Sent) + { + throw new InvalidOperationException( + $"An outgoing message filter suppressed the '{request.Method}' request without sending it."); + } // Now that the request has been sent, register for cancellation. If we registered before, // a cancellation request could arrive before the server knew about that request ID, in which @@ -819,33 +870,61 @@ public async Task SendMessageAsync(JsonRpcMessage message, CancellationToken can // Streamable HTTP transport where the specification states that the server SHOULD include JSON-RPC responses in // the HTTP response body for the POST request containing the corresponding JSON-RPC request. private Task SendToRelatedTransportAsync(JsonRpcMessage message, CancellationToken cancellationToken) - => _outgoingMessageFilter((msg, ct) => + => _outgoingMessageHandler(message, cancellationToken); + + private async Task SendToTransportCoreAsync(JsonRpcMessage msg, CancellationToken ct) + { + if (msg is JsonRpcRequest request) { - if (msg is JsonRpcRequest request) + if (_currentOutgoingRequestState.Value is { } outgoingState && outgoingState.RequestId == request.Id) { - if (_logger.IsEnabled(LogLevel.Trace)) - { - LogSendingRequestSensitive(EndpointName, request.Method, JsonSerializer.Serialize(msg, McpJsonUtilities.JsonContext.Default.JsonRpcMessage)); - } - else - { - LogSendingRequest(EndpointName, request.Method); - } + outgoingState.Sent = true; + } + + if (_logger.IsEnabled(LogLevel.Trace)) + { + LogSendingRequestSensitive(EndpointName, request.Method, JsonSerializer.Serialize(msg, McpJsonUtilities.JsonContext.Default.JsonRpcMessage)); } else { - if (_logger.IsEnabled(LogLevel.Trace)) - { - LogSendingMessageSensitive(EndpointName, JsonSerializer.Serialize(msg, McpJsonUtilities.JsonContext.Default.JsonRpcMessage)); - } - else - { - LogSendingMessage(EndpointName); - } + LogSendingRequest(EndpointName, request.Method); + } + } + else + { + if (_logger.IsEnabled(LogLevel.Trace)) + { + LogSendingMessageSensitive(EndpointName, JsonSerializer.Serialize(msg, McpJsonUtilities.JsonContext.Default.JsonRpcMessage)); + } + else + { + LogSendingMessage(EndpointName); } + } + + await (msg.Context?.RelatedTransport ?? _transport).SendMessageAsync(msg, ct).ConfigureAwait(false); - return (msg.Context?.RelatedTransport ?? _transport).SendMessageAsync(msg, ct); - })(message, cancellationToken); + if (msg is JsonRpcResponse or JsonRpcError && + msg is JsonRpcMessageWithId replyWithId && + _currentIncomingState.Value is { } incomingState && + incomingState.RequestId == replyWithId.Id) + { + incomingState.ResponseSent = true; + } + } + + private sealed class IncomingMessageState(RequestId requestId) + { + public RequestId RequestId { get; } = requestId; + public JsonNode? Result { get; set; } + public bool ResponseSent { get; set; } + } + + private sealed class OutgoingRequestState(RequestId requestId) + { + public RequestId RequestId { get; } = requestId; + public bool Sent { get; set; } + } private static CancelledNotificationParams? GetCancelledNotificationParams(JsonNode? notificationParams) { diff --git a/tests/ModelContextProtocol.Tests/Client/McpClientMessageFilterTests.cs b/tests/ModelContextProtocol.Tests/Client/McpClientMessageFilterTests.cs new file mode 100644 index 000000000..f78ab4280 --- /dev/null +++ b/tests/ModelContextProtocol.Tests/Client/McpClientMessageFilterTests.cs @@ -0,0 +1,990 @@ +using Microsoft.Extensions.DependencyInjection; +using ModelContextProtocol.Client; +using ModelContextProtocol.Protocol; +using ModelContextProtocol.Server; +using ModelContextProtocol.Tests.Utils; +using System.Collections.Concurrent; +using System.ComponentModel; +using System.Text.Json; +using System.Text.Json.Nodes; + +namespace ModelContextProtocol.Tests.Client; + +public class McpClientMessageFilterTests(ITestOutputHelper outputHelper) : ClientServerTestBase(outputHelper, startServer: false) +{ + private const string LegacyProtocolVersion = "2025-11-25"; + private const string ModernProtocolVersion = "2026-07-28"; + + [Fact] + public async Task OutgoingFilters_ExecuteInRegistrationOrder_BeforeAndAfter() + { + McpServerBuilder.WithTools(); + StartServer(); + + List events = []; + var options = new McpClientOptions(); + options.Filters.Message.OutgoingFilters.Add(next => async (context, cancellationToken) => + { + if (context.JsonRpcMessage is JsonRpcRequest { Method: RequestMethods.ToolsCall }) + { + events.Add("Filter1.Before"); + await next(context, cancellationToken); + events.Add("Filter1.After"); + } + else + { + await next(context, cancellationToken); + } + }); + options.Filters.Message.OutgoingFilters.Add(next => async (context, cancellationToken) => + { + if (context.JsonRpcMessage is JsonRpcRequest { Method: RequestMethods.ToolsCall }) + { + events.Add("Filter2.Before"); + await next(context, cancellationToken); + events.Add("Filter2.After"); + } + else + { + await next(context, cancellationToken); + } + }); + + await using var client = await CreateMcpClientForServer(options); + await client.CallToolAsync( + "echo", + new Dictionary { ["message"] = "hello" }, + cancellationToken: TestContext.Current.CancellationToken); + + Assert.Equal(["Filter1.Before", "Filter2.Before", "Filter2.After", "Filter1.After"], events); + } + + [Fact] + public async Task IncomingFilters_ExecuteInRegistrationOrder_BeforeAndAfter() + { + McpServerBuilder.WithTools(); + StartServer(); + + List events = []; + var filter1Completed = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + RequestId? callToolRequestId = null; + + var options = new McpClientOptions(); + options.Filters.Message.OutgoingFilters.Add(next => (context, cancellationToken) => + { + if (context.JsonRpcMessage is JsonRpcRequest { Method: RequestMethods.ToolsCall } req) + { + callToolRequestId = req.Id; + } + + return next(context, cancellationToken); + }); + options.Filters.Message.IncomingFilters.Add(next => async (context, cancellationToken) => + { + if (context.JsonRpcMessage is JsonRpcResponse resp && resp.Id == callToolRequestId) + { + events.Add("Filter1.Before"); + await next(context, cancellationToken); + events.Add("Filter1.After"); + filter1Completed.TrySetResult(true); + } + else + { + await next(context, cancellationToken); + } + }); + options.Filters.Message.IncomingFilters.Add(next => async (context, cancellationToken) => + { + if (context.JsonRpcMessage is JsonRpcResponse resp && resp.Id == callToolRequestId) + { + events.Add("Filter2.Before"); + await next(context, cancellationToken); + events.Add("Filter2.After"); + } + else + { + await next(context, cancellationToken); + } + }); + + await using var client = await CreateMcpClientForServer(options); + await client.CallToolAsync( + "echo", + new Dictionary { ["message"] = "hello" }, + cancellationToken: TestContext.Current.CancellationToken); + + await filter1Completed.Task.WaitAsync(TestConstants.DefaultTimeout, TestContext.Current.CancellationToken); + Assert.Equal(["Filter1.Before", "Filter2.Before", "Filter2.After", "Filter1.After"], events); + } + + [Theory] + [InlineData(ModernProtocolVersion)] + [InlineData(LegacyProtocolVersion)] + public async Task OutgoingFilter_CanAddUpdateRemoveMeta_AndPreservesUnknownMeta(string protocolVersion) + { + var serverReceivedMeta = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + + McpServerBuilder + .WithTools() + .WithMessageFilters(filters => + { + filters.AddIncomingFilter(next => (context, cancellationToken) => + { + if (context.JsonRpcMessage is JsonRpcRequest { Method: RequestMethods.ToolsCall } req) + { + serverReceivedMeta.TrySetResult(req.Params?["_meta"]?.AsObject().DeepClone().AsObject()); + } + + return next(context, cancellationToken); + }); + }); + StartServer(); + + var options = new McpClientOptions { ProtocolVersion = protocolVersion }; + options.Filters.Message.OutgoingFilters.Add(next => (context, cancellationToken) => + { + if (context.JsonRpcMessage is JsonRpcRequest { Method: RequestMethods.ToolsCall } req && + req.Params is JsonObject paramsObj) + { + var meta = paramsObj["_meta"] as JsonObject ?? new JsonObject(); + paramsObj["_meta"] = meta; + + meta["com.example/added"] = "from-filter"; + meta["com.example/updated"] = "new-value"; + meta.Remove("com.example/removed"); + } + + return next(context, cancellationToken); + }); + + await using var client = await CreateMcpClientForServer(options); + + var requestParams = new CallToolRequestParams + { + Name = "echo", + Arguments = new Dictionary + { + ["message"] = JsonSerializer.SerializeToElement("hi", McpJsonUtilities.DefaultOptions), + }, + Meta = new JsonObject + { + ["com.example/updated"] = "old-value", + ["com.example/removed"] = "should-be-removed", + ["com.example/unknown"] = "preserved", + }, + }; + await client.CallToolAsync(requestParams, TestContext.Current.CancellationToken); + + var meta = await serverReceivedMeta.Task.WaitAsync(TestConstants.DefaultTimeout, TestContext.Current.CancellationToken); + Assert.NotNull(meta); + Assert.Equal("from-filter", meta["com.example/added"]?.GetValue()); + Assert.Equal("new-value", meta["com.example/updated"]?.GetValue()); + Assert.False(meta.ContainsKey("com.example/removed")); + Assert.Equal("preserved", meta["com.example/unknown"]?.GetValue()); + + if (protocolVersion == ModernProtocolVersion) + { + Assert.Equal(ModernProtocolVersion, meta[MetaKeys.ProtocolVersion]?.GetValue()); + } + } + + [Fact] + public async Task IncomingFilter_CanModifyResponsePayload() + { + McpServerBuilder.WithTools(); + StartServer(); + + RequestId? callToolRequestId = null; + var options = new McpClientOptions(); + options.Filters.Message.OutgoingFilters.Add(next => (context, cancellationToken) => + { + if (context.JsonRpcMessage is JsonRpcRequest { Method: RequestMethods.ToolsCall } req) + { + callToolRequestId = req.Id; + } + + return next(context, cancellationToken); + }); + options.Filters.Message.IncomingFilters.Add(next => (context, cancellationToken) => + { + if (context.JsonRpcMessage is JsonRpcResponse resp && + resp.Id == callToolRequestId && + resp.Result is JsonObject resultObj && + resultObj["content"] is JsonArray content && + content[0] is JsonObject firstBlock) + { + firstBlock["text"] = "modified-by-filter"; + } + + return next(context, cancellationToken); + }); + + await using var client = await CreateMcpClientForServer(options); + var result = await client.CallToolAsync( + "echo", + new Dictionary { ["message"] = "original" }, + cancellationToken: TestContext.Current.CancellationToken); + + var text = Assert.IsType(Assert.Single(result.Content)); + Assert.Equal("modified-by-filter", text.Text); + } + + [Fact] + public async Task IncomingFilter_CanReplaceResponseWithError() + { + McpServerBuilder.WithTools(); + StartServer(); + + RequestId? callToolRequestId = null; + var options = new McpClientOptions(); + options.Filters.Message.OutgoingFilters.Add(next => (context, cancellationToken) => + { + if (context.JsonRpcMessage is JsonRpcRequest { Method: RequestMethods.ToolsCall } req) + { + callToolRequestId = req.Id; + } + + return next(context, cancellationToken); + }); + options.Filters.Message.IncomingFilters.Add(next => (context, cancellationToken) => + { + if (context.JsonRpcMessage is JsonRpcResponse resp && resp.Id == callToolRequestId) + { + context.JsonRpcMessage = new JsonRpcError + { + Id = resp.Id, + Error = new JsonRpcErrorDetail + { + Code = -31050, + Message = "Rejected by client filter", + }, + }; + } + + return next(context, cancellationToken); + }); + + await using var client = await CreateMcpClientForServer(options); + var ex = await Assert.ThrowsAsync(() => + client.CallToolAsync( + "echo", + new Dictionary { ["message"] = "hello" }, + cancellationToken: TestContext.Current.CancellationToken).AsTask()); + + Assert.Equal((McpErrorCode)(-31050), ex.ErrorCode); + Assert.Contains("Rejected by client filter", ex.Message); + } + + [Fact] + public async Task Filters_CanSuppressIncomingAndOutgoingNotifications_WithoutBreakingOperations() + { + ConcurrentQueue serverReceivedNotifications = new(); + var serverSawAllowed = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + + McpServerBuilder + .WithTools() + .WithMessageFilters(filters => + { + filters.AddIncomingFilter(next => (context, cancellationToken) => + { + if (context.JsonRpcMessage is JsonRpcNotification n && + n.Method.StartsWith("com.example/", StringComparison.Ordinal)) + { + serverReceivedNotifications.Enqueue(n.Method); + if (n.Method == "com.example/allowed") + { + serverSawAllowed.TrySetResult(true); + } + } + + return next(context, cancellationToken); + }); + }); + StartServer(); + + var options = new McpClientOptions(); + options.Filters.Message.OutgoingFilters.Add(next => (context, cancellationToken) => + { + if (context.JsonRpcMessage is JsonRpcNotification { Method: "com.example/suppressed-out" }) + { + return Task.CompletedTask; + } + + return next(context, cancellationToken); + }); + options.Filters.Message.IncomingFilters.Add(next => (context, cancellationToken) => + { + if (context.JsonRpcMessage is JsonRpcNotification { Method: "com.example/suppressed-in" }) + { + return Task.CompletedTask; + } + + return next(context, cancellationToken); + }); + + await using var client = await CreateMcpClientForServer(options); + + ConcurrentQueue clientReceivedNotifications = new(); + var clientSawAllowed = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + await using var reg1 = client.RegisterNotificationHandler("com.example/suppressed-in", (n, _) => + { + clientReceivedNotifications.Enqueue(n.Method); + return default; + }); + await using var reg2 = client.RegisterNotificationHandler("com.example/allowed-in", (n, _) => + { + clientReceivedNotifications.Enqueue(n.Method); + clientSawAllowed.TrySetResult(true); + return default; + }); + + await client.SendNotificationAsync("com.example/suppressed-out", TestContext.Current.CancellationToken); + await client.SendNotificationAsync("com.example/allowed", TestContext.Current.CancellationToken); + await serverSawAllowed.Task.WaitAsync(TestConstants.DefaultTimeout, TestContext.Current.CancellationToken); + + await Server.SendNotificationAsync("com.example/suppressed-in", TestContext.Current.CancellationToken); + await Server.SendNotificationAsync("com.example/allowed-in", TestContext.Current.CancellationToken); + await clientSawAllowed.Task.WaitAsync(TestConstants.DefaultTimeout, TestContext.Current.CancellationToken); + + // Subsequent normal request still works cleanly. + var result = await client.CallToolAsync( + "echo", + new Dictionary { ["message"] = "still-works" }, + cancellationToken: TestContext.Current.CancellationToken); + var text = Assert.IsType(Assert.Single(result.Content)); + Assert.Equal("echo: still-works", text.Text); + + Assert.Equal(["com.example/allowed"], serverReceivedNotifications.ToArray()); + Assert.Equal(["com.example/allowed-in"], clientReceivedNotifications.ToArray()); + } + + [Fact] + public async Task IncomingFilter_StreamingNotifications_ArriveIndividuallyInOrder() + { + var firstNotificationSeen = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var secondNotificationSeen = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var allowSecondNotification = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + List filterObservedSteps = []; + + McpServerBuilder.WithTools([ + McpServerTool.Create( + async (McpServer server, CancellationToken ct) => + { + await server.SendMessageAsync( + new JsonRpcNotification { Method = "com.example/step", Params = new JsonObject { ["step"] = 1 } }, + ct); + await allowSecondNotification.Task.WaitAsync(TestConstants.DefaultTimeout, ct); + await server.SendMessageAsync( + new JsonRpcNotification { Method = "com.example/step", Params = new JsonObject { ["step"] = 2 } }, + ct); + return "done"; + }, + new McpServerToolCreateOptions { Name = "stream_steps" }), + ]); + StartServer(); + + var options = new McpClientOptions(); + options.Filters.Message.IncomingFilters.Add(next => (context, cancellationToken) => + { + if (context.JsonRpcMessage is JsonRpcNotification { Method: "com.example/step" } n && + n.Params?["step"]?.GetValue() is int step) + { + lock (filterObservedSteps) + { + filterObservedSteps.Add(step); + } + + if (step == 1) + { + firstNotificationSeen.TrySetResult(true); + } + else if (step == 2) + { + secondNotificationSeen.TrySetResult(true); + } + } + + return next(context, cancellationToken); + }); + + await using var client = await CreateMcpClientForServer(options); + + var callTask = client.CallToolAsync("stream_steps", cancellationToken: TestContext.Current.CancellationToken).AsTask(); + + // First notification must arrive at the filter BEFORE the tool finishes or sends the second notification. + await firstNotificationSeen.Task.WaitAsync(TestConstants.DefaultTimeout, TestContext.Current.CancellationToken); + Assert.False(callTask.IsCompleted); + + allowSecondNotification.TrySetResult(true); + var result = await callTask; + await secondNotificationSeen.Task.WaitAsync(TestConstants.DefaultTimeout, TestContext.Current.CancellationToken); + + var text = Assert.IsType(Assert.Single(result.Content)); + Assert.Equal("done", text.Text); + Assert.Equal([1, 2], filterObservedSteps); + } + + [Fact] + public async Task IncomingFilter_ThrowingOnResponse_FailsPendingRequestAndRunsOuterCleanup() + { + McpServerBuilder.WithTools(); + StartServer(); + + RequestId? callToolRequestId = null; + var outerCleanupRan = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + + var options = new McpClientOptions(); + options.Filters.Message.OutgoingFilters.Add(next => (context, cancellationToken) => + { + if (context.JsonRpcMessage is JsonRpcRequest { Method: RequestMethods.ToolsCall } req) + { + callToolRequestId = req.Id; + } + + return next(context, cancellationToken); + }); + options.Filters.Message.IncomingFilters.Add(next => async (context, cancellationToken) => + { + if (context.JsonRpcMessage is JsonRpcResponse resp && resp.Id == callToolRequestId) + { + try + { + await next(context, cancellationToken); + } + finally + { + outerCleanupRan.TrySetResult(true); + } + } + else + { + await next(context, cancellationToken); + } + }); + options.Filters.Message.IncomingFilters.Add(next => (context, cancellationToken) => + { + if (context.JsonRpcMessage is JsonRpcResponse resp && resp.Id == callToolRequestId) + { + throw new InvalidOperationException("Signature check failed"); + } + + return next(context, cancellationToken); + }); + + await using var client = await CreateMcpClientForServer(options); + var ex = await Assert.ThrowsAsync(() => + client.CallToolAsync( + "echo", + new Dictionary { ["message"] = "hello" }, + cancellationToken: TestContext.Current.CancellationToken).AsTask()); + + Assert.Equal("Signature check failed", ex.Message); + Assert.True(await outerCleanupRan.Task.WaitAsync(TestConstants.DefaultTimeout, TestContext.Current.CancellationToken)); + } + + [Fact] + public async Task OutgoingFilter_ThrowingOnRequest_PropagatesExceptionAndRunsOuterCleanup() + { + McpServerBuilder.WithTools(); + StartServer(); + + bool outerCleanupRan = false; + var options = new McpClientOptions(); + options.Filters.Message.OutgoingFilters.Add(next => async (context, cancellationToken) => + { + if (context.JsonRpcMessage is JsonRpcRequest { Method: RequestMethods.ToolsCall }) + { + try + { + await next(context, cancellationToken); + } + finally + { + outerCleanupRan = true; + } + } + else + { + await next(context, cancellationToken); + } + }); + options.Filters.Message.OutgoingFilters.Add(next => (context, cancellationToken) => + { + if (context.JsonRpcMessage is JsonRpcRequest { Method: RequestMethods.ToolsCall }) + { + throw new InvalidOperationException("Blocked outgoing request"); + } + + return next(context, cancellationToken); + }); + + await using var client = await CreateMcpClientForServer(options); + var ex = await Assert.ThrowsAsync(() => + client.CallToolAsync( + "echo", + new Dictionary { ["message"] = "hello" }, + cancellationToken: TestContext.Current.CancellationToken).AsTask()); + + Assert.Equal("Blocked outgoing request", ex.Message); + Assert.True(outerCleanupRan); + } + + [Fact] + public async Task Filters_SnapshotAtClientCreation_PostCreationMutationDoesNotAffectRunningClient() + { + McpServerBuilder.WithTools(); + StartServer(); + + int originalFilterCalls = 0; + int mutatedFilterCalls = 0; + + var options = new McpClientOptions(); + options.Filters.Message.OutgoingFilters.Add(next => (context, cancellationToken) => + { + if (context.JsonRpcMessage is JsonRpcRequest { Method: RequestMethods.ToolsCall }) + { + Interlocked.Increment(ref originalFilterCalls); + } + + return next(context, cancellationToken); + }); + + await using var client = await CreateMcpClientForServer(options); + + // Mutate the options list after client construction. + options.Filters.Message.OutgoingFilters.Clear(); + options.Filters.Message.OutgoingFilters.Add(next => (context, cancellationToken) => + { + Interlocked.Increment(ref mutatedFilterCalls); + return next(context, cancellationToken); + }); + + await client.CallToolAsync( + "echo", + new Dictionary { ["message"] = "snapshot" }, + cancellationToken: TestContext.Current.CancellationToken); + + Assert.Equal(1, originalFilterCalls); + Assert.Equal(0, mutatedFilterCalls); + } + + [Fact] + public async Task Filters_ShareStateViaContextItems() + { + McpServerBuilder.WithTools(); + StartServer(); + + string? innerSaw = null; + string? outerSawAfter = null; + + var options = new McpClientOptions(); + options.Filters.Message.OutgoingFilters.Add(next => async (context, cancellationToken) => + { + if (context.JsonRpcMessage is JsonRpcRequest { Method: RequestMethods.ToolsCall }) + { + context.Items["trace"] = "outer-value"; + await next(context, cancellationToken); + outerSawAfter = context.Items["trace"] as string; + } + else + { + await next(context, cancellationToken); + } + }); + options.Filters.Message.OutgoingFilters.Add(next => (context, cancellationToken) => + { + if (context.JsonRpcMessage is JsonRpcRequest { Method: RequestMethods.ToolsCall }) + { + innerSaw = context.Items["trace"] as string; + context.Items["trace"] = "inner-updated"; + } + + return next(context, cancellationToken); + }); + + await using var client = await CreateMcpClientForServer(options); + await client.CallToolAsync( + "echo", + new Dictionary { ["message"] = "items" }, + cancellationToken: TestContext.Current.CancellationToken); + + Assert.Equal("outer-value", innerSaw); + Assert.Equal("inner-updated", outerSawAfter); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task FilterReturningNullHandler_ThrowsInvalidOperationExceptionDuringCreation(bool incoming) + { + McpServerBuilder.WithTools(); + StartServer(); + + var options = new McpClientOptions(); + if (incoming) + { + options.Filters.Message.IncomingFilters.Add(_ => null!); + } + else + { + options.Filters.Message.OutgoingFilters.Add(_ => null!); + } + + await Assert.ThrowsAsync(() => CreateMcpClientForServer(options)); + } + + [Fact] + public async Task FilterFactories_InvokedOncePerClient_ClosureStatePersistsAcrossMessages() + { + McpServerBuilder.WithTools(); + StartServer(); + + int outgoingFactoryCalls = 0; + int incomingFactoryCalls = 0; + int capturedOutgoingCount = 0; + int capturedIncomingCount = 0; + + var options = new McpClientOptions(); + options.Filters.Message.OutgoingFilters.Add(next => + { + Interlocked.Increment(ref outgoingFactoryCalls); + int localCounter = 0; + return (context, cancellationToken) => + { + if (context.JsonRpcMessage is JsonRpcRequest { Method: RequestMethods.ToolsCall }) + { + capturedOutgoingCount = Interlocked.Increment(ref localCounter); + } + + return next(context, cancellationToken); + }; + }); + options.Filters.Message.IncomingFilters.Add(next => + { + Interlocked.Increment(ref incomingFactoryCalls); + int localCounter = 0; + return (context, cancellationToken) => + { + if (context.JsonRpcMessage is JsonRpcResponse) + { + capturedIncomingCount = Interlocked.Increment(ref localCounter); + } + + return next(context, cancellationToken); + }; + }); + + await using var client = await CreateMcpClientForServer(options); + + await client.CallToolAsync("echo", new Dictionary { ["message"] = "1" }, cancellationToken: TestContext.Current.CancellationToken); + await client.CallToolAsync("echo", new Dictionary { ["message"] = "2" }, cancellationToken: TestContext.Current.CancellationToken); + + Assert.Equal(1, outgoingFactoryCalls); + Assert.Equal(1, incomingFactoryCalls); + Assert.Equal(2, capturedOutgoingCount); + Assert.True(capturedIncomingCount >= 2); + } + + [Fact] + public async Task OutgoingFilter_SuppressingRequest_FailsPendingRequestInsteadOfHanging() + { + McpServerBuilder.WithTools(); + StartServer(); + + var options = new McpClientOptions(); + options.Filters.Message.OutgoingFilters.Add(next => async (context, cancellationToken) => + { + if (context.JsonRpcMessage is JsonRpcRequest { Method: RequestMethods.ToolsCall }) + { + // Even if the filter emits an unrelated notification, suppressing the request itself must fail the caller. + await next( + new McpClientMessageContext(context.Client, new JsonRpcNotification { Method = "com.example/side-effect" }), + cancellationToken); + return; + } + + await next(context, cancellationToken); + }); + + await using var client = await CreateMcpClientForServer(options); + + var ex = await Assert.ThrowsAsync(() => + client.CallToolAsync( + "echo", + new Dictionary { ["message"] = "suppressed" }, + cancellationToken: TestContext.Current.CancellationToken).AsTask()); + Assert.Contains(RequestMethods.ToolsCall, ex.Message); + } + + [Fact] + public async Task IncomingFilter_SuppressingResponse_FailsPendingRequestInsteadOfHanging() + { + McpServerBuilder.WithTools(); + StartServer(); + + RequestId? callToolRequestId = null; + + var options = new McpClientOptions(); + options.Filters.Message.OutgoingFilters.Add(next => (context, cancellationToken) => + { + if (context.JsonRpcMessage is JsonRpcRequest { Method: RequestMethods.ToolsCall } req) + { + callToolRequestId = req.Id; + } + + return next(context, cancellationToken); + }); + options.Filters.Message.IncomingFilters.Add(next => (context, cancellationToken) => + { + if (context.JsonRpcMessage is JsonRpcResponse resp && resp.Id == callToolRequestId) + { + return Task.CompletedTask; + } + + return next(context, cancellationToken); + }); + + await using var client = await CreateMcpClientForServer(options); + + await Assert.ThrowsAsync(() => + client.CallToolAsync( + "echo", + new Dictionary { ["message"] = "suppressed-response" }, + cancellationToken: TestContext.Current.CancellationToken).AsTask()); + } + + [Fact] + public async Task Filters_ReplacingJsonRpcMessage_PreservesItemsAndContext() + { + McpServerBuilder.WithTools(); + StartServer(); + + string? innerObservedItem = null; + string? innerObservedRoutingName = null; + + var options = new McpClientOptions(); + options.Filters.Message.OutgoingFilters.Add(next => (context, cancellationToken) => + { + if (context.JsonRpcMessage is JsonRpcRequest { Method: RequestMethods.ToolsCall } req) + { + context.Items["correlation"] = "preserved-value"; +#pragma warning disable MCPEXP002 + req.Context!.RoutingName = "custom-route"; +#pragma warning restore MCPEXP002 + } + + return next(context, cancellationToken); + }); + options.Filters.Message.OutgoingFilters.Add(next => (context, cancellationToken) => + { + if (context.JsonRpcMessage is JsonRpcRequest { Method: RequestMethods.ToolsCall } req) + { + // Replace JsonRpcMessage without setting Context explicitly. + context.JsonRpcMessage = new JsonRpcRequest + { + Id = req.Id, + Method = req.Method, + Params = new JsonObject + { + ["name"] = "echo", + ["arguments"] = new JsonObject { ["message"] = "replaced-with-context" }, + }, + }; + } + + return next(context, cancellationToken); + }); + options.Filters.Message.OutgoingFilters.Add(next => (context, cancellationToken) => + { + if (context.JsonRpcMessage is JsonRpcRequest { Method: RequestMethods.ToolsCall } req) + { + innerObservedItem = context.Items.TryGetValue("correlation", out var val) ? val as string : null; +#pragma warning disable MCPEXP002 + innerObservedRoutingName = req.Context?.RoutingName; +#pragma warning restore MCPEXP002 + } + + return next(context, cancellationToken); + }); + + await using var client = await CreateMcpClientForServer(options); + var result = await client.CallToolAsync( + "echo", + new Dictionary { ["message"] = "original" }, + cancellationToken: TestContext.Current.CancellationToken); + + var text = Assert.IsType(Assert.Single(result.Content)); + Assert.Equal("echo: replaced-with-context", text.Text); + Assert.Equal("preserved-value", innerObservedItem); + Assert.Equal("custom-route", innerObservedRoutingName); + } + + [Fact] + public async Task IncomingFilter_ThrowingAfterNextOnServerRequest_DoesNotSendDuplicateReply() + { + McpServerBuilder.WithTools(); + StartServer(); + + int outgoingReplies = 0; + var postThrowReached = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + + var options = new McpClientOptions + { +#pragma warning disable MCPEXP002 + RequestHandlers = + [ + new McpClientRequestHandler + { + Method = "com.example/check", + Handler = (_, _) => new ValueTask(new JsonObject { ["ok"] = true }), + }, + ], +#pragma warning restore MCPEXP002 + }; + options.Filters.Message.OutgoingFilters.Add(next => (context, cancellationToken) => + { + if (context.JsonRpcMessage is JsonRpcResponse or JsonRpcError) + { + Interlocked.Increment(ref outgoingReplies); + } + + return next(context, cancellationToken); + }); + options.Filters.Message.IncomingFilters.Add(next => async (context, cancellationToken) => + { + if (context.JsonRpcMessage is JsonRpcRequest { Method: "com.example/check" }) + { + await next(context, cancellationToken); + postThrowReached.TrySetResult(true); + throw new InvalidOperationException("Post-processing failure after reply already sent"); + } + + await next(context, cancellationToken); + }); + + await using var client = await CreateMcpClientForServer(options); + + // Server invokes client request; handler sends JsonRpcResponse, then filter throws after next. + var response = await Server.SendRequestAsync( + new JsonRpcRequest { Method = "com.example/check" }, + TestContext.Current.CancellationToken); + Assert.True(response.Result?["ok"]?.GetValue()); + await postThrowReached.Task.WaitAsync(TestConstants.DefaultTimeout, TestContext.Current.CancellationToken); + + // Make another request to ensure any erroneous second reply would have been flushed through OutgoingFilters. + await client.CallToolAsync( + "echo", + new Dictionary { ["message"] = "after-throw" }, + cancellationToken: TestContext.Current.CancellationToken); + + Assert.Equal(1, outgoingReplies); + } + + [Fact] + public async Task OutgoingFilter_MrtrInputRequiredRetry_GetsFreshItemsPerAttempt() + { + ServiceCollection.Configure(o => o.ProtocolVersion = "2026-07-28"); + McpServerBuilder.WithTools([ + McpServerTool.Create( + async (McpServer server, CancellationToken ct) => + { + var elicitResult = await server.ElicitAsync( + new ElicitRequestParams { Message = "Confirm", RequestedSchema = new() }, + ct); + return $"action:{elicitResult.Action}"; + }, + new McpServerToolCreateOptions { Name = "elicit_tool" }), + ]); + StartServer(); + + int attemptCount = 0; + + var options = new McpClientOptions + { + ProtocolVersion = "2026-07-28", + Handlers = new McpClientHandlers + { + ElicitationHandler = (_, _) => ValueTask.FromResult(new ElicitResult { Action = "accept" }), + }, + }; + options.Filters.Message.OutgoingFilters.Add(next => (context, cancellationToken) => + { + if (context.JsonRpcMessage is JsonRpcRequest { Method: RequestMethods.ToolsCall }) + { + int attempt = Interlocked.Increment(ref attemptCount); + // Using Items.Add (rather than indexer) would throw ArgumentException if retry reused prior attempt's Items. + context.Items.Add("attempt", attempt); + } + + return next(context, cancellationToken); + }); + + await using var client = await CreateMcpClientForServer(options); + var result = await client.CallToolAsync("elicit_tool", cancellationToken: TestContext.Current.CancellationToken); + + var text = Assert.IsType(Assert.Single(result.Content)); + Assert.Equal("action:accept", text.Text); + Assert.Equal(2, attemptCount); + } + + private sealed class EchoTools + { + [McpServerTool(Name = "echo"), Description("Echoes the input message.")] + public static string Echo(string message) => $"echo: {message}"; + } +} + +public class McpClientMessageFilterValidationTests(ITestOutputHelper outputHelper) : LoggedTest(outputHelper) +{ + [Theory] + [InlineData(true)] + [InlineData(false)] + public async Task NullFilter_FailsFastBeforeTransportConnect(bool incoming) + { + var transport = new TrackingClientTransport(); + var options = new McpClientOptions(); + if (incoming) + { + options.Filters.Message.IncomingFilters.Add(null!); + } + else + { + options.Filters.Message.OutgoingFilters.Add(null!); + } + + await Assert.ThrowsAsync(() => + McpClient.CreateAsync(transport, options, cancellationToken: TestContext.Current.CancellationToken)); + Assert.Equal(0, transport.ConnectCount); + + var resumeOptions = new ResumeClientSessionOptions + { + ServerCapabilities = new(), + ServerInfo = new() { Name = "test", Version = "1.0" }, + }; + await Assert.ThrowsAsync(() => + McpClient.ResumeSessionAsync(transport, resumeOptions, options, cancellationToken: TestContext.Current.CancellationToken)); + Assert.Equal(0, transport.ConnectCount); + } + + [Fact] + public void FilterContainers_RejectNullValues() + { + var options = new McpClientOptions(); + Assert.Throws(() => options.Filters = null!); + Assert.Throws(() => options.Filters.Message = null!); + Assert.Throws(() => options.Filters.Message.IncomingFilters = null!); + Assert.Throws(() => options.Filters.Message.OutgoingFilters = null!); + } + + private sealed class TrackingClientTransport : IClientTransport + { + public int ConnectCount { get; private set; } + public string Name => "tracking"; + + public Task ConnectAsync(CancellationToken cancellationToken = default) + { + ConnectCount++; + throw new InvalidOperationException("ConnectAsync should not have been called."); + } + } +} diff --git a/tests/ModelContextProtocol.Tests/Client/McpClientRequestHandlerTests.cs b/tests/ModelContextProtocol.Tests/Client/McpClientRequestHandlerTests.cs new file mode 100644 index 000000000..ecb5c83f4 --- /dev/null +++ b/tests/ModelContextProtocol.Tests/Client/McpClientRequestHandlerTests.cs @@ -0,0 +1,447 @@ +#pragma warning disable MCPEXP002 + +using Microsoft.Extensions.DependencyInjection; +using ModelContextProtocol.Client; +using ModelContextProtocol.Protocol; +using ModelContextProtocol.Server; +using ModelContextProtocol.Tests.Utils; +using System.Text.Json; +using System.Text.Json.Nodes; +using System.Text.Json.Serialization; + +namespace ModelContextProtocol.Tests.Client; + +public partial class McpClientRequestHandlerTests(ITestOutputHelper outputHelper) : ClientServerTestBase(outputHelper) +{ + protected override void ConfigureServices(ServiceCollection services, IMcpServerBuilder mcpServerBuilder) + { + services.Configure(o => + { + o.ServerInfo = new Implementation + { + Name = "custom-client-handler-server", + Version = "1.0.0", + }; + }); + } + + [Fact] + public async Task CustomRequestHandler_RawJsonNode_HandlesServerInitiatedRequest() + { + string? observedServerName = null; + string? observedMethod = null; + + var options = new McpClientOptions + { + RequestHandlers = + [ + new McpClientRequestHandler + { + Method = "com.example/echo", + Handler = (context, _) => + { + observedServerName = context.Client.ServerInfo?.Name; + observedMethod = context.JsonRpcRequest.Method; + string? text = context.Params?["text"]?.GetValue(); + return new ValueTask(new JsonObject { ["echoed"] = $"client:{text}" }); + }, + }, + ], + }; + + await using var client = await CreateMcpClientForServer(options); + + var response = await Server.SendRequestAsync( + new JsonRpcRequest + { + Method = "com.example/echo", + Params = new JsonObject { ["text"] = "hello" }, + }, + TestContext.Current.CancellationToken); + + Assert.Equal("client:hello", response.Result?["echoed"]?.GetValue()); + Assert.Equal("custom-client-handler-server", observedServerName); + Assert.Equal("com.example/echo", observedMethod); + } + + [Fact] + public async Task CustomRequestHandler_TypedCreate_WithSerializerOptions_DeserializesAndSerializes() + { + var serializerOptions = new JsonSerializerOptions(JsonSerializerDefaults.Web) + { + TypeInfoResolver = TestJsonContext.Default, + }; + + var options = new McpClientOptions + { + RequestHandlers = + [ + McpClientRequestHandler.Create( + "com.example/search", + (context, _) => + { + Assert.NotNull(context.Params); + return new ValueTask(new SearchResult([$"match:{context.Params.Query}"])); + }, + serializerOptions), + ], + }; + + await using var client = await CreateMcpClientForServer(options); + + var result = await Server.SendRequestAsync( + "com.example/search", + new SearchParams("invoices"), + serializerOptions, + cancellationToken: TestContext.Current.CancellationToken); + + Assert.Equal(["match:invoices"], result.Matches); + } + + [Fact] + public async Task CustomRequestHandler_TypedCreate_WithJsonTypeInfo_DeserializesAndSerializes() + { + var options = new McpClientOptions + { + RequestHandlers = + [ + McpClientRequestHandler.Create( + "com.example/search-aot", + (McpClientRequestContext context, CancellationToken _) => + new ValueTask(new SearchResult([$"aot:{context.Params?.Query ?? "none"}"])), + TestJsonContext.Default.SearchParams, + TestJsonContext.Default.SearchResult), + ], + }; + + await using var client = await CreateMcpClientForServer(options); + + var serializerOptions = new JsonSerializerOptions(JsonSerializerDefaults.Web) + { + TypeInfoResolver = TestJsonContext.Default, + }; + + // With params + var result = await Server.SendRequestAsync( + "com.example/search-aot", + new SearchParams("docs"), + serializerOptions, + cancellationToken: TestContext.Current.CancellationToken); + Assert.Equal(["aot:docs"], result.Matches); + + // With null/missing params + var emptyResponse = await Server.SendRequestAsync( + new JsonRpcRequest { Method = "com.example/search-aot", Params = null }, + TestContext.Current.CancellationToken); + var emptyResult = emptyResponse.Result.Deserialize(TestJsonContext.Default.SearchResult); + Assert.NotNull(emptyResult); + Assert.Equal(["aot:none"], emptyResult.Matches); + } + + [Fact] + public async Task CustomRequestHandler_TypedCreate_InvalidParams_ReturnsInvalidParamsError() + { + var options = new McpClientOptions + { + RequestHandlers = + [ + McpClientRequestHandler.Create( + "com.example/strict", + (McpClientRequestContext _, CancellationToken _) => + new ValueTask(new SearchResult([])), + TestJsonContext.Default.SearchParams, + TestJsonContext.Default.SearchResult), + ], + }; + + await using var client = await CreateMcpClientForServer(options); + + var ex = await Assert.ThrowsAsync(() => + Server.SendRequestAsync( + new JsonRpcRequest + { + Method = "com.example/strict", + Params = JsonValue.Create("not-an-object"), + }, + TestContext.Current.CancellationToken)); + + Assert.Equal(McpErrorCode.InvalidParams, ex.ErrorCode); + } + + [Fact] + public async Task CustomRequestHandler_ThrowsMcpProtocolException_PropagatesErrorCodeToServer() + { + var options = new McpClientOptions + { + RequestHandlers = + [ + new McpClientRequestHandler + { + Method = "com.example/fail", + Handler = (_, _) => throw new McpProtocolException("Extension failure", (McpErrorCode)(-31001)), + }, + ], + }; + + await using var client = await CreateMcpClientForServer(options); + + var ex = await Assert.ThrowsAsync(() => + Server.SendRequestAsync( + new JsonRpcRequest { Method = "com.example/fail" }, + TestContext.Current.CancellationToken)); + + Assert.Equal((McpErrorCode)(-31001), ex.ErrorCode); + Assert.Contains("Extension failure", ex.Message); + } + + [Fact] + public async Task CustomRequestHandler_Cancellation_CancelsHandlerToken() + { + var handlerStarted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + var handlerCanceled = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + + var options = new McpClientOptions + { + RequestHandlers = + [ + new McpClientRequestHandler + { + Method = "com.example/slow", + Handler = async (_, cancellationToken) => + { + handlerStarted.TrySetResult(true); + try + { + await Task.Delay(Timeout.InfiniteTimeSpan, cancellationToken); + } + catch (OperationCanceledException) + { + handlerCanceled.TrySetResult(true); + throw; + } + + return null; + }, + }, + ], + }; + + await using var client = await CreateMcpClientForServer(options); + + using var cts = CancellationTokenSource.CreateLinkedTokenSource(TestContext.Current.CancellationToken); + var requestTask = Server.SendRequestAsync( + new JsonRpcRequest { Method = "com.example/slow" }, + cts.Token); + + await handlerStarted.Task.WaitAsync(TestConstants.DefaultTimeout, TestContext.Current.CancellationToken); + await cts.CancelAsync(); + + await Assert.ThrowsAnyAsync(() => requestTask); + Assert.True(await handlerCanceled.Task.WaitAsync(TestConstants.DefaultTimeout, TestContext.Current.CancellationToken)); + } + + [Fact] + public async Task CustomRequestHandler_ReceivesContextItemsFromIncomingMessageFilter() + { + string? observedItem = null; + + var options = new McpClientOptions + { + RequestHandlers = + [ + new McpClientRequestHandler + { + Method = "com.example/with-items", + Handler = (context, _) => + { + observedItem = context.Items["correlation"] as string; + return new ValueTask(new JsonObject { ["ok"] = true }); + }, + }, + ], + }; + options.Filters.Message.IncomingFilters.Add(next => (context, cancellationToken) => + { + if (context.JsonRpcMessage is JsonRpcRequest { Method: "com.example/with-items" }) + { + context.Items["correlation"] = "trace-123"; + } + + return next(context, cancellationToken); + }); + + await using var client = await CreateMcpClientForServer(options); + + var response = await Server.SendRequestAsync( + new JsonRpcRequest { Method = "com.example/with-items" }, + TestContext.Current.CancellationToken); + + Assert.True(response.Result?["ok"]?.GetValue()); + Assert.Equal("trace-123", observedItem); + } + + [Fact] + public async Task CustomRequestHandler_IncomingFilterCanShortCircuitServerRequest() + { + bool handlerInvoked = false; + + var options = new McpClientOptions + { + RequestHandlers = + [ + new McpClientRequestHandler + { + Method = "com.example/shortcircuit", + Handler = (_, _) => + { + handlerInvoked = true; + return new ValueTask(new JsonObject { ["source"] = "handler" }); + }, + }, + ], + }; + options.Filters.Message.IncomingFilters.Add(next => async (context, cancellationToken) => + { + if (context.JsonRpcMessage is JsonRpcRequest { Method: "com.example/shortcircuit" } req) + { + await context.Client.SendMessageAsync( + new JsonRpcResponse + { + Id = req.Id, + Result = new JsonObject { ["source"] = "filter" }, + }, + cancellationToken); + return; + } + + await next(context, cancellationToken); + }); + + await using var client = await CreateMcpClientForServer(options); + + var response = await Server.SendRequestAsync( + new JsonRpcRequest { Method = "com.example/shortcircuit" }, + TestContext.Current.CancellationToken); + + Assert.Equal("filter", response.Result?["source"]?.GetValue()); + Assert.False(handlerInvoked); + } + + [Theory] + [InlineData(RequestMethods.Ping)] +#pragma warning disable MCP9005 + [InlineData(RequestMethods.SamplingCreateMessage)] + [InlineData(RequestMethods.RootsList)] +#pragma warning restore MCP9005 + [InlineData(RequestMethods.ElicitationCreate)] + [InlineData(RequestMethods.Initialize)] + [InlineData(RequestMethods.ToolsCall)] + [InlineData(RequestMethods.SubscriptionsListen)] + public async Task Validation_RejectsCoreMethodsBeforeTransportConnect(string coreMethod) + { + var transport = new TrackingClientTransport(); + var options = new McpClientOptions + { + RequestHandlers = + [ + new McpClientRequestHandler + { + Method = coreMethod, + Handler = (_, _) => new ValueTask((JsonNode?)null), + }, + ], + }; + + var createEx = await Assert.ThrowsAsync(() => + McpClient.CreateAsync(transport, options, cancellationToken: TestContext.Current.CancellationToken)); + Assert.Contains(coreMethod, createEx.Message); + Assert.Equal(0, transport.ConnectCount); + + var resumeOptions = new ResumeClientSessionOptions + { + ServerCapabilities = new(), + ServerInfo = new() { Name = "test", Version = "1.0" }, + }; + var resumeEx = await Assert.ThrowsAsync(() => + McpClient.ResumeSessionAsync(transport, resumeOptions, options, cancellationToken: TestContext.Current.CancellationToken)); + Assert.Contains(coreMethod, resumeEx.Message); + Assert.Equal(0, transport.ConnectCount); + } + + [Fact] + public async Task Validation_RejectsDuplicateAndMalformedHandlersBeforeTransportConnect() + { + var transport = new TrackingClientTransport(); + + // Duplicate method + var duplicateOptions = new McpClientOptions + { + RequestHandlers = + [ + new McpClientRequestHandler { Method = "com.example/dup", Handler = (_, _) => default }, + new McpClientRequestHandler { Method = "com.example/dup", Handler = (_, _) => default }, + ], + }; + var dupEx = await Assert.ThrowsAsync(() => + McpClient.CreateAsync(transport, duplicateOptions, cancellationToken: TestContext.Current.CancellationToken)); + Assert.Contains("com.example/dup", dupEx.Message); + Assert.Equal(0, transport.ConnectCount); + + // Null entry + var nullEntryOptions = new McpClientOptions { RequestHandlers = [null!] }; + await Assert.ThrowsAsync(() => + McpClient.CreateAsync(transport, nullEntryOptions, cancellationToken: TestContext.Current.CancellationToken)); + Assert.Equal(0, transport.ConnectCount); + + // Whitespace method + var blankMethodOptions = new McpClientOptions + { + RequestHandlers = [new McpClientRequestHandler { Method = " ", Handler = (_, _) => default }], + }; + await Assert.ThrowsAsync(() => + McpClient.CreateAsync(transport, blankMethodOptions, cancellationToken: TestContext.Current.CancellationToken)); + Assert.Equal(0, transport.ConnectCount); + + // Null handler delegate + var nullDelegateOptions = new McpClientOptions + { + RequestHandlers = [new McpClientRequestHandler { Method = "com.example/null", Handler = null! }], + }; + await Assert.ThrowsAsync(() => + McpClient.CreateAsync(transport, nullDelegateOptions, cancellationToken: TestContext.Current.CancellationToken)); + Assert.Equal(0, transport.ConnectCount); + } + + [Fact] + public async Task RequestContext_SettingNonRequestJsonRpcMessage_ThrowsArgumentException() + { + await using var client = await CreateMcpClientForServer(); + + var request = new JsonRpcRequest { Id = new RequestId(1), Method = "com.example/test" }; + var context = new McpClientRequestContext(client, request, null); + + Assert.Throws(() => context.JsonRpcMessage = new JsonRpcNotification { Method = "com.example/notify" }); + Assert.Throws(() => context.JsonRpcMessage = null!); + Assert.Same(request, context.JsonRpcRequest); + } + + private sealed record SearchParams(string Query); + private sealed record SearchResult(string[] Matches); + + [JsonSourceGenerationOptions(JsonSerializerDefaults.Web)] + [JsonSerializable(typeof(SearchParams))] + [JsonSerializable(typeof(SearchResult))] + private sealed partial class TestJsonContext : JsonSerializerContext; + + private sealed class TrackingClientTransport : IClientTransport + { + public int ConnectCount { get; private set; } + public string Name => "tracking"; + + public Task ConnectAsync(CancellationToken cancellationToken = default) + { + ConnectCount++; + throw new InvalidOperationException("ConnectAsync should not have been called."); + } + } +} diff --git a/tests/ModelContextProtocol.Tests/Configuration/McpServerBuilderExtensionsMessageFilterTests.cs b/tests/ModelContextProtocol.Tests/Configuration/McpServerBuilderExtensionsMessageFilterTests.cs index 45cf0379c..01e5d2095 100644 --- a/tests/ModelContextProtocol.Tests/Configuration/McpServerBuilderExtensionsMessageFilterTests.cs +++ b/tests/ModelContextProtocol.Tests/Configuration/McpServerBuilderExtensionsMessageFilterTests.cs @@ -836,6 +836,98 @@ public async Task AddIncomingMessageFilter_Items_Flow_Through_Multiple_Request_F Assert.Equal("modifiedByFilter1", observedValues[1]); } + [Fact] + public async Task AddIncomingMessageFilter_ThrowingOnClientResponse_FailsPendingServerRequest() + { + RequestId? serverPingId = null; + + McpServerBuilder + .WithMessageFilters(filters => + { + filters.AddOutgoingFilter(next => (context, cancellationToken) => + { + if (context.JsonRpcMessage is JsonRpcRequest { Method: RequestMethods.Ping } req) + { + serverPingId = req.Id; + } + + return next(context, cancellationToken); + }); + filters.AddIncomingFilter(next => (context, cancellationToken) => + { + if (context.JsonRpcMessage is JsonRpcResponse resp && resp.Id == serverPingId) + { + throw new InvalidOperationException("Rejected client response"); + } + + return next(context, cancellationToken); + }); + }) + .WithTools(); + + StartServer(); + + await using McpClient client = await CreateMcpClientForServer(new McpClientOptions + { + ProtocolVersion = "2025-11-25", + }); + + var ex = await Assert.ThrowsAsync(() => + Server.SendRequestAsync( + new JsonRpcRequest { Method = RequestMethods.Ping }, + TestContext.Current.CancellationToken)); + Assert.Equal("Rejected client response", ex.Message); + } + + [Fact] + public async Task AddIncomingMessageFilter_ThrowingAfterNext_DoesNotSendDuplicateErrorResponse() + { + int repliesSentForListTools = 0; + RequestId? listToolsId = null; + var postThrowReached = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + + McpServerBuilder + .WithMessageFilters(filters => + { + filters.AddIncomingFilter(next => async (context, cancellationToken) => + { + if (context.JsonRpcMessage is JsonRpcRequest { Method: RequestMethods.ToolsList } req) + { + listToolsId = req.Id; + await next(context, cancellationToken); + postThrowReached.TrySetResult(true); + throw new InvalidOperationException("Post-response failure"); + } + + await next(context, cancellationToken); + }); + filters.AddOutgoingFilter(next => (context, cancellationToken) => + { + if (context.JsonRpcMessage is JsonRpcMessageWithId msg && msg.Id == listToolsId) + { + Interlocked.Increment(ref repliesSentForListTools); + } + + return next(context, cancellationToken); + }); + }) + .WithTools(); + + StartServer(); + + await using McpClient client = await CreateMcpClientForServer(); + + var tools = await client.ListToolsAsync(cancellationToken: TestContext.Current.CancellationToken); + Assert.Single(tools); + + await postThrowReached.Task.WaitAsync(TestConstants.DefaultTimeout, TestContext.Current.CancellationToken); + + // Follow-up round-trip ensures any erroneous duplicate error would have been flushed. + await client.CallToolAsync("test_tool_method", cancellationToken: TestContext.Current.CancellationToken); + + Assert.Equal(1, repliesSentForListTools); + } + public sealed class TestTool { [McpServerTool]