Skip to content

Conversation

@ahammednibras8
Copy link

PR: Middleware Support for McpServer (Fixes #1238)

🚀 Summary

This PR implements a request-lifecycle middleware system for McpServer,
enabling cross-cutting concerns (logging, authentication, error handling) to be
applied consistently across all Tools, Resources, and Prompts.

It introduces a strictly ordered "Onion Model" execution pipeline ensuring:

  1. Zero-Behavior Default: No overhead/changes if no middleware is
    registered.
  2. Type Safety: Strictly typed context and zero any usage.
  3. Safety: Lifecycle freezing (cannot add middleware after start) and
    double-invocation guards.

🛠️ Key Changes

  • Core: Added private _executeRequest pipeline to McpServer.
  • API: Added public use(middleware: McpMiddleware) method.
  • Refactor: Wrapped setToolRequestHandlers, setResourceRequestHandlers,
    and setPromptRequestHandlers to utilize the pipeline.

🧪 Verification

  • Automated Tests: Added packages/server/test/server/mcpServer.test.ts
    covering:
    • Execution Order (FIFO)
    • Short-circuiting
    • Error propagation (Upstream & Downstream)
    • Async timing & Double-next safety
  • Manual Verification: Verified real-world "Logging + Auth" scenario in
    packages/server/examples/manual_verification.ts.
  • Regressions: pnpm test (348 passing) and pnpm typecheck passed.

📝 Example Usage

server.use(async (context, next) => {
    console.log(`[${Date.now()}] ${context.request.method}`);
    try {
        await next(); // Execute next middleware/handler
    } catch (err) {
        console.error("Error intercepted:", err);
        throw err;
    }
});

@ahammednibras8 ahammednibras8 requested a review from a team as a code owner December 28, 2025 14:01
@changeset-bot
Copy link

changeset-bot bot commented Dec 28, 2025

⚠️ No Changeset found

Latest commit: 7b88bd1

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@pkg-pr-new
Copy link

pkg-pr-new bot commented Dec 28, 2025

Open in StackBlitz

npm i https://pkg.pr.new/modelcontextprotocol/typescript-sdk/@modelcontextprotocol/client@1344
npm i https://pkg.pr.new/modelcontextprotocol/typescript-sdk/@modelcontextprotocol/server@1344

commit: 7b88bd1

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.

Feature Request: Middleware support for McpServer

1 participant