serial-mcp 0.9.3

MCP server for serial port communication. 25 tools (list/open/read/write/transact/capture_boot/get_status/reconfigure/list_profiles/open_profile/save_profile/delete_profile/configure/rollback_profile/get_log/clear_log/export_log/reconnect/compute_checksum/...), resources, prompts, task cancellation, stdio + streamable-HTTP transports.
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
//! Per-connection TX worker for serialized write/flush operations.
//!
//! Each open connection can have at most one [`TxSession`], which owns a
//! background task that is the sole caller of `SerialConnection::write()` and
//! `SerialConnection::flush_buffers(Output)`. MCP write and flush tools
//! enqueue requests via an mpsc channel and await a oneshot acknowledgment.
//! TX serialization does not contend with the active RX pump.

use std::collections::HashMap;
use std::sync::Arc;
use std::sync::Mutex as StdMutex;

use tokio::sync::Mutex as AsyncMutex;
use tokio::sync::{mpsc, oneshot};
use tokio::task::JoinHandle;
use tokio_util::sync::CancellationToken;
use tracing::{debug, info};

use crate::error::SerialError;
use crate::serial::{FlushTarget, SerialConnection};

const TX_CHANNEL_CAPACITY: usize = 64;

enum TxRequest {
    Write {
        data: Arc<[u8]>,
        ack: oneshot::Sender<Result<usize, SerialError>>,
    },
    Flush {
        ack: oneshot::Sender<Result<(), SerialError>>,
    },
}

pub struct TxSession {
    connection_id: String,
    tx: StdMutex<Option<mpsc::Sender<TxRequest>>>,
    worker_task: StdMutex<Option<JoinHandle<()>>>,
}

impl TxSession {
    pub fn new(connection: Arc<SerialConnection>) -> Self {
        let connection_id = connection.id().to_string();
        let close_token = connection.cancel_token();
        let (tx, rx) = mpsc::channel(TX_CHANNEL_CAPACITY);
        let handle = tokio::spawn(tx_worker(connection, rx, close_token));
        Self {
            connection_id,
            tx: StdMutex::new(Some(tx)),
            worker_task: StdMutex::new(Some(handle)),
        }
    }

    pub fn connection_id(&self) -> &str {
        &self.connection_id
    }

    pub async fn write(&self, data: Arc<[u8]>) -> Result<usize, SerialError> {
        let (ack_tx, ack_rx) = oneshot::channel();
        let tx = self
            .tx
            .lock()
            .expect("tx mutex poisoned")
            .as_ref()
            .cloned()
            .ok_or_else(|| SerialError::ConnectionClosed(self.connection_id.clone()))?;
        tx.send(TxRequest::Write { data, ack: ack_tx })
            .await
            .map_err(|_| SerialError::ConnectionClosed(self.connection_id.clone()))?;
        ack_rx
            .await
            .map_err(|_| SerialError::ConnectionClosed(self.connection_id.clone()))?
    }

    pub async fn flush_output(&self) -> Result<(), SerialError> {
        let (ack_tx, ack_rx) = oneshot::channel();
        let tx = self
            .tx
            .lock()
            .expect("tx mutex poisoned")
            .as_ref()
            .cloned()
            .ok_or_else(|| SerialError::ConnectionClosed(self.connection_id.clone()))?;
        tx.send(TxRequest::Flush { ack: ack_tx })
            .await
            .map_err(|_| SerialError::ConnectionClosed(self.connection_id.clone()))?;
        ack_rx
            .await
            .map_err(|_| SerialError::ConnectionClosed(self.connection_id.clone()))?
    }

    pub async fn shutdown_and_join(&self) {
        let _ = self.tx.lock().expect("tx mutex poisoned").take();
        let handle = self
            .worker_task
            .lock()
            .expect("worker_task mutex poisoned")
            .take();
        if let Some(h) = handle {
            let _ = h.await;
        }
    }
}

async fn tx_worker(
    connection: Arc<SerialConnection>,
    mut rx: mpsc::Receiver<TxRequest>,
    close_token: CancellationToken,
) {
    let conn_id = connection.id().to_string();
    info!("tx_session: worker entered for {conn_id}");

    loop {
        let req = tokio::select! {
            _ = close_token.cancelled() => break,
            req = rx.recv() => match req {
                Some(r) => r,
                None => break,
            },
        };
        match req {
            TxRequest::Write { data, ack } => {
                let result = connection.write(&data).await;
                let _ = ack.send(result);
            }
            TxRequest::Flush { ack } => {
                let result = connection.flush_buffers(FlushTarget::Output).await;
                let _ = ack.send(result);
            }
        }
    }

    info!("tx_session: worker exiting for {conn_id}");
}

pub struct TxSessionManager {
    sessions: AsyncMutex<HashMap<String, Arc<TxSession>>>,
}

impl Default for TxSessionManager {
    fn default() -> Self {
        Self::new()
    }
}

impl TxSessionManager {
    pub fn new() -> Self {
        Self {
            sessions: AsyncMutex::new(HashMap::new()),
        }
    }

    pub async fn get_or_create(&self, connection: Arc<SerialConnection>) -> Arc<TxSession> {
        let conn_id = connection.id().to_string();
        let mut sessions = self.sessions.lock().await;
        if let Some(existing) = sessions.get(&conn_id) {
            return Arc::clone(existing);
        }
        let session = Arc::new(TxSession::new(connection));
        sessions.insert(conn_id, Arc::clone(&session));
        debug!(
            "tx_session: created new session for connection {}",
            session.connection_id()
        );
        session
    }

    pub async fn remove(&self, connection_id: &str) {
        let session = {
            let mut sessions = self.sessions.lock().await;
            sessions.remove(connection_id)
        };
        if let Some(session) = session {
            session.shutdown_and_join().await;
            info!("tx_session: removed session for connection {connection_id}");
        }
    }

    pub async fn count(&self) -> usize {
        self.sessions.lock().await.len()
    }

    pub async fn get(&self, connection_id: &str) -> Option<Arc<TxSession>> {
        self.sessions.lock().await.get(connection_id).cloned()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::serial::test_support::loopback_connection;
    use std::time::Duration;
    use tokio::io::AsyncReadExt;

    #[tokio::test]
    async fn tx_write_bytes_reach_peer() {
        let (conn, mut peer) = loopback_connection("test-write-peer");
        let conn = Arc::new(conn);
        let session = TxSession::new(Arc::clone(&conn));

        let data: Arc<[u8]> = Arc::from(b"hello".as_slice());
        let n = session.write(data).await.unwrap();
        assert_eq!(n, 5);

        let mut buf = [0u8; 5];
        tokio::time::timeout(Duration::from_millis(500), peer.read_exact(&mut buf))
            .await
            .unwrap()
            .unwrap();
        assert_eq!(&buf, b"hello");
    }

    #[tokio::test]
    async fn tx_sequential_writes_preserve_order() {
        let (conn, mut peer) = loopback_connection("test-write-order");
        let conn = Arc::new(conn);
        let session = TxSession::new(Arc::clone(&conn));

        for ch in b"ABCDE" {
            let data: Arc<[u8]> = Arc::from(vec![*ch].as_slice());
            session.write(data).await.unwrap();
        }

        let mut buf = [0u8; 5];
        tokio::time::timeout(Duration::from_millis(500), peer.read_exact(&mut buf))
            .await
            .unwrap()
            .unwrap();
        assert_eq!(&buf, b"ABCDE");
    }

    #[tokio::test]
    async fn tx_write_during_active_pump_returns_quickly() {
        use crate::buffer_budget::AtomicBudget;
        use crate::rx_session::RxSessionManager;

        let (conn, _peer) = loopback_connection("test-write-fast");
        let conn = Arc::new(conn);
        let budget: Arc<dyn crate::buffer_budget::BufferBudget> =
            Arc::new(AtomicBudget::new(1024 * 1024, 1024 * 1024));
        let rx_mgr = RxSessionManager::new(
            budget,
            std::sync::Arc::new(crate::resource_events::ResourceEventHub::new(64)),
        );
        let _rx_session = rx_mgr.get_or_create(Arc::clone(&conn), 1024).await.unwrap();

        let tx_session = TxSession::new(Arc::clone(&conn));

        let start = std::time::Instant::now();
        let data: Arc<[u8]> = Arc::from(b"x".as_slice());
        tx_session.write(data).await.unwrap();
        let elapsed = start.elapsed();
        assert!(
            elapsed < Duration::from_millis(200),
            "write via TxSession took {elapsed:?}, should be fast even with pump active"
        );

        rx_mgr.remove(conn.id()).await;
    }

    #[tokio::test]
    async fn tx_flush_output_sequenced_after_writes() {
        let (conn, mut peer) = loopback_connection("test-flush-order");
        let conn = Arc::new(conn);
        let session = TxSession::new(Arc::clone(&conn));

        for ch in b"abc" {
            let data: Arc<[u8]> = Arc::from(vec![*ch].as_slice());
            session.write(data).await.unwrap();
        }
        session.flush_output().await.unwrap();

        let mut buf = [0u8; 3];
        tokio::time::timeout(Duration::from_millis(500), peer.read_exact(&mut buf))
            .await
            .unwrap()
            .unwrap();
        assert_eq!(&buf, b"abc");
    }

    #[tokio::test]
    async fn tx_close_while_writes_queued_returns_connection_closed() {
        let (conn, _peer) = loopback_connection("test-close-queued");
        let conn = Arc::new(conn);
        let session = TxSession::new(Arc::clone(&conn));

        conn.close().await.unwrap();

        let data: Arc<[u8]> = Arc::from(b"fail".as_slice());
        let result = session.write(data).await;
        assert!(
            matches!(result, Err(SerialError::ConnectionClosed(_))),
            "expected ConnectionClosed after close, got {result:?}"
        );
    }

    #[tokio::test]
    async fn tx_get_or_create_is_idempotent() {
        let (conn, _peer) = loopback_connection("test-idempotent");
        let conn = Arc::new(conn);
        let mgr = TxSessionManager::new();
        let s1 = mgr.get_or_create(Arc::clone(&conn)).await;
        let s2 = mgr.get_or_create(Arc::clone(&conn)).await;
        assert!(Arc::ptr_eq(&s1, &s2));
        assert_eq!(mgr.count().await, 1);
    }

    #[tokio::test]
    async fn tx_no_session_for_read_only_connection() {
        let (conn, _peer) = loopback_connection("test-read-only");
        let conn = Arc::new(conn);
        let mgr = TxSessionManager::new();
        assert_eq!(mgr.count().await, 0);

        use crate::buffer_budget::AtomicBudget;
        use crate::rx_session::RxSessionManager;
        let budget: Arc<dyn crate::buffer_budget::BufferBudget> =
            Arc::new(AtomicBudget::new(1024 * 1024, 1024 * 1024));
        let rx_mgr = RxSessionManager::new(
            budget,
            std::sync::Arc::new(crate::resource_events::ResourceEventHub::new(64)),
        );
        let rx_session = rx_mgr.get_or_create(Arc::clone(&conn), 1024).await.unwrap();
        drop(rx_session); // pump is running, no need to hold a consumer

        assert_eq!(mgr.count().await, 0);

        rx_mgr.remove(conn.id()).await;
    }

    // ── TX flush-before-delivery semantics ───────────────────────────────
    //
    // These tests cover the flushed-before-delivery TX case: bytes written
    // via `TxSession::write` that are still queued in the OS transmit queue
    // are discarded by `flush(target=output)` before the device drains them.
    // They use `queued_tx_connection`, a mock `SerialIo` backend whose TX
    // path models an OS transmit queue: written bytes land in the queue, and
    // `clear_os_buffers(Output)` (the backend behind `flush(target=output)`)
    // discards bytes still queued before the device has drained them. This
    // is the state a real PTY cannot reproduce because a PTY delivers every
    // `write()` byte into its kernel buffer immediately.

    /// Bytes written via `TxSession::write` land in the OS TX queue. A
    /// subsequent `flush_output` discards them before the device drains,
    /// so the device never sees them. Proves flushed-before-delivery.
    #[tokio::test]
    async fn tx_flush_output_drops_undrained_queued_tx() {
        use crate::serial::test_support::queued_tx_connection;

        let (conn, handle) = queued_tx_connection("test-flush-before-delivery");
        let conn = Arc::new(conn);
        let session = TxSession::new(Arc::clone(&conn));

        // Write a command. Bytes land in the OS TX queue; the device has not
        // drained them yet.
        let data: Arc<[u8]> = Arc::from(b"ping\r\n".as_slice());
        let n = session.write(data).await.unwrap();
        assert_eq!(n, 6, "write should report all bytes accepted");
        assert_eq!(
            handle.tx_queue_len(),
            6,
            "bytes should be queued, not yet delivered to device"
        );

        // Flush output before the device drains. This must discard the
        // queued bytes.
        session.flush_output().await.unwrap();
        assert_eq!(
            handle.tx_queue_len(),
            0,
            "flush(output) must discard undrained TX queue"
        );

        // The device now drains its RX: there must be nothing to drain.
        let drained = handle.drain_tx(64);
        assert!(
            drained.is_empty(),
            "device must receive nothing after flush-before-delivery, got {drained:?}"
        );

        // Sanity: a later write still lands in the queue and is drainable,
        // proving the flush did not break the TX path.
        let data2: Arc<[u8]> = Arc::from(b"pong\r\n".as_slice());
        session.write(data2).await.unwrap();
        assert_eq!(handle.tx_queue_len(), 6, "second write should queue");
        let drained2 = handle.drain_tx(64);
        assert_eq!(drained2, b"pong\r\n", "device should drain second write");
    }

    /// A flush(output) issued when the TX queue is already empty is a no-op
    /// and does not affect later writes. Guards against a flush that
    /// accidentally discards bytes written after it.
    #[tokio::test]
    async fn tx_flush_output_on_empty_queue_does_not_drop_later_write() {
        use crate::serial::test_support::queued_tx_connection;

        let (conn, handle) = queued_tx_connection("test-flush-empty-queue");
        let conn = Arc::new(conn);
        let session = TxSession::new(Arc::clone(&conn));

        // Flush with an empty queue — must succeed and change nothing.
        session.flush_output().await.unwrap();
        assert_eq!(handle.tx_queue_len(), 0);

        // A write after the flush must still be drainable by the device.
        let data: Arc<[u8]> = Arc::from(b"after\r\n".as_slice());
        session.write(data).await.unwrap();
        assert_eq!(handle.tx_queue_len(), 7);
        let drained = handle.drain_tx(64);
        assert_eq!(
            drained, b"after\r\n",
            "write after empty flush must survive"
        );
    }

    /// Flushing output after the device has already drained the queue does
    /// not retroactively affect the delivered bytes. Proves flush(output)
    /// is a no-op on already-delivered TX.
    #[tokio::test]
    async fn tx_flush_output_after_drain_does_not_recall_delivered() {
        use crate::serial::test_support::queued_tx_connection;

        let (conn, handle) = queued_tx_connection("test-flush-after-drain");
        let conn = Arc::new(conn);
        let session = TxSession::new(Arc::clone(&conn));

        // Write, then drain (device consumes) before flushing.
        let data: Arc<[u8]> = Arc::from(b"delivered\r\n".as_slice());
        session.write(data).await.unwrap();
        let drained = handle.drain_tx(64);
        assert_eq!(drained, b"delivered\r\n", "device drains first");
        assert_eq!(handle.tx_queue_len(), 0, "queue empty after drain");

        // Flush output now — must succeed and must not "un-deliver" anything.
        session.flush_output().await.unwrap();
        assert_eq!(handle.tx_queue_len(), 0);

        // Device has already received the bytes; a second drain yields nothing.
        let redrained = handle.drain_tx(64);
        assert!(redrained.is_empty(), "no double-delivery after flush");
    }
}