Repository navigation
Description
What version of Codex CLI is running?
Official unmodified codex-cli 0.165.0 and codex-cli 0.161.0 macOS arm64 release binaries. Both reproduce. Each downloaded release archive was checked against its GitHub release asset SHA-256 before extraction.
What subscription do you have? Which model were you using?
No subscription, account credentials, or model request is required. The reproducer only uses app-server initialize, thread/start, and mcpServerStatus/list. It never starts a turn; the configured provider is an unused local fixture.
Platform
macOS arm64, local Python standard-library HTTP server, app-server JSONL over subprocess pipes. No terminal/multiplexer dependency. An isolated HOME, CODEX_HOME and TMPDIR are used for each case.
What issue are you seeing?
With features.mcp_2026_07_28=true, a modern-only HTTP MCP server connects and exposes its echo tool when server/discover responds immediately. If its correctly correlated successful discovery response is intentionally held for 12 seconds, the same official clients fail with:
MCP startup failed: handshaking with MCP server failed: conflict initialized response id: expected 1, got 0
The client sends initialize after the outstanding discover response. The fixture advertises only 2026-07-28 and deliberately rejects legacy initialize; it echoes every valid request ID. This occurs with both application/json and text/event-stream. A separate wrong-ID negative control is rejected without initialize fallback.
| Fixture | 0.161.0 | 0.165.0 |
|---|---|---|
| Immediate JSON discovery | Connected; echo discovered; no initialize | Same |
| Immediate SSE discovery | Connected; echo discovered; no initialize | Same |
| Discovery success delayed 12 s, JSON | expected 1, got 0; initialize observed; no tools | Same |
| Discovery success delayed 12 s, SSE | expected 1, got 0; initialize observed; no tools | Same |
| Immediate JSON, response ID intentionally 99 | expected 0, got 99; no initialize | Same |
What steps can reproduce the bug?
- Download the unmodified
codex-aarch64-apple-darwin.tar.gzassets from 0.161.0 and 0.165.0. Check each archive against GitHub's asset digest. The tested archive SHA-256 values were:- 0.161.0:
bd83479f3ae21474c407ec2164fbc2a63fa763f7afbbd123fb6a69c5201cfd38 - 0.165.0:
78ea9c178d2dc8fde71d6494df3b9eab902fd6d6de0a84e65234220d93bb6144
- 0.161.0:
- Save the script below as reproduce.py. Place the extracted native executables beside it as
assets/codex-0.161.0andassets/codex-0.165.0; verify --version. - Run with Python 3.13+ (the script uses no third-party packages):
python3 reproduce.py --output runs/control --cases fast-json fast-sse
python3 reproduce.py --output runs/late --cases slow-json slow-sse wrong-idOutput directories must be new. Ten total observations were recorded. Each case closes its app-server process group and local listener. Script output contains selected method/ID/timing and server-status fields, not raw request bodies or arbitrary stderr.
Self-contained reproduce.py
"""Stock Codex app-server against an isolated HTTP MCP boundary; no model turn.
Only method, request id, response type and elapsed times are recorded.
The delayed cases deliberately withhold discovery for 12 seconds to cross the
SDK's internal 10-second Auto probe deadline. This is fault injection, not retry.
"""
import argparse
import concurrent.futures
import hashlib
import http.server
import json
import os
from pathlib import Path
import queue
import re
import signal
import subprocess
import threading
import time
ROOT = Path(__file__).resolve().parent
TOOL = {"name": "echo", "description": "Synthetic echo", "inputSchema": {"type": "object", "properties": {}}}
class Fixture:
def __init__(self, delay, sse, wrong_id=False):
self.delay, self.sse, self.wrong_id = delay, sse, wrong_id
self.started = time.monotonic()
self.events, self.lock = [], threading.Lock()
self.stop = threading.Event()
self.model_requests = 0
fixture = self
class Handler(http.server.BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def log_message(self, *_):
pass
def do_GET(self):
self.send_response(405)
self.send_header("Content-Length", "0")
self.end_headers()
def do_POST(self):
if self.path != "/mcp":
fixture.model_requests += 1
self.send_response(503)
self.send_header("Content-Length", "0")
self.end_headers()
return
body = json.loads(self.rfile.read(int(self.headers.get("Content-Length", 0))))
method, ident = body.get("method"), body.get("id")
fixture.record("received", method=method, id=ident,
protocol=self.headers.get("MCP-Protocol-Version"),
methodHeader=self.headers.get("Mcp-Method"))
if method == "server/discover":
if fixture.stop.wait(fixture.delay):
return
result = {"resultType": "complete", "supportedVersions": ["2026-07-28"],
"capabilities": {"tools": {}}, "ttlMs": 0, "cacheScope": "private",
"_meta": {"io.modelcontextprotocol/serverInfo": {"name": "modern-only-fixture", "version": "1"}}}
reply = {"jsonrpc": "2.0", "id": ident + 99 if fixture.wrong_id else ident, "result": result}
elif method == "initialize":
reply = {"jsonrpc": "2.0", "id": ident, "error": {"code": -32022,
"message": "Unsupported protocol version", "data": {"supported": ["2026-07-28"]}}}
elif method == "tools/list":
reply = {"jsonrpc": "2.0", "id": ident, "result": {"resultType": "complete", "tools": [TOOL]}}
elif method == "tools/call":
reply = {"jsonrpc": "2.0", "id": ident, "result": {"resultType": "complete", "content": [{"type": "text", "text": "pong"}]}}
elif method in ["resources/list", "resources/templates/list", "prompts/list"]:
key = {"resources/list": "resources", "resources/templates/list": "resourceTemplates", "prompts/list": "prompts"}[method]
reply = {"jsonrpc": "2.0", "id": ident, "result": {"resultType": "complete", key: []}}
else:
reply = {"jsonrpc": "2.0", "id": ident, "error": {"code": -32601, "message": "Method not found"}}
raw = json.dumps(reply).encode()
if fixture.sse:
raw = b"event: message\ndata: " + raw + b"\n\n"
try:
self.send_response(200)
self.send_header("Content-Type", "text/event-stream" if fixture.sse else "application/json")
self.send_header("Content-Length", str(len(raw)))
self.end_headers()
self.wfile.write(raw)
self.wfile.flush()
fixture.record("responded", method=method, id=reply["id"], result="error" if "error" in reply else "success")
except (BrokenPipeError, ConnectionResetError):
fixture.record("client_closed", method=method, id=reply["id"])
self.server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler)
self.server.daemon_threads = True
self.base = "http://127.0.0.1:" + str(self.server.server_port)
self.thread = threading.Thread(target=self.server.serve_forever, daemon=True)
self.thread.start()
def record(self, kind, **fields):
with self.lock:
self.events.append({"seconds": round(time.monotonic() - self.started, 4), "event": kind, **fields})
def close(self):
self.stop.set()
self.server.shutdown()
self.server.server_close()
self.thread.join(timeout=3)
class Rpc:
def __init__(self, binary, case, fixture):
self.pending, self.sequence, self.lock = {}, 0, threading.Lock()
self.errors = []
self.notifications = []
home, project, temp = (case / x for x in ["home", "project", "tmp"])
for d in [home, project, temp]:
d.mkdir()
(home / "config.toml").write_text(f'''model="gpt-5.4"
model_provider="fixture"
approval_policy="never"
sandbox_mode="danger-full-access"
cli_auth_credentials_store="ephemeral"
[features]
shell_snapshot=false
mcp_2026_07_28=true
[model_providers.fixture]
name="Unused local fixture"
base_url="{fixture.base}/v1"
wire_api="responses"
requires_openai_auth=false
[mcp_servers.probe]
url="{fixture.base}/mcp"
startup_timeout_sec=30
tool_timeout_sec=5
''')
env = {"PATH": "/usr/bin:/bin:/usr/sbin:/sbin", "HOME": str(case), "CODEX_HOME": str(home),
"TMPDIR": str(temp), "LANG": "C.UTF-8", "NO_PROXY": "127.0.0.1,localhost", "RUST_LOG": "off"}
self.proc = subprocess.Popen([str(binary), "app-server", "--strict-config"], cwd=project, env=env,
stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
text=True, bufsize=1, start_new_session=True)
self.reader = threading.Thread(target=self.read, daemon=True)
self.reader.start()
self.stderr_reader = threading.Thread(target=self.drain, daemon=True)
self.stderr_reader.start()
self.call("initialize", {"clientInfo": {"name": "http-discovery-reproducer", "version": "1"}, "capabilities": {"experimentalApi": True}})
self.write({"method": "initialized", "params": {}})
self.project = project
def drain(self):
# Retain only the exact diagnostic of interest, never complete stderr.
for line in self.proc.stderr:
match = re.search(r"conflict initialized response id: expected \d+, got \d+", line)
if match:
self.errors.append(match.group())
def read(self):
for line in self.proc.stdout:
msg = json.loads(line)
if "id" in msg and "method" not in msg:
q = self.pending.get(msg["id"])
if q:
q.put(msg)
elif "id" in msg:
self.write({"id": msg["id"], "error": {"code": -32601, "message": "No interaction allowed in fixture"}})
else:
self.notifications.append(msg)
def write(self, obj):
with self.lock:
self.proc.stdin.write(json.dumps(obj) + "\n")
self.proc.stdin.flush()
def call(self, method, params, timeout=40):
self.sequence += 1
ident, q = self.sequence, queue.Queue()
self.pending[ident] = q
self.write({"id": ident, "method": method, "params": params})
try:
msg = q.get(timeout=timeout)
finally:
self.pending.pop(ident, None)
if "error" in msg:
raise RuntimeError(json.dumps(msg["error"]))
return msg.get("result")
def close(self):
if self.proc.poll() is None:
os.killpg(self.proc.pid, signal.SIGTERM)
try:
self.proc.wait(timeout=5)
except subprocess.TimeoutExpired:
os.killpg(self.proc.pid, signal.SIGKILL)
self.proc.wait(timeout=5)
self.reader.join(timeout=2)
self.stderr_reader.join(timeout=2)
def run_case(version, name, delay, sse, wrong_id, output):
case = output / version / name
case.mkdir(parents=True)
binary = ROOT / "assets" / ("codex-" + version)
fixture = Fixture(delay, sse, wrong_id)
rpc = None
result = {"version": version, "case": name, "delaySeconds": delay, "responseFormat": "sse" if sse else "json",
"wrongResponseId": wrong_id, "startupTimeoutSeconds": 30}
try:
rpc = Rpc(binary, case, fixture)
tid = rpc.call("thread/start", {"cwd": str(rpc.project), "model": "gpt-5.4", "approvalPolicy": "never",
"sandbox": "danger-full-access", "ephemeral": True})["thread"]["id"]
status = rpc.call("mcpServerStatus/list", {"threadId": tid, "serverName": "probe", "detail": "toolsAndAuthOnly"})
servers = status.get("data", [])
selected = next((s for s in servers if s.get("name") == "probe"), {})
result["runtimeStatus"] = selected.get("runtimeStatus")
result["toolsError"] = selected.get("toolsError")
tools = selected.get("tools", {})
result["toolNames"] = list(tools) if isinstance(tools, dict) else [t.get("name") for t in tools]
result["statusFields"] = list(selected)
# Only the explicit local probe server error is retained from RPC output.
# There are no credentials, model responses or user data in this run.
result["connected"] = result["runtimeStatus"] == "connected" and bool(result["toolNames"])
except Exception as error:
result["driverError"] = str(error)[:1500]
finally:
if rpc:
rpc.close()
result["idConflictDiagnostics"] = sorted(set(rpc.errors))
fixture.close()
result["modelRequests"] = fixture.model_requests
result["events"] = fixture.events
result["methods"] = [e["method"] for e in fixture.events if e["event"] == "received"]
result["initializeSent"] = "initialize" in result["methods"]
(case / "result.json").write_text(json.dumps(result, indent=2) + "\n")
print(json.dumps({k: result.get(k) for k in ["version", "case", "connected", "initializeSent", "toolsError", "driverError"]}), flush=True)
return result
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--output", required=True)
parser.add_argument("--cases", nargs="+", default=["fast-json", "slow-json", "fast-sse", "slow-sse", "wrong-id"])
args = parser.parse_args()
output = Path(args.output).resolve()
output.mkdir(parents=True, exist_ok=False)
cases = {"fast-json": (0, False, False), "slow-json": (12, False, False),
"fast-sse": (0, True, False), "slow-sse": (12, True, False), "wrong-id": (0, False, True)}
tasks = [(v, n, *cases[n], output) for v in ["0.161.0", "0.165.0"] for n in args.cases]
with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool:
results = list(pool.map(lambda task: run_case(*task), tasks))
summary = {"scope": "Official macOS arm64 Codex app-server; synthetic loopback HTTP MCP; no model turn or authentication",
"results": results, "sourceSha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest()}
(output / "summary.json").write_text(json.dumps(summary, indent=2) + "\n")
if __name__ == "__main__":
main()What is the expected behavior?
A successful modern discovery response should not be consumed as a response to a different initialize request. The client may fail at a documented discovery/startup deadline, or handle late response correlation correctly; it should retain an actionable error instead of misreporting the earlier ID as an invalid initialization result. This report does not request indefinite startup waits, weakened ID validation, or a legacy initialize bridge in a modern-only server.
A supported per-server modern-only lifecycle would also let managed modern-only configurations fail closed instead of falling back. Both inspected releases currently map the modern feature to ClientLifecycleMode::Auto; this is a possible API improvement, not a claim that changing lifecycle policy is the only correct fix.
Additional information and evidence limits
Related SDK report: modelcontextprotocol/rust-sdk#1400. That report uses official Goose and a legacy stdio fixture; this reproduction uses official Codex and a modern-only Streamable HTTP fixture.
Source inspection shows an internal ten-second Auto discovery timeout and same-transport initialize fallback in the pinned Rust SDK. In the recorded HTTP server trace, the server receives discover ID 0, writes its correct success approximately twelve seconds later, then receives initialize ID 1 and returns a correctly correlated unsupported-version error. Server-side timestamps do not independently prove when the client internally chose fallback or sent a queued HTTP request; the native mcpServerStatus/list error is the directly observed result.
The overall MCP startup timeout is 30 seconds in every case. Intentional fixture delay is fault injection; there are no retries or timeout increases to mask the result. No production endpoint, OAuth, nono, private plugin, real account or user conversation is involved. Passing immediate-response controls demonstrate that the response shape is accepted by both tested clients. The discover response shape follows Codex's own rmcp-client modern_discover_result fixture.
Codex doctor output was not collected; this isolated, unauthenticated app-server protocol reproducer avoids importing personal client state. Codex agents assisted with source investigation and authored/executed this reproducer. No fix is claimed.
Activity