Skip to content

Windows: stdio MCP servers fail under the shared app-server daemon because it keeps the PATH it started with (any -c override "fixes" it) #55888

Open

Description

@minjipi

What version of Codex CLI is running?

codex-cli 0.163.0 (managed app-server daemon package 0.163.0), which is the latest stable release. Still present on main at d138398cef: the relevant files are unchanged since c419fd01a7, the commit the links below point to.

What subscription do you have?

ChatGPT Business (Team)

Which model were you using?

gpt-6-luna (not model-specific)

What platform is your computer?

Microsoft Windows NT 10.0.26200.0 x64 (Korean locale, ACP/OEMCP 949)

What terminal emulator and version are you using (if applicable)?

Windows PowerShell 5.1 in the PyCharm 2026.2.3 integrated terminal

Codex doctor report

codex doctor reports app_server.status: ok / background server is running, so it doesn't surface this problem. Paths are redacted. I ran it from a non-interactive shell, so the terminal.env fields describe that shell, not the terminal running the TUI.

codex doctor --json
{
  "schemaVersion": 1,
  "generatedAt": "1792587596s since unix epoch",
  "overallStatus": "warning",
  "codexVersion": "0.163.0",
  "checks": {
    "app_server.status": {
      "id": "app_server.status",
      "category": "app-server",
      "status": "ok",
      "summary": "background server is running",
      "details": {
        "app-server version": "0.163.0",
        "control socket": "C:\\Users\\<user>\\.codex\\app-server-control\\app-server-control.sock",
        "daemon state dir": "C:\\Users\\<user>\\.codex\\app-server-daemon",
        "dedicated pid file": "C:\\Users\\<user>\\.codex\\app-server-daemon\\daemon.pid (file)",
        "dedicated update-loop pid file": "C:\\Users\\<user>\\.codex\\app-server-daemon\\daemon-updater.pid (file)",
        "mode": "ephemeral",
        "pid file": "C:\\Users\\<user>\\.codex\\app-server-daemon\\app-server.pid (missing)",
        "settings": "C:\\Users\\<user>\\.codex\\app-server-daemon\\settings.json (missing)",
        "status": "running",
        "update-loop pid file": "C:\\Users\\<user>\\.codex\\app-server-daemon\\app-server-updater.pid (missing)"
      },
      "remediation": null,
      "durationMs": 15
    },
    "auth.credentials": {
      "id": "auth.credentials",
      "category": "auth",
      "status": "ok",
      "summary": "auth is configured",
      "details": {
        "auth file": "C:\\Users\\<user>\\.codex\\auth.json",
        "auth storage mode": "File",
        "stored API key": "false",
        "stored ChatGPT tokens": "true",
        "stored agent identity": "false",
        "stored auth mode": "chatgpt"
      },
      "remediation": null,
      "durationMs": 0
    },
    "config.load": {
      "id": "config.load",
      "category": "config",
      "status": "ok",
      "summary": "config loaded",
      "details": {
        "CODEX_HOME": "C:\\Users\\<user>\\.codex",
        "active thread overrides": "not inspected",
        "config.toml": "C:\\Users\\<user>\\.codex\\config.toml",
        "config.toml parse": "ok",
        "configuration load ms": "38",
        "configuration scope": "invocation config, including cloud-managed policy",
        "configured TUI mode": "fullscreen",
        "cwd": "C:\\<repo>",
        "enabled feature flags": "<redacted>",
        "feature flag overrides": "none",
        "feature flags enabled": "60",
        "log dir": "C:\\Users\\<user>\\.codex\\log",
        "mcp servers": "1",
        "model": "gpt-6-luna",
        "model provider": "openai",
        "sqlite home": "C:\\Users\\<user>\\.codex"
      },
      "remediation": null,
      "durationMs": 0
    },
    "git.environment": {
      "id": "git.environment",
      "category": "git",
      "status": "ok",
      "summary": "git executable found; execution not verified",
      "details": {
        ".git entry": "directory",
        "PATH git #1": "C:\\Program Files\\Git\\cmd\\git.exe",
        "PATH git entries": "1",
        "git execution": "not inspected (PATH helpers are not executed)",
        "repo detected": "true",
        "repo root": "C:\\<repo>",
        "selected git": "C:\\Program Files\\Git\\cmd\\git.exe"
      },
      "remediation": null,
      "durationMs": 5
    },
    "git.worktree.dev_drive": {
      "id": "git.worktree.dev_drive",
      "category": "git",
      "status": "warning",
      "summary": "this worktree is not on a Windows Dev Drive; moving it to a trusted Dev Drive can significantly improve repository and filesystem performance",
      "details": {},
      "remediation": "create a trusted Windows Dev Drive for source repositories: https://learn.microsoft.com/en-us/<redacted>",
      "durationMs": 0
    },
    "installation": {
      "id": "installation",
      "category": "install",
      "status": "ok",
      "summary": "installation looks consistent",
      "details": {
        "PATH codex #1": "C:\\Users\\<user>\\AppData\\Local\\Programs\\OpenAI\\Codex\\bin\\codex.exe",
        "current executable": "C:\\Users\\<user>\\AppData\\Local\\Programs\\OpenAI\\Codex\\bin\\codex.exe",
        "install context": "standalone (windows, package C:\\Users\\<user>\\.codex\\packages\\standalone\\releases\\0.163.0-x86_64-pc-windows-msvc, bin C:\\Users\\<user>\\.codex\\packages\\standalone\\releases\\0.163.0-x86_64-pc-windows-msvc\\bin, resources C:\\Users\\<user>\\.codex\\packages\\standalone\\releases\\0.163.0-x86_64-pc-windows-msvc\\codex-resources, path C:\\Users\\<user>\\.codex\\packages\\standalone\\releases\\0.163.0-x86_64-pc-windows-msvc\\codex-path)",
        "managed by Vite+": "false",
        "managed by bun": "false",
        "managed by npm": "false",
        "managed by pnpm": "false",
        "managed package root": "not set"
      },
      "remediation": null,
      "durationMs": 3
    },
    "mcp.config": {
      "id": "mcp.config",
      "category": "mcp",
      "status": "ok",
      "summary": "MCP configuration is locally consistent",
      "details": {
        "configured servers": "1",
        "disabled servers": "0",
        "stdio servers": "1"
      },
      "remediation": null,
      "durationMs": 1
    },
    "network.env": {
      "id": "network.env",
      "category": "network",
      "status": "ok",
      "summary": "network-related environment looks readable",
      "details": {
        "managed proxy": "not configured",
        "proxy env vars": "none",
        "respect system proxy": "disabled"
      },
      "remediation": null,
      "durationMs": 0
    },
    "network.provider_reachability": {
      "id": "network.provider_reachability",
      "category": "reachability",
      "status": "ok",
      "summary": "active provider endpoints are reachable over HTTP",
      "details": {
        "ChatGPT inference URL": "https://chatgpt.com/backend-api/<redacted> reachable (HTTP 405)",
        "reachability mode": "ChatGPT auth"
      },
      "remediation": null,
      "durationMs": 364
    },
    "network.websocket_reachability": {
      "id": "network.websocket_reachability",
      "category": "websocket",
      "status": "ok",
      "summary": "Responses WebSocket handshake succeeded",
      "details": {
        "DNS": "2 IPv4, 0 IPv6, first IPv4",
        "auth mode": "chatgpt",
        "connect timeout": "15000 ms",
        "endpoint": "wss://chatgpt.com/backend-api/<redacted>",
        "handshake result": "HTTP 101 Switching Protocols",
        "model provider": "openai",
        "provider name": "OpenAI",
        "proxy env vars": "none",
        "reasoning header": "false",
        "server model present": "false",
        "supports websockets": "true",
        "wire API": "responses"
      },
      "remediation": null,
      "durationMs": 1383
    },
    "runtime.provenance": {
      "id": "runtime.provenance",
      "category": "runtime",
      "status": "ok",
      "summary": "running standalone on windows-x86_64",
      "details": {
        "commit": "unknown",
        "current executable": "C:\\Users\\<user>\\AppData\\Local\\Programs\\OpenAI\\Codex\\bin\\codex.exe",
        "install method": "standalone (windows, package C:\\Users\\<user>\\.codex\\packages\\standalone\\releases\\0.163.0-x86_64-pc-windows-msvc, bin C:\\Users\\<user>\\.codex\\packages\\standalone\\releases\\0.163.0-x86_64-pc-windows-msvc\\bin, resources C:\\Users\\<user>\\.codex\\packages\\standalone\\releases\\0.163.0-x86_64-pc-windows-msvc\\codex-resources, path C:\\Users\\<user>\\.codex\\packages\\standalone\\releases\\0.163.0-x86_64-pc-windows-msvc\\codex-path)",
        "platform": "windows-x86_64",
        "version": "0.163.0"
      },
      "remediation": null,
      "durationMs": 0
    },
    "runtime.search": {
      "id": "runtime.search",
      "category": "search",
      "status": "ok",
      "summary": "search command found (bundled); execution not verified",
      "details": {
        "search command": "C:\\Users\\<user>\\.codex\\packages\\standalone\\releases\\0.163.0-x86_64-pc-windows-msvc\\codex-path\\rg.exe",
        "search command readiness": "file exists",
        "search provider": "bundled"
      },
      "remediation": null,
      "durationMs": 0
    },
    "sandbox.filesystem_paths": {
      "id": "sandbox.filesystem_paths",
      "category": "sandbox",
      "status": "ok",
      "summary": "no explicit filesystem paths to probe",
      "details": {},
      "remediation": null,
      "durationMs": 0
    },
    "sandbox.helpers": {
      "id": "sandbox.helpers",
      "category": "sandbox",
      "status": "ok",
      "summary": "sandbox configuration is readable",
      "details": {
        "approval policy": "OnRequest",
        "codex-linux-sandbox helper": "none",
        "denied-read glob rules": "0",
        "denied-read restrictions": "false",
        "denied-read rules": "0",
        "filesystem sandbox": "restricted",
        "glob scan max depth": "unbounded",
        "managed filesystem source": "none",
        "network sandbox": "restricted",
        "sandbox backend": "elevated",
        "sandbox provisioning": "complete"
      },
      "remediation": null,
      "durationMs": 39
    },
    "security.endpoint": {
      "id": "security.endpoint",
      "category": "security",
      "status": "warning",
      "summary": "endpoint protection detected; Codex exclusions are unverified",
      "details": {
        "Codex exclusions": "not verified",
        "endpoint products": "Microsoft Defender",
        "exclusion targets": "signed Codex app; codex.exe; codex-windows-sandbox-setup.exe; codex-command-runner.exe; codex-code-mode-host.exe"
      },
      "issues": [
        {
          "severity": "warning",
          "cause": "Microsoft Defender can interfere with Codex. Verify Codex exclusions.",
          "measured": "not verified",
          "expected": "Codex application and helper exclusions",
          "remedy": "Microsoft Defender: Add a certificate or executable-path exclusion for Codex and its helpers. If Attack Surface Reduction blocks Codex, add a rule exclusion. If Controlled Folder Access blocks Codex, allow the app.",
          "fields": [
            "Codex exclusions"
          ]
        }
      ],
      "remediation": "ask your security administrator to verify Codex exclusions and required helper allowances",
      "durationMs": 76
    },
    "state.paths": {
      "id": "state.paths",
      "category": "state",
      "status": "ok",
      "summary": "state paths and databases are inspectable",
      "details": {
        "CODEX_HOME": "C:\\Users\\<user>\\.codex (dir)",
        "active rollout files": "90 files, 57540243 total bytes, 639336 average bytes",
        "archived rollout files": "0 files, 0 total bytes, 0 average bytes",
        "goals DB": "C:\\Users\\<user>\\.codex\\goals_1.sqlite (file)",
        "goals DB integrity": "ok",
        "log DB": "C:\\Users\\<user>\\.codex\\logs_2.sqlite (file)",
        "log DB integrity": "ok",
        "log dir": "C:\\Users\\<user>\\.codex\\log (dir)",
        "memories DB": "C:\\Users\\<user>\\.codex\\memories_1.sqlite (file)",
        "memories DB integrity": "ok",
        "memories v2 DB": "C:\\Users\\<user>\\.codex\\memories_v2_1.sqlite (missing)",
        "memories v2 DB integrity": "skipped (missing)",
        "queue DB": "C:\\Users\\<user>\\.codex\\queue_1.sqlite (file)",
        "queue DB integrity": "ok",
        "sqlite home": "C:\\Users\\<user>\\.codex (dir)",
        "standalone release cache": "2 entries in C:\\Users\\<user>\\.codex\\packages\\standalone\\releases",
        "state DB": "C:\\Users\\<user>\\.codex\\state_5.sqlite (file)",
        "state DB integrity": "ok",
        "thread history DB": "C:\\Users\\<user>\\.codex\\thread_history_1.sqlite (file)",
        "thread history DB integrity": "ok"
      },
      "remediation": null,
      "durationMs": 1494
    },
    "state.rollout_db_parity": {
      "id": "state.rollout_db_parity",
      "category": "threads",
      "status": "ok",
      "summary": "rollout files and state DB thread inventory agree",
      "details": {
        "default model provider": "openai",
        "rollout DB active files": "90",
        "rollout DB active rows": "90",
        "rollout DB archive mismatches": "0",
        "rollout DB archived files": "0",
        "rollout DB archived rows": "0",
        "rollout DB duplicate DB paths": "0",
        "rollout DB duplicate rollout thread ids": "0",
        "rollout DB malformed file names": "0",
        "rollout DB missing active rows": "0",
        "rollout DB missing archived rows": "0",
        "rollout DB model providers": "openai=90",
        "rollout DB rows": "90",
        "rollout DB scan cap reached": "false",
        "rollout DB scan errors": "0",
        "rollout DB sources": "vscode=31, subagent:thread_spawn=25, cli=20, subagent:other=13, exec=1",
        "rollout DB stale rows": "0"
      },
      "remediation": null,
      "durationMs": 1087
    },
    "system.disk": {
      "id": "system.disk",
      "category": "disk",
      "status": "ok",
      "summary": "sufficient free disk space (199.7 GiB)",
      "details": {
        "CODEX_HOME available": "199.7 GiB",
        "failure threshold": "1.0 GiB",
        "warning threshold": "5.0 GiB",
        "worktree available": "199.7 GiB"
      },
      "remediation": null,
      "durationMs": 0
    },
    "system.environment": {
      "id": "system.environment",
      "category": "system",
      "status": "ok",
      "summary": "OS language ko-KR",
      "details": {
        "EDITOR": "not set",
        "VISUAL": "not set",
        "os": "Windows 10.0.26200 (Windows 11 Professional) [64-bit]",
        "os language": "ko-KR",
        "os type": "Windows",
        "os version": "10.0.26200"
      },
      "remediation": null,
      "durationMs": 1
    },
    "terminal.env": {
      "id": "terminal.env",
      "category": "terminal",
      "status": "ok",
      "summary": "terminal metadata was detected",
      "details": {
        "NO_COLOR": "1",
        "WT_SESSION": "present",
        "color output": "disabled (NO_COLOR)",
        "console input code page": "65001",
        "console output code page": "65001",
        "stderr console mode": "unavailable",
        "stderr is terminal": "false",
        "stdin is terminal": "false",
        "stdout console mode": "unavailable",
        "stdout is terminal": "false",
        "terminal": "Windows Terminal",
        "terminal size": "120x30"
      },
      "remediation": null,
      "durationMs": 2
    },
    "terminal.title": {
      "id": "terminal.title",
      "category": "title",
      "status": "ok",
      "summary": "terminal title default",
      "details": {
        "terminal title activity": "true",
        "terminal title items": "activity, project-name",
        "terminal title project source": "git repo root",
        "terminal title project value": "codex",
        "terminal title source": "default"
      },
      "remediation": null,
      "durationMs": 0
    },
    "updates.status": {
      "id": "updates.status",
      "category": "updates",
      "status": "ok",
      "summary": "update configuration is locally consistent",
      "details": {
        "cached latest version": "0.163.0",
        "check for update on startup": "true",
        "last checked at": "2026-10-21T00:49:21.378974100Z",
        "latest version": "0.163.0",
        "latest version status": "current version is not older",
        "update action": "standalone installer",
        "version cache": "C:\\Users\\<user>\\.codex\\version.json"
      },
      "remediation": null,
      "durationMs": 214
    }
  }
}

What issue are you seeing?

On Windows, codex attaches to the shared background app-server daemon. In that mode my stdio MCP server never connects. /mcp shows:

MCP client for `chrome-devtools` failed to start: MCP startup failed: handshaking with MCP server failed: connection closed: initialize response

Running codex -c 'log_dir="C:/Users/<user>/.codex-log"' makes the same server connect normally. log_dir itself is irrelevant: any -c override has the same effect.

Root cause (traced in the source at c419fd01a7)

  1. Any -c override bypasses the daemon. It disables reuse of the shared daemon (tui/src/daemon_startup.rs config_exclusion). The TUI then runs the app-server embedded, and that process inherits the current shell's environment.

  2. The daemon's PATH is frozen at startup. The daemon is a long-lived detached process that inherits the environment of whoever launched it (pid_start.rs). On my machine:

    • The daemon started on 2026-10-16.
    • Node.js (via nvm) was installed and added to the user PATH on 2026-10-19.

    I read the PATH from the environment blocks of both processes:

    Process ...\nvm / ...\nvm\.nodejs on PATH
    Daemon (codex.exe app-server --listen unix:// --managed-daemon) no
    Embedded (codex -c log_dir=...) yes
  3. Local stdio MCP servers inherit that frozen PATH. create_env_for_mcp_server copies PATH from the server process. Inside the daemon, cmd /c npx ... therefore prints 'npx' is not recognized as an internal or external command and exits, and rmcp reports connection closed: initialize response.

  4. The real error is hidden. On a CP949 system, cmd prints that error in CP949. The stderr reader uses BufReader::lines() (stdio_server_launcher.rs). That call fails on non-UTF-8 input, so the reader logs one warning and stops reading. Neither /mcp nor the logs contain the actual reason.

Daemon log (from ~/.codex/logs_2.sqlite):

WARN codex_rmcp_client::stdio_server_launcher: Failed to read MCP server stderr (cmd): stream did not contain valid UTF-8
WARN codex_mcp::rmcp_client: ... MCP server startup failed server_name="chrome-devtools" error=handshaking with MCP server failed: connection closed: initialize response

What steps can reproduce the bug?

Natural repro

  1. On Windows, start Codex so the shared app-server daemon is running.
  2. Afterwards, install a tool and add it to the user PATH (here: Node.js via nvm).
  3. Add an MCP server that needs it:
    [mcp_servers.chrome-devtools]
    command = "cmd"
    args = ["/c", "npx", "-y", "chrome-devtools-mcp@latest"]
  4. In a new terminal (where npx resolves), run codex and then /mcp. Result: chrome-devtools failed.
  5. Run codex -c 'log_dir="C:/tmp/codex-log"' and then /mcp. Result: connected.

Deterministic repro (script, throwaway CODEX_HOME, no login needed)

The script below needs only Node.js on the persisted PATH and Python 3. It does four things:

  1. Starts codex app-server --listen unix:// detached (no console, like the managed daemon) with PATH=C:\WINDOWS\system32;C:\WINDOWS, simulating a daemon that started before Node.js was installed.
  2. Connects through codex app-server proxy over WebSocket, the way the TUI does.
  3. Sends initialize and thread/start, then prints the mcpServer/startupStatus/updated result and the MCP stderr lines the server logged.
  4. Deletes its temporary CODEX_HOME.
python repro_mcp_stale_path.py <path-to-codex.exe>

Output with 0.163.0:

  + 0.1s repro-mcp: failed
RESULT: failed
  error: MCP client for `repro-mcp` failed to start: MCP startup failed: handshaking with MCP server failed: connection closed: initialize response: ...
MCP stderr lines logged by the server:
  Failed to read MCP server stderr (cmd): stream did not contain valid UTF-8

Output with the patch below:

  + 1.0s repro-mcp: ready
RESULT: ready

The PATH failure should reproduce on any locale. The stderr symptom needs a non-UTF-8 OEM code page (CP949 here); on an English system cmd's message is ASCII and gets logged normally.

repro_mcp_stale_path.py
"""Reproduce: stdio MCP servers fail inside a daemon-like app-server whose PATH is stale.

Requirements: Windows, Python 3, Node.js installed with its directory on the persisted
(registry) PATH, and a codex.exe to test. No login is needed.

    python repro_mcp_stale_path.py C:\\path\\to\\codex.exe

The script creates a throwaway CODEX_HOME, starts `codex app-server --listen unix://`
detached (no console, like the managed daemon) with PATH=C:\\WINDOWS\\system32;C:\\WINDOWS
(a daemon started before Node.js was installed), connects through `codex app-server
proxy` like the TUI, starts a thread, and prints the MCP startup status plus the MCP
stderr lines the server logged.
"""

import base64
import json
import os
import re
import shutil
import stat
import struct
import subprocess
import sys
import tempfile
import time
from pathlib import Path

STALE_PATH = r"C:\WINDOWS\system32;C:\WINDOWS"
SERVER = "repro-mcp"
CONFIG = f"""[features]
daemon_auto_start = false

[mcp_servers.{SERVER}]
command = "cmd"
args = ["/c", "npx", "-y", "chrome-devtools-mcp@latest"]
startup_timeout_sec = 60
"""


class ProxyWebSocket:
    def __init__(self, codex, env):
        self.proc = subprocess.Popen([codex, "app-server", "proxy"], env=env,
                                     stdin=subprocess.PIPE, stdout=subprocess.PIPE,
                                     stderr=subprocess.DEVNULL)
        key = base64.b64encode(os.urandom(16)).decode()
        self._write((f"GET / HTTP/1.1\r\nHost: localhost\r\nUpgrade: websocket\r\n"
                     f"Connection: Upgrade\r\nSec-WebSocket-Key: {key}\r\n"
                     "Sec-WebSocket-Version: 13\r\n\r\n").encode())
        header = b""
        while not header.endswith(b"\r\n\r\n"):
            header += self._read(1)
        if b" 101 " not in header.split(b"\r\n")[0]:
            raise RuntimeError(f"WebSocket handshake failed: {header!r}")

    def _write(self, data):
        self.proc.stdin.write(data)
        self.proc.stdin.flush()

    def _read(self, n):
        data = b""
        while len(data) < n:
            chunk = self.proc.stdout.read(n - len(data))
            if not chunk:
                raise EOFError("proxy closed")
            data += chunk
        return data

    def _frame(self, opcode, payload):
        mask = os.urandom(4)
        n = len(payload)
        head = bytes([0x80 | opcode])
        if n < 126:
            head += bytes([0x80 | n])
        elif n < 65536:
            head += bytes([0x80 | 126]) + struct.pack(">H", n)
        else:
            head += bytes([0x80 | 127]) + struct.pack(">Q", n)
        self._write(head + mask + bytes(b ^ mask[i % 4] for i, b in enumerate(payload)))

    def send(self, message):
        self._frame(0x1, json.dumps(message).encode())

    def recv(self):
        message = b""
        while True:
            b0, b1 = self._read(2)
            n = b1 & 0x7F
            if n == 126:
                n = struct.unpack(">H", self._read(2))[0]
            elif n == 127:
                n = struct.unpack(">Q", self._read(8))[0]
            payload = self._read(n)
            opcode = b0 & 0x0F
            if opcode == 0x8:
                raise EOFError("server closed the WebSocket")
            if opcode == 0x9:
                self._frame(0xA, payload)
                continue
            message += payload
            if b0 & 0x80:
                return json.loads(message)

    def close(self):
        self.proc.kill()


def _clear_readonly_and_retry(func, path, _):
    os.chmod(path, stat.S_IWRITE)
    func(path)


def remove_tree(path):
    # The server clones plugins in the background; git leaves read-only pack files.
    for _ in range(10):
        try:
            if sys.version_info >= (3, 12):
                shutil.rmtree(path, onexc=_clear_readonly_and_retry)
            else:
                shutil.rmtree(path, onerror=_clear_readonly_and_retry)
            return
        except OSError:
            time.sleep(1)
    print(f"note: could not remove {path}")


def main():
    codex = sys.argv[1]
    # Keep CODEX_HOME short: the control socket path has a length limit.
    home = Path(tempfile.mkdtemp(prefix="cxr", dir="C:\\"))
    (home / "config.toml").write_text(CONFIG, encoding="utf-8")
    log_path = home / "server.stderr.log"

    server_env = dict(os.environ, CODEX_HOME=str(home),
                      RUST_LOG="error,codex_rmcp_client::stdio_server_launcher=info")
    for key in [k for k in server_env if k.upper() == "PATH"]:
        del server_env[key]
    server_env["PATH"] = STALE_PATH

    print(f"codex      : {codex}")
    print(f"CODEX_HOME : {home}")
    print(f"server PATH: {STALE_PATH}")
    with open(log_path, "wb") as log:
        server = subprocess.Popen(
            [codex, "app-server", "--listen", "unix://"], env=server_env, cwd=home,
            stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=log,
            creationflags=subprocess.DETACHED_PROCESS | subprocess.CREATE_NEW_PROCESS_GROUP)
    ws = None
    try:
        client_env = dict(os.environ, CODEX_HOME=str(home))
        for _ in range(60):
            try:
                ws = ProxyWebSocket(codex, client_env)
                break
            except (EOFError, RuntimeError):
                time.sleep(0.5)
        if ws is None:
            raise RuntimeError("could not connect to the app-server control socket")

        ws.send({"id": 1, "method": "initialize",
                 "params": {"clientInfo": {"name": "repro", "title": None, "version": "0"}}})
        ws.send({"method": "initialized"})
        ws.send({"id": 2, "method": "thread/start", "params": {"cwd": str(home)}})
        started = time.time()
        status = None
        while time.time() - started < 90:
            msg = ws.recv()
            if msg.get("id") == 2 and "error" in msg:
                raise RuntimeError(f"thread/start failed: {msg['error']}")
            if (msg.get("method") == "mcpServer/startupStatus/updated"
                    and msg["params"]["name"] == SERVER):
                p = msg["params"]
                print(f"  +{time.time() - started:4.1f}s {SERVER}: {p['status']}")
                if p["status"] in ("ready", "failed", "cancelled"):
                    status = p
                    break
        print("RESULT:", status["status"] if status else "no final status within 90s")
        if status and status.get("error"):
            print("  error:", status["error"].splitlines()[0])
    finally:
        if ws:
            ws.close()
        subprocess.run(["taskkill", "/T", "/F", "/PID", str(server.pid)], capture_output=True)
        time.sleep(1)
        print("MCP stderr lines logged by the server:")
        for line in log_path.read_bytes().splitlines():
            text = re.sub(r"\x1b\[[0-9;]*m", "", line.decode("utf-8", "replace"))
            if "MCP server stderr" in text:
                print("  " + text.split("stdio_server_launcher: ", 1)[-1][:160])
        remove_tree(home)


main()

What is the expected behavior?

  • MCP servers from config.toml start the same way whether the TUI uses the shared daemon or the embedded app-server.
  • Persisting a PATH change after the daemon started should not silently break them.
  • If a stdio server exits during startup, its stderr should be readable in the logs, whatever the console code page.

Additional information

Workarounds

  • Restart the daemon (codex app-server daemon restart) from a shell that has the updated PATH.
  • Use codex --no-daemon. This is the same embedded path that -c triggers.

Possible fix (patch below; verified locally)

I don't intend to open a PR. The patch is here as a reference for the analysis.

  1. Refresh PATH from the registry (rmcp-client/src/windows_persisted_path.rs, new). Before spawning a local stdio MCP server on Windows:

    • read the persisted user and system Path from the registry (HKCU\Environment and HKLM\...\Session Manager\Environment);
    • expand REG_EXPAND_SZ references, with persisted variables taking precedence;
    • append only the entries missing from the current PATH.

    Existing entries and their order are unchanged, and an explicit env.PATH in the MCP config still wins.

  2. Read stderr as raw lines (split(b'\n')). Lines that aren't valid UTF-8 are decoded with the OEM code page on Windows, falling back to lossy UTF-8, so one bad line no longer ends the reader.

Verification of the patch

Both builds ran as a detached server with the stale daemon environment, and also with PATH=C:\WINDOWS\system32;C:\WINDOWS.

Server build chrome-devtools stderr in log
0.163.0 failed (connection closed) stream did not contain valid UTF-8
patched (debug build of c419fd01a7) ready, 32 tools, 2–4 s 'codex-missing-command-probe'은(는) 내부 또는 외부 명령, ... (decoded correctly)
  • cargo test -p codex-rmcp-client --lib: 257 passed, including 6 new tests.
  • cargo clippy -p codex-rmcp-client --all-targets -- -D warnings: clean.
  • One caveat: the first patched run hit the 30 s startup timeout. That looked like a cold npx -y ...@latest fetch; the server still finished connecting. Later runs were ready in 2–4 s, the same as the unpatched build with a fresh PATH.

Not covered by the patch

Commands run through the shell tool inside the daemon probably see the same stale PATH. I haven't verified this. Fixing it would mean refreshing the environment more generally, or forwarding the client's environment to the daemon.

Related

Smaller suggestion

codex doctor could compare the daemon's PATH with the persisted PATH and warn when entries are missing. Here it reports the background server as healthy.

Patch (git apply applies it cleanly to both c419fd0 and d138398)
diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock
index cd2a7e99f9..0abb5540e0 100644
--- a/codex-rs/Cargo.lock
+++ b/codex-rs/Cargo.lock
@@ -4527,6 +4527,7 @@ dependencies = [
  "webbrowser",
  "which 8.0.0",
  "windows-sys 0.61.2",
+ "winreg 0.55.0",
  "wiremock",
 ]
 
diff --git a/codex-rs/rmcp-client/Cargo.toml b/codex-rs/rmcp-client/Cargo.toml
index 4702b0f53f..1bd4128659 100644
--- a/codex-rs/rmcp-client/Cargo.toml
+++ b/codex-rs/rmcp-client/Cargo.toml
@@ -90,7 +90,11 @@ keyring = { workspace = true, features = ["apple-native"] }
 
 [target.'cfg(target_os = "windows")'.dependencies]
 keyring = { workspace = true, features = ["windows-native"] }
-windows-sys = { workspace = true, features = ["Win32_Storage_FileSystem"] }
+windows-sys = { workspace = true, features = [
+    "Win32_Globalization",
+    "Win32_Storage_FileSystem",
+] }
+winreg = { workspace = true }
 
 [target.'cfg(any(target_os = "freebsd", target_os = "openbsd"))'.dependencies]
 keyring = { workspace = true, features = ["sync-secret-service"] }
diff --git a/codex-rs/rmcp-client/src/lib.rs b/codex-rs/rmcp-client/src/lib.rs
index e555b61c8d..31fd276eda 100644
--- a/codex-rs/rmcp-client/src/lib.rs
+++ b/codex-rs/rmcp-client/src/lib.rs
@@ -35,6 +35,8 @@ mod tool_list_changes;
 mod trace_context;
 mod user_verification;
 mod utils;
+#[cfg(windows)]
+mod windows_persisted_path;
 mod www_authenticate;
 
 pub use auth_status::McpAuthState;
diff --git a/codex-rs/rmcp-client/src/stdio_server_launcher.rs b/codex-rs/rmcp-client/src/stdio_server_launcher.rs
index 92ccfa2107..147b36f6f9 100644
--- a/codex-rs/rmcp-client/src/stdio_server_launcher.rs
+++ b/codex-rs/rmcp-client/src/stdio_server_launcher.rs
@@ -361,7 +361,9 @@ impl LocalStdioServerLauncher {
             let program_name = program_name.clone();
             let (stop_tx, mut stop_rx) = watch::channel(());
             std::mem::drop(tokio::spawn(async move {
-                let mut reader = BufReader::new(stderr).lines();
+                // Read raw lines so a non-UTF-8 line (such as a localized Windows
+                // shell error) cannot end the stream and hide later diagnostics.
+                let mut reader = BufReader::new(stderr).split(b'\n');
                 // Give queued diagnostics time to reach the logs without waiting
                 // indefinitely for a descendant that still has stderr open.
                 let drain_deadline = tokio::time::sleep(STDERR_READER_DRAIN_GRACE_PERIOD);
@@ -377,9 +379,10 @@ impl LocalStdioServerLauncher {
                                 Instant::now() + STDERR_READER_DRAIN_GRACE_PERIOD
                             );
                         }
-                        line = reader.next_line() => {
+                        line = reader.next_segment() => {
                             match line {
                                 Ok(Some(line)) => {
+                                    let line = decode_stderr_line(&line);
                                     info!("MCP server stderr ({program_name}): {line}");
                                 }
                                 Ok(None) => break,
@@ -403,6 +406,57 @@ impl LocalStdioServerLauncher {
     }
 }
 
+/// Decodes one stderr line, falling back to the console code page that Windows
+/// shells use for localized errors.
+fn decode_stderr_line(line: &[u8]) -> String {
+    let line = line.strip_suffix(b"\r").unwrap_or(line);
+    match std::str::from_utf8(line) {
+        Ok(line) => line.to_string(),
+        Err(_) => decode_non_utf8_stderr_line(line),
+    }
+}
+
+#[cfg(windows)]
+fn decode_non_utf8_stderr_line(line: &[u8]) -> String {
+    use windows_sys::Win32::Globalization::CP_OEMCP;
+    use windows_sys::Win32::Globalization::MB_ERR_INVALID_CHARS;
+    use windows_sys::Win32::Globalization::MultiByteToWideChar;
+
+    let decoded = i32::try_from(line.len()).ok().and_then(|len| {
+        // SAFETY: the pointer and length describe `line`; a null output buffer only measures.
+        let wide_len = unsafe {
+            MultiByteToWideChar(
+                CP_OEMCP,
+                MB_ERR_INVALID_CHARS,
+                line.as_ptr(),
+                len,
+                std::ptr::null_mut(),
+                0,
+            )
+        };
+        let mut wide = vec![0u16; usize::try_from(wide_len).ok().filter(|len| *len > 0)?];
+        // SAFETY: `wide` has room for exactly `wide_len` UTF-16 units.
+        let written = unsafe {
+            MultiByteToWideChar(
+                CP_OEMCP,
+                MB_ERR_INVALID_CHARS,
+                line.as_ptr(),
+                len,
+                wide.as_mut_ptr(),
+                wide_len,
+            )
+        };
+        wide.truncate(usize::try_from(written).ok().filter(|len| *len > 0)?);
+        Some(String::from_utf16_lossy(&wide))
+    });
+    decoded.unwrap_or_else(|| String::from_utf8_lossy(line).into_owned())
+}
+
+#[cfg(not(windows))]
+fn decode_non_utf8_stderr_line(line: &[u8]) -> String {
+    String::from_utf8_lossy(line).into_owned()
+}
+
 impl LocalProcessTerminator {
     #[cfg(not(windows))]
     fn new(process_group_id: u32) -> Self {
@@ -724,6 +778,23 @@ mod tests {
     use codex_protocol::shell_environment;
     use pretty_assertions::assert_eq;
 
+    #[test]
+    fn decode_stderr_line_strips_carriage_return_and_keeps_utf8() {
+        assert_eq!(
+            decode_stderr_line("오류: missing\r".as_bytes()),
+            "오류: missing"
+        );
+    }
+
+    #[test]
+    fn decode_stderr_line_keeps_ascii_context_of_non_utf8_lines() {
+        // CP949 bytes for "'npx'은(는)"; ASCII survives whatever the system code page is.
+        let line = decode_stderr_line(b"'npx'\xc0\xba(\xb4\xc2) not found");
+
+        assert!(line.starts_with("'npx'"), "unexpected decoding: {line}");
+        assert!(line.ends_with(" not found"), "unexpected decoding: {line}");
+    }
+
     #[test]
     fn remote_env_policy_uses_core_env_without_remote_source_vars() {
         let policy = ExecutorStdioServerLauncher::remote_env_policy(&[], &HashMap::new());
diff --git a/codex-rs/rmcp-client/src/utils.rs b/codex-rs/rmcp-client/src/utils.rs
index dac42ca611..ea1d97a656 100644
--- a/codex-rs/rmcp-client/src/utils.rs
+++ b/codex-rs/rmcp-client/src/utils.rs
@@ -24,6 +24,12 @@ pub(crate) fn create_env_for_mcp_server(
         .chain(additional_env_vars)
         .filter_map(|var| env::var_os(var).map(|value| (OsString::from(var), value)))
         .collect();
+    // A long-lived parent such as the managed daemon may predate tools installed
+    // since it started. An explicit `env.PATH` override below still wins.
+    #[cfg(windows)]
+    if let Some(path) = env.get_mut(std::ffi::OsStr::new("PATH")) {
+        *path = crate::windows_persisted_path::with_persisted_path_entries(path);
+    }
     for name in CUSTOM_CA_ENV_KEYS {
         let Some(value) = env::var_os(name) else {
             continue;
diff --git a/codex-rs/rmcp-client/src/windows_persisted_path.rs b/codex-rs/rmcp-client/src/windows_persisted_path.rs
new file mode 100644
index 0000000000..49b89f7fce
--- /dev/null
+++ b/codex-rs/rmcp-client/src/windows_persisted_path.rs
@@ -0,0 +1,231 @@
+//! Long-lived Windows processes keep the PATH they were started with.
+//!
+//! The managed app-server daemon can outlive a tool install (for example Node.js
+//! installed through nvm), so stdio MCP servers it spawns would miss PATH entries
+//! the user has persisted since. Windows stores the persisted environment in the
+//! registry; this module appends persisted PATH entries the current PATH lacks,
+//! keeping every existing entry and its precedence.
+
+use std::collections::HashMap;
+use std::collections::HashSet;
+use std::ffi::OsStr;
+use std::ffi::OsString;
+use std::path::PathBuf;
+
+use winreg::RegKey;
+use winreg::enums::HKEY_CURRENT_USER;
+use winreg::enums::HKEY_LOCAL_MACHINE;
+use winreg::enums::KEY_READ;
+use winreg::enums::RegType;
+use winreg::types::FromRegValue;
+
+const SYSTEM_ENVIRONMENT_KEY: &str =
+    r"SYSTEM\CurrentControlSet\Control\Session Manager\Environment";
+const USER_ENVIRONMENT_KEY: &str = "Environment";
+
+struct PersistedValue {
+    value: String,
+    expand: bool,
+}
+
+/// Returns `path` followed by any persisted PATH entries it does not already contain.
+pub(crate) fn with_persisted_path_entries(path: &OsStr) -> OsString {
+    let system = read_environment_key(RegKey::predef(HKEY_LOCAL_MACHINE), SYSTEM_ENVIRONMENT_KEY);
+    let user = read_environment_key(RegKey::predef(HKEY_CURRENT_USER), USER_ENVIRONMENT_KEY);
+    append_missing_path_entries(path, persisted_path_entries(&system, &user))
+}
+
+fn read_environment_key(root: RegKey, subkey: &str) -> HashMap<String, PersistedValue> {
+    let Ok(key) = root.open_subkey_with_flags(subkey, KEY_READ) else {
+        return HashMap::new();
+    };
+    key.enum_values()
+        .filter_map(Result::ok)
+        .filter_map(|(name, raw)| {
+            let expand = raw.vtype == RegType::REG_EXPAND_SZ;
+            let value = String::from_reg_value(&raw).ok()?;
+            Some((name.to_ascii_uppercase(), PersistedValue { value, expand }))
+        })
+        .collect()
+}
+
+/// System entries come first, matching how Windows builds a new logon PATH.
+fn persisted_path_entries(
+    system: &HashMap<String, PersistedValue>,
+    user: &HashMap<String, PersistedValue>,
+) -> Vec<OsString> {
+    // Persisted variables win so references to variables this process predates
+    // (for example `%NVM_HOME%`) still resolve.
+    let lookup = |name: &str| {
+        let name = name.to_ascii_uppercase();
+        user.get(&name)
+            .or_else(|| system.get(&name))
+            .map(|persisted| persisted.value.clone())
+            .or_else(|| std::env::var(&name).ok())
+    };
+    [system, user]
+        .into_iter()
+        .filter_map(|vars| vars.get("PATH"))
+        .flat_map(|path| {
+            let value = if path.expand {
+                expand_references(&path.value, lookup)
+            } else {
+                path.value.clone()
+            };
+            std::env::split_paths(&value)
+                .map(PathBuf::into_os_string)
+                .collect::<Vec<_>>()
+        })
+        .collect()
+}
+
+/// Expands `%NAME%` references like `ExpandEnvironmentStrings`, leaving unknown
+/// references untouched.
+fn expand_references(value: &str, lookup: impl Fn(&str) -> Option<String>) -> String {
+    let mut expanded = String::with_capacity(value.len());
+    let mut rest = value;
+    while let Some(start) = rest.find('%') {
+        expanded.push_str(&rest[..start]);
+        let after = &rest[start + 1..];
+        let Some(end) = after.find('%') else {
+            expanded.push_str(&rest[start..]);
+            return expanded;
+        };
+        let name = &after[..end];
+        match lookup(name).filter(|_| !name.is_empty()) {
+            Some(replacement) => {
+                expanded.push_str(&replacement);
+                rest = &after[end + 1..];
+            }
+            None => {
+                // The closing `%` may open the next reference.
+                expanded.push('%');
+                expanded.push_str(name);
+                rest = &after[end..];
+            }
+        }
+    }
+    expanded.push_str(rest);
+    expanded
+}
+
+fn append_missing_path_entries(
+    path: &OsStr,
+    persisted: impl IntoIterator<Item = OsString>,
+) -> OsString {
+    let mut seen: HashSet<String> = std::env::split_paths(path)
+        .map(|entry| normalize_path_entry(entry.as_os_str()))
+        .collect();
+    let mut result = path.to_os_string();
+    let mut needs_separator = !path.is_empty() && !path.to_string_lossy().ends_with(';');
+    for entry in persisted {
+        if entry.is_empty() || !seen.insert(normalize_path_entry(&entry)) {
+            continue;
+        }
+        if needs_separator {
+            result.push(";");
+        }
+        if entry.to_string_lossy().contains(';') {
+            result.push("\"");
+            result.push(&entry);
+            result.push("\"");
+        } else {
+            result.push(&entry);
+        }
+        needs_separator = true;
+    }
+    result
+}
+
+fn normalize_path_entry(entry: &OsStr) -> String {
+    entry
+        .to_string_lossy()
+        .trim()
+        .trim_end_matches(['\\', '/'])
+        .to_lowercase()
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+    use pretty_assertions::assert_eq;
+
+    fn persisted(value: &str, expand: bool) -> PersistedValue {
+        PersistedValue {
+            value: value.to_string(),
+            expand,
+        }
+    }
+
+    #[test]
+    fn appends_only_missing_entries_after_existing_ones() {
+        let path = append_missing_path_entries(
+            OsStr::new(r"C:\codex\bin;C:\Windows\system32"),
+            [
+                OsString::from(r"C:\WINDOWS\System32\"),
+                OsString::from(r"C:\nvm\nodejs"),
+                OsString::from(""),
+                OsString::from(r"c:\nvm\NODEJS\"),
+                OsString::from(r"C:\has;semicolon"),
+            ],
+        );
+
+        assert_eq!(
+            path,
+            OsString::from(r#"C:\codex\bin;C:\Windows\system32;C:\nvm\nodejs;"C:\has;semicolon""#)
+        );
+    }
+
+    #[test]
+    fn leaves_path_unchanged_when_nothing_is_missing() {
+        let path =
+            append_missing_path_entries(OsStr::new(r"C:\a;C:\b;"), [OsString::from(r"C:\B\")]);
+
+        assert_eq!(path, OsString::from(r"C:\a;C:\b;"));
+    }
+
+    #[test]
+    fn expands_known_references_and_keeps_unknown_ones() {
+        let lookup = |name: &str| match name.to_ascii_uppercase().as_str() {
+            "SYSTEMROOT" => Some(r"C:\Windows".to_string()),
+            "NVM_HOME" => Some(r"C:\nvm".to_string()),
+            _ => None,
+        };
+
+        assert_eq!(
+            expand_references(
+                r"%SystemRoot%\system32;%MISSING%;%NVM_HOME%\nodejs;100%;%%",
+                lookup
+            ),
+            r"C:\Windows\system32;%MISSING%;C:\nvm\nodejs;100%;%%"
+        );
+    }
+
+    #[test]
+    fn persisted_entries_list_system_before_user_and_resolve_persisted_variables() {
+        let system = HashMap::from([(
+            "PATH".to_string(),
+            persisted(r"C:\system;%TOOLS%\bin", /*expand*/ true),
+        )]);
+        let user = HashMap::from([
+            (
+                "TOOLS".to_string(),
+                persisted(r"C:\tools", /*expand*/ false),
+            ),
+            (
+                "PATH".to_string(),
+                persisted(r"C:\user;%TOOLS%\literal", /*expand*/ false),
+            ),
+        ]);
+
+        assert_eq!(
+            persisted_path_entries(&system, &user),
+            vec![
+                OsString::from(r"C:\system"),
+                OsString::from(r"C:\tools\bin"),
+                OsString::from(r"C:\user"),
+                OsString::from(r"%TOOLS%\literal"),
+            ]
+        );
+    }
+}

Activity

  1. added
    bug
    CLI
    windows-os
    mcp
    app-server
    on Oct 21, 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

    CLIapp-serverbugmcpwindows-os

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions