Skip to main content

a2a_protocol_server/dispatch/
version.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Tom F. <[email protected]> (https://github.com/tomtom215)
3
4//! Protocol version negotiation (spec §3.6): which `A2A-Version` a request
5//! asks for, and whether this server serves it. Every built-in binding checks
6//! through [`validate_version_header`]; a binding outside this crate checks
7//! through [`validate_version_metadata`].
8
9/// The service parameter naming the A2A protocol version, spelled the way a
10/// non-HTTP binding carries it.
11///
12/// A2A §3.6.2 defines the parameter and §10.2 says each binding transmits it in
13/// whatever its own metadata mechanism is: an `A2A-Version` HTTP header for
14/// JSON-RPC and REST, a gRPC metadata entry, SLIMRPC session metadata. HTTP
15/// header names are case-insensitive and gRPC requires lowercase, so this is
16/// the lowercase spelling and [`validate_version_metadata`] matches keys
17/// without regard to case.
18pub const A2A_VERSION_METADATA_KEY: &str = "a2a-version";
19
20/// Validates the A2A version carried in a binding's request metadata.
21///
22/// The counterpart of this crate's private header validator, for bindings that
23/// carry service parameters in a string map rather than in HTTP headers, and
24/// the supported way for a binding **outside this crate** to enforce §3.6.2 —
25/// which the built-in bindings do through private helpers this makes public.
26/// Without it an out-of-tree binding can send a version but cannot check one,
27/// and would have to reimplement the comparison and hope it stays in step.
28///
29/// Key lookup is case-insensitive. Only this server's `Major.Minor`
30/// ([`A2A_VERSION`](a2a_protocol_types::A2A_VERSION), `1.0`) is accepted, as
31/// §3.6.2 requires; a patch segment is ignored, per §3.6. The map is generic over its hasher so a binding that
32/// keeps metadata in something other than the default `RandomState` — most
33/// transport crates do — can pass it without rebuilding the map.
34///
35/// `require` decides what an absent or empty value means, and the two answers
36/// are both defensible, which is why it is the caller's to make. §3.6.2 says a
37/// missing value MUST be read as protocol 0.3 — a version this server does not
38/// implement — so `true` rejects it, matching the reference Python SDK and this
39/// crate's own HTTP default. `false` accepts it, which is what the gRPC binding
40/// does for clients predating the parameter.
41///
42/// # Errors
43///
44/// [`A2aError::version_not_supported`] when the version is one this server does
45/// not implement, or is absent while `require` is set.
46///
47/// # Example
48///
49/// ```rust
50/// use a2a_protocol_server::dispatch::validate_version_metadata;
51/// use std::collections::HashMap;
52///
53/// let mut metadata = HashMap::new();
54/// metadata.insert("A2A-Version".to_string(), "1.0".to_string());
55/// assert!(validate_version_metadata(&metadata, true).is_ok());
56///
57/// // Absent, and the caller requires it: rejected as 0.3 per §3.6.2.
58/// assert!(validate_version_metadata(&HashMap::new(), true).is_err());
59/// ```
60///
61/// [`A2aError::version_not_supported`]: a2a_protocol_types::error::A2aError::version_not_supported
62pub fn validate_version_metadata<S: std::hash::BuildHasher>(
63    metadata: &std::collections::HashMap<String, String, S>,
64    require: bool,
65) -> Result<(), a2a_protocol_types::error::A2aError> {
66    let value = metadata
67        .iter()
68        .find(|(k, _)| k.eq_ignore_ascii_case(A2A_VERSION_METADATA_KEY))
69        .map(|(_, v)| v.as_str());
70    validate_version_header(value, require)
71}
72
73/// The `A2A-Version` a request asks for: its header, or else the
74/// `A2A-Version` request parameter.
75///
76/// Spec §3.6.1: "Clients MAY provide the `A2A-Version` as a request parameter
77/// instead of a header", with `GET /tasks/task-123?A2A-Version=1.0` as the
78/// example. Until 2026-10-10 only the header was read, so a client doing
79/// exactly what the example shows was taken to be speaking 0.3 and refused.
80/// A non-empty header wins over the parameter; an empty or absent one falls
81/// back to it.
82pub fn requested_version(headers: &hyper::HeaderMap, uri: &hyper::Uri) -> Option<String> {
83    let header = headers
84        .get(a2a_protocol_types::A2A_VERSION_HEADER)
85        .and_then(|v| v.to_str().ok())
86        .filter(|v| !v.trim().is_empty());
87    if let Some(v) = header {
88        return Some(v.to_owned());
89    }
90    uri.query().and_then(|q| {
91        super::rest::query::parse_query_param(q, a2a_protocol_types::A2A_VERSION_HEADER)
92    })
93}
94
95/// Validates an `A2A-Version` header value per spec §3.6.2.
96///
97/// `value` is the raw header value (`None` when the header is absent).
98/// Absent or empty MUST be interpreted as protocol 0.3; when `require` is
99/// set (the strict default) that yields the same `VersionNotSupported`
100/// rejection the reference Python SDK produces. Otherwise the value must
101/// name this server's `Major.Minor` ([`is_served_version`]): §3.6.2 says a
102/// request is processed with the semantics of the version it asks for, and
103/// this server has only 1.0's. Until 0.15 any `1.x` was accepted and served
104/// as 1.0, as the Python SDK still does.
105pub fn validate_version_header(
106    value: Option<&str>,
107    require: bool,
108) -> Result<(), a2a_protocol_types::error::A2aError> {
109    let v = value.unwrap_or("").trim();
110    if v.is_empty() {
111        if require {
112            return Err(a2a_protocol_types::error::A2aError::version_not_supported(
113                "A2A version '0.3' is not supported by this server; expected '1.0' (send the A2A-Version header)",
114            ));
115        }
116        return Ok(());
117    }
118    if is_served_version(v) {
119        return Ok(());
120    }
121    Err(a2a_protocol_types::error::A2aError::version_not_supported(
122        format!(
123            "unsupported A2A version: {v}; this server supports {}",
124            a2a_protocol_types::A2A_VERSION
125        ),
126    ))
127}
128
129/// Whether `version` names the protocol version this server implements: the
130/// `Major.Minor` of [`A2A_VERSION`](a2a_protocol_types::A2A_VERSION), with
131/// anything after the minor ignored (§3.6: patch numbers "MUST not be
132/// considered"). Both components must be decimal digits only, so `"1"`,
133/// `"v1.0"`, `"+1.0"` and `"1.0-rc"` name no `Major.Minor` and are refused.
134fn is_served_version(version: &str) -> bool {
135    fn major_minor(version: &str) -> Option<(u32, u32)> {
136        let mut parts = version.split('.');
137        let mut number = || {
138            parts
139                .next()
140                .filter(|p| p.bytes().all(|b| b.is_ascii_digit()))?
141                .parse()
142                .ok()
143        };
144        Some((number()?, number()?))
145    }
146    major_minor(version).is_some_and(|v| Some(v) == major_minor(a2a_protocol_types::A2A_VERSION))
147}
148
149#[cfg(test)]
150mod tests {
151    use super::*;
152
153    #[test]
154    fn version_metadata_matches_key_case_insensitively() {
155        // Bindings spell this differently — HTTP headers arrive in whatever
156        // case the peer sent, gRPC lowercases, SLIMRPC passes through what the
157        // caller set. All four spellings are the same parameter.
158        for key in ["a2a-version", "A2A-Version", "A2A-VERSION", "a2a-Version"] {
159            let mut md = std::collections::HashMap::new();
160            md.insert(key.to_string(), "1.0".to_string());
161            assert!(
162                validate_version_metadata(&md, true).is_ok(),
163                "key spelling {key} should be recognised"
164            );
165        }
166    }
167
168    #[test]
169    fn version_metadata_rejects_unsupported_version() {
170        let mut md = std::collections::HashMap::new();
171        md.insert("a2a-version".to_string(), "0.3".to_string());
172        let err = validate_version_metadata(&md, true).expect_err("0.3 is not supported");
173        assert!(
174            err.message.contains("0.3"),
175            "the error should name the version it rejected, got: {}",
176            err.message
177        );
178    }
179
180    #[test]
181    fn version_metadata_accepts_this_major_minor_with_any_patch() {
182        for v in ["1.0", "1.0.2", "1.00", " 1.0 "] {
183            let mut md = std::collections::HashMap::new();
184            md.insert("a2a-version".to_string(), v.to_string());
185            assert!(
186                validate_version_metadata(&md, true).is_ok(),
187                "{v} names 1.0 and should be accepted"
188            );
189        }
190    }
191
192    /// §3.6.2: a request is processed with the semantics of the requested
193    /// `Major.Minor`, and this server has only 1.0's, so another minor is
194    /// refused with an error naming what it does support. Not-a-version
195    /// spellings are refused too.
196    #[test]
197    fn version_metadata_refuses_another_minor_or_no_minor() {
198        for v in [
199            "1.1", "1.4", "1", "1.", "v1.0", "+1.0", "1.0-rc", "1.+0", "0.0", "2.0",
200        ] {
201            let mut md = std::collections::HashMap::new();
202            md.insert("a2a-version".to_string(), v.to_string());
203            let err = validate_version_metadata(&md, true)
204                .expect_err(&format!("{v:?} is not 1.0 and must be refused"));
205            assert_eq!(
206                err.code,
207                a2a_protocol_types::error::ErrorCode::VersionNotSupported
208            );
209            assert!(err.message.contains("supports 1.0"), "{}", err.message);
210        }
211    }
212
213    #[test]
214    fn version_metadata_absent_follows_the_require_flag() {
215        let empty = std::collections::HashMap::new();
216        assert!(
217            validate_version_metadata(&empty, false).is_ok(),
218            "require=false is the gRPC posture: absent means a legacy client, accept it"
219        );
220        assert!(
221            validate_version_metadata(&empty, true).is_err(),
222            "require=true is the HTTP posture: absent means 0.3 per 3.6.2, reject it"
223        );
224    }
225
226    #[test]
227    fn version_metadata_treats_empty_value_as_absent() {
228        // A binding that sets the key but leaves it blank has told us nothing,
229        // and 3.6.2 reads "no value" as 0.3 regardless of how it got that way.
230        let mut md = std::collections::HashMap::new();
231        md.insert("a2a-version".to_string(), "   ".to_string());
232        assert!(validate_version_metadata(&md, true).is_err());
233        assert!(validate_version_metadata(&md, false).is_ok());
234    }
235
236    #[test]
237    fn version_metadata_ignores_unrelated_keys() {
238        let mut md = std::collections::HashMap::new();
239        md.insert("authorization".to_string(), "Bearer x".to_string());
240        md.insert("x-tenant-id".to_string(), "acme".to_string());
241        assert!(
242            validate_version_metadata(&md, false).is_ok(),
243            "no version key present, and require=false accepts that"
244        );
245    }
246}