Skip to content

feat: add MCP client sub-capability bridges#6136

Open
Last-emo-boy wants to merge 1 commit intoAstrBotDevs:masterfrom
Last-emo-boy:master
Open

feat: add MCP client sub-capability bridges#6136
Last-emo-boy wants to merge 1 commit intoAstrBotDevs:masterfrom
Last-emo-boy:master

Conversation

@Last-emo-boy
Copy link

• 补齐 AstrBot 对 MCP client 子能力的接线,并把这些能力接入现有 bot / dashboard 交互链路,使 MCP server 除普通 tools 外还能通过 AstrBot 使用 sampling、resources、roots、elicitation 和 prompts,且尽量不影响现有工具调用与会话流程。

Modifications / 改动点

  • 新增 MCP client 子能力桥接层,补齐并接入以下能力:

    • sampling
    • resources
    • roots
    • elicitation
    • prompts
  • 将 MCP server 的 resources / prompts 暴露为 AstrBot 可调用的 bridge tools,复用现有 FunctionTool 和 agent tool loop。

  • 为 MCP server 增加按服务粒度的 client_capabilities 配置,并在 ClientSession.initialize 时按配置声明能力。

  • 优化 stdio MCP server 接入,忽略空行和明显非 JSON-RPC 的启动输出,避免因 npm run 横幅导致解析报错。

  • 优化 WebChat 下的 elicitation 交互:

    • 枚举项显示为按钮
    • 支持额外自定义输入
    • 支持 cancel
    • 前端直接回复 pending elicitation,不再额外发起新的 chat run
  • 优化 bot 场景下的 elicitation 解析:

    • 支持自然语言 key-value 回复
    • 规则解析失败时可回退到 LLM 生成 JSON,再做 schema 校验
  • 补充 MCP bridge、dashboard、stdio 容错、chat 交互等测试,并更新中英文文档与 changelog。

  • This is NOT a breaking change. / 这不是一个破坏性变更。

Screenshots or Test Results / 运行截图或测试结果

本地已执行并通过:

  • uv sync
  • uv run ruff format --check .
  • uv run ruff check .
  • uv run pytest tests/unit/test_mcp_subcapability_bridge.py tests/unit/test_mcp_resource_bridge.py tests/unit/test_mcp_prompt_bridge.py tests/unit/test_mcp_stdio_client.py tests/test_dashboard.py tests/unit/test_astr_agent_tool_exec.py tests/test_tool_loop_agent_runner.py tests/unit/test_astr_main_agent.py -q
    • 结果:153 passed
  • cd dashboard && pnpm install && pnpm i --save-dev @types/markdown-it && pnpm run build
    • 结果:通过
  • 本地 smoke test:
    • 启动 uv run main.py
    • 检查 http://localhost:6185
    • 结果:通过
  • cd docs && npm install && npm run docs:build
    • 结果:通过

Checklist / 检查清单

  • 😊 如果 PR 中有新加入的功能,已经通过 Issue / 邮件等方式和作者讨论过。/ If there are new features added in the PR, I have discussed it with the authors through issues/emails, etc.
  • 👀 我的更改经过了良好的测试,并已在上方提供了“验证步骤”和“运行截图”。/ My changes have been well-tested, and "Verification Steps" and "Screenshots" have been provided above.
  • 🤓 我确保没有引入新依赖库,或者引入了新依赖库的同时将其添加到了 requirements.txtpyproject.toml 文件相应位置。/ I have ensured that no new dependencies are introduced, OR if new dependencies are introduced, they have been added to the appropriate locations in requirements.txt and pyproject.toml.
  • 😮 我的更改没有引入恶意代码。/ My changes do not introduce malicious code.

补齐 AstrBot 对 MCP client 子能力的接线,并把能力接入现有 bot / dashboard 交互链路,在尽量不影响现有工具流的前提下支持更完整的 MCP 使用场景。
Copy link
Contributor

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Sorry @Last-emo-boy, your pull request is larger than the review limit of 150000 diff characters

@Last-emo-boy Last-emo-boy marked this pull request as ready for review March 12, 2026 15:09
@dosubot dosubot bot added the size:XXL This PR changes 1000+ lines, ignoring generated files. label Mar 12, 2026
@Last-emo-boy Last-emo-boy marked this pull request as draft March 12, 2026 15:09
@dosubot dosubot bot added area:core The bug / feature is about astrbot's core, backend area:platform The bug / feature is about IM platform adapter, such as QQ, Lark, Telegram, WebChat and so on. area:webui The bug / feature is about webui(dashboard) of astrbot. labels Mar 12, 2026
@gemini-code-assist
Copy link
Contributor

Warning

Gemini is experiencing higher than usual traffic and was unable to create the summary. Please try again in a few hours by commenting /gemini summary.

@Last-emo-boy Last-emo-boy marked this pull request as ready for review March 12, 2026 15:12
@dosubot
Copy link

dosubot bot commented Mar 12, 2026

Related Documentation

1 document(s) may need updating based on files changed in this PR:

AstrBotTeam's Space

pr4697的改动
View Suggested Changes
@@ -376,7 +376,112 @@
 
 [PR #5993](https://github.com/AstrBotDevs/AstrBot/pull/5993) 对 MCP(Model Context Protocol)客户端初始化流程进行了重大优化,从阻塞系统启动改为后台异步初始化,提升了系统启动速度和容错能力。
 
-**后台初始化机制:**
+#### MCP 客户端子能力桥接(PR #6136)
+
+[PR #6136](https://github.com/AstrBotDevs/AstrBot/pull/6136) 扩展了 AstrBot 的 MCP 客户端,在基础工具调用之外支持 MCP 协议的额外子能力,使 MCP 服务器能够通过 AstrBot 使用 sampling、resources、roots、elicitation 和 prompts。
+
+**新增 MCP 子能力支持:**
+
+1. **Resources Bridge(`mcp_resource_bridge.py`)**:
+   - 将 MCP 服务器资源暴露为可调用的桥接工具,集成到 AstrBot 的 FunctionTool 系统
+   - 提供以下工具:
+     - `mcp_{server}_list_resources`:列出 MCP 服务器暴露的可读资源
+     - `mcp_{server}_read_resource`:通过 URI 读取特定 MCP 资源
+     - `mcp_{server}_list_resource_templates`(可选):列出 MCP 资源 URI 模板
+   - 支持文本和二进制资源内容,图片资源可作为 `EmbeddedResource` 嵌入响应
+
+2. **Prompts Bridge(`mcp_prompt_bridge.py`)**:
+   - 将 MCP 服务器 prompts 暴露为可调用的桥接工具,使 prompts 可通过 Agent 工具循环调用
+   - 提供以下工具:
+     - `mcp_{server}_list_prompts`:列出 MCP 服务器暴露的 prompts
+     - `mcp_{server}_get_prompt`:通过名称获取特定 MCP prompt,可选提供 prompt 参数
+   - 支持参数化 prompt 模板,参数作为字符串键值对发送到 MCP 服务器
+
+3. **Elicitation Support(`mcp_elicitation_registry.py`)**:
+   - 实现 MCP elicitation 处理机制,支持用户交互流程
+   - 包含以下组件:
+     - **Elicitation 注册表**:按 UMO(统一消息来源)追踪待处理的 elicitation 请求
+     - **回调机制**:处理 MCP 服务器的 elicitation 请求
+     - **WebChat UI 支持**:在 WebChat 中提供增强的 elicitation 交互体验
+       - 枚举值显示为按钮(`ElicitationCard.vue` 组件)
+       - 支持自定义输入字段
+       - 支持 cancel、decline、accept 操作
+     - **Bot 场景支持**:支持自然语言键值对回复,解析失败时可回退到 LLM 生成 JSON 并进行 schema 校验
+   - Elicitation 超时时间可按服务器配置(默认 300 秒)
+
+4. **Sampling Capabilities**:
+   - 新增 sampling 回调支持,允许 MCP 服务器通过 AstrBot 请求 AI 模型生成补全
+   - Sampling 能力可按 MCP 服务器配置启用/禁用
+   - 初始集成限制:不支持 `includeContext`、工具辅助 sampling 和多模态 sampling 输入
+
+5. **Roots Handling**:
+   - 实现 `list_roots_callback`,允许 MCP 服务器查询可用的 root 上下文
+   - 支持路径别名解析(如 `data`、`temp`、`config`、`plugins` 等)
+   - 可按 MCP 服务器配置 root 路径列表
+
+**配置增强:**
+
+- **按服务器配置 client_capabilities**:
+  - 在 MCP 服务器配置中新增 `client_capabilities` 字段,支持按服务器粒度启用/禁用 MCP 子能力
+  - 配置项包括:
+    - `elicitation.enabled`:是否启用 elicitation 支持(默认 `false`)
+    - `elicitation.timeout_seconds`:elicitation 超时时间(默认 300 秒)
+    - `sampling.enabled`:是否启用 sampling 支持(默认 `false`)
+    - `roots.enabled`:是否启用 roots 支持(默认 `false`)
+    - `roots.paths`:root 路径列表(默认 `["data", "temp"]`)
+  - 配置格式支持向后兼容(布尔值自动转换为对象格式)
+
+- **ClientSession 初始化集成**:
+  - `ClientSession.initialize` 时根据服务器配置声明对应的 client_capabilities
+  - 桥接层(`MCPClientSubCapabilityBridge`)根据配置动态启用相应能力
+
+**集成改进:**
+
+- **工具管理器集成**(`func_tool_manager.py`):
+  - 修改工具注册逻辑以处理 MCP bridge 工具(resources、prompts)
+  - MCP bridge 工具与普通 MCP 工具共享命名空间,支持统一的工具调用流程
+
+- **Agent 内部阶段集成**(`internal.py`):
+  - 更新 Agent 内部处理阶段以支持 MCP 子能力工作流
+  - Elicitation 请求与 Agent 交互上下文绑定,确保请求-响应匹配
+
+- **Dashboard 路由集成**:
+  - `chat.py`、`live_chat.py`、`open_api.py`、`tools.py` 等路由已更新以暴露 MCP 子能力
+  - 新增 `/api/chat/reply_elicitation` 端点,支持 WebChat 中的 elicitation 回复
+
+- **前端更新**:
+  - 新增 `ElicitationCard.vue` 组件,提供表单式 elicitation UI
+  - 更新 `MessageList.vue`、`Chat.vue`、`StandaloneChat.vue`,集成 elicitation 消息渲染
+  - 新增 `useMessages.ts` 中的 `replyToElicitation()` 方法,支持前端直接回复 elicitation
+  - 国际化支持:中英日文翻译已覆盖 MCP elicitation 功能(`chat.json` 文件)
+
+**基础设施改进:**
+
+- **容错性 stdio MCP 客户端**(`mcp_stdio_client.py`):
+  - 优化 stdio MCP 服务器接入,忽略空行和非 JSON-RPC 的启动输出
+  - 避免因 `npm run` 横幅等启动日志导致解析报错
+  - 增强 SSE 缓冲区保护,防止无分隔符场景下 buffer 无界增长
+
+- **WebChat 事件处理增强**(`webchat_event.py`):
+  - 新增 `set_message_type()` 方法,支持设置消息类型(如 `elicitation`)
+  - Elicitation 消息通过 WebChat 平台的自定义消息类型传递,确保前端正确渲染
+
+**测试覆盖:**
+
+新增以下测试文件,确保 MCP 子能力的正确性和稳定性:
+- `test_mcp_subcapability_bridge.py`:MCP 子能力桥接层核心逻辑测试
+- `test_mcp_resource_bridge.py`:MCP resources 桥接工具测试
+- `test_mcp_prompt_bridge.py`:MCP prompts 桥接工具测试
+- `test_mcp_stdio_client.py`:容错性 stdio 客户端测试
+- 更新 `test_dashboard.py`,新增 elicitation 相关 API 测试
+
+**文档更新:**
+
+中英文 MCP 使用文档(`docs/zh/use/mcp.md` 和 `docs/en/use/mcp.md`)已更新,补充 MCP 子能力桥接的使用说明和配置示例。
+
+该更新确保 MCP 服务器可以通过 AstrBot 利用完整的 MCP 协议规范,不仅限于基础工具调用,为 MCP 生态系统的集成提供更全面的支持。
+
+**后台初始化机制(PR #5993):**
 - MCP 客户端初始化现在在提供商加载完成后异步执行,不再阻塞系统启动
 - 初始化任务通过 `_init_mcp_clients_bg()` 后台任务管理,由 `ProviderManager._mcp_init_task` 追踪
 - 系统启动时 MCP 工具可能尚未完全可用,但不影响其他功能正常运行

[Accept] [Decline]

Note: You must be authenticated to accept/decline updates.

How did I do? Any feedback?  Join Discord

@dosubot dosubot bot added area:provider The bug / feature is about AI Provider, Models, LLM Agent, LLM Agent Runner. feature:chatui The bug / feature is about astrbot's chatui, webchat labels Mar 12, 2026
@Last-emo-boy
Copy link
Author

/gemini summary

@gemini-code-assist
Copy link
Contributor

Summary of Changes

This pull request significantly expands AstrBot's integration with Model Context Protocol (MCP) servers by introducing a robust bridging layer for several client-side sub-capabilities. It enables MCP servers to utilize AstrBot's conversational and agentic features for advanced interactions such as AI model sampling, user elicitation for missing information, and dynamic management of resources and prompts. This enhancement allows for more interactive and capable MCP-powered tools within the AstrBot ecosystem, improving both developer flexibility and user experience.

Highlights

  • MCP Client Sub-Capabilities Integration: Introduced support for 'sampling', 'resources', 'roots', 'elicitation', and 'prompts' within the MCP client, allowing MCP servers to leverage these functionalities through AstrBot.
  • Resource and Prompt Bridging: Exposed MCP server 'resources' and 'prompts' as callable bridge tools within AstrBot's FunctionTool system, enabling agents to interact with them.
  • Granular Capability Configuration: Added 'client_capabilities' configuration per MCP server, allowing fine-grained control over which sub-capabilities are enabled (e.g., 'elicitation', 'sampling', 'roots').
  • Improved stdio Server Handling: Enhanced the stdio MCP client to tolerate non-JSON-RPC output (like 'npm run' banners) and empty lines, preventing parsing errors during server startup.
  • Enhanced Elicitation Interaction: Optimized the user experience for elicitation requests in WebChat with interactive buttons for enumerated options, support for custom input, and a cancel option. For bot scenarios, natural language key-value replies are supported, with an LLM fallback for schema validation.
  • Comprehensive Testing and Documentation: Added new unit tests for the MCP sub-capability bridge, resource bridge, prompt bridge, and tolerant stdio client, alongside updates to the dashboard tests and both English and Chinese documentation.
Changelog
  • astrbot/core/agent/mcp_client.py
    • Updated type hints, integrated new MCP bridge modules, enhanced configuration parsing to include client capabilities, added new attributes for managing prompts and resources, implemented methods for loading resource and prompt capabilities, and refined reconnection and cleanup logic to manage sub-capability states.
  • astrbot/core/agent/mcp_elicitation_registry.py
    • Added a new module to manage pending MCP elicitation requests, including data structures for replies and a context manager for handling elicitation lifecycles.
  • astrbot/core/agent/mcp_prompt_bridge.py
    • Introduced a new module to define and build MCP prompt-related tools, allowing AstrBot agents to list and retrieve prompts from MCP servers.
  • astrbot/core/agent/mcp_resource_bridge.py
    • Added a new module to define and build MCP resource-related tools, enabling AstrBot agents to list, read, and discover resource templates from MCP servers.
  • astrbot/core/agent/mcp_stdio_client.py
    • Implemented a new tolerant stdio client for MCP, designed to filter out non-JSON-RPC output from server processes, improving robustness.
  • astrbot/core/agent/mcp_subcapability_bridge.py
    • Created a new core module to bridge MCP client sub-capability requests (sampling, elicitation, roots) into AstrBot's runtime, including configuration normalization and interactive handling.
  • astrbot/core/pipeline/process_stage/method/agent_sub_stages/internal.py
    • Modified to incorporate the capture of pending MCP elicitation replies, ensuring that user responses to elicitation requests are processed correctly within the agent's workflow.
  • astrbot/core/platform/sources/webchat/webchat_event.py
    • Updated to support the 'elicitation' message type, allowing structured JSON payloads for interactive elicitation forms in the WebChat interface.
  • astrbot/core/provider/func_tool_manager.py
    • Refactored MCP configuration loading and saving to use Path objects and normalization, and extended tool registration to include newly introduced MCP resource and prompt bridge tools.
  • astrbot/dashboard/routes/chat.py
    • Added a new API endpoint '/api/chat/respond_elicitation' to handle user replies to MCP elicitation requests from the dashboard, and updated message streaming to support elicitation message types.
  • astrbot/dashboard/routes/live_chat.py
    • Modified the live chat message handling to correctly process and display 'elicitation' type messages.
  • astrbot/dashboard/routes/open_api.py
    • Updated the OpenAPI WebSocket message handling to support the new 'elicitation' message type.
  • astrbot/dashboard/routes/tools.py
    • Enhanced the MCP server information API to include the names of resource and prompt bridge tools, and updated the tool listing to correctly identify MCP-bound tools.
  • dashboard/src/components/chat/Chat.vue
    • Updated to pass elicitation submission functionality to the MessageList component, enabling interactive elicitation in the chat UI.
  • dashboard/src/components/chat/MessageList.vue
    • Enhanced to render interactive elicitation cards and manage their submission state, including a new prop for handling elicitation replies.
  • dashboard/src/components/chat/StandaloneChat.vue
    • Modified to integrate elicitation submission functionality, similar to Chat.vue, for standalone chat instances.
  • dashboard/src/components/chat/message_list_comps/ElicitationCard.vue
    • Added a new Vue component to render interactive elicitation forms, supporting URL-based and form-based elicitation with buttons, text fields, and boolean switches.
  • dashboard/src/components/chat/message_list_comps/MessagePartsRenderer.vue
    • Updated to include the ElicitationCard for rendering elicitation message parts within the chat display.
  • dashboard/src/composables/useMessages.ts
    • Extended with new TypeScript interfaces for ElicitationField and ElicitationPayload, added logic to normalize and handle elicitation message types, and implemented submitElicitationResponse for API interaction.
  • dashboard/src/i18n/locales/en-US/features/chat.json
    • Added new English localization strings for the elicitation feature.
  • dashboard/src/i18n/locales/zh-CN/features/chat.json
    • Added new Chinese localization strings for the elicitation feature.
  • docs/en/use/mcp.md
    • Expanded the English documentation to detail the new MCP client sub-capabilities (sampling, elicitation, roots), stdio server notes, and the resource and prompt bridging features.
  • docs/zh/use/mcp.md
    • Expanded the Chinese documentation to detail the new MCP client sub-capabilities (sampling, elicitation, roots), stdio server notes, and the resource and prompt bridging features.
  • tests/test_dashboard.py
    • Added new asynchronous tests to verify the dashboard API's handling of MCP client capabilities, resource and prompt bridge tools, and the 'respond_elicitation' endpoint.
  • tests/unit/test_mcp_prompt_bridge.py
    • Introduced new unit tests to validate the functionality of the MCP prompt bridge, including tool registration, listing, and retrieval with arguments.
  • tests/unit/test_mcp_resource_bridge.py
    • Added new unit tests to verify the MCP resource bridge's functionality, covering resource listing, template listing, and reading resources.
  • tests/unit/test_mcp_stdio_client.py
    • Created new unit tests to ensure the tolerant stdio client correctly filters non-protocol output and integrates with the MCP client.
  • tests/unit/test_mcp_subcapability_bridge.py
    • Implemented new unit tests to thoroughly test the MCP sub-capability bridge, including configuration, roots handling, sampling, and elicitation logic.
Activity
  • Gemini bot initially failed to generate a summary due to high traffic.
  • Dosu bot provided a comprehensive summary of the pull request, detailing modifications, new features, and integrations.
  • The author, Last-emo-boy, requested a Gemini summary again.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:core The bug / feature is about astrbot's core, backend area:platform The bug / feature is about IM platform adapter, such as QQ, Lark, Telegram, WebChat and so on. area:provider The bug / feature is about AI Provider, Models, LLM Agent, LLM Agent Runner. area:webui The bug / feature is about webui(dashboard) of astrbot. feature:chatui The bug / feature is about astrbot's chatui, webchat size:XXL This PR changes 1000+ lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant