Skip to content

feat(agent-core-v2): defer MCP tools by default and cap startup wait at 2s - #5433

Merged
sailist merged 1 commit into
mainfrom
feat-464-11-25-mcp-timeout-2s
Nov 27, 2026
Merged

sailist merged 1 commit into
mainfrom
feat-464-11-25-mcp-timeout-2s

Conversation

@sailist

@sailist sailist commented Nov 25, 2026 •

Copy link
Copy Markdown
Collaborator

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 的 2s CLAUDE_CODE_MCP_STARTUP_WAIT_MS、Codex 的 1s mcp_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 目录与公告机制在后续步骤对模型可见:

 McpConnectionManager
-  resolveDeferred: config.deferred ?? defaults.defaultDeferred ?? false
+  resolveDeferred: config.deferred ?? defaults.defaultDeferred ?? true
   DEFAULT_STARTUP_TIMEOUT_MS = 30_000
   handshakeFailed -> failureTarget
+    if (transport === 'stdio' && failureStreak === 0) return 'failed'

 AgentLoopService.initializeLoop
-  await sessionMcpHandle.ready
+  waitMs = [mcp].startup_wait_ms ?? 2000   (env KIMI_MCP_STARTUP_WAIT_MS, 0 = skip)
+  await Promise.race([sessionMcpHandle.ready, timeoutOutcome(waitMs)])  (finally clear, no client close)
   freeze current initialTools() into profile.tools

 AgentToolSelectService.requestTools(base, disclosure)
   if (disclosure) -> existing deferred filtering + <tools_added> deltas via select_tools
+  if (!disclosure) -> append active deferred MCP tools outside baselineTools() inline (without deferred flag)
  • 默认 deferred(packages/agent-core-v2/src/mcpCore/connection-manager.ts):resolveDeferred 内置兜底改为 true,普通 MCP 工具与 OAuth 授权工具统一生效;server 级 mcp.json deferred 与 [mcp] default_deferred = false 保留为逃生口。
  • 2s 启动等待上限(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,继续绕过等待。
  • stdio 首次启动失败不重试(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() 之间的启动竞态。
  • 文档与 changeset:同步 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

Behavior Before After Who relies on the old behavior Escape hatch
未配置 deferred 时 MCP 工具的披露方式 默认 inline,直接进入顶层 tools 默认 deferred;支持动态加载的模型经 <tools_added> + select_tools 按需加载 依赖 MCP 工具在首个请求顶层 tools 中直接可见的客户端/工作流(TUI、print、Desktop/Web、VS Code、ACP、SDK) 单个 server 设 deferred: false,或全局设 [mcp] default_deferred = false
会话创建/恢复等待首轮 MCP 发现的时长 等待所有 server 首轮尝试 settle,最坏 startupTimeoutMs(默认 30s) 最多等待 startup_wait_ms(默认 2s),未就绪 server 保持 pending 在后台继续按 30s 超时连接 启动时需要立即对话、或配置了慢启动/挂起 MCP server 的用户 调大 [mcp] startup_wait_ms / KIMI_MCP_STARTUP_WAIT_MS;0 表示完全不等待
启动超过 2s 但不超过 30s 的 stdio server 首轮等待其连上后工具直接可见 2s 放行不杀进程,连上后支持动态加载的模型下一步经 <tools_added> 可见,非动态模型下一步直接平铺进 tools 使用 npx/uvx 冷缓存、Python 重依赖、浏览器自动化等慢启动 stdio server 的用户 若使用显式 deferred: false 且要求首个请求必须包含该工具,可调大 startup_wait_ms
不支持 dynamically_loaded_tools 的模型遇到运行期新增 MCP 工具(含 deferred: false 慢启动 server) 仅收到纯文本变更提醒,tools 中无对应 schema Loop 基线请求在后续步骤将当前已连接的基线外 MCP 工具平铺进 tools(无 deferred 标记,不分 deferred/inline);旁路显式工具列表与内置 deferred 工具(如 Tower)行为不变 使用未声明 dynamically_loaded_tools 能力的第三方模型且 MCP server 迟到连上或中途切换模型的用户 无需配置
stdio server 首次启动失败(含 30s 超时、临时 EAGAIN、进程提前退出) 开启 reconnectRetryEnabled 时进入无限指数退避后台重试 停在 failed,不自动后台重试;手动 reconnect 重试一次 依赖客户端反复重启失败 stdio 进程直到偶然成功的场景 在 /mcp / SDK 中手动 reconnect
HTTP/SSE 启动失败、已建立连接后的掉线(含 stdio)、单次工具调用超时、存活探测 HTTP/SSE 启动失败与掉线自动退避重连;工具调用默认 60s;ping 5s 不变 所有现有远程传输与长耗时工具调用场景 无需变更

受影响模块与测试覆盖:

  • 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-manager 59/59、toolSelect 126/126、loop 73/73、forkParity 17/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/core 37 文件 402/402 通过,agent-core-v2 376 个文件通过(含 sessionExport 23/23、towerDeferredTools),仅 gitService 两个 config.worktree sparse-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 --noEmit
  • 本地:pnpm 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.ts
  • m0-dev:pnpm --filter @moonshot-ai/agent-core-v2 --filter @moonshot-ai/core test
  • lint worktree:pnpm lint 与 pnpm run check:duplication

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 25, 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-26T03:20:32.842584Z 2222fd5 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.

@changeset-bot

changeset-bot Bot commented Nov 25, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: d0c3b29

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

This PR includes changesets to release 5 packages
Name Type
@moonshot-ai/agent-core-v2 Patch
@moonshot-ai/kimi-code Patch
kimi-code-app Patch
kimi-code Patch
@moonshot-ai/kimi-code-sdk 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

@pkg-pr-new

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

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

commit: d0c3b29

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 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".

Comment on lines +2 to +4
"@moonshot-ai/kimi-code": patch
"kimi-code-app": patch
"kimi-code": patch

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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.

@sailist
sailist force-pushed the feat-464-11-25-mcp-timeout-2s branch from 65fcd8f to fa38cbb Compare November 26, 2026 02:12
@sailist sailist changed the title feat(agent-core-v2): reduce default MCP startup timeout to 2s feat(agent-core-v2): defer MCP tools by default and cap startup wait at 2s Nov 26, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 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".

Comment on lines +179 to +180
!present.has(info.name) &&
!baselineNames.has(info.name) &&

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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' &&

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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).

Comment on lines +37 to +38
const parsed = Number(raw);
return Number.isInteger(parsed) && parsed >= 0 && parsed <= MAX_MCP_TIMEOUT_MS

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

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).

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 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;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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]);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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';

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

@sailist sailist closed this Nov 26, 2026
@sailist sailist reopened this Nov 26, 2026
@sailist
sailist force-pushed the feat-464-11-25-mcp-timeout-2s branch from c8445fc to 2222fd5 Compare November 26, 2026 03:13

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 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;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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]);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

@sailist
sailist merged commit 357a311 into main Nov 27, 2026
21 checks passed
@sailist
sailist deleted the feat-464-11-25-mcp-timeout-2s branch November 27, 2026 04:31
epatey pushed a commit to meridianlabs-ai/inspect_swe that referenced this pull request Nov 27, 2026
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]>
7723qqq pushed a commit to 7723qqq/kimi-code that referenced this pull request Dec 2, 2026
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.
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