unified-agent-api-codex 0.3.5

Async wrapper around the Codex CLI for programmatic prompting
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
use std::{
    collections::HashMap,
    ffi::OsString,
    sync::{
        atomic::{AtomicU64, Ordering},
        Arc,
    },
    time::Duration,
};

use serde::Deserialize;
use serde_json::Value;
use tokio::{
    io::{AsyncBufReadExt, AsyncWriteExt, BufReader},
    process::{Child, ChildStderr, ChildStdin, ChildStdout, Command},
    sync::{mpsc, oneshot, Mutex},
    task::JoinHandle,
    time,
};
use tracing::{debug, warn};

use super::{
    AppNotification, ApprovalKind, ApprovalRequest, CodexEvent, EventStream, InitializeParams,
    McpError, RequestId, StdioServerConfig, METHOD_CANCEL, METHOD_CODEX_EVENT, METHOD_EXIT,
    METHOD_INITIALIZE, METHOD_SHUTDOWN,
};

#[derive(Clone)]
enum NotificationHook {
    Codex {
        sinks: Arc<Mutex<Vec<mpsc::UnboundedSender<CodexEvent>>>>,
    },
    App {
        sinks: Arc<Mutex<Vec<mpsc::UnboundedSender<AppNotification>>>>,
    },
}

type PendingRequests = Arc<Mutex<HashMap<RequestId, oneshot::Sender<Result<Value, McpError>>>>>;

/// Internal transport that handles stdio JSON-RPC.
pub(super) struct JsonRpcTransport {
    writer: mpsc::UnboundedSender<String>,
    pending: PendingRequests,
    notification_hook: NotificationHook,
    next_id: AtomicU64,
    tasks: Vec<JoinHandle<()>>,
    child: Arc<Mutex<Option<Child>>>,
    startup_timeout: Duration,
}

impl JsonRpcTransport {
    pub(super) async fn spawn_mcp(config: StdioServerConfig) -> Result<Self, McpError> {
        let hook = NotificationHook::Codex {
            sinks: Arc::new(Mutex::new(Vec::new())),
        };
        Self::spawn_with_subcommand(config, "mcp-server", hook).await
    }

    pub(super) async fn spawn_app(config: StdioServerConfig) -> Result<Self, McpError> {
        let hook = NotificationHook::App {
            sinks: Arc::new(Mutex::new(Vec::new())),
        };
        Self::spawn_with_subcommand(config, "app-server", hook).await
    }

    async fn spawn_with_subcommand(
        config: StdioServerConfig,
        subcommand: &str,
        notification_hook: NotificationHook,
    ) -> Result<Self, McpError> {
        let mut command = Command::new(&config.binary);
        command
            .arg(subcommand)
            .args(
                (subcommand == "app-server" && config.app_server_analytics_default_enabled)
                    .then_some(OsString::from("--analytics-default-enabled")),
            )
            .stdin(std::process::Stdio::piped())
            .stdout(std::process::Stdio::piped())
            .stderr(std::process::Stdio::piped())
            .kill_on_drop(true);

        if let Some(dir) = &config.current_dir {
            command.current_dir(dir);
        }

        if let Some(code_home) = &config.code_home {
            command.env("CODEX_HOME", code_home);
        }

        for (key, value) in &config.env {
            command.env(key, value);
        }

        let command_debug = format!("{command:?}");
        let mut backoff = Duration::from_millis(2);
        let mut child = {
            let mut child = None;
            for attempt in 0..5 {
                match command.spawn() {
                    Ok(spawned) => {
                        child = Some(spawned);
                        break;
                    }
                    Err(source) => {
                        let is_busy =
                            matches!(source.kind(), std::io::ErrorKind::ExecutableFileBusy)
                                || source.raw_os_error() == Some(26);
                        if is_busy && attempt < 4 {
                            tokio::time::sleep(backoff).await;
                            backoff = std::cmp::min(backoff * 2, Duration::from_millis(50));
                            continue;
                        }
                        return Err(McpError::Spawn {
                            command: command_debug,
                            source,
                        });
                    }
                }
            }
            child.expect("spawn loop should return or set child")
        };

        let stdout = child
            .stdout
            .take()
            .ok_or_else(|| McpError::Transport("child stdout unavailable".into()))?;
        let stdin = child
            .stdin
            .take()
            .ok_or_else(|| McpError::Transport("child stdin unavailable".into()))?;
        let stderr = child.stderr.take();

        let pending = Arc::new(Mutex::new(HashMap::new()));
        let (writer_tx, writer_rx) = mpsc::unbounded_channel();

        let writer_handle = tokio::spawn(writer_task(stdin, writer_rx));
        let reader_handle = tokio::spawn(reader_task(
            stdout,
            pending.clone(),
            notification_hook.clone(),
            config.mirror_stdio,
        ));

        let stderr_handle =
            stderr.map(|stderr| tokio::spawn(stderr_task(stderr, config.mirror_stdio)));

        let mut tasks = vec![writer_handle, reader_handle];
        if let Some(handle) = stderr_handle {
            tasks.push(handle);
        }

        Ok(Self {
            writer: writer_tx,
            pending,
            notification_hook,
            next_id: AtomicU64::new(1),
            tasks,
            child: Arc::new(Mutex::new(Some(child))),
            startup_timeout: config.startup_timeout,
        })
    }

    pub(super) async fn initialize(
        &self,
        params: InitializeParams,
        timeout: Duration,
    ) -> Result<Value, McpError> {
        let (_, rx) = self
            .request(METHOD_INITIALIZE, serde_json::to_value(params)?)
            .await?;
        recv_with_timeout(rx, timeout).await
    }

    pub(super) async fn request(
        &self,
        method: &str,
        params: Value,
    ) -> Result<(RequestId, oneshot::Receiver<Result<Value, McpError>>), McpError> {
        let id = self.next_id.fetch_add(1, Ordering::SeqCst);
        let message = serde_json::json!({
            "jsonrpc": "2.0",
            "id": id,
            "method": method,
            "params": params
        });
        let serialized = serde_json::to_string(&message)?;
        let (tx, rx) = oneshot::channel();

        {
            let mut guard = self.pending.lock().await;
            guard.insert(id, tx);
        }

        if self.writer.send(serialized).is_err() {
            let mut guard = self.pending.lock().await;
            guard.remove(&id);
            return Err(McpError::ChannelClosed);
        }

        Ok((id, rx))
    }

    pub(super) async fn register_codex_listener(&self) -> EventStream<CodexEvent> {
        match &self.notification_hook {
            NotificationHook::Codex { sinks } => {
                let (tx, rx) = mpsc::unbounded_channel();
                let mut guard = sinks.lock().await;
                guard.push(tx);
                rx
            }
            _ => {
                let (_tx, rx) = mpsc::unbounded_channel();
                rx
            }
        }
    }

    pub(super) async fn register_app_listener(&self) -> EventStream<AppNotification> {
        match &self.notification_hook {
            NotificationHook::App { sinks } => {
                let (tx, rx) = mpsc::unbounded_channel();
                let mut guard = sinks.lock().await;
                guard.push(tx);
                rx
            }
            _ => {
                let (_tx, rx) = mpsc::unbounded_channel();
                rx
            }
        }
    }

    pub(super) fn cancel(&self, request_id: RequestId) -> Result<(), McpError> {
        let message = serde_json::json!({
            "jsonrpc": "2.0",
            "method": METHOD_CANCEL,
            "params": { "id": request_id }
        });
        let serialized = serde_json::to_string(&message)?;
        self.writer
            .send(serialized)
            .map_err(|_| McpError::ChannelClosed)
    }

    pub(super) async fn shutdown(&self) -> Result<(), McpError> {
        if let Ok((_, rx)) = self.request(METHOD_SHUTDOWN, Value::Null).await {
            let _ = recv_with_timeout(rx, Duration::from_secs(5)).await;
        }

        let exit_message = serde_json::json!({
            "jsonrpc": "2.0",
            "method": METHOD_EXIT,
            "params": Value::Null
        });

        let _ = self
            .writer
            .send(serde_json::to_string(&exit_message).unwrap_or_default());

        Ok(())
    }

    pub(super) fn startup_timeout(&self) -> Duration {
        self.startup_timeout
    }
}

impl Drop for JsonRpcTransport {
    fn drop(&mut self) {
        for handle in &self.tasks {
            handle.abort();
        }

        if let Ok(mut child_guard) = self.child.try_lock() {
            if let Some(mut child) = child_guard.take() {
                let _ = child.start_kill();
            }
        }
    }
}

#[derive(Debug, Deserialize)]
struct RpcResponse {
    id: Value,
    result: Option<Value>,
    error: Option<RpcError>,
}

#[derive(Debug, Deserialize)]
struct RpcNotification {
    method: String,
    params: Option<Value>,
}

#[derive(Debug, Deserialize)]
struct RpcError {
    code: i64,
    message: String,
    data: Option<Value>,
}

async fn writer_task(mut stdin: ChildStdin, mut rx: mpsc::UnboundedReceiver<String>) {
    while let Some(message) = rx.recv().await {
        if stdin.write_all(message.as_bytes()).await.is_err() {
            break;
        }
        if stdin.write_all(b"\n").await.is_err() {
            break;
        }
        let _ = stdin.flush().await;
    }

    let _ = stdin.shutdown().await;
}

async fn reader_task(
    stdout: ChildStdout,
    pending: PendingRequests,
    notification_hook: NotificationHook,
    mirror_stdio: bool,
) {
    let mut lines = BufReader::new(stdout).lines();
    loop {
        let line = match lines.next_line().await {
            Ok(Some(line)) => line,
            Ok(None) => break,
            Err(err) => {
                warn!("failed to read MCP stdout: {err}");
                break;
            }
        };

        if mirror_stdio {
            eprintln!("[mcp stdout] {line}");
        }

        if line.trim().is_empty() {
            continue;
        }

        let value: Value = match serde_json::from_str(&line) {
            Ok(value) => value,
            Err(err) => {
                warn!("failed to parse MCP stdout as JSON: {err}");
                continue;
            }
        };

        match decode_message(value) {
            Some(Incoming::Response(response)) => {
                handle_response(response, &pending).await;
            }
            Some(Incoming::Notification(notification)) => match &notification_hook {
                NotificationHook::Codex { sinks } => {
                    if notification.method == METHOD_CODEX_EVENT {
                        let params = notification.params.unwrap_or(Value::Null);
                        let event = parse_codex_event(&params).unwrap_or(CodexEvent::Raw {
                            method: METHOD_CODEX_EVENT.to_string(),
                            params,
                        });
                        broadcast_codex_event(event, sinks).await;
                    }
                }
                NotificationHook::App { sinks } => {
                    let params = notification.params.unwrap_or(Value::Null);
                    let event = parse_app_notification(&notification.method, &params);
                    broadcast_app_event(event, sinks).await;
                }
            },
            None => {
                warn!("received malformed MCP message");
            }
        }
    }

    let mut guard = pending.lock().await;
    for (_, tx) in guard.drain() {
        let _ = tx.send(Err(McpError::ChannelClosed));
    }
}

async fn stderr_task(stderr: ChildStderr, mirror_stdio: bool) {
    let mut lines = BufReader::new(stderr).lines();
    loop {
        let line = match lines.next_line().await {
            Ok(Some(line)) => line,
            Ok(None) => break,
            Err(err) => {
                warn!("failed to read MCP stderr: {err}");
                break;
            }
        };

        if mirror_stdio {
            eprintln!("[mcp stderr] {line}");
        } else {
            debug!("mcp stderr: {line}");
        }
    }
}

pub(super) fn map_response<T: for<'a> Deserialize<'a> + Send + 'static>(
    rx: oneshot::Receiver<Result<Value, McpError>>,
) -> oneshot::Receiver<Result<T, McpError>> {
    let (tx, mapped_rx) = oneshot::channel();
    tokio::spawn(async move {
        let mapped = match rx.await {
            Ok(Ok(value)) => serde_json::from_value::<T>(value).map_err(McpError::from),
            Ok(Err(err)) => Err(err),
            Err(_) => Err(McpError::ChannelClosed),
        };
        let _ = tx.send(mapped);
    });
    mapped_rx
}

async fn recv_with_timeout(
    rx: oneshot::Receiver<Result<Value, McpError>>,
    timeout: Duration,
) -> Result<Value, McpError> {
    match time::timeout(timeout, rx).await {
        Ok(Ok(Ok(value))) => Ok(value),
        Ok(Ok(Err(err))) => Err(err),
        Ok(Err(_)) => Err(McpError::ChannelClosed),
        Err(_) => Err(McpError::Timeout(timeout)),
    }
}

#[derive(Debug)]
enum Incoming {
    Response(RpcResponse),
    Notification(RpcNotification),
}

fn decode_message(value: Value) -> Option<Incoming> {
    let is_notification = value.get("id").is_none() && value.get("method").is_some();
    if is_notification {
        let notification: RpcNotification = serde_json::from_value(value).ok()?;
        return Some(Incoming::Notification(notification));
    }

    let is_response = value.get("id").is_some();
    if is_response {
        let response: RpcResponse = serde_json::from_value(value).ok()?;
        return Some(Incoming::Response(response));
    }

    None
}

async fn handle_response(response: RpcResponse, pending: &PendingRequests) {
    let Some(id) = parse_request_id(&response.id) else {
        warn!("received response without numeric id");
        return;
    };

    let sender = { pending.lock().await.remove(&id) };
    let Some(tx) = sender else {
        return;
    };

    if let Some(err) = response.error {
        let mapped = if err.code == -32800 {
            McpError::Cancelled
        } else {
            McpError::Rpc {
                code: err.code,
                message: err.message,
                data: err.data,
            }
        };
        let _ = tx.send(Err(mapped));
    } else if let Some(result) = response.result {
        let _ = tx.send(Ok(result));
    } else {
        let _ = tx.send(Err(McpError::Transport(
            "response missing result and error".into(),
        )));
    }
}

fn parse_request_id(value: &Value) -> Option<RequestId> {
    if let Some(num) = value.as_u64() {
        return Some(num);
    }

    value.as_str().and_then(|s| s.parse::<RequestId>().ok())
}

fn parse_codex_event(value: &Value) -> Option<CodexEvent> {
    let payload = value.get("msg").unwrap_or(value);
    let event_type = payload.get("type")?.as_str()?;
    let conversation_id = payload
        .get("thread_id")
        .or_else(|| payload.get("threadId"))
        .or_else(|| payload.get("session_id"))
        .or_else(|| payload.get("conversation_id"))
        .or_else(|| payload.get("conversationId"))
        .and_then(Value::as_str)
        .unwrap_or_default()
        .to_string();

    match event_type {
        "task_complete" => Some(CodexEvent::TaskComplete {
            conversation_id,
            result: payload
                .get("result")
                .cloned()
                .unwrap_or_else(|| payload.clone()),
        }),
        "approval_required" | "approval" => {
            let approval_id = payload
                .get("approval_id")
                .or_else(|| payload.get("id"))
                .and_then(Value::as_str)
                .unwrap_or_default()
                .to_string();
            let raw_kind = payload
                .get("kind")
                .or_else(|| payload.get("approval_kind"))
                .and_then(Value::as_str)
                .unwrap_or("unknown")
                .to_string();

            let kind = match raw_kind.to_lowercase().as_str() {
                "exec" => ApprovalKind::Exec,
                "apply" => ApprovalKind::Apply,
                other => ApprovalKind::Unknown(other.to_string()),
            };

            Some(CodexEvent::ApprovalRequired(ApprovalRequest {
                approval_id,
                kind,
                payload: payload.clone(),
            }))
        }
        "cancelled" | "canceled" => Some(CodexEvent::Cancelled {
            conversation_id: payload
                .get("conversation_id")
                .and_then(Value::as_str)
                .map(|s| s.to_string()),
            reason: payload
                .get("reason")
                .and_then(Value::as_str)
                .map(|s| s.to_string()),
        }),
        "error" => Some(CodexEvent::Error {
            message: payload
                .get("message")
                .or_else(|| payload.get("error"))
                .and_then(Value::as_str)
                .unwrap_or_default()
                .to_string(),
            data: payload.get("data").cloned(),
        }),
        _ => None,
    }
}

async fn broadcast_codex_event(
    event: CodexEvent,
    sinks: &Arc<Mutex<Vec<mpsc::UnboundedSender<CodexEvent>>>>,
) {
    let mut guard = sinks.lock().await;
    guard.retain(|tx| tx.send(event.clone()).is_ok());
}

fn parse_app_notification(method: &str, value: &Value) -> AppNotification {
    let notification_type = value
        .get("type")
        .and_then(Value::as_str)
        .unwrap_or_default()
        .to_lowercase();

    let thread_id = extract_string(value, &["thread_id", "threadId"]).unwrap_or_default();
    let turn_id = extract_string(value, &["turn_id", "turnId"]);

    match notification_type.as_str() {
        "task_complete" | "taskcomplete" => AppNotification::TaskComplete {
            thread_id,
            turn_id,
            result: value.get("result").cloned().unwrap_or(Value::Null),
        },
        "item" => AppNotification::Item {
            thread_id,
            turn_id,
            item: value.get("item").cloned().unwrap_or_else(|| value.clone()),
        },
        "error" => AppNotification::Error {
            message: value
                .get("message")
                .or_else(|| value.get("error"))
                .and_then(Value::as_str)
                .unwrap_or_default()
                .to_string(),
            data: value.get("data").cloned(),
        },
        _ => AppNotification::Raw {
            method: method.to_string(),
            params: value.clone(),
        },
    }
}

fn extract_string(value: &Value, keys: &[&str]) -> Option<String> {
    keys.iter()
        .find_map(|key| value.get(key).and_then(Value::as_str))
        .map(|s| s.to_string())
}

async fn broadcast_app_event(
    event: AppNotification,
    sinks: &Arc<Mutex<Vec<mpsc::UnboundedSender<AppNotification>>>>,
) {
    let mut guard = sinks.lock().await;
    guard.retain(|tx| tx.send(event.clone()).is_ok());
}