atpmcp 0.15.0

AT Protocol MCP server (Model Context Protocol 2026-07-28)
//! The single task that owns stdout.
//!
//! Everything this process emits goes through one task fed by one channel.
//! That is not tidiness; it is how two transport requirements stop being
//! conventions and become properties of the code:
//!
//! - *"The server MUST NOT write anything to its stdout that is not a valid
//!   MCP message."* Nothing else holds the handle. The crate also denies
//!   `clippy::print_stdout`, so a stray `println!` is a compile error rather
//!   than a corrupted stream a user discovers at runtime.
//! - *"Messages are delimited by newlines, and MUST NOT contain embedded
//!   newlines."* Compact `serde_json` escapes newlines inside strings, so a
//!   serialized message is always one line. Do not introduce a pretty-printer.
//!
//! Messages are written and flushed one at a time. A line-oriented protocol
//! where the client blocks on a response cannot tolerate a buffered writer.

use tokio::io::{AsyncWrite, AsyncWriteExt};
use tokio::sync::mpsc;

use crate::proto::{JsonRpcNotification, JsonRpcResponse};

/// Anything the writer task can emit.
#[derive(Debug)]
pub enum Outgoing {
    /// A response to a client request.
    Response(Box<JsonRpcResponse>),
    /// A server-to-client notification.
    Notification(Box<JsonRpcNotification>),
}

impl Outgoing {
    /// Wrap a response.
    #[must_use]
    pub fn response(response: JsonRpcResponse) -> Self {
        Self::Response(Box::new(response))
    }

    /// Wrap a notification.
    #[must_use]
    pub fn notification(notification: JsonRpcNotification) -> Self {
        Self::Notification(Box::new(notification))
    }

    /// Serialize to the single line that goes on the wire.
    fn to_line(&self) -> Result<String, serde_json::Error> {
        match self {
            Self::Response(response) => serde_json::to_string(response),
            Self::Notification(notification) => serde_json::to_string(notification),
        }
    }
}

/// Capacity of the outbound channel.
///
/// Bounded on purpose. An unbounded channel lets a runaway progress emitter
/// grow memory without limit; a bounded one turns that into backpressure on
/// the handler producing it.
pub const CHANNEL_CAPACITY: usize = 1024;

/// Drain `rx` onto `writer` until the channel closes.
///
/// Returns when every sender has been dropped and the queue is empty, which is
/// what makes dropping the last sender a clean shutdown signal.
pub async fn run<W>(mut writer: W, mut rx: mpsc::Receiver<Outgoing>)
where
    W: AsyncWrite + Unpin,
{
    while let Some(message) = rx.recv().await {
        let line = match message.to_line() {
            Ok(line) => line,
            Err(error) => {
                // Serializing our own message failed. Nothing useful can be
                // written for this one, but the stream is still intact.
                tracing::error!(error = ?error, "Failed to serialize outgoing message.");
                continue;
            }
        };

        debug_assert!(
            !line.contains('\n'),
            "serialized message contains a raw newline"
        );

        if let Err(error) = writer.write_all(line.as_bytes()).await {
            tracing::error!(error = ?error, "Failed to write to stdout.");
            return;
        }
        if let Err(error) = writer.write_all(b"\n").await {
            tracing::error!(error = ?error, "Failed to write message delimiter.");
            return;
        }
        if let Err(error) = writer.flush().await {
            tracing::error!(error = ?error, "Failed to flush stdout.");
            return;
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::proto::JsonRpcResponse;

    #[tokio::test]
    async fn writes_one_line_per_message() {
        let (tx, rx) = mpsc::channel(8);
        let mut buffer = Vec::new();

        tx.send(Outgoing::response(JsonRpcResponse::success(
            serde_json::json!(1),
            serde_json::json!({ "resultType": "complete" }),
        )))
        .await
        .unwrap();
        tx.send(Outgoing::notification(JsonRpcNotification::new(
            "notifications/progress",
            serde_json::json!({ "progressToken": "t", "progress": 1 }),
        )))
        .await
        .unwrap();
        drop(tx);

        run(&mut buffer, rx).await;

        let text = String::from_utf8(buffer).unwrap();
        let lines: Vec<&str> = text.lines().collect();
        assert_eq!(lines.len(), 2);
        assert!(lines[0].contains("\"id\":1"));
        assert!(lines[1].contains("notifications/progress"));
    }

    #[tokio::test]
    async fn embedded_newlines_are_escaped_not_emitted() {
        let (tx, rx) = mpsc::channel(8);
        let mut buffer = Vec::new();

        tx.send(Outgoing::response(JsonRpcResponse::success(
            serde_json::json!(1),
            serde_json::json!({ "text": "first\nsecond\nthird" }),
        )))
        .await
        .unwrap();
        drop(tx);

        run(&mut buffer, rx).await;

        let text = String::from_utf8(buffer).unwrap();
        // One trailing delimiter, and nothing else.
        assert_eq!(text.matches('\n').count(), 1);
        assert!(text.contains("first\\nsecond\\nthird"));
    }

    #[tokio::test]
    async fn returns_when_all_senders_drop() {
        let (tx, rx) = mpsc::channel::<Outgoing>(1);
        drop(tx);
        // Would hang if the writer did not treat a closed channel as an exit.
        tokio::time::timeout(std::time::Duration::from_secs(1), run(Vec::new(), rx))
            .await
            .expect("writer exits on channel close");
    }
}