Skip to content

Protocol-level middleware (SEP-3371) #778

Backlog

Description

@soyuka

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 messages

Order 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 StatelessProtocol and the handler call in Protocol. 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 ClientGateway and the notifications sent outside of a request.
  • Streams: the chain runs on the request fiber, with one processNotification call 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 WeakMap keyed by the request.
  • _meta: requests already have getMeta()/withMeta(), we add them to Notification and Response. 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 CallToolRequest does the job.

Decisions

  • D1 Shape. Synchronous onion like PSR-15, as above. The alternative is generators like the SEP pseudocode, where a forgotten yield from only fails at runtime.
  • D2 elicit() on 2026-07-28. An unanswered elicit() 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 through HandlerFibers and 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 add Response::getMeta()/withMeta() and apply the change when we serialize. The alternative is a $meta property on the 11 others.
  • D4 Extensions. Add getReceivingMiddleware() and getSendingMiddleware() to ServerExtensionInterface and ClientExtensionInterface. It breaks BC, but [Server][Client] Add SEP-3371 extension registration and custom methods #777 already does for getNotificationHandlers() and we keep one interface per side. The alternative is an optional MiddlewareProviderInterface, 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 Request would need to carry inputResponses and requestState. Per logical call is simpler and hides the rounds. Not decided.

Plan

  • Draft PR: inner fiber spike through HandlerFibers and a real event loop (D2)
  • _meta accessors on Notification and Response
  • 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/listen as 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/listen itself 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

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions