Skip to content

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

Closed

Description

@crlcrl1

你运行的 Kimi Code 版本是?

2.6.0

你使用的是哪个开放平台/订阅?

Kimi Code 订阅

你使用的是哪个模型?

K3.1 Pro(kimi-code/k3.1-pro)

你的电脑平台是?

Linux 7.2.15-arch1-1 x86_64 unknown

你遇到了什么问题?

从 2.5.3 升级到 2.6.0 后,新会话中的部分 MCP 工具不会进入实际发给模型的工具列表,导致 Agent 无法调用这些工具。

表面上可能表现为 Agent 不再遵循 AGENTS.md 中关于主动使用 MCP 的指令,但排查后确认,AGENTS.md 已正确加载,MCP 服务器也已成功连接;实际问题是工具定义在模型请求装配阶段被遗漏。

在一个受影响的 2.6.0 会话中:

  1. 三个启动较慢的 MCP 服务器均成功完成工具发现,共计发现 92 个工具。
  2. tool_select.initialized 包含 126 个工具,其中包括上述全部 92 个 MCP 工具。
  3. 但 llm.tools_snapshot 只有 34 个工具,上述 92 个工具全部被省略。
  4. 启动较快、在会话初始化前完成发现的其他 MCP 工具则正常保留。
  5. 会话同时收到:No tools are currently available for dynamic loading in this session.
  6. 后续没有出现包含缺失工具的 <tools_added> 公告,因此也无法通过 select_tools 加载。
  7. 缺失状态在后续 Turn 中不会自动恢复。

执行 /mcp 并等待所有服务器显示已连接,再提交第一条 prompt,也不能解决问题。此时会话的模型工具基线已经固定,/mcp 不会重建该基线。

关闭 tool-select 同样无效。

复现步骤?

  1. 配置多个 stdio MCP 服务器,其中至少一个需要数秒才能完成初始化和工具发现。
  2. 不为这些服务器设置 deferred。
  3. 启动一个新会话并立即提交 prompt。
  4. 检查该会话的 agents/main/wire.jsonl。
  5. 在异常会话中可以观察到以下顺序:
    • 记录 turn.prompt
    • 较慢的 MCP 服务器随后记录 mcp.tools_discovered
    • tool_select.initialized 包含这些较晚发现的工具
    • llm.tools_snapshot 却不包含这些工具
  6. 后续请求仍不会恢复这些工具。

仅提交“回复 OK”之类不需要调用工具的 prompt,即可检查实际工具列表。

在相同机器、相同配置和相同 MCP 服务器下进行版本对照。两个版本中,较慢的 MCP 都是在 turn.prompt 之后、llm.tools_snapshot 之前完成发现:

  • 2.5.3:llm.tools_snapshot 包含 124 个工具,较晚发现的 MCP 工具全部存在。
  • 2.6.0:llm.tools_snapshot 只有 34 个工具,这些 MCP 工具全部缺失。
  • 2.6.0 关闭 tool-select:只有 32 个工具,这些 MCP 工具仍全部缺失。

问题发生在模型请求装配阶段,因此应该与具体模型和具体 MCP 服务器无关。

期望的行为是什么?

会话不应在初始 MCP 发现尚未完成时永久固定一个不完整的工具基线。

可以考虑以下任一行为:

  1. 在初始化会话工具基线前,等待初始 MCP 发现达到稳定状态,包括 connected、needs-auth、disabled 或明确失败;或
  2. 将初始化后发现的工具正确作为运行时新增工具处理,并在支持动态加载时通过 <tools_added> 公告。

成功连接的 MCP 服务器不应在整个会话中对模型保持不可见。

补充信息

该回归可能由 #4630(refactor(agent-core-v2): port agent loop runtime core)引入。

2.6.0 的 AgentLoopService.initializeLoop() 会通过 requestFactory.baselineTools() 获取工具,并将其保存到 loop.state.profile.tools,但该初始化过程没有等待 MCP 就绪。

后续 /mcp 只显示 MCP 状态,不会重建这个已经保存的基线。

2.5.3 的 createToolSelectResolver 在 prepareForRequest() 后,当 request.profile.tools 未定义时使用 toolSelect.defaultTools(disclosure)。2.6.0 改为将已有的工具基线传给 toolSelect.requestTools(...);如果基线在 MCP 发现完成前生成,较晚发现的工具就不会进入模型请求。

受影响的会话中,动态工具公告也是空的,因此没有通过 select_tools 恢复的路径。

目前确认有效的临时处理只有回退到 2.5.3。以下操作均无效:

  • 在第一条 prompt 前执行 /mcp 并等待全部服务器 connected
  • 在异常会话中继续等待或提交后续 Turn
  • 关闭 tool-select

相关但不完全相同的旧问题:#3442。该 issue 报告的是旧版本 /reload 后的 MCP readiness 竞争;本问题发生在 2.6.0 普通新会话的 Agent Loop 初始化路径,并附有 2.5.3/2.6.0 的直接对照。

Contribution

  • 我愿意自己提交修复此 bug 的 PR(请先等待维护者在本 issue 中批准)

Activity

  1. ilyavasilenko89 commented on Nov 14, 2026

    @ilyavasilenko89

    I reproduced the incomplete MCP tool baseline on main at f082f04a093a3e71a2263c5461d52507dc31f83a, using the in-repository test harness with no credentials, external sites, or real model requests.

    This also matches a Windows 11 report on CLI 2.6.1: Playwright MCP connects and registers 25 tools; tool_select.initialized contains 52 tools, but llm.tools_snapshot contains only 26 built-ins, with neither mcp__playwright__* nor select_tools. Setting [experimental] tool-select = false does not recover the missing tools. Those counts describe the affected session; the reproduction below uses one synthetic MCP tool.

    Reproduced scope and cause

    The isolated reproduction specifically covers disabled progressive disclosure, for both inline and deferred MCP registrations. It does not establish the effective flag/capabilities of the original Windows session or prove every enabled-disclosure path in this issue.

    1. AgentLoopService.initializeLoop() captures toolSelect.initialTools() before initial MCP discovery has finished.
    2. Discovery completes, and the tool-selection catalog contains the MCP tool.
    3. In the disabled-disclosure branch, AgentToolSelectService.requestTools() starts from the earlier baseline and adds only schemas already loaded in message history. The newly completed initial catalog does not reach the request.

    Relevant code: loop initialization, request tool selection.

    The same requestTools() implementation is present in the official @moonshot-ai/[email protected] tag (30e3ce442ae850a7461b80f2ce209cd73a301d02). This path was introduced by #4630. The installed CLI was not modified or used for these tests.

    Minimal reproduction

    After installing the repository dependencies, save the following two files. Tested with Node.js 24.19.0 and pnpm 10.33.0 on Windows. The test registers the synthetic tool after Loop initialization and before the first request, isolating the discovery timing boundary without requiring an MCP transport.

    packages/agent-core-v2/.tmp/issue/reproduce.test.ts:

    import { expect, it } from 'vitest';
    
    import { IAgentToolRegistryService } from '#/agent/toolRegistry/toolRegistry';
    import { IAgentToolSelectService } from '#/agent/toolSelect/toolSelect';
    import { createTestAgent } from '../../test/harness';
    
    it.each(['inline', 'deferred'] as const)(
      'exposes a late-discovered %s MCP tool without tool-select',
      async (disclosure) => {
        const ctx = createTestAgent({
          autoStart: false,
          initialConfig: { experimental: { 'tool-select': false } },
        });
        const name = 'mcp__example__echo';
        try {
          ctx.configure({
            tools: ['Read', 'mcp__*'],
            modelCapabilities: {
              image_in: false,
              video_in: false,
              audio_in: false,
              thinking: false,
              tool_use: true,
              dynamically_loaded_tools: true,
              maxContextSize: 128_000,
            },
          });
          await ctx.restorePersisted();
          ctx.get(IAgentToolRegistryService).register({
            name,
            description: 'Return a synthetic value.',
            parameters: { type: 'object', properties: {} },
            resolveExecution: () => ({
              description: 'Synthetic echo',
              approvalRule: name,
              execute: async () => ({ output: 'ok' }),
            }),
          }, { source: 'mcp', disclosure });
          expect(ctx.get(IAgentToolSelectService).enabled()).toBe(false);
          ctx.mockNextResponse({ type: 'text', text: 'ok' });
          await ctx.rpc.prompt({ input: [{ type: 'text', text: 'reply ok' }] });
          await ctx.untilTurnEnd();
    
          expect(ctx.get(IAgentToolSelectService).initialTools().map((tool) => tool.name))
            .toContain(name);
          expect(ctx.llmCalls[0]!.tools.map((tool) => tool.name))
            .toEqual([name, 'Read']);
        } finally {
          await ctx.dispose();
        }
      },
    );

    packages/agent-core-v2/.tmp/issue/vitest.config.ts:

    import { defineConfig } from 'vitest/config';
    
    export default defineConfig({
      test: {
        include: ['.tmp/issue/reproduce.test.ts'],
        setupFiles: ['test/setup.ts'],
        testTimeout: 30_000,
      },
    });

    Run from the repository root:

    pnpm --filter '@moonshot-ai/agent-core-v2' exec vitest run --config .tmp/issue/vitest.config.ts

    Both cases fail on the stated baseline: the catalog assertion passes, but the actual request contains ['Read'] instead of ['mcp__example__echo', 'Read']. There are no real model calls or credentials involved.

    Related work

    This is distinct from #2381 / #2384, which concern activation of select_tools. The activation policy has already been addressed in merged #3667. The reproduction above deliberately disables disclosure, so restoring select_tools activation cannot fix it.

    A first local attempt to append the complete initial catalog in every fallback request was rejected during review: it broke the same-profile fork invariant restored by #4832. The revised patch below preserves that invariant.

    Revised local patch

    The Loop completes its initial tools once, after startup MCP discovery and before the first model request, and records the completed baseline in its existing tools.settled state. Agent creation remains non-blocking. Only missing initial MCP definitions are added; existing definitions and built-in tools remain pinned. An explicitly inherited baseline bypasses this completion step, so a same-profile fork does not acquire additional tools from its own fresh catalog.

    When progressive disclosure is unavailable, definitions already in that baseline are sent inline, including deferred definitions. Previously loaded schemas retain precedence for deferred tools. The patch does not merge the live catalog into every request or change configuration defaults or persistence formats.

    Validation on the stated base, on 2026-11-14:

    • 422 tests passed in 20 files, covering tool selection and policies, the Loop, agent lifecycle, and fork parity.
    • Four startup-discovery regressions (inline/deferred × disabled flag/unsupported model) fail with the original production sources and pass with the patch.
    • A loopback MCP test covers /btw after both startup and runtime discovery. Startup tools are inherited; a server connecting after the parent's first request does not widen the child's baseline. The original runtime-fork review counterexample now passes too.
    • Enabled-disclosure cases, cancellation, failed preparation/retry, pinned schemas, and the existing built-in Lookup snapshot are covered.
    • Typecheck passed for core and agent-core-v2; import-boundary checks passed. Type-aware lint: 0 errors; pre-existing warnings remain, with none on added lines.
    • CLI patch changeset included. No full monorepo CI or real-model/Playwright run is claimed.

    All reproduction data is synthetic. Tests use the repository harness and a local loopback MCP server, with no credentials or external sites. The diff is provided below for review; no commit, push, or PR has been created. Would maintainers approve a focused bug-fix PR for #4904 with this approach?

    Local patch, including regression tests and changeset
    diff --git a/packages/agent-core-v2/src/agent/loop/loopService.ts b/packages/agent-core-v2/src/agent/loop/loopService.ts
    index 9b8f233e2..0aba78830 100644
    --- a/packages/agent-core-v2/src/agent/loop/loopService.ts
    +++ b/packages/agent-core-v2/src/agent/loop/loopService.ts
    @@ -469,7 +469,7 @@ export class AgentLoopService extends Disposable implements IAgentLoopService {
           });
           const pendingWork = (snapshot.input.inbox?.normal?.length ?? 0) + (snapshot.input.inbox?.notify?.length ?? 0);
           if (lease === undefined && (completions.length > 0 || pendingWork > 0)) lease = this.runGate.acquire();
    -      this.createLoopFromSnapshot(snapshot, tools, completions, seededMessages);
    +      this.createLoopFromSnapshot(snapshot, tools, initialTools === undefined, completions, seededMessages);
         } finally {
           lease?.release();
         }
    @@ -478,6 +478,7 @@ export class AgentLoopService extends Disposable implements IAgentLoopService {
       private createLoopFromSnapshot(
         snapshot: LoopJournalSnapshot,
         tools: readonly Tool[],
    +    prepareInitialTools: boolean,
         completions: readonly UserMessage[],
         seededMessages?: readonly Message[],
         minimumNextTurnId = 0,
    @@ -485,6 +486,12 @@ export class AgentLoopService extends Disposable implements IAgentLoopService {
       ): void {
         this.initialized = true;
         const loop = createLoop({
    +      prepareInitialTools: prepareInitialTools ? async (baseline, signal) => {
    +        await this.toolSelect.prepareCatalog(signal);
    +        const names = new Set(baseline.map((tool) => tool.name));
    +        return [...baseline, ...this.toolSelect.initialTools('mcp').filter((tool) => !names.has(tool.name))]
    +          .toSorted((left, right) => left.name.localeCompare(right.name));
    +      } : undefined,
           completionMessage: (input: ToolCompletionInput) => {
             const handler = this.toolExecutor.handlerForCall(input.toolCall.id);
             if (handler?.snapshot().fields.task === undefined) {
    diff --git a/packages/agent-core-v2/src/agent/toolSelect/toolSelect.ts b/packages/agent-core-v2/src/agent/toolSelect/toolSelect.ts
    index d039cc781..ee1dc7571 100644
    --- a/packages/agent-core-v2/src/agent/toolSelect/toolSelect.ts
    +++ b/packages/agent-core-v2/src/agent/toolSelect/toolSelect.ts
    @@ -60,7 +60,7 @@ export interface IAgentToolSelectService {
     
       prepareCatalog(signal?: AbortSignal): Promise<void>;
     
    -  initialTools(): readonly Tool[];
    +  initialTools(source?: ToolInfo['source']): readonly Tool[];
     
       defaultTools(disclosure?: boolean): readonly Tool[];
     
    diff --git a/packages/agent-core-v2/src/agent/toolSelect/toolSelectService.ts b/packages/agent-core-v2/src/agent/toolSelect/toolSelectService.ts
    index 5ab3c8514..8d1a5ba4e 100644
    --- a/packages/agent-core-v2/src/agent/toolSelect/toolSelectService.ts
    +++ b/packages/agent-core-v2/src/agent/toolSelect/toolSelectService.ts
    @@ -140,8 +140,8 @@ export class AgentToolSelectService extends Service implements IAgentToolSelectS
         return this.defaultToolsForDisclosure(disclosure);
       }
     
    -  initialTools(): readonly Tool[] {
    -    const tools = this.initialToolInfos();
    +  initialTools(source?: ToolInfo['source']): readonly Tool[] {
    +    const tools = this.initialToolInfos().filter((tool) => source === undefined || tool.source === source);
         return this.activeEntries(tools, this.featureEnabled()).map((tool) => ({
           name: tool.name,
           description: tool.description,
    @@ -159,7 +159,9 @@ export class AgentToolSelectService extends Service implements IAgentToolSelectS
         if (!dynamic) return base ?? this.defaultToolsForDisclosure(disclosure);
         if (disclosure) return base ?? [];
         const loaded = collectLoadedDynamicTools(messages);
    -    const tools = (base ?? []).filter((tool) => tool.name !== SELECT_TOOLS_TOOL_NAME && tool.deferred !== true);
    +    const tools = (base ?? [])
    +      .filter((tool) => tool.name !== SELECT_TOOLS_TOOL_NAME)
    +      .map((tool) => tool.deferred === true ? { ...(loaded.get(tool.name) ?? tool), deferred: undefined } : tool);
         const names = new Set(tools.map((tool) => tool.name));
         for (const tool of loaded.values()) {
           if (names.has(tool.name)) continue;
    diff --git a/packages/agent-core-v2/test/agent/loop/core/requester.test.ts b/packages/agent-core-v2/test/agent/loop/core/requester.test.ts
    index 1604a0fc9..d27ee4053 100644
    --- a/packages/agent-core-v2/test/agent/loop/core/requester.test.ts
    +++ b/packages/agent-core-v2/test/agent/loop/core/requester.test.ts
    @@ -1,4 +1,5 @@
    -import { describe, expect, it } from 'vitest';
    +import { createControlledPromise } from '@antfu/utils';
    +import { describe, expect, it, vi } from 'vitest';
     
     import { createUserMessage, extractText } from '@moonshot-ai/core/llm/message';
     import type { LlmRecovery } from '@moonshot-ai/core/llm/policy/recovery';
    @@ -27,6 +28,98 @@ function listOf<T>(value: readonly T[] | (() => readonly T[]) | undefined): read
     }
     
     describe('loop.requester', () => {
    +  it('prepares initial tools once and preserves them in the loop baseline', async () => {
    +    const started = createControlledPromise<void>();
    +    const ready = createControlledPromise<void>();
    +    const tools = [{ name: 'late', description: 'late tool', parameters: { type: 'object', properties: {} } }];
    +    const seen: LlmRequest[] = [];
    +    const prepareInitialTools = vi.fn(async () => {
    +      started.resolve();
    +      await ready;
    +      return tools;
    +    });
    +    const loop = createLoop({
    +      executor: noopExecutor,
    +      input: { profile: { tools: [] } },
    +      prepareInitialTools,
    +      requester: fakeRequester((request) => {
    +        seen.push(request);
    +        return done('reply');
    +      }).with({ model: { spec } }),
    +    });
    +    try {
    +      const first = loop.runTurn(createUserMessage('hello'));
    +      await started;
    +      expect(seen).toHaveLength(0);
    +      ready.resolve();
    +      expect((await first).type).toBe('done');
    +      expect(loop.state.profile.tools).toEqual(tools);
    +      expect((await loop.runTurn(createUserMessage('again'))).type).toBe('done');
    +      expect(prepareInitialTools).toHaveBeenCalledTimes(1);
    +      expect(seen.map((request) => request.profile?.tools)).toEqual([tools, tools]);
    +    } finally {
    +      ready.resolve();
    +      await loop.close();
    +    }
    +  });
    +
    +  it('retries initial tool preparation after a failed attempt without sending an incomplete request', async () => {
    +    const seen: LlmRequest[] = [];
    +    const prepareInitialTools = vi.fn(async () => [])
    +      .mockRejectedValueOnce(new Error('initial tools unavailable'));
    +    const loop = createLoop({
    +      executor: noopExecutor,
    +      prepareInitialTools,
    +      requester: fakeRequester((request) => {
    +        seen.push(request);
    +        return done('reply');
    +      }).with({ model: { spec } }),
    +    });
    +    try {
    +      expect((await loop.runTurn(createUserMessage('first'))).type).toBe('failed');
    +      expect(seen).toHaveLength(0);
    +      expect((await loop.runTurn(createUserMessage('retry'))).type).toBe('done');
    +      expect(prepareInitialTools).toHaveBeenCalledTimes(2);
    +      expect(seen).toHaveLength(1);
    +    } finally {
    +      await loop.close();
    +    }
    +  });
    +
    +  it('does not settle initial tools returned after the first turn was aborted', async () => {
    +    const started = createControlledPromise<void>();
    +    const ready = createControlledPromise<void>();
    +    const seen: LlmRequest[] = [];
    +    const prepareInitialTools = vi.fn(async () => {
    +      started.resolve();
    +      await ready;
    +      return [];
    +    });
    +    const loop = createLoop({
    +      executor: noopExecutor,
    +      input: { profile: { tools: [] } },
    +      prepareInitialTools,
    +      requester: fakeRequester((request) => {
    +        seen.push(request);
    +        return done('reply');
    +      }).with({ model: { spec } }),
    +    });
    +    try {
    +      const first = loop.runTurn(createUserMessage('first'));
    +      await started;
    +      loop.abort();
    +      ready.resolve();
    +      expect((await first).type).toBe('aborted');
    +      expect(seen).toHaveLength(0);
    +      expect((await loop.runTurn(createUserMessage('retry'))).type).toBe('done');
    +      expect(prepareInitialTools).toHaveBeenCalledTimes(2);
    +      expect(seen).toHaveLength(1);
    +    } finally {
    +      ready.resolve();
    +      await loop.close();
    +    }
    +  });
    +
       it('creates one requester snapshot per turn and fills live history and policies', async () => {
         const seen: LlmRequest[] = [];
         let snapshotCount = 0;
    diff --git a/packages/agent-core-v2/test/agent/toolSelect/toolSelect.e2e.test.ts b/packages/agent-core-v2/test/agent/toolSelect/toolSelect.e2e.test.ts
    index 48efc3389..3e6285b2a 100644
    --- a/packages/agent-core-v2/test/agent/toolSelect/toolSelect.e2e.test.ts
    +++ b/packages/agent-core-v2/test/agent/toolSelect/toolSelect.e2e.test.ts
    @@ -131,7 +131,7 @@ describe('progressive tool disclosure end-to-end', () => {
         await ctx.dispose();
       });
     
    -  it('announces MCP tools discovered during startup in the first model request', async () => {
    +  it.each(['inline', 'deferred'] as const)('exposes %s MCP tools discovered during startup with disclosure enabled', async (disclosure) => {
         registration?.dispose();
         const ready = createControlledPromise<void>();
         const waiting = createControlledPromise<void>();
    @@ -143,14 +143,13 @@ describe('progressive tool disclosure end-to-end', () => {
         await waiting;
         expect(ctx.llmCalls).toHaveLength(0);
         registration = ctx.get(IAgentToolRegistryService)
    -      .register(alpha, { source: 'mcp', disclosure: 'deferred' });
    +      .register(alpha, { source: 'mcp', disclosure });
         ready.resolve();
         await ctx.untilTurnEnd();
     
         const firstWire = ctx.llmCalls[0]!;
    -    expect(toolNames(firstWire.tools)).not.toContain(MCP_ALPHA);
    -    expect(historyText(firstWire.history)).toContain('<tools_added>');
    -    expect(historyText(firstWire.history)).toContain(MCP_ALPHA);
    +    expect(toolNames(firstWire.tools).includes(MCP_ALPHA)).toBe(disclosure === 'inline');
    +    expect(historyText(firstWire.history).includes(MCP_ALPHA)).toBe(disclosure === 'deferred');
       });
     
       it('can cancel the first turn while MCP discovery is still pending', async () => {
    @@ -173,6 +172,62 @@ describe('progressive tool disclosure end-to-end', () => {
         expect(ctx.llmCalls).toHaveLength(0);
       });
     
    +  it.each([
    +    { disclosure: 'inline' as const, toolSelect: false },
    +    { disclosure: 'deferred' as const, toolSelect: false },
    +    { disclosure: 'inline' as const, toolSelect: true },
    +    { disclosure: 'deferred' as const, toolSelect: true },
    +  ])(
    +    'exposes $disclosure MCP tools discovered during startup without disclosure (flag: $toolSelect)',
    +    async ({ disclosure, toolSelect }) => {
    +      await ctx.dispose();
    +      registration = undefined;
    +      vi.stubEnv(TOOL_SELECT_FLAG_ENV, toolSelect ? '1' : '0');
    +      const ready = createControlledPromise<void>();
    +      const waiting = createControlledPromise<void>();
    +      ctx = createTestAgent(sessionService(ISessionMcpHandle, {
    +        _serviceBrand: undefined,
    +        get ready() {
    +          waiting.resolve();
    +          return ready;
    +        },
    +        connectionManager: new McpConnectionManager(),
    +        isBaselineServer: () => true,
    +      }));
    +      ctx.configure({
    +        tools: ['Read', 'mcp__*'],
    +        modelCapabilities: { ...DISCLOSURE_CAPABILITIES, dynamically_loaded_tools: !toolSelect },
    +      });
    +      await ctx.restorePersisted();
    +      await ctx.rpc.setPermission({ mode: 'yolo' });
    +      expect(ctx.get(IAgentToolSelectService).enabled()).toBe(false);
    +      ctx.mockNextResponse({ type: 'text', text: 'ready' });
    +
    +      await ctx.rpc.prompt({ input: [{ type: 'text', text: 'use the server tool' }] });
    +      await waiting;
    +      expect(ctx.llmCalls).toHaveLength(0);
    +      registration = ctx.get(IAgentToolRegistryService)
    +        .register(alpha, { source: 'mcp', disclosure });
    +      ready.resolve();
    +      await ctx.untilTurnEnd();
    +
    +      const firstWire = ctx.llmCalls[0]!;
    +      expect(toolNames(firstWire.tools)).toEqual([MCP_ALPHA, 'Read']);
    +      const schema = firstWire.tools.find((tool) => tool.name === MCP_ALPHA);
    +      expect(schema?.parameters).toEqual(alpha.parameters);
    +      expect(schema).not.toHaveProperty('deferred', true);
    +
    +      ctx.mockNextResponse({ type: 'function', id: 'call_alpha', name: MCP_ALPHA, arguments: '{}' });
    +      ctx.mockNextResponse({ type: 'text', text: 'done' });
    +      await ctx.rpc.prompt({ input: [{ type: 'text', text: 'call the server tool' }] });
    +      await ctx.untilTurnEnd();
    +
    +      expect(alpha.calls).toBe(1);
    +      expect(ctx.llmCalls.every((call) => JSON.stringify(call.tools) === JSON.stringify(firstWire.tools)))
    +        .toBe(true);
    +    },
    +  );
    +
       it('announces, loads, preserves schemas through replacements and restore, and keeps the baseline stable', async () => {
         const inlineName = 'mcp__srv__inline';
         const inlineTool = new StubMcpTool(inlineName);
    diff --git a/packages/agent-core-v2/test/agent/toolSelect/toolSelectService.test.ts b/packages/agent-core-v2/test/agent/toolSelect/toolSelectService.test.ts
    index f246ab347..e3d3a645d 100644
    --- a/packages/agent-core-v2/test/agent/toolSelect/toolSelectService.test.ts
    +++ b/packages/agent-core-v2/test/agent/toolSelect/toolSelectService.test.ts
    @@ -649,6 +649,30 @@ describe('AgentToolSelectService gate', () => {
     });
     
     describe('AgentToolSelectService S0 baseline (gate closed)', () => {
    +  it.each([false, true])('preserves an explicit tool baseline without disclosure (flag: %s)', async (enabled) => {
    +    flagEnabled = enabled;
    +    capabilities = makeCapabilities({ tool_use: true, dynamically_loaded_tools: !enabled });
    +    const h = createHarness();
    +    registerBuiltin(h, new EchoTool());
    +    const baseline = h.sut.initialTools();
    +    const alpha = new StubMcpTool(MCP_ALPHA);
    +    const registration = registerMcp(h, alpha);
    +    registerMcp(h, new StubMcpTool(MCP_BETA), 'inline');
    +    registerBuiltin(h, new EchoTool('Denied'));
    +    activeToolNames = new Set(['Echo', MCP_ALPHA, MCP_BETA, MCP_GAMMA]);
    +
    +    const first = await resolveWith(h, { tools: baseline, messages: [], capabilities, dynamic: true });
    +    expect(first.profile?.tools?.map((tool) => tool.name)).toEqual(['Echo']);
    +    expect(first.profile?.tools?.every((tool) => tool.deferred === undefined)).toBe(true);
    +    expect(baseline.map((tool) => tool.name)).toEqual(['Echo']);
    +
    +    registration.dispose();
    +    registerMcp(h, new StubMcpTool(MCP_ALPHA, 'ok', REQUIRED_PAYLOAD_PARAMETERS));
    +    registerMcp(h, new StubMcpTool(MCP_GAMMA));
    +    const next = await resolveWith(h, { tools: baseline, messages: [], capabilities, dynamic: true });
    +    expect(next.profile?.tools).toEqual(first.profile?.tools);
    +  });
    +
       it.each([false, true])('keeps initial schemas pinned without dynamic loading (restored: %s)', async (restoring) => {
         flagEnabled = true;
         const h = createHarness();
    @@ -1054,8 +1078,9 @@ describe('AgentToolSelectService view shaping (gate open)', () => {
         expect(h.sut.requestTools(frozen, true, false)).toBe(frozen);
         expect(h.sut.requestTools(frozen, true, true)).toBe(frozen);
         const staticTools = h.sut.requestTools(shaped, false, true, messages);
    -    expect(staticTools.map((tool) => tool.name)).toEqual(['Echo', MCP_ALPHA]);
    +    expect(staticTools.map((tool) => tool.name)).toEqual(['Echo', MCP_ALPHA, MCP_BETA]);
         expect(staticTools.find((tool) => tool.name === MCP_ALPHA)?.deferred).toBeUndefined();
    +    expect(staticTools.find((tool) => tool.name === MCP_BETA)?.deferred).toBeUndefined();
         expect(h.sut.requestTools(shaped, true, true, messages)).toBe(shaped);
         expect(shaped.find((tool) => tool.name === SELECT_TOOLS_TOOL_NAME)).toBeDefined();
       });
    diff --git a/packages/agent-core-v2/test/session/subagent/forkParity.test.ts b/packages/agent-core-v2/test/session/subagent/forkParity.test.ts
    index a17173ece..9f42826c0 100644
    --- a/packages/agent-core-v2/test/session/subagent/forkParity.test.ts
    +++ b/packages/agent-core-v2/test/session/subagent/forkParity.test.ts
    @@ -33,6 +33,8 @@ import { IAgentToolActivationService } from '#/agent/toolActivation/toolActivati
     import { IAgentToolRegistryService } from '#/agent/toolRegistry/toolRegistry';
     import { IAgentToolPolicyService } from '#/agent/toolPolicy/toolPolicy';
     import { IAgentToolSelectService, SELECT_TOOLS_TOOL_NAME } from '#/agent/toolSelect/toolSelect';
    +import { McpConnectionManager } from '#/mcpCore/connection-manager';
    +import { startInProcessHttpMcpServer } from '../../mcpCore/stubs';
     import { WAIT_FOR_FLAG_ID } from '#/agent/tools/task/task-wait/flag';
     import { IWebSearchProviderService } from '#/app/auth/webSearch/webSearch';
     import { IFlagService } from '#/app/flag/flag';
    @@ -57,8 +59,10 @@ import {
       appService,
       agentServices,
       createMockProvider,
    +  createTestAgent,
       createScriptedGenerate,
       llmGenerateServices,
    +  mcpServices,
       sessionServices,
       telemetryServices,
       testAgent,
    @@ -614,6 +618,46 @@ describe('subagent task reminders and fork request parity', () => {
         expect(taskReminders(child.accessor.get(IAgentLoopService).history())).toHaveLength(1);
       });
     
    +  it.each(['startup', 'runtime'] as const)('keeps btw tools identical after %s MCP discovery', async (timing) => {
    +    const server = await startInProcessHttpMcpServer();
    +    const manager = new McpConnectionManager();
    +    ctx = createTestAgent(
    +      mcpServices({ manager }),
    +      appService(IAppendLogStore, new ScopedAppendLogStore()),
    +      appService(IFlagService, stubFlag(false)),
    +    );
    +    try {
    +      ctx.configure({ tools: ['Read', 'mcp__*'] });
    +      await ctx.restorePersisted();
    +      const config = { srv: { transport: 'http' as const, url: server.url, deferred: false } };
    +      if (timing === 'startup') await manager.connectAll(config);
    +      ctx.mockNextResponse({ type: 'text', text: 'first' });
    +      await ctx.rpc.prompt({ input: [{ type: 'text', text: 'start' }] });
    +      await ctx.untilTurnEnd();
    +      if (timing === 'runtime') await manager.connectAll(config);
    +      ctx.mockNextResponse({ type: 'text', text: 'second' });
    +      await ctx.rpc.prompt({ input: [{ type: 'text', text: 'continue' }] });
    +      await ctx.untilTurnEnd();
    +      const parentTools = ctx.llmCalls[1]!.tools;
    +      expect(parentTools.map((tool) => tool.name)).toEqual(timing === 'startup' ? ['mcp__srv__echo', 'Read'] : ['Read']);
    +      expect(ctx.llmCalls[0]!.tools).toEqual(parentTools);
    +
    +      const childId = await ctx.get(ISessionBtwService).start();
    +      const child = ctx.get(IAgentLifecycleService).handleOf(childId)!;
    +      const childLoop = child.accessor.get(IAgentLoopService);
    +      expect(childLoop.baselineTools()).toEqual(ctx.get(IAgentLoopService).baselineTools());
    +      expect(child.accessor.get(IAgentToolRegistryService).resolve('mcp__srv__echo')).toBeDefined();
    +      ctx.mockNextResponse({ type: 'text', text: 'child' });
    +      const prompt = childLoop.submit({ role: 'user', content: [{ type: 'text', text: 'side question' }] });
    +      expect((await childLoop.promptHandle(prompt.id)!.completion).state).toBe('completed');
    +      expect(ctx.llmCalls[2]!.tools).toEqual(parentTools);
    +    } finally {
    +      await ctx.dispose();
    +      await manager.shutdown();
    +      await server.close();
    +    }
    +  });
    +
       it('keeps btw system, tools and inherited history identical to main', async () => {
         createMainForkCtx();
         await ctx.get(IAgentLoopService).bindProfile({ profile: 'agent', model: 'mock-model' });
    diff --git a/packages/core/src/loop/create-loop.ts b/packages/core/src/loop/create-loop.ts
    index 0b0147040..d4c0c7295 100644
    --- a/packages/core/src/loop/create-loop.ts
    +++ b/packages/core/src/loop/create-loop.ts
    @@ -2,7 +2,7 @@
      * `Loop` interface and `createLoop` entry: the options a host supplies (tool executor, requester,
      * hooks, restored input) and the operations it can call on a running loop.
      */
    -import type { Message, SystemMessage, ToolCall, UserMessage } from '#/llm/message';
    +import type { Message, SystemMessage, ToolCall, ToolDescription, UserMessage } from '#/llm/message';
     import type { PolicyRegistry } from '#/llm/policy/registry';
     import type { ToolExecutionHandler } from '#/tool/runtime';
     import type { WaitOpts } from '#/utils/wait';
    @@ -38,6 +38,7 @@ export interface CreateLoopOptions {
       readonly toolContext?: (turnId: number) => Omit<LoopToolContext, 'turnId'>;
       readonly hooks?: readonly HookRegistration[];
       readonly input?: LoopInput;
    +  readonly prepareInitialTools?: (tools: readonly ToolDescription[], signal: AbortSignal) => Promise<readonly ToolDescription[]>;
       readonly abortGraceMs?: number;
       readonly completionMessage?: ToolCompletionFactory;
       readonly onListenerError?: (error: unknown, event: LoopEmitted) => void;
    diff --git a/packages/core/src/loop/loop-actor.ts b/packages/core/src/loop/loop-actor.ts
    index eb7675d16..c6728c493 100644
    --- a/packages/core/src/loop/loop-actor.ts
    +++ b/packages/core/src/loop/loop-actor.ts
    @@ -70,6 +70,11 @@ import {
     } from './tool/outcome';
     import { createWaitForTasks, type WaitForTasks } from './tool/tasks';
     
    +interface PreparedStepStartingRun extends StepStartingRun {
    +  readonly tools?: readonly ToolDescription[];
    +  readonly preparationFailure?: { readonly error: unknown };
    +}
    +
     interface Deferred<T> {
       readonly promise: Promise<T>;
       resolve(value: T): void;
    @@ -259,7 +264,7 @@ type ActorMessage =
       | { readonly type: 'turn.failed'; readonly turn: LiveTurn; readonly error: unknown }
       | { readonly type: 'step.start'; readonly turn: LiveTurn }
       | { readonly type: 'step.hooks'; readonly turn: LiveTurn; readonly step: StepState }
    -  | { readonly type: 'step.started'; readonly turn: LiveTurn; readonly step: StepState; readonly run: StepStartingRun }
    +  | { readonly type: 'step.started'; readonly turn: LiveTurn; readonly step: StepState; readonly run: PreparedStepStartingRun }
       | { readonly type: 'step.after_starting'; readonly turn: LiveTurn; readonly step: StepState }
       | { readonly type: 'step.ending'; readonly turn: LiveTurn; readonly step: StepState }
       | { readonly type: 'step.ended'; readonly turn: LiveTurn; readonly step: StepState; readonly run: StepEndingRun }
    @@ -321,6 +326,7 @@ class LoopActor implements Loop {
       private profile: LoopProfile | undefined;
       private requesterError: unknown;
       private toolsSettled = false;
    +  private prepareInitialTools: CreateLoopOptions['prepareInitialTools'];
       private revision = 0;
       private seq = 0;
       private kicking = false;
    @@ -352,6 +358,7 @@ class LoopActor implements Loop {
           this.record(event);
         });
         this.requesterTemplate = options.requester;
    +    this.prepareInitialTools = options.prepareInitialTools;
         this.executor = options.executor;
         this.toolContext = options.toolContext;
         this.completionFactory = options.completionMessage;
    @@ -1288,9 +1295,10 @@ class LoopActor implements Loop {
         this.complete(turn, this.stepStarting(turn, step), (run) => ({ type: 'step.started', turn, step, run }));
       }
     
    -  private async stepStarting(turn: LiveTurn, step: StepState): Promise<StepStartingRun> {
    +  private async stepStarting(turn: LiveTurn, step: StepState): Promise<PreparedStepStartingRun> {
    +    let run: StepStartingRun;
         try {
    -      return await runStepStarting(
    +      run = await runStepStarting(
             this.registry,
             {
               turnId: turn.id,
    @@ -1303,6 +1311,13 @@ class LoopActor implements Loop {
         } catch (error) {
           return { messages: this.durable.messages, failures: [runtimeFailure(error)] };
         }
    +    if (run.blocked !== undefined || turn.promptOnly === true || this.prepareInitialTools === undefined) return run;
    +    try {
    +      const tools = await this.prepareInitialTools(this.durable.profile.tools ?? [], step.scope.signal);
    +      return { ...run, tools };
    +    } catch (error) {
    +      return { ...run, preparationFailure: { error } };
    +    }
       }
     
       private finishSteeredStep(turn: LiveTurn, step: StepState): boolean {
    @@ -1318,7 +1333,7 @@ class LoopActor implements Loop {
         return true;
       }
     
    -  private completeStepStarting(turn: LiveTurn, step: StepState, run: StepStartingRun): void {
    +  private completeStepStarting(turn: LiveTurn, step: StepState, run: PreparedStepStartingRun): void {
         if (!this.isCurrentStep(turn, step, 'stepStarting')) return;
         if (this.finishSteeredStep(turn, step)) return;
         const reports = hookFailureReports('step.starting', run.failures);
    @@ -1326,6 +1341,10 @@ class LoopActor implements Loop {
           this.record({ type: 'context.settled', messages: [...run.messages], reason: run.rewrittenBy });
         }
         this.report('step.starting', turn, reports, true);
    +    if (run.preparationFailure !== undefined) {
    +      this.fail(turn, run.preparationFailure.error);
    +      return;
    +    }
         if (run.blocked !== undefined) {
           step.outcome = { type: 'blocked', at: 'step.starting', cause: run.blocked };
           turn.outcome = step.outcome;
    @@ -1333,6 +1352,12 @@ class LoopActor implements Loop {
           step.outcome = { type: 'done', cause: { by: 'loop', reason: 'prompt_only' } };
           turn.outcome = step.outcome;
         } else {
    +      if (run.tools !== undefined) {
    +        this.profile = { ...this.profile, tools: [...run.tools] };
    +        this.record({ type: 'tools.settled', tools: [...run.tools] });
    +        this.toolsSettled = true;
    +        this.prepareInitialTools = undefined;
    +      }
           turn.phase = 'requesting';
         }
         this.post({ type: 'step.after_starting', turn, step });
    diff --git a/.changeset/fix-mcp-tool-visibility.md b/.changeset/fix-mcp-tool-visibility.md
    new file mode 100644
    --- /dev/null
    +++ b/.changeset/fix-mcp-tool-visibility.md
    @@ -0,0 +1,5 @@
    +---
    +'@moonshot-ai/kimi-code': patch
    +---
    +
    +Fix missing MCP tools discovered during session startup.
  2. Aleksey-Forest commented on Nov 16, 2026

    @Aleksey-Forest

    kimi-code-mcp-issue-4904-wire-logs-min.zip

    Confirming the same bug on macOS, CLI v2.6.0, provider managed:kimi-code
    (Kimi For Coding plan). Reproduced 2x; three wire.jsonl sessions attached
    (wire.jsonl, wire-1.jsonl, wire-2.jsonl).

    Identical signature to the report above:

    • mcp.tools_discovered fires for all 4 MCP servers at startup;
      tool_select.initialized registers 102 tools including 75 mcp__* and select_tools.
    • Every llm.tools_snapshot contains only 26 builtin tools — zero mcp__*,
      no select_tools — and stays that way for the whole session (~10 min observed).
    • The model consistently reports it has no MCP tools.

    Data points that may help narrow it down:

    • Baseline stays broken for the entire session. Mid-session model switches
      recompute the snapshot inconsistently: one switch produced a correct
      101-tool snapshot ~10 minutes in; in another session an mcp__ call only
      succeeded after switching away and back.
    • Fresh sessions started on sibling models of the same managed provider
      (k3-256k, kimi-for-coding-highspeed) get the full 101-tool schema —
      so the issue is not provider-wide.
    • In the broken sessions the first prompt was sent immediately at startup;
      MCP discovery events land ~1s later. Consistent with the race described here.
    • Ruled out from the user side: no experimental env vars set; a user-defined
      model alias on the same provider without dynamically_loaded_tools still
      reproduces (not a config-level capability issue); [experimental] tool-select = false
      does not recover the tools (matches the note above).

    No reliable user-side workaround found so far. Happy to test the revised
    patch or provide more logs.

  3. xxchan commented on Nov 18, 2026

    @xxchan

    Still present in 2.6.3, and it also affects the ACP path (kimi acp, session/new with an HTTP MCP server), not only interactive sessions.

    Isolated controls, fresh HOME/KIMI_CODE_HOME, local OpenAI-compatible provider, no real account or model. One HTTP MCP server delays its first tools/list reply by exactly 1000 ms; everything else is immediate; deferred loading off. The session then waits before prompting and sends two prompts:

    Version No delay 1 s tools/list delay
    2.4.1 tool in both requests tool in both requests, 2/2
    2.5.2 tool in both requests tool in both requests, 2/2
    2.5.3 tool in both requests tool in both requests, 2/2
    2.6.0 tool in both requests absent from both requests, 2/2
    2.6.3 tool in both requests absent from both requests, 3/3

    On 2.6.3 the wire shows mcp.tools_discovered and tool_select.initialized containing the tool while both provider tools arrays omit it, the same signature as above. Waiting after discovery and before the first prompt does not help. Source reading on the 2.6.3 tag (b0de2fbd) agrees with the analysis here: initializeLoop() stores requestFactory.baselineTools() before MCP readiness is joined in mcpService.ts, and nothing replaces that baseline afterwards.

    This is separate from #5036 (MCP configuration replaced on resume).

    AI-assisted report from the OAR project's runtime tests; measurements and source references as stated above.


    Agent Cindy wrote this for @xxchan through Stamp (grant cgr_ac42b22a2ac64436db46020f9fd977e8)

  4. namuda commented on Nov 19, 2026

    @namuda

    Independent reproduction and version bisection on Windows 11 (kimi-code win32-x64), confirming this regression and narrowing it down:

    Version kimi -p with a 5s-delay MCP server llm.tools_snapshot
    2.4.1 ✅ tool callable mcp=1
    2.5.3 ✅ tool callable mcp=1
    2.6.0 ❌ tool missing mcp=0
    2.6.2 ❌ tool missing mcp=0
    2.6.3 ❌ tool missing mcp=0
    2.7.0-canary.20261118115856-50ec3c3 ❌ tool missing mcp=0

    So the regression landed in 2.6.0 exactly as analyzed above, and is still present in the latest canary (2026-11-18).

    Additional data points from our sessions (agents/main/wire.jsonl, 2.6.3):

    1. In kimi -p (print mode), the freeze happens very early — before turn.prompt. A fast MCP server that completes discovery before changeNotifier.snapshot is included; anything slower is excluded even when mcp.tools_discovered is recorded well before llm.tools_snapshot:
      L3  changeNotifier.snapshot
      L5  mcp.tools_discovered codebase-memory-mcp=17
      L7  turn.prompt
      L14 llm.tools_snapshot total=26 mcp=0   <- discovery already logged, still excluded
      
    2. Within a print-mode session the snapshot never updates again — forcing a second LLM request (via a builtin tool call) still shows the model zero MCP tools. The "first request waits for MCP startup" behavior (0.33.0) still holds timing-wise, but the frozen baseline isn't refreshed with the discovered tools.
    3. In an interactive 2.6.3 session, a server that finished discovery mid-session was included in the next request's llm.tools_snapshot (472 MCP tools after a late godot-mcp-pro discovery). So the interactive path has some per-request rebuild, while the print/headless path does not. Print mode (CI) is therefore the most severely affected surface.

    Workaround we're using meanwhile: a local HTTP MCP shim that answers initialize/tools/list instantly from a cached schema (HTTP transport connects in-process, so it wins the race against changeNotifier.snapshot) and proxies tools/call to the real stdio server. Works reliably in kimi -p on 2.6.3. Posting here in case it helps others; the proper fix is of course not freezing the baseline before initial MCP discovery settles.

  5. keros68 commented on Nov 21, 2026

    @keros68

    在 Windows 11 + Kimi Code 2.7.2 + kimi-cu-win 0.3.6 + Node.js 24.19.0 上确认,当前 npm 最新版仍复现,使用真实模型 kimi-code/k3.1-pro 和真实 KimiCU MCP 调用验证。

    版本对照(同一台机器、同一插件和配置,均为全新 kimi -p 会话):

    • 2.5.3:首轮 llm.tools_snapshot 为 42 个工具,包含 KimiCU 的 3 个工具;实际 js → kimiCU.list_windows() 成功。
    • 2.6.3 / 2.7.2 原版:mcp.tools_discovered 已记录 plugin-kimi-cu-win:win 的 js、js_reset、js_add_node_module_dir,tool_select.initialized 为 43 个工具,但首轮 llm.tools_snapshot 只有 39 个,KimiCU 全部缺失,模型因此报告没有 js 工具。
    • 等待 MCP 已连接后再发 prompt 仍不能恢复,符合这里描述的“初始化时固定不完整基线”。

    作为本地诊断,将最新 defaultToolsForDisclosure() 中缺失的工具合并进请求后,2.7.2 首轮恢复为 42 个工具并实际调用 KimiCU 成功。这里仅将其作为根因验证,不建议把每次请求合并完整目录作为正式修复;已看到上面关于 same-profile fork invariant 的说明。希望优先评估并合入前面更完整的 startup baseline 修复方案。

  6. added a commit that references this issue on Nov 27, 2026
    0bea2ad
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions