atpmcp 0.15.0

AT Protocol MCP server (Model Context Protocol 2026-07-28)
//! `subscriptions/listen` — the long-lived notification stream.
//!
//! This server has nothing that changes. Its tool list is a compile-time
//! constant, its resource list is empty, and a blob addressed by its CID is
//! immutable by construction. So there is genuinely nothing to notify about.
//!
//! It is implemented anyway, because the specification requires every
//! implementation to support the base message patterns, and subscribe-and-
//! notify is one of the three. A client may open a stream regardless of what
//! the server declared, and the honest answer is an acknowledgment naming the
//! empty subset we honour — the specification tells clients to "check the
//! acknowledged filter against what it requested", which only works if we
//! answer.
//!
//! Answering it is also what forces the whole transport to be concurrent: a
//! request that never returns would deadlock a serial loop.
//!
//! # Teardown
//!
//! Two ways a subscription ends, and they are not symmetric:
//!
//! - **The client cancels it**, via `notifications/cancelled`. The general
//!   cancellation rule applies: do not send a response.
//! - **The server tears it down**, during shutdown. Cancellation requires the
//!   server to send `notifications/cancelled` for the subscription; the
//!   subscriptions page says it should also answer the original request with a
//!   completion result to signal a graceful end. These describe one event, and
//!   the two pages do not agree on which message carries it, so both are sent.
//!   A client expecting one ignores the other.

use std::collections::HashMap;
use std::sync::Arc;
use std::sync::Mutex;
use std::sync::atomic::{AtomicBool, Ordering};

use serde_json::Value;
use tokio_util::sync::CancellationToken;

use crate::proto::meta::KEY_SUBSCRIPTION_ID;
use crate::proto::{JsonRpcNotification, RequestKey};

/// One open subscription.
#[derive(Debug, Clone)]
pub struct Subscription {
    /// Fired to end the subscription.
    pub token: CancellationToken,
    /// Set before cancelling when the *client* asked for the end, which
    /// suppresses the graceful-closure response.
    pub client_cancelled: Arc<AtomicBool>,
}

/// Open subscriptions, keyed by the id of the `subscriptions/listen` request.
#[derive(Debug, Default)]
pub struct Registry {
    entries: Mutex<HashMap<RequestKey, Subscription>>,
}

impl Registry {
    /// An empty registry.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Open a subscription under `key`.
    pub fn register(&self, key: RequestKey) -> Subscription {
        let subscription = Subscription {
            token: CancellationToken::new(),
            client_cancelled: Arc::new(AtomicBool::new(false)),
        };
        self.lock().insert(key, subscription.clone());
        subscription
    }

    /// Remove a subscription without cancelling it.
    pub fn remove(&self, key: &RequestKey) {
        self.lock().remove(key);
    }

    /// End a subscription at the client's request.
    ///
    /// Returns whether one was open.
    pub fn cancel_by_client(&self, key: &RequestKey) -> bool {
        match self.lock().remove(key) {
            Some(subscription) => {
                subscription.client_cancelled.store(true, Ordering::SeqCst);
                subscription.token.cancel();
                true
            }
            None => false,
        }
    }

    /// End every subscription on the server's initiative, for shutdown.
    pub fn cancel_all(&self) {
        for (_, subscription) in self.lock().drain() {
            subscription.token.cancel();
        }
    }

    /// How many subscriptions are open.
    pub fn len(&self) -> usize {
        self.lock().len()
    }

    /// Whether none are open.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    fn lock(&self) -> std::sync::MutexGuard<'_, HashMap<RequestKey, Subscription>> {
        self.entries.lock().unwrap_or_else(|poisoned| {
            tracing::warn!("Subscription registry lock was poisoned; recovering.");
            poisoned.into_inner()
        })
    }
}

/// The notification filter this server agrees to honour.
///
/// The acknowledgment reflects the subset the server will actually deliver,
/// with unsupported types omitted. Nothing here changes, so the honoured
/// subset is empty — and saying so plainly is more useful to a client than
/// echoing a filter we will never satisfy.
#[must_use]
pub fn honoured_filter(_requested: Option<&Value>) -> Value {
    serde_json::json!({})
}

/// The acknowledgment that must precede any notification on a subscription.
#[must_use]
pub fn acknowledgement(key: &RequestKey, requested: Option<&Value>) -> JsonRpcNotification {
    JsonRpcNotification::new(
        "notifications/subscriptions/acknowledged",
        serde_json::json!({
            "_meta": { KEY_SUBSCRIPTION_ID: key.to_value() },
            "notifications": honoured_filter(requested),
        }),
    )
}

/// The `notifications/cancelled` a server sends when it tears a stream down.
///
/// This is the *only* sanctioned use of a server-sent cancellation; the
/// specification forbids every other.
#[must_use]
pub fn teardown_notification(key: &RequestKey) -> JsonRpcNotification {
    JsonRpcNotification::new(
        "notifications/cancelled",
        serde_json::json!({
            "requestId": key.to_value(),
            "reason": "Server shutting down",
        }),
    )
}

/// The payload of the graceful-closure response to `subscriptions/listen`.
#[must_use]
pub fn graceful_closure_payload(key: &RequestKey) -> Value {
    serde_json::json!({ "_meta": { KEY_SUBSCRIPTION_ID: key.to_value() } })
}

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

    fn key(n: i64) -> RequestKey {
        RequestKey::Num(n)
    }

    #[test]
    fn acknowledgement_carries_the_subscription_id_and_an_empty_filter() {
        let ack = acknowledgement(
            &key(1),
            Some(&serde_json::json!({ "toolsListChanged": true })),
        );
        assert_eq!(ack.method, "notifications/subscriptions/acknowledged");
        let params = ack.params.unwrap();
        assert_eq!(params["_meta"][KEY_SUBSCRIPTION_ID], 1);
        assert_eq!(params["notifications"], serde_json::json!({}));
    }

    #[test]
    fn client_cancellation_is_flagged_as_such() {
        let registry = Registry::new();
        let subscription = registry.register(key(1));
        assert!(registry.cancel_by_client(&key(1)));
        assert!(subscription.token.is_cancelled());
        assert!(subscription.client_cancelled.load(Ordering::SeqCst));
        assert!(registry.is_empty());
    }

    #[test]
    fn server_teardown_is_not_flagged_as_client_cancellation() {
        let registry = Registry::new();
        let subscription = registry.register(key(1));
        registry.cancel_all();
        assert!(subscription.token.is_cancelled());
        assert!(!subscription.client_cancelled.load(Ordering::SeqCst));
    }

    #[test]
    fn cancelling_an_unknown_subscription_is_ignored() {
        let registry = Registry::new();
        assert!(!registry.cancel_by_client(&key(7)));
    }

    #[test]
    fn teardown_messages_reference_the_subscription() {
        let notification = teardown_notification(&key(3));
        assert_eq!(notification.method, "notifications/cancelled");
        assert_eq!(notification.params.unwrap()["requestId"], 3);
        let payload = graceful_closure_payload(&key(3));
        assert_eq!(payload["_meta"][KEY_SUBSCRIPTION_ID], 3);
    }
}