Description
SEP-3371 says SDKs MUST let applications and extensions wrap JSON-RPC requests, responses and notifications, core and custom, in both directions. We only have PSR-15 middleware on the HTTP transport. #777 covers registration and custom methods, this is the design for middleware, before any code.
Other SDKs
| SDK | Status | Requests / notifications | Directions | Link |
|---|---|---|---|---|
| TypeScript | merged, @experimental, not released |
requests only, per method name | receiving | typescript-sdk#2820 |
| Python | merged, provisional | both | receiving, server only | middleware.md |
| C# | merged | both, plus typed request filters | incoming and outgoing | filters.md |
| Go | merged | both | sending and receiving, client and server | shared.go |
| PHP | nothing at the JSON-RPC level | PSR-15 on HTTP only |
The SEP is still In-Review. Nobody fully meets it yet, Go and C# are the closest.
Proposal
namespace Mcp\Server\Middleware;
interface RequestMiddlewareInterface
{
public function processRequest(Request $request, SessionInterface $session, RequestHandlerInterface $next): Response|Error;
}
interface NotificationMiddlewareInterface
{
public function processNotification(Notification $notification, SessionInterface $session, NotificationHandlerInterface $next): void;
}$next is the handler interface we already have. Return a Response or an Error without calling $next to answer early, skip $next in processNotification to drop a notification. Cleanup is try/finally.
The client mirrors them in Mcp\Client\Middleware, with a read-only Context (protocolVersion, serverCapabilities, serverInfo, cancellation) in place of the session.
Server::builder()
->addReceivingMiddleware($audit) // outermost
->enableExtension(new SearchExtension()) // its middleware, in the order the extension declares
->addReceivingMiddleware($redact) // innermost, next to the handler
->addSendingMiddleware($stampTrace); // separate list for outgoing messagesOrder is the builder call order, the first registered is the outermost. An extension can't reorder or remove what others registered.
- The receiving chain runs after parsing and validation, before the handler lookup. Results pass back before the SDK checks and serialization, so a middleware can't bypass them. It replaces the lookup loop in
StatelessProtocoland the handler call inProtocol. The SEP only asks for 2026-07-28, I think we need both because a client could skip a redaction layer by offering an older revision. - The sending chain wraps what handlers send through
ClientGatewayand the notifications sent outside of a request. - Streams: the chain runs on the request fiber, with one
processNotificationcall per notification when it is produced. Nothing is buffered. - Worker mode: middleware instances live as long as the worker, so no per-request state in properties. Use local variables, the session or a
WeakMapkeyed by the request. _meta: requests already havegetMeta()/withMeta(), we add them toNotificationandResponse. Unknown keys are kept. The SDK reads its reserved keys before the chain and writes its own after it.- No typed per-method middleware (a MAY in the SEP),
$request instanceof CallToolRequestdoes the job.
Decisions
- D1 Shape. Synchronous onion like PSR-15, as above. The alternative is generators like the SEP pseudocode, where a forgotten
yield fromonly fails at runtime. - D2
elicit()on 2026-07-28. An unansweredelicit()abandons the handler fiber, so the code after$next->handle()never sees the ask. I'd run the handler in an inner fiber and return the ask through the chain. I only checked this with a throwaway script, so a small draft PR will try it throughHandlerFibersand a real event loop first. The alternative is to keep one fiber and document that this result skips the code after$next. - D3 Result
_meta. Only 4 of the 15 result classes have it. I'd addResponse::getMeta()/withMeta()and apply the change when we serialize. The alternative is a$metaproperty on the 11 others. - D4 Extensions. Add
getReceivingMiddleware()andgetSendingMiddleware()toServerExtensionInterfaceandClientExtensionInterface. It breaks BC, but [Server][Client] Add SEP-3371 extension registration and custom methods #777 already does forgetNotificationHandlers()and we keep one interface per side. The alternative is an optionalMiddlewareProviderInterface, no break but one more interface. - D5 Client sending chain. Per wire exchange matches the SEP text and shows every MRTR round, but the retries are built as arrays and
Requestwould need to carryinputResponsesandrequestState. Per logical call is simpler and hides the rounds. Not decided.
Plan
- Draft PR: inner fiber spike through
HandlerFibersand a real event loop (D2) -
_metaaccessors onNotificationandResponse - Server receiving request chain: interfaces,
addReceivingMiddleware(), both protocols - Inner fiber for
elicit()on 2026-07-28 (D2) - Server notifications and sending chain,
addSendingMiddleware() - Extensions: the two getters, group order,
docs/advanced/middleware.md - Client:
Mcp\Client\Middleware, builder methods - Optional:
subscriptions/listenas a typed request through the chain, named insertion points
Open questions
- On 2026-07-28 an inbound notification is acknowledged without any dispatch, so the receiving notification chain has nothing to wrap there. Do we fix that here or in its own issue?
- Does
subscriptions/listenitself need to pass the request chain, or is one call per notification enough? - At runtime we'd only check that an early response has the id of the request. Do we also check that the request class didn't change before the handler?
ping @chr-hertel, you raised the gap on the SEP, what's your take on D1 to D5?
Activity