atpmcp 0.15.0

AT Protocol MCP server (Model Context Protocol 2026-07-28)
//! Progress notifications for long transfers.
//!
//! A client opts in by putting a `progressToken` in a request's `_meta`; the
//! server may then report progress against that token while the request runs.
//! Blob transfer is the first operation in this server where that means
//! anything.
//!
//! Three rules the specification imposes, each of which is easy to violate by
//! accident:
//!
//! - `progress` **MUST** increase with each notification. Report cumulative
//!   bytes, never a percentage recomputed against a total that can change.
//! - Both parties **SHOULD** rate-limit. A 16 MiB download over a fast link
//!   emits thousands of chunks; without a floor this becomes thousands of
//!   lines on the same stream the response has to travel.
//! - Notifications **MUST** stop after completion, which here is structural:
//!   the emitter is owned by the handler and dropped when it returns.

use std::time::{Duration, Instant};

use serde_json::Value;
use tokio::sync::mpsc;

use crate::proto::JsonRpcNotification;
use crate::proto::writer::Outgoing;

/// Minimum wall-clock gap between two notifications for one request.
const MIN_INTERVAL: Duration = Duration::from_millis(250);

/// Minimum fraction of the total that must elapse between notifications.
const MIN_FRACTION: f64 = 0.01;

/// Emits `notifications/progress` for one request, with rate limiting.
#[derive(Debug)]
pub struct Emitter {
    token: Value,
    out: mpsc::Sender<Outgoing>,
    total: Option<u64>,
    last_at: Instant,
    last_value: u64,
    started: bool,
}

impl Emitter {
    /// Build an emitter for a request that opted into progress.
    ///
    /// Returns `None` when the client sent no `progressToken`, so a caller can
    /// hold an `Option<Emitter>` and let the absence of a token disable
    /// reporting rather than branching at every call site.
    #[must_use]
    pub fn new(token: Option<Value>, out: mpsc::Sender<Outgoing>) -> Option<Self> {
        token.map(|token| Self {
            token,
            out,
            total: None,
            // Positioned so the first `report` always passes the interval
            // check: the opening notification should not be swallowed.
            last_at: Instant::now() - MIN_INTERVAL,
            last_value: 0,
            started: false,
        })
    }

    /// Record the expected total, when one is known.
    ///
    /// For a download this is `Content-Length`, which is attacker-controlled
    /// input from a host named by a third-party DID document. It bounds
    /// nothing; it only makes the notification more legible.
    pub fn set_total(&mut self, total: Option<u64>) {
        self.total = total;
    }

    /// Report cumulative progress, subject to rate limiting.
    ///
    /// `current` must not go backwards; a non-increasing value is dropped
    /// rather than emitted, since the specification requires monotonicity.
    pub fn report(&mut self, current: u64, message: &str) {
        if self.started && current <= self.last_value {
            return;
        }

        let now = Instant::now();
        if self.started && now.duration_since(self.last_at) < MIN_INTERVAL {
            return;
        }

        if self.started
            && let Some(total) = self.total
            && total > 0
        {
            let moved = (current - self.last_value) as f64 / total as f64;
            if moved < MIN_FRACTION && current < total {
                return;
            }
        }

        self.last_at = now;
        self.last_value = current;
        self.started = true;

        let mut params = serde_json::Map::new();
        params.insert("progressToken".to_string(), self.token.clone());
        params.insert("progress".to_string(), Value::Number(current.into()));
        if let Some(total) = self.total {
            params.insert("total".to_string(), Value::Number(total.into()));
        }
        params.insert("message".to_string(), Value::String(message.to_string()));

        // Deliberately lossy. Progress is advisory, and dropping a tick when
        // the outbound queue is full is always better than stalling the
        // transfer that produces it.
        let _ = self
            .out
            .try_send(Outgoing::notification(JsonRpcNotification::new(
                "notifications/progress",
                Value::Object(params),
            )));
    }

    /// Report the final value, bypassing the rate limit.
    pub fn finish(&mut self, current: u64, message: &str) {
        self.last_at = Instant::now() - MIN_INTERVAL;
        if current > self.last_value || !self.started {
            self.last_value = current.saturating_sub(1);
            self.report(current, message);
        }
    }
}

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

    fn drain(rx: &mut mpsc::Receiver<Outgoing>) -> Vec<Value> {
        let mut out = Vec::new();
        while let Ok(message) = rx.try_recv() {
            if let Outgoing::Notification(notification) = message {
                out.push(notification.params.clone().unwrap());
            }
        }
        out
    }

    #[tokio::test]
    async fn no_token_means_no_emitter() {
        let (tx, _rx) = mpsc::channel(8);
        assert!(Emitter::new(None, tx).is_none());
    }

    #[tokio::test]
    async fn first_report_is_always_emitted() {
        let (tx, mut rx) = mpsc::channel(8);
        let mut emitter = Emitter::new(Some(serde_json::json!("t")), tx).unwrap();
        emitter.report(10, "starting");
        let sent = drain(&mut rx);
        assert_eq!(sent.len(), 1);
        assert_eq!(sent[0]["progressToken"], "t");
        assert_eq!(sent[0]["progress"], 10);
        assert!(sent[0].get("total").is_none());
    }

    #[tokio::test]
    async fn rate_limit_suppresses_a_rapid_second_report() {
        let (tx, mut rx) = mpsc::channel(8);
        let mut emitter = Emitter::new(Some(serde_json::json!(1)), tx).unwrap();
        emitter.report(10, "a");
        emitter.report(20, "b");
        assert_eq!(drain(&mut rx).len(), 1);
    }

    #[tokio::test]
    async fn non_increasing_progress_is_dropped() {
        let (tx, mut rx) = mpsc::channel(8);
        let mut emitter = Emitter::new(Some(serde_json::json!(1)), tx).unwrap();
        emitter.report(100, "a");
        drain(&mut rx);
        emitter.last_at = Instant::now() - Duration::from_secs(1);
        emitter.report(100, "same");
        emitter.report(50, "backwards");
        assert!(drain(&mut rx).is_empty());
    }

    #[tokio::test]
    async fn progress_is_monotonic_across_a_transfer() {
        let (tx, mut rx) = mpsc::channel(64);
        let mut emitter = Emitter::new(Some(serde_json::json!(1)), tx).unwrap();
        emitter.set_total(Some(1000));
        for step in 1..=10u64 {
            emitter.last_at = Instant::now() - Duration::from_secs(1);
            emitter.report(step * 100, "chunk");
        }
        emitter.finish(1000, "done");

        let values: Vec<u64> = drain(&mut rx)
            .iter()
            .map(|params| params["progress"].as_u64().unwrap())
            .collect();
        assert!(values.len() >= 2);
        assert!(
            values.windows(2).all(|pair| pair[1] > pair[0]),
            "progress must strictly increase: {values:?}"
        );
        assert_eq!(*values.last().unwrap(), 1000);
    }

    #[tokio::test]
    async fn total_is_included_when_known() {
        let (tx, mut rx) = mpsc::channel(8);
        let mut emitter = Emitter::new(Some(serde_json::json!(1)), tx).unwrap();
        emitter.set_total(Some(2048));
        emitter.report(1024, "half");
        let sent = drain(&mut rx);
        assert_eq!(sent[0]["total"], 2048);
    }
}