Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
65 changes: 58 additions & 7 deletions docs/concepts/filters.md
Original file line number Diff line number Diff line change
@@ -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

Expand Down Expand Up @@ -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<McpClientMessageFilter>`) - 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<McpClientMessageFilter>`) - 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.

2 changes: 1 addition & 1 deletion docs/list-of-diagnostics.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. |

Expand Down
24 changes: 22 additions & 2 deletions src/ModelContextProtocol.Core/Client/McpClient.Methods.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,11 +44,21 @@ public static async Task<McpClient> 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);
Expand Down Expand Up @@ -117,10 +127,20 @@ public static async Task<McpClient> 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;
Expand Down
25 changes: 25 additions & 0 deletions src/ModelContextProtocol.Core/Client/McpClientFilters.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
namespace ModelContextProtocol.Client;

/// <summary>
/// Provides filter collections for MCP client pipelines.
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
public sealed class McpClientFilters
{
/// <summary>
/// Gets or sets the filters for incoming and outgoing JSON-RPC messages.
/// </summary>
/// <exception cref="ArgumentNullException">The value is <see langword="null"/>.</exception>
public McpClientMessageFilters Message
{
get => field ??= new();
set
{
Throw.IfNull(value);
field = value;
}
}
}
Loading
Loading