Repository navigation
Description
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.jsonconfigures three servers (stdio +mcp-remoteHTTP). 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,zedand a few ACPs.
Reproduction
- Configure ≥1 MCP server in
~/.jcode/mcp.json. Restart fountain (the jcode daemon). - Confirm the daemon log shows successful connection:
MCP: Connecting to '<server>' (...)followed byMCP: Connected to N server(s) with M tools. - 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.). - Observe in
~/.jcode/logs/jcode-<date>.logthat everyPROVIDER_CANONICAL_INPUTline reports:across all turns.tools_hash=Some(<constant>) tools_json_chars=Some(<constant>) tool_count=Some(<small>) tools_changed=Some(false)tool_countnever grows,tools_changednever flips totrue, andgrep -c 'mcp__' ~/.jcode/logs/*.logreturns0.
Diagnosis
Tracing the relevant code at HEAD 50d2c68b:
src/mcp/tool.rs::create_mcp_tools(lines 104-106) correctly materializes MCP tools with the canonicalmcp__<server>__<tool>name. Namespacing is present.src/tool/mod.rs::Registry::register_mcp_tools(lines 474-563) is called once perhandle_subscribe. It synchronously registers only the"mcp"management tool, thentokio::spawns a background task that runspool.connect_all().await, thencreate_mcp_tools().await, thenregistry.register(...)for eachmcp__*tool. The outer function returns in ~0ms (this matches the observedmcp_register=0mstiming log fromhandle_subscribe).src/server/client_session.rs:521-533callsregister_mcp_toolsand 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 snapshotsregistry.definitions()intoself.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 atsrc/agent.rs:173-176confirms the trade-off.src/agent/turn_execution.rs::unlock_tools_if_needed(lines 221-225) is the only path that dropslocked_tools, and it fires only whentool_name == "mcp"— i.e. when the user explicitly invokes themcpmanagement tool. The LLM never does this because it doesn't seemcp__*tools advertised, so the unlock never triggers automatically.src/tui/app/remote/server_events.rs:940-950handlesMcpStatusevents for the TUI header indicator only; it does not callunlock_toolson 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:
-
Event-driven. Add a
ServerEvent::McpToolsRegisteredvariant emitted from the spawned task inregister_mcp_toolsafter the registration loop completes. Route it server-side to callagent.unlock_tools()on the appropriate Agent. Touches protocol enum + server event router + agent state. -
Notify-based. Wire an
Arc<tokio::sync::Notify>from the per-session Agent intoregister_mcp_tools; fire it from the spawned task after the registration loop. The Agent's turn loop checks/consumes the notification beforetool_definitions(). -
Length comparison in
tool_definitions(~5 LOC). Before returning the cachedlockedsnapshot, compareself.registry.tool_names().await.len()tolocked.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:
- Constructs an Agent with a registry where
register_mcp_toolshas been called but the spawned task hasn't completed. - Calls
tool_definitions()and asserts the snapshot has built-ins only. - Completes the spawned task (e.g., manually registers an
mcp__test__tool). - Calls
tool_definitions()again and asserts the snapshot has grown to include the new tool, andtools_hashhas changed.
Risks and second-order concerns
- Prompt-cache invalidation. The whole point of
locked_toolsis stabletools_hashfor 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
50d2c68bthere is no trust check (src/mcp/pool.rs:67::connect_allconnects 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_toolsinteraction. Whenallowed_toolsisSome(set)(e.g., a skill-scoped subagent),Registry::definitionsatsrc/tool/mod.rs:275filters tool names against the set. Skill frontmatter (src/skill.rs:16) declaresallowed_toolsas static strings with no apparent glob support, so skill-scoped subagents still won't seemcp__*tools unless skills can list patterns likemcp__*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:1247and:1455consume thetools_hashfor staleness indication. The fix should ensure the recomputed hash propagates so the TUI doesn't lie about cache state. - The
tool_count=10discrepancy. I expectedRegistry::base_toolsto surface roughly 25-30 tools, but my session ships 10. There's likely a separateallowed_toolsfilter 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:
- In-session toggle / enable / disable MCP servers without restarting fountain. Today the only way to drop a server is to edit
mcp.jsonand bounce the daemon. - Refresh / reconnect a specific MCP server from inside a session. The
unlock_toolsmachinery exists (used by themcptool path and the debug socket atsrc/server/debug_command_exec.rs:303) but isn't reachable through a user-facing command or hotkey. - 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
1jehuang commentedon May 31, 2026
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 viaregister_mcp_tools()'stokio::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 resetslocked_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 markingtriage: needs-decisionrather than a quick mechanical fix. Your diagnosis was accurate.1jehuang commentedon Jun 1, 2026
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 eachmcp__*tool into the registry, then only emitsServerEvent::McpStatus. There is noMcpToolsRegisteredevent or agent unlock signal. MeanwhileAgent::tool_definitionsstill returnslocked_toolsunconditionally when present (crates/jcode-app-core/src/agent/turn_execution.rs:277-305), andunlock_tools_if_neededonly unlocks after themcpmanagement 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 cachedlocked_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 syntheticmcp__test__toolregistration, registers it, then asserts the nexttool_definitionsincludes it. Not implementing here per triage scope.fix(mcp): surface MCP tools that register after the tool snapshot loc…
1jehuang commentedon Jun 1, 2026
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 backgroundtokio::spawndoes onceconnect_all().awaitresolves), and asserts the agent's tool surface includes it. Before the fix it failed:(Aside: locally the base set is 30 tools, not 10 — so the
tool_count=10you 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_toolsfiltering rather than a raw length compare.Agent::tool_definitions()now, when it has a locked snapshot, checks whether the registry containsmcp__*tools (subject to the session'sallowed_tools/disabled_toolsfilters) 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:
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.connect_all/registration needs no change here.Tests
Three assertions, all green:
mcp__test__write_memorybecomes visible on the next turn (the core regression).Not addressed here (orthogonal, as you flagged)
allowed_toolsglob gap for skill-scoped subagents (skills can't yet listmcp__*patterns) — separate feature, the filter logic above respectsallowed_toolsso a skill that names MCP tools explicitly will see them.tools_hashstaleness 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.
mcp: make late-registration tool refresh one-shot + surface it (#206 …
mcp: disk-cache tool schemas + connect-on-first-call (#206 Phase 2)
mcp: advertise cached tools at spawn + reconcile cache on connect (#206…
release: v0.18.0
1 remaining item
fix(mcp): surface MCP tools that register after the tool snapshot loc…
mcp: make late-registration tool refresh one-shot + surface it (1jehu…
mcp: disk-cache tool schemas + connect-on-first-call (1jehuang#206 Ph…
mcp: advertise cached tools at spawn + reconcile cache on connect (1j…
release: v0.18.0
feat(cli): load MCP tools in headless `jcode run` (1jehuang#390)
fix(mcp): surface MCP tools that register after the tool snapshot loc…
mcp: make late-registration tool refresh one-shot + surface it (1jehu…
mcp: disk-cache tool schemas + connect-on-first-call (1jehuang#206 Ph…
mcp: advertise cached tools at spawn + reconcile cache on connect (1j…
release: v0.18.0
feat(cli): load MCP tools in headless `jcode run` (1jehuang#390)
mcp: auto mode never busts the prompt cache on any provider
mcp: auto mode never busts the prompt cache on any provider
refactor(decollision): rename jcode to kcode (#33)