Skip to content

feat: add MCP support to jcode run (headless single-message mode) #390

Closed

Description

@codebyshoaib

Problem

jcode run "prompt" creates a bare Registry::new() without calling register_mcp_tools, so MCP servers configured in ~/.jcode/mcp.json are never loaded. The agent has no MCP tools available in headless mode.

This is the code path in src/cli/commands.rs:

pub async fn run_single_message_command(...) -> Result<()> {
    let registry = crate::tool::Registry::new(provider.clone()).await;
    let mut agent = crate::agent::Agent::new(provider.clone(), registry);
    // ↑ no register_mcp_tools call — MCP never loads
    ...
}

By contrast, the server path (jcode serve → create_headless_session) correctly calls register_mcp_tools with the shared pool.

Impact

Any workflow that uses jcode run for scripting or automation (e.g. CI pipelines, per-job agent spawning via shell scripts) gets zero MCP tools, even with a fully populated ~/.jcode/mcp.json.

Proposed fix

Add register_mcp_tools to run_single_message_command, similar to how create_headless_session does it:

let registry = crate::tool::Registry::new(provider.clone()).await;
registry.register_mcp_tools(None, None, None).await;  // load from ~/.jcode/mcp.json
let mut agent = crate::agent::Agent::new(provider.clone(), registry);

Since MCP connections happen in background (non-blocking), this adds negligible startup latency for short runs. A --no-mcp flag could skip it for latency-sensitive scripting if needed.

Environment

  • jcode v0.30.2 (5e7ab42)
  • Linux x86_64
  • MCP servers configured: codebase-memory-mcp, notion, slack

Activity

  1. codebyshoaib commented on Jun 20, 2026

    @codebyshoaib
    Author

    Update: the server path (jcode serve) has a related but distinct bug

    After filing this, I tested whether the server path works around it. It doesn't — there's a second, deeper issue worth flagging here.

    What I tested

    Started jcode serve (v0.30.2) with display.debug_socket = true, created a headless session via the debug socket, and waited for the MCP pool to warm up. The logs confirm all servers connect cleanly:

    MCP: Connected to 'codebase-memory-mcp' with 14 tools
    MCP: Connected to 'slack' with 8 tools
    MCP: Connected to 'notion' with 22 tools
    MCP pool: session 'headless' acquired 3 server handle(s)
    

    jcode debug -S <session> tools shows all 44 mcp__* tools in the registry, and direct execution works — tool:mcp__slack__slack_list_channels {"limit":3} returned real channel data from the live Slack workspace.

    The bug

    When the model runs a turn (via message / message_async), the MCP tools never reach the API request. From PROVIDER_CANONICAL_INPUT in the logs:

    tool_count=Some(9) tools_json_chars=Some(2910) tools_hash=14934252255076953967
    

    Only 9 tools are sent to Anthropic — none of them MCP — and the tools_hash is identical across a fresh jcode run and a warm server session, i.e. it's a fixed minimal snapshot that never picks up the registered MCP tools. The model consequently insists it has no MCP tools, even though the registry holds 44 and they're directly invocable.

    This looks like the "MCP tools registered after first turn locked the tool snapshot" path (the string is in the binary, and there's a prior fix #206 referencing it) — but it's still reproducing in v0.30.2 on both paths:

    • jcode run: never calls register_mcp_tools at all (the original report above)
    • jcode serve session: registers them, but the model's tool snapshot is locked to the 9-tool default before/independent of MCP registration

    Net effect

    MCP is effectively unusable for agentic workflows on either path today: the tools connect and are callable programmatically, but the model is never told they exist, so it can't decide to call them.

    Environment: jcode v0.30.2 (5e7ab42), Linux x86_64. Servers: codebase-memory-mcp, notion, slack.

  2. codebyshoaib commented on Jun 20, 2026

    @codebyshoaib
    Author

    Confirmed: the interactive TUI is affected too — this is not a headless-only bug

    Tested the normal interactive TUI (jcode with a connected terminal client, not run or the debug socket). Asked it to list Slack channels.

    Result: the model reported it could not access the Slack MCP tools and fell back to a raw API query via bash — and that fallback only surfaced a partial result. So MCP is unusable for the model on all three paths in v0.30.2:

    Path MCP servers connect? Tools in registry? Directly callable? Model receives tools?
    jcode run n/a (never registers) no no no
    debug session (create_session → create_headless_session) yes yes (debug tools shows 44) yes (tool:mcp__slack__... returns real data) no (tool_count=9)
    interactive TUI yes yes — no (model falls back to raw bash)

    The common symptom across the registering paths: the API request the model sees is locked to a 9-tool snapshot (tool_count=Some(9), identical tools_hash across sessions) that never contains the mcp__* tools, even on the second turn where the late-registration recovery (#206) is supposed to rebuild. The recovery's registry_has_new_mcp_tools check apparently sees nothing new, which suggests the agent's own registry (the one feeding tool_definitions) is a different view from the one debug tools reports — i.e. register_mcp_tools is populating a pool/registry that the agent's turn loop doesn't read from, or mcp_pool is arriving as None at the agent-construction call site.

    Net: MCP tools connect and are callable out-of-band, but never reach the model in any user-facing path. Happy to run more diagnostics if useful.

  3. codebyshoaib commented on Jun 20, 2026

    @codebyshoaib
    Author

    Correction to my previous comment — the interactive TUI is NOT broken

    My earlier "TUI affected too" claim was wrong, and I want to correct the record.

    On retest: in the interactive TUI, when the agent itself configures and connects MCP (correct env, then connecting via the mcp tool), the model does receive the mcp__* tools and uses them successfully (it listed Slack channels). My earlier TUI failure was an env/config problem on my end, not a jcode defect.

    The likely mechanism: agent-initiated mcp connect/reload hits the unlock_tools() path and rebuilds the tool snapshot, so the freshly-connected tools surface to the model. My failing tests relied on passive auto-registration from ~/.jcode/mcp.json — the servers connect, but the model's locked 9-tool snapshot is never rebuilt to include them (the late-registration recovery didn't fire in the debug-socket session path).

    So the accurate, narrowed report is:

    • jcode run (headless single-message): still legitimately lacks any register_mcp_tools call — the original issue stands.
    • Passive auto-registration from mcp.json: servers connect but tools may not surface to the model unless the snapshot is unlocked (e.g. the agent invokes the mcp tool). Possibly a UX/timing gap rather than a hard bug.
    • Interactive TUI with agent-driven MCP connect: works correctly. Withdrawing my claim that it was affected.

    Apologies for the noise in the prior comment.

  4. 1jehuang commented on Jun 21, 2026

    @1jehuang
    Owner

    Thanks for the careful investigation, and especially for the follow-up corrections, they're spot on. Here's how the MCP-in-tool-snapshot system actually works, why the "9-tool locked snapshot" you saw is expected on a cold cache, and the fix for jcode run.

    How the tool snapshot + MCP loading works

    There are two cooperating layers. The design goal is: the user can talk to the agent the instant a session spawns, with zero startup delay and zero prompt-cache miss, even though MCP servers can be slow to connect or hang.

    1. Snapshot locking (cache stability)

    Agent::tool_definitions() (in crates/jcode-app-core/src/agent/turn_execution.rs) locks the tool list on the first turn (locked_tools). This keeps the provider prompt-cache stable: tools that arrive asynchronously mid-session don't silently invalidate the cache.

    2. Advertise-early (the part that avoids the cache miss)

    Registry::register_mcp_tools() (in crates/jcode-app-core/src/tool/mod.rs) does not block on connections. At spawn it:

    1. Loads the on-disk schema cache (McpSchemaCache::load()) and registers proxy mcp__* tools for each configured server synchronously, before any connection settles. So the first locked snapshot already contains the MCP tools. The log line is:
      MCP: advertised N cached tool(s) from M server(s) at spawn
      (connect-on-first-call); zero prompt-cache miss expected (#206)
      
    2. Spawns a background task that actually connects (connect_all()), then re-registers the live schemas (idempotent, handles schema drift) and reconciles the on-disk schema cache with the live tools so the next spawn is also zero-miss.

    The proxies are connect-on-first-call: if the model invokes an MCP tool before the background connection finishes, that single call connects synchronously and then proceeds. So there's no "tools missing" window for the model and no blocking wait for the user.

    3. Cold-cache fallback (the one intentional miss)

    If a server has no cached schema yet (first time ever using it, or its config fingerprint changed), advertise-early has nothing to register for it. For that case there's a one-shot recovery in tool_definitions(): exactly once per locked snapshot, if mcp__* tools have since appeared in the registry, it drops the stale snapshot and rebuilds (mcp_late_register_resolved guards it to a single rescan). That rebuild is the one intentional prompt-cache miss, accepted only because we refuse to block spawn on MCP connection.

    So: steady state = zero cache miss, zero delay. The tool_count=9 / fixed tools_hash you observed is the cold-cache state, before the schema cache is populated. After one successful run that reaches connect_all() + cache reconcile, subsequent spawns advertise the cached MCP tools up front and the model sees them on turn one. Your comment-3 correction matches this exactly: agent-driven mcp connect hits unlock_tools() and forces a rebuild, while passive auto-registration relies on advertise-early (warm cache) or the one-shot recovery (cold cache).

    The jcode run bug (confirmed + fixed)

    You're right that jcode run was the genuine, unambiguous defect: run_single_message_command built a bare Registry::new() and never called register_mcp_tools at all, so neither layer above ran. No advertise-early, no background connect, no cache. MCP was simply absent from headless single-message mode.

    Fixed in 53cae6cb: jcode run now calls register_mcp_tools(None, None, None) (loads ~/.jcode/mcp.json), so it gets the same advertise-early + background-connect behavior as the other paths. As you noted, this adds negligible startup latency for short runs because connection is backgrounded. I also added a JCODE_RUN_MCP=0 opt-out for latency-sensitive scripting.

    Verified against a configured server:

    $ jcode run "List every tool you have starting with 'mcp__'."
    mcp__agentcard__check_balance, mcp__agentcard__create_card, ... (8 tools)
    
    $ JCODE_RUN_MCP=0 jcode run "...same prompt..."
    NONE
    

    Summary vs. your final narrowed report

    • jcode run: fixed, now registers MCP tools (with JCODE_RUN_MCP=0 opt-out).
    • Passive auto-registration from mcp.json: working as designed; the tool_count=9 you saw is the cold-cache fallback. Once the schema cache is warm (after one connect), advertise-early puts MCP tools in the first snapshot with no cache miss. If you can reproduce the model not seeing MCP tools on a warm cache (i.e. a second spawn after servers previously connected), that would be a real bug in the one-shot recovery / cache reconcile, and I'd love a repro.
    • Interactive TUI: works (your correction confirmed).
  5. 1jehuang commented on Jun 21, 2026

    @1jehuang
    Owner

    Follow-up: there was one real UX gap, now also fixed

    After replying I tested the cold-cache case honestly instead of asserting it, and you were effectively right that something was still off for jcode run. Here's the finding and the fix.

    The cold-cache gap

    Advertise-early can only pre-register tools for servers whose schemas are already in ~/.jcode/mcp-schema-cache.json. On a cold cache (first-ever use of a server, or one whose config changed), it registers nothing for that server, and a single-turn jcode run locks its tool snapshot before the background connection finishes. Long-lived sessions recover on a later turn via the one-shot late-registration rebuild, but jcode run has no later turn, so the model saw NONE.

    Reproduced precisely:

    $ rm ~/.jcode/mcp-schema-cache.json        # cold cache
    $ jcode run "List every tool starting with 'mcp__'. If none, say NONE."
    NONE                                        # <-- gap
    
    $ jcode run "...same..."                    # cache now warm
    mcp__agentcard__check_balance, ... (8 tools)   # <-- works from 2nd run on
    

    So jcode run was reliable from the second invocation, but the very first run on a fresh machine silently had no MCP. For a scripting/CI tool that's exactly where it bites.

    Fix (#390)

    When (and only when) a configured server has no cached schema, jcode run now briefly polls the registry until that server's mcp__* tools register, bounded by JCODE_RUN_MCP_WAIT_MS (default 5000ms, set 0 to disable). Warm runs detect a populated cache and skip the wait entirely, staying instant.

    Verified:

    # cold cache + wait fix
    $ rm ~/.jcode/mcp-schema-cache.json
    $ jcode run "List every tool starting with 'mcp__'..."
    mcp__agentcard__check_balance, ... (8 tools)   # now works on first run
    
    # warm cache -> no wait
    $ time jcode run "Reply with exactly: OK"
    OK
    real 0m2.7s
    
    # opt-out
    $ JCODE_RUN_MCP=0 jcode run "..."
    NONE
    

    Summary of the jcode run changes

    • register_mcp_tools is now wired into headless single-message mode (the original report).
    • Cold-cache first run no longer drops MCP tools (this follow-up).
    • Env knobs: JCODE_RUN_MCP=0 to skip MCP entirely; JCODE_RUN_MCP_WAIT_MS to tune/disable the cold-cache wait.

    Fixed in 53cae6cb + 72801ba1, shipping in v0.30.3. The passive-auto-registration (non-run) and interactive paths remain as described above; if you ever see the model miss MCP tools on a warm cache there, that'd be a separate bug and I'd want a repro. Thanks again for the detailed reports.

  6. added
    enhancement
    triage: fixed-pending-release
    on Jun 24, 2026
  7. 1jehuang commented on Jun 24, 2026

    @1jehuang
    Owner

    Triage: this is already implemented in master — run_single_message_command in src/cli/commands.rs now calls registry.register_mcp_tools(None, None, None) (gated by run_command_mcp_enabled()) plus a cold-cache wait so the first locked tool snapshot includes mcp__* tools. Will close automatically on the next release.

  8. 1jehuang commented on Jun 28, 2026

    @1jehuang
    Owner

    Released in v0.32.0. Run jcode update to get it.

  9. removed
    triage: fixed-pending-release
    on Jun 28, 2026
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

    enhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions