Skip to content

fix(agent-core-v2): pin the initial tool baseline after startup MCP discovery - #5240

Merged
sailist merged 1 commit into
mainfrom
loop-421-stack/07-pin-initial-tool-baseline
Nov 23, 2026
Merged

sailist merged 1 commit into
mainfrom
loop-421-stack/07-pin-initial-tool-baseline

Conversation

@sailist

@sailist sailist commented Nov 23, 2026

Copy link
Copy Markdown
Collaborator

Part 7/7 of the loop stack onto main. Identical diff to #5217, previously reviewed and merged into the loop integration branch. Stacked on #5239; the shown diff contains only this PR's own changes.

Requirement or Bug

Resolve #4904。

2.6.0 引入的回归:会话在初始 MCP 发现完成前就固定了工具基线,启动较慢的 MCP 服务器发现的工具对整个会话不可见——tool_select.initialized 包含全部工具,但 llm.tools_snapshot 缺失这些工具,后续 turn 也不会恢复。本 PR 之后,启动期发现的 MCP 工具从首个请求起就在请求工具列表里。

Bug Reproduction Steps

See linked issue(慢速 stdio MCP 服务器 + 新会话立即提交 prompt,观察首个请求的 llm.tools_snapshot)。

Root Cause

根本修复,非绕过。

agent 的请求工具列表来自 loop 启动时钉死的基线(profile.tools),而不是 toolSelect 的工具目录。initializeLoop() 捕获基线时不等待 MCP 就绪,钉入的是启动瞬间的注册表快照;之后没有任何路径重建基线。启动期稍晚发现的 MCP 工具只进入 toolSelect 目录和公告,永远到不了请求——这就是 issue 里"目录有、请求没有"的分层错位。

修复把"等待 MCP 首轮发现 settle"放到钉基线之前:等待之后注册表必然完整(connected 事件同步注册工具,且先于连接尝试 resolve),此刻钉入的基线天然包含启动期发现的全部 MCP 工具。

Code Changes

核心思路:把 MCP 就绪等待收敛到 loop 启动这唯一一处,钉基线发生在等待之后;会话过程中不再有任何对 MCP 连接的 await,工具增删改全部走既有的事件驱动 reconcile。

 initializeLoop(initialTools?)
   …
+  if initialTools === undefined            // 自发现基线(主 agent、恢复会话)
+    await ISessionMcpHandle.ready          // 唯一等待点:首轮连接全部 settle
   tools = initialTools() ?? [...initialTools]  // fork/btw 显式继承基线,绕过等待
 AgentMcpService
-  loop.hooks.onWillBeginStep: await waitForInitialLoad   // 每 step 等待,冗余
-  toolExecutor.beforeExecute: await waitForInitialLoad   // 每工具执行等待,冗余
 AgentToolSelectService.reconcileForRequest
-  await mcpHandle.ready                                   // 每请求等待,冗余

关键决策:

决策 选择 没选 理由
等待点位置 initializeLoop 钉基线前 core loop 加 prepareInitialTools 钩子(issue 评论区的方案) 不改动 packages/core,不新增钩子机制,改动面最小
等待次数 仅启动时一次,之后事件驱动 保留每 step / 每请求等待 基线钉死后重复等待恒为 no-op,纯误导
initial 目录构建时机 维持首个请求时构建(与基线一致) 启动时同步构建 initial=current 启动时构建实测触发 DI 级联问题(unprovideUnit('reminder') 会级联 dispose AgentLoopService),留作后续项
fork/btw 显式继承父基线,绕过等待 子代理各自重新发现 保住 #4832 的 fork 平价不变量

阅读指南:先看 packages/agent-core-v2/src/agent/loop/loopService.ts 的 initializeLoop(全部修复就这一处等待),再看 mcpService.ts 与 toolSelectService.ts 的删除(纯收敛),测试看 toolSelect.e2e.test.ts 的启动发现三例与 forkParity.test.ts 的基线一致两例。可略读:changeset 与测试桩清理。

Behavior Changes and Affected Users

Behavior Before After Who relies on the old behavior Escape hatch
启动期发现的 MCP 工具 整个会话从请求中缺失(#4904) 首个请求起出现在请求工具列表 无(bug 本身) —
会话创建/恢复耗时 不等 MCP 连接 等待最慢 server 首轮连接 settle(per-server 启动超时兜底);TUI 默认启动是 sessionless,卡顿点落在首条 prompt TUI、kap-server POST /sessions、ACP session/new、desktop 打开会话 调低对应 server 的 startupTimeoutMs;不配置 MCP 无影响
启动等待期间的取消 可取消进行中的首个 turn(turn.ended cancelled) 等待发生在 turn 存在之前;等待期间提交的 prompt 可按 promptId 取消,且不发出任何请求 依赖 turn 级取消时序的客户端 按 promptId 取消
每 step / 每工具执行前的 MCP 就绪等待 存在(冗余) 移除 无——loop 启动后 ready 恒已解决,行为等价 —
启动→首请求窗口内新注册的 inline 工具 进入基线(旧钉入点在该窗口之后) 不进基线也不被告警(已知窄缺陷,deferred 工具经公告可加载,不受影响) 在该窗口内注册 inline 工具的集成方 窗口极窄(ready 已 resolve 后才连上的 server);后续可随"启动时构建 initial"一并解决

受影响模块与测试覆盖:

  • loopService.initializeLoop(等待 + 钉基线):toolSelect.e2e.test.ts 启动发现公告用例、disclosure 形态矩阵(inline/deferred × 开关)、"启动等待期间按 id 取消排队 prompt"用例;forkParity.test.ts startup/runtime 两用例断言 fork 基线与父 loop 基线完全一致。
  • mcpService 钩子删除:mcp.test.ts + 上述 e2e(原 "holds the LLM step" 用例随钩子删除,契约由 e2e 在真实入口覆盖)。
  • reconcileForRequest 等待删除:toolSelectService.test.ts + e2e。
  • fork 基线继承:forkParity.test.ts 新增 2 用例。
验证记录
  • 聚焦 7 文件 251/251:toolSelect e2e/service、mcp、forkParity、reminder、context、tokenCounting。
  • 全量 agent-core-v2 + core:7716 通过 / 4 失败——3 个为 macOS 本地 subagent deadline 超时(loop-refact 基线本地同样失败、CI 全绿,见 refactor(core): run loop turns on an independent state machine #5211 对照),1 个 task wire-history flake(隔离运行 242/242 通过)。
  • tsc -p packages/agent-core-v2/tsconfig.json --noEmit 通过。
  • lint:oxlint type-aware、导入边界、guards、ratchet 通过;check-comments.mjs 与 check:duplication 在 jj-only 工作区因 git 根解析上溯无法整体运行(预存在的工具问题),已改为对全部改动文件显式验证无注释。
  • test-doubles:新用例全部使用 testkit(testkitAgentFixtures + model.script,fork 子代理走 subagent lane);toolSelect.e2e 的 legacy mockNextResponse 计数 44 → 42(净减少,基线已随 PR 下调),forkParity 保持 14 零新增。forkParity 新用例将 btw fork 安排在父代理任何 turn 之前:harness 的 PersistenceAppendLogStore.read 不按 scope 过滤,父代理已有 turn 时子代理 restore 会 replay 到父记录、触发 initializeHistory 的 BugIndicatingError(基线同样复现的 harness 限制),父历史为空时 fork 不调用 initializeHistory,语义不变。
  • 未验证:真实模型、真实 Playwright MCP 端到端(复现基于仓库测试 harness 与 in-process MCP server)。

Checklist

  • I have read the CONTRIBUTING document.
  • I have linked a related issue (external PRs: issue must have a maintainer's /approve).
  • I have added tests that prove my feature works.
  • The behavior-change table above is complete, and every removed behavior or flipped default is named in the changeset and either has an escape hatch or was explicitly approved by a maintainer in this PR.
  • Ran gen-changesets skill, or this PR needs no changeset.
  • Ran gen-docs skill, or this PR needs no doc update.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-23T05:52:09.324799Z b81d3ca New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@pkg-pr-new

pkg-pr-new Bot commented Nov 23, 2026 •

Copy link
Copy Markdown
pnpm dlx https://pkg.pr.new/@moonshot-ai/kimi-code@b81d3ca
npx https://pkg.pr.new/@moonshot-ai/kimi-code@b81d3ca

commit: b81d3ca

7Sageer
7Sageer previously approved these changes Nov 23, 2026

@7Sageer 7Sageer left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

LGTM。等待点收敛在基线固定之前,显式继承的 fork/btw 基线保持一致,MCP 工具可见性与取消路径都有回归覆盖。已在本机运行该 PR 涉及的定向用例,相关测试通过。

@sailist
sailist changed the base branch from loop-421-stack/06-truncate-detach-output to main November 23, 2026 04:38
@sailist
sailist dismissed 7Sageer’s stale review November 23, 2026 04:38

The base branch was changed.

@sailist
sailist force-pushed the loop-421-stack/07-pin-initial-tool-baseline branch from ea19860 to 007a9d9 Compare November 23, 2026 04:49
@changeset-bot

changeset-bot Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: b81d3ca

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 2 packages
Name Type
@moonshot-ai/agent-core-v2 Patch
@moonshot-ai/kimi-code Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@sailist
sailist changed the base branch from main to loop-421-stack/06-truncate-detach-output November 23, 2026 04:49
@chatgpt-codex-connector

Copy link
Copy Markdown

💡 Codex Review

enabled(capabilities: ToolSelectCapabilities | undefined = this.profile.getModelCapabilities()): boolean {
return capabilities?.dynamically_loaded_tools === true && capabilities.tool_use === true;

P1 Badge Preserve the tool-select opt-out

When a deployment leaves the experimental flag at its default-off value or explicitly sets KIMI_CODE_EXPERIMENTAL_TOOL_SELECT=0 / [experimental] tool-select = false, a model advertising both capabilities now enables progressive disclosure anyway because this check no longer consults the flag and its registration was deleted. For users with deferred MCP servers, upgrading silently removes those schemas from the top-level tool list with no remaining escape hatch; retain the opt-out or provide an explicitly approved migration and changeset.

AGENTS.md reference: AGENTS.md:L195-L197


const drop = disclosure
? tool.deferred === true
: tool.name === SELECT_TOOLS_TOOL_NAME;

P1 Badge Keep loaded tools when switching to a non-dynamic model

When a deferred or runtime-added tool has been loaded through select_tools and the user switches the session to a model without dynamically_loaded_tools, base contains only the immutable startup baseline while the loaded schemas live in history. This replacement no longer merges collectLoadedDynamicTools(messages) into the non-disclosure tool list, and shapeUnsupportedDynamicToolContext subsequently strips the message-level schemas, so the request contains no declaration for those tools and they become unusable; restore the previous fallback for non-dynamic models.

AGENTS.md reference: AGENTS.md:L207-L209


await this.instantiation.invokeFunction((accessor) => accessor.get(ISessionMcpHandle).ready);

P1 Badge Cancel startup-queued prompts through existing session controls

When a prompt is submitted before MCP readiness settles, this await leaves it in pendingSubmissions without a loop or active turn. Existing unaddressed cancellation paths—including KAP :cancel, ACP cancellation before a turn ID is available, and TUI session cancellation—call cancel() without a prompt ID, so cancelActiveTurn returns false and the queued prompt still launches after MCP startup, potentially sending an LLM request after the user pressed Stop. The prompt-specific abort endpoint is not a compatible escape hatch for those clients; make unaddressed cancellation remove the startup-queued prompt or establish a cancellable turn before waiting.

AGENTS.md reference: AGENTS.md:L203-L205


messages[index] = { ...message, tools: kept };

P2 Badge Remove messages emptied by tool deduplication

When a contentless system message contains only tool declarations that duplicate a later message or profile.tools, this assignment replaces its tools with [] after the structural-cleanup pass has already run. The message therefore reaches OpenAI-compatible encoders as { role: "system", content: "" }, which the newly recognized text content is empty class of backends rejects as a request-structure error; run cleanup after deduplication or drop a system message whose content and retained tools are both empty.

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

7Sageer
7Sageer previously approved these changes Nov 23, 2026
Base automatically changed from loop-421-stack/06-truncate-detach-output to main November 23, 2026 05:45
@7Sageer
7Sageer dismissed their stale review November 23, 2026 05:45

The base branch was changed.

@7Sageer
7Sageer force-pushed the loop-421-stack/07-pin-initial-tool-baseline branch from 007a9d9 to b81d3ca Compare November 23, 2026 05:46
@sailist
sailist merged commit 6bdb7ea into main Nov 23, 2026
23 checks passed
@sailist
sailist deleted the loop-421-stack/07-pin-initial-tool-baseline branch November 23, 2026 05:53
7723qqq pushed a commit to 7723qqq/kimi-code that referenced this pull request Nov 25, 2026
Loop initialization now waits for the session MCP handle's ready before
pinning the tool baseline, and mcpService drops its per-step and
per-tool-call waits, so tools from slow-starting servers stay visible for
the session (MoonshotAI#5240). The obsolete waits are covered by the loop suites
(mcp 44, loop+toolSelect 176).
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.

[Bug] 2.6.0 在 MCP 发现完成前固定会话工具基线,导致部分 MCP 工具对整个会话不可见

3 participants