Skip to content

Add client JSON-RPC message filters and custom request handlers - #2055

Open
PederHP wants to merge 1 commit into
modelcontextprotocol:mainfrom
PederHP:feat/client-message-filters-and-custom-handlers
Open

PederHP wants to merge 1 commit into
modelcontextprotocol:mainfrom
PederHP:feat/client-message-filters-and-custom-handlers

Conversation

@PederHP

@PederHP PederHP commented Nov 29, 2026

Copy link
Copy Markdown
Member

Part of #2051 (addresses two of the SEP-3371 extensibility gaps for McpClient).

Summary

1. Client JSON-RPC message filters (stable)

Adds incoming and outgoing JSON-RPC message filtering on McpClientOptions.Filters.Message, mirroring the server-side McpMessageFilters / MessageContext middleware pattern:

  • McpClientFilters / McpClientMessageFilters (McpClientOptions.Filters.Message.IncomingFilters & OutgoingFilters)
  • McpClientMessageFilter / McpClientMessageHandler delegates
  • McpClientMessageContext exposing Client, JsonRpcMessage (replacing it with a context-less message preserves the prior JsonRpcMessageContext, including Items and transport metadata), and per-message Items
  • Filters are validated and snapshotted before IClientTransport.ConnectAsync in both McpClient.CreateAsync and McpClient.ResumeSessionAsync, and composed once per session
  • MRTR input_required retries clone JsonRpcMessageContext with fresh per-attempt Items (preserving pre-filter entries such as ToolContextKey)
  • Updated docs/concepts/filters.md with client message filter usage, handshake caveats (ServerInfo / ServerCapabilities are unavailable during server/discover / initialize), and suppression/error semantics

2. Client custom request handlers ([Experimental(MCPEXP002)])

Adds custom server-to-client request handler registration on McpClientOptions.RequestHandlers for extension methods:

  • McpClientRequestHandler (raw JsonNode? handler + AOT-friendly generic Create<TParams, TResult> overloads accepting JsonTypeInfo<T> or JsonSerializerOptions)
  • McpClientRequestContext<TParams> (derives from McpClientMessageContext, shares Items with incoming message filters, and enforces JsonRpcRequest on JsonRpcMessage)
  • Rejects reserved core MCP methods, duplicate methods, null/empty entries, and already-registered built-in handlers before transport connect
  • Updated docs/list-of-diagnostics.md for MCPEXP002

3. Shared McpSessionHandler pipeline improvements (affects both client and server)

Because McpClient and McpServer share McpSessionHandler, this PR also includes three shared pipeline improvements with both client- and server-side tests:

  • Single filter-pipeline composition per session: Incoming and outgoing filter pipelines are composed once in the McpSessionHandler constructor rather than rebuilt per message, so filter factory closures retain state across messages and null-returning factories fail at construction.
  • No hanging pending requests on filter errors or suppression: When an incoming message filter throws on or suppresses a JsonRpcResponse/JsonRpcError matching a pending request, or when an outgoing filter suppresses a JsonRpcRequest without sending it, the awaiting caller now fails immediately (with the filter's exception or InvalidOperationException) instead of waiting until cancellation. Previously, incoming filter exceptions on responses were only logged.
  • No duplicate error replies after next throws: Tracks per-request ResponseSent state so an incoming filter throwing after next (or after sending its own response) does not send a second JsonRpcError with the same request ID.

Testing

  • Added tests/ModelContextProtocol.Tests/Client/McpClientMessageFilterTests.cs
  • Added tests/ModelContextProtocol.Tests/Client/McpClientRequestHandlerTests.cs
  • Added server-side tests for the shared McpSessionHandler changes in tests/ModelContextProtocol.Tests/Configuration/McpServerBuilderExtensionsMessageFilterTests.cs
  • Verified locally:
    • dotnet build across all projects and target frameworks (0 warnings, 0 errors)
    • Targeted filter & handler tests across net8.0, net9.0 (reflection-disabled/AOT), and net10.0: 63/63 passed on each TFM
    • ModelContextProtocol.Tests (net10.0, non-manual): 3,717/3,717 passed
    • ModelContextProtocol.AspNetCore.Tests (net10.0, non-manual): 754/754 passed
    • dotnet pack src/ModelContextProtocol.Core/ModelContextProtocol.Core.csproj -c Release (ApiCompat): succeeded

Note

This pull request description and code were generated with assistance from GitHub Copilot.

Adds two SEP-3371 extensibility capabilities to McpClient:

1. Client JSON-RPC message filters (stable):
   - McpClientFilters, McpClientMessageFilters, McpClientMessageFilter,
     McpClientMessageHandler, and McpClientMessageContext on
     McpClientOptions.Filters.Message (IncomingFilters / OutgoingFilters).
   - Intercepts all incoming and outgoing JSON-RPC messages in deterministic
     registration order, sharing per-message state via Items and preserving
     JsonRpcMessage.Context when replacing JsonRpcMessage with a context-less
     message.
   - Validates and snapshots filters before transport connect and composes
     filter pipelines once per session in McpSessionHandler.
   - Isolates per-attempt Items across MRTR input_required retries.

2. Client custom request handlers ([Experimental(MCPEXP002)]):
   - McpClientRequestHandler and McpClientRequestContext<TParams> on
     McpClientOptions.RequestHandlers for server-initiated extension requests.
   - Validates against reserved core methods, duplicate registrations, and
     already-registered built-in handlers before transport connect.

3. Shared McpSessionHandler pipeline improvements (client and server):
   - Composes incoming/outgoing message filter pipelines once at construction.
   - Fails pending requests immediately when an incoming filter throws on or
     suppresses a response/error, or when an outgoing filter suppresses a
     request without sending it.
   - Prevents sending a duplicate JSON-RPC error reply if an incoming filter
     throws after a response has already been sent for that request.

Refs modelcontextprotocol#2051

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant