Skip to main content

lean_ctx/
mcp_stdio.rs

1use std::{
2    future::Future,
3    marker::PhantomData,
4    sync::{Arc, Mutex},
5};
6
7use futures::{SinkExt, StreamExt};
8use rmcp::{
9    service::{RoleServer, RxJsonRpcMessage, ServiceRole, TxJsonRpcMessage},
10    transport::Transport,
11};
12use serde::{Serialize, de::DeserializeOwned};
13use thiserror::Error;
14use tokio::{
15    io::{AsyncRead, AsyncWrite},
16    sync::Mutex as AsyncMutex,
17};
18use tokio_util::{
19    bytes::{Buf, BufMut, BytesMut},
20    codec::{Decoder, Encoder, FramedRead, FramedWrite},
21};
22
23#[derive(Clone, Copy, Debug, Eq, PartialEq)]
24enum WireProtocol {
25    JsonLine,
26    ContentLength,
27}
28
29#[derive(Debug, Clone)]
30struct SharedProtocol(Arc<Mutex<Option<WireProtocol>>>);
31
32impl SharedProtocol {
33    fn new() -> Self {
34        Self(Arc::new(Mutex::new(None)))
35    }
36
37    fn get(&self) -> Option<WireProtocol> {
38        *self
39            .0
40            .lock()
41            .unwrap_or_else(std::sync::PoisonError::into_inner)
42    }
43
44    fn set_if_unset(&self, protocol: WireProtocol) {
45        let mut guard = self
46            .0
47            .lock()
48            .unwrap_or_else(std::sync::PoisonError::into_inner);
49        if guard.is_none() {
50            *guard = Some(protocol);
51        }
52    }
53}
54
55pub type TransportWriter<Role, W> =
56    FramedWrite<W, HybridJsonRpcMessageCodec<TxJsonRpcMessage<Role>>>;
57
58pub struct HybridStdioTransport<Role: ServiceRole, R: AsyncRead, W: AsyncWrite> {
59    read: FramedRead<R, HybridJsonRpcMessageCodec<RxJsonRpcMessage<Role>>>,
60    write: Arc<AsyncMutex<Option<TransportWriter<Role, W>>>>,
61}
62
63impl<Role: ServiceRole, R, W> HybridStdioTransport<Role, R, W>
64where
65    R: Send + AsyncRead + Unpin,
66    W: Send + AsyncWrite + Unpin + 'static,
67{
68    pub fn new(read: R, write: W) -> Self {
69        let protocol = SharedProtocol::new();
70        let read = FramedRead::new(
71            read,
72            HybridJsonRpcMessageCodec::<RxJsonRpcMessage<Role>>::new(protocol.clone()),
73        );
74        let write = Arc::new(AsyncMutex::new(Some(FramedWrite::new(
75            write,
76            HybridJsonRpcMessageCodec::<TxJsonRpcMessage<Role>>::new(protocol),
77        ))));
78        Self { read, write }
79    }
80}
81
82impl<R, W> HybridStdioTransport<RoleServer, R, W>
83where
84    R: Send + AsyncRead + Unpin,
85    W: Send + AsyncWrite + Unpin + 'static,
86{
87    pub fn new_server(read: R, write: W) -> Self {
88        Self::new(read, write)
89    }
90}
91
92impl<Role: ServiceRole, R, W> Transport<Role> for HybridStdioTransport<Role, R, W>
93where
94    R: Send + AsyncRead + Unpin,
95    W: Send + AsyncWrite + Unpin + 'static,
96{
97    type Error = std::io::Error;
98
99    fn send(
100        &mut self,
101        item: TxJsonRpcMessage<Role>,
102    ) -> impl Future<Output = Result<(), Self::Error>> + Send + 'static {
103        let lock = self.write.clone();
104        async move {
105            let mut write = lock.lock().await;
106            if let Some(ref mut write) = *write {
107                write.send(item).await.map_err(Into::into)
108            } else {
109                Err(std::io::Error::new(
110                    std::io::ErrorKind::NotConnected,
111                    "Transport is closed",
112                ))
113            }
114        }
115    }
116
117    fn receive(&mut self) -> impl Future<Output = Option<RxJsonRpcMessage<Role>>> + Send {
118        let next = self.read.next();
119        async {
120            next.await.and_then(|result| {
121                result
122                    .inspect_err(|error| {
123                        tracing::error!("Error reading from stream: {}", error);
124                    })
125                    .ok()
126            })
127        }
128    }
129
130    async fn close(&mut self) -> Result<(), Self::Error> {
131        let mut write = self.write.lock().await;
132        drop(write.take());
133        Ok(())
134    }
135}
136
137#[derive(Debug, Clone)]
138pub struct HybridJsonRpcMessageCodec<T> {
139    _marker: PhantomData<fn() -> T>,
140    next_index: usize,
141    max_length: usize,
142    is_discarding: bool,
143    protocol: SharedProtocol,
144}
145
146impl<T> HybridJsonRpcMessageCodec<T> {
147    fn new(protocol: SharedProtocol) -> Self {
148        Self {
149            _marker: PhantomData,
150            next_index: 0,
151            max_length: 32 * 1024 * 1024, // 32 MiB — prevents OOM from oversized messages
152            is_discarding: false,
153            protocol,
154        }
155    }
156}
157
158fn without_carriage_return(s: &[u8]) -> &[u8] {
159    if let Some(&b'\r') = s.last() {
160        &s[..s.len() - 1]
161    } else {
162        s
163    }
164}
165
166fn is_standard_method(method: &str) -> bool {
167    matches!(
168        method,
169        "initialize"
170            | "ping"
171            | "prompts/get"
172            | "prompts/list"
173            | "resources/list"
174            | "resources/read"
175            | "resources/subscribe"
176            | "resources/unsubscribe"
177            | "resources/templates/list"
178            | "tools/call"
179            | "tools/list"
180            | "completion/complete"
181            | "logging/setLevel"
182            | "roots/list"
183            | "sampling/createMessage"
184    ) || is_standard_notification(method)
185}
186
187fn is_standard_notification(method: &str) -> bool {
188    matches!(
189        method,
190        "notifications/cancelled"
191            | "notifications/initialized"
192            | "notifications/message"
193            | "notifications/progress"
194            | "notifications/prompts/list_changed"
195            | "notifications/resources/list_changed"
196            | "notifications/resources/updated"
197            | "notifications/roots/list_changed"
198            | "notifications/tools/list_changed"
199    )
200}
201
202fn should_ignore_notification(json_value: &serde_json::Value, method: &str) -> bool {
203    let is_notification = json_value.get("id").is_none();
204    if is_notification && !is_standard_method(method) {
205        tracing::trace!(
206            "Ignoring non-MCP notification '{}' for compatibility",
207            method
208        );
209        return true;
210    }
211
212    matches!(
213        (
214            method.starts_with("notifications/"),
215            is_standard_notification(method)
216        ),
217        (true, false)
218    )
219}
220
221fn try_parse_with_compatibility<T: DeserializeOwned>(
222    payload: &[u8],
223    context: &str,
224) -> Result<Option<T>, HybridCodecError> {
225    if let Ok(line_str) = std::str::from_utf8(payload) {
226        match serde_json::from_slice(payload) {
227            Ok(item) => Ok(Some(item)),
228            Err(error) => {
229                if let Ok(json_value) = serde_json::from_str::<serde_json::Value>(line_str)
230                    && let Some(method) =
231                        json_value.get("method").and_then(serde_json::Value::as_str)
232                    && should_ignore_notification(&json_value, method)
233                {
234                    return Ok(None);
235                }
236
237                tracing::debug!(
238                    "Failed to parse message {}: {} | Error: {}",
239                    context,
240                    line_str,
241                    error
242                );
243                Err(HybridCodecError::Serde(error))
244            }
245        }
246    } else {
247        serde_json::from_slice(payload)
248            .map(Some)
249            .map_err(HybridCodecError::Serde)
250    }
251}
252
253#[derive(Debug, Error)]
254pub enum HybridCodecError {
255    #[error("max line length exceeded")]
256    MaxLineLengthExceeded,
257    #[error("missing Content-Length header")]
258    MissingContentLength,
259    #[error("invalid Content-Length value: {0}")]
260    InvalidContentLength(String),
261    #[error("invalid header frame: {0}")]
262    InvalidHeaderFrame(String),
263    #[error("serde error {0}")]
264    Serde(#[from] serde_json::Error),
265    #[error("io error {0}")]
266    Io(#[from] std::io::Error),
267}
268
269impl From<HybridCodecError> for std::io::Error {
270    fn from(value: HybridCodecError) -> Self {
271        match value {
272            HybridCodecError::MaxLineLengthExceeded
273            | HybridCodecError::MissingContentLength
274            | HybridCodecError::InvalidContentLength(_)
275            | HybridCodecError::InvalidHeaderFrame(_) => {
276                std::io::Error::new(std::io::ErrorKind::InvalidData, value)
277            }
278            HybridCodecError::Serde(error) => error.into(),
279            HybridCodecError::Io(error) => error,
280        }
281    }
282}
283
284fn looks_like_content_length_frame(buf: &BytesMut) -> bool {
285    let prefix = &buf[..buf.len().min(32)];
286    prefix
287        .windows(b"content-length".len())
288        .next()
289        .is_some_and(|candidate| candidate.eq_ignore_ascii_case(b"content-length"))
290}
291
292fn find_header_terminator(buf: &BytesMut) -> Option<(usize, usize)> {
293    if let Some(index) = buf.windows(4).position(|window| window == b"\r\n\r\n") {
294        return Some((index, 4));
295    }
296    buf.windows(2)
297        .position(|window| window == b"\n\n")
298        .map(|index| (index, 2))
299}
300
301fn parse_content_length(header: &str) -> Result<usize, HybridCodecError> {
302    for raw_line in header.lines() {
303        let line = raw_line.trim_end_matches('\r');
304        let Some((name, value)) = line.split_once(':') else {
305            continue;
306        };
307        if name.trim().eq_ignore_ascii_case("content-length") {
308            return value
309                .trim()
310                .parse::<usize>()
311                .map_err(|_| HybridCodecError::InvalidContentLength(value.trim().to_string()));
312        }
313    }
314
315    Err(HybridCodecError::MissingContentLength)
316}
317
318impl<T: DeserializeOwned> HybridJsonRpcMessageCodec<T> {
319    fn decode_content_length(&mut self, buf: &mut BytesMut) -> Result<Option<T>, HybridCodecError> {
320        // Loop so a skipped (malformed) frame body resyncs onto the next framed
321        // message already buffered, instead of stalling until more bytes arrive.
322        loop {
323            let Some((header_end, delimiter_len)) = find_header_terminator(buf) else {
324                return Ok(None);
325            };
326
327            let header = std::str::from_utf8(&buf[..header_end])
328                .map_err(|error| HybridCodecError::InvalidHeaderFrame(error.to_string()))?;
329            let content_length = parse_content_length(header)?;
330            if content_length > self.max_length {
331                return Err(HybridCodecError::MaxLineLengthExceeded);
332            }
333            let body_start = header_end + delimiter_len;
334            let frame_len = body_start
335                .checked_add(content_length)
336                .ok_or(HybridCodecError::MaxLineLengthExceeded)?;
337            if buf.len() < frame_len {
338                return Ok(None);
339            }
340
341            let frame = buf.split_to(frame_len);
342            let payload = &frame[body_start..];
343            self.protocol.set_if_unset(WireProtocol::ContentLength);
344
345            match try_parse_with_compatibility(payload, "decode_content_length") {
346                Ok(Some(item)) => return Ok(Some(item)),
347                // An ignored notification — fall through and scan the next frame.
348                Ok(None) => {}
349                // Skip a malformed body instead of fusing the transport (see
350                // `decode_json_line` / #453). The Content-Length framing stayed
351                // intact, so the next frame in the buffer is still recoverable.
352                Err(err) => {
353                    tracing::warn!("skipping malformed Content-Length frame: {err}");
354                }
355            }
356        }
357    }
358
359    fn decode_json_line(&mut self, buf: &mut BytesMut) -> Result<Option<T>, HybridCodecError> {
360        loop {
361            let read_to = std::cmp::min(self.max_length.saturating_add(1), buf.len());
362            let newline_offset = buf[self.next_index..read_to]
363                .iter()
364                .position(|byte| *byte == b'\n');
365
366            match (self.is_discarding, newline_offset) {
367                (true, Some(offset)) => {
368                    buf.advance(offset + self.next_index + 1);
369                    self.is_discarding = false;
370                    self.next_index = 0;
371                }
372                (true, None) => {
373                    buf.advance(read_to);
374                    self.next_index = 0;
375                    if buf.is_empty() {
376                        return Ok(None);
377                    }
378                }
379                (false, Some(offset)) => {
380                    let newline_index = offset + self.next_index;
381                    self.next_index = 0;
382                    let line = buf.split_to(newline_index + 1);
383                    let line = &line[..line.len() - 1];
384                    let payload = without_carriage_return(line);
385                    self.protocol.set_if_unset(WireProtocol::JsonLine);
386
387                    match try_parse_with_compatibility(payload, "decode_json_line") {
388                        Ok(Some(item)) => return Ok(Some(item)),
389                        // An ignored notification — keep scanning for a real frame.
390                        Ok(None) => {}
391                        // A single malformed line must NOT tear down the transport.
392                        // Returning Err here makes `FramedRead` fuse the stream
393                        // (`has_errored`), so the next poll yields `None`; rmcp then
394                        // exits with `QuitReason::Closed`, the agent respawns us, and
395                        // the fresh process pays another index build — the respawn /
396                        // idle-CPU churn behind #453. The bad line is already consumed
397                        // (`split_to` above), so we just skip it and resync on the
398                        // next newline-delimited frame.
399                        Err(err) => {
400                            tracing::warn!("skipping malformed JSON-RPC line: {err}");
401                        }
402                    }
403                }
404                (false, None) if buf.len() > self.max_length => {
405                    self.is_discarding = true;
406                    return Err(HybridCodecError::MaxLineLengthExceeded);
407                }
408                (false, None) => {
409                    self.next_index = read_to;
410                    return Ok(None);
411                }
412            }
413        }
414    }
415}
416
417impl<T: DeserializeOwned> Decoder for HybridJsonRpcMessageCodec<T> {
418    type Item = T;
419    type Error = HybridCodecError;
420
421    fn decode(&mut self, buf: &mut BytesMut) -> Result<Option<T>, HybridCodecError> {
422        match self.protocol.get() {
423            Some(WireProtocol::ContentLength) => self.decode_content_length(buf),
424            Some(WireProtocol::JsonLine) => self.decode_json_line(buf),
425            None => {
426                if looks_like_content_length_frame(buf) {
427                    self.decode_content_length(buf)
428                } else {
429                    self.decode_json_line(buf)
430                }
431            }
432        }
433    }
434
435    fn decode_eof(&mut self, buf: &mut BytesMut) -> Result<Option<T>, HybridCodecError> {
436        match self.protocol.get() {
437            Some(WireProtocol::ContentLength) if !buf.is_empty() => self.decode_content_length(buf),
438            _ => Ok(if let Some(frame) = self.decode(buf)? {
439                Some(frame)
440            } else {
441                self.next_index = 0;
442                if buf.is_empty() || buf == &b"\r"[..] {
443                    None
444                } else {
445                    let line = buf.split_to(buf.len());
446                    let payload = without_carriage_return(&line);
447                    // At true stream end a malformed trailing frame is discarded
448                    // (clean close) rather than surfaced as a transport error.
449                    match try_parse_with_compatibility(payload, "decode_eof") {
450                        Ok(item) => item,
451                        Err(err) => {
452                            tracing::warn!("discarding malformed trailing frame at EOF: {err}");
453                            None
454                        }
455                    }
456                }
457            }),
458        }
459    }
460}
461
462impl<T: Serialize> Encoder<T> for HybridJsonRpcMessageCodec<T> {
463    type Error = HybridCodecError;
464
465    fn encode(&mut self, item: T, buf: &mut BytesMut) -> Result<(), HybridCodecError> {
466        let payload = serde_json::to_vec(&item)?;
467
468        match self.protocol.get().unwrap_or(WireProtocol::ContentLength) {
469            WireProtocol::ContentLength => {
470                buf.extend_from_slice(
471                    format!("Content-Length: {}\r\n\r\n", payload.len()).as_bytes(),
472                );
473                buf.extend_from_slice(&payload);
474            }
475            WireProtocol::JsonLine => {
476                buf.extend_from_slice(&payload);
477                buf.put_u8(b'\n');
478            }
479        }
480
481        Ok(())
482    }
483}
484
485#[cfg(test)]
486mod tests {
487    use super::*;
488
489    use tokio_util::bytes::BytesMut;
490
491    fn sample_message() -> serde_json::Value {
492        serde_json::json!({
493            "jsonrpc": "2.0",
494            "id": 1,
495            "method": "initialize",
496            "params": {
497                "protocolVersion": "2024-11-05",
498                "capabilities": {},
499                "clientInfo": {
500                    "name": "probe",
501                    "version": "0.0.0"
502                }
503            }
504        })
505    }
506
507    #[test]
508    fn decodes_json_line_and_marks_protocol() {
509        let protocol = SharedProtocol::new();
510        let mut codec = HybridJsonRpcMessageCodec::<serde_json::Value>::new(protocol.clone());
511        let payload = serde_json::to_vec(&sample_message()).unwrap();
512        let mut buf = BytesMut::from(&payload[..]);
513        buf.put_u8(b'\n');
514
515        let item = codec.decode(&mut buf).unwrap();
516        assert!(item.is_some());
517        assert_eq!(protocol.get(), Some(WireProtocol::JsonLine));
518    }
519
520    #[test]
521    fn decodes_content_length_and_marks_protocol() {
522        let protocol = SharedProtocol::new();
523        let mut codec = HybridJsonRpcMessageCodec::<serde_json::Value>::new(protocol.clone());
524        let payload = serde_json::to_vec(&sample_message()).unwrap();
525        let mut frame = BytesMut::new();
526        frame.extend_from_slice(format!("Content-Length: {}\r\n\r\n", payload.len()).as_bytes());
527        frame.extend_from_slice(&payload);
528
529        let item = codec.decode(&mut frame).unwrap();
530        assert!(item.is_some());
531        assert_eq!(protocol.get(), Some(WireProtocol::ContentLength));
532    }
533
534    #[test]
535    fn encodes_using_content_length_when_protocol_is_detected() {
536        let protocol = SharedProtocol::new();
537        protocol.set_if_unset(WireProtocol::ContentLength);
538        let mut codec = HybridJsonRpcMessageCodec::<serde_json::Value>::new(protocol);
539        let mut buf = BytesMut::new();
540        codec
541            .encode(
542                serde_json::json!({"jsonrpc":"2.0","id":1,"result":{"ok":true}}),
543                &mut buf,
544            )
545            .unwrap();
546
547        assert!(
548            std::str::from_utf8(&buf)
549                .unwrap()
550                .starts_with("Content-Length: ")
551        );
552    }
553
554    #[test]
555    fn decode_skips_malformed_json_line_and_recovers() {
556        // A bad line followed by a valid frame: the codec must skip the bad one
557        // and return the valid frame in the same decode pass — never an Err that
558        // would fuse the transport and trigger an MCP-server respawn (#453).
559        let protocol = SharedProtocol::new();
560        let mut codec = HybridJsonRpcMessageCodec::<serde_json::Value>::new(protocol);
561        let good = serde_json::to_vec(&sample_message()).unwrap();
562        let mut buf = BytesMut::new();
563        buf.extend_from_slice(b"{ this is : not valid json }\n");
564        buf.extend_from_slice(&good);
565        buf.put_u8(b'\n');
566
567        let item = codec
568            .decode(&mut buf)
569            .expect("a malformed line must not be a hard transport error");
570        assert!(item.is_some(), "valid frame after a bad line must decode");
571    }
572
573    #[test]
574    fn decode_malformed_json_line_alone_is_not_a_transport_error() {
575        // A lone malformed line yields Ok(None) (stream stays alive), not Err.
576        let protocol = SharedProtocol::new();
577        let mut codec = HybridJsonRpcMessageCodec::<serde_json::Value>::new(protocol);
578        let mut buf = BytesMut::from(&b"{ not valid json }\n"[..]);
579
580        let item = codec
581            .decode(&mut buf)
582            .expect("a malformed line must not be a hard transport error");
583        assert!(item.is_none());
584    }
585
586    #[test]
587    fn decode_skips_malformed_content_length_frame_and_recovers() {
588        // Same guarantee for the Content-Length wire protocol: a bad body is
589        // skipped and the next well-framed message is still delivered.
590        let protocol = SharedProtocol::new();
591        protocol.set_if_unset(WireProtocol::ContentLength);
592        let mut codec = HybridJsonRpcMessageCodec::<serde_json::Value>::new(protocol);
593
594        let bad_body = b"{ not json }";
595        let good_body = serde_json::to_vec(&sample_message()).unwrap();
596        let mut buf = BytesMut::new();
597        buf.extend_from_slice(format!("Content-Length: {}\r\n\r\n", bad_body.len()).as_bytes());
598        buf.extend_from_slice(bad_body);
599        buf.extend_from_slice(format!("Content-Length: {}\r\n\r\n", good_body.len()).as_bytes());
600        buf.extend_from_slice(&good_body);
601
602        let item = codec
603            .decode(&mut buf)
604            .expect("a malformed CL frame must not be a hard transport error");
605        assert!(item.is_some(), "valid CL frame after a bad one must decode");
606    }
607}