8000 fix: sse new ctx by akitaSummer · Pull Request #323 · eggjs/tegg · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

fix: sse new ctx 8000 #323

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
May 27, 2025
Merged

fix: sse new ctx #323

merged 2 commits into from
May 27, 2025

Conversation

akitaSummer
Copy link
Contributor
@akitaSummer akitaSummer commented May 27, 2025
Checklist
  • npm test passes
  • tests and/or benchmarks are included
  • documentation is changed or added
  • commit message follows commit guidelines
Affected core subsystem(s)
Description of change

Summary by CodeRabbit

  • New Features
    • Introduced a plugin system for controller hooks, allowing user information to be injected into request contexts based on authorization headers.
    • Added a new tool, "echoUser", which greets the authenticated user.
  • Bug Fixes
    • Improved request header handling for Server-Sent Events to ensure all original headers are included.
  • Tests
    • Enhanced tests to cover authentication scenarios and verify the new "echoUser" tool functionality.
  • Chores
    • Added configuration and setup for the new hook plugin.

Copy link
coderabbitai bot commented May 27, 2025

Walkthrough

This update introduces a controller hook system for the MCP controller by modifying the SSE context handling to invoke registered preHandle hooks with the request context. It also adds a sample hook plugin that injects user information from authorization headers, updates test controllers and configurations, and extends tests to verify user context propagation and the new hook functionality.

Changes

File(s) Change Summary
plugin/controller/lib/impl/mcp/MCPControllerRegister.ts Modified SSE context to include all original headers and sequentially invoke registered hooks' preHandle.
plugin/controller/test/fixtures/apps/mcp-app/app/controller/McpController.ts Added injected user property and new echoUser tool method to greet the user.
plugin/controller/test/fixtures/apps/mcp-app/config/plugin.js Added configuration to enable the new hookPlugin.
plugin/controller/test/fixtures/apps/mcp-app/hook-plugin/app.ts Introduced ControllerAppBootHook to register a controller hook during app boot.
plugin/controller/test/fixtures/apps/mcp-app/hook-plugin/lib/MCPControllerHook.ts Added hook factory that injects user info from authorization headers into context via multiple lifecycle hooks.
plugin/controller/test/fixtures/apps/mcp-app/hook-plugin/package.json New package manifest for the hook plugin.
plugin/controller/test/mcp/mcp.test.ts
plugin/controller/test/mcp/mcpCluster.test.ts
Enhanced tests to use authProvider, verify user context, and test the new echoUser tool response.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant MCPControllerRegister
    participant HookPlugin
    participant Controller

    Client->>MCPControllerRegister: Send SSE request
    MCPControllerRegister->>MCPControllerRegister: Create new context with all headers
    MCPControllerRegister->>HookPlugin: Call preHandle(ctx) for each registered hook
    HookPlugin->>MCPControllerRegister: (Inject user info into ctx)
    MCPControllerRegister->>Controller: Pass context to middleware and handler
    Controller->>Client: Respond (e.g., echoUser greets user)
Loading

Possibly related PRs

  • fix: mcp context proto #318: Also modifies the sseCtxStorageRun method in MCPControllerRegister, but focuses on context prototype initialization and request promise tracking for SSE transports.

Suggested reviewers

  • killagu

Poem

A hop and a skip, a header or two,
Now hooks can greet users, as rabbits would do!
With context and care, the plugins awake,
And "hello akita" is what the tests make.
In the garden of code, new features take root—
This bunny approves, with a happy salute! 🐇✨

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

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

plugin/mcp-proxy/index.ts

Oops! 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:

npm install eslint-plugin-eggache@latest --save-dev

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
  • 📝 Generate Docstrings

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.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need 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)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 6

🧹 Nitpick comments (3)
plugin/controller/test/fixtures/apps/mcp-app/hook-plugin/package.json (1)

1-6: LGTM! Consider adding version field for completeness.

The package.json structure correctly follows Egg.js plugin conventions with the proper eggPlugin configuration.

Consider adding a version field for better package management:

{
  "name": "@eggjs/hook-plugin",
+ "version": "1.0.0",
  "eggPlugin": {
    "name": "hookPlugin"
  }
}
plugin/controller/test/fixtures/apps/mcp-app/config/plugin.js (1)

2-3: Consider using consistent import style for the path module.

The functionality is correct, but for consistency with other plugin files in the codebase, consider using the Node.js built-in module specifier.

Based on the pattern used in plugin/mcp-proxy/test/fixtures/apps/mcp-proxy/config/plugin.js (line 4), consider this change:

-// eslint-disable-next-line @typescript-eslint/no-var-requires
-const path = require('path');
+const path = require('node:path');

This follows the modern Node.js convention for built-in modules and eliminates the need for the eslint disable comment.

plugin/controller/test/fixtures/apps/mcp-app/hook-plugin/app.ts (1)

1-15: Well-structured boot hook implementation.

The boot hook correctly follows Egg.js patterns and uses the appropriate lifecycle method for hook registration.

Consider adding error handling for hook registration to make the system more robust:

 configWillLoad() {
-  MCPControllerRegister.addHook(GetAlipayTeggHook(this.#app));
+  try {
+    MCPControllerRegister.addHook(GetAlipayTeggHook(this.#app));
+  } catch (error) {
+    this.#app.logger.error('Failed to register MCP controller hook:', error);
+    throw error;
+  }
 }

Note: The function name GetAlipayTeggHook appears specific to Alipay. If this is intended for general use, consider a more generic name like GetUserInjectionHook.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ab43456 and 39c95ac.

📒 Files selected for processing (8)
  • plugin/controller/lib/impl/mcp/MCPControllerRegister.ts (1 hunks)
  • plugin/controller/test/fixtures/apps/mcp-app/app/controller/McpController.ts (2 hunks)
  • plugin/controller/test/fixtures/apps/mcp-app/config/plugin.js (2 hunks)
  • plugin/controller/test/fixtures/apps/mcp-app/hook-plugin/app.ts (1 hunks)
  • plugin/controller/test/fixtures/apps/mcp-app/hook-plugin/lib/MCPControllerHook.ts (1 hunks)
  • plugin/controller/test/fixtures/apps/mcp-app/hook-plugin/package.json (1 hunks)
  • plugin/controller/test/mcp/mcp.test.ts (9 hunks)
  • plugin/controller/test/mcp/mcpCluster.test.ts (9 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (3)
plugin/controller/test/fixtures/apps/mcp-app/config/plugin.js (1)
plugin/mcp-proxy/test/fixtures/apps/mcp-proxy/config/plugin.js (1)
  • path (4-4)
plugin/controller/test/fixtures/apps/mcp-app/hook-plugin/lib/MCPControllerHook.ts (1)
plugin/controller/lib/impl/mcp/MCPControllerRegister.ts (1)
  • MCPControllerHook (31-44)
plugin/controller/test/fixtures/apps/mcp-app/app/controller/McpController.ts (2)
core/controller-decorator/src/decorator/mcp/MCPTool.ts (1)
  • MCPTool (10-33)
core/types/controller-decorator/MCPToolParams.ts (1)
  • MCPToolResponse (8-8)
⏰ Context from checks skipped due to timeout of 90000ms (9)
  • GitHub Check: Runner-ubuntu (22)
  • GitHub Check: Runner-ubuntu (20)
  • GitHub Check: Runner-ubuntu (16)
  • GitHub Check: Runner-macos (16)
  • GitHub Check: Runner-ubuntu (18)
  • GitHub Check: Runner-macos (20)
  • GitHub Check: Runner-macos (18)
  • GitHub Check: Analyze (javascript)
  • GitHub Check: Analyze (typescript)
🔇 Additional comments (8)
plugin/controller/test/fixtures/apps/mcp-app/config/plugin.js (1)

31-34: Plugin configuration looks good.

The hookPlugin configuration correctly follows Egg.js plugin patterns with proper path resolution and enablement.

plugin/controller/lib/impl/mcp/MCPControllerRegister.ts (1)

400-403:

❓ Verification inconclusive

Verify security implications of propagating all headers.

The change from setting specific headers to spreading all headers (...ctx.req.headers) could potentially expose sensitive information. Consider filtering or whitelisting specific headers instead of propagating everything.


🏁 Script executed:

#!/bin/bash
# Check if there are any header filtering mechanisms or security considerations documented
rg -A 5 -B 5 "headers.*security|sensitive.*header|filter.*header" --type ts

Length of output: 77


Review header propagation security

I didn’t find any existing header‐filtering or whitelist mechanism in the codebase. Spreading all incoming headers (...ctx.req.headers) risks leaking sensitive data.

• File/plugin: plugin/controller/lib/impl/mcp/MCPControllerRegister.ts (lines 400–403)
• No “allowed headers” list or sanitization logic detected
• Suggest explicitly selecting or filtering headers (e.g. only propagate accept, content-type, and any required auth headers) rather than spreading everything

Please verify that only safe headers are forwarded or implement a header whitelist before propagation.

plugin/controller/test/mcp/mcpCluster.test.ts (3)

103-125: LGTM! Auth provider implementation is consistent and well-structured.

The auth provider configuration is properly implemented across all three transport types with:

  • Consistent structure and mock implementations
  • Proper base64 encoding of test token
  • Appropriate no-op functions for unused auth methods

The test setup enables proper verification of the hook functionality.

Also applies to: 227-250, 359-381


142-145: LGTM! Test coverage for new echoUser tool is comprehensive.

The addition of echoUser to the expected tools list is consistent across all transport types and properly tests the new hook functionality.

Also applies to: 268-271, 398-401


157-163: LGTM! echoUser tool invocation tests are well-structured.

The test calls to echoUser tool properly verify:

  • Tool accepts empty arguments
  • Returns expected greeting message with injected user
  • Validates integration between auth provider, hook, and controller

Also applies to: 283-289, 413-419

plugin/controller/test/mcp/mcp.test.ts (3)

93-115: LGTM! Auth provider implementation matches cluster tests.

The auth provider configuration is identical to the cluster test file, ensuring consistent test coverage across both single-process and multi-process scenarios.

Also applies to: 218-241, 351-373


132-135: LGTM! Tool list assertions are consistent with cluster tests.

The echoUser tool addition maintains consistency between test files and properly validates the new hook functionality.

Also applies to: 259-262, 390-393


148-154: LGTM! echoUser tool tests validate end-to-end functionality.

The test calls confirm that the authentication hook properly injects user context and that the controller method returns the expected greeting message.

Also applies to: 275-281, 406-412

Copy link
@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (3)
plugin/mcp-proxy/index.ts (3)

69-76: Approve the response format change but verify content-type header.

The change from Express-style to raw HTTP responses provides better control and is consistent with the low-level nature of the proxy.

Consider adding a content-type header for consistency:

-        res.writeHead(400).end(JSON.stringify({
+        res.writeHead(400, { 'content-type': 'application/json' }).end(JSON.stringify({

This matches the pattern used elsewhere in the file (lines 130, 145, 164) and ensures proper content-type handling.


97-104: Approve the response format change but add content-type header for consistency.

The error response structure and JSON-RPC 2.0 format are correct.

Add content-type header to match the pattern used elsewhere in the file:

-        res.writeHead(404).end(JSON.stringify({
+        res.writeHead(404, { 'content-type': 'application/json' }).end(JSON.stringify({

This ensures consistent content-type handling across all error responses.


69-104: Consider extracting error response helper function.

The JSON-RPC error response pattern is repeated multiple times throughout the file with slight variations.

Consider creating a helper function to reduce duplication:

function sendJsonRpcError(res: http.ServerResponse, statusCode: number, err
8000
orCode: number, message: string, id: any = null) {
  res.writeHead(statusCode, { 'content-type': 'application/json' }).end(JSON.stringify({
    jsonrpc: '2.0',
    error: {
      code: errorCode,
      message,
    },
    id,
  }));
}

// Usage:
sendJsonRpcError(res, 400, -32000, 'Bad Request: Session exists but uses a different transport protocol');
sendJsonRpcError(res, 404, -32602, 'Bad Request: No transport found for sessionId');

This would improve maintainability and ensure consistent error response formatting.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 39c95ac and d9cf484.

📒 Files selected for processing (1)
  • plugin/mcp-proxy/index.ts (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (7)
  • GitHub Check: Runner-ubuntu (16)
  • GitHub Check: Runner-ubuntu (22)
  • GitHub Check: Runner-macos (16)
  • GitHub Check: Runner-ubuntu (20)
  • GitHub Check: Runner-macos (20)
  • GitHub Check: Runner-macos (18)
  • GitHub Check: Runner-ubuntu (18)

Copy link
Contributor
@killagu killagu left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@akitaSummer akitaSummer merged commit 5716e0a into eggjs:master May 27, 2025
13 checks passed
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.

2 participants
0