Middleware Support for McpServer (Fixes #1238)#1345
Middleware Support for McpServer (Fixes #1238)#1345ahammednibras8 wants to merge 22 commits intomodelcontextprotocol:mainfrom
Conversation
…ial request processing
…, and error handling
…authentication, and activity aggregation
…d tool handler error propagation
… once and adding a verification test
… middleware timing
|
commit: |
|
Thanks for the thorough implementation. I'm not sure a middleware engine belongs in the SDK though. The design goal is a thin protocol layer rather than an application framework. For cross-cutting concerns like auth or logging, handler composition covers most cases: const withAuth = (handler) => async (args, ctx) => {
if (!ctx.http?.authInfo) throw new Error('Unauthorized');
return handler(args, ctx);
};
const withLogging = (handler) => async (args, ctx) => {
console.log('calling', ctx.mcpReq.method);
return handler(args, ctx);
};
server.registerTool('my-tool', {...}, withAuth(withLogging(myHandler)));HTTP framework middleware (Express, Hono, Fastify) also handles transport-level concerns. Closing, but let's continue the discussion in #1238 if there's a case this pattern doesn't cover. |
This PR implements a request-lifecycle middleware system for
McpServer(fixes#1238), enabling cross-cutting concerns (logging, authentication, error
handling) to be applied consistently across all Tools, Resources, and Prompts
using a standard "Onion Model".
Motivation and Context
Currently, developers must manually wrap every single tool handler to add logic
like logging or auth checks. This is repetitive and prone to security errors
(forgetting one handler).
This change introduces
server.use(), allowing centralized middlewareregistration that applies to the entire server lifecycle. It solves the need for
reliable, cross-cutting logic execution without boilerplate.
How Has This Been Tested?
packages/server/test/server/mcpServer.test.tscovering:
real-time logging middleware.
pnpm testpassed (348 tests) andpnpm typecheckpassed(strict typing).
Breaking Changes
No. This is a strictly additive change.
_executeRequestpath is optimized to have negligible overheadif no middleware is registered.
Types of changes
change)
Checklist
Additional context
Design Decision:
server.use()freezes the middleware stack upon serverconnection (start). This prevents race conditions where middleware might be
added mid-request, ensuring deterministic behavior.
Example Usage: