Skip to content

MCP tools never reach the agent: locked_tools snapshot races the async MCP-register tokio::spawn #206

Closed

Description

@jerudnik

MCP tools never reach the agent: locked_tools snapshot races the async MCP-register tokio::spawn

Summary

In jcode v0.12.1 (f6ce4fd8), MCP servers declared in ~/.jcode/mcp.json connect successfully and the daemon logs Connected to N server(s) with M tools, but the agent's tool surface never includes them. Every PROVIDER_CANONICAL_INPUT log line shows a stable small tool_count (Some(10)), tools_changed=Some(false), fixed tools_hash, and grep -c 'mcp__' ~/.jcode/logs/*.log returns 0. This is true in fresh sessions, resumed sessions, and subagent dispatches.

Not a missing bridge issue; the mcp__<server>__<tool> namespacing is correctly implemented in src/mcp/tool.rs:104-106. It looks like a race between async MCP server connection and the agent's first-turn tool-list snapshot, governed by a tool-list lock that was added to preserve provider prompt-cache stability.

Environment

  • jcode v0.12.1 (f6ce4fd8) (Homebrew tap, /opt/homebrew/bin/jcode).
  • macOS 26.4.1 on Apple Silicon (arm64).
  • Provider: claude (OAuth, claude-opus-4-7).
  • ~/.jcode/mcp.json configures three servers (stdio + mcp-remote HTTP). All three connect cleanly per daemon log.
  • May or may not matter (because I have skill issues): system configuration via nix-darwin + home-manager; MCP servers built by nix and symlinked in. These servers are confirmed working with claude, codex, opencode, zed and a few ACPs.

Reproduction

  1. Configure ≥1 MCP server in ~/.jcode/mcp.json. Restart fountain (the jcode daemon).
  2. Confirm the daemon log shows successful connection: MCP: Connecting to '<server>' (...) followed by MCP: Connected to N server(s) with M tools.
  3. Open any agent session and ask the agent to list its tools or call a known MCP tool (mcp__serena__write_memory, mcp__bifrost-gateway__executeToolCode, etc.).
  4. Observe in ~/.jcode/logs/jcode-<date>.log that every PROVIDER_CANONICAL_INPUT line reports:
    tools_hash=Some(<constant>) tools_json_chars=Some(<constant>) tool_count=Some(<small>) tools_changed=Some(false)
    
    across all turns. tool_count never grows, tools_changed never flips to true, and grep -c 'mcp__' ~/.jcode/logs/*.log returns 0.

Diagnosis

Tracing the relevant code at HEAD 50d2c68b:

  • src/mcp/tool.rs::create_mcp_tools (lines 104-106) correctly materializes MCP tools with the canonical mcp__<server>__<tool> name. Namespacing is present.
  • src/tool/mod.rs::Registry::register_mcp_tools (lines 474-563) is called once per handle_subscribe. It synchronously registers only the "mcp" management tool, then tokio::spawns a background task that runs pool.connect_all().await, then create_mcp_tools().await, then registry.register(...) for each mcp__* tool. The outer function returns in ~0ms (this matches the observed mcp_register=0ms timing log from handle_subscribe).
  • src/server/client_session.rs:521-533 calls register_mcp_tools and awaits only the synchronous portion; the spawned task is never awaited.
  • src/agent/turn_execution.rs::Agent::tool_definitions (lines 277-301) is called on every agent turn to build the tool list sent to the provider. On first call, it snapshots registry.definitions() into self.locked_tools. All subsequent calls return the cached snapshot. The comment at lines 282-283 explicitly states the intent: "Return locked tools if available (prevents cache invalidation from MCP tools arriving asynchronously after the first API request)." The matching field declaration at src/agent.rs:173-176 confirms the trade-off.
  • src/agent/turn_execution.rs::unlock_tools_if_needed (lines 221-225) is the only path that drops locked_tools, and it fires only when tool_name == "mcp" — i.e. when the user explicitly invokes the mcp management tool. The LLM never does this because it doesn't see mcp__* tools advertised, so the unlock never triggers automatically.
  • src/tui/app/remote/server_events.rs:940-950 handles McpStatus events for the TUI header indicator only; it does not call unlock_tools on the server-side Agent.

The race: the user's first prompt typically arrives within a few hundred milliseconds of session start, well before pool.connect_all().await resolves (which takes seconds for stdio handshakes and longer for mcp-remote HTTP wrappers). tool_definitions therefore snapshots a registry containing only the ~10 built-ins plus the "mcp" management tool, and that snapshot is reused forever — the tools_hash stays constant, the tools_changed=false flag stays false, and the LLM is permanently blind to the MCP catalog.

The cache-stability optimization (designed to keep provider prompt-cache hits warm) is unconditionally winning over the MCP-arrival path because the unlock signal that would correct it never fires.

Possible fixes

Three viable shapes:

  1. Event-driven. Add a ServerEvent::McpToolsRegistered variant emitted from the spawned task in register_mcp_tools after the registration loop completes. Route it server-side to call agent.unlock_tools() on the appropriate Agent. Touches protocol enum + server event router + agent state.

  2. Notify-based. Wire an Arc<tokio::sync::Notify> from the per-session Agent into register_mcp_tools; fire it from the spawned task after the registration loop. The Agent's turn loop checks/consumes the notification before tool_definitions().

  3. Length comparison in tool_definitions (~5 LOC). Before returning the cached locked snapshot, compare self.registry.tool_names().await.len() to locked.len(). If the registry has grown, drop the lock and rebuild the snapshot once. This costs exactly one provider-prompt-cache miss per session — the turn during which MCP tools first appear — which seems acceptable given MCP servers register at most once per session under normal operation.

A test could be added that:

  1. Constructs an Agent with a registry where register_mcp_tools has been called but the spawned task hasn't completed.
  2. Calls tool_definitions() and asserts the snapshot has built-ins only.
  3. Completes the spawned task (e.g., manually registers an mcp__test__tool).
  4. Calls tool_definitions() again and asserts the snapshot has grown to include the new tool, and tools_hash has changed.

Risks and second-order concerns

  • Prompt-cache invalidation. The whole point of locked_tools is stable tools_hash for provider-side prompt cache hits. Option 3 invalidates the cache exactly once per session (at the MCP-arrival transition) and is stable thereafter; that's the right shape, but the fix must be careful not to flap if MCP servers reconnect or arrive in stages. A simple "if length grew, snapshot once and re-lock" is the safest invariant.
  • Trust gate (Require explicit trust approval before starting project-local MCP servers #64). Issue Require explicit trust approval before starting project-local MCP servers #64 ("Require explicit trust approval before starting project-local MCP servers") implies a future trust layer. Auto-surfacing MCP tools the moment they register is exactly what Require explicit trust approval before starting project-local MCP servers #64 would gate. As of HEAD 50d2c68b there is no trust check (src/mcp/pool.rs:67::connect_all connects unconditionally), but whichever fix lands here should be designed so that a subsequent trust gate slots in cleanly — probably by gating the registration itself, not the unlock signal, so this fix doesn't need to change.
  • allowed_tools interaction. When allowed_tools is Some(set) (e.g., a skill-scoped subagent), Registry::definitions at src/tool/mod.rs:275 filters tool names against the set. Skill frontmatter (src/skill.rs:16) declares allowed_tools as static strings with no apparent glob support, so skill-scoped subagents still won't see mcp__* tools unless skills can list patterns like mcp__* or explicit names. That's an orthogonal feature gap worth tracking separately — fixing the unlock race doesn't address it.
  • TUI status panel. src/tui/app.rs:1247 and :1455 consume the tools_hash for staleness indication. The fix should ensure the recomputed hash propagates so the TUI doesn't lie about cache state.
  • The tool_count=10 discrepancy. I expected Registry::base_tools to surface roughly 25-30 tools, but my session ships 10. There's likely a separate allowed_tools filter applied for this provider/session/skill mode that I haven't traced. This doesn't change the diagnosis (whatever the locked size, it's frozen pre-MCP) but is worth confirming as part of the fix to make sure MCP tools are not inadvertently filtered by the same mechanism.

Related: secondary asks (lower priority, listed for context)

These would naturally pair with the unlock fix but aren't blockers:

  1. In-session toggle / enable / disable MCP servers without restarting fountain. Today the only way to drop a server is to edit mcp.json and bounce the daemon.
  2. Refresh / reconnect a specific MCP server from inside a session. The unlock_tools machinery exists (used by the mcp tool path and the debug socket at src/server/debug_command_exec.rs:303) but isn't reachable through a user-facing command or hotkey.
  3. Surface MCP-server connection state to the agent, not just the TUI. Currently the agent can only discover failures by attempting a call.

Happy to test try writing a PR or testing a candidate fix against this repro on the same machine if helpful.

Activity

  1. added
    bug
    priority: high
    triage: needs-decision
    on May 31, 2026
  2. 1jehuang commented on May 31, 2026

    @1jehuang
    Owner

    Triage note: this race is still present by design. Agent::tool_definitions() (crates/jcode-app-core/src/agent/turn_execution.rs ~L282-303) intentionally locks the tool list on the first turn for prompt-cache stability and returns the cached snapshot thereafter; MCP tools register asynchronously via register_mcp_tools()'s tokio::spawn (crates/jcode-app-core/src/tool/mod.rs). If the lock snapshot is taken before that spawn finishes connecting/registering, MCP tools won't surface until something resets locked_tools (turn boundary / compaction / model change). Reconciling cache stability with late-arriving MCP tools (e.g. await MCP-connect before the first lock, or force a single re-lock on first MCP registration) is a design decision that touches the cache invariant, so marking triage: needs-decision rather than a quick mechanical fix. Your diagnosis was accurate.

  3. added
    triage: reproducible
    on Jun 1, 2026
  4. 1jehuang commented on Jun 1, 2026

    @1jehuang
    Owner

    Repro confirmed by current code reading. MCP tools are still registered asynchronously in Registry::register_mcp_tools (crates/jcode-app-core/src/tool/mod.rs:677-721): the spawned task registers each mcp__* tool into the registry, then only emits ServerEvent::McpStatus. There is no McpToolsRegistered event or agent unlock signal. Meanwhile Agent::tool_definitions still returns locked_tools unconditionally when present (crates/jcode-app-core/src/agent/turn_execution.rs:277-305), and unlock_tools_if_needed only unlocks after the mcp management tool runs (turn_execution.rs:221-224). So the first-turn snapshot can still permanently hide late-arriving MCP tools.

    Clear mechanical fix path: in Agent::tool_definitions, before returning the cached locked_tools, compare the current filtered registry definitions (or at least visible tool count/names after allowed/disabled/selfdev filtering) against the locked snapshot; if the visible set has grown, drop/rebuild the lock and reset cache tracking once. Add a unit test that locks before a synthetic mcp__test__tool registration, registers it, then asserts the next tool_definitions includes it. Not implementing here per triage scope.

  5. removed
    triage: needs-decision
    on Jun 1, 2026
  6. added
    triage: fixed
    on Jun 1, 2026
  7. 1jehuang commented on Jun 1, 2026

    @1jehuang
    Owner

    Reproduced and fixed in 2f8af3f7.

    Reproduced

    Your diagnosis was exactly right. I added a failing regression test that locks the tool snapshot (as the first turn does), then registers an mcp__* tool afterward (as the background tokio::spawn does once connect_all().await resolves), and asserts the agent's tool surface includes it. Before the fix it failed:

    regression #206: MCP tool registered after the first turn never reaches the
    agent's tool surface (locked snapshot of 30 tools is reused forever)
    

    (Aside: locally the base set is 30 tools, not 10 — so the tool_count=10 you saw isn't an MCP-specific filter, just your build's base count. The freeze behavior is identical regardless of size, as you noted.)

    Fix

    I went with your option 3 (the safest, lowest-churn shape), refined to be robust against the allowed_tools/disabled_tools filtering rather than a raw length compare. Agent::tool_definitions() now, when it has a locked snapshot, checks whether the registry contains mcp__* tools (subject to the session's allowed_tools/disabled_tools filters) that are absent from the locked snapshot. If so, it unlocks and rebuilds once, then re-locks. Otherwise it returns the cached snapshot verbatim, exactly as before.

    Properties:

    • One cache miss per session, on the turn MCP tools first appear; stable thereafter. No flapping.
    • Single chokepoint. The fix lives in tool_definitions(), which every turn path (run_turn, run_turn_streaming, run_turn_streaming_mpsc) funnels through, so fresh sessions, resumed sessions, and subagent dispatches are all covered.
    • Cache stability preserved. Non-MCP registry changes never invalidate the snapshot (guarded by a test). Only late MCP arrival yields.
    • Trust gate (Require explicit trust approval before starting project-local MCP servers #64) slots in cleanly. As you recommended, this gates on the unlock signal, not registration, so a future trust layer that gates connect_all/registration needs no change here.

    Tests

    Three assertions, all green:

    1. A late-registered mcp__test__write_memory becomes visible on the next turn (the core regression).
    2. Once present, the snapshot is stable across subsequent turns (cache stays warm).
    3. A non-MCP tool registered after lock does not invalidate or leak into the snapshot.

    Not addressed here (orthogonal, as you flagged)

    • The allowed_tools glob gap for skill-scoped subagents (skills can't yet list mcp__* patterns) — separate feature, the filter logic above respects allowed_tools so a skill that names MCP tools explicitly will see them.
    • The TUI tools_hash staleness panel — the recomputed snapshot flows through the normal hashing path on the rebuild turn, so the hash updates correctly.

    Thanks for the genuinely excellent writeup — code paths, line numbers, the race timing, and three ranked fix options made this fast.

  8. 1 remaining item

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

    bugpriority: hightriage: fixedtriage: reproducible

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions