Skip to content

[Fix] Improve tool system stability and simplify MCP commands#595

Merged
dingyi222666 merged 4 commits into
v1-devfrom
fix/tools
Oct 15, 2025
Merged

[Fix] Improve tool system stability and simplify MCP commands#595
dingyi222666 merged 4 commits into
v1-devfrom
fix/tools

Conversation

@dingyi222666
Copy link
Copy Markdown
Member

This PR improves the stability of the tool system and simplifies the MCP command interface.

Bug Fixes

  • Fix tool creation error handling: Added try-catch blocks in createToolsRef to gracefully handle tool creation failures and filter out undefined tools (packages/core/src/llm-core/agent/creator.ts:78-91)
  • Fix lifecycle management: Wrapped prompt function provider registration in ctx.effect() for proper cleanup in long-memory extension (packages/extension-long-memory/src/plugins/prompt_varaiable.ts:136-148)

Refactor

  • Simplify MCP list command: Removed the -r/--raw option from chatluna.mcp.list command to streamline user experience and focus on tool management rather than exposing internal server configuration details (packages/extension-mcp/src/command.ts:8-45)
  • Code cleanup: Minor formatting fix in command execute tool

Other Changes

  • Improved error logging for tool creation failures with descriptive messages
  • Reduced code complexity by removing unnecessary nested logic in MCP commands

These changes enhance system stability by preventing crashes from tool creation errors and ensuring proper resource cleanup through Koishi's effect system.

…d fix formatting

- Remove raw server listing option from chatluna.mcp.list command
- Simplify command to only list MCP tools without raw config display
- Fix spacing in image URL format string in command execute tool
- Clean up code structure by removing unnecessary nested logic

The raw server listing functionality was removed to streamline the
user experience and focus on tool management rather than exposing
internal server configuration details.
… and lifecycle management

- Add try-catch block in createToolsRef to handle tool creation errors
- Filter out failed tool creations to prevent undefined tools
- Wrap prompt function provider registration in ctx.effect() for proper lifecycle management
- Add error logging for tool creation failures

These changes improve stability by gracefully handling tool creation errors
and ensuring proper cleanup of registered providers through Koishi's effect system.
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Oct 15, 2025

Important

Review skipped

Review was skipped due to path filters

⛔ Files ignored due to path filters (26)
  • packages/adapter-azure-openai/package.json is excluded by !**/*.json
  • packages/adapter-claude/package.json is excluded by !**/*.json
  • packages/adapter-deepseek/package.json is excluded by !**/*.json
  • packages/adapter-dify/package.json is excluded by !**/*.json
  • packages/adapter-doubao/package.json is excluded by !**/*.json
  • packages/adapter-gemini/package.json is excluded by !**/*.json
  • packages/adapter-hunyuan/package.json is excluded by !**/*.json
  • packages/adapter-ollama/package.json is excluded by !**/*.json
  • packages/adapter-openai-like/package.json is excluded by !**/*.json
  • packages/adapter-openai/package.json is excluded by !**/*.json
  • packages/adapter-qwen/package.json is excluded by !**/*.json
  • packages/adapter-rwkv/package.json is excluded by !**/*.json
  • packages/adapter-spark/package.json is excluded by !**/*.json
  • packages/adapter-wenxin/package.json is excluded by !**/*.json
  • packages/adapter-zhipu/package.json is excluded by !**/*.json
  • packages/core/package.json is excluded by !**/*.json
  • packages/extension-long-memory/package.json is excluded by !**/*.json
  • packages/extension-mcp/package.json is excluded by !**/*.json
  • packages/extension-tools/package.json is excluded by !**/*.json
  • packages/extension-variable/package.json is excluded by !**/*.json
  • packages/renderer-image/package.json is excluded by !**/*.json
  • packages/service-embeddings/package.json is excluded by !**/*.json
  • packages/service-image/package.json is excluded by !**/*.json
  • packages/service-search/package.json is excluded by !**/*.json
  • packages/service-vector-store/package.json is excluded by !**/*.json
  • packages/shared-adapter/package.json is excluded by !**/*.json

CodeRabbit blocks several paths by default. You can override this behavior by explicitly including those paths in the path filters. For example, including **/dist/** will override the default block on the dist directory, by removing the pattern from both the lists.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

Walkthrough

对多处组件进行控制流与健壮性调整:工具创建对每项增加 try/catch 并过滤失败项;长记忆提供者注册移入 ctx.effect;MCP 列表命令简化为基于服务的 globalTools 列表并统一错误路径;工具插件中修正了图片输出文本的空格。

Changes

Cohort / File(s) Change Summary
工具创建健壮性
packages/core/src/llm-core/agent/creator.ts
createToolsRef 在对每个 tool.createTool() 的调用上加入 try/catch,日志记录失败并继续;随后使用 .filter(Boolean) 去除失败或空值结果。
长记忆提供者注册时机
packages/extension-long-memory/src/plugins/prompt_varaiable.ts
register('long_memory', ...) 包裹入 ctx.effect(() => ...) 中以在响应式 effect 中注册,内部错误处理和消息保持不变。
MCP 列表命令重写
packages/extension-mcp/src/command.ts
移除列举 raw 服务器/配置解析分支;改为检查服务就绪性并从 service.globalTools 列出工具,空列表与异常走统一消息路径,导出签名不变。
工具插件文案微调
packages/extension-tools/src/plugins/command.ts
修正图像处理提示文本中的空格:将双空格改为单空格(仅文本格式调整,无控制流变更)。

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant Caller as Agent
  participant Creator as createToolsRef
  participant Tool as ToolItem

  Caller->>Creator: createToolsRef(tools[])
  loop 对每个 tool
    Creator->>Tool: tool.createTool()
    alt 成功
      Note right of Creator #DFF2E1: 收集有效实例
    else 失败
      Creator-->>Creator: 记录错误并跳过
    end
  end
  Creator-->>Caller: 返回过滤后的工具列表 (.filter(Boolean))
Loading
sequenceDiagram
  autonumber
  participant User as 命令调用者
  participant Cmd as chatluna.mcp.list
  participant Svc as ctx.chatluna_mcp
  participant UI as 渲染器

  User->>Cmd: 执行 list
  alt 服务未就绪
    Cmd-->>UI: 返回 service_not_ready
  else 服务就绪
    Cmd->>Svc: 读取 globalTools
    alt 无工具
      Cmd-->>UI: 返回 empty-tools
    else 有工具
      Cmd-->>UI: 渲染工具列表
    end
  end
  Note over Cmd,UI #FFF4D6: 异常统一走 list_error
Loading
sequenceDiagram
  autonumber
  participant Host as 插件宿主
  participant Ctx as ctx
  participant Eff as ctx.effect
  participant Reg as ProviderRegistry

  Host->>Ctx: 插件初始化
  Ctx->>Eff: effect(() => register('long_memory', handler))
  Eff->>Reg: 注册 long_memory 提供者
  Note over Eff,Reg #E8F0FF: 注册由 effect 驱动,处理逻辑不变
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Poem

我是小兔啃代码,try/catch 铺路跑;
effect 轻敲注册门,记忆悄然进草包;
列表只留真工具,空格收敛不凌乱;
提交轻轻一跃起,仓库里跳舞笑眯眯。 🐇✨

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Title Check ✅ Passed 该标题简洁明了地概括了改动的核心——提升工具系统稳定性并简化 MCP 命令接口,同时避免了与变更无关的信息或模糊术语,使团队成员在浏览提交历史时能够快速理解主要内容。
Description Check ✅ Passed 此描述与 PR 的实际更改内容紧密相关,清晰列出了工具创建错误处理、长内存扩展中生命周期管理的改进及 MCP 命令接口简化等关键点,足以向审阅者传达主要改动目的与内容。

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

Comment @coderabbitai help to get the list of available commands and usage tips.

@gemini-code-assist
Copy link
Copy Markdown
Contributor

Summary of Changes

Hello @dingyi222666, 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 significantly enhances the overall stability and user experience of the tool system. It addresses potential system crashes by gracefully handling tool creation errors and ensures efficient resource management through proper lifecycle integration. Additionally, it refines the command-line interface for MCP tools, making it more intuitive and focused on tool management.

Highlights

  • Enhanced Tool Stability: Implemented robust error handling during tool creation, preventing failures from crashing the system and ensuring only valid tools are utilized. Failed tool creations are now logged.
  • Improved Resource Management: Ensured proper cleanup of prompt function providers in the long-memory extension by integrating their registration with Koishi's effect system for correct lifecycle management.
  • Streamlined MCP Commands: Simplified the chatluna.mcp.list command by removing the -r/--raw option, focusing its utility on tool management rather than exposing internal server configurations.
  • Code Quality: Applied minor formatting adjustments to improve code readability in the command execute tool.
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 by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

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 pull request 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 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. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

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

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

Copy link
Copy Markdown
Contributor

@gemini-code-assist gemini-code-assist Bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request introduces several valuable improvements. The addition of error handling in tool creation significantly enhances system stability. Wrapping the prompt provider registration in ctx.effect is a great fix for proper lifecycle management in the Koishi plugin. The simplification of the chatluna.mcp.list command by removing the --raw option improves user experience and maintainability. I've left a couple of minor suggestions to improve logging consistency and code clarity. Overall, these are solid changes.

Comment thread packages/core/src/llm-core/agent/creator.ts
Comment thread packages/extension-mcp/src/command.ts
Copy link
Copy Markdown
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 (1)
packages/core/src/llm-core/agent/creator.ts (1)

78-91: 防御性错误处理显著提升了稳定性。

通过为每个工具创建添加 try-catch 并过滤失败结果,确保单个工具创建失败不会导致整个代理系统崩溃。这与 PR 目标一致。

不过,建议改进错误日志记录:

应用此 diff 以改进错误日志记录:

                 try {
                     return tool.createTool({
                         embeddings: options.embeddings
                     })
                 } catch (error) {
-                    console.error(`Error creating tool ${tool.id}:`, error)
+                    console.error(`Failed to create tool "${tool.id}":`, error instanceof Error ? error.message : error)
+                    console.debug(`Tool creation stack trace for ${tool.id}:`, error)
                 }

改进原因:

  1. 使用更具描述性的 "Failed to create" 而不是 "Error creating"
  2. 仅在主要错误消息中记录 error.message,避免日志混乱
  3. 在 debug 级别记录完整堆栈跟踪,便于调试时查看详细信息
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between dcbd05c and 9d3776c.

📒 Files selected for processing (4)
  • packages/core/src/llm-core/agent/creator.ts (1 hunks)
  • packages/extension-long-memory/src/plugins/prompt_varaiable.ts (1 hunks)
  • packages/extension-mcp/src/command.ts (1 hunks)
  • packages/extension-tools/src/plugins/command.ts (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (2)
packages/extension-long-memory/src/plugins/prompt_varaiable.ts (1)
packages/extension-long-memory/src/index.ts (1)
  • logger (9-9)
packages/extension-mcp/src/command.ts (1)
packages/extension-mcp/src/index.ts (1)
  • name (76-76)
⏰ 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). (2)
  • GitHub Check: lint
  • GitHub Check: build
🔇 Additional comments (3)
packages/extension-tools/src/plugins/command.ts (1)

288-288: 文本格式改进看起来不错!

将图片 URL 提示消息中的双空格修正为单空格,提高了文本一致性。

packages/extension-long-memory/src/plugins/prompt_varaiable.ts (1)

136-148: 正确使用 Koishi 的 effect 系统进行资源管理。

将函数提供者注册包装在 ctx.effect() 中,确保当插件被释放时能够正确清理注册的提供者。这是 Koishi 插件开发的最佳实践,防止内存泄漏并确保资源正确回收。

packages/extension-mcp/src/command.ts (1)

8-46: 简化的 MCP 列表命令提升了可维护性,已确认未发现对 -r/--raw 的引用,可安全移除

  • 添加了服务就绪检查,防止在服务未初始化时崩溃
  • 统一使用 service.globalTools 作为单一数据源
  • 移除了 -r/--raw 选项,简化了用户界面
  • 统一的错误处理路径提高了代码一致性

…d validation

- Replace array filter/find operations with Map for O(1) lookup performance
- Add validation warning when rawCommandList references non-existent commands
- Simplify conditional logic: use rawCommandList for mapping when provided, otherwise return all commands
- Reduce redundant operations by calling toJSON() once per command
- Improve code readability with clearer separation of execution paths

This optimization significantly improves performance when dealing with large command lists
and provides better debugging feedback when commands are misconfigured.
- Update core package version from 1.3.0-alpha.64 to 1.3.0-alpha.65
- Update extension-mcp version from 1.3.0-alpha.8 to 1.3.0-alpha.9
- Update extension-tools version from 1.3.0-alpha.20 to 1.3.0-alpha.21
- Update all adapter packages peer dependency to ^1.3.0-alpha.65
- Update all extension packages peer dependency to ^1.3.0-alpha.65
- Update all service packages peer dependency to ^1.3.0-alpha.65

This version bump includes improvements to tool system stability, MCP command
simplification, and getCommandList optimization.
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.

1 participant