1use std::{
3 future::Future,
4 marker::PhantomData,
5 sync::{Arc, Mutex},
6};
7
8use futures::{SinkExt, StreamExt};
9use rmcp::{
10 service::{RoleServer, RxJsonRpcMessage, ServiceRole, TxJsonRpcMessage},
11 transport::Transport,
12};
13use serde::{Serialize, de::DeserializeOwned};
14use thiserror::Error;
15use tokio::{
16 io::{AsyncRead, AsyncWrite},
17 sync::Mutex as AsyncMutex,
18};
19use tokio_util::{
20 bytes::{Buf, BufMut, BytesMut},
21 codec::{Decoder, Encoder, FramedRead, FramedWrite},
22};
23
24#[derive(Clone, Copy, Debug, Eq, PartialEq)]
25enum WireProtocol {
26 JsonLine,
27 ContentLength,
28}
29
30#[derive(Debug, Clone)]
31pub struct SharedProtocol(Arc<Mutex<Option<WireProtocol>>>);
32
33impl SharedProtocol {
34 fn new() -> Self {
35 Self(Arc::new(Mutex::new(None)))
36 }
37
38 fn get(&self) -> Option<WireProtocol> {
39 *self
40 .0
41 .lock()
42 .unwrap_or_else(std::sync::PoisonError::into_inner)
43 }
44
45 fn set_if_unset(&self, protocol: WireProtocol) {
46 let mut guard = self
47 .0
48 .lock()
49 .unwrap_or_else(std::sync::PoisonError::into_inner);
50 if guard.is_none() {
51 *guard = Some(protocol);
52 }
53 }
54}
55
56pub type TransportWriter<Role, W> =
57 FramedWrite<W, HybridJsonRpcMessageCodec<TxJsonRpcMessage<Role>>>;
58
59pub struct HybridStdioTransport<Role: ServiceRole, R: AsyncRead, W: AsyncWrite> {
60 read: FramedRead<R, HybridJsonRpcMessageCodec<RxJsonRpcMessage<Role>>>,
61 write: Arc<AsyncMutex<Option<TransportWriter<Role, W>>>>,
62 protocol: SharedProtocol,
63}
64
65impl<Role: ServiceRole, R, W> HybridStdioTransport<Role, R, W>
66where
67 R: Send + AsyncRead + Unpin,
68 W: Send + AsyncWrite + Unpin + 'static,
69{
70 pub fn new(read: R, write: W) -> Self {
71 let protocol = SharedProtocol::new();
72 let read = FramedRead::new(
73 read,
74 HybridJsonRpcMessageCodec::<RxJsonRpcMessage<Role>>::new(protocol.clone()),
75 );
76 let write = Arc::new(AsyncMutex::new(Some(FramedWrite::new(
77 write,
78 HybridJsonRpcMessageCodec::<TxJsonRpcMessage<Role>>::new(protocol.clone()),
79 ))));
80 Self {
81 read,
82 write,
83 protocol,
84 }
85 }
86
87 pub fn protocol(&self) -> SharedProtocol {
90 self.protocol.clone()
91 }
92}
93
94impl<R, W> HybridStdioTransport<RoleServer, R, W>
95where
96 R: Send + AsyncRead + Unpin,
97 W: Send + AsyncWrite + Unpin + 'static,
98{
99 pub fn new_server(read: R, write: W) -> Self {
100 Self::new(read, write)
101 }
102}
103
104impl<Role: ServiceRole, R, W> Transport<Role> for HybridStdioTransport<Role, R, W>
105where
106 R: Send + AsyncRead + Unpin,
107 W: Send + AsyncWrite + Unpin + 'static,
108{
109 type Error = std::io::Error;
110
111 fn send(
112 &mut self,
113 item: TxJsonRpcMessage<Role>,
114 ) -> impl Future<Output = Result<(), Self::Error>> + Send + 'static {
115 let lock = self.write.clone();
116 async move {
117 let mut write = lock.lock().await;
118 if let Some(ref mut write) = *write {
119 write.send(item).await.map_err(Into::into)
120 } else {
121 Err(std::io::Error::new(
122 std::io::ErrorKind::NotConnected,
123 "Transport is closed",
124 ))
125 }
126 }
127 }
128
129 fn receive(&mut self) -> impl Future<Output = Option<RxJsonRpcMessage<Role>>> + Send {
130 let next = self.read.next();
131 async {
132 next.await.and_then(|result| {
133 result
134 .inspect_err(|error| {
135 tracing::error!("Error reading from stream: {}", error);
136 })
137 .ok()
138 })
139 }
140 }
141
142 async fn close(&mut self) -> Result<(), Self::Error> {
143 let mut write = self.write.lock().await;
144 drop(write.take());
145 Ok(())
146 }
147}
148
149#[derive(Debug, Clone)]
150pub struct HybridJsonRpcMessageCodec<T> {
151 _marker: PhantomData<fn() -> T>,
152 next_index: usize,
153 max_length: usize,
154 is_discarding: bool,
155 protocol: SharedProtocol,
156}
157
158impl<T> HybridJsonRpcMessageCodec<T> {
159 fn new(protocol: SharedProtocol) -> Self {
160 Self {
161 _marker: PhantomData,
162 next_index: 0,
163 max_length: 32 * 1024 * 1024, is_discarding: false,
165 protocol,
166 }
167 }
168}
169
170fn without_carriage_return(s: &[u8]) -> &[u8] {
171 if let Some(&b'\r') = s.last() {
172 &s[..s.len() - 1]
173 } else {
174 s
175 }
176}
177
178fn is_standard_method(method: &str) -> bool {
179 matches!(
180 method,
181 "initialize"
182 | "ping"
183 | "prompts/get"
184 | "prompts/list"
185 | "resources/list"
186 | "resources/read"
187 | "resources/subscribe"
188 | "resources/unsubscribe"
189 | "resources/templates/list"
190 | "tools/call"
191 | "tools/list"
192 | "completion/complete"
193 | "logging/setLevel"
194 | "roots/list"
195 | "sampling/createMessage"
196 ) || is_standard_notification(method)
197}
198
199fn is_standard_notification(method: &str) -> bool {
200 matches!(
201 method,
202 "notifications/cancelled"
203 | "notifications/initialized"
204 | "notifications/message"
205 | "notifications/progress"
206 | "notifications/prompts/list_changed"
207 | "notifications/resources/list_changed"
208 | "notifications/resources/updated"
209 | "notifications/roots/list_changed"
210 | "notifications/tools/list_changed"
211 )
212}
213
214fn should_ignore_notification(json_value: &serde_json::Value, method: &str) -> bool {
215 let is_notification = json_value.get("id").is_none();
216 if is_notification && !is_standard_method(method) {
217 tracing::trace!(
218 "Ignoring non-MCP notification '{}' for compatibility",
219 method
220 );
221 return true;
222 }
223
224 matches!(
225 (
226 method.starts_with("notifications/"),
227 is_standard_notification(method)
228 ),
229 (true, false)
230 )
231}
232
233fn write_method_not_found(id: &serde_json::Value, method: &str, protocol: Option<WireProtocol>) {
237 let response = serde_json::json!({
238 "jsonrpc": "2.0",
239 "id": id,
240 "error": {
241 "code": -32601,
242 "message": format!("Method not found: {method}")
243 }
244 });
245 let body = serde_json::to_string(&response).unwrap_or_default();
246 let mut out = std::io::stdout().lock();
247 use std::io::Write;
248 let _ = if let Some(WireProtocol::ContentLength) = protocol {
249 write!(out, "Content-Length: {}\r\n\r\n{}", body.len(), body)
250 } else {
251 writeln!(out, "{body}")
252 };
253 let _ = std::io::Write::flush(&mut out);
254 tracing::debug!("Replied -32601 MethodNotFound for '{method}'");
255}
256
257pub fn write_method_not_found_pre_init(
271 id: &serde_json::Value,
272 method: &str,
273 protocol: &SharedProtocol,
274) {
275 let response = serde_json::json!({
276 "jsonrpc": "2.0",
277 "id": id,
278 "error": {
279 "code": -32601,
280 "message": concat!(
281 "Method not found. This server supports MCP protocol 2025-11-25 ",
282 "(legacy initialize handshake only)."
283 )
284 }
285 });
286 let body = serde_json::to_string(&response).unwrap_or_default();
287 let mut out = std::io::stdout().lock();
288 use std::io::Write;
289 let _ = if protocol.get() == Some(WireProtocol::ContentLength) {
290 write!(out, "Content-Length: {}\r\n\r\n{}", body.len(), body)
291 } else {
292 writeln!(out, "{body}")
293 };
294 let _ = std::io::Write::flush(&mut out);
295 tracing::debug!("Replied -32601 MethodNotFound for pre-init '{method}'");
296}
297
298fn try_parse_with_compatibility<T: DeserializeOwned>(
299 payload: &[u8],
300 context: &str,
301 protocol: Option<WireProtocol>,
302) -> Result<Option<T>, HybridCodecError> {
303 if let Ok(line_str) = std::str::from_utf8(payload) {
304 match serde_json::from_slice(payload) {
305 Ok(item) => Ok(Some(item)),
306 Err(error) => {
307 if let Ok(json_value) = serde_json::from_str::<serde_json::Value>(line_str)
308 && let Some(method) =
309 json_value.get("method").and_then(serde_json::Value::as_str)
310 {
311 if should_ignore_notification(&json_value, method) {
312 return Ok(None);
313 }
314 if let Some(id) = json_value.get("id") {
316 if !is_standard_method(method) {
317 write_method_not_found(id, method, protocol);
318 return Ok(None);
319 }
320 }
321 }
322
323 tracing::debug!(
324 "Failed to parse message {}: {} | Error: {}",
325 context,
326 line_str,
327 error
328 );
329 Err(HybridCodecError::Serde(error))
330 }
331 }
332 } else {
333 serde_json::from_slice(payload)
334 .map(Some)
335 .map_err(HybridCodecError::Serde)
336 }
337}
338
339#[derive(Debug, Error)]
340pub enum HybridCodecError {
341 #[error("max line length exceeded")]
342 MaxLineLengthExceeded,
343 #[error("missing Content-Length header")]
344 MissingContentLength,
345 #[error("invalid Content-Length value: {0}")]
346 InvalidContentLength(String),
347 #[error("invalid header frame: {0}")]
348 InvalidHeaderFrame(String),
349 #[error("serde error {0}")]
350 Serde(#[from] serde_json::Error),
351 #[error("io error {0}")]
352 Io(#[from] std::io::Error),
353}
354
355impl From<HybridCodecError> for std::io::Error {
356 fn from(value: HybridCodecError) -> Self {
357 match value {
358 HybridCodecError::MaxLineLengthExceeded
359 | HybridCodecError::MissingContentLength
360 | HybridCodecError::InvalidContentLength(_)
361 | HybridCodecError::InvalidHeaderFrame(_) => {
362 std::io::Error::new(std::io::ErrorKind::InvalidData, value)
363 }
364 HybridCodecError::Serde(error) => error.into(),
365 HybridCodecError::Io(error) => error,
366 }
367 }
368}
369
370fn looks_like_content_length_frame(buf: &BytesMut) -> bool {
371 let prefix = &buf[..buf.len().min(32)];
372 prefix
373 .windows(b"content-length".len())
374 .next()
375 .is_some_and(|candidate| candidate.eq_ignore_ascii_case(b"content-length"))
376}
377
378fn find_header_terminator(buf: &BytesMut) -> Option<(usize, usize)> {
379 if let Some(index) = buf.windows(4).position(|window| window == b"\r\n\r\n") {
380 return Some((index, 4));
381 }
382 buf.windows(2)
383 .position(|window| window == b"\n\n")
384 .map(|index| (index, 2))
385}
386
387fn parse_content_length(header: &str) -> Result<usize, HybridCodecError> {
388 for raw_line in header.lines() {
389 let line = raw_line.trim_end_matches('\r');
390 let Some((name, value)) = line.split_once(':') else {
391 continue;
392 };
393 if name.trim().eq_ignore_ascii_case("content-length") {
394 return value
395 .trim()
396 .parse::<usize>()
397 .map_err(|_| HybridCodecError::InvalidContentLength(value.trim().to_string()));
398 }
399 }
400
401 Err(HybridCodecError::MissingContentLength)
402}
403
404impl<T: DeserializeOwned> HybridJsonRpcMessageCodec<T> {
405 fn decode_content_length(&mut self, buf: &mut BytesMut) -> Result<Option<T>, HybridCodecError> {
406 loop {
409 let Some((header_end, delimiter_len)) = find_header_terminator(buf) else {
410 return Ok(None);
411 };
412
413 let header = std::str::from_utf8(&buf[..header_end])
414 .map_err(|error| HybridCodecError::InvalidHeaderFrame(error.to_string()))?;
415 let content_length = parse_content_length(header)?;
416 if content_length > self.max_length {
417 return Err(HybridCodecError::MaxLineLengthExceeded);
418 }
419 let body_start = header_end + delimiter_len;
420 let frame_len = body_start
421 .checked_add(content_length)
422 .ok_or(HybridCodecError::MaxLineLengthExceeded)?;
423 if buf.len() < frame_len {
424 return Ok(None);
425 }
426
427 let frame = buf.split_to(frame_len);
428 let payload = &frame[body_start..];
429 self.protocol.set_if_unset(WireProtocol::ContentLength);
430
431 match try_parse_with_compatibility(
432 payload,
433 "decode_content_length",
434 self.protocol.get(),
435 ) {
436 Ok(Some(item)) => return Ok(Some(item)),
437 Ok(None) => {}
439 Err(err) => {
443 tracing::warn!("skipping malformed Content-Length frame: {err}");
444 }
445 }
446 }
447 }
448
449 fn decode_json_line(&mut self, buf: &mut BytesMut) -> Result<Option<T>, HybridCodecError> {
450 loop {
451 let read_to = std::cmp::min(self.max_length.saturating_add(1), buf.len());
452 let newline_offset = buf[self.next_index..read_to]
453 .iter()
454 .position(|byte| *byte == b'\n');
455
456 match (self.is_discarding, newline_offset) {
457 (true, Some(offset)) => {
458 buf.advance(offset + self.next_index + 1);
459 self.is_discarding = false;
460 self.next_index = 0;
461 }
462 (true, None) => {
463 buf.advance(read_to);
464 self.next_index = 0;
465 if buf.is_empty() {
466 return Ok(None);
467 }
468 }
469 (false, Some(offset)) => {
470 let newline_index = offset + self.next_index;
471 self.next_index = 0;
472 let line = buf.split_to(newline_index + 1);
473 let line = &line[..line.len() - 1];
474 let payload = without_carriage_return(line);
475 self.protocol.set_if_unset(WireProtocol::JsonLine);
476
477 match try_parse_with_compatibility(
478 payload,
479 "decode_json_line",
480 self.protocol.get(),
481 ) {
482 Ok(Some(item)) => return Ok(Some(item)),
483 Ok(None) => {}
485 Err(err) => {
494 tracing::warn!("skipping malformed JSON-RPC line: {err}");
495 }
496 }
497 }
498 (false, None) if buf.len() > self.max_length => {
499 self.is_discarding = true;
500 return Err(HybridCodecError::MaxLineLengthExceeded);
501 }
502 (false, None) => {
503 self.next_index = read_to;
504 return Ok(None);
505 }
506 }
507 }
508 }
509}
510
511impl<T: DeserializeOwned> Decoder for HybridJsonRpcMessageCodec<T> {
512 type Item = T;
513 type Error = HybridCodecError;
514
515 fn decode(&mut self, buf: &mut BytesMut) -> Result<Option<T>, HybridCodecError> {
516 match self.protocol.get() {
517 Some(WireProtocol::ContentLength) => self.decode_content_length(buf),
518 Some(WireProtocol::JsonLine) => self.decode_json_line(buf),
519 None => {
520 if looks_like_content_length_frame(buf) {
521 self.decode_content_length(buf)
522 } else {
523 self.decode_json_line(buf)
524 }
525 }
526 }
527 }
528
529 fn decode_eof(&mut self, buf: &mut BytesMut) -> Result<Option<T>, HybridCodecError> {
530 match self.protocol.get() {
531 Some(WireProtocol::ContentLength) if !buf.is_empty() => self.decode_content_length(buf),
532 _ => Ok(if let Some(frame) = self.decode(buf)? {
533 Some(frame)
534 } else {
535 self.next_index = 0;
536 if buf.is_empty() || buf == &b"\r"[..] {
537 None
538 } else {
539 let line = buf.split_to(buf.len());
540 let payload = without_carriage_return(&line);
541 match try_parse_with_compatibility(payload, "decode_eof", self.protocol.get()) {
544 Ok(item) => item,
545 Err(err) => {
546 tracing::warn!("discarding malformed trailing frame at EOF: {err}");
547 None
548 }
549 }
550 }
551 }),
552 }
553 }
554}
555
556impl<T: Serialize> Encoder<T> for HybridJsonRpcMessageCodec<T> {
557 type Error = HybridCodecError;
558
559 fn encode(&mut self, item: T, buf: &mut BytesMut) -> Result<(), HybridCodecError> {
560 let payload = serde_json::to_vec(&item)?;
561
562 match self.protocol.get().unwrap_or(WireProtocol::ContentLength) {
563 WireProtocol::ContentLength => {
564 buf.extend_from_slice(
565 format!("Content-Length: {}\r\n\r\n", payload.len()).as_bytes(),
566 );
567 buf.extend_from_slice(&payload);
568 }
569 WireProtocol::JsonLine => {
570 buf.extend_from_slice(&payload);
571 buf.put_u8(b'\n');
572 }
573 }
574
575 Ok(())
576 }
577}
578
579#[cfg(test)]
580mod tests {
581 use super::*;
582
583 use tokio_util::bytes::BytesMut;
584
585 fn sample_message() -> serde_json::Value {
586 serde_json::json!({
587 "jsonrpc": "2.0",
588 "id": 1,
589 "method": "initialize",
590 "params": {
591 "protocolVersion": "2024-11-05",
592 "capabilities": {},
593 "clientInfo": {
594 "name": "probe",
595 "version": "0.0.0"
596 }
597 }
598 })
599 }
600
601 #[test]
602 fn decodes_json_line_and_marks_protocol() {
603 let protocol = SharedProtocol::new();
604 let mut codec = HybridJsonRpcMessageCodec::<serde_json::Value>::new(protocol.clone());
605 let payload = serde_json::to_vec(&sample_message()).unwrap();
606 let mut buf = BytesMut::from(&payload[..]);
607 buf.put_u8(b'\n');
608
609 let item = codec.decode(&mut buf).unwrap();
610 assert!(item.is_some());
611 assert_eq!(protocol.get(), Some(WireProtocol::JsonLine));
612 }
613
614 #[test]
615 fn decodes_content_length_and_marks_protocol() {
616 let protocol = SharedProtocol::new();
617 let mut codec = HybridJsonRpcMessageCodec::<serde_json::Value>::new(protocol.clone());
618 let payload = serde_json::to_vec(&sample_message()).unwrap();
619 let mut frame = BytesMut::new();
620 frame.extend_from_slice(format!("Content-Length: {}\r\n\r\n", payload.len()).as_bytes());
621 frame.extend_from_slice(&payload);
622
623 let item = codec.decode(&mut frame).unwrap();
624 assert!(item.is_some());
625 assert_eq!(protocol.get(), Some(WireProtocol::ContentLength));
626 }
627
628 #[test]
629 fn encodes_using_content_length_when_protocol_is_detected() {
630 let protocol = SharedProtocol::new();
631 protocol.set_if_unset(WireProtocol::ContentLength);
632 let mut codec = HybridJsonRpcMessageCodec::<serde_json::Value>::new(protocol);
633 let mut buf = BytesMut::new();
634 codec
635 .encode(
636 serde_json::json!({"jsonrpc":"2.0","id":1,"result":{"ok":true}}),
637 &mut buf,
638 )
639 .unwrap();
640
641 assert!(
642 std::str::from_utf8(&buf)
643 .unwrap()
644 .starts_with("Content-Length: ")
645 );
646 }
647
648 #[test]
649 fn decode_skips_malformed_json_line_and_recovers() {
650 let protocol = SharedProtocol::new();
654 let mut codec = HybridJsonRpcMessageCodec::<serde_json::Value>::new(protocol);
655 let good = serde_json::to_vec(&sample_message()).unwrap();
656 let mut buf = BytesMut::new();
657 buf.extend_from_slice(b"{ this is : not valid json }\n");
658 buf.extend_from_slice(&good);
659 buf.put_u8(b'\n');
660
661 let item = codec
662 .decode(&mut buf)
663 .expect("a malformed line must not be a hard transport error");
664 assert!(item.is_some(), "valid frame after a bad line must decode");
665 }
666
667 #[test]
668 fn decode_malformed_json_line_alone_is_not_a_transport_error() {
669 let protocol = SharedProtocol::new();
671 let mut codec = HybridJsonRpcMessageCodec::<serde_json::Value>::new(protocol);
672 let mut buf = BytesMut::from(&b"{ not valid json }\n"[..]);
673
674 let item = codec
675 .decode(&mut buf)
676 .expect("a malformed line must not be a hard transport error");
677 assert!(item.is_none());
678 }
679
680 #[test]
681 fn decode_skips_malformed_content_length_frame_and_recovers() {
682 let protocol = SharedProtocol::new();
685 protocol.set_if_unset(WireProtocol::ContentLength);
686 let mut codec = HybridJsonRpcMessageCodec::<serde_json::Value>::new(protocol);
687
688 let bad_body = b"{ not json }";
689 let good_body = serde_json::to_vec(&sample_message()).unwrap();
690 let mut buf = BytesMut::new();
691 buf.extend_from_slice(format!("Content-Length: {}\r\n\r\n", bad_body.len()).as_bytes());
692 buf.extend_from_slice(bad_body);
693 buf.extend_from_slice(format!("Content-Length: {}\r\n\r\n", good_body.len()).as_bytes());
694 buf.extend_from_slice(&good_body);
695
696 let item = codec
697 .decode(&mut buf)
698 .expect("a malformed CL frame must not be a hard transport error");
699 assert!(item.is_some(), "valid CL frame after a bad one must decode");
700 }
701}