Skip to content

Conversation

@zerob13
Copy link
Collaborator

@zerob13 zerob13 commented Jun 19, 2025

Pull Request Description (中文)

你的功能请求是否与某个问题有关?请描述一下。
修复 #534 问题
支持http协议在遇到400等错误的时候自动重启服务,多次重启失败后关闭服务

Summary by CodeRabbit

  • New Features
    • Introduced automatic session recovery for MCP Streamable HTTP sessions, improving resilience against session expiration or invalidation errors.
  • Documentation
    • Added detailed documentation explaining the session recovery mechanism, error handling workflow, and usage recommendations.
  • Bug Fixes
    • Enhanced error handling to prevent infinite retry loops and ensure proper cleanup and notification when persistent session errors occur.
  • Style
    • Minor syntax update for improved code consistency.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jun 19, 2025

Walkthrough

The changes introduce robust session error detection and automatic recovery logic to the MCP client, centralizing error handling and recovery in the codebase. A new documentation file explains the mechanism and its workflow. Additionally, a minor syntax update is made in the Gemini provider code, with no functional impact.

Changes

File(s) Change Summary
docs/mcp-session-recovery.md Added documentation describing the MCP session recovery mechanism, error types, workflow, and usage.
src/main/presenter/mcpPresenter/mcpClient.ts Implemented session error detection, automatic recovery, restart/stop logic, and refactored disconnect.
src/main/presenter/llmProviderPresenter/providers/geminiProvider.ts Minor arrow function syntax update in model lookup, no logic change.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant McpClient
    participant MCPServer
    participant EventBus

    Client->>McpClient: callTool / listTools / etc.
    McpClient->>MCPServer: Send request
    MCPServer-->>McpClient: Error (session expired/invalid)
    McpClient->>McpClient: Detect session error
    alt First session error
        McpClient->>McpClient: Restart service, clear caches
        McpClient-->>Client: Propagate error
        Client->>McpClient: Retry operation
        McpClient->>MCPServer: Send request
        MCPServer-->>McpClient: Error (if still session error)
        McpClient->>McpClient: Stop service
        McpClient->>EventBus: Emit server status event
    else Not a session error
        McpClient-->>Client: Propagate error
    end
Loading

Poem

In the warren of code, a session may stray,
But now the client hops in to save the day!
With caches cleared and errors caught,
Recovery’s swift—no endless loops are sought.
If trouble persists, the service takes a rest,
And rabbits rejoice: robust code is best! 🐇✨

✨ 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
Contributor

@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: 0

🧹 Nitpick comments (3)
docs/mcp-session-recovery.md (3)

7-9: Specify language for code blocks to improve readability.

The fenced code blocks should have language specifiers for proper syntax highlighting.

Apply this diff to add language specifiers:

-```
+```text
 Error POSTing to endpoint (HTTP 400): Bad Request: No valid session ID provided
-```
+```

158-158: Minor language correction suggestion.

The static analysis tool suggests a grammatical improvement for Chinese text flow.

Consider changing "新的连接" to "新地连接" for better Chinese grammar flow, though this is a very minor stylistic preference.


175-177: Add language specifiers to log output code blocks.

The log output examples should specify the language for better formatting.

Apply this diff to improve the formatting:

-```
+```text
 Session error detected for server doris_server, restarting service...
 Service doris_server restarted due to session error
-```
+```

-```
+```text
 Session error persists after restart for server doris_server, stopping service...
 MCP service doris_server has been stopped due to persistent session errors
-```
+```

Also applies to: 181-183

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8f17b58 and b8f0f51.

📒 Files selected for processing (3)
  • docs/mcp-session-recovery.md (1 hunks)
  • src/main/presenter/llmProviderPresenter/providers/geminiProvider.ts (1 hunks)
  • src/main/presenter/mcpPresenter/mcpClient.ts (15 hunks)
🧰 Additional context used
🪛 LanguageTool
docs/mcp-session-recovery.md

[uncategorized] ~158-~158: 动词的修饰一般为‘形容词(副词)+地+动词’。您的意思是否是:新"地"连接
Context: ...用者知道需要重试 5. 重新调用: 上层调用者重新发起请求,此时会建立新的连接和session 6. 持续错误检测: 如果重启后再次出现sessi...

(wb4)

🪛 markdownlint-cli2 (0.17.2)
docs/mcp-session-recovery.md

7-7: Fenced code blocks should have a language specified
null

(MD040, fenced-code-language)


175-175: Fenced code blocks should have a language specified
null

(MD040, fenced-code-language)


181-181: Fenced code blocks should have a language specified
null

(MD040, fenced-code-language)

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: build-check (x64)
🔇 Additional comments (11)
src/main/presenter/llmProviderPresenter/providers/geminiProvider.ts (1)

445-445: LGTM: Minor syntax improvement for consistency.

The addition of parentheses around the arrow function parameter is a harmless style improvement that enhances code consistency.

docs/mcp-session-recovery.md (1)

1-241: Excellent comprehensive documentation.

This documentation provides a thorough explanation of the session recovery mechanism, covering:

  • Problem background and MCP specification compliance
  • Clear solution overview with error detection and recovery workflow
  • Detailed code examples and usage patterns
  • Distinction between different disconnect methods
  • Practical usage recommendations

The documentation effectively complements the implementation changes in the mcpClient.ts file.

src/main/presenter/mcpPresenter/mcpClient.ts (9)

47-51: Well-designed session error interface.

The SessionError interface properly extends Error with optional HTTP status and session expiry fields, providing structured error information for session management.


53-84: Robust session error detection with pattern matching.

The isSessionError function implements comprehensive error detection with:

  • High-confidence session-specific patterns (session expired, invalid session, etc.)
  • HTTP error patterns with transport context validation
  • Proper defensive programming with type guards

This approach ensures accurate identification of session-related errors while avoiding false positives.


100-103: Appropriate state management for recovery control.

The addition of isRecovering and hasRestarted flags provides proper concurrency control and prevents infinite retry loops, which is essential for robust session management.


667-706: Well-implemented session error recovery logic.

The checkAndHandleSessionError method provides:

  • Proper concurrency control with isRecovering flag
  • Single restart attempt with complete state cleanup
  • Service shutdown on persistent errors to prevent infinite loops
  • Clear logging for debugging and monitoring

The recovery strategy is simple yet effective, following the principle of fail-fast when recovery attempts don't succeed.


708-716: Clean service shutdown implementation.

The stopService method properly delegates to the internal disconnect method with a specific reason, maintaining consistency in cleanup behavior.


718-734: Unified disconnect logic with proper event notification.

The internalDisconnect method provides:

  • Centralized cleanup logic used by both normal disconnect and forced stop
  • Customizable logging based on the disconnect reason
  • Proper system notification via event bus
  • Consistent resource cleanup

This design eliminates code duplication and ensures consistent behavior across different disconnect scenarios.


626-627: Proper refactoring of disconnect method.

The public disconnect method now correctly delegates to the internal method, maintaining the same public API while leveraging the shared cleanup logic.


737-776: Consistent session error handling across all public methods.

All public async methods (callTool, listTools, listPrompts, getPrompt, listResources, readResource) now include:

  • Automatic connection establishment when needed
  • Session error detection and recovery via checkAndHandleSessionError
  • Reset of hasRestarted flag on successful operations
  • Proper error propagation to callers

This consistent implementation ensures that session errors are handled uniformly across the entire MCP client API, allowing callers to retry operations after automatic recovery.

Also applies to: 785-826, 835-889, 892-934, 943-990, 993-1028


754-755: Smart recovery state reset on successful operations.

The reset of hasRestarted flag after successful operations is a clever design choice that allows the service to attempt recovery again if session errors occur later, while still preventing infinite loops during persistent issues.

Also applies to: 797-798, 848-849, 908-909, 956-957, 1007-1008

@zerob13 zerob13 merged commit 65a684d into dev Jun 19, 2025
2 checks passed
@coderabbitai coderabbitai bot mentioned this pull request Jun 21, 2025
@zerob13 zerob13 deleted the feature/streamable-http-session branch September 21, 2025 14:48
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