NextChat icon indicating copy to clipboard operation
NextChat copied to clipboard

Add support for MCP(sse/streamableHttp) in export mode

Open mokeyish opened this issue 9 months ago • 7 comments

closes #6473,#6448, #6437,#6323,#6154

💻 变更类型 | Change Type

  • [x] feat
  • [ ] fix
  • [ ] refactor
  • [ ] perf
  • [ ] style
  • [ ] test
  • [ ] docs
  • [ ] ci
  • [ ] chore
  • [x] build

🔀 变更说明 | Description of Change

📝 补充信息 | Additional Information

Summary by CodeRabbit

Summary by CodeRabbit

  • New Features

    • Added support for both server and client modes, allowing configuration and tool data to be managed via local storage or file system based on build mode.
    • Introduced new build configuration options, including toggles for features like GPT-4, custom config, balance query, and more, all controllable via environment variables.
    • Added global compile-time constant to indicate export mode, improving environment-specific behavior.
    • Implemented a comprehensive MCP client and server management system with lifecycle controls, tool mapping, and configuration persistence.
    • Enabled dynamic delegation of MCP actions to client or server modules based on build mode.
  • Improvements

    • Enhanced type safety and clarity in handling server configurations and tool lists.
    • Improved client lookup logic for tool execution, providing better fallback mechanisms.
    • Optimized initialization for access store in export mode to avoid unnecessary network requests.
    • Updated client creation to dynamically select transport type based on server config and build mode.
    • Simplified tools state management and rendering with clearer typing and type guards.
  • Bug Fixes

    • Refined checks for server configuration types to ensure correct extraction and usage of user configurations.

mokeyish avatar May 08 '25 05:05 mokeyish

@mokeyish is attempting to deploy a commit to the NextChat Team on Vercel.

A member of the Team first needs to authorize it.

vercel[bot] avatar May 08 '25 05:05 vercel[bot]

"""

Walkthrough

This update introduces dual client/server mode support for MCP-related logic, governed by a new global EXPORT_MODE constant. It refactors server configuration types, enhances type safety for tool schemas, expands build configuration options, and adapts client/server behaviors to use localStorage or filesystem as appropriate. Type guards and conditional logic are added throughout.

Changes

File(s) Change Summary
app/components/mcp-market.tsx Refined type handling for the tools state, updated modal rendering logic, and improved server config checks using new type guards for better type safety and clarity. Added imports for ToolSchema and isServerStdioConfig.
app/config/build.ts Extended getBuildConfig to include new properties (feature toggles, URLs, flags) sourced from environment variables, enriching the build configuration.
app/mcp/actions.ts Replaced entire implementation with a dynamic import that conditionally loads either client or server-specific MCP actions module based on EXPORT_MODE. Removed all previous functions and internal logic.
app/mcp/actions.base.ts Added comprehensive MCP client/server management module with functions for initializing, adding, pausing, resuming, removing, restarting clients, managing tools, and executing MCP actions. Supports config loading/saving via file or localStorage depending on mode, with logging and error handling.
app/mcp/actions.client.ts New module re-exporting all exports from actions.base for client-side usage.
app/mcp/actions.server.ts New server-side module re-exporting all exports from actions.base with "use server" directive for server context.
app/mcp/client.ts Modified createClient to dynamically select between SSE and stdio transports using type guards and dynamic imports. Throws error if stdio transport is requested in export mode.
app/mcp/types.ts Refactored server config to discriminated union of ServerStdioConfig, ServerSseConfig, and ServerSteamableConfig with type guards. Added ToolSchema interface and changed tools array type accordingly. Extended McpRequestMessage and McpConfigData interfaces with new properties.
app/store/access.ts Modified fetch logic in useAccessStore to initialize state from client config in export mode before returning early, avoiding unnecessary network requests.
app/typing.ts Declared global constant EXPORT_MODE: boolean for compile-time usage throughout the app.
next.config.mjs Injected EXPORT_MODE as a compile-time constant into webpack build via DefinePlugin for conditional bundling logic.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant MCPMarketPage
    participant MCPClient
    participant ConfigStore
    participant LocalStorage
    participant FileSystem

    User->>MCPMarketPage: Open MCP Market
    MCPMarketPage->>ConfigStore: Load MCP Config
    alt EXPORT_MODE enabled
        ConfigStore->>LocalStorage: Read MCP Config
        LocalStorage-->>ConfigStore: Config Data (possibly merged)
    else Not EXPORT_MODE
        ConfigStore->>FileSystem: Read MCP Config
        FileSystem-->>ConfigStore: Config Data
    end
    MCPMarketPage->>MCPClient: List Tools (with config)
    MCPClient->>MCPMarketPage: Tools List
    MCPMarketPage-->>User: Render Tools Modal

Assessment against linked issues

Objective Addressed Explanation
Support MCP SSE transport (#6473) Introduced ServerSseConfig type, isServerSseConfig guard, and SSE transport in client creation to support SSE.

Suggested labels

enhancement, planned

Suggested reviewers

  • Dogtiti

Poem

A toggle for export, a config anew,
With type guards and unions, the logic grew.
Now tools are more clear,
And configs appear
From disk or from storage, depending on view!

🐇✨ """

[!NOTE]

⚡️ AI Code Reviews for VS Code, Cursor, Windsurf

CodeRabbit now has a plugin for VS Code, Cursor and Windsurf. This brings AI code reviews directly in the code editor. Each commit is reviewed immediately, finding bugs before the PR is raised. Seamless context handoff to your AI code agent ensures that you can easily incorporate review feedback. Learn more here.


[!NOTE]

⚡️ Faster reviews with caching

CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 16th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings. Enjoy the performance boost—your workflow just got faster.


📜 Recent review details

Configuration used: CodeRabbit UI Review profile: CHILL Plan: Pro Cache: Disabled due to data retention organization setting Knowledge Base: Disabled due to data retention organization setting

📥 Commits

Reviewing files that changed from the base of the PR and between 62d32f317d071efeadf12147570c83c75361e1af and 2f20905544d62224a0edd3cc85a446da4f6eda5c.

⛔ Files ignored due to path filters (1)
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
📒 Files selected for processing (3)
  • app/mcp/client.ts (1 hunks)
  • app/mcp/types.ts (3 hunks)
  • package.json (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • package.json
🚧 Files skipped from review as they are similar to previous changes (1)
  • app/mcp/client.ts
🔇 Additional comments (5)
app/mcp/types.ts (5)

11-11: LGTM: Added optional name parameter

The addition of an optional name property to the McpRequestMessage params object allows for more flexible parameter identification when making tool calls.


69-77: Good improvement to type safety

Replacing the previous generic typing with a more specific ToolSchema interface improves type safety and makes the code more self-documenting. Having explicit fields for name, description, and inputSchema makes the expected structure clearer while still allowing for extensibility with the index signature.


117-122: Type guards correctly implement null checks

The type guards properly check for null before checking for object type, addressing the potential issue where typeof null === "object" would return true and could lead to runtime errors.


124-149: Good use of discriminated union for server configs

Refactoring the ServerConfig into a discriminated union with distinct types (ServerStdioConfig, ServerSseConfig, ServerSteamableConfig) improves type safety and makes the different configuration options explicit. This aligns well with the PR objective to support different modes in the MCP implementation.


152-152: LGTM: Added enableMcp flag

The addition of an optional enableMcp flag to McpConfigData allows for toggling MCP functionality, which is essential for the dual client/server mode support described in the PR objectives.

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

coderabbitai[bot] avatar May 08 '25 05:05 coderabbitai[bot]

我想支持stido模式该如何改代码

madaochina-dev avatar May 16 '25 01:05 madaochina-dev

Bot detected the issue body's language is not English, translate it automatically.


I want to support sido mode how to change the code

Issues-translate-bot avatar May 16 '25 01:05 Issues-translate-bot

stdio 必须有后台进程,帮忙调用系统命令。纯前端只能 sse 和 streamableHttp。

mokeyish avatar May 16 '25 11:05 mokeyish

Bot detected the issue body's language is not English, translate it automatically.


stdio must have a background process to help call system commands. Pure front-end can only sse and streamableHttp.

Issues-translate-bot avatar May 16 '25 11:05 Issues-translate-bot

Hi @mokeyish @madaochina-dev @marcusschiesser @shoito Thanks for your time and effort maintaining NextChat. I have a suggestion for you:

Why not using https://github.com/modelcontextprotocol/use-mcp hook to provide mcp client functionality?

Let me know if I can contribute to NextChat. I'd be more than happy to create a pull request and integrate use-mcp hook into nextChat.

HsnVahedi avatar Jul 14 '25 21:07 HsnVahedi