atpmcp 0.15.0

AT Protocol MCP server (Model Context Protocol 2026-07-28)
//! Per-request `_meta` parsing and validation.
//!
//! The 2026-07-28 revision removed the `initialize` handshake and made MCP
//! stateless: a server may not infer the protocol version, the client's
//! identity, or its capabilities from anything it saw earlier on the same
//! connection. Every request restates them in `_meta`.
//!
//! Two fields are required on every request — `protocolVersion` and
//! `clientCapabilities` — and a request missing either is malformed and
//! **MUST** be rejected with `-32602`. A version this server does not
//! implement is `-32022`, carrying the list of versions it does.

use serde_json::Value;

use crate::errors::ProtocolError;
use crate::proto::PROTOCOL_VERSION;

/// The `_meta` key carrying the protocol version of a request.
pub const KEY_PROTOCOL_VERSION: &str = "io.modelcontextprotocol/protocolVersion";

/// The `_meta` key carrying the client's name and version.
pub const KEY_CLIENT_INFO: &str = "io.modelcontextprotocol/clientInfo";

/// The `_meta` key carrying the client's capabilities for a request.
pub const KEY_CLIENT_CAPABILITIES: &str = "io.modelcontextprotocol/clientCapabilities";

/// The `_meta` key carrying the server's name and version on a result.
pub const KEY_SERVER_INFO: &str = "io.modelcontextprotocol/serverInfo";

/// The `_meta` key correlating a notification with its subscription.
pub const KEY_SUBSCRIPTION_ID: &str = "io.modelcontextprotocol/subscriptionId";

/// The `_meta` key opting a request into progress notifications.
pub const KEY_PROGRESS_TOKEN: &str = "progressToken";

/// The protocol metadata carried by one request.
#[derive(Debug, Clone)]
pub struct Meta {
    /// The protocol version the client is speaking. Always equal to
    /// [`PROTOCOL_VERSION`]; a mismatch is rejected before this is built.
    pub protocol_version: String,
    /// What the client declared it can do. May be an empty object.
    ///
    /// Required on every request and validated here, but not yet read by any
    /// handler: this server uses no client capability. It is the gate any
    /// future use must pass, because a server **MUST NOT** rely on a
    /// capability the client did not declare.
    // Its own unit test uses it, so the expectation holds outside tests only.
    #[cfg_attr(
        not(test),
        expect(
            dead_code,
            reason = "the gate for any future capability use; fires when a handler reads it"
        )
    )]
    pub client_capabilities: Value,
    /// The client's self-reported identity, when it sent one.
    ///
    /// Self-reported and unverified: for display and logging, never for a
    /// behavioural or security decision.
    pub client_info: Option<Value>,
    /// The progress token, when the client opted into progress notifications.
    pub progress_token: Option<Value>,
}

impl Meta {
    /// Whether the client declared support for a named capability.
    ///
    /// A server **MUST NOT** rely on a capability the client did not declare,
    /// so anything optional is gated on this rather than attempted and
    /// recovered from.
    #[must_use]
    // Its own unit test uses it, so the expectation holds outside tests only.
    #[cfg_attr(
        not(test),
        expect(
            dead_code,
            reason = "no handler gates on a client capability yet; fires once one does"
        )
    )]
    pub fn client_supports(&self, capability: &str) -> bool {
        self.client_capabilities.get(capability).is_some()
    }
}

/// Parse and validate the `_meta` of an incoming request.
///
/// # Errors
///
/// Returns [`ProtocolError::MissingMeta`] when a required field is absent, and
/// [`ProtocolError::UnsupportedVersion`] when the client asks for a version
/// this server does not implement.
pub fn parse(params: Option<&Value>) -> Result<Meta, ProtocolError> {
    let meta = params.and_then(|params| params.get("_meta"));

    let protocol_version = meta
        .and_then(|meta| meta.get(KEY_PROTOCOL_VERSION))
        .and_then(Value::as_str)
        .ok_or_else(|| ProtocolError::MissingMeta {
            field: KEY_PROTOCOL_VERSION.to_string(),
        })?;

    if protocol_version != PROTOCOL_VERSION {
        return Err(ProtocolError::UnsupportedVersion {
            requested: protocol_version.to_string(),
        });
    }

    // Required, but an empty object is a legitimate value: a client that can
    // do nothing extra still has to say so.
    let client_capabilities = meta
        .and_then(|meta| meta.get(KEY_CLIENT_CAPABILITIES))
        .cloned()
        .ok_or_else(|| ProtocolError::MissingMeta {
            field: KEY_CLIENT_CAPABILITIES.to_string(),
        })?;

    Ok(Meta {
        protocol_version: protocol_version.to_string(),
        client_capabilities,
        client_info: meta.and_then(|meta| meta.get(KEY_CLIENT_INFO)).cloned(),
        progress_token: meta.and_then(|meta| meta.get(KEY_PROGRESS_TOKEN)).cloned(),
    })
}

/// The `data` member for an [`ProtocolError::UnsupportedVersion`] error.
#[must_use]
pub fn unsupported_version_data(requested: &str) -> Value {
    serde_json::json!({
        "supported": [PROTOCOL_VERSION],
        "requested": requested,
    })
}

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

    fn params_with_meta(meta: Value) -> Value {
        serde_json::json!({ "_meta": meta })
    }

    fn valid_meta() -> Value {
        serde_json::json!({
            KEY_PROTOCOL_VERSION: PROTOCOL_VERSION,
            KEY_CLIENT_CAPABILITIES: {},
        })
    }

    #[test]
    fn accepts_the_minimum_valid_meta() {
        let params = params_with_meta(valid_meta());
        let meta = parse(Some(&params)).expect("minimal meta is valid");
        assert_eq!(meta.protocol_version, PROTOCOL_VERSION);
        assert!(meta.client_info.is_none());
        assert!(meta.progress_token.is_none());
    }

    #[test]
    fn carries_optional_fields_through() {
        let params = params_with_meta(serde_json::json!({
            KEY_PROTOCOL_VERSION: PROTOCOL_VERSION,
            KEY_CLIENT_CAPABILITIES: { "elicitation": {} },
            KEY_CLIENT_INFO: { "name": "example", "version": "1.0.0" },
            KEY_PROGRESS_TOKEN: "abc123",
        }));
        let meta = parse(Some(&params)).expect("meta is valid");
        assert_eq!(meta.client_info.as_ref().unwrap()["name"], "example");
        assert_eq!(meta.progress_token.as_ref().unwrap(), "abc123");
        assert!(meta.client_supports("elicitation"));
        assert!(!meta.client_supports("sampling"));
    }

    #[test]
    fn rejects_absent_meta_entirely() {
        let error = parse(None).expect_err("absent _meta is malformed");
        assert!(matches!(error, ProtocolError::MissingMeta { .. }));
        assert_eq!(error.code(), crate::proto::INVALID_PARAMS);
    }

    #[test]
    fn rejects_missing_protocol_version() {
        let params = params_with_meta(serde_json::json!({ KEY_CLIENT_CAPABILITIES: {} }));
        let error = parse(Some(&params)).expect_err("protocolVersion is required");
        match error {
            ProtocolError::MissingMeta { ref field } => assert_eq!(field, KEY_PROTOCOL_VERSION),
            other => panic!("unexpected error: {other}"),
        }
    }

    #[test]
    fn rejects_missing_client_capabilities() {
        let params =
            params_with_meta(serde_json::json!({ KEY_PROTOCOL_VERSION: PROTOCOL_VERSION }));
        let error = parse(Some(&params)).expect_err("clientCapabilities is required");
        match error {
            ProtocolError::MissingMeta { ref field } => assert_eq!(field, KEY_CLIENT_CAPABILITIES),
            other => panic!("unexpected error: {other}"),
        }
    }

    #[test]
    fn rejects_a_version_this_server_does_not_implement() {
        let params = params_with_meta(serde_json::json!({
            KEY_PROTOCOL_VERSION: "2025-11-25",
            KEY_CLIENT_CAPABILITIES: {},
        }));
        let error = parse(Some(&params)).expect_err("legacy version is unsupported");
        assert_eq!(error.code(), crate::proto::UNSUPPORTED_PROTOCOL_VERSION);
        match error {
            ProtocolError::UnsupportedVersion { ref requested } => {
                assert_eq!(requested, "2025-11-25");
                let data = unsupported_version_data(requested);
                assert_eq!(data["supported"][0], PROTOCOL_VERSION);
                assert_eq!(data["requested"], "2025-11-25");
            }
            other => panic!("unexpected error: {other}"),
        }
    }

    #[test]
    fn unknown_meta_keys_are_ignored() {
        let params = params_with_meta(serde_json::json!({
            KEY_PROTOCOL_VERSION: PROTOCOL_VERSION,
            KEY_CLIENT_CAPABILITIES: {},
            "traceparent": "00-0af7651916cd43dd8448eb211c80319c-00f067aa0ba902b7-01",
            "com.example/whatever": 1,
        }));
        assert!(parse(Some(&params)).is_ok());
    }
}