Skip to content

[Fix] Improve MCP tool handling and timeout support#613

Merged
dingyi222666 merged 4 commits into
v1-devfrom
fix-mcp
Oct 24, 2025
Merged

[Fix] Improve MCP tool handling and timeout support#613
dingyi222666 merged 4 commits into
v1-devfrom
fix-mcp

Conversation

@dingyi222666
Copy link
Copy Markdown
Member

This PR improves the MCP extension with better tool handling, timeout configuration support, and bug fixes.

Bug Fixes

Other Changes

  • Refactor MCP client storage from array to Map for better server config tracking
  • Add mime-types dependency for proper MIME type to file extension conversion
  • Improve error handling and logging for tool observations
  • Fix typo: mineTypemimeType

- Add timeout configuration support for MCP tool calls
- Improve tool schema generation and display formatting
- Enhance error handling in agent executor
@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 Model Context Protocol (MCP) extension by introducing configurable timeouts for tool executions, improving the reliability of file handling through accurate MIME type-based extension generation, and making the agent executor more resilient to unexpected tool observation formats. These changes aim to provide a more stable and configurable environment for MCP tool interactions.

Highlights

  • Timeout Configuration: Added support for configuring timeouts for MCP tool calls at both the server and individual tool levels, addressing issue [Feature] 支持为 MCP 设置自定义超时 #612.
  • File Extension Handling: Improved file extension generation by using the mime-types library for proper MIME type lookup, fixing issue [Bug] MCP 扩展的图片保存后缀名bug #611 and replacing hardcoded suffixes.
  • Non-String Tool Observations: Enhanced agent executor robustness by converting non-string tool observations to JSON strings instead of throwing an error, with a warning logged for such cases.
  • MCP Client Storage Refactor: Refactored the internal MCP client storage from an array to a Map for more efficient tracking and management of server configurations.
  • Typo Fix: Corrected a typo from mineType to mimeType in relevant code sections.
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.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Oct 24, 2025

Important

Review skipped

Review was skipped due to path filters

⛔ Files ignored due to path filters (28)
  • 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-mcp/src/locales/en-US.schema.yml is excluded by !**/*.yml
  • packages/extension-mcp/src/locales/zh-CN.schema.yml is excluded by !**/*.yml
  • 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

此 PR:将工具非字符串观察值从致命错误改为记录并 stringify;为 MCP 配置与工具项添加可选/默认超时并把超时传入调用包装;将 MCP 客户端存储从数组改为 Map 并相应调整迭代与注册逻辑;修复 MIME 类型到文件后缀的映射与拼写错误,并新增 ToolException 导出。

Changes

Cohort / File(s) 变更摘要
工具观察值处理
packages/core/src/llm-core/agent/executor.ts
将当工具返回非字符串观察值时抛出运行时错误的逻辑改为:记录警告并使用 JSON.stringify(observation) 转为字符串,继续后续处理(在两处相似代码路径中均修改)。
MCP 配置:超时字段
packages/extension-mcp/src/index.ts
Config 类型与 schema 中为 server 条目添加可选 timeout?: number,并为 tools 条目添加 timeout(默认 60),导出类型同步更新。
MCP 客户端服务重构
packages/extension-mcp/src/service.ts
_clientsClient[] 改为 Map<Config['server'][0], Client>;更新连接、迭代、注册、停止等逻辑以适配 Map;在全局/每工具数据结构中加入可选 timeout?: number,并将计算得到的 timeout 注入每次工具调用的 config 中;get clients() 改为返回 Map。
资源存储与 MIME 处理
packages/extension-mcp/src/utils.ts
修正 mineTypemimeType;引入 mime-types 库,将 MIME 映射为文件后缀并在 putResourceToStorage 中校验支持性,生成标准化文件名 file.{extension};新增并导出 ToolException 类与 isToolException 类型保护。
Manifest
package.json
依赖或元数据更新以支持新增的 mime-types(在 manifest 中体现)。

Sequence Diagram(s)

sequenceDiagram
    participant Agent as Agent Executor
    participant Service as MCP Client Service
    participant MCP as MCP / Tool
    participant Schema as Schema/Config
    participant Result as Result Handler

    rect rgba(120,200,255,0.08)
    Note over Service,Schema: 启动时注册工具并计算超时(tool/server/default)
    Service->>Schema: 读取 server/tool timeout
    Schema-->>Service: 返回 timeout
    end

    Agent->>Service: 构建工具调用(含 config.timeout)
    Service->>MCP: 调用工具 (含 timeout)
    alt 工具返回字符串
        MCP-->>Service: 字符串观察值
        Service-->>Agent: 字符串观察值
        Agent->>Result: 继续处理
    else 工具返回非字符串
        MCP-->>Service: 非字符串观察值
        Service->>Service: 记录警告并 stringify
        Service-->>Agent: 字符串观察值
        Agent->>Result: 继续处理
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Poem

🐰 我在代码地里跳跃一圈,超时与后缀都带回家,
非字符串的观察值被我轻声 stringify,
客户端排成 Map 队列,工具口袋有了 timeout,
MIME 找到真名,文件不再迷路,
小兔一笑,提交里藏着胡萝卜的祝贺。

Pre-merge checks and finishing touches

❌ Failed checks (1 warning, 1 inconclusive)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
Linked Issues Check ❓ Inconclusive 针对#612(超时配置支持):raw_summary显示packages/extension-mcp/src/index.ts中为server和tool条目添加了timeout字段,packages/extension-mcp/src/service.ts实现了超时逻辑处理,包括工具级和服务器级超时的计算和应用,充分满足该需求。针对#611(文件扩展名生成和typo修复):packages/extension-mcp/src/utils.ts中导入了mime-types库、将mineType修复为mimeType、并从MIME类型派生正确的文件扩展名而非直接使用MIME类型字符串,满足前两个子目标。然而,#611中关于确保MCP返回的图像被正确输出到AI/用户的第三个目标在提供的raw_summary中未明确体现,无法确认该部分需求是否已完全实现。 建议审查者确认packages/extension-mcp/src/utils.ts中的putResourceToStorage函数是否已实现将MIME返回的图像内容通过content blocks正确传播到AI/用户的逻辑,或确认该部分功能是否在其他已进行的代码变更中处理。此外,可补充raw_summary来明确此项是否已覆盖。
✅ Passed checks (3 passed)
Check name Status Explanation
Title Check ✅ Passed PR标题"[Fix] Improve MCP tool handling and timeout support"清晰且与代码变更密切相关。根据raw_summary,此PR的主要改动涉及三个方面:添加超时配置支持(#612)、修复MIME类型相关的文件扩展名生成问题(#611)以及在agent executor中改进非字符串工具观测的处理。标题准确概括了这些关键改动,特别是突出了MCP工具处理和超时支持这两个核心主题,没有使用模糊措辞。
Out of Scope Changes Check ✅ Passed 从raw_summary分析,所有代码变更都与关联问题直接相关或为其提供必要支持:agent executor中的工具观测处理改进与问题描述的改善工具处理一致;index.ts和service.ts中的超时配置变更直接满足#612需求;utils.ts中的MIME类型修复和mime-types依赖添加直接满足#611的前两个子目标;客户端存储从数组改为Map是支持按服务器配置跟踪以实现超时功能的必要架构改动。未发现与关联问题范围无关的改动。
Description Check ✅ Passed PR描述与代码变更内容相关,并提供了充分的背景信息。描述清晰地列出了关联的bug修复(#612和#611)、具体的改动内容(如从数组重构为Map存储、添加mime-types依赖、拼写错误修复)以及改动的目的。描述的各个要点都能在raw_summary中找到对应,包括超时配置、MIME类型查找和工具观测处理,说明描述准确反映了本PR的实质内容。

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.

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 to the MCP extension. The support for configurable timeouts at both the server and tool level is a great addition for managing tool execution. The refactoring of client storage to a Map is a good architectural change, and the fix for file extension generation using mime-types makes file handling more robust. The change to gracefully handle non-string tool observations also improves the agent's resilience.

I've found one issue in the timeout calculation logic where there's a unit mismatch and incorrect handling of a 0 timeout value. My review includes a specific suggestion to fix this. Overall, this is a solid set of changes.

Comment thread packages/extension-mcp/src/service.ts Outdated
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: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
packages/core/src/llm-core/agent/executor.ts (1)

587-591: 存在不一致的错误处理逻辑。

Lines 728-733 已将非字符串观察值的处理从抛出错误改为记录警告并转换为 JSON 字符串,但此处(lines 587-591)仍然抛出错误。这导致两个相似的代码路径对相同情况的处理不一致,可能造成不可预测的行为。

建议应用以下修复以保持一致性:

                         observation = tool
                             ? await tool.invoke(
                                   action.toolInput,
                                   patchConfig(config, {
                                       callbacks: runManager?.getChild()
                                   })
                               )
                             : `${action.tool} is not a valid tool, try another one.`
                         if (typeof observation !== 'string') {
-                            throw new Error(
-                                'Received unsupported non-string response from tool call.'
-                            )
+                            logger.warn(
+                                `Tool ${action.tool} returned non-string observation`,
+                                observation
+                            )
+                            observation = JSON.stringify(observation)
                         }
packages/extension-mcp/src/utils.ts (1)

492-492: 修复参数名称中的拼写错误。

函数参数名称仍为 mineType(拼写错误),但在函数内部使用时却是正确的 mimeType(line 499, 502)。这与 PR 目标(修复 issue #611 中的 mineType 拼写错误)不一致。

应用以下修复:

 async function putResourceToStorage(
     ctx: Context,
     blob: string | Buffer,
-    mineType: string
+    mimeType: string
 ) {
     if (!ctx.chatluna_storage) {
         return
     }
 
     const buffer = typeof blob === 'string' ? Buffer.from(blob, 'base64') : blob
-    const extension = mimeTypes.extension(mineType)
+    const extension = mimeTypes.extension(mimeType)
 
     if (!extension) {
-        throw new Error(`Unsupported mime type: ${mineType}`)
+        throw new Error(`Unsupported mime type: ${mimeType}`)
     }
 
     const fileName = `file.${extension}`
     return await ctx.chatluna_storage.createTempFile(buffer, fileName)
 }
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e52faaa and 6b23950.

⛔ Files ignored due to path filters (1)
  • packages/extension-mcp/package.json is excluded by !**/*.json
📒 Files selected for processing (4)
  • packages/core/src/llm-core/agent/executor.ts (1 hunks)
  • packages/extension-mcp/src/index.ts (3 hunks)
  • packages/extension-mcp/src/service.ts (6 hunks)
  • packages/extension-mcp/src/utils.ts (3 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
packages/extension-mcp/src/service.ts (1)
packages/extension-mcp/src/index.ts (2)
  • Config (26-41)
  • Config (43-67)
⏰ 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: build
  • GitHub Check: lint
🔇 Additional comments (9)
packages/core/src/llm-core/agent/executor.ts (1)

728-733: 改进非字符串观察值的处理逻辑。

将抛出错误改为记录警告并转换为 JSON 字符串是一个很好的防御性修复,使得工具调用更加健壮。不过请确保同时修复 lines 587-591 处的类似逻辑以保持一致性。

packages/extension-mcp/src/index.ts (2)

32-32: 超时配置已正确添加。

为工具配置添加了超时字段,默认值为 60 秒。此配置将在 service.ts 中被转换为毫秒(乘以 1000),逻辑合理。


53-53: 服务器和工具级别的超时配置已添加。

在配置接口中正确添加了可选的 timeout 字段,支持在服务器级别和工具级别设置超时。这满足了 issue #612 中要求的自定义超时支持。

Also applies to: 62-62

packages/extension-mcp/src/utils.ts (2)

499-506: MIME 类型到文件扩展名的转换逻辑正确。

使用 mime-types 库正确地将 MIME 类型转换为文件扩展名,并在不支持的 MIME 类型时抛出错误。这修复了 issue #611 中提到的问题,不再使用硬编码的 MIME 类型作为文件后缀(如 xxx.image/png),而是使用正确的扩展名(如 file.png)。


163-163: Line 163 的拼写修复正确。

此处已将 content.mineType 正确修复为 content.mimeType,符合 PR 目标。

packages/extension-mcp/src/service.ts (4)

15-15: 客户端存储重构为 Map 结构。

_clients 从数组重构为 Map<Config['server'][0], Client> 是一个很好的改进,能够更好地追踪服务器配置与客户端的对应关系,便于后续根据服务器配置查找和管理客户端。


226-228: 超时配置已正确传递给工具调用。

将超时配置通过 config 对象传递给 callTool 函数,确保工具调用时能够使用配置的超时值。这满足了 issue #612 的需求,支持为 MCP 工具设置自定义超时。


146-146: Map 操作已正确更新。

客户端的添加和存在性检查已正确更新为使用 Map 的 setsize 方法,与新的数据结构保持一致。

Also applies to: 158-158


266-269: 停止方法已正确更新。

stop() 方法正确地遍历 Map 的所有客户端值,关闭每个客户端连接,并在最后清空 Map。这确保了资源的正确释放。

Comment thread packages/extension-mcp/src/service.ts
Fix timeout calculation to properly handle default values and convert to milliseconds correctly.
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: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/extension-mcp/src/utils.ts (1)

489-507: 修复参数名称中的拼写错误。

函数参数名称在第 492 行仍然是 mineType(拼写错误),应该是 mimeType。这与 PR 目标不一致,PR 的目标是修复所有 mimeType 拼写错误的出现位置。

此外,使用 mime-types 库来正确映射 MIME 类型到文件扩展名是一个很好的改进,解决了 issue #611 中提到的文件扩展名问题。

应用此差异修复参数名称:

 async function putResourceToStorage(
     ctx: Context,
     blob: string | Buffer,
-    mineType: string
+    mimeType: string
 ) {
     if (!ctx.chatluna_storage) {
         return
     }
 
     const buffer = typeof blob === 'string' ? Buffer.from(blob, 'base64') : blob
-    const extension = mimeTypes.extension(mineType)
+    const extension = mimeTypes.extension(mimeType)
 
     if (!extension) {
-        throw new Error(`Unsupported mime type: ${mineType}`)
+        throw new Error(`Unsupported mime type: ${mimeType}`)
     }
 
     const fileName = `file.${extension}`
     return await ctx.chatluna_storage.createTempFile(buffer, fileName)
 }
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6b23950 and 870533b.

📒 Files selected for processing (2)
  • packages/extension-mcp/src/service.ts (6 hunks)
  • packages/extension-mcp/src/utils.ts (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/extension-mcp/src/service.ts
🧰 Additional context used
🪛 ESLint
packages/extension-mcp/src/utils.ts

[error] 20-20: 'Logger' is defined but never used.

(@typescript-eslint/no-unused-vars)

🪛 GitHub Check: CodeFactor
packages/extension-mcp/src/utils.ts

[warning] 20-20: packages/extension-mcp/src/utils.ts#L20
'Logger' is defined but never used. (@typescript-eslint/no-unused-vars)

⏰ 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 (2)
packages/extension-mcp/src/utils.ts (2)

28-42: 很好的错误处理改进!

新增的 ToolException 类和 isToolException 类型守卫为工具异常提供了结构化的错误处理。这使得错误识别更加明确,并支持更好的错误处理逻辑。


163-163: 正确修复了拼写错误。

已将 content.mineType 正确更正为 content.mimeType,解决了 PR 目标中提到的拼写错误问题。

Comment thread packages/extension-mcp/src/utils.ts Outdated
- Bump core package version to 1.3.0-alpha.74
- Bump extension-mcp version to 1.3.0-alpha.13
- Update peer dependencies across all adapter and extension packages
- Add timeout locale entries for MCP tool configuration
@dingyi222666 dingyi222666 merged commit 315469a into v1-dev Oct 24, 2025
3 of 5 checks passed
@dingyi222666 dingyi222666 deleted the fix-mcp branch October 27, 2025 12:38
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.

[Feature] 支持为 MCP 设置自定义超时 [Bug] MCP 扩展的图片保存后缀名bug

1 participant