Repository navigation
feat(agent-core-v2): defer MCP tools by default and cap startup wait at 2s - #5433
Conversation
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
🦋 Changeset detectedLatest commit: d0c3b29 The changes in this PR will be included in the next version bump. This PR includes changesets to release 5 packages
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 |
commit: |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: b33d62476d
ℹ️ 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".
| "@moonshot-ai/kimi-code": patch | ||
| "kimi-code-app": patch | ||
| "kimi-code": patch |
There was a problem hiding this comment.
Add the SDK to the timeout changeset
Include @moonshot-ai/kimi-code-sdk as a patch package here. The SDK directly imports McpConnectionManager in packages/node-sdk/src/sdk-rpc-client-v2.ts, and its build bundles all @moonshot-ai/* dependencies via packages/node-sdk/tsdown.config.ts; without an SDK changeset, the release process will not version or publish an SDK containing this new default, even though the PR explicitly lists SDK callers as affected.
AGENTS.md reference: AGENTS.md:L169-L170
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed in packages/node-sdk/tsdown.config.ts (alwaysBundle: [/^@moonshot-ai\//]). Added a separate "@moonshot-ai/kimi-code-sdk": patch entry in .changeset/mcp-startup-timeout-sdk.md (65fcd8f) and updated the PR description.
65fcd8f to
fa38cbb
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 3b779def47
ℹ️ 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".
| !present.has(info.name) && | ||
| !baselineNames.has(info.name) && |
There was a problem hiding this comment.
Preserve explicit tool lists when adding late MCP tools
When a request supplies an explicit tool list through options.tools or request.profile.tools after a deferred MCP server connects, this filter appends every late MCP tool that was absent from the session baseline. Before this commit, requestTools only filtered the supplied list, and the existing explicit-tools resolver test documents that restriction; the new baseline-name check therefore silently broadens special/custom requests instead of preserving their selected tools. Distinguish an explicit request list from the normal baseline before adding late tools.
AGENTS.md reference: AGENTS.md:L191-L193
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed: prepareOperation side requests share createToolSelectResolver, so a custom options.tools list could be broadened. requestTools now returns early unless the supplied list matches this.profile.baselineTools() by length and name order; added a unit test covering both loop-baseline requests and explicit overrides (ca73423).
| const lateDeferred = this.currentTools().filter( | ||
| (info) => | ||
| info.source === 'mcp' && | ||
| info.disclosure === 'deferred' && |
There was a problem hiding this comment.
Append late inline MCP tools for non-dynamic models
When [mcp] default_deferred = false or a server sets deferred: false and that server finishes connecting after the new 2-second wait, its tools are absent from the frozen baseline but have disclosure === 'inline', so this filter excludes them. A model without dynamic loading has no select_tools fallback, leaving the schema absent from every subsequent request and making the tool unusable; before this change, the 30-second initialization wait normally put the same slow server in the baseline. Include late active MCP tools regardless of disclosure while still respecting explicit request tool lists.
AGENTS.md reference: AGENTS.md:L195-L197
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed: models without dynamic loading have no select_tools fallback, so deferred: false slow servers would lose their schemas. Dropped the disclosure === "deferred" condition (keeping source === "mcp" and the loop-baseline guard), parameterized the e2e test over deferred/inline, and updated docs (ca73423).
| const parsed = Number(raw); | ||
| return Number.isInteger(parsed) && parsed >= 0 && parsed <= MAX_MCP_TIMEOUT_MS |
There was a problem hiding this comment.
Reject empty startup-wait environment values
When KIMI_MCP_STARTUP_WAIT_MS is present but empty or whitespace-only, Number(raw) evaluates to 0, and the range check accepts it as an intentional request to skip waiting. This silently overrides a configured startup_wait_ms or the 2-second default even though the environment-variable documentation says invalid values are ignored; empty values are common in templated container environments. Validate the raw string before numeric coercion so only an explicit numeric zero disables the wait.
AGENTS.md reference: AGENTS.md:L118-L118
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed: Number("") and Number(" ") coerce to 0. Added an early raw.trim() === "" return in parseWaitMsEnv and test cases asserting empty/whitespace values fall back to config.toml (ca73423).
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: ca73423dfd
ℹ️ 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".
| } | ||
| return shaped ?? tools; | ||
| const result = shaped ?? tools; | ||
| if (disclosure) return result; |
There was a problem hiding this comment.
Keep late opted-out MCP tools inline
When a dynamic-loading-capable model uses deferred: false or [mcp] default_deferred = false and the MCP server finishes connecting after the new startup cutoff, this early return prevents the late-tool append from running. isDynamicallyLoadable then treats the runtime-added inline tool as dynamically loadable, so the model receives an announcement and must call select_tools instead of receiving the schema in its top-level tool list. Thus the documented opt-out does not actually restore inline behavior for slow servers; the fresh evidence beyond the earlier non-dynamic finding is that the new fallback is explicitly gated behind !disclosure. Include late inline MCP tools in baseline requests even when disclosure is enabled.
AGENTS.md reference: AGENTS.md:L195-L197
Useful? React with 👍 / 👎.
| const ready = this.instantiation.invokeFunction((accessor) => accessor.get(ISessionMcpHandle).ready); | ||
| const deadline = timeoutOutcome(waitMs, undefined); | ||
| try { | ||
| await Promise.race([ready, deadline]); |
There was a problem hiding this comment.
Apply MCP updates during background startup
When any initial MCP server is still connecting after this race releases the session, plugin enable/disable events and mcp.json reloads remain queued by ProjectMcpService.scheduleApply behind the full this.ready promise. If a plugin is enabled in that interval, the session baseline freezes when ready resolves before the queued upsert runs, so the newly enabled plugin never joins the already-open session despite the documented behavior; disabling an existing server is likewise delayed for up to startupTimeoutMs. Apply configuration changes without waiting for the original connection batch to settle, or otherwise keep them in the current session baseline.
Useful? React with 👍 / 👎.
| private failureTarget(entry: InternalEntry, kind: McpFailureKind): 'failed' | 'needsAuth' | 'retryWaiting' { | ||
| if (kind === 'config' || kind === 'protocol' || kind === 'auth-static') return 'failed'; | ||
| if (kind === 'auth-oauth' && this.oauthService !== undefined) return 'needsAuth'; | ||
| if (entry.config.transport === 'stdio' && entry.failureStreak === 0) return 'failed'; |
There was a problem hiding this comment.
Correct the reconnect environment-variable documentation
After this condition stops retrying initial stdio failures, both docs/en/configuration/env-vars.md and its Chinese mirror still say KIMI_MCP_RECONNECT_INITIAL_DELAY_MS controls the first automatic reconnect for any workspace-level MCP server that failed to connect. For an initial stdio failure that variable now has no effect, so users following the environment-variable reference will wait for a retry that never occurs. Narrow both reconnect rows to HTTP/SSE startup failures and established connection drops, matching the updated MCP and configuration-file pages.
AGENTS.md reference: docs/AGENTS.md:L23-L26
Useful? React with 👍 / 👎.
c8445fc to
2222fd5
Compare
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 2222fd5d29
ℹ️ 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".
|
|
||
| private resolveDeferred(config: McpServerConfig): boolean { | ||
| return config.deferred ?? this.options.resolveDefaults?.().defaultDeferred ?? false; | ||
| return config.deferred ?? this.options.resolveDefaults?.().defaultDeferred ?? true; |
There was a problem hiding this comment.
Keep MCP tools usable when
select_tools is disabled
When a dynamic-tool-capable model runs under a profile, workspace, global, or session policy that explicitly disables select_tools, this new deferred-by-default value makes every otherwise-unspecified MCP tool inaccessible: requestTools removes their deferred schemas while the policy also removes the only tool that can load them. The existing explicit-deny path confirms this is a supported configuration, and before this change the same MCP tools remained inline; fall back to inline disclosure when select_tools is unavailable so these users do not silently lose all MCP tools.
AGENTS.md reference: AGENTS.md:L195-L197
Useful? React with 👍 / 👎.
| const ready = this.instantiation.invokeFunction((accessor) => accessor.get(ISessionMcpHandle).ready); | ||
| const deadline = timeoutOutcome(waitMs, undefined); | ||
| try { | ||
| await Promise.race([ready, deadline]); |
There was a problem hiding this comment.
Exclude pending restored MCP tools after the startup cutoff
On a resumed session after the CLI or server restarts, if an MCP server is still pending when this 2-second race completes, initialTools() reads the persisted tool-selection state and puts that server's old schemas into the frozen loop baseline even though AgentMcpService has not registered any executors for a pending connection. For models without dynamic loading, requestTools then sends those stale schemas as callable, so an immediate model call fails instead of waiting for a server that would have connected within the previous 30-second startup window; when the cutoff wins, reconcile restored MCP entries against the live registry before freezing the baseline.
AGENTS.md reference: AGENTS.md:L111-L113
Useful? React with 👍 / 👎.
2222fd5 to
d0c3b29
Compare
Kimi Code fixed MoonshotAI/kimi-code#4904, so `test_kimi_code_bridged_tools` passes again and the strict xfail from #263 now fails the nightly. This removes the marker. Last night's [Inspect SWE Nightly Tests run 45781716402](https://github.com/meridianlabs-ai/actions/actions/runs/45781716402) ended with one failure, `test_kimi_code_bridged_tools - [XPASS(strict)]`. The night before used the same inspect_swe commit (`88f5e8c`) and the same inspect-ai (0.3.291), and that test was the one xfail. The only thing that moved between the two runs was Kimi Code. 2.8.0 shipped on 2026-11-25 at 12:41Z, and its notes say "Fix MCP tools discovered during session startup being unavailable for the whole session". We download whatever Kimi's `latest.json` names, so the nightly picked it up. Its log doesn't print the Kimi version, so 2.8.0 is my inference from the timing. #263 made the test check that `secret_lookup` really ran and returned the secret, not just that the model said its name. So this XPASS means Kimi offered the tool and the tool ran. A lucky guess at the call name doesn't count. ### Validation - `make check` passes. - The test body is unchanged, and the nightly above ran this exact test on real Kimi Code with `claude-sonnet-4-5` and passed. - A reviewer replayed the `bridged_tools` example in Docker against a scripted mock model on three Kimi versions. On 2.7.2, no MCP tool reached the first request and the tool-ran assertion failed. On 2.8.0 and 2.8.1, `mcp__secrets__secret_lookup` was in the first request and both assertions passed. 2.8.1 passed 4 times out of 4. - I have not dispatched the nightly against this branch. Tonight's scheduled run picks it up once this merges. ### Not this PR - Two comments in `src/inspect_swe/_kimi_code/kimi_code.py` (near lines 350 and 402) say Kimi never waits for MCP connections before the first turn. 2.8.0 changed that. The pre-launch endpoint wait is still harmless, so I left the code and comments alone. - MoonshotAI/kimi-code#5433 is open and would defer MCP tools by default, with a 2-second startup wait. If this test goes red again, check that first. - `claude-sonnet-4-5` reaches end-of-life on 2026-11-30, per a deprecation warning in the nightly. Eleven test files use it, including this one. ### Agent review - Reviewers: Claude Fable 5.2 (`claude -p`, xhigh) and Codex GPT-6.2-Sol (`codex exec review`, xhigh), each in a fresh context with no conclusions from me, 1 pass each. Both are different models from the author (Claude Opus 5.5). - Findings: none from either. Fable flagged the stale comments and the upstream PR listed under "Not this PR". 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 <[email protected]>
Port upstream 357a311 (MoonshotAI#5433) in the upstream-final shape: MCP server tools are deferred by default; session initialization waits at most startup_wait_ms (default 2000, KIMI_MCP_STARTUP_WAIT_MS, 0 skips) for initial MCP discovery and then freezes the tool baseline; stdio servers that fail their initial startup stay failed without background retries, while HTTP/SSE startup failures and established-connection drops still retry. Fork adaptations: the capped wait also replaces the unconditional session MCP ready wait in toolSelectService.prepareForRequest, using the remaining budget from initialLoadDurationMs (upstream MoonshotAI#5635 shape), so the 2s cap is not defeated; the late-MCP inline append from MoonshotAI#5433 is skipped because upstream MoonshotAI#5638 reverted it to protect the prompt-cache prefix, and the fork's existing runtime inline-tool behavior is unchanged. Docs en/zh, the config manifest, a CLI changeset and the affected config, connection-manager, loop, toolSelect and forkParity tests are updated; the oxlint ratchet baseline moves down only.
Requirement or Bug
#4904 修复后,会话创建与恢复会在
initializeLoop中等待 MCP 首轮工具发现全部 settle,单个挂起或启动缓慢的 MCP server 会把会话可用时间拖长到startupTimeoutMs(默认 30 秒)。如果简单把startupTimeoutMs默认值改成 2 秒,stdio server 每次重试都会重新spawn子进程并在 2 秒时被杀,导致冷启动稳定超过 2 秒的 stdio server 永远连不上。本 PR 将「会话启动时等待 MCP 的时长上限」与「MCP server 连接/进程启动的存活超时」解耦(与 OpenCode 的 2s
STARTUP_GRACE_MS、Claude Code 的 2sCLAUDE_CODE_MCP_STARTUP_WAIT_MS、Codex 的 1smcp_optional_startup_grace_ms同一思路):默认将所有 MCP 工具按 deferred 披露,首轮最多等待 2 秒即带着已就绪工具开始对话,未就绪的 server 保持pending在后台继续按 30 秒超时连接;同时 stdio 首次启动失败不再进入无限后台重试。Bug Reproduction Steps
N/A
Root Cause
N/A
Code Changes
核心思路是把「等待上限」从
startupTimeoutMs中拆出来,并让迟到连上的 MCP 工具通过既有 deferred 目录与公告机制在后续步骤对模型可见:packages/agent-core-v2/src/mcpCore/connection-manager.ts):resolveDeferred内置兜底改为true,普通 MCP 工具与 OAuth 授权工具统一生效;server 级mcp.jsondeferred与[mcp] default_deferred = false保留为逃生口。packages/agent-core-v2/src/app/mcpConfig/configSection.ts、projectMcpConfig*、agent/loop/loopService.ts):新增[mcp] startup_wait_ms/KIMI_MCP_STARTUP_WAIT_MS(0–2147483647,默认2000,0表示不等)。复用_base/utils/promise.ts的timeoutOutcome限时等待ISessionMcpHandle.ready,超时只停止等待,不关闭任何 client,也不改变ready表示「首轮全部 settle」的语义;same-profile fork/btw 显式传入initialTools,继续绕过等待。connection-manager.ts):failureTarget对transport === 'stdio'且failureStreak === 0(首次启动或手动kick重连)直接返回'failed',避免「每次新起子进程、到点强杀、再重起」的死循环;HTTP/SSE 启动失败及已建立连接后的掉线(probeFailed/ 硬断连证据,failureStreak > 0)仍按既有指数退避自动重连。agent/toolSelect/toolSelectService.ts、docs/en/llm.md):当模型未声明dynamically_loaded_tools时,当请求携带 Loop 自身冻结基线时,将baselineTools()之外当前已连接的source === 'mcp'工具(不区分 deferred/inline)去除deferred标记后平铺进请求tools,避免模型只收到工具名提醒却拿不到 schema;显式旁路工具覆盖列表、既有工具 schema 钉住以及 Tower 等内置 deferred 工具(source === 'builtin')的行为均保持不变。test/agent/loop/loop.test.ts中#5394新增的「取消启动中 prompt」用例开头补充await agent.restorePersisted(),消除ProfileBind异步落盘与测试夹具首次submit自动restore()之间的启动竞态。docs/{en,zh}/configuration/config-files.md、env-vars.md、customization/mcp.md、docs/config-manifest.toml与三份 changeset(agent-core-v2、打包引擎的@moonshot-ai/kimi-code-sdk、CLI/Desktop/VS Code)。Behavior Changes and Affected Users
deferred时 MCP 工具的披露方式tools<tools_added>+select_tools按需加载tools中直接可见的客户端/工作流(TUI、print、Desktop/Web、VS Code、ACP、SDK)deferred: false,或全局设[mcp] default_deferred = falsestartupTimeoutMs(默认 30s)startup_wait_ms(默认 2s),未就绪 server 保持pending在后台继续按 30s 超时连接[mcp] startup_wait_ms/KIMI_MCP_STARTUP_WAIT_MS;0表示完全不等待<tools_added>可见,非动态模型下一步直接平铺进toolsnpx/uvx冷缓存、Python 重依赖、浏览器自动化等慢启动 stdio server 的用户deferred: false且要求首个请求必须包含该工具,可调大startup_wait_msdynamically_loaded_tools的模型遇到运行期新增 MCP 工具(含deferred: false慢启动 server)tools中无对应 schematools(无deferred标记,不分 deferred/inline);旁路显式工具列表与内置 deferred 工具(如 Tower)行为不变dynamically_loaded_tools能力的第三方模型且 MCP server 迟到连上或中途切换模型的用户EAGAIN、进程提前退出)reconnectRetryEnabled时进入无限指数退避后台重试failed,不自动后台重试;手动reconnect重试一次/mcp/ SDK 中手动reconnectping5s受影响模块与测试覆盖:
mcpCore/connection-manager.ts:test/mcpCore/connection-manager.test.ts覆盖内置默认 deferred 与defaultDeferred: false/ per-server 逃生口、三传输默认30_000ms 透传、2s 时仍pending不关闭连接并在 30s 超时、stdio 首次启动失败/超时不重试且手动reconnect可恢复、远程启动失败仍退避重试、已连接 stdio 掉线后仍自动重连。agent/loop/loopService.ts与agent/toolSelect/toolSelectService.ts:test/agent/toolSelect/toolSelect.e2e.test.ts覆盖默认 2s(1999ms 等待、2000ms 放行)不取消后台连接、迟到 deferred 工具经<tools_added>+select_tools调用、非动态模型下一请求平铺 schema、KIMI_MCP_STARTUP_WAIT_MS=0立即放行、会话中途切换非动态模型时平铺 MCP deferred 工具;toolSelectService.test.ts覆盖显式工具覆盖列表不被突破;features/tower/towerDeferredTools.e2e.test.ts覆盖内置 deferred 工具行为不变;session/subagent/forkParity.test.ts(17/17)覆盖父 agent 与 btw 子代理在启动期/运行期 MCP 发现后基线与请求工具列表完全一致。test/app/config/config.test.ts、test/project/projectMcpConfig覆盖startup_wait_ms解析、0/上下界与环境变量优先级。connection-manager59/59、toolSelect126/126、loop73/73、forkParity17/17、towerDeferredTools、projectMcpConfig、gitService、sessionExport、remote/process、config新增用例)全部通过,本地与 m0-dev 的tsc -p packages/agent-core-v2/tsconfig.json --noEmit均 0 错误;完整pnpm lint与check:duplication通过;m0-dev 全量packages/core37 文件 402/402 通过,agent-core-v2376 个文件通过(含sessionExport23/23、towerDeferredTools),仅gitService两个config.worktreesparse-checkout 用例因 m0-dev 自带 git 2.34.1 过旧而失败(本地 macOS 通过),以及remote/process.test.ts在全量并发高负载下触发 fake-timer 超时(单独复跑通过)。未在 Windows 实机验证(coding-win 环境创建失败);未跑 VitePress 文档构建。验证命令
pnpm exec tsc -p packages/agent-core-v2/tsconfig.json --noEmitpnpm exec vitest run --reporter=agent packages/agent-core-v2/test/mcpCore/connection-manager.test.ts packages/agent-core-v2/test/agent/toolSelect packages/agent-core-v2/test/agent/loop packages/agent-core-v2/test/features/tower/towerDeferredTools.e2e.test.ts packages/agent-core-v2/test/project/projectMcpConfig packages/agent-core-v2/test/app/config/config.test.tspnpm --filter @moonshot-ai/agent-core-v2 --filter @moonshot-ai/core testpnpm lint与pnpm run check:duplicationChecklist
/approve).gen-changesetsskill, or this PR needs no changeset.gen-docsskill, or this PR needs no doc update.