Skip to content

Conversation

@dingyi222666
Copy link
Member

This PR improves the MCP (Model Context Protocol) client initialization and tool selector logic, along with domain-based header configuration for request tools.

Bug Fixes

  • Improve MCP client initialization and tool selector logic in extension-mcp and extension-tools
  • Fix configuration parsing and tool registration in extension-mcp

New Features

  • Add domain-based header configuration for request tools, allowing more flexible HTTP request customization

Other Changes

  • Enhanced error handling and robustness in MCP client lifecycle management

…est tools

Add requestHeaders configuration to allow setting custom headers based on domain matching patterns. This enables different headers to be applied to different domains when using the web_fetcher and web_poster tools.

- Add requestHeaders config array with matcher and headers fields
- Implement getHeadersForUrl() function using micromatch for domain pattern matching
- Update RequestsGetTool and RequestsPostTool to support headerConfigs
- Add i18n translations for new configuration options in zh-CN and en-US
- Headers are merged with default headers, with matched headers taking precedence

Example usage:
requestHeaders:
  - matcher: "api.github.com"
    headers:
      Authorization: "Bearer token123"
  - matcher: "*.example.com"
    headers:
      X-Custom-Header: "value"
… and tool selector logic

- Move ChatLunaPlugin instance creation to module scope to avoid initialization issues
- Upgrade @modelcontextprotocol/sdk to 1.19.1 and remove unused json-schema-to-zod dependency
- Add client metadata (title, description) for better MCP protocol compliance
- Improve logging messages for better clarity during initialization and connection
- Fix prepareClient to return true only when at least one server connects successfully
- Enhance cron tool selector to check all history messages instead of only the last one
- Add proper type annotation for fs tool selector
- Remove redundant empty lines in fs tool registrations
@gemini-code-assist
Copy link
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 by dingyi222666 focuses on enhancing the MCP client's initialization and tool selection mechanisms, alongside introducing domain-specific header configurations for request tools. It includes dependency updates, significant refactoring for robustness, and improvements to tool activation logic.

Highlights

  • Intent: This pull request aims to improve the Model Context Protocol (MCP) client initialization and tool selector logic across the extension-mcp and extension-tools packages. It also introduces a new feature for domain-based header configuration for request tools and enhances error handling.
  • Key Changes: The PR updates the MCP SDK dependency, refactors MCP client initialization for better robustness and logging, and introduces a significant new feature in extension-tools allowing domain-based custom HTTP headers for request tools. Additionally, it refines tool selection logic for cron and request tools and improves type safety.
  • Detailed Changes: - extension-mcp: Upgraded @modelcontextprotocol/sdk to ^1.19.1 and removed json-schema-to-zod. The ChatLunaPlugin instance is now initialized once in index.ts and reused in service.ts. MCP client initialization now includes title and description, features enhanced logging, and robust connection checks (client is 'prepared' only if at least one server connects successfully). Type assertions for tool schemas were also updated.
  • extension-tools: Introduced a new requestHeaders configuration option for the request plugin, enabling users to define custom HTTP headers that are applied based on URL domain matching using micromatch. The cron tool's selector now evaluates all messages in the history for fuzzy matching, not just the last one. The request tool's selector was made more resilient to undefined configurations. Type safety was improved for the fsSelector function, and the web_post tool was renamed to web_poster. Localization files (en-US.schema.yml, zh-CN.schema.yml) were updated to reflect the new requestHeaders configuration.
  • Reviewer Notes: Reviewers should pay close attention to the refactoring of ChatLunaPlugin initialization in extension-mcp to ensure no unintended side effects. The new domain-based header configuration in extension-tools is a core feature; its implementation, especially the micromatch usage and header merging logic, should be thoroughly reviewed and tested. The updated tool selector logic for cron and request tools should be verified for correct behavior and improved tool activation. The dependency update in extension-mcp might bring changes from the SDK that could impact existing functionality.
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
Contributor

coderabbitai bot commented Oct 8, 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

该变更引入共享的 ChatLunaPlugin 实例并调整 MCP 客户端就绪逻辑(至少一台服务器可用);为请求工具新增按域匹配的请求头配置并在 GET/POST 中合并;cron 选择器改为扫描整个历史;强化 fs 工具类型注解;新增消息转发长度阈值与文本提取逻辑。

Changes

Cohort / File(s) Change Summary
MCP 插件集成与初始化
packages/extension-mcp/src/index.ts, packages/extension-mcp/src/service.ts
导入并导出共享 ChatLunaPlugin 实例;在 apply 中实例化并赋值;MCP 客户端构造增加 title/description;引入 availableServers 计数并调整连接/就绪判断(仅当 ≥1 台服务器可用时标记已就绪);日志与连接成功计数逻辑更新。
请求工具与配置:按域请求头
packages/extension-tools/src/config.ts, packages/extension-tools/src/plugins/request.ts
配置 Config 新增 requestHeaders(matcher + headers 列表,schema 已同步);新增 getHeadersForUrl 以基于 hostname/micromatch 匹配 headers;RequestsGet/RequestsPost 工具和接口添加 headerConfigs 字段并在请求时合并匹配到的 headers;web_post 重命名为 web_poster;apply 将全局配置下传至工具。
Cron 选择器行为
packages/extension-tools/src/plugins/cron.ts
由仅检查最后一条消息改为扫描全部历史消息内容来执行模糊匹配触发逻辑。
FS 工具类型强化
packages/extension-tools/src/plugins/fs.ts
显式导入 ChatLunaTool 并将 fsSelector 注解为 ChatLunaTool['selector'];若干格式调整,无行为变化。
消息转发阈值与文本提取
packages/core/src/chains/chain.ts, packages/core/src/config.ts
新增配置字段 forwardMsgMinLength(schema 同步);在 DefaultChatChainSender 中新增 getMessageText 并仅当 isForwardMsg 且文本长度超过阈值时才转发消息。

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor User
  participant Koishi as Koishi Context
  participant Plugin as ChatLunaPlugin (shared)
  participant MCP as MCP Client
  participant Servers as MCP Servers

  User->>Koishi: 启动 extension-mcp
  Koishi->>Plugin: new ChatLunaPlugin(ctx, config, "mcp-client", false)
  Koishi->>MCP: 初始化 (title, description)
  loop 连接各服务器
    MCP->>Servers: 尝试连接
    alt 连接成功
      MCP-->>MCP: availableServers += 1
    else 连接失败
      MCP-->>MCP: 记录失败日志
    end
  end
  alt availableServers >= 1
    MCP-->>Koishi: 就绪(注册/工具准备)
  else
    MCP-->>Koishi: 未就绪(无可用服务器)
  end
Loading
sequenceDiagram
  autonumber
  actor Agent
  participant Tool as RequestsGetTool / RequestsPostTool
  participant Matcher as Header Matcher (micromatch)
  participant HTTP as HTTP Client

  Agent->>Tool: 调用 (url, options.headers)
  Tool->>Matcher: getHeadersForUrl(url, headerConfigs)
  Matcher-->>Tool: matchedHeaders (可能为空)
  Tool-->>Tool: 合并 headers = {...options.headers, ...matchedHeaders}
  Tool->>HTTP: 发起请求 (url, headers)
  HTTP-->>Tool: 响应
  Tool-->>Agent: 返回结果
  note right of Matcher: 使用 hostname 与 matcher 列表匹配
Loading
sequenceDiagram
  autonumber
  actor System
  participant Sender as DefaultChatChainSender
  participant Config as Core Config

  System->>Sender: 请求转发(msgs, isForwardMsg)
  Sender->>Sender: text = getMessageText(msgs)
  Sender->>Config: 检查 forwardMsgMinLength
  alt isForwardMsg && text.length >= forwardMsgMinLength
    Sender->>System: 执行转发
  else
    Sender->>System: 跳过转发
  end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Poem

我是代码田里的小兔子,蹦蹦跳跳巡逻时,
MCP 连上几座山,至少一峰亮起灯。
网请求头随域变,星光贴在每条绳。
Cron 不只看最后句,全史皆能闻其声。
小兔轻嗅 FS 类型稳,消息长短也分明。 🐰✨

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Title Check ✅ Passed 标题“fix(extension-mcp,extension-tools): improve MCP client initialization and tool selector logic”清晰地描述了本次提交中对 MCP 客户端初始化和工具选择逻辑的改进,且使用了常见的前缀规范,与实际改动高度关联,尽管未提及域名请求头配置这一次要功能,但标题仍准确反映了主要改动内容。
Description Check ✅ Passed 拉取请求描述详细列出了对 MCP 客户端初始化和工具选择逻辑的改进、域名请求头配置的新功能以及错误处理增强等内容,与提交的实际改动高度匹配且不偏离主题。
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.

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
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 some great improvements, particularly the domain-based header configuration for request tools and the more robust MCP client initialization. The tool selector logic enhancement to check the entire history is also a valuable change.

I've identified a critical issue regarding the ChatLunaPlugin initialization that needs to be addressed, as well as a medium-severity issue concerning a potentially breaking change in a tool's name. Please see my detailed comments below.

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

🧹 Nitpick comments (2)
packages/extension-tools/src/plugins/request.ts (2)

12-31: 整体实现正确,建议增强错误可观测性。

getHeadersForUrl 函数的实现逻辑正确:

  • 使用 micromatch 进行模式匹配,{ dot: true } 选项正确处理子域名
  • 返回第一个匹配的配置,符合预期
  • 错误处理防止无效 URL 导致崩溃

不过,静默捕获所有错误可能会隐藏问题。建议在生产环境中记录解析失败的情况。

可选的改进建议:

     } catch (error) {
-        // Invalid URL, return empty headers
+        // Invalid URL, return empty headers
+        // 可以考虑添加日志记录以便调试
+        // console.warn(`Failed to parse URL for header matching: ${url}`, error)
     }

64-76: 改进了空值处理的健壮性。

使用 (config.requestSelector?.length ?? 0) === 0 替代之前的 > 0 检查,更明确地处理了 undefined 情况。

不过第 73 行的 config?.requestSelector || [] 有些冗余,因为上面已经检查过长度。但这种防御性编程也无害。

可选的简化建议:

-    config?.requestSelector || []
+    config.requestSelector!

因为在第 65 行已经确保了 requestSelector 存在且长度大于 0。

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 886bfa0 and e159dcb.

⛔ Files ignored due to path filters (3)
  • packages/extension-mcp/package.json is excluded by !**/*.json
  • packages/extension-tools/src/locales/en-US.schema.yml is excluded by !**/*.yml
  • packages/extension-tools/src/locales/zh-CN.schema.yml is excluded by !**/*.yml
📒 Files selected for processing (6)
  • packages/extension-mcp/src/index.ts (2 hunks)
  • packages/extension-mcp/src/service.ts (7 hunks)
  • packages/extension-tools/src/config.ts (2 hunks)
  • packages/extension-tools/src/plugins/cron.ts (2 hunks)
  • packages/extension-tools/src/plugins/fs.ts (2 hunks)
  • packages/extension-tools/src/plugins/request.ts (7 hunks)
🧰 Additional context used
🧬 Code graph analysis (5)
packages/extension-tools/src/plugins/cron.ts (1)
packages/core/src/utils/string.ts (2)
  • fuzzyQuery (29-37)
  • getMessageContent (150-166)
packages/extension-tools/src/plugins/fs.ts (1)
packages/core/src/llm-core/platform/types.ts (1)
  • ChatLunaTool (62-68)
packages/extension-mcp/src/index.ts (1)
packages/core/src/services/chat.ts (1)
  • ChatLunaPlugin (594-792)
packages/extension-tools/src/plugins/request.ts (2)
packages/core/src/utils/string.ts (2)
  • fuzzyQuery (29-37)
  • getMessageContent (150-166)
packages/core/src/services/chat.ts (1)
  • ChatLunaPlugin (594-792)
packages/extension-mcp/src/service.ts (2)
packages/core/src/services/chat.ts (1)
  • ChatLunaPlugin (594-792)
packages/extension-mcp/src/index.ts (2)
  • plugin (9-9)
  • logger (8-8)
⏰ 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 (4)
packages/extension-tools/src/plugins/request.ts (4)

42-62: LGTM!

工具实例化正确传递了 headerConfigs,使用空合并运算符 ?? 安全处理可选配置项。


93-97: LGTM!

RequestTool 接口和具体实现类正确添加了 headerConfigs 属性,类型定义准确,初始化为空数组是合理的默认值。

Also applies to: 114-114, 171-171


152-152: 确认破坏性更改及迁移支持

  • 工具名称已从 web_post 改为 web_poster,请手动核查所有外部引用(配置、文档、CI 脚本等)已同步更新。
  • 如仍有用户或集成依赖旧名称,需提供迁移指南或对旧名称做兼容层。
  • 发布说明中必须明确标注此破坏性变更。

139-142: 验证请求头合并顺序 当前合并为 { ...this.headers, ...matchedHeaders },matchedHeaders 会覆盖默认 headers;未在代码库中发现相关测试或文档,请确认该行为是否符合预期。

Add forwardMsgMinLength configuration option to control when messages should be sent as forward/merged messages. When set to 0, always use forward messages. When set to a value greater than 0, only messages exceeding that length will be sent as forward messages.

Changes:
- Add forwardMsgMinLength config option (0-400 range) in config.ts
- Implement length check logic in DefaultChatChainSender
- Add getMessageText helper method to calculate total message length
- Update localization files for both en-US and zh-CN

close #580
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: 1

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e159dcb and 19d4ecf.

⛔ Files ignored due to path filters (2)
  • packages/core/src/locales/en-US.schema.yml is excluded by !**/*.yml
  • packages/core/src/locales/zh-CN.schema.yml is excluded by !**/*.yml
📒 Files selected for processing (2)
  • packages/core/src/chains/chain.ts (2 hunks)
  • packages/core/src/config.ts (2 hunks)
⏰ 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/core/src/config.ts (1)

9-9: 配置添加正确。

新增的 forwardMsgMinLength 配置字段类型定义和验证规则都正确。默认值为 0 表示当 isForwardMsg 启用时转发所有非空消息。

Also applies to: 69-69

packages/core/src/chains/chain.ts (1)

723-727: 验证比较运算符是否符合预期。

当前使用 > 比较运算符,这意味着当 forwardMsgMinLength 设置为 10 时,只有长度 大于 10(即 11 及以上)的消息才会被转发。如果配置项语义是"最小长度",用户可能期望长度等于或大于 10 的消息被转发,这种情况下应使用 >= 运算符。

请确认以下行为是否符合预期:

  • forwardMsgMinLength = 0(默认值):转发所有长度 ≥ 1 的消息 ✓
  • forwardMsgMinLength = 10:仅转发长度 ≥ 11 的消息(而非 ≥ 10)

如果"最小长度"应该表示"至少此长度",请应用以下修复:

 if (
     this.config.isForwardMsg &&
-    this.getMessageText(messages).length >
+    this.getMessageText(messages).length >=
         this.config.forwardMsgMinLength
 ) {

Update core package version and all peer dependencies across the monorepo to version 1.3.0-alpha.54.

Affected packages:
- core: 1.3.0-alpha.53 -> 1.3.0-alpha.54
- extension-mcp: 1.3.0-alpha.5 -> 1.3.0-alpha.6
- extension-tools: 1.3.0-alpha.15 -> 1.3.0-alpha.16
- All adapter and service packages peer dependency updated
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