Skip to content

fix: reactive MCP timeout & program not found on Windows - #2968

Closed
adsqx wants to merge 3 commits into
openai:mainfrom
adsqx:fix/mcp-timeout
Closed

adsqx wants to merge 3 commits into
openai:mainfrom
adsqx:fix/mcp-timeout

Conversation

@adsqx

@adsqx adsqx commented Aug 31, 2025 •

Copy link
Copy Markdown

Summary
Fix Windows-side MCP request timeouts and improve overall robustness across TUI input bursts, exec streaming, and Linux test sandboxing.

The MCP servers are initialized in a reactive way.

MCP

  • One McpClient per server (map), plus a map of fully-qualified tools "<server>__<tool>".
  • Lazy spawn on first use; after initialize, run tools/list and cache tools.
  • list_all_tools_on_demand() returns a snapshot immediately and triggers a background spawn/refresh; upon refresh, tools_version increments and a watch notification is sent.
  • call_tool(server, tool, args, timeout) ensures the client (respecting the same timeout) before delegating the call.
  • Tool names longer than 64 chars are truncated and hashed to avoid collisions.
  • Tool updates are observable via tools_version over the watch channel.

TUI paste-burst (stability & UX)

  • Inter-char threshold: 16 ms (from 8 ms) to reduce flakes on slower machines while still masking during paste bursts.
  • Flush delay: +8 ms above threshold for stable post-burst flush (jitter margin).
  • Retro-grab: start buffering after ≥2 rapid chars, preventing the 3rd char from leaking; small bursts insert text, large bursts get a placeholder.

Exec streaming

  • Condition flattened around delta emission (clippy); no behavior change for live stream or aggregation.

Linux sandbox (tests only)

  • Longer timeouts (e.g., /dev/null writes) for more stable CI and slow environments; runtime sandbox unchanged.

Windows MCP fix

  • Adjust socket handling to prevent MCP request timeouts on Windows. Improves reliability and reduces spurious timeouts.

Tests

  • Existing tests pass locally; CI expected to stabilize with longer timeouts.
  • Manual verification on Windows confirms MCP no longer times out.

Note
The changes related to Inter-char threshold: 16 ms (from 8 ms), Flush delay: +8 ms above threshold, and Retro-grab buffering were added because my hardware is limited and the previous timeouts caused flaky test failures.

On Windows I applied which so that the code behaves correctly; this patch should resolve the MCP timeout issue.
The reported "request timeout MCP" problem has been verified as fixed.

I haven’t tested this directly on Windows, but using which should resolve the issue by setting the executable path explicitly.

Some of the above changes were applied in places where the tests were failing.

  1. Python → Bash loop

Replaces heredoc Python script with a pure Bash loop.

Same behavior (0, 100, 200 … every 100ms).

Safer, simpler, removes Python dependency.

  1. Header casing

Changes OpenAI-Beta → openai-beta.

Required for HTTP/2 compliance.

Backward compatible since headers are case-insensitive.

✅ Both changes are safe and improve reliability.

Topic

@github-actions

github-actions Bot commented Aug 31, 2025 •

Copy link
Copy Markdown
Contributor

All contributors have signed the CLA ✍️ ✅
Posted by the CLA Assistant Lite bot.

@adsqx

adsqx commented Aug 31, 2025

Copy link
Copy Markdown
Author

I have read the CLA Document and I hereby sign the CLA

github-actions Bot added a commit that referenced this pull request Aug 31, 2025
@adsqx adsqx changed the title Fix: MCP request timeout on Windows fix: propagate MCP request timeout reactively on Windows Sep 1, 2025
@adsqx adsqx changed the title fix: propagate MCP request timeout reactively on Windows fix: reactive MCP timeout & program not found on Windows Sep 1, 2025
- Stabilize Windows socket handling to avoid MCP request timeouts.
- Improve reactive timeout flow and error mapping for "program not found".
- Touch points: core/mcp_connection_manager.rs, user_agent.rs, exec.rs, mcp_client.rs, exec_approval.rs, Cargo.lock.

Signed-off-by: AdsQnn <[email protected]>
@bolinfest

Copy link
Copy Markdown
Collaborator

@AdsQnn Thank for investing time working on the Codex source code.

I know you have a very detailed write-up, but this PR does too many different things for me to review it. In particular, smaller, non-controversial changes generally get reviewed faster and have a higher likelihood of being accepted. This PR has a mix of changes of different risk levels.

In particular, with respect to lazy loading of MCP servers, we're discussing on our side the tradeoffs between faster startup versus potential problems with the model getting different lists of tools presented to it on multiple turns. We aren't 100% clear on how that would affect model performance, which is part of the reason why things work the way they do today.

@adsqx

adsqx commented Sep 8, 2025 •

Copy link
Copy Markdown
Author

@bolinfest

Ok, I understand :) Maybe it’s worth considering borrowing something from which — that change shouldn’t have any impact on performance.

Headings in lowercase also seem to be required; during testing with HTTP/2, uppercase ones were causing errors.

The timeouts probably appeared because there’s no initial waiting step for MCP.

It might also be worth considering not adding the list in multiple rounds, but instead waiting for all responses and then loading a complete list at once.
Adding some kind of notifier, e.g., “Loading MCP…”, “MCP loaded.”, and then showing the list could improve the perceived loading speed and make the process more reliable.

Thanks for the reply! I hope that even if this can’t be directly used, it might still help point in the right direction.

Thanks

@bolinfest

Copy link
Copy Markdown
Collaborator

@AdsQnn so that you get the "credit," would you be willing to put up your changes to codex-rs/tui/src/bottom_pane/paste_burst.rs in a separate PR?

@adsqx

adsqx commented Sep 8, 2025 •

Copy link
Copy Markdown
Author

@bolinfest Ok, I’ll try to implement it as quickly as possible. Thank you, and good luck with the fixes! :)
PS. I’m waiting for a PR without errors — the current one probably didn’t pass the tests.

This change might have caused the error because, instead of creating new Strings (Line<'static>), it stores references to cmd, which become dangling pointers after drop, leading to UB and a SIGSEGV.

If that helps in any way.

@adsqx

adsqx commented Sep 8, 2025

Copy link
Copy Markdown
Author

@bolinfest

I know this is a reply to a reply, but it just came to mind now and I’m not sure where else to write it.
It seems to me that maybe instead of using time, you could try something like this. And I think this is interesting — maybe something to keep in mind for the future.

The example below is just a concept of how it could look — it’s untested, but maybe some part of it could be useful.

We reserve a separate channel:
The MCP writes only a READY token to stdout, while all logs are sent to stderr.
The parent process waits reactively, until it receives exactly that token.


Parent (launcher) – Rust/Tokio

// Cargo.toml (parent)
# anyhow = "1"
# rand = "0.8"
# tokio = { version = "1", features = ["rt-multi-thread","macros","process","io-util"] }

use anyhow::Result;
use rand::{distributions::Alphanumeric, Rng};
use std::process::Stdio;
use tokio::{
    io::{AsyncBufReadExt, BufReader},
    process::Command,
};

#[tokio::main]
async fn main() -> Result<()> {
    // 1) Generate a random token (nonce) as a “readiness proof”
    let nonce: String = rand::thread_rng()
        .sample_iter(&Alphanumeric)
        .take(32)
        .map(char::from)
        .collect();

    // 2) Start MCP: stdout = READY channel, stderr = logs
    let mut child = Command::new("./mcp_binary")
        .env("MCP_READY_NONCE", &nonce)
        .stdout(Stdio::piped())     // only READY/nonce
        .stderr(Stdio::inherit())   // logs go normally
        .spawn()?;

    let stdout = child.stdout.take().expect("no stdout");
    let mut lines = BufReader::new(stdout).lines();

    // 3) Reactively wait for *exactly* that nonce (no timeout needed)
    while let Some(line) = lines.next_line().await? {
        if line.trim() == nonce {
            println!("MCP READY (pid={})", child.id());
            break;
        }
        // Optionally: discard anything else (don’t log stdout here)
    }

    // 4) ... you can now continue working with the ready MCP ...
    Ok(())
}

MCP (child) – minimal skeleton

// Cargo.toml (mcp)
# tokio = { version = "1", features = ["rt-multi-thread","macros"] }

use std::{env, io::{self, Write}, thread, time::Duration};

#[tokio::main]
async fn main() -> io::Result<()> {
    // 1) Perform normal initialization...
    // (simulating some work here)
    thread::sleep(Duration::from_millis(350));

    // 2) After being fully ready, print the nonce to stdout + flush
    let nonce = env::var("MCP_READY_NONCE").expect("missing MCP_READY_NONCE");
    println!("{}", nonce);
    io::stdout().flush()?; // very important!

    // 3) Logs and other output go to stderr (keep READY channel clean)
    eprintln!("[MCP] started and serving...");

    // 4) ...rest of server work...
    // tokio::signal::ctrl_c().await?;
    Ok(())
}

Why this is “safer” and stable

  • Dedicated READY channel:
    Stdout is used only for the one-time READY token; logs are sent to stderr.
  • Nonce (32 characters):
    The parent only accepts its own random token → zero false READY signals.
  • No timeouts:
    I/O wakes up the task reactively (like epoll/IOCP), no countdowns or delays.
  • Cross-platform:
    Works identically on Linux, macOS, and Windows without extra privileges.

@adsqx adsqx closed this Sep 9, 2025
@github-actions github-actions Bot locked and limited conversation to collaborators Sep 9, 2025
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants