Conversation
WalkthroughThis change introduces global middleware support for the MCP server by allowing middleware to be configured and applied to all MCP server handlers. Middleware is defined in the configuration, composed, and executed after the lifecycle middleware. Tests and a sample middleware demonstrate the new functionality and verify its correct integration. Changes
Sequence Diagram(s)sequenceDiagram
participant Client
participant Router
participant MCPControllerRegister
participant LifecycleMiddleware
participant GlobalMiddleware
participant Handler
Client->>Router: HTTP Request (e.g., POST /mcp/tool/traceTest)
Router->>MCPControllerRegister: Route match
MCPControllerRegister->>LifecycleMiddleware: Process context
LifecycleMiddleware->>GlobalMiddleware: Apply global middlewares (e.g., tracelog)
GlobalMiddleware->>Handler: Invoke tool handler (traceTest)
Handler->>GlobalMiddleware: Return response
GlobalMiddleware->>LifecycleMiddleware: Return response
LifecycleMiddleware->>MCPControllerRegister: Return response
MCPControllerRegister->>Router: Return response
Router->>Client: Response (e.g., "hello middleware")
Possibly related PRs
Suggested reviewers
Poem
Warning There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure. 🔧 ESLint
plugin/controller/lib/impl/mcp/MCPServerHelper.tsOops! Something went wrong! :( ESLint: 8.57.1 ESLint couldn't find the plugin "eslint-plugin-eggache". (The package "eslint-plugin-eggache" was not found when loaded as a Node module from the directory "".) It's likely that the plugin isn't installed correctly. Try reinstalling by running the following: The plugin "eslint-plugin-eggache" was referenced from the config file in ".eslintrc » eslint-config-egg/typescript » ./index.js". If you still can't figure out the problem, please stop by https://eslint.org/chat/help to chat with the team. plugin/controller/test/fixtures/apps/mcp-app/app/controller/McpController.tsOops! Something went wrong! :( ESLint: 8.57.1 ESLint couldn't find the plugin "eslint-plugin-eggache". (The package "eslint-plugin-eggache" was not found when loaded as a Node module from the directory "".) It's likely that the plugin isn't installed correctly. Try reinstalling by running the following: The plugin "eslint-plugin-eggache" was referenced from the config file in ".eslintrc » eslint-config-egg/typescript » ./index.js". If you still can't figure out the problem, please stop by https://eslint.org/chat/help to chat with the team. plugin/controller/lib/impl/mcp/MCPControllerRegister.tsOops! Something went wrong! :( ESLint: 8.57.1 ESLint couldn't find the plugin "eslint-plugin-eggache". (The package "eslint-plugin-eggache" was not found when loaded as a Node module from the directory "".) It's likely that the plugin isn't installed correctly. Try reinstalling by running the following: The plugin "eslint-plugin-eggache" was referenced from the config file in ".eslintrc » eslint-config-egg/typescript » ./index.js". If you still can't figure out the problem, please stop by https://eslint.org/chat/help to chat with the team.
✨ Finishing Touches
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Summary of Changes
Hello @akitaSummer, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!
This pull request introduces a significant enhancement by adding support for global middleware within the Model Context Protocol (MCP) controllers. This feature allows developers to define and apply custom Koa-style middleware functions that will execute for all incoming MCP requests, providing a powerful and flexible way to manage common concerns such as request tracing, authentication, or data manipulation across all MCP endpoints.
Highlights
- Global Middleware for MCP: Implemented a new mechanism to define and apply global Koa-style middleware to all Model Context Protocol (MCP) requests, allowing for centralized handling of cross-cutting concerns like request tracing or authentication.
- Configurable Middleware Loading: Enabled configuration of global MCP middleware via the
app.config.mcp.middlewarearray. Middleware names specified here are dynamically loaded, initialized with options, and composed usingkoa-compose. - Integrated Request Processing: Ensured the new global middleware is seamlessly integrated into the existing MCP request handling flow, applying it before the
teggCtxLifecycleMiddlewarefor various entry points including stateless transport, stream server, and SSE message processing. - Enhanced Test Coverage: Added a new test middleware (
tracelog.js) and a corresponding test MCP tool (traceTest) to thoroughly verify the functionality and correct application of the global middleware, demonstrating its ability to modify request context (e.g., headers).
Using Gemini Code Assist
The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.
Invoking Gemini
You can request assistance from Gemini at any point in your pull request via creating an issue comment (i.e. comment on the pull request page) using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands.
| Feature | Command | Description |
|---|---|---|
| Code Review | /gemini review |
Performs a code review for the current pull request in its current state. |
| Pull Request Summary | /gemini summary |
Provides a summary of the current pull request in its current state. |
| Comment | @gemini-code-assist | Responds in comments when explicitly tagged, both in issue comments and review comments. |
| Help | /gemini help |
Displays a list of available commands. |
Customization
To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.
Limitations & Feedback
Gemini Code Assist is currently in preview and may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments to provide feedback.
You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.
Footnotes
-
Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution. ↩
There was a problem hiding this comment.
Code Review
This pull request introduces a feature to add global middleware for MCP controllers. The implementation correctly loads middleware from the configuration and applies it to the different MCP transport handlers. The feature is well-tested across different scenarios, including cluster mode. My review focuses on improving code maintainability by addressing code duplication and the use of @ts-ignore to suppress type errors.
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (5)
plugin/controller/test/fixtures/apps/mcp-app/app/middleware/tracelog.js (1)
1-1: Remove redundant 'use strict' directive.As indicated by static analysis, the 'use strict' directive is redundant in JavaScript modules where strict mode is automatically enabled.
-'use strict';plugin/controller/lib/impl/mcp/MCPControllerRegister.ts (4)
166-169: Consider extracting the middleware composition logic.The middleware composition pattern is repeated across multiple methods. Consider extracting this into a helper method to reduce code duplication.
+ private composeWithGlobalMiddleware(baseMiddleware: any) { + return this.globalMiddlewares ? compose([baseMiddleware, this.globalMiddlewares]) : baseMiddleware; + }Then use it consistently:
- let mw = self.app.middleware.teggCtxLifecycleMiddleware(); - if (self.globalMiddlewares) { - mw = compose([ mw, self.globalMiddlewares ]); - } + const mw = self.composeWithGlobalMiddleware(self.app.middleware.teggCtxLifecycleMiddleware());
227-230: Address static analysis hint: unnecessarythisaliasing.The static analysis tool correctly identifies that the
selfalias is unnecessary in this context since arrow functions inheritthisfrom their enclosing scope.- const self = this; - let mw = self.app.middleware.teggCtxLifecycleMiddleware(); - if (self.globalMiddlewares) { - mw = compose([ mw, self.globalMiddlewares ]); + let mw = this.app.middleware.teggCtxLifecycleMiddleware(); + if (this.globalMiddlewares) { + mw = compose([ mw, this.globalMiddlewares ]); }
389-392: Address static analysis hint: unnecessarythisaliasing.Similar to the previous case, the
selfalias is unnecessary here.- const self = this; - let mw = this.app.middleware.teggCtxLifecycleMiddleware(); - if (self.globalMiddlewares) { - mw = compose([ mw, self.globalMiddlewares ]); + let mw = this.app.middleware.teggCtxLifecycleMiddleware(); + if (this.globalMiddlewares) { + mw = compose([ mw, this.globalMiddlewares ]); }
452-455: Inconsistent formatting in middleware composition.The middleware composition logic here has inconsistent formatting compared to other instances.
- - let mw = self.app.middleware.teggCtxLifecycleMiddleware(); - if (self.globalMiddlewares) { - mw = compose([ mw, self.globalMiddlewares ]); - } + let mw = self.app.middleware.teggCtxLifecycleMiddleware(); + if (self.globalMiddlewares) { + mw = compose([ mw, self.globalMiddlewares ]); + }
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (6)
plugin/controller/lib/impl/mcp/MCPControllerRegister.ts(8 hunks)plugin/controller/test/fixtures/apps/mcp-app/app/controller/McpController.ts(2 hunks)plugin/controller/test/fixtures/apps/mcp-app/app/middleware/tracelog.js(1 hunks)plugin/controller/test/fixtures/apps/mcp-app/config/config.default.js(1 hunks)plugin/controller/test/mcp/mcp.test.ts(6 hunks)plugin/controller/test/mcp/mcpCluster.test.ts(6 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
plugin/controller/test/fixtures/apps/mcp-app/app/controller/McpController.ts (3)
core/controller-decorator/src/decorator/mcp/MCPTool.ts (1)
MCPTool(10-33)core/controller-decorator/src/decorator/mcp/Extra.ts (1)
Extra(6-16)core/types/controller-decorator/MCPToolParams.ts (2)
ToolExtra(6-6)MCPToolResponse(8-8)
plugin/controller/lib/impl/mcp/MCPControllerRegister.ts (1)
core/types/controller-decorator/model/types.ts (1)
EggContext(3-3)
🪛 Biome (1.9.4)
plugin/controller/test/fixtures/apps/mcp-app/app/middleware/tracelog.js
[error] 1-1: Redundant use strict directive.
The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.
(lint/suspicious/noRedundantUseStrict)
plugin/controller/lib/impl/mcp/MCPControllerRegister.ts
[error] 228-228: This aliasing of this is unnecessary.
Arrow functions inherits this from their enclosing scope.
Safe fix: Use this instead of an alias.
(lint/complexity/noUselessThisAlias)
[error] 390-390: This aliasing of this is unnecessary.
Arrow functions inherits this from their enclosing scope.
Safe fix: Use this instead of an alias.
(lint/complexity/noUselessThisAlias)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (9)
- GitHub Check: Analyze (javascript)
- GitHub Check: Runner-ubuntu (20)
- GitHub Check: Analyze (typescript)
- GitHub Check: Runner-ubuntu (22)
- GitHub Check: Runner-ubuntu (18)
- GitHub Check: Runner-macos (18)
- GitHub Check: Runner-ubuntu (16)
- GitHub Check: Runner-macos (20)
- GitHub Check: Runner-macos (16)
🔇 Additional comments (22)
plugin/controller/test/fixtures/apps/mcp-app/config/config.default.js (1)
17-19: LGTM! Middleware configuration correctly added.The middleware configuration follows the expected pattern for registering global middleware in the MCP system.
plugin/controller/test/fixtures/apps/mcp-app/app/middleware/tracelog.js (1)
3-8: LGTM! Middleware implementation is correct.The middleware properly sets the trace header and calls the next middleware in the chain. The implementation follows standard Express.js middleware patterns.
plugin/controller/test/fixtures/apps/mcp-app/app/controller/McpController.ts (2)
16-17: LGTM! Imports correctly added.The Extra and ToolExtra imports are needed for the new traceTest method implementation.
95-105: LGTM! Method implementation correctly demonstrates middleware integration.The traceTest method properly uses the @extra() decorator to access request information and returns the trace header value set by the middleware. This provides a good test case for verifying global middleware functionality.
plugin/controller/test/mcp/mcpCluster.test.ts (6)
146-149: LGTM! Test coverage for traceTest tool added.The test correctly includes the new traceTest tool in the expected tools list for SSE client.
169-175: LGTM! Integration test for middleware functionality.The test correctly verifies that the traceTest tool returns "hello middleware", confirming that the global middleware is properly setting the trace header.
284-287: LGTM! Consistent test coverage for streamable client.The test maintains consistency by including traceTest in the tools list for the streamable HTTP client.
307-313: LGTM! Middleware verification for streamable client.The test confirms middleware functionality works correctly with the streamable HTTP client transport.
426-429: LGTM! Test coverage for stateless streamable client.The test includes traceTest for the stateless streamable client, ensuring comprehensive coverage across all client types.
449-455: LGTM! Complete middleware verification across all client types.The test confirms that the global middleware functionality works correctly with the stateless streamable client, completing the test coverage for all transport mechanisms.
plugin/controller/test/mcp/mcp.test.ts (6)
136-139: LGTM! Test coverage for traceTest tool added.The test correctly includes the new traceTest tool in the expected tools list for SSE client in the standard MCP test suite.
160-166: LGTM! Integration test for middleware functionality.The test correctly verifies that the traceTest tool returns "hello middleware", confirming global middleware works in the standard MCP environment.
275-278: LGTM! Consistent test coverage for streamable client.The test maintains consistency by including traceTest in the tools list for the streamable HTTP client in the standard environment.
299-305: LGTM! Middleware verification for streamable client.The test confirms middleware functionality works correctly with the streamable HTTP client transport in the standard environment.
418-421: LGTM! Test coverage for stateless streamable client.The test includes traceTest for the stateless streamable client, ensuring comprehensive coverage in the standard environment.
442-448: LGTM! Complete middleware verification across all client types.The test confirms that the global middleware functionality works correctly with the stateless streamable client in the standard environment, completing comprehensive test coverage.
plugin/controller/lib/impl/mcp/MCPControllerRegister.ts (6)
14-14: LGTM: Type import added correctly.The
EggContexttype is properly imported and used consistently throughout the middleware compositions.
25-25: LGTM: Compose utility imported.The
koa-composeimport is necessary for middleware composition functionality.
95-95: LGTM: Property declaration is well-typed.The
globalMiddlewaresproperty is properly typed ascompose.ComposedMiddleware<EggContext>.
496-496: LGTM: Middleware correctly applied to router.The middleware is properly passed to the router's post method for the SSE message path.
501-519: Well-implemented global middleware initialization.The
getGlobalMiddleware()method correctly:
- Reads middleware names from configuration
- Validates middleware existence
- Instantiates middleware with their options
- Composes them into a single middleware chain
The error handling for missing middleware is appropriate.
523-523: LGTM: Proper initialization timing.The
getGlobalMiddleware()call is correctly placed before initializing the MCP server helpers, ensuring global middleware is ready before server initialization.
197928a to
176bf20
Compare
There was a problem hiding this comment.
Actionable comments posted: 0
♻️ Duplicate comments (2)
plugin/controller/lib/impl/mcp/MCPControllerRegister.ts (2)
166-169: Address code duplication across middleware composition points.This middleware composition logic is duplicated in several places within this file (e.g.,
mcpStreamServerIniton line 227,sseCtxStorageRunon line 389, andmcpServerRegisteron line 452).To improve maintainability and avoid future inconsistencies, consider extracting this logic into a private helper method.
Example:
private getComposedMiddleware(): compose.ComposedMiddleware<EggContext> { const teggMw = this.app.middleware.teggCtxLifecycleMiddleware(); if (this.globalMiddlewares) { return compose([ teggMw, this.globalMiddlewares ]); } return teggMw; }You could then call
const mw = this.getComposedMiddleware();at each of the current locations.
501-515: Improve type safety in middleware loading.The current implementation uses type assertions that suppress TypeScript's type checking, which can hide potential bugs and makes the code harder to maintain.
Consider this more type-safe approach:
getGlobalMiddleware() { const middlewareNames = this.app.config.mcp.middleware || []; const middlewares: compose.Middleware<EggContext>[] = []; for (const name of middlewareNames) { - const middlewareFactory = (this.app as unknown as any).middlewares[name]; + const middlewareFactory = (this.app.middlewares as any)[name]; if (!middlewareFactory) { throw new TypeError(`Middleware ${name} not found`); } - const options = (this.app.config as any)[name] || {}; + const options = (this.app.config as any)[name] || {}; const mw = middlewareFactory(options, this.app); (mw as any)._name = name; middlewares.push(mw); } this.globalMiddlewares = compose(middlewares); }
🧹 Nitpick comments (1)
plugin/controller/test/fixtures/apps/mcp-app/app/middleware/tracelog.js (1)
1-1: Remove redundant 'use strict' directive.ES modules are automatically in strict mode, making this directive unnecessary.
-'use strict'; -
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (8)
plugin/controller/lib/impl/mcp/MCPControllerRegister.ts(8 hunks)plugin/controller/lib/impl/mcp/MCPServerHelper.ts(1 hunks)plugin/controller/test/fixtures/apps/mcp-app/app/controller/McpController.ts(2 hunks)plugin/controller/test/fixtures/apps/mcp-app/app/middleware/tracelog.js(1 hunks)plugin/controller/test/fixtures/apps/mcp-app/config/config.default.js(1 hunks)plugin/controller/test/mcp/mcp.test.ts(6 hunks)plugin/controller/test/mcp/mcpCluster.test.ts(6 hunks)plugin/mcp-proxy/index.ts(2 hunks)
🚧 Files skipped from review as they are similar to previous changes (4)
- plugin/controller/test/fixtures/apps/mcp-app/config/config.default.js
- plugin/controller/test/mcp/mcpCluster.test.ts
- plugin/controller/test/mcp/mcp.test.ts
- plugin/controller/test/fixtures/apps/mcp-app/app/controller/McpController.ts
🧰 Additional context used
🧬 Code Graph Analysis (1)
plugin/controller/lib/impl/mcp/MCPControllerRegister.ts (1)
core/types/controller-decorator/model/types.ts (1)
EggContext(3-3)
🪛 Biome (1.9.4)
plugin/controller/lib/impl/mcp/MCPControllerRegister.ts
[error] 228-228: This aliasing of this is unnecessary.
Arrow functions inherits this from their enclosing scope.
Safe fix: Use this instead of an alias.
(lint/complexity/noUselessThisAlias)
[error] 390-390: This aliasing of this is unnecessary.
Arrow functions inherits this from their enclosing scope.
Safe fix: Use this instead of an alias.
(lint/complexity/noUselessThisAlias)
plugin/controller/test/fixtures/apps/mcp-app/app/middleware/tracelog.js
[error] 1-1: Redundant use strict directive.
The entire contents of JavaScript modules are automatically in strict mode, with no statement needed to initiate it.
Safe fix: Remove the redundant use strict directive.
(lint/suspicious/noRedundantUseStrict)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (9)
- GitHub Check: Runner-ubuntu (22)
- GitHub Check: Runner-ubuntu (20)
- GitHub Check: Runner-macos (16)
- GitHub Check: Runner-ubuntu (16)
- GitHub Check: Runner-macos (20)
- GitHub Check: Runner-ubuntu (18)
- GitHub Check: Analyze (typescript)
- GitHub Check: Analyze (javascript)
- GitHub Check: Runner-macos (18)
🔇 Additional comments (8)
plugin/controller/test/fixtures/apps/mcp-app/app/middleware/tracelog.js (1)
3-8: LGTM: Clean middleware implementation.The middleware correctly sets the trace header and calls next() to continue the chain. The implementation follows standard Koa middleware patterns.
plugin/mcp-proxy/index.ts (2)
17-17: LGTM: Appropriate import for middleware composition.The
koa-composeimport is correctly added to support the new middleware composition functionality.
122-125: LGTM: Correct middleware composition logic.The implementation properly composes the lifecycle middleware with global middlewares when available. The order ensures lifecycle middleware runs first, followed by global middlewares.
plugin/controller/lib/impl/mcp/MCPServerHelper.ts (1)
53-59: LGTM: Improved resource registration logic clarity.The refactoring makes the precedence between
uriandtemplateexplicit, improving code readability while maintaining the same functional behavior.plugin/controller/lib/impl/mcp/MCPControllerRegister.ts (4)
14-14: LGTM: Appropriate type import.Adding
EggContextimport supports the new middleware typing requirements.
25-25: LGTM: Required import for middleware composition.The
koa-composeimport is necessary for the new global middleware functionality.
95-95: LGTM: Appropriate property for global middleware chain.The
globalMiddlewaresproperty correctly stores the composed middleware chain with proper typing.
519-519: LGTM: Global middleware initialization in correct location.Calling
getGlobalMiddleware()during registration ensures the middleware chain is prepared before server initialization.
killagu
left a comment
There was a problem hiding this comment.
配置里会新增一个 mcpMiddlewares 么?
@killagu mcp: {
middleware: [
'tracelog',
],
}, |
Checklist
npm testpassesAffected core subsystem(s)
Description of change
Summary by CodeRabbit
New Features
Tests